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