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