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