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