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