xref: /freebsd/sys/netinet/tcp_hpts.c (revision 79059e0ec9b1d3273ce32fdd028802fcad4b85ab)
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) > (NUM_OF_HPTSI_SLOTS - 1)) &&
1167 	    (hpts->p_on_queue_cnt != 0)) {
1168 		/*
1169 		 * Wheel wrap is occuring, basically we
1170 		 * are behind and the distance between
1171 		 * run's has spread so much it has exceeded
1172 		 * the time on the wheel (1.024 seconds). This
1173 		 * is ugly and should NOT be happening. We
1174 		 * need to run the entire wheel. We last processed
1175 		 * p_prev_slot, so that needs to be the last slot
1176 		 * we run. The next slot after that should be our
1177 		 * reserved first slot for new, and then starts
1178 		 * the running position. Now the problem is the
1179 		 * reserved "not to yet" place does not exist
1180 		 * and there may be inp's in there that need
1181 		 * running. We can merge those into the
1182 		 * first slot at the head.
1183 		 */
1184 		wrap_loop_cnt++;
1185 		hpts->p_nxt_slot = hpts_slot(hpts->p_prev_slot, 1);
1186 		hpts->p_runningslot = hpts_slot(hpts->p_prev_slot, 2);
1187 		/*
1188 		 * Adjust p_cur_slot to be where we are starting from
1189 		 * hopefully we will catch up (fat chance if something
1190 		 * is broken this bad :( )
1191 		 */
1192 		hpts->p_cur_slot = hpts->p_prev_slot;
1193 		/*
1194 		 * The next slot has guys to run too, and that would
1195 		 * be where we would normally start, lets move them into
1196 		 * the next slot (p_prev_slot + 2) so that we will
1197 		 * run them, the extra 10usecs of late (by being
1198 		 * put behind) does not really matter in this situation.
1199 		 */
1200 		TAILQ_FOREACH(tp, &hpts->p_hptss[hpts->p_nxt_slot].head,
1201 		    t_hpts) {
1202 			MPASS(tp->t_hpts_slot == hpts->p_nxt_slot);
1203 			MPASS(tp->t_hpts_gencnt ==
1204 			    hpts->p_hptss[hpts->p_nxt_slot].gencnt);
1205 			MPASS(tp->t_in_hpts == IHPTS_ONQUEUE);
1206 
1207 			/*
1208 			 * Update gencnt and nextslot accordingly to match
1209 			 * the new location. This is safe since it takes both
1210 			 * the INP lock and the pacer mutex to change the
1211 			 * t_hptsslot and t_hpts_gencnt.
1212 			 */
1213 			tp->t_hpts_gencnt =
1214 			    hpts->p_hptss[hpts->p_runningslot].gencnt;
1215 			tp->t_hpts_slot = hpts->p_runningslot;
1216 		}
1217 		TAILQ_CONCAT(&hpts->p_hptss[hpts->p_runningslot].head,
1218 		    &hpts->p_hptss[hpts->p_nxt_slot].head, t_hpts);
1219 		hpts->p_hptss[hpts->p_runningslot].count +=
1220 		    hpts->p_hptss[hpts->p_nxt_slot].count;
1221 		hpts->p_hptss[hpts->p_nxt_slot].count = 0;
1222 		hpts->p_hptss[hpts->p_nxt_slot].gencnt++;
1223 		slots_to_run = NUM_OF_HPTSI_SLOTS - 1;
1224 		counter_u64_add(wheel_wrap, 1);
1225 	} else {
1226 		/*
1227 		 * Nxt slot is always one after p_runningslot though
1228 		 * its not used usually unless we are doing wheel wrap.
1229 		 */
1230 		hpts->p_nxt_slot = hpts->p_prev_slot;
1231 		hpts->p_runningslot = hpts_slot(hpts->p_prev_slot, 1);
1232 	}
1233 	if (hpts->p_on_queue_cnt == 0) {
1234 		goto no_one;
1235 	}
1236 	for (i = 0; i < slots_to_run; i++) {
1237 		struct tcpcb *tp, *ntp;
1238 		TAILQ_HEAD(, tcpcb) head = TAILQ_HEAD_INITIALIZER(head);
1239 		struct hptsh *hptsh;
1240 		uint32_t runningslot;
1241 
1242 		/*
1243 		 * Calculate our delay, if there are no extra ticks there
1244 		 * was not any (i.e. if slots_to_run == 1, no delay).
1245 		 */
1246 		hpts->p_delayed_by = (slots_to_run - (i + 1)) *
1247 		    HPTS_USECS_PER_SLOT;
1248 
1249 		runningslot = hpts->p_runningslot;
1250 		hptsh = &hpts->p_hptss[runningslot];
1251 		TAILQ_SWAP(&head, &hptsh->head, tcpcb, t_hpts);
1252 		hpts->p_on_queue_cnt -= hptsh->count;
1253 		hptsh->count = 0;
1254 		hptsh->gencnt++;
1255 
1256 		HPTS_UNLOCK(hpts);
1257 
1258 		TAILQ_FOREACH_SAFE(tp, &head, t_hpts, ntp) {
1259 			struct inpcb *inp = tptoinpcb(tp);
1260 			bool set_cpu;
1261 
1262 			if (ntp != NULL) {
1263 				/*
1264 				 * If we have a next tcpcb, see if we can
1265 				 * prefetch it. Note this may seem
1266 				 * "risky" since we have no locks (other
1267 				 * than the previous inp) and there no
1268 				 * assurance that ntp was not pulled while
1269 				 * we were processing tp and freed. If this
1270 				 * occurred it could mean that either:
1271 				 *
1272 				 * a) Its NULL (which is fine we won't go
1273 				 * here) <or> b) Its valid (which is cool we
1274 				 * will prefetch it) <or> c) The inp got
1275 				 * freed back to the slab which was
1276 				 * reallocated. Then the piece of memory was
1277 				 * re-used and something else (not an
1278 				 * address) is in inp_ppcb. If that occurs
1279 				 * we don't crash, but take a TLB shootdown
1280 				 * performance hit (same as if it was NULL
1281 				 * and we tried to pre-fetch it).
1282 				 *
1283 				 * Considering that the likelyhood of <c> is
1284 				 * quite rare we will take a risk on doing
1285 				 * this. If performance drops after testing
1286 				 * we can always take this out. NB: the
1287 				 * kern_prefetch on amd64 actually has
1288 				 * protection against a bad address now via
1289 				 * the DMAP_() tests. This will prevent the
1290 				 * TLB hit, and instead if <c> occurs just
1291 				 * cause us to load cache with a useless
1292 				 * address (to us).
1293 				 *
1294 				 * XXXGL: this comment and the prefetch action
1295 				 * could be outdated after tp == inp change.
1296 				 */
1297 				kern_prefetch(ntp, &prefetch_tp);
1298 				prefetch_tp = 1;
1299 			}
1300 
1301 			/* For debugging */
1302 			if (!seen_endpoint) {
1303 				seen_endpoint = true;
1304 				orig_exit_slot = slot_pos_of_endpoint =
1305 				    runningslot;
1306 			} else if (!completed_measure) {
1307 				/* Record the new position */
1308 				orig_exit_slot = runningslot;
1309 			}
1310 
1311 			INP_WLOCK(inp);
1312 			if ((tp->t_flags2 & TF2_HPTS_CPU_SET) == 0) {
1313 				set_cpu = true;
1314 			} else {
1315 				set_cpu = false;
1316 			}
1317 
1318 			if (__predict_false(tp->t_in_hpts == IHPTS_MOVING)) {
1319 				if (tp->t_hpts_slot == -1) {
1320 					tp->t_in_hpts = IHPTS_NONE;
1321 					if (in_pcbrele_wlocked(inp) == false)
1322 						INP_WUNLOCK(inp);
1323 				} else {
1324 					HPTS_LOCK(hpts);
1325 					tcp_hpts_insert_internal(tp, hpts);
1326 					HPTS_UNLOCK(hpts);
1327 					INP_WUNLOCK(inp);
1328 				}
1329 				continue;
1330 			}
1331 
1332 			MPASS(tp->t_in_hpts == IHPTS_ONQUEUE);
1333 			MPASS(!(inp->inp_flags & INP_DROPPED));
1334 			KASSERT(runningslot == tp->t_hpts_slot,
1335 				("Hpts:%p inp:%p slot mis-aligned %u vs %u",
1336 				 hpts, inp, runningslot, tp->t_hpts_slot));
1337 
1338 			if (tp->t_hpts_request) {
1339 				/*
1340 				 * This guy is deferred out further in time
1341 				 * then our wheel had available on it.
1342 				 * Push him back on the wheel or run it
1343 				 * depending.
1344 				 */
1345 				uint32_t maxslots, last_slot, remaining_slots;
1346 
1347 				remaining_slots = slots_to_run - (i + 1);
1348 				if (tp->t_hpts_request > remaining_slots) {
1349 					HPTS_LOCK(hpts);
1350 					/*
1351 					 * How far out can we go?
1352 					 */
1353 					maxslots = max_slots_available(hpts,
1354 					    hpts->p_cur_slot, &last_slot);
1355 					if (maxslots >= tp->t_hpts_request) {
1356 						/* We can place it finally to
1357 						 * be processed.  */
1358 						tp->t_hpts_slot = hpts_slot(
1359 						    hpts->p_runningslot,
1360 						    tp->t_hpts_request);
1361 						tp->t_hpts_request = 0;
1362 					} else {
1363 						/* Work off some more time */
1364 						tp->t_hpts_slot = last_slot;
1365 						tp->t_hpts_request -=
1366 						    maxslots;
1367 					}
1368 					tcp_hpts_insert_internal(tp, hpts);
1369 					HPTS_UNLOCK(hpts);
1370 					INP_WUNLOCK(inp);
1371 					continue;
1372 				}
1373 				tp->t_hpts_request = 0;
1374 				/* Fall through we will so do it now */
1375 			}
1376 
1377 			tcp_hpts_release(tp);
1378 			if (set_cpu) {
1379 				/*
1380 				 * Setup so the next time we will move to
1381 				 * the right CPU. This should be a rare
1382 				 * event. It will sometimes happens when we
1383 				 * are the client side (usually not the
1384 				 * server). Somehow tcp_output() gets called
1385 				 * before the tcp_do_segment() sets the
1386 				 * intial state. This means the r_cpu and
1387 				 * r_hpts_cpu is 0. We get on the hpts, and
1388 				 * then tcp_input() gets called setting up
1389 				 * the r_cpu to the correct value. The hpts
1390 				 * goes off and sees the mis-match. We
1391 				 * simply correct it here and the CPU will
1392 				 * switch to the new hpts nextime the tcb
1393 				 * gets added to the hpts (not this one)
1394 				 * :-)
1395 				 */
1396 				tcp_set_hpts(tp);
1397 			}
1398 			CURVNET_SET(inp->inp_vnet);
1399 			/* Lets do any logging that we might want to */
1400 			tcp_hpts_log(hpts, tp, &tv, slots_to_run, i, from_callout);
1401 
1402 			if (tp->t_fb_ptr != NULL) {
1403 				kern_prefetch(tp->t_fb_ptr, &did_prefetch);
1404 				did_prefetch = 1;
1405 			}
1406 			/*
1407 			 * We set TF2_HPTS_CALLS before any possible output.
1408 			 * The contract with the transport is that if it cares
1409 			 * about hpts calling it should clear the flag. That
1410 			 * way next time it is called it will know it is hpts.
1411 			 *
1412 			 * We also only call tfb_do_queued_segments() <or>
1413 			 * tcp_output().  It is expected that if segments are
1414 			 * queued and come in that the final input mbuf will
1415 			 * cause a call to output if it is needed so we do
1416 			 * not need a second call to tcp_output(). So we do
1417 			 * one or the other but not both.
1418 			 *
1419 			 * XXXGL: some KPI abuse here.  tfb_do_queued_segments
1420 			 * returns unlocked with positive error (always 1) and
1421 			 * tcp_output returns unlocked with negative error.
1422 			 */
1423 			tp->t_flags2 |= TF2_HPTS_CALLS;
1424 			if ((tp->t_flags2 & TF2_SUPPORTS_MBUFQ) &&
1425 			    !STAILQ_EMPTY(&tp->t_inqueue))
1426 				error = -(*tp->t_fb->tfb_do_queued_segments)(tp,
1427 				    0);
1428 			else
1429 				error = tcp_output(tp);
1430 			if (__predict_true(error >= 0))
1431 				INP_WUNLOCK(inp);
1432 			CURVNET_RESTORE();
1433 		}
1434 		if (seen_endpoint) {
1435 			/*
1436 			 * We now have a accurate distance between
1437 			 * slot_pos_of_endpoint <-> orig_exit_slot
1438 			 * to tell us how late we were, orig_exit_slot
1439 			 * is where we calculated the end of our cycle to
1440 			 * be when we first entered.
1441 			 */
1442 			completed_measure = true;
1443 		}
1444 		HPTS_LOCK(hpts);
1445 		hpts->p_runningslot++;
1446 		if (hpts->p_runningslot >= NUM_OF_HPTSI_SLOTS) {
1447 			hpts->p_runningslot = 0;
1448 		}
1449 	}
1450 no_one:
1451 	HPTS_MTX_ASSERT(hpts);
1452 	hpts->p_delayed_by = 0;
1453 	/*
1454 	 * Check to see if we took an excess amount of time and need to run
1455 	 * more ticks (if we did not hit eno-bufs).
1456 	 */
1457 	hpts->p_prev_slot = hpts->p_cur_slot;
1458 	hpts->p_lasttick = hpts->p_curtick;
1459 	if (!from_callout || (loop_cnt > max_pacer_loops)) {
1460 		/*
1461 		 * Something is serious slow we have
1462 		 * looped through processing the wheel
1463 		 * and by the time we cleared the
1464 		 * needs to run max_pacer_loops time
1465 		 * we still needed to run. That means
1466 		 * the system is hopelessly behind and
1467 		 * can never catch up :(
1468 		 *
1469 		 * We will just lie to this thread
1470 		 * and let it thing p_curtick is
1471 		 * correct. When it next awakens
1472 		 * it will find itself further behind.
1473 		 */
1474 		if (from_callout)
1475 			counter_u64_add(hpts_hopelessly_behind, 1);
1476 		goto no_run;
1477 	}
1478 	hpts->p_curtick = tcp_gethptstick(&tv);
1479 	hpts->p_cur_slot = tick_to_wheel(hpts->p_curtick);
1480 	if (!seen_endpoint) {
1481 		/* We saw no endpoint but we may be looping */
1482 		orig_exit_slot = hpts->p_cur_slot;
1483 	}
1484 	if ((wrap_loop_cnt < 2) &&
1485 	    (hpts->p_lasttick != hpts->p_curtick)) {
1486 		counter_u64_add(hpts_loops, 1);
1487 		loop_cnt++;
1488 		goto again;
1489 	}
1490 no_run:
1491 	tcp_pace.cts_last_ran[hpts->p_num] = tcp_tv_to_usec(&tv);
1492 	/*
1493 	 * Set flag to tell that we are done for
1494 	 * any slot input that happens during
1495 	 * input.
1496 	 */
1497 	hpts->p_wheel_complete = 1;
1498 	/*
1499 	 * Now did we spend too long running input and need to run more ticks?
1500 	 * Note that if wrap_loop_cnt < 2 then we should have the conditions
1501 	 * in the KASSERT's true. But if the wheel is behind i.e. wrap_loop_cnt
1502 	 * is greater than 2, then the condtion most likely are *not* true.
1503 	 * Also if we are called not from the callout, we don't run the wheel
1504 	 * multiple times so the slots may not align either.
1505 	 */
1506 	KASSERT(((hpts->p_prev_slot == hpts->p_cur_slot) ||
1507 		 (wrap_loop_cnt >= 2) || !from_callout),
1508 		("H:%p p_prev_slot:%u not equal to p_cur_slot:%u", hpts,
1509 		 hpts->p_prev_slot, hpts->p_cur_slot));
1510 	KASSERT(((hpts->p_lasttick == hpts->p_curtick)
1511 		 || (wrap_loop_cnt >= 2) || !from_callout),
1512 		("H:%p p_lasttick:%u not equal to p_curtick:%u", hpts,
1513 		 hpts->p_lasttick, hpts->p_curtick));
1514 	if (from_callout && (hpts->p_lasttick != hpts->p_curtick)) {
1515 		hpts->p_curtick = tcp_gethptstick(&tv);
1516 		counter_u64_add(hpts_loops, 1);
1517 		hpts->p_cur_slot = tick_to_wheel(hpts->p_curtick);
1518 		goto again;
1519 	}
1520 
1521 	if (from_callout) {
1522 		tcp_hpts_set_max_sleep(hpts, wrap_loop_cnt);
1523 	}
1524 	if (seen_endpoint)
1525 		return(hpts_slots_diff(slot_pos_of_endpoint, orig_exit_slot));
1526 	else
1527 		return (0);
1528 }
1529 
1530 void
tcp_set_hpts(struct tcpcb * tp)1531 tcp_set_hpts(struct tcpcb *tp)
1532 {
1533 	struct tcp_hpts_entry *hpts;
1534 	int failed;
1535 
1536 	INP_WLOCK_ASSERT(tptoinpcb(tp));
1537 
1538 	hpts = tcp_hpts_lock(tp);
1539 	if (tp->t_in_hpts == IHPTS_NONE && !(tp->t_flags2 & TF2_HPTS_CPU_SET)) {
1540 		tp->t_hpts_cpu = hpts_cpuid(tp, &failed);
1541 		if (failed == 0)
1542 			tp->t_flags2 |= TF2_HPTS_CPU_SET;
1543 	}
1544 	HPTS_UNLOCK(hpts);
1545 }
1546 
1547 static struct tcp_hpts_entry *
tcp_choose_hpts_to_run(void)1548 tcp_choose_hpts_to_run(void)
1549 {
1550 	int i, oldest_idx, start, end;
1551 	uint32_t cts, time_since_ran, calc;
1552 
1553 	cts = tcp_get_usecs(NULL);
1554 	time_since_ran = 0;
1555 	/* Default is all one group */
1556 	start = 0;
1557 	end = tcp_pace.rp_num_hptss;
1558 	/*
1559 	 * If we have more than one L3 group figure out which one
1560 	 * this CPU is in.
1561 	 */
1562 	if (tcp_pace.grp_cnt > 1) {
1563 		for (i = 0; i < tcp_pace.grp_cnt; i++) {
1564 			if (CPU_ISSET(curcpu, &tcp_pace.grps[i]->cg_mask)) {
1565 				start = tcp_pace.grps[i]->cg_first;
1566 				end = (tcp_pace.grps[i]->cg_last + 1);
1567 				break;
1568 			}
1569 		}
1570 	}
1571 	oldest_idx = -1;
1572 	for (i = start; i < end; i++) {
1573 		if (TSTMP_GT(cts, tcp_pace.cts_last_ran[i]))
1574 			calc = cts - tcp_pace.cts_last_ran[i];
1575 		else
1576 			calc = 0;
1577 		if (calc > time_since_ran) {
1578 			oldest_idx = i;
1579 			time_since_ran = calc;
1580 		}
1581 	}
1582 	if (oldest_idx >= 0)
1583 		return(tcp_pace.rp_ent[oldest_idx]);
1584 	else
1585 		return(tcp_pace.rp_ent[(curcpu % tcp_pace.rp_num_hptss)]);
1586 }
1587 
1588 static void
__tcp_run_hpts(void)1589 __tcp_run_hpts(void)
1590 {
1591 	struct epoch_tracker et;
1592 	struct tcp_hpts_entry *hpts;
1593 	int ticks_ran;
1594 
1595 	hpts = tcp_choose_hpts_to_run();
1596 
1597 	if (hpts->p_hpts_active) {
1598 		/* Already active */
1599 		return;
1600 	}
1601 	if (!HPTS_TRYLOCK(hpts)) {
1602 		/* Someone else got the lock */
1603 		return;
1604 	}
1605 	NET_EPOCH_ENTER(et);
1606 	if (hpts->p_hpts_active)
1607 		goto out_with_mtx;
1608 	hpts->syscall_cnt++;
1609 	counter_u64_add(hpts_direct_call, 1);
1610 	hpts->p_hpts_active = 1;
1611 	ticks_ran = tcp_hptsi(hpts, false);
1612 	/* We may want to adjust the sleep values here */
1613 	if (hpts->p_on_queue_cnt >= conn_cnt_thresh) {
1614 		if (ticks_ran > slots_indicate_less_sleep) {
1615 			struct timeval tv;
1616 			sbintime_t sb;
1617 
1618 			hpts->p_mysleep.tv_usec /= 2;
1619 			if (hpts->p_mysleep.tv_usec < dynamic_min_sleep)
1620 				hpts->p_mysleep.tv_usec = dynamic_min_sleep;
1621 			/* Reschedule with new to value */
1622 			tcp_hpts_set_max_sleep(hpts, 0);
1623 			tv.tv_sec = 0;
1624 			tv.tv_usec = hpts->p_hpts_sleep_time * HPTS_USECS_PER_SLOT;
1625 			/* Validate its in the right ranges */
1626 			if (tv.tv_usec < hpts->p_mysleep.tv_usec) {
1627 				hpts->overidden_sleep = tv.tv_usec;
1628 				tv.tv_usec = hpts->p_mysleep.tv_usec;
1629 			} else if (tv.tv_usec > dynamic_max_sleep) {
1630 				/* Lets not let sleep get above this value */
1631 				hpts->overidden_sleep = tv.tv_usec;
1632 				tv.tv_usec = dynamic_max_sleep;
1633 			}
1634 			/*
1635 			 * In this mode the timer is a backstop to
1636 			 * all the userret/lro_flushes so we use
1637 			 * the dynamic value and set the on_min_sleep
1638 			 * flag so we will not be awoken.
1639 			 */
1640 			sb = tvtosbt(tv);
1641 			/* Store off to make visible the actual sleep time */
1642 			hpts->sleeping = tv.tv_usec;
1643 			callout_reset_sbt_on(&hpts->co, sb, 0,
1644 					     hpts_timeout_swi, hpts, hpts->p_cpu,
1645 					     (C_DIRECT_EXEC | C_PREL(tcp_hpts_precision)));
1646 		} else if (ticks_ran < slots_indicate_more_sleep) {
1647 			/* For the further sleep, don't reschedule  hpts */
1648 			hpts->p_mysleep.tv_usec *= 2;
1649 			if (hpts->p_mysleep.tv_usec > dynamic_max_sleep)
1650 				hpts->p_mysleep.tv_usec = dynamic_max_sleep;
1651 		}
1652 		hpts->p_on_min_sleep = 1;
1653 	}
1654 	hpts->p_hpts_active = 0;
1655 out_with_mtx:
1656 	HPTS_UNLOCK(hpts);
1657 	NET_EPOCH_EXIT(et);
1658 }
1659 
1660 static void
tcp_hpts_thread(void * ctx)1661 tcp_hpts_thread(void *ctx)
1662 {
1663 	struct tcp_hpts_entry *hpts;
1664 	struct epoch_tracker et;
1665 	struct timeval tv;
1666 	sbintime_t sb;
1667 	int ticks_ran;
1668 
1669 	hpts = (struct tcp_hpts_entry *)ctx;
1670 	HPTS_LOCK(hpts);
1671 	if (hpts->p_direct_wake) {
1672 		/* Signaled by input or output with low occupancy count. */
1673 		callout_stop(&hpts->co);
1674 		counter_u64_add(hpts_direct_awakening, 1);
1675 	} else {
1676 		/* Timed out, the normal case. */
1677 		counter_u64_add(hpts_wake_timeout, 1);
1678 		if (callout_pending(&hpts->co) ||
1679 		    !callout_active(&hpts->co)) {
1680 			HPTS_UNLOCK(hpts);
1681 			return;
1682 		}
1683 	}
1684 	callout_deactivate(&hpts->co);
1685 	hpts->p_hpts_wake_scheduled = 0;
1686 	NET_EPOCH_ENTER(et);
1687 	if (hpts->p_hpts_active) {
1688 		/*
1689 		 * We are active already. This means that a syscall
1690 		 * trap or LRO is running in behalf of hpts. In that case
1691 		 * we need to double our timeout since there seems to be
1692 		 * enough activity in the system that we don't need to
1693 		 * run as often (if we were not directly woken).
1694 		 */
1695 		tv.tv_sec = 0;
1696 		if (hpts->p_direct_wake == 0) {
1697 			counter_u64_add(hpts_back_tosleep, 1);
1698 			if (hpts->p_on_queue_cnt >= conn_cnt_thresh) {
1699 				hpts->p_mysleep.tv_usec *= 2;
1700 				if (hpts->p_mysleep.tv_usec > dynamic_max_sleep)
1701 					hpts->p_mysleep.tv_usec = dynamic_max_sleep;
1702 				tv.tv_usec = hpts->p_mysleep.tv_usec;
1703 				hpts->p_on_min_sleep = 1;
1704 			} else {
1705 				/*
1706 				 * Here we have low count on the wheel, but
1707 				 * somehow we still collided with one of the
1708 				 * connections. Lets go back to sleep for a
1709 				 * min sleep time, but clear the flag so we
1710 				 * can be awoken by insert.
1711 				 */
1712 				hpts->p_on_min_sleep = 0;
1713 				tv.tv_usec = tcp_min_hptsi_time;
1714 			}
1715 		} else {
1716 			/*
1717 			 * Directly woken most likely to reset the
1718 			 * callout time.
1719 			 */
1720 			tv.tv_usec = hpts->p_mysleep.tv_usec;
1721 		}
1722 		goto back_to_sleep;
1723 	}
1724 	hpts->sleeping = 0;
1725 	hpts->p_hpts_active = 1;
1726 	ticks_ran = tcp_hptsi(hpts, true);
1727 	tv.tv_sec = 0;
1728 	tv.tv_usec = hpts->p_hpts_sleep_time * HPTS_USECS_PER_SLOT;
1729 	if ((hpts->p_on_queue_cnt > conn_cnt_thresh) && (hpts->hit_callout_thresh == 0)) {
1730 		hpts->hit_callout_thresh = 1;
1731 		atomic_add_int(&hpts_that_need_softclock, 1);
1732 	} else if ((hpts->p_on_queue_cnt <= conn_cnt_thresh) && (hpts->hit_callout_thresh == 1)) {
1733 		hpts->hit_callout_thresh = 0;
1734 		atomic_subtract_int(&hpts_that_need_softclock, 1);
1735 	}
1736 	if (hpts->p_on_queue_cnt >= conn_cnt_thresh) {
1737 		if(hpts->p_direct_wake == 0) {
1738 			/*
1739 			 * Only adjust sleep time if we were
1740 			 * called from the callout i.e. direct_wake == 0.
1741 			 */
1742 			if (ticks_ran < slots_indicate_more_sleep) {
1743 				hpts->p_mysleep.tv_usec *= 2;
1744 				if (hpts->p_mysleep.tv_usec > dynamic_max_sleep)
1745 					hpts->p_mysleep.tv_usec = dynamic_max_sleep;
1746 			} else if (ticks_ran > slots_indicate_less_sleep) {
1747 				hpts->p_mysleep.tv_usec /= 2;
1748 				if (hpts->p_mysleep.tv_usec < dynamic_min_sleep)
1749 					hpts->p_mysleep.tv_usec = dynamic_min_sleep;
1750 			}
1751 		}
1752 		if (tv.tv_usec < hpts->p_mysleep.tv_usec) {
1753 			hpts->overidden_sleep = tv.tv_usec;
1754 			tv.tv_usec = hpts->p_mysleep.tv_usec;
1755 		} else if (tv.tv_usec > dynamic_max_sleep) {
1756 			/* Lets not let sleep get above this value */
1757 			hpts->overidden_sleep = tv.tv_usec;
1758 			tv.tv_usec = dynamic_max_sleep;
1759 		}
1760 		/*
1761 		 * In this mode the timer is a backstop to
1762 		 * all the userret/lro_flushes so we use
1763 		 * the dynamic value and set the on_min_sleep
1764 		 * flag so we will not be awoken.
1765 		 */
1766 		hpts->p_on_min_sleep = 1;
1767 	} else if (hpts->p_on_queue_cnt == 0)  {
1768 		/*
1769 		 * No one on the wheel, please wake us up
1770 		 * if you insert on the wheel.
1771 		 */
1772 		hpts->p_on_min_sleep = 0;
1773 		hpts->overidden_sleep = 0;
1774 	} else {
1775 		/*
1776 		 * We hit here when we have a low number of
1777 		 * clients on the wheel (our else clause).
1778 		 * We may need to go on min sleep, if we set
1779 		 * the flag we will not be awoken if someone
1780 		 * is inserted ahead of us. Clearing the flag
1781 		 * means we can be awoken. This is "old mode"
1782 		 * where the timer is what runs hpts mainly.
1783 		 */
1784 		if (tv.tv_usec < tcp_min_hptsi_time) {
1785 			/*
1786 			 * Yes on min sleep, which means
1787 			 * we cannot be awoken.
1788 			 */
1789 			hpts->overidden_sleep = tv.tv_usec;
1790 			tv.tv_usec = tcp_min_hptsi_time;
1791 			hpts->p_on_min_sleep = 1;
1792 		} else {
1793 			/* Clear the min sleep flag */
1794 			hpts->overidden_sleep = 0;
1795 			hpts->p_on_min_sleep = 0;
1796 		}
1797 	}
1798 	HPTS_MTX_ASSERT(hpts);
1799 	hpts->p_hpts_active = 0;
1800 back_to_sleep:
1801 	hpts->p_direct_wake = 0;
1802 	sb = tvtosbt(tv);
1803 	/* Store off to make visible the actual sleep time */
1804 	hpts->sleeping = tv.tv_usec;
1805 	callout_reset_sbt_on(&hpts->co, sb, 0,
1806 			     hpts_timeout_swi, hpts, hpts->p_cpu,
1807 			     (C_DIRECT_EXEC | C_PREL(tcp_hpts_precision)));
1808 	NET_EPOCH_EXIT(et);
1809 	HPTS_UNLOCK(hpts);
1810 }
1811 
1812 #undef	timersub
1813 
1814 static int32_t
hpts_count_level(struct cpu_group * cg)1815 hpts_count_level(struct cpu_group *cg)
1816 {
1817 	int32_t count_l3, i;
1818 
1819 	count_l3 = 0;
1820 	if (cg->cg_level == CG_SHARE_L3)
1821 		count_l3++;
1822 	/* Walk all the children looking for L3 */
1823 	for (i = 0; i < cg->cg_children; i++) {
1824 		count_l3 += hpts_count_level(&cg->cg_child[i]);
1825 	}
1826 	return (count_l3);
1827 }
1828 
1829 static void
hpts_gather_grps(struct cpu_group ** grps,int32_t * at,int32_t max,struct cpu_group * cg)1830 hpts_gather_grps(struct cpu_group **grps, int32_t *at, int32_t max, struct cpu_group *cg)
1831 {
1832 	int32_t idx, i;
1833 
1834 	idx = *at;
1835 	if (cg->cg_level == CG_SHARE_L3) {
1836 		grps[idx] = cg;
1837 		idx++;
1838 		if (idx == max) {
1839 			*at = idx;
1840 			return;
1841 		}
1842 	}
1843 	*at = idx;
1844 	/* Walk all the children looking for L3 */
1845 	for (i = 0; i < cg->cg_children; i++) {
1846 		hpts_gather_grps(grps, at, max, &cg->cg_child[i]);
1847 	}
1848 }
1849 
1850 static void
tcp_hpts_mod_load(void)1851 tcp_hpts_mod_load(void)
1852 {
1853 	struct cpu_group *cpu_top;
1854 	int32_t error __diagused;
1855 	int32_t i, j, bound = 0, created = 0;
1856 	size_t sz, asz;
1857 	struct timeval tv;
1858 	sbintime_t sb;
1859 	struct tcp_hpts_entry *hpts;
1860 	struct pcpu *pc;
1861 	char unit[16];
1862 	uint32_t ncpus = mp_ncpus ? mp_ncpus : MAXCPU;
1863 	int count, domain;
1864 
1865 #ifdef SMP
1866 	cpu_top = smp_topo();
1867 #else
1868 	cpu_top = NULL;
1869 #endif
1870 	tcp_pace.rp_num_hptss = ncpus;
1871 	hpts_hopelessly_behind = counter_u64_alloc(M_WAITOK);
1872 	hpts_loops = counter_u64_alloc(M_WAITOK);
1873 	back_tosleep = counter_u64_alloc(M_WAITOK);
1874 	combined_wheel_wrap = counter_u64_alloc(M_WAITOK);
1875 	wheel_wrap = counter_u64_alloc(M_WAITOK);
1876 	hpts_wake_timeout = counter_u64_alloc(M_WAITOK);
1877 	hpts_direct_awakening = counter_u64_alloc(M_WAITOK);
1878 	hpts_back_tosleep = counter_u64_alloc(M_WAITOK);
1879 	hpts_direct_call = counter_u64_alloc(M_WAITOK);
1880 	cpu_uses_flowid = counter_u64_alloc(M_WAITOK);
1881 	cpu_uses_random = counter_u64_alloc(M_WAITOK);
1882 
1883 	sz = (tcp_pace.rp_num_hptss * sizeof(struct tcp_hpts_entry *));
1884 	tcp_pace.rp_ent = malloc(sz, M_TCPHPTS, M_WAITOK | M_ZERO);
1885 	sz = (sizeof(uint32_t) * tcp_pace.rp_num_hptss);
1886 	tcp_pace.cts_last_ran = malloc(sz, M_TCPHPTS, M_WAITOK);
1887 	tcp_pace.grp_cnt = 0;
1888 	if (cpu_top == NULL) {
1889 		tcp_pace.grp_cnt = 1;
1890 	} else {
1891 		/* Find out how many cache level 3 domains we have */
1892 		count = 0;
1893 		tcp_pace.grp_cnt = hpts_count_level(cpu_top);
1894 		if (tcp_pace.grp_cnt == 0) {
1895 			tcp_pace.grp_cnt = 1;
1896 		}
1897 		sz = (tcp_pace.grp_cnt * sizeof(struct cpu_group *));
1898 		tcp_pace.grps = malloc(sz, M_TCPHPTS, M_WAITOK);
1899 		/* Now populate the groups */
1900 		if (tcp_pace.grp_cnt == 1) {
1901 			/*
1902 			 * All we need is the top level all cpu's are in
1903 			 * the same cache so when we use grp[0]->cg_mask
1904 			 * with the cg_first <-> cg_last it will include
1905 			 * all cpu's in it. The level here is probably
1906 			 * zero which is ok.
1907 			 */
1908 			tcp_pace.grps[0] = cpu_top;
1909 		} else {
1910 			/*
1911 			 * Here we must find all the level three cache domains
1912 			 * and setup our pointers to them.
1913 			 */
1914 			count = 0;
1915 			hpts_gather_grps(tcp_pace.grps, &count, tcp_pace.grp_cnt, cpu_top);
1916 		}
1917 	}
1918 	asz = sizeof(struct hptsh) * NUM_OF_HPTSI_SLOTS;
1919 	for (i = 0; i < tcp_pace.rp_num_hptss; i++) {
1920 		tcp_pace.rp_ent[i] = malloc(sizeof(struct tcp_hpts_entry),
1921 		    M_TCPHPTS, M_WAITOK | M_ZERO);
1922 		tcp_pace.rp_ent[i]->p_hptss = malloc(asz, M_TCPHPTS, M_WAITOK);
1923 		hpts = tcp_pace.rp_ent[i];
1924 		/*
1925 		 * Init all the hpts structures that are not specifically
1926 		 * zero'd by the allocations. Also lets attach them to the
1927 		 * appropriate sysctl block as well.
1928 		 */
1929 		mtx_init(&hpts->p_mtx, "tcp_hpts_lck",
1930 		    "hpts", MTX_DEF | MTX_DUPOK);
1931 		for (j = 0; j < NUM_OF_HPTSI_SLOTS; j++) {
1932 			TAILQ_INIT(&hpts->p_hptss[j].head);
1933 			hpts->p_hptss[j].count = 0;
1934 			hpts->p_hptss[j].gencnt = 0;
1935 		}
1936 		sysctl_ctx_init(&hpts->hpts_ctx);
1937 		sprintf(unit, "%d", i);
1938 		hpts->hpts_root = SYSCTL_ADD_NODE(&hpts->hpts_ctx,
1939 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp_hpts),
1940 		    OID_AUTO,
1941 		    unit,
1942 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1943 		    "");
1944 		SYSCTL_ADD_INT(&hpts->hpts_ctx,
1945 		    SYSCTL_CHILDREN(hpts->hpts_root),
1946 		    OID_AUTO, "out_qcnt", CTLFLAG_RD,
1947 		    &hpts->p_on_queue_cnt, 0,
1948 		    "Count TCB's awaiting output processing");
1949 		SYSCTL_ADD_U16(&hpts->hpts_ctx,
1950 		    SYSCTL_CHILDREN(hpts->hpts_root),
1951 		    OID_AUTO, "active", CTLFLAG_RD,
1952 		    &hpts->p_hpts_active, 0,
1953 		    "Is the hpts active");
1954 		SYSCTL_ADD_UINT(&hpts->hpts_ctx,
1955 		    SYSCTL_CHILDREN(hpts->hpts_root),
1956 		    OID_AUTO, "curslot", CTLFLAG_RD,
1957 		    &hpts->p_cur_slot, 0,
1958 		    "What the current running pacers goal");
1959 		SYSCTL_ADD_UINT(&hpts->hpts_ctx,
1960 		    SYSCTL_CHILDREN(hpts->hpts_root),
1961 		    OID_AUTO, "runtick", CTLFLAG_RD,
1962 		    &hpts->p_runningslot, 0,
1963 		    "What the running pacers current slot is");
1964 		SYSCTL_ADD_UINT(&hpts->hpts_ctx,
1965 		    SYSCTL_CHILDREN(hpts->hpts_root),
1966 		    OID_AUTO, "curtick", CTLFLAG_RD,
1967 		    &hpts->p_curtick, 0,
1968 		    "What the running pacers last tick mapped to the wheel was");
1969 		SYSCTL_ADD_UINT(&hpts->hpts_ctx,
1970 		    SYSCTL_CHILDREN(hpts->hpts_root),
1971 		    OID_AUTO, "lastran", CTLFLAG_RD,
1972 		    &tcp_pace.cts_last_ran[i], 0,
1973 		    "The last usec tick that this hpts ran");
1974 		SYSCTL_ADD_LONG(&hpts->hpts_ctx,
1975 		    SYSCTL_CHILDREN(hpts->hpts_root),
1976 		    OID_AUTO, "cur_min_sleep", CTLFLAG_RD,
1977 		    &hpts->p_mysleep.tv_usec,
1978 		    "What the running pacers is using for p_mysleep.tv_usec");
1979 		SYSCTL_ADD_U64(&hpts->hpts_ctx,
1980 		    SYSCTL_CHILDREN(hpts->hpts_root),
1981 		    OID_AUTO, "now_sleeping", CTLFLAG_RD,
1982 		    &hpts->sleeping, 0,
1983 		    "What the running pacers is actually sleeping for");
1984 		SYSCTL_ADD_U64(&hpts->hpts_ctx,
1985 		    SYSCTL_CHILDREN(hpts->hpts_root),
1986 		    OID_AUTO, "syscall_cnt", CTLFLAG_RD,
1987 		    &hpts->syscall_cnt, 0,
1988 		    "How many times we had syscalls on this hpts");
1989 
1990 		hpts->p_hpts_sleep_time = hpts_sleep_max;
1991 		hpts->p_num = i;
1992 		hpts->p_curtick = tcp_gethptstick(&tv);
1993 		tcp_pace.cts_last_ran[i] = tcp_tv_to_usec(&tv);
1994 		hpts->p_prev_slot = hpts->p_cur_slot = tick_to_wheel(hpts->p_curtick);
1995 		hpts->p_cpu = 0xffff;
1996 		hpts->p_nxt_slot = hpts_slot(hpts->p_cur_slot, 1);
1997 		callout_init(&hpts->co, 1);
1998 	}
1999 	/* Don't try to bind to NUMA domains if we don't have any */
2000 	if (vm_ndomains == 1 && tcp_bind_threads == 2)
2001 		tcp_bind_threads = 0;
2002 
2003 	/*
2004 	 * Now lets start ithreads to handle the hptss.
2005 	 */
2006 	for (i = 0; i < tcp_pace.rp_num_hptss; i++) {
2007 		hpts = tcp_pace.rp_ent[i];
2008 		hpts->p_cpu = i;
2009 
2010 		error = swi_add(&hpts->ie, "hpts",
2011 		    tcp_hpts_thread, (void *)hpts,
2012 		    SWI_NET, INTR_MPSAFE, &hpts->ie_cookie);
2013 		KASSERT(error == 0,
2014 			("Can't add hpts:%p i:%d err:%d",
2015 			 hpts, i, error));
2016 		created++;
2017 		hpts->p_mysleep.tv_sec = 0;
2018 		hpts->p_mysleep.tv_usec = tcp_min_hptsi_time;
2019 		if (tcp_bind_threads == 1) {
2020 			if (intr_event_bind(hpts->ie, i) == 0)
2021 				bound++;
2022 		} else if (tcp_bind_threads == 2) {
2023 			/* Find the group for this CPU (i) and bind into it */
2024 			for (j = 0; j < tcp_pace.grp_cnt; j++) {
2025 				if (CPU_ISSET(i, &tcp_pace.grps[j]->cg_mask)) {
2026 					if (intr_event_bind_ithread_cpuset(hpts->ie,
2027 						&tcp_pace.grps[j]->cg_mask) == 0) {
2028 						bound++;
2029 						pc = pcpu_find(i);
2030 						domain = pc->pc_domain;
2031 						count = hpts_domains[domain].count;
2032 						hpts_domains[domain].cpu[count] = i;
2033 						hpts_domains[domain].count++;
2034 						break;
2035 					}
2036 				}
2037 			}
2038 		}
2039 		tv.tv_sec = 0;
2040 		tv.tv_usec = hpts->p_hpts_sleep_time * HPTS_USECS_PER_SLOT;
2041 		hpts->sleeping = tv.tv_usec;
2042 		sb = tvtosbt(tv);
2043 		callout_reset_sbt_on(&hpts->co, sb, 0,
2044 				     hpts_timeout_swi, hpts, hpts->p_cpu,
2045 				     (C_DIRECT_EXEC | C_PREL(tcp_hpts_precision)));
2046 	}
2047 	/*
2048 	 * If we somehow have an empty domain, fall back to choosing
2049 	 * among all htps threads.
2050 	 */
2051 	for (i = 0; i < vm_ndomains; i++) {
2052 		if (hpts_domains[i].count == 0) {
2053 			tcp_bind_threads = 0;
2054 			break;
2055 		}
2056 	}
2057 	tcp_hpts_softclock = __tcp_run_hpts;
2058 	tcp_lro_hpts_init();
2059 	printf("TCP Hpts created %d swi interrupt threads and bound %d to %s\n",
2060 	    created, bound,
2061 	    tcp_bind_threads == 2 ? "NUMA domains" : "cpus");
2062 }
2063 
2064 static void
tcp_hpts_mod_unload(void)2065 tcp_hpts_mod_unload(void)
2066 {
2067 	int rv __diagused;
2068 
2069 	tcp_lro_hpts_uninit();
2070 	atomic_store_ptr(&tcp_hpts_softclock, NULL);
2071 
2072 	for (int i = 0; i < tcp_pace.rp_num_hptss; i++) {
2073 		struct tcp_hpts_entry *hpts = tcp_pace.rp_ent[i];
2074 
2075 		rv = callout_drain(&hpts->co);
2076 		MPASS(rv != 0);
2077 
2078 		rv = swi_remove(hpts->ie_cookie);
2079 		MPASS(rv == 0);
2080 
2081 		rv = sysctl_ctx_free(&hpts->hpts_ctx);
2082 		MPASS(rv == 0);
2083 
2084 		mtx_destroy(&hpts->p_mtx);
2085 		free(hpts->p_hptss, M_TCPHPTS);
2086 		free(hpts, M_TCPHPTS);
2087 	}
2088 
2089 	free(tcp_pace.rp_ent, M_TCPHPTS);
2090 	free(tcp_pace.cts_last_ran, M_TCPHPTS);
2091 #ifdef SMP
2092 	free(tcp_pace.grps, M_TCPHPTS);
2093 #endif
2094 
2095 	counter_u64_free(hpts_hopelessly_behind);
2096 	counter_u64_free(hpts_loops);
2097 	counter_u64_free(back_tosleep);
2098 	counter_u64_free(combined_wheel_wrap);
2099 	counter_u64_free(wheel_wrap);
2100 	counter_u64_free(hpts_wake_timeout);
2101 	counter_u64_free(hpts_direct_awakening);
2102 	counter_u64_free(hpts_back_tosleep);
2103 	counter_u64_free(hpts_direct_call);
2104 	counter_u64_free(cpu_uses_flowid);
2105 	counter_u64_free(cpu_uses_random);
2106 }
2107 
2108 static int
tcp_hpts_modevent(module_t mod,int what,void * arg)2109 tcp_hpts_modevent(module_t mod, int what, void *arg)
2110 {
2111 
2112 	switch (what) {
2113 	case MOD_LOAD:
2114 		tcp_hpts_mod_load();
2115 		return (0);
2116 	case MOD_QUIESCE:
2117 		/*
2118 		 * Since we are a dependency of TCP stack modules, they should
2119 		 * already be unloaded, and the HPTS ring is empty.  However,
2120 		 * function pointer manipulations aren't 100% safe.  Although,
2121 		 * tcp_hpts_mod_unload() use atomic(9) the userret() doesn't.
2122 		 * Thus, allow only forced unload of HPTS.
2123 		 */
2124 		return (EBUSY);
2125 	case MOD_UNLOAD:
2126 		tcp_hpts_mod_unload();
2127 		return (0);
2128 	default:
2129 		return (EINVAL);
2130 	};
2131 }
2132 
2133 static moduledata_t tcp_hpts_module = {
2134 	.name = "tcphpts",
2135 	.evhand = tcp_hpts_modevent,
2136 };
2137 
2138 DECLARE_MODULE(tcphpts, tcp_hpts_module, SI_SUB_SOFTINTR, SI_ORDER_ANY);
2139 MODULE_VERSION(tcphpts, 1);
2140