scheduler_kist.c 31 KB

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