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