scheduler_kist.c 32 KB

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