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