1 /*-
2 * Copyright (c) 2016-2018 Netflix, Inc.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 *
25 */
26 #include "opt_inet.h"
27 #include "opt_inet6.h"
28 #include "opt_rss.h"
29
30 /**
31 * Some notes about usage.
32 *
33 * The tcp_hpts system is designed to provide a high precision timer
34 * system for tcp. Its main purpose is to provide a mechanism for
35 * pacing packets out onto the wire. It can be used in two ways
36 * by a given TCP stack (and those two methods can be used simultaneously).
37 *
38 * First, and probably the main thing its used by Rack and BBR, it can
39 * be used to call tcp_output() of a transport stack at some time in the future.
40 * The normal way this is done is that tcp_output() of the stack schedules
41 * itself to be called again by calling tcp_hpts_insert(tcpcb, usecs). The
42 * usecs is the time from now that the stack wants to be called and is
43 * passing time directly in microseconds. So a typical
44 * call from the tcp_output() routine might look like:
45 *
46 * tcp_hpts_insert(tp, 550, NULL);
47 *
48 * The above would schedule tcp_output() to be called in 550 microseconds.
49 * Note that if using this mechanism the stack will want to add near
50 * its top a check to prevent unwanted calls (from user land or the
51 * arrival of incoming ack's). So it would add something like:
52 *
53 * if (tcp_in_hpts(inp))
54 * return;
55 *
56 * to prevent output processing until the time alotted has gone by.
57 * Of course this is a bare bones example and the stack will probably
58 * have more consideration then just the above.
59 *
60 * In order to run input queued segments from the HPTS context the
61 * tcp stack must define an input function for
62 * tfb_do_queued_segments(). This function understands
63 * how to dequeue a array of packets that were input and
64 * knows how to call the correct processing routine.
65 *
66 * Locking in this is important as well so most likely the
67 * stack will need to define the tfb_do_segment_nounlock()
68 * splitting tfb_do_segment() into two parts. The main processing
69 * part that does not unlock the INP and returns a value of 1 or 0.
70 * It returns 0 if all is well and the lock was not released. It
71 * returns 1 if we had to destroy the TCB (a reset received etc).
72 * The remains of tfb_do_segment() then become just a simple call
73 * to the tfb_do_segment_nounlock() function and check the return
74 * code and possibly unlock.
75 *
76 * The stack must also set the flag on the INP that it supports this
77 * feature i.e. INP_SUPPORTS_MBUFQ. The LRO code recoginizes
78 * this flag as well and will queue packets when it is set.
79 * There are other flags as well INP_MBUF_QUEUE_READY and
80 * INP_DONT_SACK_QUEUE. The first flag tells the LRO code
81 * that we are in the pacer for output so there is no
82 * need to wake up the hpts system to get immediate
83 * input. The second tells the LRO code that its okay
84 * if a SACK arrives you can still defer input and let
85 * the current hpts timer run (this is usually set when
86 * a rack timer is up so we know SACK's are happening
87 * on the connection already and don't want to wakeup yet).
88 *
89 * There is a common functions within the rack_bbr_common code
90 * version i.e. ctf_do_queued_segments(). This function
91 * knows how to take the input queue of packets from tp->t_inqueue
92 * and process them digging out all the arguments, calling any bpf tap and
93 * calling into tfb_do_segment_nounlock(). The common
94 * function (ctf_do_queued_segments()) requires that
95 * you have defined the tfb_do_segment_nounlock() as
96 * described above.
97 */
98
99 #include <sys/param.h>
100 #include <sys/bus.h>
101 #include <sys/interrupt.h>
102 #include <sys/module.h>
103 #include <sys/kernel.h>
104 #include <sys/hhook.h>
105 #include <sys/malloc.h>
106 #include <sys/mbuf.h>
107 #include <sys/proc.h> /* for proc0 declaration */
108 #include <sys/socket.h>
109 #include <sys/socketvar.h>
110 #include <sys/sysctl.h>
111 #include <sys/systm.h>
112 #include <sys/refcount.h>
113 #include <sys/sched.h>
114 #include <sys/queue.h>
115 #include <sys/smp.h>
116 #include <sys/counter.h>
117 #include <sys/time.h>
118 #include <sys/kthread.h>
119 #include <sys/kern_prefetch.h>
120
121 #include <vm/uma.h>
122 #include <vm/vm.h>
123
124 #include <net/route.h>
125 #include <net/vnet.h>
126
127 #ifdef RSS
128 #include <net/netisr.h>
129 #include <net/rss_config.h>
130 #endif
131
132 #define TCPSTATES /* for logging */
133
134 #include <netinet/in.h>
135 #include <netinet/in_kdtrace.h>
136 #include <netinet/in_pcb.h>
137 #include <netinet/ip.h>
138 #include <netinet/ip_var.h>
139 #include <netinet/ip6.h>
140 #include <netinet6/in6_pcb.h>
141 #include <netinet6/ip6_var.h>
142 #include <netinet/tcp.h>
143 #include <netinet/tcp_fsm.h>
144 #include <netinet/tcp_seq.h>
145 #include <netinet/tcp_timer.h>
146 #include <netinet/tcp_var.h>
147 #include <netinet/tcpip.h>
148 #include <netinet/cc/cc.h>
149 #include <netinet/tcp_hpts.h>
150 #include <netinet/tcp_hpts_internal.h>
151 #include <netinet/tcp_log_buf.h>
152
153 #ifdef tcp_offload
154 #include <netinet/tcp_offload.h>
155 #endif
156
157 /* Global instance for TCP HPTS */
158 struct tcp_hptsi *tcp_hptsi_pace;
159
160 /* Default function table for production use. */
161 const struct tcp_hptsi_funcs tcp_hptsi_default_funcs = {
162 .microuptime = microuptime,
163 .swi_add = swi_add,
164 .swi_remove = swi_remove,
165 .swi_sched = swi_sched,
166 .intr_event_bind = intr_event_bind,
167 .intr_event_bind_ithread_cpuset = intr_event_bind_ithread_cpuset,
168 .callout_init = callout_init,
169 .callout_reset_sbt_on = callout_reset_sbt_on,
170 ._callout_stop_safe = _callout_stop_safe,
171 };
172
173 #ifdef TCP_HPTS_KTEST
174 #define microuptime pace->funcs->microuptime
175 #define swi_add pace->funcs->swi_add
176 #define swi_remove pace->funcs->swi_remove
177 #define swi_sched pace->funcs->swi_sched
178 #define intr_event_bind pace->funcs->intr_event_bind
179 #define intr_event_bind_ithread_cpuset pace->funcs->intr_event_bind_ithread_cpuset
180 #define callout_init pace->funcs->callout_init
181 #define callout_reset_sbt_on pace->funcs->callout_reset_sbt_on
182 #define _callout_stop_safe pace->funcs->_callout_stop_safe
183 #endif
184
185 static MALLOC_DEFINE(M_TCPHPTS, "tcp_hpts", "TCP hpts");
186
187 static void tcp_hpts_thread(void *ctx);
188 static volatile uint32_t __read_frequently hpts_that_need_softclock;
189
190 #define LOWEST_SLEEP_ALLOWED 50
191 #define DEFAULT_MIN_SLEEP 250 /* How many usec's is default for hpts sleep
192 * this determines min granularity of the
193 * hpts. If 1, granularity is 10useconds at
194 * the cost of more CPU (context switching).
195 * Note do not set this to 0.
196 */
197 #define DYNAMIC_MIN_SLEEP DEFAULT_MIN_SLEEP
198 #define DYNAMIC_MAX_SLEEP 5000 /* 5ms */
199
200 /* Thresholds for raising/lowering sleep */
201 #define SLOTS_INDICATE_MORE_SLEEP 100 /* This would be 1ms */
202 #define SLOTS_INDICATE_LESS_SLEEP 1000 /* This would indicate 10ms */
203 /**
204 *
205 * Dynamic adjustment of sleeping times is done in "new" mode
206 * where we are depending on syscall returns and lro returns
207 * to push hpts forward mainly and the timer is only a backstop.
208 *
209 * When we are in the "new" mode i.e. conn_cnt > conn_cnt_thresh
210 * then we do a dynamic adjustment on the time we sleep.
211 * Our threshold is if the lateness of the first client served (in slots) is
212 * greater than or equal too slots_indicate_more_sleep (10ms
213 * or 10000 slots). If we were that late, the actual sleep time
214 * is adjusted down by 50%. If the slots_ran is less than
215 * slots_indicate_more_sleep (100 slots or 1000usecs).
216 *
217 */
218
219 #ifdef RSS
220 int tcp_bind_threads = 1;
221 #else
222 int tcp_bind_threads = 2;
223 #endif
224 static int tcp_use_irq_cpu = 0;
225 static int hpts_does_tp_logging = 0;
226 static int32_t tcp_hpts_precision = 120;
227 int32_t tcp_min_hptsi_time = DEFAULT_MIN_SLEEP;
228 static int conn_cnt_thresh = DEFAULT_CONNECTION_THRESHOLD;
229 static int32_t dynamic_min_sleep = DYNAMIC_MIN_SLEEP;
230 static int32_t dynamic_max_sleep = DYNAMIC_MAX_SLEEP;
231
232 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, hpts, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
233 "TCP Hpts controls");
234 SYSCTL_NODE(_net_inet_tcp_hpts, OID_AUTO, stats, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
235 "TCP Hpts statistics");
236
237 counter_u64_t hpts_hopelessly_behind;
238
239 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, hopeless, CTLFLAG_RD,
240 &hpts_hopelessly_behind,
241 "Number of times hpts could not catch up and was behind hopelessly");
242
243 counter_u64_t hpts_loops;
244
245 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, loops, CTLFLAG_RD,
246 &hpts_loops, "Number of times hpts had to loop to catch up");
247
248 counter_u64_t back_tosleep;
249
250 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, no_tcbsfound, CTLFLAG_RD,
251 &back_tosleep, "Number of times hpts found no tcbs");
252
253 counter_u64_t combined_wheel_wrap;
254
255 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, comb_wheel_wrap, CTLFLAG_RD,
256 &combined_wheel_wrap, "Number of times the wheel lagged enough to have an insert see wrap");
257
258 counter_u64_t wheel_wrap;
259
260 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, wheel_wrap, CTLFLAG_RD,
261 &wheel_wrap, "Number of times the wheel lagged enough to have an insert see wrap");
262
263 counter_u64_t hpts_direct_call;
264 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, direct_call, CTLFLAG_RD,
265 &hpts_direct_call, "Number of times hpts was called by syscall/trap or other entry");
266
267 counter_u64_t hpts_wake_timeout;
268
269 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, timeout_wakeup, CTLFLAG_RD,
270 &hpts_wake_timeout, "Number of times hpts threads woke up via the callout expiring");
271
272 counter_u64_t hpts_direct_awakening;
273
274 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, direct_awakening, CTLFLAG_RD,
275 &hpts_direct_awakening, "Number of times hpts threads woke up via the callout expiring");
276
277 counter_u64_t hpts_back_tosleep;
278
279 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, back_tosleep, CTLFLAG_RD,
280 &hpts_back_tosleep, "Number of times hpts threads woke up via the callout expiring and went back to sleep no work");
281
282 counter_u64_t cpu_uses_flowid;
283 counter_u64_t cpu_uses_random;
284
285 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, cpusel_flowid, CTLFLAG_RD,
286 &cpu_uses_flowid, "Number of times when setting cpuid we used the flowid field");
287 SYSCTL_COUNTER_U64(_net_inet_tcp_hpts_stats, OID_AUTO, cpusel_random, CTLFLAG_RD,
288 &cpu_uses_random, "Number of times when setting cpuid we used the a random value");
289
290 TUNABLE_INT("net.inet.tcp.bind_hptss", &tcp_bind_threads);
291 TUNABLE_INT("net.inet.tcp.use_irq", &tcp_use_irq_cpu);
292 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, bind_hptss, CTLFLAG_RD,
293 &tcp_bind_threads, 2,
294 "Thread Binding tunable");
295 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, use_irq, CTLFLAG_RD,
296 &tcp_use_irq_cpu, 0,
297 "Use of irq CPU tunable");
298 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, precision, CTLFLAG_RW,
299 &tcp_hpts_precision, 120,
300 "Value for PRE() precision of callout");
301 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, cnt_thresh, CTLFLAG_RW,
302 &conn_cnt_thresh, 0,
303 "How many connections (below) make us use the callout based mechanism");
304 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, logging, CTLFLAG_RW,
305 &hpts_does_tp_logging, 0,
306 "Do we add to any tp that has logging on pacer logs");
307 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, dyn_minsleep, CTLFLAG_RW,
308 &dynamic_min_sleep, 250,
309 "What is the dynamic minsleep value?");
310 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, dyn_maxsleep, CTLFLAG_RW,
311 &dynamic_max_sleep, 5000,
312 "What is the dynamic maxsleep value?");
313
314 static int32_t max_pacer_loops = 10;
315 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, loopmax, CTLFLAG_RW,
316 &max_pacer_loops, 10,
317 "What is the maximum number of times the pacer will loop trying to catch up");
318
319 #define HPTS_MAX_SLEEP_ALLOWED (NUM_OF_HPTSI_SLOTS/2)
320
321 static uint32_t hpts_sleep_max = HPTS_MAX_SLEEP_ALLOWED;
322
323 static int
sysctl_net_inet_tcp_hpts_max_sleep(SYSCTL_HANDLER_ARGS)324 sysctl_net_inet_tcp_hpts_max_sleep(SYSCTL_HANDLER_ARGS)
325 {
326 int error;
327 uint32_t new;
328
329 new = hpts_sleep_max;
330 error = sysctl_handle_int(oidp, &new, 0, req);
331 if (error == 0 && req->newptr) {
332 if ((new < (dynamic_min_sleep/HPTS_USECS_PER_SLOT)) ||
333 (new > HPTS_MAX_SLEEP_ALLOWED))
334 error = EINVAL;
335 else
336 hpts_sleep_max = new;
337 }
338 return (error);
339 }
340
341 static int
sysctl_net_inet_tcp_hpts_min_sleep(SYSCTL_HANDLER_ARGS)342 sysctl_net_inet_tcp_hpts_min_sleep(SYSCTL_HANDLER_ARGS)
343 {
344 int error;
345 uint32_t new;
346
347 new = tcp_min_hptsi_time;
348 error = sysctl_handle_int(oidp, &new, 0, req);
349 if (error == 0 && req->newptr) {
350 if (new < LOWEST_SLEEP_ALLOWED)
351 error = EINVAL;
352 else
353 tcp_min_hptsi_time = new;
354 }
355 return (error);
356 }
357
358 SYSCTL_PROC(_net_inet_tcp_hpts, OID_AUTO, maxsleep,
359 CTLTYPE_UINT | CTLFLAG_RW,
360 &hpts_sleep_max, 0,
361 &sysctl_net_inet_tcp_hpts_max_sleep, "IU",
362 "Maximum time hpts will sleep in slots");
363
364 SYSCTL_PROC(_net_inet_tcp_hpts, OID_AUTO, minsleep,
365 CTLTYPE_UINT | CTLFLAG_RW,
366 &tcp_min_hptsi_time, 0,
367 &sysctl_net_inet_tcp_hpts_min_sleep, "IU",
368 "The minimum time the hpts must sleep before processing more slots");
369
370 static int slots_indicate_more_sleep = SLOTS_INDICATE_MORE_SLEEP;
371 static int slots_indicate_less_sleep = SLOTS_INDICATE_LESS_SLEEP;
372 static int tcp_hpts_no_wake_over_thresh = 1;
373
374 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, more_sleep, CTLFLAG_RW,
375 &slots_indicate_more_sleep, 0,
376 "If we only process this many or less on a timeout, we need longer sleep on the next callout");
377 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, less_sleep, CTLFLAG_RW,
378 &slots_indicate_less_sleep, 0,
379 "If we process this many or more on a timeout, we need less sleep on the next callout");
380 SYSCTL_INT(_net_inet_tcp_hpts, OID_AUTO, nowake_over_thresh, CTLFLAG_RW,
381 &tcp_hpts_no_wake_over_thresh, 0,
382 "When we are over the threshold on the pacer do we prohibit wakeups?");
383
384 uint16_t
tcp_hptsi_random_cpu(struct tcp_hptsi * pace)385 tcp_hptsi_random_cpu(struct tcp_hptsi *pace)
386 {
387 uint16_t cpuid;
388 uint32_t ran;
389
390 ran = arc4random();
391 cpuid = (((ran & 0xffff) % mp_ncpus) % pace->rp_num_hptss);
392 return (cpuid);
393 }
394
395 static void
tcp_hpts_log(struct tcp_hpts_entry * hpts,struct tcpcb * tp,struct timeval * tv,int slots_to_run,int idx,bool from_callout)396 tcp_hpts_log(struct tcp_hpts_entry *hpts, struct tcpcb *tp, struct timeval *tv,
397 int slots_to_run, int idx, bool from_callout)
398 {
399 if (hpts_does_tp_logging && tcp_bblogging_on(tp)) {
400 union tcp_log_stackspecific log;
401 /*
402 * Unused logs are
403 * 64 bit - delRate, rttProp, bw_inuse
404 * 16 bit - cwnd_gain
405 * 8 bit - bbr_state, bbr_substate, inhpts;
406 */
407 memset(&log, 0, sizeof(log));
408 log.u_bbr.flex1 = hpts->p_nxt_slot;
409 log.u_bbr.flex2 = hpts->p_cur_slot;
410 log.u_bbr.flex3 = hpts->p_prev_slot;
411 log.u_bbr.flex4 = idx;
412 log.u_bbr.flex6 = hpts->p_on_queue_cnt;
413 log.u_bbr.flex7 = hpts->p_cpu;
414 log.u_bbr.flex8 = (uint8_t)from_callout;
415 log.u_bbr.inflight = slots_to_run;
416 log.u_bbr.applimited = hpts->overidden_sleep;
417 log.u_bbr.timeStamp = tcp_tv_to_usec(tv);
418 log.u_bbr.epoch = hpts->saved_curslot;
419 log.u_bbr.lt_epoch = hpts->saved_prev_slot;
420 log.u_bbr.pkts_out = hpts->p_delayed_by;
421 log.u_bbr.lost = hpts->p_hpts_sleep_time;
422 log.u_bbr.pacing_gain = hpts->p_cpu;
423 log.u_bbr.pkt_epoch = hpts->p_runningslot;
424 log.u_bbr.use_lt_bw = 1;
425 TCP_LOG_EVENTP(tp, NULL,
426 &tptosocket(tp)->so_rcv,
427 &tptosocket(tp)->so_snd,
428 BBR_LOG_HPTSDIAG, 0,
429 0, &log, false, tv);
430 }
431 }
432
433 /*
434 * Timeout handler for the HPTS sleep callout. It immediately schedules the SWI
435 * for the HPTS entry to run.
436 */
437 static void
tcp_hpts_sleep_timeout(void * arg)438 tcp_hpts_sleep_timeout(void *arg)
439 {
440 #ifdef TCP_HPTS_KTEST
441 struct tcp_hptsi *pace;
442 #endif
443 struct tcp_hpts_entry *hpts;
444
445 hpts = (struct tcp_hpts_entry *)arg;
446 #ifdef TCP_HPTS_KTEST
447 pace = hpts->p_hptsi;
448 #endif
449 swi_sched(hpts->ie_cookie, 0);
450 }
451
452 /*
453 * Reset the HPTS callout timer with the provided timeval. Returns the results
454 * of the callout_reset_sbt_on() function.
455 */
456 static int
tcp_hpts_sleep(struct tcp_hpts_entry * hpts,struct timeval * tv)457 tcp_hpts_sleep(struct tcp_hpts_entry *hpts, struct timeval *tv)
458 {
459 #ifdef TCP_HPTS_KTEST
460 struct tcp_hptsi *pace;
461 #endif
462 sbintime_t sb;
463
464 #ifdef TCP_HPTS_KTEST
465 pace = hpts->p_hptsi;
466 #endif
467
468 /* Store off to make visible the actual sleep time */
469 hpts->sleeping = tv->tv_usec;
470
471 sb = tvtosbt(*tv);
472 return (callout_reset_sbt_on(
473 &hpts->co, sb, 0, tcp_hpts_sleep_timeout, hpts, hpts->p_cpu,
474 (C_DIRECT_EXEC | C_PREL(tcp_hpts_precision))));
475 }
476
477 /*
478 * Schedules the SWI for the HTPS entry to run, if not already scheduled or
479 * running.
480 */
481 void
tcp_hpts_wake(struct tcp_hpts_entry * hpts)482 tcp_hpts_wake(struct tcp_hpts_entry *hpts)
483 {
484 #ifdef TCP_HPTS_KTEST
485 struct tcp_hptsi *pace;
486 #endif
487
488 HPTS_MTX_ASSERT(hpts);
489
490 #ifdef TCP_HPTS_KTEST
491 pace = hpts->p_hptsi;
492 #endif
493
494 if (tcp_hpts_no_wake_over_thresh && (hpts->p_on_queue_cnt >= conn_cnt_thresh)) {
495 hpts->p_direct_wake = 0;
496 return;
497 }
498 if (hpts->p_hpts_wake_scheduled == 0) {
499 hpts->p_hpts_wake_scheduled = 1;
500 swi_sched(hpts->ie_cookie, 0);
501 }
502 }
503
504 static void
tcp_hpts_insert_internal(struct tcpcb * tp,struct tcp_hpts_entry * hpts)505 tcp_hpts_insert_internal(struct tcpcb *tp, struct tcp_hpts_entry *hpts)
506 {
507 struct inpcb *inp = tptoinpcb(tp);
508 struct hptsh *hptsh;
509
510 INP_WLOCK_ASSERT(inp);
511 HPTS_MTX_ASSERT(hpts);
512 MPASS(hpts->p_cpu == tp->t_hpts_cpu);
513 MPASS(!(tp->t_flags & TF_DISCONNECTED));
514
515 hptsh = &hpts->p_hptss[tp->t_hpts_slot];
516
517 if (tp->t_in_hpts == IHPTS_NONE) {
518 tp->t_in_hpts = IHPTS_ONQUEUE;
519 in_pcbref(inp);
520 } else if (tp->t_in_hpts == IHPTS_MOVING) {
521 tp->t_in_hpts = IHPTS_ONQUEUE;
522 } else
523 MPASS(tp->t_in_hpts == IHPTS_ONQUEUE);
524 tp->t_hpts_gencnt = hptsh->gencnt;
525
526 TAILQ_INSERT_TAIL(&hptsh->head, tp, t_hpts);
527 hptsh->count++;
528 hpts->p_on_queue_cnt++;
529 }
530
531 static struct tcp_hpts_entry *
tcp_hpts_lock(struct tcp_hptsi * pace,struct tcpcb * tp)532 tcp_hpts_lock(struct tcp_hptsi *pace, struct tcpcb *tp)
533 {
534 struct tcp_hpts_entry *hpts;
535
536 INP_LOCK_ASSERT(tptoinpcb(tp));
537
538 hpts = pace->rp_ent[tp->t_hpts_cpu];
539 HPTS_LOCK(hpts);
540
541 return (hpts);
542 }
543
544 static void
tcp_hpts_release(struct tcpcb * tp)545 tcp_hpts_release(struct tcpcb *tp)
546 {
547 bool released __diagused;
548
549 tp->t_in_hpts = IHPTS_NONE;
550 released = in_pcbrele_wlocked(tptoinpcb(tp));
551 MPASS(released == false);
552 }
553
554 /*
555 * Initialize tcpcb to get ready for use with HPTS. We will know which CPU
556 * is preferred on the first incoming packet. Before that avoid crowding
557 * a single CPU with newborn connections and use a random one.
558 * This initialization is normally called on a newborn tcpcb, but potentially
559 * can be called once again if stack is switched. In that case we inherit CPU
560 * that the previous stack has set, be it random or not. In extreme cases,
561 * e.g. syzkaller fuzzing, a tcpcb can already be in HPTS in IHPTS_MOVING state
562 * and has never received a first packet.
563 */
564 void
__tcp_hpts_init(struct tcp_hptsi * pace,struct tcpcb * tp)565 __tcp_hpts_init(struct tcp_hptsi *pace, struct tcpcb *tp)
566 {
567 if (__predict_true(tp->t_hpts_cpu == HPTS_CPU_NONE)) {
568 tp->t_hpts_cpu = tcp_hptsi_random_cpu(pace);
569 MPASS(!(tp->t_flags2 & TF2_HPTS_CPU_SET));
570 }
571 }
572
573 /*
574 * Called normally with the INP_LOCKED but it
575 * does not matter, the hpts lock is the key
576 * but the lock order allows us to hold the
577 * INP lock and then get the hpts lock.
578 */
579 void
__tcp_hpts_remove(struct tcp_hptsi * pace,struct tcpcb * tp)580 __tcp_hpts_remove(struct tcp_hptsi *pace, struct tcpcb *tp)
581 {
582 struct tcp_hpts_entry *hpts;
583 struct hptsh *hptsh;
584
585 INP_WLOCK_ASSERT(tptoinpcb(tp));
586
587 hpts = tcp_hpts_lock(pace, tp);
588 if (tp->t_in_hpts == IHPTS_ONQUEUE) {
589 hptsh = &hpts->p_hptss[tp->t_hpts_slot];
590 tp->t_hpts_request = 0;
591 if (__predict_true(tp->t_hpts_gencnt == hptsh->gencnt)) {
592 TAILQ_REMOVE(&hptsh->head, tp, t_hpts);
593 MPASS(hptsh->count > 0);
594 hptsh->count--;
595 MPASS(hpts->p_on_queue_cnt > 0);
596 hpts->p_on_queue_cnt--;
597 tcp_hpts_release(tp);
598 } else {
599 /*
600 * tcp_hptsi() now owns the TAILQ head of this inp.
601 * Can't TAILQ_REMOVE, just mark it.
602 */
603 #ifdef INVARIANTS
604 struct tcpcb *tmp;
605
606 TAILQ_FOREACH(tmp, &hptsh->head, t_hpts)
607 MPASS(tmp != tp);
608 #endif
609 tp->t_in_hpts = IHPTS_MOVING;
610 tp->t_hpts_slot = -1;
611 }
612 } else if (tp->t_in_hpts == IHPTS_MOVING) {
613 /*
614 * Handle a special race condition:
615 * tcp_hptsi() moves inpcb to detached tailq
616 * tcp_hpts_remove() marks as IHPTS_MOVING, slot = -1
617 * tcp_hpts_insert() sets slot to a meaningful value
618 * The connection is terminated with the final call to
619 tcp_hpts_remove() again (we are here!) and we fail to call
620 tcp_hpts_release() since it is IHPTS_MOVING. Set slot to -1
621 to delegate the release to the owner of the detached tailq.
622 */
623 tp->t_hpts_slot = -1;
624 }
625 HPTS_UNLOCK(hpts);
626 }
627
628 static inline int
hpts_slot(uint32_t wheel_slot,uint32_t plus)629 hpts_slot(uint32_t wheel_slot, uint32_t plus)
630 {
631 /*
632 * Given a slot on the wheel, what slot
633 * is that plus slots out?
634 */
635 KASSERT(wheel_slot < NUM_OF_HPTSI_SLOTS, ("Invalid slot %u not on wheel", wheel_slot));
636 return ((wheel_slot + plus) % NUM_OF_HPTSI_SLOTS);
637 }
638
639 static inline int
cts_to_wheel(uint32_t cts)640 cts_to_wheel(uint32_t cts)
641 {
642 /*
643 * Given a timestamp in useconds map it to our limited space wheel.
644 */
645 return ((cts / HPTS_USECS_PER_SLOT) % NUM_OF_HPTSI_SLOTS);
646 }
647
648 static inline int
hpts_slots_diff(int prev_slot,int slot_now)649 hpts_slots_diff(int prev_slot, int slot_now)
650 {
651 /*
652 * Given two slots that are someplace
653 * on our wheel. How far are they apart?
654 */
655 if (slot_now > prev_slot)
656 return (slot_now - prev_slot);
657 else if (slot_now == prev_slot)
658 /*
659 * Special case, same means we can go all of our
660 * wheel less one slot.
661 */
662 return (NUM_OF_HPTSI_SLOTS - 1);
663 else
664 return ((NUM_OF_HPTSI_SLOTS - prev_slot) + slot_now);
665 }
666
667 /*
668 * Given a slot on the wheel that is the current time
669 * mapped to the wheel (wheel_slot), what is the maximum
670 * distance forward that can be obtained without
671 * wrapping past either prev_slot or running_slot
672 * depending on the htps state? Also if passed
673 * a uint32_t *, fill it with the slot location.
674 *
675 * Note if you do not give this function the current
676 * time (that you think it is) mapped to the wheel slot
677 * then the results will not be what you expect and
678 * could lead to invalid inserts.
679 */
680 static inline int32_t
max_slots_available(struct tcp_hpts_entry * hpts,uint32_t wheel_slot,uint32_t * target_slot)681 max_slots_available(struct tcp_hpts_entry *hpts, uint32_t wheel_slot, uint32_t *target_slot)
682 {
683 uint32_t dis_to_travel, end_slot, pacer_to_now, avail_on_wheel;
684
685 if ((hpts->p_hpts_active == 1) &&
686 (hpts->p_wheel_complete == 0)) {
687 end_slot = hpts->p_runningslot;
688 /* Back up one slot */
689 if (end_slot == 0)
690 end_slot = NUM_OF_HPTSI_SLOTS - 1;
691 else
692 end_slot--;
693 if (target_slot)
694 *target_slot = end_slot;
695 } else {
696 /*
697 * For the case where we are
698 * not active, or we have
699 * completed the pass over
700 * the wheel, we can use the
701 * prev slot and subtract one from it. This puts us
702 * as far out as possible on the wheel.
703 */
704 end_slot = hpts->p_prev_slot;
705 if (end_slot == 0)
706 end_slot = NUM_OF_HPTSI_SLOTS - 1;
707 else
708 end_slot--;
709 if (target_slot)
710 *target_slot = end_slot;
711 /*
712 * Now we have close to the full wheel left minus the
713 * time it has been since the pacer went to sleep. Note
714 * that wheel_slot, passed in, should be the current time
715 * from the perspective of the caller, mapped to the wheel.
716 */
717 if (hpts->p_prev_slot != wheel_slot)
718 dis_to_travel = hpts_slots_diff(hpts->p_prev_slot, wheel_slot);
719 else
720 dis_to_travel = 1;
721 /*
722 * dis_to_travel in this case is the space from when the
723 * pacer stopped (p_prev_slot) and where our wheel_slot
724 * is now. To know how many slots we can put it in we
725 * subtract from the wheel size. We would not want
726 * to place something after p_prev_slot or it will
727 * get ran too soon.
728 */
729 return (NUM_OF_HPTSI_SLOTS - dis_to_travel);
730 }
731 /*
732 * So how many slots are open between p_runningslot -> p_cur_slot
733 * that is what is currently un-available for insertion. Special
734 * case when we are at the last slot, this gets 1, so that
735 * the answer to how many slots are available is all but 1.
736 */
737 if (hpts->p_runningslot == hpts->p_cur_slot)
738 dis_to_travel = 1;
739 else
740 dis_to_travel = hpts_slots_diff(hpts->p_runningslot, hpts->p_cur_slot);
741 /*
742 * How long has the pacer been running?
743 */
744 if (hpts->p_cur_slot != wheel_slot) {
745 /* The pacer is a bit late */
746 pacer_to_now = hpts_slots_diff(hpts->p_cur_slot, wheel_slot);
747 } else {
748 /* The pacer is right on time, now == pacers start time */
749 pacer_to_now = 0;
750 }
751 /*
752 * To get the number left we can insert into we simply
753 * subtract the distance the pacer has to run from how
754 * many slots there are.
755 */
756 avail_on_wheel = NUM_OF_HPTSI_SLOTS - dis_to_travel;
757 /*
758 * Now how many of those we will eat due to the pacer's
759 * time (p_cur_slot) of start being behind the
760 * real time (wheel_slot)?
761 */
762 if (avail_on_wheel <= pacer_to_now) {
763 /*
764 * Wheel wrap, we can't fit on the wheel, that
765 * is unusual the system must be way overloaded!
766 * Insert into the assured slot, and return special
767 * "0".
768 */
769 counter_u64_add(combined_wheel_wrap, 1);
770 if (target_slot)
771 *target_slot = hpts->p_nxt_slot;
772 return (0);
773 } else {
774 /*
775 * We know how many slots are open
776 * on the wheel (the reverse of what
777 * is left to run. Take away the time
778 * the pacer started to now (wheel_slot)
779 * and that tells you how many slots are
780 * open that can be inserted into that won't
781 * be touched by the pacer until later.
782 */
783 return (avail_on_wheel - pacer_to_now);
784 }
785 }
786
787
788 #ifdef INVARIANTS
789 static void
check_if_slot_would_be_wrong(struct tcp_hpts_entry * hpts,struct tcpcb * tp,uint32_t hptsslot)790 check_if_slot_would_be_wrong(struct tcp_hpts_entry *hpts, struct tcpcb *tp,
791 uint32_t hptsslot)
792 {
793 /*
794 * Sanity checks for the pacer with invariants
795 * on insert.
796 */
797 KASSERT(hptsslot < NUM_OF_HPTSI_SLOTS,
798 ("hpts:%p tp:%p slot:%d > max", hpts, tp, hptsslot));
799 if ((hpts->p_hpts_active) &&
800 (hpts->p_wheel_complete == 0)) {
801 /*
802 * If the pacer is processing a arc
803 * of the wheel, we need to make
804 * sure we are not inserting within
805 * that arc.
806 */
807 int distance, yet_to_run;
808
809 distance = hpts_slots_diff(hpts->p_runningslot, hptsslot);
810 if (hpts->p_runningslot != hpts->p_cur_slot)
811 yet_to_run = hpts_slots_diff(hpts->p_runningslot, hpts->p_cur_slot);
812 else
813 yet_to_run = 0; /* processing last slot */
814 KASSERT(yet_to_run <= distance, ("hpts:%p tp:%p slot:%d "
815 "distance:%d yet_to_run:%d rs:%d cs:%d", hpts, tp,
816 hptsslot, distance, yet_to_run, hpts->p_runningslot,
817 hpts->p_cur_slot));
818 }
819 }
820 #endif
821
822 void
__tcp_hpts_insert(struct tcp_hptsi * pace,struct tcpcb * tp,uint32_t usecs,struct hpts_diag * diag)823 __tcp_hpts_insert(struct tcp_hptsi *pace, struct tcpcb *tp, uint32_t usecs,
824 struct hpts_diag *diag)
825 {
826 struct tcp_hpts_entry *hpts;
827 struct timeval tv;
828 uint32_t slot, wheel_cts, last_slot, need_new_to = 0;
829 int32_t wheel_slot, maxslots;
830 bool need_wakeup = false;
831
832 INP_WLOCK_ASSERT(tptoinpcb(tp));
833 MPASS(!(tp->t_flags & TF_DISCONNECTED));
834 MPASS(!(tp->t_in_hpts == IHPTS_ONQUEUE));
835
836 /*
837 * Convert microseconds to slots for internal use.
838 * We now return the next-slot the hpts will be on, beyond its
839 * current run (if up) or where it was when it stopped if it is
840 * sleeping.
841 */
842 slot = HPTS_USEC_TO_SLOTS(usecs);
843 hpts = tcp_hpts_lock(pace, tp);
844 microuptime(&tv);
845 if (diag) {
846 memset(diag, 0, sizeof(struct hpts_diag));
847 diag->p_hpts_active = hpts->p_hpts_active;
848 diag->p_prev_slot = hpts->p_prev_slot;
849 diag->p_runningslot = hpts->p_runningslot;
850 diag->p_nxt_slot = hpts->p_nxt_slot;
851 diag->p_cur_slot = hpts->p_cur_slot;
852 diag->slot_req = slot;
853 diag->p_on_min_sleep = hpts->p_on_min_sleep;
854 diag->hpts_sleep_time = hpts->p_hpts_sleep_time;
855 }
856 if (slot == 0) {
857 /* Ok we need to set it on the hpts in the current slot */
858 tp->t_hpts_request = 0;
859 if ((hpts->p_hpts_active == 0) || (hpts->p_wheel_complete)) {
860 /*
861 * A sleeping hpts we want in next slot to run
862 * note that in this state p_prev_slot == p_cur_slot
863 */
864 tp->t_hpts_slot = hpts_slot(hpts->p_prev_slot, 1);
865 if ((hpts->p_on_min_sleep == 0) &&
866 (hpts->p_hpts_active == 0))
867 need_wakeup = true;
868 } else
869 tp->t_hpts_slot = hpts->p_runningslot;
870 if (__predict_true(tp->t_in_hpts != IHPTS_MOVING))
871 tcp_hpts_insert_internal(tp, hpts);
872 if (need_wakeup) {
873 /*
874 * Activate the hpts if it is sleeping and its
875 * timeout is not 1.
876 */
877 hpts->p_direct_wake = 1;
878 tcp_hpts_wake(hpts);
879 }
880 HPTS_UNLOCK(hpts);
881
882 return;
883 }
884 /* Get the current time stamp and map it onto the wheel */
885 wheel_cts = tcp_tv_to_usec(&tv);
886 wheel_slot = cts_to_wheel(wheel_cts);
887 /* Now what's the max we can place it at? */
888 maxslots = max_slots_available(hpts, wheel_slot, &last_slot);
889 if (diag) {
890 diag->wheel_slot = wheel_slot;
891 diag->maxslots = maxslots;
892 diag->wheel_cts = wheel_cts;
893 }
894 if (maxslots == 0) {
895 /* The pacer is in a wheel wrap behind, yikes! */
896 if (slot > 1) {
897 /*
898 * Reduce by 1 to prevent a forever loop in
899 * case something else is wrong. Note this
900 * probably does not hurt because the pacer
901 * if its true is so far behind we will be
902 * > 1second late calling anyway.
903 */
904 slot--;
905 }
906 tp->t_hpts_slot = last_slot;
907 tp->t_hpts_request = slot;
908 } else if (maxslots >= slot) {
909 /* It all fits on the wheel */
910 tp->t_hpts_request = 0;
911 tp->t_hpts_slot = hpts_slot(wheel_slot, slot);
912 } else {
913 /* It does not fit */
914 tp->t_hpts_request = slot - maxslots;
915 tp->t_hpts_slot = last_slot;
916 }
917 if (diag) {
918 diag->time_remaining = tp->t_hpts_request;
919 diag->inp_hptsslot = tp->t_hpts_slot;
920 }
921 #ifdef INVARIANTS
922 check_if_slot_would_be_wrong(hpts, tp, tp->t_hpts_slot);
923 #endif
924 if (__predict_true(tp->t_in_hpts != IHPTS_MOVING))
925 tcp_hpts_insert_internal(tp, hpts);
926 if ((hpts->p_hpts_active == 0) &&
927 (tp->t_hpts_request == 0) &&
928 (hpts->p_on_min_sleep == 0)) {
929 /*
930 * The hpts is sleeping and NOT on a minimum
931 * sleep time, we need to figure out where
932 * it will wake up at and if we need to reschedule
933 * its time-out.
934 */
935 uint32_t have_slept, yet_to_sleep;
936
937 /* Now do we need to restart the hpts's timer? */
938 have_slept = hpts_slots_diff(hpts->p_prev_slot, wheel_slot);
939 if (have_slept < hpts->p_hpts_sleep_time)
940 yet_to_sleep = hpts->p_hpts_sleep_time - have_slept;
941 else {
942 /* We are over-due */
943 yet_to_sleep = 0;
944 need_wakeup = 1;
945 }
946 if (diag) {
947 diag->have_slept = have_slept;
948 diag->yet_to_sleep = yet_to_sleep;
949 }
950 if (yet_to_sleep &&
951 (yet_to_sleep > slot)) {
952 /*
953 * We need to reschedule the hpts's time-out.
954 */
955 hpts->p_hpts_sleep_time = slot;
956 need_new_to = slot * HPTS_USECS_PER_SLOT;
957 }
958 }
959 /*
960 * Now how far is the hpts sleeping to? if active is 1, its
961 * up and running we do nothing, otherwise we may need to
962 * reschedule its callout if need_new_to is set from above.
963 */
964 if (need_wakeup) {
965 hpts->p_direct_wake = 1;
966 tcp_hpts_wake(hpts);
967 if (diag) {
968 diag->need_new_to = 0;
969 diag->co_ret = 0xffff0000;
970 }
971 } else if (need_new_to) {
972 int32_t co_ret;
973 struct timeval tv;
974
975 tv.tv_sec = 0;
976 tv.tv_usec = 0;
977 while (need_new_to > HPTS_USEC_IN_SEC) {
978 tv.tv_sec++;
979 need_new_to -= HPTS_USEC_IN_SEC;
980 }
981 tv.tv_usec = need_new_to; /* XXX: Why is this sleeping over the max? */
982 co_ret = tcp_hpts_sleep(hpts, &tv);
983 if (diag) {
984 diag->need_new_to = need_new_to;
985 diag->co_ret = co_ret;
986 }
987 }
988 HPTS_UNLOCK(hpts);
989 }
990
991 static uint16_t
hpts_cpuid(struct tcp_hptsi * pace,struct tcpcb * tp,int * failed)992 hpts_cpuid(struct tcp_hptsi *pace, struct tcpcb *tp, int *failed)
993 {
994 struct inpcb *inp = tptoinpcb(tp);
995 u_int cpuid;
996 #ifdef NUMA
997 struct hpts_domain_info *di;
998 #endif
999
1000 *failed = 0;
1001 if (tp->t_flags2 & TF2_HPTS_CPU_SET) {
1002 return (tp->t_hpts_cpu);
1003 }
1004 /*
1005 * If we are using the irq cpu set by LRO or
1006 * the driver then it overrides all other domains.
1007 */
1008 if (tcp_use_irq_cpu) {
1009 if (tp->t_lro_cpu == HPTS_CPU_NONE) {
1010 *failed = 1;
1011 return (0);
1012 }
1013 return (tp->t_lro_cpu);
1014 }
1015 /* If one is set the other must be the same */
1016 #ifdef RSS
1017 cpuid = rss_hash2cpuid(inp->inp_flowid, inp->inp_flowtype);
1018 if (cpuid == NETISR_CPUID_NONE)
1019 return (tcp_hptsi_random_cpu(pace));
1020 else
1021 return (cpuid);
1022 #endif
1023 /*
1024 * We don't have a flowid -> cpuid mapping, so cheat and just map
1025 * unknown cpuids to curcpu. Not the best, but apparently better
1026 * than defaulting to swi 0.
1027 */
1028 if (inp->inp_flowtype == M_HASHTYPE_NONE) {
1029 counter_u64_add(cpu_uses_random, 1);
1030 return (tcp_hptsi_random_cpu(pace));
1031 }
1032 /*
1033 * Hash to a thread based on the flowid. If we are using numa,
1034 * then restrict the hash to the numa domain where the inp lives.
1035 */
1036
1037 #ifdef NUMA
1038 if ((vm_ndomains == 1) ||
1039 (inp->inp_numa_domain == M_NODOM)) {
1040 #endif
1041 cpuid = inp->inp_flowid % mp_ncpus;
1042 #ifdef NUMA
1043 } else {
1044 /* Hash into the cpu's that use that domain */
1045 di = &pace->domains[inp->inp_numa_domain];
1046 cpuid = di->cpu[inp->inp_flowid % di->count];
1047 }
1048 #endif
1049 counter_u64_add(cpu_uses_flowid, 1);
1050 return (cpuid);
1051 }
1052
1053 static void
tcp_hpts_set_max_sleep(struct tcp_hpts_entry * hpts,int wrap_loop_cnt)1054 tcp_hpts_set_max_sleep(struct tcp_hpts_entry *hpts, int wrap_loop_cnt)
1055 {
1056 uint32_t t = 0, i;
1057
1058 if ((hpts->p_on_queue_cnt) && (wrap_loop_cnt < 2)) {
1059 /*
1060 * Find next slot that is occupied and use that to
1061 * be the sleep time.
1062 */
1063 for (i = 0, t = hpts_slot(hpts->p_cur_slot, 1); i < NUM_OF_HPTSI_SLOTS; i++) {
1064 if (TAILQ_EMPTY(&hpts->p_hptss[t].head) == 0) {
1065 break;
1066 }
1067 t = (t + 1) % NUM_OF_HPTSI_SLOTS;
1068 }
1069 KASSERT((i != NUM_OF_HPTSI_SLOTS), ("Hpts:%p cnt:%d but none found", hpts, hpts->p_on_queue_cnt));
1070 hpts->p_hpts_sleep_time = min((i + 1), hpts_sleep_max);
1071 } else {
1072 /* No one on the wheel sleep for all but 400 slots or sleep max */
1073 hpts->p_hpts_sleep_time = hpts_sleep_max;
1074 }
1075 }
1076
1077 static bool
tcp_hpts_different_slots(uint32_t cts,uint32_t cts_last_run)1078 tcp_hpts_different_slots(uint32_t cts, uint32_t cts_last_run)
1079 {
1080 return ((cts / HPTS_USECS_PER_SLOT) != (cts_last_run / HPTS_USECS_PER_SLOT));
1081 }
1082
1083 int32_t
tcp_hptsi(struct tcp_hpts_entry * hpts,bool from_callout)1084 tcp_hptsi(struct tcp_hpts_entry *hpts, bool from_callout)
1085 {
1086 struct tcp_hptsi *pace;
1087 struct tcpcb *tp;
1088 struct timeval tv;
1089 int32_t slots_to_run, i, error;
1090 int32_t loop_cnt = 0;
1091 int32_t did_prefetch = 0;
1092 int32_t prefetch_tp = 0;
1093 int32_t wrap_loop_cnt = 0;
1094 int32_t slot_pos_of_endpoint = 0;
1095 int32_t orig_exit_slot;
1096 uint32_t cts, cts_last_run;
1097 bool completed_measure, seen_endpoint;
1098
1099 completed_measure = false;
1100 seen_endpoint = false;
1101
1102 HPTS_MTX_ASSERT(hpts);
1103 NET_EPOCH_ASSERT();
1104
1105 pace = hpts->p_hptsi;
1106 MPASS(pace != NULL);
1107
1108 /* record previous info for any logging */
1109 hpts->saved_curslot = hpts->p_cur_slot;
1110 hpts->saved_prev_slot = hpts->p_prev_slot;
1111
1112 microuptime(&tv);
1113 cts_last_run = pace->cts_last_ran[hpts->p_cpu];
1114 pace->cts_last_ran[hpts->p_cpu] = cts = tcp_tv_to_usec(&tv);
1115
1116 orig_exit_slot = hpts->p_cur_slot = cts_to_wheel(cts);
1117 if ((hpts->p_on_queue_cnt == 0) ||
1118 !tcp_hpts_different_slots(cts, cts_last_run)) {
1119 /*
1120 * Not enough time has yet passed or nothing to do.
1121 */
1122 hpts->p_prev_slot = hpts->p_cur_slot;
1123 goto no_run;
1124 }
1125 again:
1126 hpts->p_wheel_complete = 0;
1127 HPTS_MTX_ASSERT(hpts);
1128 slots_to_run = hpts_slots_diff(hpts->p_prev_slot, hpts->p_cur_slot);
1129 if ((hpts->p_on_queue_cnt != 0) &&
1130 ((cts - cts_last_run) >
1131 ((NUM_OF_HPTSI_SLOTS-1) * HPTS_USECS_PER_SLOT))) {
1132 /*
1133 * Wheel wrap is occuring, basically we
1134 * are behind and the distance between
1135 * run's has spread so much it has exceeded
1136 * the time on the wheel (1.024 seconds). This
1137 * is ugly and should NOT be happening. We
1138 * need to run the entire wheel. We last processed
1139 * p_prev_slot, so that needs to be the last slot
1140 * we run. The next slot after that should be our
1141 * reserved first slot for new, and then starts
1142 * the running position. Now the problem is the
1143 * reserved "not to yet" place does not exist
1144 * and there may be inp's in there that need
1145 * running. We can merge those into the
1146 * first slot at the head.
1147 */
1148 wrap_loop_cnt++;
1149 hpts->p_nxt_slot = hpts_slot(hpts->p_prev_slot, 1);
1150 hpts->p_runningslot = hpts_slot(hpts->p_prev_slot, 2);
1151 /*
1152 * Adjust p_cur_slot to be where we are starting from
1153 * hopefully we will catch up (fat chance if something
1154 * is broken this bad :( )
1155 */
1156 hpts->p_cur_slot = hpts->p_prev_slot;
1157 /*
1158 * The next slot has guys to run too, and that would
1159 * be where we would normally start, lets move them into
1160 * the next slot (p_prev_slot + 2) so that we will
1161 * run them, the extra 10usecs of late (by being
1162 * put behind) does not really matter in this situation.
1163 */
1164 TAILQ_FOREACH(tp, &hpts->p_hptss[hpts->p_nxt_slot].head,
1165 t_hpts) {
1166 MPASS(tp->t_hpts_slot == hpts->p_nxt_slot);
1167 MPASS(tp->t_hpts_gencnt ==
1168 hpts->p_hptss[hpts->p_nxt_slot].gencnt);
1169 MPASS(tp->t_in_hpts == IHPTS_ONQUEUE);
1170
1171 /*
1172 * Update gencnt and nextslot accordingly to match
1173 * the new location. This is safe since it takes both
1174 * the INP lock and the pacer mutex to change the
1175 * t_hptsslot and t_hpts_gencnt.
1176 */
1177 tp->t_hpts_gencnt =
1178 hpts->p_hptss[hpts->p_runningslot].gencnt;
1179 tp->t_hpts_slot = hpts->p_runningslot;
1180 }
1181 TAILQ_CONCAT(&hpts->p_hptss[hpts->p_runningslot].head,
1182 &hpts->p_hptss[hpts->p_nxt_slot].head, t_hpts);
1183 hpts->p_hptss[hpts->p_runningslot].count +=
1184 hpts->p_hptss[hpts->p_nxt_slot].count;
1185 hpts->p_hptss[hpts->p_nxt_slot].count = 0;
1186 hpts->p_hptss[hpts->p_nxt_slot].gencnt++;
1187 slots_to_run = NUM_OF_HPTSI_SLOTS - 1;
1188 counter_u64_add(wheel_wrap, 1);
1189 } else {
1190 /*
1191 * Nxt slot is always one after p_runningslot though
1192 * its not used usually unless we are doing wheel wrap.
1193 */
1194 hpts->p_nxt_slot = hpts->p_prev_slot;
1195 hpts->p_runningslot = hpts_slot(hpts->p_prev_slot, 1);
1196 }
1197 if (hpts->p_on_queue_cnt == 0) {
1198 goto no_one;
1199 }
1200 for (i = 0; i < slots_to_run; i++) {
1201 struct tcpcb *tp, *ntp;
1202 TAILQ_HEAD(, tcpcb) head = TAILQ_HEAD_INITIALIZER(head);
1203 struct hptsh *hptsh;
1204 uint32_t runningslot;
1205
1206 /*
1207 * Calculate our delay, if there are no extra slots there
1208 * was not any (i.e. if slots_to_run == 1, no delay).
1209 */
1210 hpts->p_delayed_by = (slots_to_run - (i + 1)) *
1211 HPTS_USECS_PER_SLOT;
1212
1213 runningslot = hpts->p_runningslot;
1214 hptsh = &hpts->p_hptss[runningslot];
1215 TAILQ_SWAP(&head, &hptsh->head, tcpcb, t_hpts);
1216 hpts->p_on_queue_cnt -= hptsh->count;
1217 hptsh->count = 0;
1218 hptsh->gencnt++;
1219
1220 HPTS_UNLOCK(hpts);
1221
1222 TAILQ_FOREACH_SAFE(tp, &head, t_hpts, ntp) {
1223 struct inpcb *inp = tptoinpcb(tp);
1224 bool set_cpu;
1225
1226 if (ntp != NULL) {
1227 /*
1228 * If we have a next tcpcb, see if we can
1229 * prefetch it. Note this may seem
1230 * "risky" since we have no locks (other
1231 * than the previous inp) and there no
1232 * assurance that ntp was not pulled while
1233 * we were processing tp and freed. If this
1234 * occurred it could mean that either:
1235 *
1236 * a) Its NULL (which is fine we won't go
1237 * here) <or> b) Its valid (which is cool we
1238 * will prefetch it) <or> c) The inp got
1239 * freed back to the slab which was
1240 * reallocated. Then the piece of memory was
1241 * re-used and something else (not an
1242 * address) is in inp_ppcb. If that occurs
1243 * we don't crash, but take a TLB shootdown
1244 * performance hit (same as if it was NULL
1245 * and we tried to pre-fetch it).
1246 *
1247 * Considering that the likelyhood of <c> is
1248 * quite rare we will take a risk on doing
1249 * this. If performance drops after testing
1250 * we can always take this out. NB: the
1251 * kern_prefetch on amd64 actually has
1252 * protection against a bad address now via
1253 * the DMAP_() tests. This will prevent the
1254 * TLB hit, and instead if <c> occurs just
1255 * cause us to load cache with a useless
1256 * address (to us).
1257 *
1258 * XXXGL: this comment and the prefetch action
1259 * could be outdated after tp == inp change.
1260 */
1261 kern_prefetch(ntp, &prefetch_tp);
1262 prefetch_tp = 1;
1263 }
1264
1265 /* For debugging */
1266 if (!seen_endpoint) {
1267 seen_endpoint = true;
1268 orig_exit_slot = slot_pos_of_endpoint =
1269 runningslot;
1270 } else if (!completed_measure) {
1271 /* Record the new position */
1272 orig_exit_slot = runningslot;
1273 }
1274
1275 INP_WLOCK(inp);
1276 if ((tp->t_flags2 & TF2_HPTS_CPU_SET) == 0) {
1277 set_cpu = true;
1278 } else {
1279 set_cpu = false;
1280 }
1281
1282 if (__predict_false(tp->t_in_hpts == IHPTS_MOVING)) {
1283 if (tp->t_hpts_slot == -1) {
1284 tp->t_in_hpts = IHPTS_NONE;
1285 if (in_pcbrele_wlocked(inp) == false)
1286 INP_WUNLOCK(inp);
1287 } else {
1288 HPTS_LOCK(hpts);
1289 tcp_hpts_insert_internal(tp, hpts);
1290 HPTS_UNLOCK(hpts);
1291 INP_WUNLOCK(inp);
1292 }
1293 continue;
1294 }
1295
1296 MPASS(tp->t_in_hpts == IHPTS_ONQUEUE);
1297 MPASS(!(tp->t_flags & TF_DISCONNECTED));
1298 KASSERT(runningslot == tp->t_hpts_slot,
1299 ("Hpts:%p inp:%p slot mis-aligned %u vs %u",
1300 hpts, inp, runningslot, tp->t_hpts_slot));
1301
1302 if (tp->t_hpts_request) {
1303 /*
1304 * This guy is deferred out further in time
1305 * then our wheel had available on it.
1306 * Push him back on the wheel or run it
1307 * depending.
1308 */
1309 uint32_t maxslots, last_slot, remaining_slots;
1310
1311 remaining_slots = slots_to_run - (i + 1);
1312 if (tp->t_hpts_request > remaining_slots) {
1313 HPTS_LOCK(hpts);
1314 /*
1315 * How far out can we go?
1316 */
1317 maxslots = max_slots_available(hpts,
1318 hpts->p_cur_slot, &last_slot);
1319 if (maxslots >= tp->t_hpts_request) {
1320 /* We can place it finally to
1321 * be processed. */
1322 tp->t_hpts_slot = hpts_slot(
1323 hpts->p_runningslot,
1324 tp->t_hpts_request);
1325 tp->t_hpts_request = 0;
1326 } else {
1327 /* Work off some more time */
1328 tp->t_hpts_slot = last_slot;
1329 tp->t_hpts_request -=
1330 maxslots;
1331 }
1332 tcp_hpts_insert_internal(tp, hpts);
1333 HPTS_UNLOCK(hpts);
1334 INP_WUNLOCK(inp);
1335 continue;
1336 }
1337 tp->t_hpts_request = 0;
1338 /* Fall through we will so do it now */
1339 }
1340
1341 tcp_hpts_release(tp);
1342 if (set_cpu) {
1343 /*
1344 * Setup so the next time we will move to
1345 * the right CPU. This should be a rare
1346 * event. It will sometimes happens when we
1347 * are the client side (usually not the
1348 * server). Somehow tcp_output() gets called
1349 * before the tcp_do_segment() sets the
1350 * intial state. This means the r_cpu and
1351 * r_hpts_cpu is 0. We get on the hpts, and
1352 * then tcp_input() gets called setting up
1353 * the r_cpu to the correct value. The hpts
1354 * goes off and sees the mis-match. We
1355 * simply correct it here and the CPU will
1356 * switch to the new hpts nextime the tcb
1357 * gets added to the hpts (not this one)
1358 * :-)
1359 */
1360 __tcp_set_hpts(pace, tp);
1361 }
1362 CURVNET_SET(inp->inp_socket->so_vnet);
1363 /* Lets do any logging that we might want to */
1364 tcp_hpts_log(hpts, tp, &tv, slots_to_run, i, from_callout);
1365
1366 if (tp->t_fb_ptr != NULL) {
1367 kern_prefetch(tp->t_fb_ptr, &did_prefetch);
1368 did_prefetch = 1;
1369 }
1370 /*
1371 * We set TF2_HPTS_CALLS before any possible output.
1372 * The contract with the transport is that if it cares
1373 * about hpts calling it should clear the flag. That
1374 * way next time it is called it will know it is hpts.
1375 *
1376 * We also only call tfb_do_queued_segments() <or>
1377 * tcp_output(). It is expected that if segments are
1378 * queued and come in that the final input mbuf will
1379 * cause a call to output if it is needed so we do
1380 * not need a second call to tcp_output(). So we do
1381 * one or the other but not both.
1382 *
1383 * XXXGL: some KPI abuse here. tfb_do_queued_segments
1384 * returns unlocked with positive error (always 1) and
1385 * tcp_output returns unlocked with negative error.
1386 */
1387 tp->t_flags2 |= TF2_HPTS_CALLS;
1388 if ((tp->t_flags2 & TF2_SUPPORTS_MBUFQ) &&
1389 !STAILQ_EMPTY(&tp->t_inqueue))
1390 error = -(*tp->t_fb->tfb_do_queued_segments)(tp,
1391 0);
1392 else
1393 error = tcp_output(tp);
1394 if (__predict_true(error >= 0))
1395 INP_WUNLOCK(inp);
1396 CURVNET_RESTORE();
1397 }
1398 if (seen_endpoint) {
1399 /*
1400 * We now have a accurate distance between
1401 * slot_pos_of_endpoint <-> orig_exit_slot
1402 * to tell us how late we were, orig_exit_slot
1403 * is where we calculated the end of our cycle to
1404 * be when we first entered.
1405 */
1406 completed_measure = true;
1407 }
1408 HPTS_LOCK(hpts);
1409 hpts->p_runningslot++;
1410 if (hpts->p_runningslot >= NUM_OF_HPTSI_SLOTS) {
1411 hpts->p_runningslot = 0;
1412 }
1413 }
1414 no_one:
1415 HPTS_MTX_ASSERT(hpts);
1416 hpts->p_delayed_by = 0;
1417 /*
1418 * Check to see if we took an excess amount of time and need to run
1419 * more slots (if we did not hit eno-bufs).
1420 */
1421 hpts->p_prev_slot = hpts->p_cur_slot;
1422 microuptime(&tv);
1423 cts_last_run = cts;
1424 cts = tcp_tv_to_usec(&tv);
1425 if (!from_callout || (loop_cnt > max_pacer_loops)) {
1426 /*
1427 * Something is serious slow we have
1428 * looped through processing the wheel
1429 * and by the time we cleared the
1430 * needs to run max_pacer_loops time
1431 * we still needed to run. That means
1432 * the system is hopelessly behind and
1433 * can never catch up :(
1434 *
1435 * We will just lie to this thread
1436 * and let it think p_curslot is
1437 * correct. When it next awakens
1438 * it will find itself further behind.
1439 */
1440 if (from_callout)
1441 counter_u64_add(hpts_hopelessly_behind, 1);
1442 goto no_run;
1443 }
1444
1445 hpts->p_cur_slot = cts_to_wheel(cts);
1446 if (!seen_endpoint) {
1447 /* We saw no endpoint but we may be looping */
1448 orig_exit_slot = hpts->p_cur_slot;
1449 }
1450 if ((wrap_loop_cnt < 2) && tcp_hpts_different_slots(cts, cts_last_run)) {
1451 counter_u64_add(hpts_loops, 1);
1452 loop_cnt++;
1453 goto again;
1454 }
1455 no_run:
1456 pace->cts_last_ran[hpts->p_cpu] = cts;
1457 /*
1458 * Set flag to tell that we are done for
1459 * any slot input that happens during
1460 * input.
1461 */
1462 hpts->p_wheel_complete = 1;
1463 /*
1464 * If enough time has elapsed that we should be processing the next
1465 * slot(s), then we should have kept running and not marked the wheel as
1466 * complete.
1467 *
1468 * But there are several other conditions where we would have stopped
1469 * processing, so the prev/cur slots and cts variables won't match.
1470 * These conditions are:
1471 *
1472 * - Calls not from callouts don't run multiple times
1473 * - The wheel is empty
1474 * - We've processed more than max_pacer_loops times
1475 * - We've wrapped more than 2 times
1476 *
1477 * This assert catches when the logic above has violated this design.
1478 *
1479 */
1480 KASSERT((!from_callout || (hpts->p_on_queue_cnt == 0) ||
1481 (loop_cnt > max_pacer_loops) || (wrap_loop_cnt >= 2) ||
1482 ((hpts->p_prev_slot == hpts->p_cur_slot) &&
1483 !tcp_hpts_different_slots(cts, cts_last_run))),
1484 ("H:%p Shouldn't be done! prev_slot:%u, cur_slot:%u, "
1485 "cts_last_run:%u, cts:%u, loop_cnt:%d, wrap_loop_cnt:%d",
1486 hpts, hpts->p_prev_slot, hpts->p_cur_slot,
1487 cts_last_run, cts, loop_cnt, wrap_loop_cnt));
1488
1489 if (from_callout && tcp_hpts_different_slots(cts, cts_last_run)) {
1490 microuptime(&tv);
1491 cts = tcp_tv_to_usec(&tv);
1492 hpts->p_cur_slot = cts_to_wheel(cts);
1493 counter_u64_add(hpts_loops, 1);
1494 goto again;
1495 }
1496
1497 if (from_callout) {
1498 tcp_hpts_set_max_sleep(hpts, wrap_loop_cnt);
1499 }
1500 if (seen_endpoint)
1501 return(hpts_slots_diff(slot_pos_of_endpoint, orig_exit_slot));
1502 else
1503 return (0);
1504 }
1505
1506 void
__tcp_set_hpts(struct tcp_hptsi * pace,struct tcpcb * tp)1507 __tcp_set_hpts(struct tcp_hptsi *pace, struct tcpcb *tp)
1508 {
1509 struct tcp_hpts_entry *hpts;
1510 int failed;
1511
1512 INP_WLOCK_ASSERT(tptoinpcb(tp));
1513
1514 hpts = tcp_hpts_lock(pace, tp);
1515 if (tp->t_in_hpts == IHPTS_NONE && !(tp->t_flags2 & TF2_HPTS_CPU_SET)) {
1516 tp->t_hpts_cpu = hpts_cpuid(pace, tp, &failed);
1517 if (failed == 0)
1518 tp->t_flags2 |= TF2_HPTS_CPU_SET;
1519 }
1520 HPTS_UNLOCK(hpts);
1521 }
1522
1523 static struct tcp_hpts_entry *
tcp_choose_hpts_to_run(struct tcp_hptsi * pace)1524 tcp_choose_hpts_to_run(struct tcp_hptsi *pace)
1525 {
1526 struct timeval tv;
1527 int i, oldest_idx, start, end;
1528 uint32_t cts, time_since_ran, calc;
1529
1530 microuptime(&tv);
1531 cts = tcp_tv_to_usec(&tv);
1532 time_since_ran = 0;
1533 /* Default is all one group */
1534 start = 0;
1535 end = pace->rp_num_hptss;
1536 /*
1537 * If we have more than one L3 group figure out which one
1538 * this CPU is in.
1539 */
1540 if (pace->grp_cnt > 1) {
1541 for (i = 0; i < pace->grp_cnt; i++) {
1542 if (CPU_ISSET(curcpu, &pace->grps[i]->cg_mask)) {
1543 start = pace->grps[i]->cg_first;
1544 end = (pace->grps[i]->cg_last + 1);
1545 break;
1546 }
1547 }
1548 }
1549 oldest_idx = -1;
1550 for (i = start; i < end; i++) {
1551 if (TSTMP_GT(cts, pace->cts_last_ran[i]))
1552 calc = cts - pace->cts_last_ran[i];
1553 else
1554 calc = 0;
1555 if (calc > time_since_ran) {
1556 oldest_idx = i;
1557 time_since_ran = calc;
1558 }
1559 }
1560 if (oldest_idx >= 0)
1561 return(pace->rp_ent[oldest_idx]);
1562 else
1563 return(pace->rp_ent[(curcpu % pace->rp_num_hptss)]);
1564 }
1565
1566 void
_tcp_hpts_softclock(void)1567 _tcp_hpts_softclock(void)
1568 {
1569 struct epoch_tracker et;
1570 struct tcp_hpts_entry *hpts;
1571 int slots_ran;
1572
1573 if (hpts_that_need_softclock == 0)
1574 return;
1575
1576 hpts = tcp_choose_hpts_to_run(tcp_hptsi_pace);
1577
1578 if (hpts->p_hpts_active) {
1579 /* Already active */
1580 return;
1581 }
1582 if (!HPTS_TRYLOCK(hpts)) {
1583 /* Someone else got the lock */
1584 return;
1585 }
1586 NET_EPOCH_ENTER(et);
1587 if (hpts->p_hpts_active)
1588 goto out_with_mtx;
1589 hpts->syscall_cnt++;
1590 counter_u64_add(hpts_direct_call, 1);
1591 hpts->p_hpts_active = 1;
1592 slots_ran = tcp_hptsi(hpts, false);
1593 /* We may want to adjust the sleep values here */
1594 if (hpts->p_on_queue_cnt >= conn_cnt_thresh) {
1595 if (slots_ran > slots_indicate_less_sleep) {
1596 struct timeval tv;
1597
1598 hpts->p_mysleep.tv_usec /= 2;
1599 if (hpts->p_mysleep.tv_usec < dynamic_min_sleep)
1600 hpts->p_mysleep.tv_usec = dynamic_min_sleep;
1601 /* Reschedule with new to value */
1602 tcp_hpts_set_max_sleep(hpts, 0);
1603 tv.tv_sec = 0;
1604 tv.tv_usec = hpts->p_hpts_sleep_time * HPTS_USECS_PER_SLOT;
1605 /* Validate its in the right ranges */
1606 if (tv.tv_usec < hpts->p_mysleep.tv_usec) {
1607 hpts->overidden_sleep = tv.tv_usec;
1608 tv.tv_usec = hpts->p_mysleep.tv_usec;
1609 } else if (tv.tv_usec > dynamic_max_sleep) {
1610 /* Lets not let sleep get above this value */
1611 hpts->overidden_sleep = tv.tv_usec;
1612 tv.tv_usec = dynamic_max_sleep;
1613 }
1614 /*
1615 * In this mode the timer is a backstop to
1616 * all the lro_flushes so we use
1617 * the dynamic value and set the on_min_sleep
1618 * flag so we will not be awoken.
1619 */
1620 (void)tcp_hpts_sleep(hpts, &tv);
1621 } else if (slots_ran < slots_indicate_more_sleep) {
1622 /* For the further sleep, don't reschedule hpts */
1623 hpts->p_mysleep.tv_usec *= 2;
1624 if (hpts->p_mysleep.tv_usec > dynamic_max_sleep)
1625 hpts->p_mysleep.tv_usec = dynamic_max_sleep;
1626 }
1627 hpts->p_on_min_sleep = 1;
1628 }
1629 hpts->p_hpts_active = 0;
1630 out_with_mtx:
1631 HPTS_UNLOCK(hpts);
1632 NET_EPOCH_EXIT(et);
1633 }
1634
1635 static void
tcp_hpts_thread(void * ctx)1636 tcp_hpts_thread(void *ctx)
1637 {
1638 #ifdef TCP_HPTS_KTEST
1639 struct tcp_hptsi *pace;
1640 #endif
1641 struct tcp_hpts_entry *hpts;
1642 struct epoch_tracker et;
1643 struct timeval tv;
1644 int slots_ran;
1645
1646 hpts = (struct tcp_hpts_entry *)ctx;
1647 #ifdef TCP_HPTS_KTEST
1648 pace = hpts->p_hptsi;
1649 #endif
1650 HPTS_LOCK(hpts);
1651 if (hpts->p_direct_wake) {
1652 /* Signaled by input or output with low occupancy count. */
1653 _callout_stop_safe(&hpts->co, 0);
1654 counter_u64_add(hpts_direct_awakening, 1);
1655 } else {
1656 /* Timed out, the normal case. */
1657 counter_u64_add(hpts_wake_timeout, 1);
1658 if (callout_pending(&hpts->co) ||
1659 !callout_active(&hpts->co)) {
1660 HPTS_UNLOCK(hpts);
1661 return;
1662 }
1663 }
1664 callout_deactivate(&hpts->co);
1665 hpts->p_hpts_wake_scheduled = 0;
1666 NET_EPOCH_ENTER(et);
1667 if (hpts->p_hpts_active) {
1668 /*
1669 * We are active already. This means that a syscall
1670 * trap or LRO is running in behalf of hpts. In that case
1671 * we need to double our timeout since there seems to be
1672 * enough activity in the system that we don't need to
1673 * run as often (if we were not directly woken).
1674 */
1675 tv.tv_sec = 0;
1676 if (hpts->p_direct_wake == 0) {
1677 counter_u64_add(hpts_back_tosleep, 1);
1678 if (hpts->p_on_queue_cnt >= conn_cnt_thresh) {
1679 hpts->p_mysleep.tv_usec *= 2;
1680 if (hpts->p_mysleep.tv_usec > dynamic_max_sleep)
1681 hpts->p_mysleep.tv_usec = dynamic_max_sleep;
1682 tv.tv_usec = hpts->p_mysleep.tv_usec;
1683 hpts->p_on_min_sleep = 1;
1684 } else {
1685 /*
1686 * Here we have low count on the wheel, but
1687 * somehow we still collided with one of the
1688 * connections. Lets go back to sleep for a
1689 * min sleep time, but clear the flag so we
1690 * can be awoken by insert.
1691 */
1692 hpts->p_on_min_sleep = 0;
1693 tv.tv_usec = tcp_min_hptsi_time;
1694 }
1695 } else {
1696 /*
1697 * Directly woken most likely to reset the
1698 * callout time.
1699 */
1700 tv.tv_usec = hpts->p_mysleep.tv_usec;
1701 }
1702 goto back_to_sleep;
1703 }
1704 hpts->sleeping = 0;
1705 hpts->p_hpts_active = 1;
1706 slots_ran = tcp_hptsi(hpts, true);
1707 tv.tv_sec = 0;
1708 tv.tv_usec = hpts->p_hpts_sleep_time * HPTS_USECS_PER_SLOT;
1709 if ((hpts->p_on_queue_cnt > conn_cnt_thresh) && (hpts->hit_callout_thresh == 0)) {
1710 hpts->hit_callout_thresh = 1;
1711 atomic_add_int(&hpts_that_need_softclock, 1);
1712 } else if ((hpts->p_on_queue_cnt <= conn_cnt_thresh) && (hpts->hit_callout_thresh == 1)) {
1713 hpts->hit_callout_thresh = 0;
1714 atomic_subtract_int(&hpts_that_need_softclock, 1);
1715 }
1716 if (hpts->p_on_queue_cnt >= conn_cnt_thresh) {
1717 if(hpts->p_direct_wake == 0) {
1718 /*
1719 * Only adjust sleep time if we were
1720 * called from the callout i.e. direct_wake == 0.
1721 */
1722 if (slots_ran < slots_indicate_more_sleep) {
1723 hpts->p_mysleep.tv_usec *= 2;
1724 if (hpts->p_mysleep.tv_usec > dynamic_max_sleep)
1725 hpts->p_mysleep.tv_usec = dynamic_max_sleep;
1726 } else if (slots_ran > slots_indicate_less_sleep) {
1727 hpts->p_mysleep.tv_usec /= 2;
1728 if (hpts->p_mysleep.tv_usec < dynamic_min_sleep)
1729 hpts->p_mysleep.tv_usec = dynamic_min_sleep;
1730 }
1731 }
1732 if (tv.tv_usec < hpts->p_mysleep.tv_usec) {
1733 hpts->overidden_sleep = tv.tv_usec;
1734 tv.tv_usec = hpts->p_mysleep.tv_usec;
1735 } else if (tv.tv_usec > dynamic_max_sleep) {
1736 /* Lets not let sleep get above this value */
1737 hpts->overidden_sleep = tv.tv_usec;
1738 tv.tv_usec = dynamic_max_sleep;
1739 }
1740 /*
1741 * In this mode the timer is a backstop to
1742 * all the lro_flushes so we use
1743 * the dynamic value and set the on_min_sleep
1744 * flag so we will not be awoken.
1745 */
1746 hpts->p_on_min_sleep = 1;
1747 } else if (hpts->p_on_queue_cnt == 0) {
1748 /*
1749 * No one on the wheel, please wake us up
1750 * if you insert on the wheel.
1751 */
1752 hpts->p_on_min_sleep = 0;
1753 hpts->overidden_sleep = 0;
1754 } else {
1755 /*
1756 * We hit here when we have a low number of
1757 * clients on the wheel (our else clause).
1758 * We may need to go on min sleep, if we set
1759 * the flag we will not be awoken if someone
1760 * is inserted ahead of us. Clearing the flag
1761 * means we can be awoken. This is "old mode"
1762 * where the timer is what runs hpts mainly.
1763 */
1764 if (tv.tv_usec < tcp_min_hptsi_time) {
1765 /*
1766 * Yes on min sleep, which means
1767 * we cannot be awoken.
1768 */
1769 hpts->overidden_sleep = tv.tv_usec;
1770 tv.tv_usec = tcp_min_hptsi_time;
1771 hpts->p_on_min_sleep = 1;
1772 } else {
1773 /* Clear the min sleep flag */
1774 hpts->overidden_sleep = 0;
1775 hpts->p_on_min_sleep = 0;
1776 }
1777 }
1778 HPTS_MTX_ASSERT(hpts);
1779 hpts->p_hpts_active = 0;
1780 back_to_sleep:
1781 hpts->p_direct_wake = 0;
1782 (void)tcp_hpts_sleep(hpts, &tv);
1783 NET_EPOCH_EXIT(et);
1784 HPTS_UNLOCK(hpts);
1785 }
1786
1787 static int32_t
hpts_count_level(struct cpu_group * cg)1788 hpts_count_level(struct cpu_group *cg)
1789 {
1790 int32_t count_l3, i;
1791
1792 count_l3 = 0;
1793 if (cg->cg_level == CG_SHARE_L3)
1794 count_l3++;
1795 /* Walk all the children looking for L3 */
1796 for (i = 0; i < cg->cg_children; i++) {
1797 count_l3 += hpts_count_level(&cg->cg_child[i]);
1798 }
1799 return (count_l3);
1800 }
1801
1802 static void
hpts_gather_grps(struct cpu_group ** grps,int32_t * at,int32_t max,struct cpu_group * cg)1803 hpts_gather_grps(struct cpu_group **grps, int32_t *at, int32_t max, struct cpu_group *cg)
1804 {
1805 int32_t idx, i;
1806
1807 idx = *at;
1808 if (cg->cg_level == CG_SHARE_L3) {
1809 grps[idx] = cg;
1810 idx++;
1811 if (idx == max) {
1812 *at = idx;
1813 return;
1814 }
1815 }
1816 *at = idx;
1817 /* Walk all the children looking for L3 */
1818 for (i = 0; i < cg->cg_children; i++) {
1819 hpts_gather_grps(grps, at, max, &cg->cg_child[i]);
1820 }
1821 }
1822
1823 /*
1824 * Initialize a tcp_hptsi structure. This performs the core initialization
1825 * without starting threads.
1826 */
1827 struct tcp_hptsi*
tcp_hptsi_create(const struct tcp_hptsi_funcs * funcs,bool enable_sysctl)1828 tcp_hptsi_create(const struct tcp_hptsi_funcs *funcs, bool enable_sysctl)
1829 {
1830 struct tcp_hptsi *pace;
1831 struct cpu_group *cpu_top;
1832 uint32_t i, j, cts;
1833 int32_t count;
1834 size_t sz, asz;
1835 struct timeval tv;
1836 struct tcp_hpts_entry *hpts;
1837 char unit[16];
1838 uint32_t ncpus = mp_ncpus ? mp_ncpus : MAXCPU;
1839
1840 KASSERT(funcs != NULL, ("funcs is NULL"));
1841
1842 /* Allocate the main structure */
1843 pace = malloc(sizeof(struct tcp_hptsi), M_TCPHPTS, M_WAITOK | M_ZERO);
1844 if (pace == NULL)
1845 return (NULL);
1846
1847 memset(pace, 0, sizeof(*pace));
1848 pace->funcs = funcs;
1849
1850 /* Setup CPU topology information */
1851 #ifdef SMP
1852 cpu_top = smp_topo();
1853 #else
1854 cpu_top = NULL;
1855 #endif
1856 pace->rp_num_hptss = ncpus;
1857
1858 /* Allocate hpts entry array */
1859 sz = (pace->rp_num_hptss * sizeof(struct tcp_hpts_entry *));
1860 pace->rp_ent = malloc(sz, M_TCPHPTS, M_WAITOK | M_ZERO);
1861
1862 /* Allocate timestamp tracking array */
1863 sz = (sizeof(uint32_t) * pace->rp_num_hptss);
1864 pace->cts_last_ran = malloc(sz, M_TCPHPTS, M_WAITOK);
1865
1866 /* Setup CPU groups */
1867 if (cpu_top == NULL) {
1868 pace->grp_cnt = 1;
1869 } else {
1870 /* Find out how many cache level 3 domains we have */
1871 count = 0;
1872 pace->grp_cnt = hpts_count_level(cpu_top);
1873 if (pace->grp_cnt == 0) {
1874 pace->grp_cnt = 1;
1875 }
1876 sz = (pace->grp_cnt * sizeof(struct cpu_group *));
1877 pace->grps = malloc(sz, M_TCPHPTS, M_WAITOK);
1878 /* Now populate the groups */
1879 if (pace->grp_cnt == 1) {
1880 /*
1881 * All we need is the top level all cpu's are in
1882 * the same cache so when we use grp[0]->cg_mask
1883 * with the cg_first <-> cg_last it will include
1884 * all cpu's in it. The level here is probably
1885 * zero which is ok.
1886 */
1887 pace->grps[0] = cpu_top;
1888 } else {
1889 /*
1890 * Here we must find all the level three cache domains
1891 * and setup our pointers to them.
1892 */
1893 count = 0;
1894 hpts_gather_grps(pace->grps, &count, pace->grp_cnt, cpu_top);
1895 }
1896 }
1897
1898 /* Cache the current time for initializing the hpts entries */
1899 microuptime(&tv);
1900 cts = tcp_tv_to_usec(&tv);
1901
1902 /* Initialize each hpts entry */
1903 asz = sizeof(struct hptsh) * NUM_OF_HPTSI_SLOTS;
1904 for (i = 0; i < pace->rp_num_hptss; i++) {
1905 pace->rp_ent[i] = malloc(sizeof(struct tcp_hpts_entry),
1906 M_TCPHPTS, M_WAITOK | M_ZERO);
1907 pace->rp_ent[i]->p_hptss = malloc(asz, M_TCPHPTS,
1908 M_WAITOK | M_ZERO);
1909 hpts = pace->rp_ent[i];
1910
1911 /* Basic initialization */
1912 hpts->p_hpts_sleep_time = hpts_sleep_max;
1913 hpts->p_cpu = i;
1914 pace->cts_last_ran[i] = cts;
1915 hpts->p_cur_slot = cts_to_wheel(cts);
1916 hpts->p_prev_slot = hpts->p_cur_slot;
1917 hpts->p_nxt_slot = hpts_slot(hpts->p_cur_slot, 1);
1918 callout_init(&hpts->co, 1);
1919 hpts->p_hptsi = pace;
1920 mtx_init(&hpts->p_mtx, "tcp_hpts_lck", "hpts",
1921 MTX_DEF | MTX_DUPOK);
1922 for (j = 0; j < NUM_OF_HPTSI_SLOTS; j++) {
1923 TAILQ_INIT(&hpts->p_hptss[j].head);
1924 }
1925
1926 /* Setup SYSCTL if requested */
1927 if (enable_sysctl) {
1928 sysctl_ctx_init(&hpts->hpts_ctx);
1929 sprintf(unit, "%d", i);
1930 hpts->hpts_root = SYSCTL_ADD_NODE(&hpts->hpts_ctx,
1931 SYSCTL_STATIC_CHILDREN(_net_inet_tcp_hpts),
1932 OID_AUTO,
1933 unit,
1934 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1935 "");
1936 SYSCTL_ADD_INT(&hpts->hpts_ctx,
1937 SYSCTL_CHILDREN(hpts->hpts_root),
1938 OID_AUTO, "out_qcnt", CTLFLAG_RD,
1939 &hpts->p_on_queue_cnt, 0,
1940 "Count TCB's awaiting output processing");
1941 SYSCTL_ADD_U16(&hpts->hpts_ctx,
1942 SYSCTL_CHILDREN(hpts->hpts_root),
1943 OID_AUTO, "active", CTLFLAG_RD,
1944 &hpts->p_hpts_active, 0,
1945 "Is the hpts active");
1946 SYSCTL_ADD_UINT(&hpts->hpts_ctx,
1947 SYSCTL_CHILDREN(hpts->hpts_root),
1948 OID_AUTO, "curslot", CTLFLAG_RD,
1949 &hpts->p_cur_slot, 0,
1950 "What the current running pacers goal");
1951 SYSCTL_ADD_UINT(&hpts->hpts_ctx,
1952 SYSCTL_CHILDREN(hpts->hpts_root),
1953 OID_AUTO, "runslot", CTLFLAG_RD,
1954 &hpts->p_runningslot, 0,
1955 "What the running pacers current slot is");
1956 SYSCTL_ADD_UINT(&hpts->hpts_ctx,
1957 SYSCTL_CHILDREN(hpts->hpts_root),
1958 OID_AUTO, "lastran", CTLFLAG_RD,
1959 &pace->cts_last_ran[i], 0,
1960 "The last usec timestamp that this hpts ran");
1961 SYSCTL_ADD_LONG(&hpts->hpts_ctx,
1962 SYSCTL_CHILDREN(hpts->hpts_root),
1963 OID_AUTO, "cur_min_sleep", CTLFLAG_RD,
1964 &hpts->p_mysleep.tv_usec,
1965 "What the running pacers is using for p_mysleep.tv_usec");
1966 SYSCTL_ADD_U64(&hpts->hpts_ctx,
1967 SYSCTL_CHILDREN(hpts->hpts_root),
1968 OID_AUTO, "now_sleeping", CTLFLAG_RD,
1969 &hpts->sleeping, 0,
1970 "What the running pacers is actually sleeping for");
1971 SYSCTL_ADD_U64(&hpts->hpts_ctx,
1972 SYSCTL_CHILDREN(hpts->hpts_root),
1973 OID_AUTO, "syscall_cnt", CTLFLAG_RD,
1974 &hpts->syscall_cnt, 0,
1975 "How many times we had syscalls on this hpts");
1976 }
1977 }
1978
1979 return (pace);
1980 }
1981
1982 /*
1983 * Create threads for a tcp_hptsi structure and starts timers for the current
1984 * (minimum) sleep interval.
1985 */
1986 void
tcp_hptsi_start(struct tcp_hptsi * pace)1987 tcp_hptsi_start(struct tcp_hptsi *pace)
1988 {
1989 struct tcp_hpts_entry *hpts;
1990 struct pcpu *pc;
1991 struct timeval tv;
1992 uint32_t i, j;
1993 int count, domain;
1994 int error __diagused;
1995
1996 KASSERT(pace != NULL, ("tcp_hptsi_start: pace is NULL"));
1997
1998 /* Start threads for each hpts entry */
1999 for (i = 0; i < pace->rp_num_hptss; i++) {
2000 hpts = pace->rp_ent[i];
2001
2002 KASSERT(hpts->ie_cookie == NULL,
2003 ("tcp_hptsi_start: hpts[%d]->ie_cookie is not NULL", i));
2004
2005 error = swi_add(&hpts->ie, "hpts",
2006 tcp_hpts_thread, (void *)hpts,
2007 SWI_NET, INTR_MPSAFE, &hpts->ie_cookie);
2008 KASSERT(error == 0,
2009 ("Can't add hpts:%p i:%d err:%d", hpts, i, error));
2010
2011 if (tcp_bind_threads == 1) {
2012 (void)intr_event_bind(hpts->ie, i);
2013 } else if (tcp_bind_threads == 2) {
2014 /* Find the group for this CPU (i) and bind into it */
2015 for (j = 0; j < pace->grp_cnt; j++) {
2016 if (CPU_ISSET(i, &pace->grps[j]->cg_mask)) {
2017 if (intr_event_bind_ithread_cpuset(hpts->ie,
2018 &pace->grps[j]->cg_mask) == 0) {
2019 pc = pcpu_find(i);
2020 domain = pc->pc_domain;
2021 count = pace->domains[domain].count;
2022 pace->domains[domain].cpu[count] = i;
2023 pace->domains[domain].count++;
2024 break;
2025 }
2026 }
2027 }
2028 }
2029
2030 hpts->p_mysleep.tv_sec = 0;
2031 hpts->p_mysleep.tv_usec = tcp_min_hptsi_time;
2032 tv.tv_sec = 0;
2033 tv.tv_usec = hpts->p_hpts_sleep_time * HPTS_USECS_PER_SLOT;
2034 (void)tcp_hpts_sleep(hpts, &tv);
2035 }
2036 }
2037
2038 /*
2039 * Stop all callouts/threads for a tcp_hptsi structure.
2040 */
2041 void
tcp_hptsi_stop(struct tcp_hptsi * pace)2042 tcp_hptsi_stop(struct tcp_hptsi *pace)
2043 {
2044 struct tcp_hpts_entry *hpts;
2045 int rv __diagused;
2046 uint32_t i;
2047
2048 KASSERT(pace != NULL, ("tcp_hptsi_stop: pace is NULL"));
2049
2050 for (i = 0; i < pace->rp_num_hptss; i++) {
2051 hpts = pace->rp_ent[i];
2052 KASSERT(hpts != NULL, ("tcp_hptsi_stop: hpts[%d] is NULL", i));
2053 KASSERT(hpts->ie_cookie != NULL,
2054 ("tcp_hptsi_stop: hpts[%d]->ie_cookie is NULL", i));
2055
2056 rv = _callout_stop_safe(&hpts->co, CS_DRAIN);
2057 MPASS(rv != 0);
2058
2059 rv = swi_remove(hpts->ie_cookie);
2060 MPASS(rv == 0);
2061 hpts->ie_cookie = NULL;
2062 }
2063 }
2064
2065 /*
2066 * Destroy a tcp_hptsi structure initialized by tcp_hptsi_create.
2067 */
2068 void
tcp_hptsi_destroy(struct tcp_hptsi * pace)2069 tcp_hptsi_destroy(struct tcp_hptsi *pace)
2070 {
2071 struct tcp_hpts_entry *hpts;
2072 uint32_t i;
2073
2074 KASSERT(pace != NULL, ("tcp_hptsi_destroy: pace is NULL"));
2075 KASSERT(pace->rp_ent != NULL, ("tcp_hptsi_destroy: pace->rp_ent is NULL"));
2076
2077 /* Cleanup each hpts entry */
2078 for (i = 0; i < pace->rp_num_hptss; i++) {
2079 hpts = pace->rp_ent[i];
2080 if (hpts != NULL) {
2081 /* Cleanup SYSCTL if it was initialized */
2082 if (hpts->hpts_root != NULL) {
2083 sysctl_ctx_free(&hpts->hpts_ctx);
2084 }
2085
2086 mtx_destroy(&hpts->p_mtx);
2087 free(hpts->p_hptss, M_TCPHPTS);
2088 free(hpts, M_TCPHPTS);
2089 }
2090 }
2091
2092 /* Cleanup main arrays */
2093 free(pace->rp_ent, M_TCPHPTS);
2094 free(pace->cts_last_ran, M_TCPHPTS);
2095 #ifdef SMP
2096 free(pace->grps, M_TCPHPTS);
2097 #endif
2098
2099 /* Free the main structure */
2100 free(pace, M_TCPHPTS);
2101 }
2102
2103 static int
tcp_hpts_mod_load(void)2104 tcp_hpts_mod_load(void)
2105 {
2106 int i;
2107
2108 /* Don't try to bind to NUMA domains if we don't have any */
2109 if (vm_ndomains == 1 && tcp_bind_threads == 2)
2110 tcp_bind_threads = 0;
2111
2112 /* Create the tcp_hptsi structure */
2113 tcp_hptsi_pace = tcp_hptsi_create(&tcp_hptsi_default_funcs, true);
2114 if (tcp_hptsi_pace == NULL)
2115 return (ENOMEM);
2116
2117 /* Initialize global counters */
2118 hpts_hopelessly_behind = counter_u64_alloc(M_WAITOK);
2119 hpts_loops = counter_u64_alloc(M_WAITOK);
2120 back_tosleep = counter_u64_alloc(M_WAITOK);
2121 combined_wheel_wrap = counter_u64_alloc(M_WAITOK);
2122 wheel_wrap = counter_u64_alloc(M_WAITOK);
2123 hpts_wake_timeout = counter_u64_alloc(M_WAITOK);
2124 hpts_direct_awakening = counter_u64_alloc(M_WAITOK);
2125 hpts_back_tosleep = counter_u64_alloc(M_WAITOK);
2126 hpts_direct_call = counter_u64_alloc(M_WAITOK);
2127 cpu_uses_flowid = counter_u64_alloc(M_WAITOK);
2128 cpu_uses_random = counter_u64_alloc(M_WAITOK);
2129
2130 /* Start the threads */
2131 tcp_hptsi_start(tcp_hptsi_pace);
2132
2133 /* Initialize LRO HPTS */
2134 tcp_lro_hpts_init();
2135
2136 /*
2137 * If we somehow have an empty domain, fall back to choosing among all
2138 * HPTS threads.
2139 */
2140 for (i = 0; i < vm_ndomains; i++) {
2141 if (tcp_hptsi_pace->domains[i].count == 0) {
2142 tcp_bind_threads = 0;
2143 break;
2144 }
2145 }
2146
2147 printf("TCP HPTS started %u (%s) swi interrupt threads\n",
2148 tcp_hptsi_pace->rp_num_hptss, (tcp_bind_threads == 0) ?
2149 "(unbounded)" :
2150 (tcp_bind_threads == 1 ? "per-cpu" : "per-NUMA-domain"));
2151
2152 return (0);
2153 }
2154
2155 static void
tcp_hpts_mod_unload(void)2156 tcp_hpts_mod_unload(void)
2157 {
2158 tcp_lro_hpts_uninit();
2159
2160 tcp_hptsi_stop(tcp_hptsi_pace);
2161 tcp_hptsi_destroy(tcp_hptsi_pace);
2162 tcp_hptsi_pace = NULL;
2163
2164 /* Cleanup global counters */
2165 counter_u64_free(hpts_hopelessly_behind);
2166 counter_u64_free(hpts_loops);
2167 counter_u64_free(back_tosleep);
2168 counter_u64_free(combined_wheel_wrap);
2169 counter_u64_free(wheel_wrap);
2170 counter_u64_free(hpts_wake_timeout);
2171 counter_u64_free(hpts_direct_awakening);
2172 counter_u64_free(hpts_back_tosleep);
2173 counter_u64_free(hpts_direct_call);
2174 counter_u64_free(cpu_uses_flowid);
2175 counter_u64_free(cpu_uses_random);
2176 }
2177
2178 static int
tcp_hpts_mod_event(module_t mod,int what,void * arg)2179 tcp_hpts_mod_event(module_t mod, int what, void *arg)
2180 {
2181 switch (what) {
2182 case MOD_LOAD:
2183 return (tcp_hpts_mod_load());
2184 case MOD_QUIESCE:
2185 /*
2186 * Since we are a dependency of TCP stack modules, they should
2187 * already be unloaded, and the HPTS ring is empty. However,
2188 * function pointer manipulations aren't 100% safe.
2189 * Thus, allow only forced unload of HPTS.
2190 */
2191 return (EBUSY);
2192 case MOD_UNLOAD:
2193 tcp_hpts_mod_unload();
2194 return (0);
2195 default:
2196 return (EINVAL);
2197 };
2198 }
2199
2200 static moduledata_t tcp_hpts_module = {
2201 .name = "tcphpts",
2202 .evhand = tcp_hpts_mod_event,
2203 };
2204
2205 DECLARE_MODULE(tcphpts, tcp_hpts_module, SI_SUB_SOFTINTR, SI_ORDER_ANY);
2206 MODULE_VERSION(tcphpts, 1);
2207