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