Avoid crashing if we call num_usable_bridges() when bridges are not enabled
[tor/appveyor.git] / src / or / scheduler_kist.c
blobd1726ba3450a74f01cb78c11205410be838e4154
1 /* Copyright (c) 2017, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 #define SCHEDULER_KIST_PRIVATE
6 #include <event2/event.h>
8 #include "or.h"
9 #include "buffers.h"
10 #include "config.h"
11 #include "connection.h"
12 #include "networkstatus.h"
13 #define TOR_CHANNEL_INTERNAL_
14 #include "channel.h"
15 #include "channeltls.h"
16 #define SCHEDULER_PRIVATE_
17 #include "scheduler.h"
19 #define TLS_PER_CELL_OVERHEAD 29
21 #ifdef HAVE_KIST_SUPPORT
22 /* Kernel interface needed for KIST. */
23 #include <netinet/tcp.h>
24 #include <linux/sockios.h>
25 #endif /* HAVE_KIST_SUPPORT */
27 /*****************************************************************************
28 * Data structures and supporting functions
29 *****************************************************************************/
31 /* Socket_table hash table stuff. The socket_table keeps track of per-socket
32 * limit information imposed by kist and used by kist. */
34 static uint32_t
35 socket_table_ent_hash(const socket_table_ent_t *ent)
37 return (uint32_t)ent->chan->global_identifier;
40 static unsigned
41 socket_table_ent_eq(const socket_table_ent_t *a, const socket_table_ent_t *b)
43 return a->chan == b->chan;
46 typedef HT_HEAD(socket_table_s, socket_table_ent_s) socket_table_t;
48 static socket_table_t socket_table = HT_INITIALIZER();
50 HT_PROTOTYPE(socket_table_s, socket_table_ent_s, node, socket_table_ent_hash,
51 socket_table_ent_eq)
52 HT_GENERATE2(socket_table_s, socket_table_ent_s, node, socket_table_ent_hash,
53 socket_table_ent_eq, 0.6, tor_reallocarray, tor_free_)
55 /* outbuf_table hash table stuff. The outbuf_table keeps track of which
56 * channels have data sitting in their outbuf so the kist scheduler can force
57 * a write from outbuf to kernel periodically during a run and at the end of a
58 * run. */
60 typedef struct outbuf_table_ent_s {
61 HT_ENTRY(outbuf_table_ent_s) node;
62 channel_t *chan;
63 } outbuf_table_ent_t;
65 static uint32_t
66 outbuf_table_ent_hash(const outbuf_table_ent_t *ent)
68 return (uint32_t)ent->chan->global_identifier;
71 static unsigned
72 outbuf_table_ent_eq(const outbuf_table_ent_t *a, const outbuf_table_ent_t *b)
74 return a->chan->global_identifier == b->chan->global_identifier;
77 HT_PROTOTYPE(outbuf_table_s, outbuf_table_ent_s, node, outbuf_table_ent_hash,
78 outbuf_table_ent_eq)
79 HT_GENERATE2(outbuf_table_s, outbuf_table_ent_s, node, outbuf_table_ent_hash,
80 outbuf_table_ent_eq, 0.6, tor_reallocarray, tor_free_)
82 /*****************************************************************************
83 * Other internal data
84 *****************************************************************************/
86 /* Store the last time the scheduler was run so we can decide when to next run
87 * the scheduler based on it. */
88 static monotime_t scheduler_last_run;
89 /* This is a factor for the extra_space calculation in kist per-socket limits.
90 * It is the number of extra congestion windows we want to write to the kernel.
92 static double sock_buf_size_factor = 1.0;
93 /* How often the scheduler runs. */
94 STATIC int sched_run_interval = KIST_SCHED_RUN_INTERVAL_DEFAULT;
96 #ifdef HAVE_KIST_SUPPORT
97 /* Indicate if KIST lite mode is on or off. We can disable it at runtime.
98 * Important to have because of the KISTLite -> KIST possible transition. */
99 static unsigned int kist_lite_mode = 0;
100 /* Indicate if we don't have the kernel support. This can happen if the kernel
101 * changed and it doesn't recognized the values passed to the syscalls needed
102 * by KIST. In that case, fallback to the naive approach. */
103 static unsigned int kist_no_kernel_support = 0;
104 #else /* !(defined(HAVE_KIST_SUPPORT)) */
105 static unsigned int kist_lite_mode = 1;
106 #endif /* defined(HAVE_KIST_SUPPORT) */
108 /*****************************************************************************
109 * Internally called function implementations
110 *****************************************************************************/
112 /* Little helper function to get the length of a channel's output buffer */
113 static inline size_t
114 channel_outbuf_length(channel_t *chan)
116 /* In theory, this can not happen because we can not scheduler a channel
117 * without a connection that has its outbuf initialized. Just in case, bug
118 * on this so we can understand a bit more why it happened. */
119 if (SCHED_BUG(BASE_CHAN_TO_TLS(chan)->conn == NULL, chan)) {
120 return 0;
122 return buf_datalen(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn)->outbuf);
125 /* Little helper function for HT_FOREACH_FN. */
126 static int
127 each_channel_write_to_kernel(outbuf_table_ent_t *ent, void *data)
129 (void) data; /* Make compiler happy. */
130 channel_write_to_kernel(ent->chan);
131 return 0; /* Returning non-zero removes the element from the table. */
134 /* Free the given outbuf table entry ent. */
135 static int
136 free_outbuf_info_by_ent(outbuf_table_ent_t *ent, void *data)
138 (void) data; /* Make compiler happy. */
139 log_debug(LD_SCHED, "Freeing outbuf table entry from chan=%" PRIu64,
140 ent->chan->global_identifier);
141 tor_free(ent);
142 return 1; /* So HT_FOREACH_FN will remove the element */
145 /* Free the given socket table entry ent. */
146 static int
147 free_socket_info_by_ent(socket_table_ent_t *ent, void *data)
149 (void) data; /* Make compiler happy. */
150 log_debug(LD_SCHED, "Freeing socket table entry from chan=%" PRIu64,
151 ent->chan->global_identifier);
152 tor_free(ent);
153 return 1; /* So HT_FOREACH_FN will remove the element */
156 /* Clean up socket_table. Probably because the KIST sched impl is going away */
157 static void
158 free_all_socket_info(void)
160 HT_FOREACH_FN(socket_table_s, &socket_table, free_socket_info_by_ent, NULL);
161 HT_CLEAR(socket_table_s, &socket_table);
164 static socket_table_ent_t *
165 socket_table_search(socket_table_t *table, const channel_t *chan)
167 socket_table_ent_t search, *ent = NULL;
168 search.chan = chan;
169 ent = HT_FIND(socket_table_s, table, &search);
170 return ent;
173 /* Free a socket entry in table for the given chan. */
174 static void
175 free_socket_info_by_chan(socket_table_t *table, const channel_t *chan)
177 socket_table_ent_t *ent = NULL;
178 ent = socket_table_search(table, chan);
179 if (!ent)
180 return;
181 log_debug(LD_SCHED, "scheduler free socket info for chan=%" PRIu64,
182 chan->global_identifier);
183 HT_REMOVE(socket_table_s, table, ent);
184 free_socket_info_by_ent(ent, NULL);
187 /* Perform system calls for the given socket in order to calculate kist's
188 * per-socket limit as documented in the function body. */
189 MOCK_IMPL(void,
190 update_socket_info_impl, (socket_table_ent_t *ent))
192 #ifdef HAVE_KIST_SUPPORT
193 int64_t tcp_space, extra_space;
194 const tor_socket_t sock =
195 TO_CONN(BASE_CHAN_TO_TLS((channel_t *) ent->chan)->conn)->s;
196 struct tcp_info tcp;
197 socklen_t tcp_info_len = sizeof(tcp);
199 if (kist_no_kernel_support || kist_lite_mode) {
200 goto fallback;
203 /* Gather information */
204 if (getsockopt(sock, SOL_TCP, TCP_INFO, (void *)&(tcp), &tcp_info_len) < 0) {
205 if (errno == EINVAL) {
206 /* Oops, this option is not provided by the kernel, we'll have to
207 * disable KIST entirely. This can happen if tor was built on a machine
208 * with the support previously or if the kernel was updated and lost the
209 * support. */
210 log_notice(LD_SCHED, "Looks like our kernel doesn't have the support "
211 "for KIST anymore. We will fallback to the naive "
212 "approach. Remove KIST from the Schedulers list "
213 "to disable.");
214 kist_no_kernel_support = 1;
216 goto fallback;
218 if (ioctl(sock, SIOCOUTQNSD, &(ent->notsent)) < 0) {
219 if (errno == EINVAL) {
220 log_notice(LD_SCHED, "Looks like our kernel doesn't have the support "
221 "for KIST anymore. We will fallback to the naive "
222 "approach. Remove KIST from the Schedulers list "
223 "to disable.");
224 /* Same reason as the above. */
225 kist_no_kernel_support = 1;
227 goto fallback;
229 ent->cwnd = tcp.tcpi_snd_cwnd;
230 ent->unacked = tcp.tcpi_unacked;
231 ent->mss = tcp.tcpi_snd_mss;
233 /* In order to reduce outbound kernel queuing delays and thus improve Tor's
234 * ability to prioritize circuits, KIST wants to set a socket write limit
235 * that is near the amount that the socket would be able to immediately send
236 * into the Internet.
238 * We first calculate how much the socket could send immediately (assuming
239 * completely full packets) according to the congestion window and the number
240 * of unacked packets.
242 * Then we add a little extra space in a controlled way. We do this so any
243 * when the kernel gets ACKs back for data currently sitting in the "TCP
244 * space", it will already have some more data to send immediately. It will
245 * not have to wait for the scheduler to run again. The amount of extra space
246 * is a factor of the current congestion window. With the suggested
247 * sock_buf_size_factor value of 1.0, we allow at most 2*cwnd bytes to sit in
248 * the kernel: 1 cwnd on the wire waiting for ACKs and 1 cwnd ready and
249 * waiting to be sent when those ACKs finally come.
251 * In the below diagram, we see some bytes in the TCP-space (denoted by '*')
252 * that have be sent onto the wire and are waiting for ACKs. We have a little
253 * more room in "TCP space" that we can fill with data that will be
254 * immediately sent. We also see the "extra space" KIST calculates. The sum
255 * of the empty "TCP space" and the "extra space" is the kist-imposed write
256 * limit for this socket.
258 * <----------------kernel-outbound-socket-queue----------------|
259 * <*********---------------------------------------------------|
260 * |----TCP-space-----|----extra-space-----|
261 * |------------------|
262 * ^ ((cwnd - unacked) * mss) bytes
263 * |--------------------|
264 * ^ ((cwnd * mss) * factor) bytes
267 /* Assuming all these values from the kernel are uint32_t still, they will
268 * always fit into a int64_t tcp_space variable. */
269 tcp_space = (ent->cwnd - ent->unacked) * (int64_t)ent->mss;
270 if (tcp_space < 0) {
271 tcp_space = 0;
274 /* The clamp_double_to_int64 makes sure the first part fits into an int64_t.
275 * In fact, if sock_buf_size_factor is still forced to be >= 0 in config.c,
276 * then it will be positive for sure. Then we subtract a uint32_t. At worst
277 * we end up negative, but then we just set extra_space to 0 in the sanity
278 * check.*/
279 extra_space =
280 clamp_double_to_int64(
281 (ent->cwnd * (int64_t)ent->mss) * sock_buf_size_factor) -
282 ent->notsent;
283 if (extra_space < 0) {
284 extra_space = 0;
287 /* Finally we set the limit. Adding two positive int64_t together will always
288 * fit in an uint64_t. */
289 ent->limit = (uint64_t)tcp_space + (uint64_t)extra_space;
290 return;
292 #else /* !(defined(HAVE_KIST_SUPPORT)) */
293 goto fallback;
294 #endif /* defined(HAVE_KIST_SUPPORT) */
296 fallback:
297 /* If all of a sudden we don't have kist support, we just zero out all the
298 * variables for this socket since we don't know what they should be.
299 * We also effectively allow the socket write as much as it wants to the
300 * kernel, effectively returning it to vanilla scheduler behavior. Writes
301 * are still limited by the lower layers of Tor: socket blocking, full
302 * outbuf, etc. */
303 ent->cwnd = ent->unacked = ent->mss = ent->notsent = 0;
304 ent->limit = INT_MAX;
307 /* Given a socket that isn't in the table, add it.
308 * Given a socket that is in the table, re-init values that need init-ing
309 * every scheduling run
311 static void
312 init_socket_info(socket_table_t *table, const channel_t *chan)
314 socket_table_ent_t *ent = NULL;
315 ent = socket_table_search(table, chan);
316 if (!ent) {
317 log_debug(LD_SCHED, "scheduler init socket info for chan=%" PRIu64,
318 chan->global_identifier);
319 ent = tor_malloc_zero(sizeof(*ent));
320 ent->chan = chan;
321 HT_INSERT(socket_table_s, table, ent);
323 ent->written = 0;
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)
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);
343 static void
344 outbuf_table_remove(outbuf_table_t *table, channel_t *chan)
346 outbuf_table_ent_t search, *ent;
347 search.chan = chan;
348 ent = HT_FIND(outbuf_table_s, table, &search);
349 if (ent) {
350 HT_REMOVE(outbuf_table_s, table, ent);
351 free_outbuf_info_by_ent(ent, NULL);
355 /* Set the scheduler running interval. */
356 static void
357 set_scheduler_run_interval(const networkstatus_t *ns)
359 int old_sched_run_interval = sched_run_interval;
360 sched_run_interval = kist_scheduler_run_interval(ns);
361 if (old_sched_run_interval != sched_run_interval) {
362 log_info(LD_SCHED, "Scheduler KIST changing its running interval "
363 "from %" PRId32 " to %" PRId32,
364 old_sched_run_interval, sched_run_interval);
368 /* Return true iff the channel hasn’t hit its kist-imposed write limit yet */
369 static int
370 socket_can_write(socket_table_t *table, const channel_t *chan)
372 socket_table_ent_t *ent = NULL;
373 ent = socket_table_search(table, chan);
374 if (SCHED_BUG(!ent, chan)) {
375 return 1; // Just return true, saying that kist wouldn't limit the socket
378 /* We previously calculated a write limit for this socket. In the below
379 * calculation, first determine how much room is left in bytes. Then divide
380 * that by the amount of space a cell takes. If there's room for at least 1
381 * cell, then KIST will allow the socket to write. */
382 int64_t kist_limit_space =
383 (int64_t) (ent->limit - ent->written) /
384 (CELL_MAX_NETWORK_SIZE + TLS_PER_CELL_OVERHEAD);
385 return kist_limit_space > 0;
388 /* Update the channel's socket kernel information. */
389 static void
390 update_socket_info(socket_table_t *table, const channel_t *chan)
392 socket_table_ent_t *ent = NULL;
393 ent = socket_table_search(table, chan);
394 if (SCHED_BUG(!ent, chan)) {
395 return; // Whelp. Entry didn't exist for some reason so nothing to do.
397 update_socket_info_impl(ent);
400 /* Increment the channel's socket written value by the number of bytes. */
401 static void
402 update_socket_written(socket_table_t *table, channel_t *chan, size_t bytes)
404 socket_table_ent_t *ent = NULL;
405 ent = socket_table_search(table, chan);
406 if (SCHED_BUG(!ent, chan)) {
407 return; // Whelp. Entry didn't exist so nothing to do.
410 log_debug(LD_SCHED, "chan=%" PRIu64 " wrote %lu bytes, old was %" PRIi64,
411 chan->global_identifier, (unsigned long) bytes, ent->written);
413 ent->written += bytes;
417 * A naive KIST impl would write every single cell all the way to the kernel.
418 * That would take a lot of system calls. A less bad KIST impl would write a
419 * channel's outbuf to the kernel only when we are switching to a different
420 * channel. But if we have two channels with equal priority, we end up writing
421 * one cell for each and bouncing back and forth. This KIST impl avoids that
422 * by only writing a channel's outbuf to the kernel if it has 8 cells or more
423 * in it.
425 MOCK_IMPL(int, channel_should_write_to_kernel,
426 (outbuf_table_t *table, channel_t *chan))
428 outbuf_table_add(table, chan);
429 /* CELL_MAX_NETWORK_SIZE * 8 because we only want to write the outbuf to the
430 * kernel if there's 8 or more cells waiting */
431 return channel_outbuf_length(chan) > (CELL_MAX_NETWORK_SIZE * 8);
434 /* Little helper function to write a channel's outbuf all the way to the
435 * kernel */
436 MOCK_IMPL(void, channel_write_to_kernel, (channel_t *chan))
438 log_debug(LD_SCHED, "Writing %lu bytes to kernel for chan %" PRIu64,
439 (unsigned long)channel_outbuf_length(chan),
440 chan->global_identifier);
441 connection_handle_write(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn), 0);
444 /* Return true iff the scheduler has work to perform. */
445 static int
446 have_work(void)
448 smartlist_t *cp = get_channels_pending();
449 IF_BUG_ONCE(!cp) {
450 return 0; // channels_pending doesn't exist so... no work?
452 return smartlist_len(cp) > 0;
455 /* Function of the scheduler interface: free_all() */
456 static void
457 kist_free_all(void)
459 free_all_socket_info();
462 /* Function of the scheduler interface: on_channel_free() */
463 static void
464 kist_on_channel_free(const channel_t *chan)
466 free_socket_info_by_chan(&socket_table, chan);
469 /* Function of the scheduler interface: on_new_consensus() */
470 static void
471 kist_scheduler_on_new_consensus(const networkstatus_t *old_c,
472 const networkstatus_t *new_c)
474 (void) old_c;
475 (void) new_c;
477 set_scheduler_run_interval(new_c);
480 /* Function of the scheduler interface: on_new_options() */
481 static void
482 kist_scheduler_on_new_options(void)
484 sock_buf_size_factor = get_options()->KISTSockBufSizeFactor;
486 /* Calls kist_scheduler_run_interval which calls get_options(). */
487 set_scheduler_run_interval(NULL);
490 /* Function of the scheduler interface: init() */
491 static void
492 kist_scheduler_init(void)
494 /* When initializing the scheduler, the last run could be 0 because it is
495 * declared static or a value in the past that was set when it was last
496 * used. In both cases, we want to initialize it to now so we don't risk
497 * using the value 0 which doesn't play well with our monotonic time
498 * interface.
500 * One side effect is that the first scheduler run will be at the next tick
501 * that is in now + 10 msec (KIST_SCHED_RUN_INTERVAL_DEFAULT) by default. */
502 monotime_get(&scheduler_last_run);
504 kist_scheduler_on_new_options();
505 IF_BUG_ONCE(sched_run_interval == 0) {
506 log_warn(LD_SCHED, "We are initing the KIST scheduler and noticed the "
507 "KISTSchedRunInterval is telling us to not use KIST. That's "
508 "weird! We'll continue using KIST, but at %" PRId32 "ms.",
509 KIST_SCHED_RUN_INTERVAL_DEFAULT);
510 sched_run_interval = KIST_SCHED_RUN_INTERVAL_DEFAULT;
514 /* Function of the scheduler interface: schedule() */
515 static void
516 kist_scheduler_schedule(void)
518 struct monotime_t now;
519 struct timeval next_run;
520 int64_t diff;
522 if (!have_work()) {
523 return;
525 monotime_get(&now);
527 /* If time is really monotonic, we can never have now being smaller than the
528 * last scheduler run. The scheduler_last_run at first is set to 0. */
529 diff = monotime_diff_msec(&scheduler_last_run, &now);
530 IF_BUG_ONCE(diff < 0) {
531 diff = 0;
533 if (diff < sched_run_interval) {
534 next_run.tv_sec = 0;
535 /* Takes 1000 ms -> us. This will always be valid because diff can NOT be
536 * negative and can NOT be bigger than sched_run_interval so values can
537 * only go from 1000 usec (diff set to interval - 1) to 100000 usec (diff
538 * set to 0) for the maximum allowed run interval (100ms). */
539 next_run.tv_usec = (int) ((sched_run_interval - diff) * 1000);
540 /* Re-adding an event reschedules it. It does not duplicate it. */
541 scheduler_ev_add(&next_run);
542 } else {
543 scheduler_ev_active(EV_TIMEOUT);
547 /* Function of the scheduler interface: run() */
548 static void
549 kist_scheduler_run(void)
551 /* Define variables */
552 channel_t *chan = NULL; // current working channel
553 /* The last distinct chan served in a sched loop. */
554 channel_t *prev_chan = NULL;
555 int flush_result; // temporarily store results from flush calls
556 /* Channels to be re-adding to pending at the end */
557 smartlist_t *to_readd = NULL;
558 smartlist_t *cp = get_channels_pending();
560 outbuf_table_t outbuf_table = HT_INITIALIZER();
562 /* For each pending channel, collect new kernel information */
563 SMARTLIST_FOREACH_BEGIN(cp, const channel_t *, pchan) {
564 init_socket_info(&socket_table, pchan);
565 update_socket_info(&socket_table, pchan);
566 } SMARTLIST_FOREACH_END(pchan);
568 log_debug(LD_SCHED, "Running the scheduler. %d channels pending",
569 smartlist_len(cp));
571 /* The main scheduling loop. Loop until there are no more pending channels */
572 while (smartlist_len(cp) > 0) {
573 /* get best channel */
574 chan = smartlist_pqueue_pop(cp, scheduler_compare_channels,
575 offsetof(channel_t, sched_heap_idx));
576 if (SCHED_BUG(!chan, NULL)) {
577 /* Some-freaking-how a NULL got into the channels_pending. That should
578 * never happen, but it should be harmless to ignore it and keep looping.
580 continue;
582 outbuf_table_add(&outbuf_table, chan);
584 /* if we have switched to a new channel, consider writing the previous
585 * channel's outbuf to the kernel. */
586 if (!prev_chan) {
587 prev_chan = chan;
589 if (prev_chan != chan) {
590 if (channel_should_write_to_kernel(&outbuf_table, prev_chan)) {
591 channel_write_to_kernel(prev_chan);
592 outbuf_table_remove(&outbuf_table, prev_chan);
594 prev_chan = chan;
597 /* Only flush and write if the per-socket limit hasn't been hit */
598 if (socket_can_write(&socket_table, chan)) {
599 /* flush to channel queue/outbuf */
600 flush_result = (int)channel_flush_some_cells(chan, 1); // 1 for num cells
601 /* XXX: While flushing cells, it is possible that the connection write
602 * fails leading to the channel to be closed which triggers a release
603 * and free its entry in the socket table. And because of a engineering
604 * design issue, the error is not propagated back so we don't get an
605 * error at this poin. So before we continue, make sure the channel is
606 * open and if not just ignore it. See #23751. */
607 if (!CHANNEL_IS_OPEN(chan)) {
608 continue;
610 /* flush_result has the # cells flushed */
611 if (flush_result > 0) {
612 update_socket_written(&socket_table, chan, flush_result *
613 (CELL_MAX_NETWORK_SIZE + TLS_PER_CELL_OVERHEAD));
614 } else {
615 /* XXX: This can happen because tor sometimes does flush in an
616 * opportunistic way cells from the circuit to the outbuf so the
617 * channel can end up here without having anything to flush nor needed
618 * to write to the kernel. Hopefully we'll fix that soon but for now
619 * we have to handle this case which happens kind of often. */
620 log_debug(LD_SCHED,
621 "We didn't flush anything on a chan that we think "
622 "can write and wants to write. The channel's state is '%s' "
623 "and in scheduler state %d. We're going to mark it as "
624 "waiting_for_cells (as that's most likely the issue) and "
625 "stop scheduling it this round.",
626 channel_state_to_string(chan->state),
627 chan->scheduler_state);
628 chan->scheduler_state = SCHED_CHAN_WAITING_FOR_CELLS;
629 continue;
633 /* Decide what to do with the channel now */
635 if (!channel_more_to_flush(chan) &&
636 !socket_can_write(&socket_table, chan)) {
638 /* Case 1: no more cells to send, and cannot write */
641 * You might think we should put the channel in SCHED_CHAN_IDLE. And
642 * you're probably correct. While implementing KIST, we found that the
643 * scheduling system would sometimes lose track of channels when we did
644 * that. We suspect it has to do with the difference between "can't
645 * write because socket/outbuf is full" and KIST's "can't write because
646 * we've arbitrarily decided that that's enough for now." Sometimes
647 * channels run out of cells at the same time they hit their
648 * kist-imposed write limit and maybe the rest of Tor doesn't put the
649 * channel back in pending when it is supposed to.
651 * This should be investigated again. It is as simple as changing
652 * SCHED_CHAN_WAITING_FOR_CELLS to SCHED_CHAN_IDLE and seeing if Tor
653 * starts having serious throughput issues. Best done in shadow/chutney.
655 chan->scheduler_state = SCHED_CHAN_WAITING_FOR_CELLS;
656 log_debug(LD_SCHED, "chan=%" PRIu64 " now waiting_for_cells",
657 chan->global_identifier);
658 } else if (!channel_more_to_flush(chan)) {
660 /* Case 2: no more cells to send, but still open for writes */
662 chan->scheduler_state = SCHED_CHAN_WAITING_FOR_CELLS;
663 log_debug(LD_SCHED, "chan=%" PRIu64 " now waiting_for_cells",
664 chan->global_identifier);
665 } else if (!socket_can_write(&socket_table, chan)) {
667 /* Case 3: cells to send, but cannot write */
670 * We want to write, but can't. If we left the channel in
671 * channels_pending, we would never exit the scheduling loop. We need to
672 * add it to a temporary list of channels to be added to channels_pending
673 * after the scheduling loop is over. They can hopefully be taken care of
674 * in the next scheduling round.
676 chan->scheduler_state = SCHED_CHAN_WAITING_TO_WRITE;
677 if (!to_readd) {
678 to_readd = smartlist_new();
680 smartlist_add(to_readd, chan);
681 log_debug(LD_SCHED, "chan=%" PRIu64 " now waiting_to_write",
682 chan->global_identifier);
683 } else {
685 /* Case 4: cells to send, and still open for writes */
687 chan->scheduler_state = SCHED_CHAN_PENDING;
688 smartlist_pqueue_add(cp, scheduler_compare_channels,
689 offsetof(channel_t, sched_heap_idx), chan);
691 } /* End of main scheduling loop */
693 /* Write the outbuf of any channels that still have data */
694 HT_FOREACH_FN(outbuf_table_s, &outbuf_table, each_channel_write_to_kernel,
695 NULL);
696 /* We are done with it. */
697 HT_FOREACH_FN(outbuf_table_s, &outbuf_table, free_outbuf_info_by_ent, NULL);
698 HT_CLEAR(outbuf_table_s, &outbuf_table);
700 log_debug(LD_SCHED, "len pending=%d, len to_readd=%d",
701 smartlist_len(cp),
702 (to_readd ? smartlist_len(to_readd) : -1));
704 /* Re-add any channels we need to */
705 if (to_readd) {
706 SMARTLIST_FOREACH_BEGIN(to_readd, channel_t *, readd_chan) {
707 readd_chan->scheduler_state = SCHED_CHAN_PENDING;
708 if (!smartlist_contains(cp, readd_chan)) {
709 smartlist_pqueue_add(cp, scheduler_compare_channels,
710 offsetof(channel_t, sched_heap_idx), readd_chan);
712 } SMARTLIST_FOREACH_END(readd_chan);
713 smartlist_free(to_readd);
716 monotime_get(&scheduler_last_run);
719 /*****************************************************************************
720 * Externally called function implementations not called through scheduler_t
721 *****************************************************************************/
723 /* Stores the kist scheduler function pointers. */
724 static scheduler_t kist_scheduler = {
725 .type = SCHEDULER_KIST,
726 .free_all = kist_free_all,
727 .on_channel_free = kist_on_channel_free,
728 .init = kist_scheduler_init,
729 .on_new_consensus = kist_scheduler_on_new_consensus,
730 .schedule = kist_scheduler_schedule,
731 .run = kist_scheduler_run,
732 .on_new_options = kist_scheduler_on_new_options,
735 /* Return the KIST scheduler object. If it didn't exists, return a newly
736 * allocated one but init() is not called. */
737 scheduler_t *
738 get_kist_scheduler(void)
740 return &kist_scheduler;
743 /* Check the torrc (and maybe consensus) for the configured KIST scheduler run
744 * interval.
745 * - If torrc > 0, then return the positive torrc value (should use KIST, and
746 * should use the set value)
747 * - If torrc == 0, then look in the consensus for what the value should be.
748 * - If == 0, then return 0 (don't use KIST)
749 * - If > 0, then return the positive consensus value
750 * - If consensus doesn't say anything, return 10 milliseconds, default.
753 kist_scheduler_run_interval(const networkstatus_t *ns)
755 int run_interval = get_options()->KISTSchedRunInterval;
757 if (run_interval != 0) {
758 log_debug(LD_SCHED, "Found KISTSchedRunInterval=%" PRId32 " in torrc. "
759 "Using that.", run_interval);
760 return run_interval;
763 log_debug(LD_SCHED, "KISTSchedRunInterval=0, turning to the consensus.");
765 /* Will either be the consensus value or the default. Note that 0 can be
766 * returned which means the consensus wants us to NOT use KIST. */
767 return networkstatus_get_param(ns, "KISTSchedRunInterval",
768 KIST_SCHED_RUN_INTERVAL_DEFAULT,
769 KIST_SCHED_RUN_INTERVAL_MIN,
770 KIST_SCHED_RUN_INTERVAL_MAX);
773 /* Set KISTLite mode that is KIST without kernel support. */
774 void
775 scheduler_kist_set_lite_mode(void)
777 kist_lite_mode = 1;
778 kist_scheduler.type = SCHEDULER_KIST_LITE;
779 log_info(LD_SCHED,
780 "Setting KIST scheduler without kernel support (KISTLite mode)");
783 /* Set KIST mode that is KIST with kernel support. */
784 void
785 scheduler_kist_set_full_mode(void)
787 kist_lite_mode = 0;
788 kist_scheduler.type = SCHEDULER_KIST;
789 log_info(LD_SCHED,
790 "Setting KIST scheduler with kernel support (KIST mode)");
793 #ifdef HAVE_KIST_SUPPORT
795 /* Return true iff the scheduler subsystem should use KIST. */
797 scheduler_can_use_kist(void)
799 if (kist_no_kernel_support) {
800 /* We have no kernel support so we can't use KIST. */
801 return 0;
804 /* We do have the support, time to check if we can get the interval that the
805 * consensus can be disabling. */
806 int run_interval = kist_scheduler_run_interval(NULL);
807 log_debug(LD_SCHED, "Determined KIST sched_run_interval should be "
808 "%" PRId32 ". Can%s use KIST.",
809 run_interval, (run_interval > 0 ? "" : " not"));
810 return run_interval > 0;
813 #else /* !(defined(HAVE_KIST_SUPPORT)) */
816 scheduler_can_use_kist(void)
818 return 0;
821 #endif /* defined(HAVE_KIST_SUPPORT) */