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