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