more fixes for typos, grammar, whitespace, etc
[tor.git] / src / or / scheduler_kist.c
blob6d6490077d9d5fb7e71c3d6ad516cb6c0740d3c3
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 /* These values from the kernel are uint32_t, they will always fit into a
268 * int64_t tcp_space variable but if the congestion window cwnd is smaller
269 * than the unacked packets, the remaining TCP space is set to 0. */
270 if (ent->cwnd >= ent->unacked) {
271 tcp_space = (ent->cwnd - ent->unacked) * (int64_t)(ent->mss);
272 } else {
273 tcp_space = 0;
276 /* The clamp_double_to_int64 makes sure the first part fits into an int64_t.
277 * In fact, if sock_buf_size_factor is still forced to be >= 0 in config.c,
278 * then it will be positive for sure. Then we subtract a uint32_t. Getting a
279 * negative value is OK, see after how it is being handled. */
280 extra_space =
281 clamp_double_to_int64(
282 (ent->cwnd * (int64_t)ent->mss) * sock_buf_size_factor) -
283 ent->notsent;
284 if ((tcp_space + extra_space) < 0) {
285 /* This means that the "notsent" queue is just too big so we shouldn't put
286 * more in the kernel for now. */
287 ent->limit = 0;
288 } else {
289 /* The positive sum of two int64_t will always fit into an uint64_t.
290 * And we know this will always be positive, since we checked above. */
291 ent->limit = (uint64_t)tcp_space + (uint64_t)extra_space;
293 return;
295 #else /* !(defined(HAVE_KIST_SUPPORT)) */
296 goto fallback;
297 #endif /* defined(HAVE_KIST_SUPPORT) */
299 fallback:
300 /* If all of a sudden we don't have kist support, we just zero out all the
301 * variables for this socket since we don't know what they should be. We
302 * also allow the socket to write as much as it can from the estimated
303 * number of cells the lower layer can accept, effectively returning it to
304 * Vanilla scheduler behavior. */
305 ent->cwnd = ent->unacked = ent->mss = ent->notsent = 0;
306 /* This function calls the specialized channel object (currently channeltls)
307 * and ask how many cells it can write on the outbuf which we then multiply
308 * by the size of the cells for this channel. The cast is because this
309 * function requires a non-const channel object, meh. */
310 ent->limit = channel_num_cells_writeable((channel_t *) ent->chan) *
311 (get_cell_network_size(ent->chan->wide_circ_ids) +
312 TLS_PER_CELL_OVERHEAD);
315 /* Given a socket that isn't in the table, add it.
316 * Given a socket that is in the table, re-init values that need init-ing
317 * every scheduling run
319 static void
320 init_socket_info(socket_table_t *table, const channel_t *chan)
322 socket_table_ent_t *ent = NULL;
323 ent = socket_table_search(table, chan);
324 if (!ent) {
325 log_debug(LD_SCHED, "scheduler init socket info for chan=%" PRIu64,
326 chan->global_identifier);
327 ent = tor_malloc_zero(sizeof(*ent));
328 ent->chan = chan;
329 HT_INSERT(socket_table_s, table, ent);
331 ent->written = 0;
334 /* Add chan to the outbuf table if it isn't already in it. If it is, then don't
335 * do anything */
336 static void
337 outbuf_table_add(outbuf_table_t *table, channel_t *chan)
339 outbuf_table_ent_t search, *ent;
340 search.chan = chan;
341 ent = HT_FIND(outbuf_table_s, table, &search);
342 if (!ent) {
343 log_debug(LD_SCHED, "scheduler init outbuf info for chan=%" PRIu64,
344 chan->global_identifier);
345 ent = tor_malloc_zero(sizeof(*ent));
346 ent->chan = chan;
347 HT_INSERT(outbuf_table_s, table, ent);
351 static void
352 outbuf_table_remove(outbuf_table_t *table, channel_t *chan)
354 outbuf_table_ent_t search, *ent;
355 search.chan = chan;
356 ent = HT_FIND(outbuf_table_s, table, &search);
357 if (ent) {
358 HT_REMOVE(outbuf_table_s, table, ent);
359 free_outbuf_info_by_ent(ent, NULL);
363 /* Set the scheduler running interval. */
364 static void
365 set_scheduler_run_interval(void)
367 int old_sched_run_interval = sched_run_interval;
368 sched_run_interval = kist_scheduler_run_interval();
369 if (old_sched_run_interval != sched_run_interval) {
370 log_info(LD_SCHED, "Scheduler KIST changing its running interval "
371 "from %" PRId32 " to %" PRId32,
372 old_sched_run_interval, sched_run_interval);
376 /* Return true iff the channel hasn't hit its kist-imposed write limit yet */
377 static int
378 socket_can_write(socket_table_t *table, const channel_t *chan)
380 socket_table_ent_t *ent = NULL;
381 ent = socket_table_search(table, chan);
382 if (SCHED_BUG(!ent, chan)) {
383 return 1; // Just return true, saying that kist wouldn't limit the socket
386 /* We previously calculated a write limit for this socket. In the below
387 * calculation, first determine how much room is left in bytes. Then divide
388 * that by the amount of space a cell takes. If there's room for at least 1
389 * cell, then KIST will allow the socket to write. */
390 int64_t kist_limit_space =
391 (int64_t) (ent->limit - ent->written) /
392 (CELL_MAX_NETWORK_SIZE + TLS_PER_CELL_OVERHEAD);
393 return kist_limit_space > 0;
396 /* Update the channel's socket kernel information. */
397 static void
398 update_socket_info(socket_table_t *table, const channel_t *chan)
400 socket_table_ent_t *ent = NULL;
401 ent = socket_table_search(table, chan);
402 if (SCHED_BUG(!ent, chan)) {
403 return; // Whelp. Entry didn't exist for some reason so nothing to do.
405 update_socket_info_impl(ent);
406 log_debug(LD_SCHED, "chan=%" PRIu64 " updated socket info, limit: %" PRIu64
407 ", cwnd: %" PRIu32 ", unacked: %" PRIu32
408 ", notsent: %" PRIu32 ", mss: %" PRIu32,
409 ent->chan->global_identifier, ent->limit, ent->cwnd, ent->unacked,
410 ent->notsent, ent->mss);
413 /* Increment the channel's socket written value by the number of bytes. */
414 static void
415 update_socket_written(socket_table_t *table, channel_t *chan, size_t bytes)
417 socket_table_ent_t *ent = NULL;
418 ent = socket_table_search(table, chan);
419 if (SCHED_BUG(!ent, chan)) {
420 return; // Whelp. Entry didn't exist so nothing to do.
423 log_debug(LD_SCHED, "chan=%" PRIu64 " wrote %lu bytes, old was %" PRIi64,
424 chan->global_identifier, (unsigned long) bytes, ent->written);
426 ent->written += bytes;
430 * A naive KIST impl would write every single cell all the way to the kernel.
431 * That would take a lot of system calls. A less bad KIST impl would write a
432 * channel's outbuf to the kernel only when we are switching to a different
433 * channel. But if we have two channels with equal priority, we end up writing
434 * one cell for each and bouncing back and forth. This KIST impl avoids that
435 * by only writing a channel's outbuf to the kernel if it has 8 cells or more
436 * in it.
438 MOCK_IMPL(int, channel_should_write_to_kernel,
439 (outbuf_table_t *table, channel_t *chan))
441 outbuf_table_add(table, chan);
442 /* CELL_MAX_NETWORK_SIZE * 8 because we only want to write the outbuf to the
443 * kernel if there's 8 or more cells waiting */
444 return channel_outbuf_length(chan) > (CELL_MAX_NETWORK_SIZE * 8);
447 /* Little helper function to write a channel's outbuf all the way to the
448 * kernel */
449 MOCK_IMPL(void, channel_write_to_kernel, (channel_t *chan))
451 log_debug(LD_SCHED, "Writing %lu bytes to kernel for chan %" PRIu64,
452 (unsigned long)channel_outbuf_length(chan),
453 chan->global_identifier);
454 connection_handle_write(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn), 0);
457 /* Return true iff the scheduler has work to perform. */
458 static int
459 have_work(void)
461 smartlist_t *cp = get_channels_pending();
462 IF_BUG_ONCE(!cp) {
463 return 0; // channels_pending doesn't exist so... no work?
465 return smartlist_len(cp) > 0;
468 /* Function of the scheduler interface: free_all() */
469 static void
470 kist_free_all(void)
472 free_all_socket_info();
475 /* Function of the scheduler interface: on_channel_free() */
476 static void
477 kist_on_channel_free_fn(const channel_t *chan)
479 free_socket_info_by_chan(&socket_table, chan);
482 /* Function of the scheduler interface: on_new_consensus() */
483 static void
484 kist_scheduler_on_new_consensus(void)
486 set_scheduler_run_interval();
489 /* Function of the scheduler interface: on_new_options() */
490 static void
491 kist_scheduler_on_new_options(void)
493 sock_buf_size_factor = get_options()->KISTSockBufSizeFactor;
495 /* Calls kist_scheduler_run_interval which calls get_options(). */
496 set_scheduler_run_interval();
499 /* Function of the scheduler interface: init() */
500 static void
501 kist_scheduler_init(void)
503 /* When initializing the scheduler, the last run could be 0 because it is
504 * declared static or a value in the past that was set when it was last
505 * used. In both cases, we want to initialize it to now so we don't risk
506 * using the value 0 which doesn't play well with our monotonic time
507 * interface.
509 * One side effect is that the first scheduler run will be at the next tick
510 * that is in now + 10 msec (KIST_SCHED_RUN_INTERVAL_DEFAULT) by default. */
511 monotime_get(&scheduler_last_run);
513 kist_scheduler_on_new_options();
514 IF_BUG_ONCE(sched_run_interval == 0) {
515 log_warn(LD_SCHED, "We are initing the KIST scheduler and noticed the "
516 "KISTSchedRunInterval is telling us to not use KIST. That's "
517 "weird! We'll continue using KIST, but at %" PRId32 "ms.",
518 KIST_SCHED_RUN_INTERVAL_DEFAULT);
519 sched_run_interval = KIST_SCHED_RUN_INTERVAL_DEFAULT;
523 /* Function of the scheduler interface: schedule() */
524 static void
525 kist_scheduler_schedule(void)
527 struct monotime_t now;
528 struct timeval next_run;
529 int64_t diff;
531 if (!have_work()) {
532 return;
534 monotime_get(&now);
536 /* If time is really monotonic, we can never have now being smaller than the
537 * last scheduler run. The scheduler_last_run at first is set to 0.
538 * Unfortunately, not all platforms guarantee monotonic time so we log at
539 * info level but don't make it more noisy. */
540 diff = monotime_diff_msec(&scheduler_last_run, &now);
541 if (diff < 0) {
542 log_info(LD_SCHED, "Monotonic time between now and last run of scheduler "
543 "is negative: %" PRId64 ". Setting diff to 0.", diff);
544 diff = 0;
546 if (diff < sched_run_interval) {
547 next_run.tv_sec = 0;
548 /* Takes 1000 ms -> us. This will always be valid because diff can NOT be
549 * negative and can NOT be bigger than sched_run_interval so values can
550 * only go from 1000 usec (diff set to interval - 1) to 100000 usec (diff
551 * set to 0) for the maximum allowed run interval (100ms). */
552 next_run.tv_usec = (int) ((sched_run_interval - diff) * 1000);
553 /* Re-adding an event reschedules it. It does not duplicate it. */
554 scheduler_ev_add(&next_run);
555 } else {
556 scheduler_ev_active(EV_TIMEOUT);
560 /* Function of the scheduler interface: run() */
561 static void
562 kist_scheduler_run(void)
564 /* Define variables */
565 channel_t *chan = NULL; // current working channel
566 /* The last distinct chan served in a sched loop. */
567 channel_t *prev_chan = NULL;
568 int flush_result; // temporarily store results from flush calls
569 /* Channels to be re-adding to pending at the end */
570 smartlist_t *to_readd = NULL;
571 smartlist_t *cp = get_channels_pending();
573 outbuf_table_t outbuf_table = HT_INITIALIZER();
575 /* For each pending channel, collect new kernel information */
576 SMARTLIST_FOREACH_BEGIN(cp, const channel_t *, pchan) {
577 init_socket_info(&socket_table, pchan);
578 update_socket_info(&socket_table, pchan);
579 } SMARTLIST_FOREACH_END(pchan);
581 log_debug(LD_SCHED, "Running the scheduler. %d channels pending",
582 smartlist_len(cp));
584 /* The main scheduling loop. Loop until there are no more pending channels */
585 while (smartlist_len(cp) > 0) {
586 /* get best channel */
587 chan = smartlist_pqueue_pop(cp, scheduler_compare_channels,
588 offsetof(channel_t, sched_heap_idx));
589 if (SCHED_BUG(!chan, NULL)) {
590 /* Some-freaking-how a NULL got into the channels_pending. That should
591 * never happen, but it should be harmless to ignore it and keep looping.
593 continue;
595 outbuf_table_add(&outbuf_table, chan);
597 /* if we have switched to a new channel, consider writing the previous
598 * channel's outbuf to the kernel. */
599 if (!prev_chan) {
600 prev_chan = chan;
602 if (prev_chan != chan) {
603 if (channel_should_write_to_kernel(&outbuf_table, prev_chan)) {
604 channel_write_to_kernel(prev_chan);
605 outbuf_table_remove(&outbuf_table, prev_chan);
607 prev_chan = chan;
610 /* Only flush and write if the per-socket limit hasn't been hit */
611 if (socket_can_write(&socket_table, chan)) {
612 /* flush to channel queue/outbuf */
613 flush_result = (int)channel_flush_some_cells(chan, 1); // 1 for num cells
614 /* XXX: While flushing cells, it is possible that the connection write
615 * fails leading to the channel to be closed which triggers a release
616 * and free its entry in the socket table. And because of a engineering
617 * design issue, the error is not propagated back so we don't get an
618 * error at this point. So before we continue, make sure the channel is
619 * open and if not just ignore it. See #23751. */
620 if (!CHANNEL_IS_OPEN(chan)) {
621 /* Channel isn't open so we put it back in IDLE mode. It is either
622 * renegotiating its TLS session or about to be released. */
623 scheduler_set_channel_state(chan, SCHED_CHAN_IDLE);
624 continue;
626 /* flush_result has the # cells flushed */
627 if (flush_result > 0) {
628 update_socket_written(&socket_table, chan, flush_result *
629 (CELL_MAX_NETWORK_SIZE + TLS_PER_CELL_OVERHEAD));
630 } else {
631 /* XXX: This can happen because tor sometimes does flush in an
632 * opportunistic way cells from the circuit to the outbuf so the
633 * channel can end up here without having anything to flush nor needed
634 * to write to the kernel. Hopefully we'll fix that soon but for now
635 * we have to handle this case which happens kind of often. */
636 log_debug(LD_SCHED,
637 "We didn't flush anything on a chan that we think "
638 "can write and wants to write. The channel's state is '%s' "
639 "and in scheduler state '%s'. We're going to mark it as "
640 "waiting_for_cells (as that's most likely the issue) and "
641 "stop scheduling it this round.",
642 channel_state_to_string(chan->state),
643 get_scheduler_state_string(chan->scheduler_state));
644 scheduler_set_channel_state(chan, SCHED_CHAN_WAITING_FOR_CELLS);
645 continue;
649 /* Decide what to do with the channel now */
651 if (!channel_more_to_flush(chan) &&
652 !socket_can_write(&socket_table, chan)) {
654 /* Case 1: no more cells to send, and cannot write */
657 * You might think we should put the channel in SCHED_CHAN_IDLE. And
658 * you're probably correct. While implementing KIST, we found that the
659 * scheduling system would sometimes lose track of channels when we did
660 * that. We suspect it has to do with the difference between "can't
661 * write because socket/outbuf is full" and KIST's "can't write because
662 * we've arbitrarily decided that that's enough for now." Sometimes
663 * channels run out of cells at the same time they hit their
664 * kist-imposed write limit and maybe the rest of Tor doesn't put the
665 * channel back in pending when it is supposed to.
667 * This should be investigated again. It is as simple as changing
668 * SCHED_CHAN_WAITING_FOR_CELLS to SCHED_CHAN_IDLE and seeing if Tor
669 * starts having serious throughput issues. Best done in shadow/chutney.
671 scheduler_set_channel_state(chan, SCHED_CHAN_WAITING_FOR_CELLS);
672 } else if (!channel_more_to_flush(chan)) {
674 /* Case 2: no more cells to send, but still open for writes */
676 scheduler_set_channel_state(chan, SCHED_CHAN_WAITING_FOR_CELLS);
677 } else if (!socket_can_write(&socket_table, chan)) {
679 /* Case 3: cells to send, but cannot write */
682 * We want to write, but can't. If we left the channel in
683 * channels_pending, we would never exit the scheduling loop. We need to
684 * add it to a temporary list of channels to be added to channels_pending
685 * after the scheduling loop is over. They can hopefully be taken care of
686 * in the next scheduling round.
688 if (!to_readd) {
689 to_readd = smartlist_new();
691 smartlist_add(to_readd, chan);
692 } else {
694 /* Case 4: cells to send, and still open for writes */
696 scheduler_set_channel_state(chan, SCHED_CHAN_PENDING);
697 if (!SCHED_BUG(chan->sched_heap_idx != -1, chan)) {
698 smartlist_pqueue_add(cp, scheduler_compare_channels,
699 offsetof(channel_t, sched_heap_idx), chan);
702 } /* End of main scheduling loop */
704 /* Write the outbuf of any channels that still have data */
705 HT_FOREACH_FN(outbuf_table_s, &outbuf_table, each_channel_write_to_kernel,
706 NULL);
707 /* We are done with it. */
708 HT_FOREACH_FN(outbuf_table_s, &outbuf_table, free_outbuf_info_by_ent, NULL);
709 HT_CLEAR(outbuf_table_s, &outbuf_table);
711 log_debug(LD_SCHED, "len pending=%d, len to_readd=%d",
712 smartlist_len(cp),
713 (to_readd ? smartlist_len(to_readd) : -1));
715 /* Re-add any channels we need to */
716 if (to_readd) {
717 SMARTLIST_FOREACH_BEGIN(to_readd, channel_t *, readd_chan) {
718 scheduler_set_channel_state(readd_chan, SCHED_CHAN_PENDING);
719 if (!smartlist_contains(cp, readd_chan)) {
720 if (!SCHED_BUG(chan->sched_heap_idx != -1, chan)) {
721 /* XXXX Note that the check above is in theory redundant with
722 * the smartlist_contains check. But let's make sure we're
723 * not messing anything up, and leave them both for now. */
724 smartlist_pqueue_add(cp, scheduler_compare_channels,
725 offsetof(channel_t, sched_heap_idx), readd_chan);
728 } SMARTLIST_FOREACH_END(readd_chan);
729 smartlist_free(to_readd);
732 monotime_get(&scheduler_last_run);
735 /*****************************************************************************
736 * Externally called function implementations not called through scheduler_t
737 *****************************************************************************/
739 /* Stores the kist scheduler function pointers. */
740 static scheduler_t kist_scheduler = {
741 .type = SCHEDULER_KIST,
742 .free_all = kist_free_all,
743 .on_channel_free = kist_on_channel_free_fn,
744 .init = kist_scheduler_init,
745 .on_new_consensus = kist_scheduler_on_new_consensus,
746 .schedule = kist_scheduler_schedule,
747 .run = kist_scheduler_run,
748 .on_new_options = kist_scheduler_on_new_options,
751 /* Return the KIST scheduler object. If it didn't exists, return a newly
752 * allocated one but init() is not called. */
753 scheduler_t *
754 get_kist_scheduler(void)
756 return &kist_scheduler;
759 /* Check the torrc (and maybe consensus) for the configured KIST scheduler run
760 * interval.
761 * - If torrc > 0, then return the positive torrc value (should use KIST, and
762 * should use the set value)
763 * - If torrc == 0, then look in the consensus for what the value should be.
764 * - If == 0, then return 0 (don't use KIST)
765 * - If > 0, then return the positive consensus value
766 * - If consensus doesn't say anything, return 10 milliseconds, default.
769 kist_scheduler_run_interval(void)
771 int run_interval = get_options()->KISTSchedRunInterval;
773 if (run_interval != 0) {
774 log_debug(LD_SCHED, "Found KISTSchedRunInterval=%" PRId32 " in torrc. "
775 "Using that.", run_interval);
776 return run_interval;
779 log_debug(LD_SCHED, "KISTSchedRunInterval=0, turning to the consensus.");
781 /* Will either be the consensus value or the default. Note that 0 can be
782 * returned which means the consensus wants us to NOT use KIST. */
783 return networkstatus_get_param(NULL, "KISTSchedRunInterval",
784 KIST_SCHED_RUN_INTERVAL_DEFAULT,
785 KIST_SCHED_RUN_INTERVAL_MIN,
786 KIST_SCHED_RUN_INTERVAL_MAX);
789 /* Set KISTLite mode that is KIST without kernel support. */
790 void
791 scheduler_kist_set_lite_mode(void)
793 kist_lite_mode = 1;
794 kist_scheduler.type = SCHEDULER_KIST_LITE;
795 log_info(LD_SCHED,
796 "Setting KIST scheduler without kernel support (KISTLite mode)");
799 /* Set KIST mode that is KIST with kernel support. */
800 void
801 scheduler_kist_set_full_mode(void)
803 kist_lite_mode = 0;
804 kist_scheduler.type = SCHEDULER_KIST;
805 log_info(LD_SCHED,
806 "Setting KIST scheduler with kernel support (KIST mode)");
809 #ifdef HAVE_KIST_SUPPORT
811 /* Return true iff the scheduler subsystem should use KIST. */
813 scheduler_can_use_kist(void)
815 if (kist_no_kernel_support) {
816 /* We have no kernel support so we can't use KIST. */
817 return 0;
820 /* We do have the support, time to check if we can get the interval that the
821 * consensus can be disabling. */
822 int run_interval = kist_scheduler_run_interval();
823 log_debug(LD_SCHED, "Determined KIST sched_run_interval should be "
824 "%" PRId32 ". Can%s use KIST.",
825 run_interval, (run_interval > 0 ? "" : " not"));
826 return run_interval > 0;
829 #else /* !(defined(HAVE_KIST_SUPPORT)) */
832 scheduler_can_use_kist(void)
834 return 0;
837 #endif /* defined(HAVE_KIST_SUPPORT) */