scheduler.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. /* Copyright (c) 2013-2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #include "or.h"
  4. #include "config.h"
  5. #include "compat_libevent.h"
  6. #define SCHEDULER_PRIVATE_
  7. #define SCHEDULER_KIST_PRIVATE
  8. #include "scheduler.h"
  9. #include "main.h"
  10. #include "buffers.h"
  11. #define TOR_CHANNEL_INTERNAL_
  12. #include "channeltls.h"
  13. #include <event2/event.h>
  14. /**
  15. * \file scheduler.c
  16. * \brief Channel scheduling system: decides which channels should send and
  17. * receive when.
  18. *
  19. * This module is the global/common parts of the scheduling system. This system
  20. * is what decides what channels get to send cells on their circuits and when.
  21. *
  22. * Terms:
  23. * - "Scheduling system": the collection of scheduler*.{h,c} files and their
  24. * aggregate behavior.
  25. * - "Scheduler implementation": a scheduler_t. The scheduling system has one
  26. * active scheduling implementation at a time.
  27. *
  28. * In this file you will find state that any scheduler implementation can have
  29. * access to as well as the functions the rest of Tor uses to interact with the
  30. * scheduling system.
  31. *
  32. * The earliest versions of Tor approximated a kind of round-robin system
  33. * among active connections, but only approximated it. It would only consider
  34. * one connection (roughly equal to a channel in today's terms) at a time, and
  35. * thus could only prioritize circuits against others on the same connection.
  36. *
  37. * Then in response to the KIST paper[0], Tor implemented a global
  38. * circuit scheduler. It was supposed to prioritize circuits across many
  39. * channels, but wasn't effective. It is preserved in scheduler_vanilla.c.
  40. *
  41. * [0]: http://www.robgjansen.com/publications/kist-sec2014.pdf
  42. *
  43. * Then we actually got around to implementing KIST for real. We decided to
  44. * modularize the scheduler so new ones can be implemented. You can find KIST
  45. * in scheduler_kist.c.
  46. *
  47. * Channels have one of four scheduling states based on whether or not they
  48. * have cells to send and whether or not they are able to send.
  49. *
  50. * <ol>
  51. * <li>
  52. * Not open for writes, no cells to send.
  53. * <ul><li> Not much to do here, and the channel will have scheduler_state
  54. * == SCHED_CHAN_IDLE
  55. * <li> Transitions from:
  56. * <ul>
  57. * <li>Open for writes/has cells by simultaneously draining all circuit
  58. * queues and filling the output buffer.
  59. * </ul>
  60. * <li> Transitions to:
  61. * <ul>
  62. * <li> Not open for writes/has cells by arrival of cells on an attached
  63. * circuit (this would be driven from append_cell_to_circuit_queue())
  64. * <li> Open for writes/no cells by a channel type specific path;
  65. * driven from connection_or_flushed_some() for channel_tls_t.
  66. * </ul>
  67. * </ul>
  68. *
  69. * <li> Open for writes, no cells to send
  70. * <ul>
  71. * <li>Not much here either; this will be the state an idle but open
  72. * channel can be expected to settle in. It will have scheduler_state
  73. * == SCHED_CHAN_WAITING_FOR_CELLS
  74. * <li> Transitions from:
  75. * <ul>
  76. * <li>Not open for writes/no cells by flushing some of the output
  77. * buffer.
  78. * <li>Open for writes/has cells by the scheduler moving cells from
  79. * circuit queues to channel output queue, but not having enough
  80. * to fill the output queue.
  81. * </ul>
  82. * <li> Transitions to:
  83. * <ul>
  84. * <li>Open for writes/has cells by arrival of new cells on an attached
  85. * circuit, in append_cell_to_circuit_queue()
  86. * </ul>
  87. * </ul>
  88. *
  89. * <li>Not open for writes, cells to send
  90. * <ul>
  91. * <li>This is the state of a busy circuit limited by output bandwidth;
  92. * cells have piled up in the circuit queues waiting to be relayed.
  93. * The channel will have scheduler_state == SCHED_CHAN_WAITING_TO_WRITE.
  94. * <li> Transitions from:
  95. * <ul>
  96. * <li>Not open for writes/no cells by arrival of cells on an attached
  97. * circuit
  98. * <li>Open for writes/has cells by filling an output buffer without
  99. * draining all cells from attached circuits
  100. * </ul>
  101. * <li> Transitions to:
  102. * <ul>
  103. * <li>Opens for writes/has cells by draining some of the output buffer
  104. * via the connection_or_flushed_some() path (for channel_tls_t).
  105. * </ul>
  106. * </ul>
  107. *
  108. * <li>Open for writes, cells to send
  109. * <ul>
  110. * <li>This connection is ready to relay some cells and waiting for
  111. * the scheduler to choose it. The channel will have scheduler_state ==
  112. * SCHED_CHAN_PENDING.
  113. * <li>Transitions from:
  114. * <ul>
  115. * <li>Not open for writes/has cells by the connection_or_flushed_some()
  116. * path
  117. * <li>Open for writes/no cells by the append_cell_to_circuit_queue()
  118. * path
  119. * </ul>
  120. * <li> Transitions to:
  121. * <ul>
  122. * <li>Not open for writes/no cells by draining all circuit queues and
  123. * simultaneously filling the output buffer.
  124. * <li>Not open for writes/has cells by writing enough cells to fill the
  125. * output buffer
  126. * <li>Open for writes/no cells by draining all attached circuit queues
  127. * without also filling the output buffer
  128. * </ul>
  129. * </ul>
  130. * </ol>
  131. *
  132. * Other event-driven parts of the code move channels between these scheduling
  133. * states by calling scheduler functions. The scheduling system builds up a
  134. * list of channels in the SCHED_CHAN_PENDING state that the scheduler
  135. * implementation should then use when it runs. Scheduling implementations need
  136. * to properly update channel states during their scheduler_t->run() function
  137. * as that is the only opportunity for channels to move from SCHED_CHAN_PENDING
  138. * to any other state.
  139. *
  140. * The remainder of this file is a small amount of state that any scheduler
  141. * implementation should have access to, and the functions the rest of Tor uses
  142. * to interact with the scheduling system.
  143. */
  144. /*****************************************************************************
  145. * Scheduling system state
  146. *
  147. * State that can be accessed from any scheduler implementation (but not
  148. * outside the scheduling system)
  149. *****************************************************************************/
  150. /** DOCDOC */
  151. STATIC const scheduler_t *the_scheduler;
  152. /**
  153. * We keep a list of channels that are pending - i.e, have cells to write
  154. * and can accept them to send. The enum scheduler_state in channel_t
  155. * is reserved for our use.
  156. *
  157. * Priority queue of channels that can write and have cells (pending work)
  158. */
  159. STATIC smartlist_t *channels_pending = NULL;
  160. /**
  161. * This event runs the scheduler from its callback, and is manually
  162. * activated whenever a channel enters open for writes/cells to send.
  163. */
  164. STATIC struct event *run_sched_ev = NULL;
  165. static int have_logged_kist_suddenly_disabled = 0;
  166. /*****************************************************************************
  167. * Scheduling system static function definitions
  168. *
  169. * Functions that can only be accessed from this file.
  170. *****************************************************************************/
  171. /** Return a human readable string for the given scheduler type. */
  172. static const char *
  173. get_scheduler_type_string(scheduler_types_t type)
  174. {
  175. switch (type) {
  176. case SCHEDULER_VANILLA:
  177. return "Vanilla";
  178. case SCHEDULER_KIST:
  179. return "KIST";
  180. case SCHEDULER_KIST_LITE:
  181. return "KISTLite";
  182. case SCHEDULER_NONE:
  183. /* fallthrough */
  184. default:
  185. tor_assert_unreached();
  186. return "(N/A)";
  187. }
  188. }
  189. /** Returns human readable string for the given channel scheduler state. */
  190. static const char *
  191. get_scheduler_state_string(int scheduler_state)
  192. {
  193. switch (scheduler_state) {
  194. case SCHED_CHAN_IDLE:
  195. return "IDLE";
  196. case SCHED_CHAN_WAITING_FOR_CELLS:
  197. return "WAITING_FOR_CELLS";
  198. case SCHED_CHAN_WAITING_TO_WRITE:
  199. return "WAITING_TO_WRITE";
  200. case SCHED_CHAN_PENDING:
  201. return "PENDING";
  202. default:
  203. return "(invalid)";
  204. }
  205. }
  206. /**
  207. * Scheduler event callback; this should get triggered once per event loop
  208. * if any scheduling work was created during the event loop.
  209. */
  210. static void
  211. scheduler_evt_callback(evutil_socket_t fd, short events, void *arg)
  212. {
  213. (void) fd;
  214. (void) events;
  215. (void) arg;
  216. log_debug(LD_SCHED, "Scheduler event callback called");
  217. /* Run the scheduler. This is a mandatory function. */
  218. /* We might as well assert on this. If this function doesn't exist, no cells
  219. * are getting scheduled. Things are very broken. scheduler_t says the run()
  220. * function is mandatory. */
  221. tor_assert(the_scheduler->run);
  222. the_scheduler->run();
  223. /* Schedule itself back in if it has more work. */
  224. /* Again, might as well assert on this mandatory scheduler_t function. If it
  225. * doesn't exist, there's no way to tell libevent to run the scheduler again
  226. * in the future. */
  227. tor_assert(the_scheduler->schedule);
  228. the_scheduler->schedule();
  229. }
  230. /** Using the global options, select the scheduler we should be using. */
  231. static void
  232. select_scheduler(void)
  233. {
  234. scheduler_t *new_scheduler = NULL;
  235. #ifdef TOR_UNIT_TESTS
  236. /* This is hella annoying to set in the options for every test that passes
  237. * through the scheduler and there are many so if we don't explicitly have
  238. * a list of types set, just put the vanilla one. */
  239. if (get_options()->SchedulerTypes_ == NULL) {
  240. the_scheduler = get_vanilla_scheduler();
  241. return;
  242. }
  243. #endif /* defined(TOR_UNIT_TESTS) */
  244. /* This list is ordered that is first entry has the first priority. Thus, as
  245. * soon as we find a scheduler type that we can use, we use it and stop. */
  246. SMARTLIST_FOREACH_BEGIN(get_options()->SchedulerTypes_, int *, type) {
  247. switch (*type) {
  248. case SCHEDULER_VANILLA:
  249. new_scheduler = get_vanilla_scheduler();
  250. goto end;
  251. case SCHEDULER_KIST:
  252. if (!scheduler_can_use_kist()) {
  253. #ifdef HAVE_KIST_SUPPORT
  254. if (!have_logged_kist_suddenly_disabled) {
  255. /* We should only log this once in most cases. If it was the kernel
  256. * losing support for kist that caused scheduler_can_use_kist() to
  257. * return false, then this flag makes sure we only log this message
  258. * once. If it was the consensus that switched from "yes use kist"
  259. * to "no don't use kist", then we still set the flag so we log
  260. * once, but we unset the flag elsewhere if we ever can_use_kist()
  261. * again.
  262. */
  263. have_logged_kist_suddenly_disabled = 1;
  264. log_notice(LD_SCHED, "Scheduler type KIST has been disabled by "
  265. "the consensus or no kernel support.");
  266. }
  267. #else /* !(defined(HAVE_KIST_SUPPORT)) */
  268. log_info(LD_SCHED, "Scheduler type KIST not built in");
  269. #endif /* defined(HAVE_KIST_SUPPORT) */
  270. continue;
  271. }
  272. /* This flag will only get set in one of two cases:
  273. * 1 - the kernel lost support for kist. In that case, we don't expect to
  274. * ever end up here
  275. * 2 - the consensus went from "yes use kist" to "no don't use kist".
  276. * We might end up here if the consensus changes back to "yes", in which
  277. * case we might want to warn the user again if it goes back to "no"
  278. * yet again. Thus we unset the flag */
  279. have_logged_kist_suddenly_disabled = 0;
  280. new_scheduler = get_kist_scheduler();
  281. scheduler_kist_set_full_mode();
  282. goto end;
  283. case SCHEDULER_KIST_LITE:
  284. new_scheduler = get_kist_scheduler();
  285. scheduler_kist_set_lite_mode();
  286. goto end;
  287. case SCHEDULER_NONE:
  288. /* fallthrough */
  289. default:
  290. /* Our option validation should have caught this. */
  291. tor_assert_unreached();
  292. }
  293. } SMARTLIST_FOREACH_END(type);
  294. end:
  295. if (new_scheduler == NULL) {
  296. log_err(LD_SCHED, "Tor was unable to select a scheduler type. Please "
  297. "make sure Schedulers is correctly configured with "
  298. "what Tor does support.");
  299. /* We weren't able to choose a scheduler which means that none of the ones
  300. * set in Schedulers are supported or usable. We will respect the user
  301. * wishes of using what it has been configured and don't do a sneaky
  302. * fallback. Because this can be changed at runtime, we have to stop tor
  303. * right now. */
  304. exit(1); // XXXX bad exit
  305. }
  306. /* Set the chosen scheduler. */
  307. the_scheduler = new_scheduler;
  308. }
  309. /**
  310. * Helper function called from a few different places. It changes the
  311. * scheduler implementation, if necessary. And if it did, it then tells the
  312. * old one to free its state and the new one to initialize.
  313. */
  314. static void
  315. set_scheduler(void)
  316. {
  317. const scheduler_t *old_scheduler = the_scheduler;
  318. scheduler_types_t old_scheduler_type = SCHEDULER_NONE;
  319. /* We keep track of the type in order to log only if the type switched. We
  320. * can't just use the scheduler pointers because KIST and KISTLite share the
  321. * same object. */
  322. if (the_scheduler) {
  323. old_scheduler_type = the_scheduler->type;
  324. }
  325. /* From the options, select the scheduler type to set. */
  326. select_scheduler();
  327. tor_assert(the_scheduler);
  328. /* We look at the pointer difference in case the old sched and new sched
  329. * share the same scheduler object, as is the case with KIST and KISTLite. */
  330. if (old_scheduler != the_scheduler) {
  331. /* Allow the old scheduler to clean up, if needed. */
  332. if (old_scheduler && old_scheduler->free_all) {
  333. old_scheduler->free_all();
  334. }
  335. /* Initialize the new scheduler. */
  336. if (the_scheduler->init) {
  337. the_scheduler->init();
  338. }
  339. }
  340. /* Finally we notice log if we switched schedulers. We use the type in case
  341. * two schedulers share a scheduler object. */
  342. if (old_scheduler_type != the_scheduler->type) {
  343. log_notice(LD_CONFIG, "Scheduler type %s has been enabled.",
  344. get_scheduler_type_string(the_scheduler->type));
  345. }
  346. }
  347. /*****************************************************************************
  348. * Scheduling system private function definitions
  349. *
  350. * Functions that can only be accessed from scheduler*.c
  351. *****************************************************************************/
  352. /** Helper that logs channel scheduler_state changes. Use this instead of
  353. * setting scheduler_state directly. */
  354. void scheduler_set_channel_state(channel_t *chan, int new_state){
  355. log_debug(LD_SCHED, "chan %" PRIu64 " changed from scheduler state %s to %s",
  356. chan->global_identifier,
  357. get_scheduler_state_string(chan->scheduler_state),
  358. get_scheduler_state_string(new_state));
  359. chan->scheduler_state = new_state;
  360. }
  361. /** Return the pending channel list. */
  362. smartlist_t *
  363. get_channels_pending(void)
  364. {
  365. return channels_pending;
  366. }
  367. /** Comparison function to use when sorting pending channels. */
  368. MOCK_IMPL(int,
  369. scheduler_compare_channels, (const void *c1_v, const void *c2_v))
  370. {
  371. const channel_t *c1 = NULL, *c2 = NULL;
  372. /* These are a workaround for -Wbad-function-cast throwing a fit */
  373. const circuitmux_policy_t *p1, *p2;
  374. uintptr_t p1_i, p2_i;
  375. tor_assert(c1_v);
  376. tor_assert(c2_v);
  377. c1 = (const channel_t *)(c1_v);
  378. c2 = (const channel_t *)(c2_v);
  379. if (c1 != c2) {
  380. if (circuitmux_get_policy(c1->cmux) ==
  381. circuitmux_get_policy(c2->cmux)) {
  382. /* Same cmux policy, so use the mux comparison */
  383. return circuitmux_compare_muxes(c1->cmux, c2->cmux);
  384. } else {
  385. /*
  386. * Different policies; not important to get this edge case perfect
  387. * because the current code never actually gives different channels
  388. * different cmux policies anyway. Just use this arbitrary but
  389. * definite choice.
  390. */
  391. p1 = circuitmux_get_policy(c1->cmux);
  392. p2 = circuitmux_get_policy(c2->cmux);
  393. p1_i = (uintptr_t)p1;
  394. p2_i = (uintptr_t)p2;
  395. return (p1_i < p2_i) ? -1 : 1;
  396. }
  397. } else {
  398. /* c1 == c2, so always equal */
  399. return 0;
  400. }
  401. }
  402. /*****************************************************************************
  403. * Scheduling system global functions
  404. *
  405. * Functions that can be accessed from anywhere in Tor.
  406. *****************************************************************************/
  407. /**
  408. * This is how the scheduling system is notified of Tor's configuration
  409. * changing. For example: a SIGHUP was issued.
  410. */
  411. void
  412. scheduler_conf_changed(void)
  413. {
  414. /* Let the scheduler decide what it should do. */
  415. set_scheduler();
  416. /* Then tell the (possibly new) scheduler that we have new options. */
  417. if (the_scheduler->on_new_options) {
  418. the_scheduler->on_new_options();
  419. }
  420. }
  421. /**
  422. * Whenever we get a new consensus, this function is called.
  423. */
  424. void
  425. scheduler_notify_networkstatus_changed(const networkstatus_t *old_c,
  426. const networkstatus_t *new_c)
  427. {
  428. /* Maybe the consensus param made us change the scheduler. */
  429. set_scheduler();
  430. /* Then tell the (possibly new) scheduler that we have a new consensus */
  431. if (the_scheduler->on_new_consensus) {
  432. the_scheduler->on_new_consensus(old_c, new_c);
  433. }
  434. }
  435. /**
  436. * Free everything scheduling-related from main.c. Note this is only called
  437. * when Tor is shutting down, while scheduler_t->free_all() is called both when
  438. * Tor is shutting down and when we are switching schedulers.
  439. */
  440. void
  441. scheduler_free_all(void)
  442. {
  443. log_debug(LD_SCHED, "Shutting down scheduler");
  444. if (run_sched_ev) {
  445. if (event_del(run_sched_ev) < 0) {
  446. log_warn(LD_BUG, "Problem deleting run_sched_ev");
  447. }
  448. tor_event_free(run_sched_ev);
  449. run_sched_ev = NULL;
  450. }
  451. if (channels_pending) {
  452. /* We don't have ownership of the objects in this list. */
  453. smartlist_free(channels_pending);
  454. channels_pending = NULL;
  455. }
  456. if (the_scheduler && the_scheduler->free_all) {
  457. the_scheduler->free_all();
  458. }
  459. the_scheduler = NULL;
  460. }
  461. /** Mark a channel as no longer ready to accept writes. */
  462. MOCK_IMPL(void,
  463. scheduler_channel_doesnt_want_writes,(channel_t *chan))
  464. {
  465. IF_BUG_ONCE(!chan) {
  466. return;
  467. }
  468. IF_BUG_ONCE(!channels_pending) {
  469. return;
  470. }
  471. /* If it's already in pending, we can put it in waiting_to_write */
  472. if (chan->scheduler_state == SCHED_CHAN_PENDING) {
  473. /*
  474. * It's in channels_pending, so it shouldn't be in any of
  475. * the other lists. It can't write any more, so it goes to
  476. * channels_waiting_to_write.
  477. */
  478. smartlist_pqueue_remove(channels_pending,
  479. scheduler_compare_channels,
  480. offsetof(channel_t, sched_heap_idx),
  481. chan);
  482. scheduler_set_channel_state(chan, SCHED_CHAN_WAITING_TO_WRITE);
  483. } else {
  484. /*
  485. * It's not in pending, so it can't become waiting_to_write; it's
  486. * either not in any of the lists (nothing to do) or it's already in
  487. * waiting_for_cells (remove it, can't write any more).
  488. */
  489. if (chan->scheduler_state == SCHED_CHAN_WAITING_FOR_CELLS) {
  490. scheduler_set_channel_state(chan, SCHED_CHAN_IDLE);
  491. }
  492. }
  493. }
  494. /** Mark a channel as having waiting cells. */
  495. MOCK_IMPL(void,
  496. scheduler_channel_has_waiting_cells,(channel_t *chan))
  497. {
  498. IF_BUG_ONCE(!chan) {
  499. return;
  500. }
  501. IF_BUG_ONCE(!channels_pending) {
  502. return;
  503. }
  504. /* First, check if it's also writeable */
  505. if (chan->scheduler_state == SCHED_CHAN_WAITING_FOR_CELLS) {
  506. /*
  507. * It's in channels_waiting_for_cells, so it shouldn't be in any of
  508. * the other lists. It has waiting cells now, so it goes to
  509. * channels_pending.
  510. */
  511. scheduler_set_channel_state(chan, SCHED_CHAN_PENDING);
  512. smartlist_pqueue_add(channels_pending,
  513. scheduler_compare_channels,
  514. offsetof(channel_t, sched_heap_idx),
  515. chan);
  516. /* If we made a channel pending, we potentially have scheduling work to
  517. * do. */
  518. the_scheduler->schedule();
  519. } else {
  520. /*
  521. * It's not in waiting_for_cells, so it can't become pending; it's
  522. * either not in any of the lists (we add it to waiting_to_write)
  523. * or it's already in waiting_to_write or pending (we do nothing)
  524. */
  525. if (!(chan->scheduler_state == SCHED_CHAN_WAITING_TO_WRITE ||
  526. chan->scheduler_state == SCHED_CHAN_PENDING)) {
  527. scheduler_set_channel_state(chan, SCHED_CHAN_WAITING_TO_WRITE);
  528. }
  529. }
  530. }
  531. /** Add the scheduler event to the set of pending events with next_run being
  532. * the longest time libevent should wait before triggering the event. */
  533. void
  534. scheduler_ev_add(const struct timeval *next_run)
  535. {
  536. tor_assert(run_sched_ev);
  537. tor_assert(next_run);
  538. if (BUG(event_add(run_sched_ev, next_run) < 0)) {
  539. log_warn(LD_SCHED, "Adding to libevent failed. Next run time was set to: "
  540. "%ld.%06ld", next_run->tv_sec, (long)next_run->tv_usec);
  541. return;
  542. }
  543. }
  544. /** Make the scheduler event active with the given flags. */
  545. void
  546. scheduler_ev_active(int flags)
  547. {
  548. tor_assert(run_sched_ev);
  549. event_active(run_sched_ev, flags, 1);
  550. }
  551. /*
  552. * Initialize everything scheduling-related from config.c. Note this is only
  553. * called when Tor is starting up, while scheduler_t->init() is called both
  554. * when Tor is starting up and when we are switching schedulers.
  555. */
  556. void
  557. scheduler_init(void)
  558. {
  559. log_debug(LD_SCHED, "Initting scheduler");
  560. // Two '!' because we really do want to check if the pointer is non-NULL
  561. IF_BUG_ONCE(!!run_sched_ev) {
  562. log_warn(LD_SCHED, "We should not already have a libevent scheduler event."
  563. "I'll clean the old one up, but this is odd.");
  564. tor_event_free(run_sched_ev);
  565. run_sched_ev = NULL;
  566. }
  567. run_sched_ev = tor_event_new(tor_libevent_get_base(), -1,
  568. 0, scheduler_evt_callback, NULL);
  569. channels_pending = smartlist_new();
  570. set_scheduler();
  571. }
  572. /*
  573. * If a channel is going away, this is how the scheduling system is informed
  574. * so it can do any freeing necessary. This ultimately calls
  575. * scheduler_t->on_channel_free() so the current scheduler can release any
  576. * state specific to this channel.
  577. */
  578. MOCK_IMPL(void,
  579. scheduler_release_channel,(channel_t *chan))
  580. {
  581. IF_BUG_ONCE(!chan) {
  582. return;
  583. }
  584. IF_BUG_ONCE(!channels_pending) {
  585. return;
  586. }
  587. if (chan->scheduler_state == SCHED_CHAN_PENDING) {
  588. if (SCHED_BUG(smartlist_pos(channels_pending, chan) == -1, chan)) {
  589. log_warn(LD_SCHED, "Scheduler asked to release channel %" PRIu64 " "
  590. "but it wasn't in channels_pending",
  591. chan->global_identifier);
  592. } else {
  593. smartlist_pqueue_remove(channels_pending,
  594. scheduler_compare_channels,
  595. offsetof(channel_t, sched_heap_idx),
  596. chan);
  597. }
  598. }
  599. if (the_scheduler->on_channel_free) {
  600. the_scheduler->on_channel_free(chan);
  601. }
  602. scheduler_set_channel_state(chan, SCHED_CHAN_IDLE);
  603. }
  604. /** Mark a channel as ready to accept writes */
  605. void
  606. scheduler_channel_wants_writes(channel_t *chan)
  607. {
  608. IF_BUG_ONCE(!chan) {
  609. return;
  610. }
  611. IF_BUG_ONCE(!channels_pending) {
  612. return;
  613. }
  614. /* If it's already in waiting_to_write, we can put it in pending */
  615. if (chan->scheduler_state == SCHED_CHAN_WAITING_TO_WRITE) {
  616. /*
  617. * It can write now, so it goes to channels_pending.
  618. */
  619. smartlist_pqueue_add(channels_pending,
  620. scheduler_compare_channels,
  621. offsetof(channel_t, sched_heap_idx),
  622. chan);
  623. scheduler_set_channel_state(chan, SCHED_CHAN_PENDING);
  624. /* We just made a channel pending, we have scheduling work to do. */
  625. the_scheduler->schedule();
  626. } else {
  627. /*
  628. * It's not in SCHED_CHAN_WAITING_TO_WRITE, so it can't become pending;
  629. * it's either idle and goes to WAITING_FOR_CELLS, or it's a no-op.
  630. */
  631. if (!(chan->scheduler_state == SCHED_CHAN_WAITING_FOR_CELLS ||
  632. chan->scheduler_state == SCHED_CHAN_PENDING)) {
  633. scheduler_set_channel_state(chan, SCHED_CHAN_WAITING_FOR_CELLS);
  634. }
  635. }
  636. }
  637. /* Log warn the given channel and extra scheduler context as well. This is
  638. * used by SCHED_BUG() in order to be able to extract as much information as
  639. * we can when we hit a bug. Channel chan can be NULL. */
  640. void
  641. scheduler_bug_occurred(const channel_t *chan)
  642. {
  643. char buf[128];
  644. if (chan != NULL) {
  645. const size_t outbuf_len =
  646. buf_datalen(TO_CONN(BASE_CHAN_TO_TLS((channel_t *) chan)->conn)->outbuf);
  647. tor_snprintf(buf, sizeof(buf),
  648. "Channel %" PRIu64 " in state %s and scheduler state %d."
  649. " Num cells on cmux: %d. Connection outbuf len: %lu.",
  650. chan->global_identifier,
  651. channel_state_to_string(chan->state),
  652. chan->scheduler_state, circuitmux_num_cells(chan->cmux),
  653. (unsigned long)outbuf_len);
  654. }
  655. {
  656. char *msg;
  657. /* Rate limit every 60 seconds. If we start seeing this every 60 sec, we
  658. * know something is stuck/wrong. It *should* be loud but not too much. */
  659. static ratelim_t rlimit = RATELIM_INIT(60);
  660. if ((msg = rate_limit_log(&rlimit, approx_time()))) {
  661. log_warn(LD_BUG, "%s Num pending channels: %d. "
  662. "Channel in pending list: %s.%s",
  663. (chan != NULL) ? buf : "No channel in bug context.",
  664. smartlist_len(channels_pending),
  665. (smartlist_pos(channels_pending, chan) == -1) ? "no" : "yes",
  666. msg);
  667. tor_free(msg);
  668. }
  669. }
  670. }
  671. #ifdef TOR_UNIT_TESTS
  672. /*
  673. * Notify scheduler that a channel's queue position may have changed.
  674. */
  675. void
  676. scheduler_touch_channel(channel_t *chan)
  677. {
  678. IF_BUG_ONCE(!chan) {
  679. return;
  680. }
  681. if (chan->scheduler_state == SCHED_CHAN_PENDING) {
  682. /* Remove and re-add it */
  683. smartlist_pqueue_remove(channels_pending,
  684. scheduler_compare_channels,
  685. offsetof(channel_t, sched_heap_idx),
  686. chan);
  687. smartlist_pqueue_add(channels_pending,
  688. scheduler_compare_channels,
  689. offsetof(channel_t, sched_heap_idx),
  690. chan);
  691. }
  692. /* else no-op, since it isn't in the queue */
  693. }
  694. #endif /* defined(TOR_UNIT_TESTS) */