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