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