scheduler_kist.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. /* Copyright (c) 2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #define SCHEDULER_KIST_PRIVATE
  4. #include <event2/event.h>
  5. #include "or.h"
  6. #include "buffers.h"
  7. #include "config.h"
  8. #include "connection.h"
  9. #include "networkstatus.h"
  10. #define TOR_CHANNEL_INTERNAL_
  11. #include "channel.h"
  12. #include "channeltls.h"
  13. #define SCHEDULER_PRIVATE_
  14. #include "scheduler.h"
  15. #define TLS_PER_CELL_OVERHEAD 29
  16. #ifdef HAVE_KIST_SUPPORT
  17. /* Kernel interface needed for KIST. */
  18. #include <netinet/tcp.h>
  19. #include <linux/sockios.h>
  20. #endif /* HAVE_KIST_SUPPORT */
  21. /*****************************************************************************
  22. * Data structures and supporting functions
  23. *****************************************************************************/
  24. /* Socket_table hash table stuff. The socket_table keeps track of per-socket
  25. * limit information imposed by kist and used by kist. */
  26. static uint32_t
  27. socket_table_ent_hash(const socket_table_ent_t *ent)
  28. {
  29. return (uint32_t)ent->chan->global_identifier;
  30. }
  31. static unsigned
  32. socket_table_ent_eq(const socket_table_ent_t *a, const socket_table_ent_t *b)
  33. {
  34. return a->chan == b->chan;
  35. }
  36. typedef HT_HEAD(socket_table_s, socket_table_ent_s) socket_table_t;
  37. static socket_table_t socket_table = HT_INITIALIZER();
  38. HT_PROTOTYPE(socket_table_s, socket_table_ent_s, node, socket_table_ent_hash,
  39. socket_table_ent_eq)
  40. HT_GENERATE2(socket_table_s, socket_table_ent_s, node, socket_table_ent_hash,
  41. socket_table_ent_eq, 0.6, tor_reallocarray, tor_free_)
  42. /* outbuf_table hash table stuff. The outbuf_table keeps track of which
  43. * channels have data sitting in their outbuf so the kist scheduler can force
  44. * a write from outbuf to kernel periodically during a run and at the end of a
  45. * run. */
  46. typedef struct outbuf_table_ent_s {
  47. HT_ENTRY(outbuf_table_ent_s) node;
  48. channel_t *chan;
  49. } outbuf_table_ent_t;
  50. static uint32_t
  51. outbuf_table_ent_hash(const outbuf_table_ent_t *ent)
  52. {
  53. return (uint32_t)ent->chan->global_identifier;
  54. }
  55. static unsigned
  56. outbuf_table_ent_eq(const outbuf_table_ent_t *a, const outbuf_table_ent_t *b)
  57. {
  58. return a->chan->global_identifier == b->chan->global_identifier;
  59. }
  60. HT_PROTOTYPE(outbuf_table_s, outbuf_table_ent_s, node, outbuf_table_ent_hash,
  61. outbuf_table_ent_eq)
  62. HT_GENERATE2(outbuf_table_s, outbuf_table_ent_s, node, outbuf_table_ent_hash,
  63. outbuf_table_ent_eq, 0.6, tor_reallocarray, tor_free_)
  64. /*****************************************************************************
  65. * Other internal data
  66. *****************************************************************************/
  67. /* Store the last time the scheduler was run so we can decide when to next run
  68. * the scheduler based on it. */
  69. static monotime_t scheduler_last_run;
  70. /* This is a factor for the extra_space calculation in kist per-socket limits.
  71. * It is the number of extra congestion windows we want to write to the kernel.
  72. */
  73. static double sock_buf_size_factor = 1.0;
  74. /* How often the scheduler runs. */
  75. STATIC int32_t sched_run_interval = 10;
  76. #ifdef HAVE_KIST_SUPPORT
  77. /* Indicate if KIST lite mode is on or off. We can disable it at runtime.
  78. * Important to have because of the KISTLite -> KIST possible transition. */
  79. static unsigned int kist_lite_mode = 0;
  80. /* Indicate if we don't have the kernel support. This can happen if the kernel
  81. * changed and it doesn't recognized the values passed to the syscalls needed
  82. * by KIST. In that case, fallback to the naive approach. */
  83. static unsigned int kist_no_kernel_support = 0;
  84. #else /* !(defined(HAVE_KIST_SUPPORT)) */
  85. static unsigned int kist_lite_mode = 1;
  86. #endif /* defined(HAVE_KIST_SUPPORT) */
  87. /*****************************************************************************
  88. * Internally called function implementations
  89. *****************************************************************************/
  90. /* Little helper function to get the length of a channel's output buffer */
  91. static inline size_t
  92. channel_outbuf_length(channel_t *chan)
  93. {
  94. /* In theory, this can not happen because we can not scheduler a channel
  95. * without a connection that has its outbuf initialized. Just in case, bug
  96. * on this so we can understand a bit more why it happened. */
  97. if (BUG(BASE_CHAN_TO_TLS(chan)->conn == NULL)) {
  98. return 0;
  99. }
  100. return buf_datalen(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn)->outbuf);
  101. }
  102. /* Little helper function for HT_FOREACH_FN. */
  103. static int
  104. each_channel_write_to_kernel(outbuf_table_ent_t *ent, void *data)
  105. {
  106. (void) data; /* Make compiler happy. */
  107. channel_write_to_kernel(ent->chan);
  108. return 0; /* Returning non-zero removes the element from the table. */
  109. }
  110. /* Free the given outbuf table entry ent. */
  111. static int
  112. free_outbuf_info_by_ent(outbuf_table_ent_t *ent, void *data)
  113. {
  114. (void) data; /* Make compiler happy. */
  115. log_debug(LD_SCHED, "Freeing outbuf table entry from chan=%" PRIu64,
  116. ent->chan->global_identifier);
  117. tor_free(ent);
  118. return 1; /* So HT_FOREACH_FN will remove the element */
  119. }
  120. /* Free the given socket table entry ent. */
  121. static int
  122. free_socket_info_by_ent(socket_table_ent_t *ent, void *data)
  123. {
  124. (void) data; /* Make compiler happy. */
  125. log_debug(LD_SCHED, "Freeing socket table entry from chan=%" PRIu64,
  126. ent->chan->global_identifier);
  127. tor_free(ent);
  128. return 1; /* So HT_FOREACH_FN will remove the element */
  129. }
  130. /* Clean up socket_table. Probably because the KIST sched impl is going away */
  131. static void
  132. free_all_socket_info(void)
  133. {
  134. HT_FOREACH_FN(socket_table_s, &socket_table, free_socket_info_by_ent, NULL);
  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. /* Assuming all these values from the kernel are uint32_t still, they will
  234. * always fit into a int64_t tcp_space variable. */
  235. tcp_space = (ent->cwnd - ent->unacked) * (int64_t)ent->mss;
  236. if (tcp_space < 0) {
  237. tcp_space = 0;
  238. }
  239. /* The clamp_double_to_int64 makes sure the first part fits into an int64_t.
  240. * In fact, if sock_buf_size_factor is still forced to be >= 0 in config.c,
  241. * then it will be positive for sure. Then we subtract a uint32_t. At worst
  242. * we end up negative, but then we just set extra_space to 0 in the sanity
  243. * check.*/
  244. extra_space =
  245. clamp_double_to_int64(
  246. (ent->cwnd * (int64_t)ent->mss) * sock_buf_size_factor) -
  247. ent->notsent;
  248. if (extra_space < 0) {
  249. extra_space = 0;
  250. }
  251. /* Finally we set the limit. Adding two positive int64_t together will always
  252. * fit in an uint64_t. */
  253. ent->limit = (uint64_t)tcp_space + (uint64_t)extra_space;
  254. return;
  255. #else /* !(defined(HAVE_KIST_SUPPORT)) */
  256. goto fallback;
  257. #endif /* defined(HAVE_KIST_SUPPORT) */
  258. fallback:
  259. /* If all of a sudden we don't have kist support, we just zero out all the
  260. * variables for this socket since we don't know what they should be.
  261. * We also effectively allow the socket write as much as it wants to the
  262. * kernel, effectively returning it to vanilla scheduler behavior. Writes
  263. * are still limited by the lower layers of Tor: socket blocking, full
  264. * outbuf, etc. */
  265. ent->cwnd = ent->unacked = ent->mss = ent->notsent = 0;
  266. ent->limit = INT_MAX;
  267. }
  268. /* Given a socket that isn't in the table, add it.
  269. * Given a socket that is in the table, re-init values that need init-ing
  270. * every scheduling run
  271. */
  272. static void
  273. init_socket_info(socket_table_t *table, const channel_t *chan)
  274. {
  275. socket_table_ent_t *ent = NULL;
  276. ent = socket_table_search(table, chan);
  277. if (!ent) {
  278. log_debug(LD_SCHED, "scheduler init socket info for chan=%" PRIu64,
  279. chan->global_identifier);
  280. ent = tor_malloc_zero(sizeof(*ent));
  281. ent->chan = chan;
  282. HT_INSERT(socket_table_s, table, ent);
  283. }
  284. ent->written = 0;
  285. }
  286. /* Add chan to the outbuf table if it isn't already in it. If it is, then don't
  287. * do anything */
  288. static void
  289. outbuf_table_add(outbuf_table_t *table, channel_t *chan)
  290. {
  291. outbuf_table_ent_t search, *ent;
  292. search.chan = chan;
  293. ent = HT_FIND(outbuf_table_s, table, &search);
  294. if (!ent) {
  295. log_debug(LD_SCHED, "scheduler init outbuf info for chan=%" PRIu64,
  296. chan->global_identifier);
  297. ent = tor_malloc_zero(sizeof(*ent));
  298. ent->chan = chan;
  299. HT_INSERT(outbuf_table_s, table, ent);
  300. }
  301. }
  302. static void
  303. outbuf_table_remove(outbuf_table_t *table, channel_t *chan)
  304. {
  305. outbuf_table_ent_t search, *ent;
  306. search.chan = chan;
  307. ent = HT_FIND(outbuf_table_s, table, &search);
  308. if (ent) {
  309. HT_REMOVE(outbuf_table_s, table, ent);
  310. free_outbuf_info_by_ent(ent, NULL);
  311. }
  312. }
  313. /* Set the scheduler running interval. */
  314. static void
  315. set_scheduler_run_interval(const networkstatus_t *ns)
  316. {
  317. int32_t old_sched_run_interval = sched_run_interval;
  318. sched_run_interval = kist_scheduler_run_interval(ns);
  319. if (old_sched_run_interval != sched_run_interval) {
  320. log_info(LD_SCHED, "Scheduler KIST changing its running interval "
  321. "from %" PRId32 " to %" PRId32,
  322. old_sched_run_interval, sched_run_interval);
  323. }
  324. }
  325. /* Return true iff the channel hasn’t hit its kist-imposed write limit yet */
  326. static int
  327. socket_can_write(socket_table_t *table, const channel_t *chan)
  328. {
  329. socket_table_ent_t *ent = NULL;
  330. ent = socket_table_search(table, chan);
  331. IF_BUG_ONCE(!ent) {
  332. return 1; // Just return true, saying that kist wouldn't limit the socket
  333. }
  334. /* We previously calculated a write limit for this socket. In the below
  335. * calculation, first determine how much room is left in bytes. Then divide
  336. * that by the amount of space a cell takes. If there's room for at least 1
  337. * cell, then KIST will allow the socket to write. */
  338. int64_t kist_limit_space =
  339. (int64_t) (ent->limit - ent->written) /
  340. (CELL_MAX_NETWORK_SIZE + TLS_PER_CELL_OVERHEAD);
  341. return kist_limit_space > 0;
  342. }
  343. /* Update the channel's socket kernel information. */
  344. static void
  345. update_socket_info(socket_table_t *table, const channel_t *chan)
  346. {
  347. socket_table_ent_t *ent = NULL;
  348. ent = socket_table_search(table, chan);
  349. IF_BUG_ONCE(!ent) {
  350. return; // Whelp. Entry didn't exist for some reason so nothing to do.
  351. }
  352. update_socket_info_impl(ent);
  353. }
  354. /* Increment the channel's socket written value by the number of bytes. */
  355. static void
  356. update_socket_written(socket_table_t *table, channel_t *chan, size_t bytes)
  357. {
  358. socket_table_ent_t *ent = NULL;
  359. ent = socket_table_search(table, chan);
  360. IF_BUG_ONCE(!ent) {
  361. return; // Whelp. Entry didn't exist so nothing to do.
  362. }
  363. log_debug(LD_SCHED, "chan=%" PRIu64 " wrote %lu bytes, old was %" PRIi64,
  364. chan->global_identifier, (unsigned long) bytes, ent->written);
  365. ent->written += bytes;
  366. }
  367. /*
  368. * A naive KIST impl would write every single cell all the way to the kernel.
  369. * That would take a lot of system calls. A less bad KIST impl would write a
  370. * channel's outbuf to the kernel only when we are switching to a different
  371. * channel. But if we have two channels with equal priority, we end up writing
  372. * one cell for each and bouncing back and forth. This KIST impl avoids that
  373. * by only writing a channel's outbuf to the kernel if it has 8 cells or more
  374. * in it.
  375. */
  376. MOCK_IMPL(int, channel_should_write_to_kernel,
  377. (outbuf_table_t *table, channel_t *chan))
  378. {
  379. outbuf_table_add(table, chan);
  380. /* CELL_MAX_NETWORK_SIZE * 8 because we only want to write the outbuf to the
  381. * kernel if there's 8 or more cells waiting */
  382. return channel_outbuf_length(chan) > (CELL_MAX_NETWORK_SIZE * 8);
  383. }
  384. /* Little helper function to write a channel's outbuf all the way to the
  385. * kernel */
  386. MOCK_IMPL(void, channel_write_to_kernel, (channel_t *chan))
  387. {
  388. log_debug(LD_SCHED, "Writing %lu bytes to kernel for chan %" PRIu64,
  389. (unsigned long)channel_outbuf_length(chan),
  390. chan->global_identifier);
  391. connection_handle_write(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn), 0);
  392. }
  393. /* Return true iff the scheduler has work to perform. */
  394. static int
  395. have_work(void)
  396. {
  397. smartlist_t *cp = get_channels_pending();
  398. IF_BUG_ONCE(!cp) {
  399. return 0; // channels_pending doesn't exist so... no work?
  400. }
  401. return smartlist_len(cp) > 0;
  402. }
  403. /* Function of the scheduler interface: free_all() */
  404. static void
  405. kist_free_all(void)
  406. {
  407. free_all_socket_info();
  408. }
  409. /* Function of the scheduler interface: on_channel_free() */
  410. static void
  411. kist_on_channel_free(const channel_t *chan)
  412. {
  413. free_socket_info_by_chan(&socket_table, chan);
  414. }
  415. /* Function of the scheduler interface: on_new_consensus() */
  416. static void
  417. kist_scheduler_on_new_consensus(const networkstatus_t *old_c,
  418. const networkstatus_t *new_c)
  419. {
  420. (void) old_c;
  421. (void) new_c;
  422. set_scheduler_run_interval(new_c);
  423. }
  424. /* Function of the scheduler interface: on_new_options() */
  425. static void
  426. kist_scheduler_on_new_options(void)
  427. {
  428. sock_buf_size_factor = get_options()->KISTSockBufSizeFactor;
  429. /* Calls kist_scheduler_run_interval which calls get_options(). */
  430. set_scheduler_run_interval(NULL);
  431. }
  432. /* Function of the scheduler interface: init() */
  433. static void
  434. kist_scheduler_init(void)
  435. {
  436. kist_scheduler_on_new_options();
  437. IF_BUG_ONCE(sched_run_interval == 0) {
  438. log_warn(LD_SCHED, "We are initing the KIST scheduler and noticed the "
  439. "KISTSchedRunInterval is telling us to not use KIST. That's "
  440. "weird! We'll continue using KIST, but at %dms.",
  441. KIST_SCHED_RUN_INTERVAL_DEFAULT);
  442. sched_run_interval = KIST_SCHED_RUN_INTERVAL_DEFAULT;
  443. }
  444. }
  445. /* Function of the scheduler interface: schedule() */
  446. static void
  447. kist_scheduler_schedule(void)
  448. {
  449. struct monotime_t now;
  450. struct timeval next_run;
  451. int64_t diff;
  452. if (!have_work()) {
  453. return;
  454. }
  455. monotime_get(&now);
  456. /* If time is really monotonic, we can never have now being smaller than the
  457. * last scheduler run. The scheduler_last_run at first is set to 0. */
  458. diff = monotime_diff_msec(&scheduler_last_run, &now);
  459. IF_BUG_ONCE(diff < 0) {
  460. diff = 0;
  461. }
  462. if (diff < sched_run_interval) {
  463. next_run.tv_sec = 0;
  464. /* Takes 1000 ms -> us. This will always be valid because diff can NOT be
  465. * negative and can NOT be bigger than sched_run_interval so values can
  466. * only go from 1000 usec (diff set to interval - 1) to 100000 usec (diff
  467. * set to 0) for the maximum allowed run interval (100ms). */
  468. next_run.tv_usec = (int) ((sched_run_interval - diff) * 1000);
  469. /* Re-adding an event reschedules it. It does not duplicate it. */
  470. scheduler_ev_add(&next_run);
  471. } else {
  472. scheduler_ev_active(EV_TIMEOUT);
  473. }
  474. }
  475. /* Function of the scheduler interface: run() */
  476. static void
  477. kist_scheduler_run(void)
  478. {
  479. /* Define variables */
  480. channel_t *chan = NULL; // current working channel
  481. /* The last distinct chan served in a sched loop. */
  482. channel_t *prev_chan = NULL;
  483. int flush_result; // temporarily store results from flush calls
  484. /* Channels to be re-adding to pending at the end */
  485. smartlist_t *to_readd = NULL;
  486. smartlist_t *cp = get_channels_pending();
  487. outbuf_table_t outbuf_table = HT_INITIALIZER();
  488. /* For each pending channel, collect new kernel information */
  489. SMARTLIST_FOREACH_BEGIN(cp, const channel_t *, pchan) {
  490. init_socket_info(&socket_table, pchan);
  491. update_socket_info(&socket_table, pchan);
  492. } SMARTLIST_FOREACH_END(pchan);
  493. log_debug(LD_SCHED, "Running the scheduler. %d channels pending",
  494. smartlist_len(cp));
  495. /* The main scheduling loop. Loop until there are no more pending channels */
  496. while (smartlist_len(cp) > 0) {
  497. /* get best channel */
  498. chan = smartlist_pqueue_pop(cp, scheduler_compare_channels,
  499. offsetof(channel_t, sched_heap_idx));
  500. IF_BUG_ONCE(!chan) {
  501. /* Some-freaking-how a NULL got into the channels_pending. That should
  502. * never happen, but it should be harmless to ignore it and keep looping.
  503. */
  504. continue;
  505. }
  506. outbuf_table_add(&outbuf_table, chan);
  507. /* if we have switched to a new channel, consider writing the previous
  508. * channel's outbuf to the kernel. */
  509. if (!prev_chan) {
  510. prev_chan = chan;
  511. }
  512. if (prev_chan != chan) {
  513. if (channel_should_write_to_kernel(&outbuf_table, prev_chan)) {
  514. channel_write_to_kernel(prev_chan);
  515. outbuf_table_remove(&outbuf_table, prev_chan);
  516. }
  517. prev_chan = chan;
  518. }
  519. /* Only flush and write if the per-socket limit hasn't been hit */
  520. if (socket_can_write(&socket_table, chan)) {
  521. /* flush to channel queue/outbuf */
  522. flush_result = (int)channel_flush_some_cells(chan, 1); // 1 for num cells
  523. /* flush_result has the # cells flushed */
  524. if (flush_result > 0) {
  525. update_socket_written(&socket_table, chan, flush_result *
  526. (CELL_MAX_NETWORK_SIZE + TLS_PER_CELL_OVERHEAD));
  527. }
  528. /* XXX What if we didn't flush? */
  529. }
  530. /* Decide what to do with the channel now */
  531. if (!channel_more_to_flush(chan) &&
  532. !socket_can_write(&socket_table, chan)) {
  533. /* Case 1: no more cells to send, and cannot write */
  534. /*
  535. * You might think we should put the channel in SCHED_CHAN_IDLE. And
  536. * you're probably correct. While implementing KIST, we found that the
  537. * scheduling system would sometimes lose track of channels when we did
  538. * that. We suspect it has to do with the difference between "can't
  539. * write because socket/outbuf is full" and KIST's "can't write because
  540. * we've arbitrarily decided that that's enough for now." Sometimes
  541. * channels run out of cells at the same time they hit their
  542. * kist-imposed write limit and maybe the rest of Tor doesn't put the
  543. * channel back in pending when it is supposed to.
  544. *
  545. * This should be investigated again. It is as simple as changing
  546. * SCHED_CHAN_WAITING_FOR_CELLS to SCHED_CHAN_IDLE and seeing if Tor
  547. * starts having serious throughput issues. Best done in shadow/chutney.
  548. */
  549. chan->scheduler_state = SCHED_CHAN_WAITING_FOR_CELLS;
  550. log_debug(LD_SCHED, "chan=%" PRIu64 " now waiting_for_cells",
  551. chan->global_identifier);
  552. } else if (!channel_more_to_flush(chan)) {
  553. /* Case 2: no more cells to send, but still open for writes */
  554. chan->scheduler_state = SCHED_CHAN_WAITING_FOR_CELLS;
  555. log_debug(LD_SCHED, "chan=%" PRIu64 " now waiting_for_cells",
  556. chan->global_identifier);
  557. } else if (!socket_can_write(&socket_table, chan)) {
  558. /* Case 3: cells to send, but cannot write */
  559. /*
  560. * We want to write, but can't. If we left the channel in
  561. * channels_pending, we would never exit the scheduling loop. We need to
  562. * add it to a temporary list of channels to be added to channels_pending
  563. * after the scheduling loop is over. They can hopefully be taken care of
  564. * in the next scheduling round.
  565. */
  566. chan->scheduler_state = SCHED_CHAN_WAITING_TO_WRITE;
  567. if (!to_readd) {
  568. to_readd = smartlist_new();
  569. }
  570. smartlist_add(to_readd, chan);
  571. log_debug(LD_SCHED, "chan=%" PRIu64 " now waiting_to_write",
  572. chan->global_identifier);
  573. } else {
  574. /* Case 4: cells to send, and still open for writes */
  575. chan->scheduler_state = SCHED_CHAN_PENDING;
  576. smartlist_pqueue_add(cp, scheduler_compare_channels,
  577. offsetof(channel_t, sched_heap_idx), chan);
  578. }
  579. } /* End of main scheduling loop */
  580. /* Write the outbuf of any channels that still have data */
  581. HT_FOREACH_FN(outbuf_table_s, &outbuf_table, each_channel_write_to_kernel,
  582. NULL);
  583. /* We are done with it. */
  584. HT_FOREACH_FN(outbuf_table_s, &outbuf_table, free_outbuf_info_by_ent, NULL);
  585. HT_CLEAR(outbuf_table_s, &outbuf_table);
  586. log_debug(LD_SCHED, "len pending=%d, len to_readd=%d",
  587. smartlist_len(cp),
  588. (to_readd ? smartlist_len(to_readd) : -1));
  589. /* Re-add any channels we need to */
  590. if (to_readd) {
  591. SMARTLIST_FOREACH_BEGIN(to_readd, channel_t *, readd_chan) {
  592. readd_chan->scheduler_state = SCHED_CHAN_PENDING;
  593. if (!smartlist_contains(cp, readd_chan)) {
  594. smartlist_pqueue_add(cp, scheduler_compare_channels,
  595. offsetof(channel_t, sched_heap_idx), readd_chan);
  596. }
  597. } SMARTLIST_FOREACH_END(readd_chan);
  598. smartlist_free(to_readd);
  599. }
  600. monotime_get(&scheduler_last_run);
  601. }
  602. /*****************************************************************************
  603. * Externally called function implementations not called through scheduler_t
  604. *****************************************************************************/
  605. /* Stores the kist scheduler function pointers. */
  606. static scheduler_t kist_scheduler = {
  607. .type = SCHEDULER_KIST,
  608. .free_all = kist_free_all,
  609. .on_channel_free = kist_on_channel_free,
  610. .init = kist_scheduler_init,
  611. .on_new_consensus = kist_scheduler_on_new_consensus,
  612. .schedule = kist_scheduler_schedule,
  613. .run = kist_scheduler_run,
  614. .on_new_options = kist_scheduler_on_new_options,
  615. };
  616. /* Return the KIST scheduler object. If it didn't exists, return a newly
  617. * allocated one but init() is not called. */
  618. scheduler_t *
  619. get_kist_scheduler(void)
  620. {
  621. return &kist_scheduler;
  622. }
  623. /* Check the torrc (and maybe consensus) for the configured KIST scheduler run
  624. * interval.
  625. * - If torrc > 0, then return the positive torrc value (should use KIST, and
  626. * should use the set value)
  627. * - If torrc == 0, then look in the consensus for what the value should be.
  628. * - If == 0, then return 0 (don't use KIST)
  629. * - If > 0, then return the positive consensus value
  630. * - If consensus doesn't say anything, return 10 milliseconds, default.
  631. */
  632. uint32_t
  633. kist_scheduler_run_interval(const networkstatus_t *ns)
  634. {
  635. uint32_t run_interval = get_options()->KISTSchedRunInterval;
  636. if (run_interval != 0) {
  637. log_debug(LD_SCHED, "Found KISTSchedRunInterval=%" PRIu32 " in torrc. "
  638. "Using that.", run_interval);
  639. return run_interval;
  640. }
  641. log_debug(LD_SCHED, "KISTSchedRunInterval=0, turning to the consensus.");
  642. /* Will either be the consensus value or the default. Note that 0 can be
  643. * returned which means the consensus wants us to NOT use KIST. */
  644. return networkstatus_get_param(ns, "KISTSchedRunInterval",
  645. KIST_SCHED_RUN_INTERVAL_DEFAULT,
  646. KIST_SCHED_RUN_INTERVAL_MIN,
  647. KIST_SCHED_RUN_INTERVAL_MAX);
  648. }
  649. /* Set KISTLite mode that is KIST without kernel support. */
  650. void
  651. scheduler_kist_set_lite_mode(void)
  652. {
  653. kist_lite_mode = 1;
  654. kist_scheduler.type = SCHEDULER_KIST_LITE;
  655. log_info(LD_SCHED,
  656. "Setting KIST scheduler without kernel support (KISTLite mode)");
  657. }
  658. /* Set KIST mode that is KIST with kernel support. */
  659. void
  660. scheduler_kist_set_full_mode(void)
  661. {
  662. kist_lite_mode = 0;
  663. kist_scheduler.type = SCHEDULER_KIST;
  664. log_info(LD_SCHED,
  665. "Setting KIST scheduler with kernel support (KIST mode)");
  666. }
  667. #ifdef HAVE_KIST_SUPPORT
  668. /* Return true iff the scheduler subsystem should use KIST. */
  669. int
  670. scheduler_can_use_kist(void)
  671. {
  672. if (kist_no_kernel_support) {
  673. /* We have no kernel support so we can't use KIST. */
  674. return 0;
  675. }
  676. /* We do have the support, time to check if we can get the interval that the
  677. * consensus can be disabling. */
  678. uint32_t run_interval = kist_scheduler_run_interval(NULL);
  679. log_debug(LD_SCHED, "Determined KIST sched_run_interval should be "
  680. "%" PRIu32 ". Can%s use KIST.",
  681. run_interval, (run_interval > 0 ? "" : " not"));
  682. return run_interval > 0;
  683. }
  684. #else /* !(defined(HAVE_KIST_SUPPORT)) */
  685. int
  686. scheduler_can_use_kist(void)
  687. {
  688. return 0;
  689. }
  690. #endif /* defined(HAVE_KIST_SUPPORT) */