scheduler_kist.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. /* Copyright (c) 2017-2019, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #define SCHEDULER_KIST_PRIVATE
  4. #include "core/or/or.h"
  5. #include "lib/buf/buffers.h"
  6. #include "app/config/config.h"
  7. #include "core/mainloop/connection.h"
  8. #include "feature/nodelist/networkstatus.h"
  9. #define TOR_CHANNEL_INTERNAL_
  10. #include "core/or/channel.h"
  11. #include "core/or/channeltls.h"
  12. #define SCHEDULER_PRIVATE_
  13. #include "core/or/scheduler.h"
  14. #include "lib/math/fp.h"
  15. #include "core/or/or_connection_st.h"
  16. #include "core/or/connection_or.h"
  17. #ifdef HAVE_SYS_IOCTL_H
  18. #include <sys/ioctl.h>
  19. #endif
  20. #ifdef HAVE_KIST_SUPPORT
  21. /* Kernel interface needed for KIST. */
  22. #include <netinet/tcp.h>
  23. #include <linux/sockios.h>
  24. #endif /* HAVE_KIST_SUPPORT */
  25. /*****************************************************************************
  26. * Data structures and supporting functions
  27. *****************************************************************************/
  28. /* Socket_table hash table stuff. The socket_table keeps track of per-socket
  29. * limit information imposed by kist and used by kist. */
  30. static uint32_t
  31. socket_table_ent_hash(const socket_table_ent_t *ent)
  32. {
  33. return (uint32_t)ent->chan->global_identifier;
  34. }
  35. static unsigned
  36. socket_table_ent_eq(const socket_table_ent_t *a, const socket_table_ent_t *b)
  37. {
  38. return a->chan == b->chan;
  39. }
  40. typedef HT_HEAD(socket_table_s, socket_table_ent_s) socket_table_t;
  41. static socket_table_t socket_table = HT_INITIALIZER();
  42. HT_PROTOTYPE(socket_table_s, socket_table_ent_s, node, socket_table_ent_hash,
  43. socket_table_ent_eq)
  44. HT_GENERATE2(socket_table_s, socket_table_ent_s, node, socket_table_ent_hash,
  45. socket_table_ent_eq, 0.6, tor_reallocarray, tor_free_)
  46. /* outbuf_table hash table stuff. The outbuf_table keeps track of which
  47. * channels have data sitting in their outbuf so the kist scheduler can force
  48. * a write from outbuf to kernel periodically during a run and at the end of a
  49. * run. */
  50. typedef struct outbuf_table_ent_s {
  51. HT_ENTRY(outbuf_table_ent_s) node;
  52. channel_t *chan;
  53. } outbuf_table_ent_t;
  54. static uint32_t
  55. outbuf_table_ent_hash(const outbuf_table_ent_t *ent)
  56. {
  57. return (uint32_t)ent->chan->global_identifier;
  58. }
  59. static unsigned
  60. outbuf_table_ent_eq(const outbuf_table_ent_t *a, const outbuf_table_ent_t *b)
  61. {
  62. return a->chan->global_identifier == b->chan->global_identifier;
  63. }
  64. HT_PROTOTYPE(outbuf_table_s, outbuf_table_ent_s, node, outbuf_table_ent_hash,
  65. outbuf_table_ent_eq)
  66. HT_GENERATE2(outbuf_table_s, outbuf_table_ent_s, node, outbuf_table_ent_hash,
  67. outbuf_table_ent_eq, 0.6, tor_reallocarray, tor_free_)
  68. /*****************************************************************************
  69. * Other internal data
  70. *****************************************************************************/
  71. /* Store the last time the scheduler was run so we can decide when to next run
  72. * the scheduler based on it. */
  73. static monotime_t scheduler_last_run;
  74. /* This is a factor for the extra_space calculation in kist per-socket limits.
  75. * It is the number of extra congestion windows we want to write to the kernel.
  76. */
  77. static double sock_buf_size_factor = 1.0;
  78. /* How often the scheduler runs. */
  79. STATIC int sched_run_interval = KIST_SCHED_RUN_INTERVAL_DEFAULT;
  80. #ifdef HAVE_KIST_SUPPORT
  81. /* Indicate if KIST lite mode is on or off. We can disable it at runtime.
  82. * Important to have because of the KISTLite -> KIST possible transition. */
  83. static unsigned int kist_lite_mode = 0;
  84. /* Indicate if we don't have the kernel support. This can happen if the kernel
  85. * changed and it doesn't recognized the values passed to the syscalls needed
  86. * by KIST. In that case, fallback to the naive approach. */
  87. static unsigned int kist_no_kernel_support = 0;
  88. #else /* !defined(HAVE_KIST_SUPPORT) */
  89. static unsigned int kist_lite_mode = 1;
  90. #endif /* defined(HAVE_KIST_SUPPORT) */
  91. /*****************************************************************************
  92. * Internally called function implementations
  93. *****************************************************************************/
  94. /* Little helper function to get the length of a channel's output buffer */
  95. static inline size_t
  96. channel_outbuf_length(channel_t *chan)
  97. {
  98. tor_assert(chan);
  99. /* In theory, this can not happen because we can not scheduler a channel
  100. * without a connection that has its outbuf initialized. Just in case, bug
  101. * on this so we can understand a bit more why it happened. */
  102. if (SCHED_BUG(BASE_CHAN_TO_TLS(chan)->conn == NULL, chan)) {
  103. return 0;
  104. }
  105. //return buf_datalen(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn)->outbuf);
  106. //return connection_get_outbuf_len(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn));
  107. size_t len = 0;
  108. // TODO: fix this ugly locking
  109. connection_t *conn = TO_CONN(BASE_CHAN_TO_TLS(chan)->conn);
  110. tor_assert(conn->safe_conn != NULL);
  111. tor_mutex_acquire(&(conn->safe_conn->lock));
  112. len = buf_datalen(conn->safe_conn->outbuf);
  113. tor_mutex_release(&(conn->safe_conn->lock));
  114. return len;
  115. }
  116. /* Little helper function for HT_FOREACH_FN. */
  117. static int
  118. each_channel_wakeup_listeners(outbuf_table_ent_t *ent, void *data)
  119. {
  120. (void) data;
  121. connection_t *conn = TO_CONN(BASE_CHAN_TO_TLS(ent->chan)->conn);
  122. event_source_deliver_silently(conn->event_source,
  123. or_conn_outgoing_packed_cell, false);
  124. event_source_wakeup_listener(conn->event_source,
  125. or_conn_outgoing_packed_cell);
  126. return 0; /* Returning non-zero removes the element from the table. */
  127. }
  128. /* Little helper function for HT_FOREACH_FN. */
  129. static int
  130. each_channel_write_to_kernel(outbuf_table_ent_t *ent, void *data)
  131. {
  132. (void) data; /* Make compiler happy. */
  133. channel_write_to_kernel(ent->chan);
  134. return 0; /* Returning non-zero removes the element from the table. */
  135. }
  136. /* Free the given outbuf table entry ent. */
  137. static int
  138. free_outbuf_info_by_ent(outbuf_table_ent_t *ent, void *data)
  139. {
  140. (void) data; /* Make compiler happy. */
  141. log_debug(LD_SCHED, "Freeing outbuf table entry from chan=%" PRIu64,
  142. ent->chan->global_identifier);
  143. tor_free(ent);
  144. return 1; /* So HT_FOREACH_FN will remove the element */
  145. }
  146. /* Free the given socket table entry ent. */
  147. static int
  148. free_socket_info_by_ent(socket_table_ent_t *ent, void *data)
  149. {
  150. (void) data; /* Make compiler happy. */
  151. log_debug(LD_SCHED, "Freeing socket table entry from chan=%" PRIu64,
  152. ent->chan->global_identifier);
  153. tor_free(ent);
  154. return 1; /* So HT_FOREACH_FN will remove the element */
  155. }
  156. /* Clean up socket_table. Probably because the KIST sched impl is going away */
  157. static void
  158. free_all_socket_info(void)
  159. {
  160. HT_FOREACH_FN(socket_table_s, &socket_table, free_socket_info_by_ent, NULL);
  161. HT_CLEAR(socket_table_s, &socket_table);
  162. }
  163. static socket_table_ent_t *
  164. socket_table_search(socket_table_t *table, const channel_t *chan)
  165. {
  166. socket_table_ent_t search, *ent = NULL;
  167. search.chan = chan;
  168. ent = HT_FIND(socket_table_s, table, &search);
  169. return ent;
  170. }
  171. /* Free a socket entry in table for the given chan. */
  172. static void
  173. free_socket_info_by_chan(socket_table_t *table, const channel_t *chan)
  174. {
  175. socket_table_ent_t *ent = NULL;
  176. ent = socket_table_search(table, chan);
  177. if (!ent)
  178. return;
  179. log_debug(LD_SCHED, "scheduler free socket info for chan=%" PRIu64,
  180. chan->global_identifier);
  181. HT_REMOVE(socket_table_s, table, ent);
  182. free_socket_info_by_ent(ent, NULL);
  183. }
  184. /* Perform system calls for the given socket in order to calculate kist's
  185. * per-socket limit as documented in the function body. */
  186. MOCK_IMPL(void,
  187. update_socket_info_impl, (socket_table_ent_t *ent))
  188. {
  189. #ifdef HAVE_KIST_SUPPORT
  190. int64_t tcp_space, extra_space;
  191. tor_assert(ent);
  192. tor_assert(ent->chan);
  193. //const tor_socket_t sock =
  194. // TO_CONN(BASE_CHAN_TO_TLS((channel_t *) ent->chan)->conn)->s;
  195. // TODO: fix this ugly locking
  196. connection_t *conn = TO_CONN(BASE_CHAN_TO_TLS((channel_t *) ent->chan)->conn);
  197. tor_assert(conn->safe_conn != NULL);
  198. tor_mutex_acquire(&(conn->safe_conn->lock));
  199. const tor_socket_t sock = conn->safe_conn->socket;
  200. tor_mutex_release(&(conn->safe_conn->lock));
  201. if (!SOCKET_OK(sock)) {
  202. // the socket is closed, so we should not write anything
  203. log_warn(LD_SCHED, "The socket for %p has been closed.", conn);
  204. // TODO: this should be debug not warn
  205. ent->limit = ent->cwnd = ent->unacked = ent->mss = ent->notsent = 0;
  206. return;
  207. }
  208. struct tcp_info tcp;
  209. socklen_t tcp_info_len = sizeof(tcp);
  210. if (kist_no_kernel_support || kist_lite_mode) {
  211. goto fallback;
  212. }
  213. /* Gather information */
  214. if (getsockopt(sock, SOL_TCP, TCP_INFO, (void *)&(tcp), &tcp_info_len) < 0) {
  215. if (errno == EBADF) {
  216. // there is a race condition where the safe_conn could close the fd after
  217. // we get it, in which case we should set a limit of 0
  218. log_warn(LD_SCHED, "The socket for %p is not a valid file descriptor.",
  219. conn);
  220. // TODO: this should be debug not warn
  221. ent->limit = ent->cwnd = ent->unacked = ent->mss = ent->notsent = 0;
  222. return;
  223. }
  224. if (errno == EINVAL) {
  225. /* Oops, this option is not provided by the kernel, we'll have to
  226. * disable KIST entirely. This can happen if tor was built on a machine
  227. * with the support previously or if the kernel was updated and lost the
  228. * support. */
  229. log_notice(LD_SCHED, "Looks like our kernel doesn't have the support "
  230. "for KIST anymore. We will fallback to the naive "
  231. "approach. Remove KIST from the Schedulers list "
  232. "to disable.");
  233. kist_no_kernel_support = 1;
  234. }
  235. goto fallback;
  236. }
  237. if (ioctl(sock, SIOCOUTQNSD, &(ent->notsent)) < 0) {
  238. if (errno == EBADF) {
  239. // there is a race condition where the safe_conn could close the fd after
  240. // we get it, in which case we should set a limit of 0
  241. log_warn(LD_SCHED, "The socket for %p is not a valid file descriptor.",
  242. conn);
  243. // TODO: this should be debug not warn
  244. ent->limit = ent->cwnd = ent->unacked = ent->mss = ent->notsent = 0;
  245. return;
  246. }
  247. if (errno == EINVAL) {
  248. log_notice(LD_SCHED, "Looks like our kernel doesn't have the support "
  249. "for KIST anymore. We will fallback to the naive "
  250. "approach. Remove KIST from the Schedulers list "
  251. "to disable.");
  252. /* Same reason as the above. */
  253. kist_no_kernel_support = 1;
  254. }
  255. goto fallback;
  256. }
  257. ent->cwnd = tcp.tcpi_snd_cwnd;
  258. ent->unacked = tcp.tcpi_unacked;
  259. ent->mss = tcp.tcpi_snd_mss;
  260. /* In order to reduce outbound kernel queuing delays and thus improve Tor's
  261. * ability to prioritize circuits, KIST wants to set a socket write limit
  262. * that is near the amount that the socket would be able to immediately send
  263. * into the Internet.
  264. *
  265. * We first calculate how much the socket could send immediately (assuming
  266. * completely full packets) according to the congestion window and the number
  267. * of unacked packets.
  268. *
  269. * Then we add a little extra space in a controlled way. We do this so any
  270. * when the kernel gets ACKs back for data currently sitting in the "TCP
  271. * space", it will already have some more data to send immediately. It will
  272. * not have to wait for the scheduler to run again. The amount of extra space
  273. * is a factor of the current congestion window. With the suggested
  274. * sock_buf_size_factor value of 1.0, we allow at most 2*cwnd bytes to sit in
  275. * the kernel: 1 cwnd on the wire waiting for ACKs and 1 cwnd ready and
  276. * waiting to be sent when those ACKs finally come.
  277. *
  278. * In the below diagram, we see some bytes in the TCP-space (denoted by '*')
  279. * that have be sent onto the wire and are waiting for ACKs. We have a little
  280. * more room in "TCP space" that we can fill with data that will be
  281. * immediately sent. We also see the "extra space" KIST calculates. The sum
  282. * of the empty "TCP space" and the "extra space" is the kist-imposed write
  283. * limit for this socket.
  284. *
  285. * <----------------kernel-outbound-socket-queue----------------|
  286. * <*********---------------------------------------------------|
  287. * |----TCP-space-----|----extra-space-----|
  288. * |------------------|
  289. * ^ ((cwnd - unacked) * mss) bytes
  290. * |--------------------|
  291. * ^ ((cwnd * mss) * factor) bytes
  292. */
  293. /* These values from the kernel are uint32_t, they will always fit into a
  294. * int64_t tcp_space variable but if the congestion window cwnd is smaller
  295. * than the unacked packets, the remaining TCP space is set to 0. */
  296. if (ent->cwnd >= ent->unacked) {
  297. tcp_space = (ent->cwnd - ent->unacked) * (int64_t)(ent->mss);
  298. } else {
  299. tcp_space = 0;
  300. }
  301. /* The clamp_double_to_int64 makes sure the first part fits into an int64_t.
  302. * In fact, if sock_buf_size_factor is still forced to be >= 0 in config.c,
  303. * then it will be positive for sure. Then we subtract a uint32_t. Getting a
  304. * negative value is OK, see after how it is being handled. */
  305. extra_space =
  306. clamp_double_to_int64(
  307. (ent->cwnd * (int64_t)ent->mss) * sock_buf_size_factor) -
  308. ent->notsent - (int64_t)channel_outbuf_length((channel_t *) ent->chan);
  309. if ((tcp_space + extra_space) < 0) {
  310. /* This means that the "notsent" queue is just too big so we shouldn't put
  311. * more in the kernel for now. */
  312. ent->limit = 0;
  313. } else {
  314. /* The positive sum of two int64_t will always fit into an uint64_t.
  315. * And we know this will always be positive, since we checked above. */
  316. ent->limit = (uint64_t)tcp_space + (uint64_t)extra_space;
  317. }
  318. return;
  319. #else /* !defined(HAVE_KIST_SUPPORT) */
  320. goto fallback;
  321. #endif /* defined(HAVE_KIST_SUPPORT) */
  322. fallback:
  323. /* If all of a sudden we don't have kist support, we just zero out all the
  324. * variables for this socket since we don't know what they should be. We
  325. * also allow the socket to write as much as it can from the estimated
  326. * number of cells the lower layer can accept, effectively returning it to
  327. * Vanilla scheduler behavior. */
  328. ent->cwnd = ent->unacked = ent->mss = ent->notsent = 0;
  329. /* This function calls the specialized channel object (currently channeltls)
  330. * and ask how many cells it can write on the outbuf which we then multiply
  331. * by the size of the cells for this channel. The cast is because this
  332. * function requires a non-const channel object, meh. */
  333. ent->limit = channel_num_cells_writeable((channel_t *) ent->chan) *
  334. (get_cell_network_size(ent->chan->wide_circ_ids) +
  335. TLS_PER_CELL_OVERHEAD);
  336. }
  337. /* Given a socket that isn't in the table, add it.
  338. * Given a socket that is in the table, re-init values that need init-ing
  339. * every scheduling run
  340. */
  341. static void
  342. init_socket_info(socket_table_t *table, const channel_t *chan)
  343. {
  344. socket_table_ent_t *ent = NULL;
  345. ent = socket_table_search(table, chan);
  346. if (!ent) {
  347. log_debug(LD_SCHED, "scheduler init socket info for chan=%" PRIu64,
  348. chan->global_identifier);
  349. ent = tor_malloc_zero(sizeof(*ent));
  350. ent->chan = chan;
  351. HT_INSERT(socket_table_s, table, ent);
  352. }
  353. ent->written = 0;
  354. }
  355. /* Add chan to the outbuf table if it isn't already in it. If it is, then don't
  356. * do anything */
  357. static bool
  358. outbuf_table_add(outbuf_table_t *table, channel_t *chan)
  359. {
  360. outbuf_table_ent_t search, *ent;
  361. search.chan = chan;
  362. ent = HT_FIND(outbuf_table_s, table, &search);
  363. if (!ent) {
  364. log_debug(LD_SCHED, "scheduler init outbuf info for chan=%" PRIu64,
  365. chan->global_identifier);
  366. ent = tor_malloc_zero(sizeof(*ent));
  367. ent->chan = chan;
  368. HT_INSERT(outbuf_table_s, table, ent);
  369. return true;
  370. }
  371. return false;
  372. }
  373. static void
  374. outbuf_table_remove(outbuf_table_t *table, channel_t *chan)
  375. {
  376. outbuf_table_ent_t search, *ent;
  377. search.chan = chan;
  378. ent = HT_FIND(outbuf_table_s, table, &search);
  379. if (ent) {
  380. HT_REMOVE(outbuf_table_s, table, ent);
  381. free_outbuf_info_by_ent(ent, NULL);
  382. }
  383. }
  384. /* Set the scheduler running interval. */
  385. static void
  386. set_scheduler_run_interval(void)
  387. {
  388. int old_sched_run_interval = sched_run_interval;
  389. sched_run_interval = kist_scheduler_run_interval();
  390. if (old_sched_run_interval != sched_run_interval) {
  391. log_info(LD_SCHED, "Scheduler KIST changing its running interval "
  392. "from %" PRId32 " to %" PRId32,
  393. old_sched_run_interval, sched_run_interval);
  394. }
  395. }
  396. /* Return true iff the channel hasn't hit its kist-imposed write limit yet */
  397. static int
  398. socket_can_write(socket_table_t *table, const channel_t *chan)
  399. {
  400. socket_table_ent_t *ent = NULL;
  401. ent = socket_table_search(table, chan);
  402. if (SCHED_BUG(!ent, chan)) {
  403. return 1; // Just return true, saying that kist wouldn't limit the socket
  404. }
  405. /* We previously calculated a write limit for this socket. In the below
  406. * calculation, first determine how much room is left in bytes. Then divide
  407. * that by the amount of space a cell takes. If there's room for at least 1
  408. * cell, then KIST will allow the socket to write. */
  409. int64_t kist_limit_space =
  410. (int64_t) (ent->limit - ent->written) /
  411. (CELL_MAX_NETWORK_SIZE + TLS_PER_CELL_OVERHEAD);
  412. return kist_limit_space > 0;
  413. }
  414. /* Update the channel's socket kernel information. */
  415. static void
  416. update_socket_info(socket_table_t *table, const channel_t *chan)
  417. {
  418. socket_table_ent_t *ent = NULL;
  419. ent = socket_table_search(table, chan);
  420. if (SCHED_BUG(!ent, chan)) {
  421. return; // Whelp. Entry didn't exist for some reason so nothing to do.
  422. }
  423. update_socket_info_impl(ent);
  424. log_debug(LD_SCHED, "chan=%" PRIu64 " updated socket info, limit: %" PRIu64
  425. ", cwnd: %" PRIu32 ", unacked: %" PRIu32
  426. ", notsent: %" PRIu32 ", mss: %" PRIu32,
  427. ent->chan->global_identifier, ent->limit, ent->cwnd, ent->unacked,
  428. ent->notsent, ent->mss);
  429. }
  430. /* Increment the channel's socket written value by the number of bytes. */
  431. static void
  432. update_socket_written(socket_table_t *table, channel_t *chan, size_t bytes)
  433. {
  434. socket_table_ent_t *ent = NULL;
  435. ent = socket_table_search(table, chan);
  436. if (SCHED_BUG(!ent, chan)) {
  437. return; // Whelp. Entry didn't exist so nothing to do.
  438. }
  439. log_debug(LD_SCHED, "chan=%" PRIu64 " wrote %lu bytes, old was %" PRIi64,
  440. chan->global_identifier, (unsigned long) bytes, ent->written);
  441. ent->written += bytes;
  442. }
  443. /*
  444. * A naive KIST impl would write every single cell all the way to the kernel.
  445. * That would take a lot of system calls. A less bad KIST impl would write a
  446. * channel's outbuf to the kernel only when we are switching to a different
  447. * channel. But if we have two channels with equal priority, we end up writing
  448. * one cell for each and bouncing back and forth. This KIST impl avoids that
  449. * by only writing a channel's outbuf to the kernel if it has 8 cells or more
  450. * in it.
  451. */
  452. //MOCK_IMPL(int, channel_should_write_to_kernel,
  453. // (outbuf_table_t *table, channel_t *chan))
  454. //{
  455. // outbuf_table_add(table, chan);
  456. // /* CELL_MAX_NETWORK_SIZE * 8 because we only want to write the outbuf to the
  457. // * kernel if there's 8 or more cells waiting */
  458. // return channel_outbuf_length(chan) > (CELL_MAX_NETWORK_SIZE * 8);
  459. //}
  460. /* Little helper function to write a channel's outbuf all the way to the
  461. * kernel */
  462. MOCK_IMPL(void, channel_write_to_kernel, (channel_t *chan))
  463. {
  464. tor_assert(chan);
  465. log_debug(LD_SCHED, "Writing %lu bytes to kernel for chan %" PRIu64,
  466. (unsigned long)channel_outbuf_length(chan),
  467. chan->global_identifier);
  468. connection_handle_write(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn), 0);
  469. }
  470. /* Return true iff the scheduler has work to perform. */
  471. static int
  472. have_work(void)
  473. {
  474. smartlist_t *cp = get_channels_pending();
  475. IF_BUG_ONCE(!cp) {
  476. return 0; // channels_pending doesn't exist so... no work?
  477. }
  478. return smartlist_len(cp) > 0;
  479. }
  480. /* Function of the scheduler interface: free_all() */
  481. static void
  482. kist_free_all(void)
  483. {
  484. free_all_socket_info();
  485. }
  486. /* Function of the scheduler interface: on_channel_free() */
  487. static void
  488. kist_on_channel_free_fn(const channel_t *chan)
  489. {
  490. free_socket_info_by_chan(&socket_table, chan);
  491. }
  492. /* Function of the scheduler interface: on_new_consensus() */
  493. static void
  494. kist_scheduler_on_new_consensus(void)
  495. {
  496. set_scheduler_run_interval();
  497. }
  498. /* Function of the scheduler interface: on_new_options() */
  499. static void
  500. kist_scheduler_on_new_options(void)
  501. {
  502. sock_buf_size_factor = get_options()->KISTSockBufSizeFactor;
  503. /* Calls kist_scheduler_run_interval which calls get_options(). */
  504. set_scheduler_run_interval();
  505. }
  506. /* Function of the scheduler interface: init() */
  507. static void
  508. kist_scheduler_init(void)
  509. {
  510. /* When initializing the scheduler, the last run could be 0 because it is
  511. * declared static or a value in the past that was set when it was last
  512. * used. In both cases, we want to initialize it to now so we don't risk
  513. * using the value 0 which doesn't play well with our monotonic time
  514. * interface.
  515. *
  516. * One side effect is that the first scheduler run will be at the next tick
  517. * that is in now + 10 msec (KIST_SCHED_RUN_INTERVAL_DEFAULT) by default. */
  518. monotime_get(&scheduler_last_run);
  519. kist_scheduler_on_new_options();
  520. IF_BUG_ONCE(sched_run_interval == 0) {
  521. log_warn(LD_SCHED, "We are initing the KIST scheduler and noticed the "
  522. "KISTSchedRunInterval is telling us to not use KIST. That's "
  523. "weird! We'll continue using KIST, but at %" PRId32 "ms.",
  524. KIST_SCHED_RUN_INTERVAL_DEFAULT);
  525. sched_run_interval = KIST_SCHED_RUN_INTERVAL_DEFAULT;
  526. }
  527. }
  528. /* Function of the scheduler interface: schedule() */
  529. static void
  530. kist_scheduler_schedule(void)
  531. {
  532. struct monotime_t now;
  533. struct timeval next_run;
  534. int64_t diff;
  535. if (!have_work()) {
  536. return;
  537. }
  538. monotime_get(&now);
  539. /* If time is really monotonic, we can never have now being smaller than the
  540. * last scheduler run. The scheduler_last_run at first is set to 0.
  541. * Unfortunately, not all platforms guarantee monotonic time so we log at
  542. * info level but don't make it more noisy. */
  543. diff = monotime_diff_msec(&scheduler_last_run, &now);
  544. if (diff < 0) {
  545. log_info(LD_SCHED, "Monotonic time between now and last run of scheduler "
  546. "is negative: %" PRId64 ". Setting diff to 0.", diff);
  547. diff = 0;
  548. }
  549. if (diff < sched_run_interval) {
  550. next_run.tv_sec = 0;
  551. /* Takes 1000 ms -> us. This will always be valid because diff can NOT be
  552. * negative and can NOT be bigger than sched_run_interval so values can
  553. * only go from 1000 usec (diff set to interval - 1) to 100000 usec (diff
  554. * set to 0) for the maximum allowed run interval (100ms). */
  555. next_run.tv_usec = (int) ((sched_run_interval - diff) * 1000);
  556. /* Re-adding an event reschedules it. It does not duplicate it. */
  557. scheduler_ev_add(&next_run);
  558. } else {
  559. scheduler_ev_active();
  560. }
  561. }
  562. /* Function of the scheduler interface: run() */
  563. static void
  564. kist_scheduler_run(void)
  565. {
  566. /* Define variables */
  567. channel_t *chan = NULL; // current working channel
  568. /* The last distinct chan served in a sched loop. */
  569. channel_t *prev_chan = NULL;
  570. int flush_result; // temporarily store results from flush calls
  571. /* Channels to be re-adding to pending at the end */
  572. smartlist_t *to_readd = NULL;
  573. smartlist_t *cp = get_channels_pending();
  574. outbuf_table_t outbuf_table = HT_INITIALIZER();
  575. /* For each pending channel, collect new kernel information */
  576. SMARTLIST_FOREACH_BEGIN(cp, const channel_t *, pchan) {
  577. init_socket_info(&socket_table, pchan);
  578. update_socket_info(&socket_table, pchan);
  579. } SMARTLIST_FOREACH_END(pchan);
  580. log_debug(LD_SCHED, "Running the scheduler. %d channels pending",
  581. smartlist_len(cp));
  582. /* The main scheduling loop. Loop until there are no more pending channels */
  583. while (smartlist_len(cp) > 0) {
  584. /* get best channel */
  585. chan = smartlist_pqueue_pop(cp, scheduler_compare_channels,
  586. offsetof(channel_t, sched_heap_idx));
  587. if (SCHED_BUG(!chan, NULL)) {
  588. /* Some-freaking-how a NULL got into the channels_pending. That should
  589. * never happen, but it should be harmless to ignore it and keep looping.
  590. */
  591. continue;
  592. }
  593. bool added_new = outbuf_table_add(&outbuf_table, chan);
  594. if (added_new) {
  595. connection_t *conn = TO_CONN(BASE_CHAN_TO_TLS(chan)->conn);
  596. event_source_deliver_silently(conn->event_source,
  597. or_conn_outgoing_packed_cell, true);
  598. //tor_assert(conn->safe_conn != NULL);
  599. //safe_connection_stop_caring_about_modified(conn->safe_conn);
  600. }
  601. /* if we have switched to a new channel, consider writing the previous
  602. * channel's outbuf to the kernel. */
  603. if (!prev_chan) {
  604. prev_chan = chan;
  605. }
  606. if (prev_chan != chan) {
  607. //if (channel_should_write_to_kernel(&outbuf_table, prev_chan)) {
  608. // channel_write_to_kernel(prev_chan);
  609. // outbuf_table_remove(&outbuf_table, prev_chan);
  610. //}
  611. prev_chan = chan;
  612. }
  613. /* Only flush and write if the per-socket limit hasn't been hit */
  614. if (socket_can_write(&socket_table, chan)) {
  615. /* flush to channel queue/outbuf */
  616. flush_result = (int)channel_flush_some_cells(chan, 1); // 1 for num cells
  617. /* XXX: While flushing cells, it is possible that the connection write
  618. * fails leading to the channel to be closed which triggers a release
  619. * and free its entry in the socket table. And because of a engineering
  620. * design issue, the error is not propagated back so we don't get an
  621. * error at this point. So before we continue, make sure the channel is
  622. * open and if not just ignore it. See #23751. */
  623. if (!CHANNEL_IS_OPEN(chan)) {
  624. /* Channel isn't open so we put it back in IDLE mode. It is either
  625. * renegotiating its TLS session or about to be released. */
  626. scheduler_set_channel_state(chan, SCHED_CHAN_IDLE);
  627. continue;
  628. }
  629. /* flush_result has the # cells flushed */
  630. if (flush_result > 0) {
  631. update_socket_written(&socket_table, chan, flush_result *
  632. (CELL_MAX_NETWORK_SIZE + TLS_PER_CELL_OVERHEAD));
  633. } else {
  634. /* XXX: This can happen because tor sometimes does flush in an
  635. * opportunistic way cells from the circuit to the outbuf so the
  636. * channel can end up here without having anything to flush nor needed
  637. * to write to the kernel. Hopefully we'll fix that soon but for now
  638. * we have to handle this case which happens kind of often. */
  639. log_debug(LD_SCHED,
  640. "We didn't flush anything on a chan that we think "
  641. "can write and wants to write. The channel's state is '%s' "
  642. "and in scheduler state '%s'. We're going to mark it as "
  643. "waiting_for_cells (as that's most likely the issue) and "
  644. "stop scheduling it this round.",
  645. channel_state_to_string(chan->state),
  646. get_scheduler_state_string(chan->scheduler_state));
  647. scheduler_set_channel_state(chan, SCHED_CHAN_WAITING_FOR_CELLS);
  648. continue;
  649. }
  650. }
  651. /* Decide what to do with the channel now */
  652. if (!channel_more_to_flush(chan) &&
  653. !socket_can_write(&socket_table, chan)) {
  654. /* Case 1: no more cells to send, and cannot write */
  655. /*
  656. * You might think we should put the channel in SCHED_CHAN_IDLE. And
  657. * you're probably correct. While implementing KIST, we found that the
  658. * scheduling system would sometimes lose track of channels when we did
  659. * that. We suspect it has to do with the difference between "can't
  660. * write because socket/outbuf is full" and KIST's "can't write because
  661. * we've arbitrarily decided that that's enough for now." Sometimes
  662. * channels run out of cells at the same time they hit their
  663. * kist-imposed write limit and maybe the rest of Tor doesn't put the
  664. * channel back in pending when it is supposed to.
  665. *
  666. * This should be investigated again. It is as simple as changing
  667. * SCHED_CHAN_WAITING_FOR_CELLS to SCHED_CHAN_IDLE and seeing if Tor
  668. * starts having serious throughput issues. Best done in shadow/chutney.
  669. */
  670. scheduler_set_channel_state(chan, SCHED_CHAN_WAITING_FOR_CELLS);
  671. } else if (!channel_more_to_flush(chan)) {
  672. /* Case 2: no more cells to send, but still open for writes */
  673. scheduler_set_channel_state(chan, SCHED_CHAN_WAITING_FOR_CELLS);
  674. } else if (!socket_can_write(&socket_table, chan)) {
  675. /* Case 3: cells to send, but cannot write */
  676. /*
  677. * We want to write, but can't. If we left the channel in
  678. * channels_pending, we would never exit the scheduling loop. We need to
  679. * add it to a temporary list of channels to be added to channels_pending
  680. * after the scheduling loop is over. They can hopefully be taken care of
  681. * in the next scheduling round.
  682. */
  683. if (!to_readd) {
  684. to_readd = smartlist_new();
  685. }
  686. smartlist_add(to_readd, chan);
  687. } else {
  688. /* Case 4: cells to send, and still open for writes */
  689. scheduler_set_channel_state(chan, SCHED_CHAN_PENDING);
  690. if (!SCHED_BUG(chan->sched_heap_idx != -1, chan)) {
  691. smartlist_pqueue_add(cp, scheduler_compare_channels,
  692. offsetof(channel_t, sched_heap_idx), chan);
  693. }
  694. }
  695. } /* End of main scheduling loop */
  696. /* Write the outbuf of any channels that still have data */
  697. //HT_FOREACH_FN(outbuf_table_s, &outbuf_table, each_channel_write_to_kernel,
  698. // NULL);
  699. HT_FOREACH_FN(outbuf_table_s, &outbuf_table, each_channel_wakeup_listeners,
  700. NULL);
  701. /* We are done with it. */
  702. HT_FOREACH_FN(outbuf_table_s, &outbuf_table, free_outbuf_info_by_ent, NULL);
  703. HT_CLEAR(outbuf_table_s, &outbuf_table);
  704. log_debug(LD_SCHED, "len pending=%d, len to_readd=%d",
  705. smartlist_len(cp),
  706. (to_readd ? smartlist_len(to_readd) : -1));
  707. /* Re-add any channels we need to */
  708. if (to_readd) {
  709. SMARTLIST_FOREACH_BEGIN(to_readd, channel_t *, readd_chan) {
  710. scheduler_set_channel_state(readd_chan, SCHED_CHAN_PENDING);
  711. if (!smartlist_contains(cp, readd_chan)) {
  712. if (!SCHED_BUG(readd_chan->sched_heap_idx != -1, readd_chan)) {
  713. /* XXXX Note that the check above is in theory redundant with
  714. * the smartlist_contains check. But let's make sure we're
  715. * not messing anything up, and leave them both for now. */
  716. smartlist_pqueue_add(cp, scheduler_compare_channels,
  717. offsetof(channel_t, sched_heap_idx), readd_chan);
  718. }
  719. }
  720. } SMARTLIST_FOREACH_END(readd_chan);
  721. smartlist_free(to_readd);
  722. }
  723. monotime_get(&scheduler_last_run);
  724. }
  725. /*****************************************************************************
  726. * Externally called function implementations not called through scheduler_t
  727. *****************************************************************************/
  728. /* Stores the kist scheduler function pointers. */
  729. static scheduler_t kist_scheduler = {
  730. .type = SCHEDULER_KIST,
  731. .free_all = kist_free_all,
  732. .on_channel_free = kist_on_channel_free_fn,
  733. .init = kist_scheduler_init,
  734. .on_new_consensus = kist_scheduler_on_new_consensus,
  735. .schedule = kist_scheduler_schedule,
  736. .run = kist_scheduler_run,
  737. .on_new_options = kist_scheduler_on_new_options,
  738. };
  739. /* Return the KIST scheduler object. If it didn't exists, return a newly
  740. * allocated one but init() is not called. */
  741. scheduler_t *
  742. get_kist_scheduler(void)
  743. {
  744. return &kist_scheduler;
  745. }
  746. /* Check the torrc (and maybe consensus) for the configured KIST scheduler run
  747. * interval.
  748. * - If torrc > 0, then return the positive torrc value (should use KIST, and
  749. * should use the set value)
  750. * - If torrc == 0, then look in the consensus for what the value should be.
  751. * - If == 0, then return 0 (don't use KIST)
  752. * - If > 0, then return the positive consensus value
  753. * - If consensus doesn't say anything, return 10 milliseconds, default.
  754. */
  755. int
  756. kist_scheduler_run_interval(void)
  757. {
  758. int run_interval = get_options()->KISTSchedRunInterval;
  759. if (run_interval != 0) {
  760. log_debug(LD_SCHED, "Found KISTSchedRunInterval=%" PRId32 " in torrc. "
  761. "Using that.", run_interval);
  762. return run_interval;
  763. }
  764. log_debug(LD_SCHED, "KISTSchedRunInterval=0, turning to the consensus.");
  765. /* Will either be the consensus value or the default. Note that 0 can be
  766. * returned which means the consensus wants us to NOT use KIST. */
  767. return networkstatus_get_param(NULL, "KISTSchedRunInterval",
  768. KIST_SCHED_RUN_INTERVAL_DEFAULT,
  769. KIST_SCHED_RUN_INTERVAL_MIN,
  770. KIST_SCHED_RUN_INTERVAL_MAX);
  771. }
  772. /* Set KISTLite mode that is KIST without kernel support. */
  773. void
  774. scheduler_kist_set_lite_mode(void)
  775. {
  776. kist_lite_mode = 1;
  777. kist_scheduler.type = SCHEDULER_KIST_LITE;
  778. log_info(LD_SCHED,
  779. "Setting KIST scheduler without kernel support (KISTLite mode)");
  780. }
  781. /* Set KIST mode that is KIST with kernel support. */
  782. void
  783. scheduler_kist_set_full_mode(void)
  784. {
  785. kist_lite_mode = 0;
  786. kist_scheduler.type = SCHEDULER_KIST;
  787. log_info(LD_SCHED,
  788. "Setting KIST scheduler with kernel support (KIST mode)");
  789. }
  790. #ifdef HAVE_KIST_SUPPORT
  791. /* Return true iff the scheduler subsystem should use KIST. */
  792. int
  793. scheduler_can_use_kist(void)
  794. {
  795. if (kist_no_kernel_support) {
  796. /* We have no kernel support so we can't use KIST. */
  797. return 0;
  798. }
  799. /* We do have the support, time to check if we can get the interval that the
  800. * consensus can be disabling. */
  801. int run_interval = kist_scheduler_run_interval();
  802. log_debug(LD_SCHED, "Determined KIST sched_run_interval should be "
  803. "%" PRId32 ". Can%s use KIST.",
  804. run_interval, (run_interval > 0 ? "" : " not"));
  805. return run_interval > 0;
  806. }
  807. #else /* !defined(HAVE_KIST_SUPPORT) */
  808. int
  809. scheduler_can_use_kist(void)
  810. {
  811. return 0;
  812. }
  813. #endif /* defined(HAVE_KIST_SUPPORT) */