scheduler_kist.c 31 KB

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