1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995 5 * The Regents of the University of California. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. Neither the name of the University nor the names of its contributors 16 * may be used to endorse or promote products derived from this software 17 * without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 */ 31 32 #include <sys/cdefs.h> 33 #include "opt_inet.h" 34 #include "opt_inet6.h" 35 #include "opt_ipsec.h" 36 #include "opt_kern_tls.h" 37 38 #include <sys/param.h> 39 #include <sys/systm.h> 40 #include <sys/arb.h> 41 #include <sys/callout.h> 42 #include <sys/eventhandler.h> 43 #ifdef TCP_HHOOK 44 #include <sys/hhook.h> 45 #endif 46 #include <sys/kernel.h> 47 #ifdef TCP_HHOOK 48 #include <sys/khelp.h> 49 #endif 50 #ifdef KERN_TLS 51 #include <sys/ktls.h> 52 #endif 53 #include <sys/qmath.h> 54 #include <sys/stats.h> 55 #include <sys/sysctl.h> 56 #include <sys/jail.h> 57 #include <sys/malloc.h> 58 #include <sys/refcount.h> 59 #include <sys/mbuf.h> 60 #include <sys/priv.h> 61 #include <sys/proc.h> 62 #include <sys/sdt.h> 63 #include <sys/socket.h> 64 #include <sys/socketvar.h> 65 #include <sys/protosw.h> 66 #include <sys/random.h> 67 68 #include <vm/uma.h> 69 70 #include <net/route.h> 71 #include <net/route/nhop.h> 72 #include <net/if.h> 73 #include <net/if_var.h> 74 #include <net/if_private.h> 75 #include <net/vnet.h> 76 77 #include <netinet/in.h> 78 #include <netinet/in_fib.h> 79 #include <netinet/in_kdtrace.h> 80 #include <netinet/in_pcb.h> 81 #include <netinet/in_systm.h> 82 #include <netinet/in_var.h> 83 #include <netinet/ip.h> 84 #include <netinet/ip_icmp.h> 85 #include <netinet/ip_var.h> 86 #ifdef INET6 87 #include <netinet/icmp6.h> 88 #include <netinet/ip6.h> 89 #include <netinet6/in6_fib.h> 90 #include <netinet6/in6_pcb.h> 91 #include <netinet6/ip6_var.h> 92 #include <netinet6/scope6_var.h> 93 #include <netinet6/nd6.h> 94 #endif 95 96 #include <netinet/tcp.h> 97 #ifdef INVARIANTS 98 #define TCPSTATES 99 #endif 100 #include <netinet/tcp_fsm.h> 101 #include <netinet/tcp_seq.h> 102 #include <netinet/tcp_timer.h> 103 #include <netinet/tcp_var.h> 104 #include <netinet/tcp_ecn.h> 105 #include <netinet/tcp_log_buf.h> 106 #include <netinet/tcp_syncache.h> 107 #include <netinet/tcp_hpts.h> 108 #include <netinet/tcp_lro.h> 109 #include <netinet/cc/cc.h> 110 #include <netinet/tcpip.h> 111 #include <netinet/tcp_fastopen.h> 112 #include <netinet/tcp_accounting.h> 113 #ifdef TCPPCAP 114 #include <netinet/tcp_pcap.h> 115 #endif 116 #ifdef TCP_OFFLOAD 117 #include <netinet/tcp_offload.h> 118 #endif 119 #include <netinet/udp.h> 120 #include <netinet/udp_var.h> 121 #ifdef INET6 122 #include <netinet6/tcp6_var.h> 123 #endif 124 125 #include <netipsec/ipsec_support.h> 126 127 #include <machine/in_cksum.h> 128 #include <crypto/siphash/siphash.h> 129 130 #include <security/mac/mac_framework.h> 131 132 #ifdef INET6 133 static ip6proto_ctlinput_t tcp6_ctlinput; 134 static udp_tun_icmp_t tcp6_ctlinput_viaudp; 135 #endif 136 137 VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS; 138 #ifdef INET6 139 VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS; 140 #endif 141 142 uint32_t tcp_ack_war_time_window = 1000; 143 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_timewindow, 144 CTLFLAG_RW, 145 &tcp_ack_war_time_window, 1000, 146 "If the tcp_stack does ack-war prevention how many milliseconds are in its time window?"); 147 uint32_t tcp_ack_war_cnt = 5; 148 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_cnt, 149 CTLFLAG_RW, 150 &tcp_ack_war_cnt, 5, 151 "If the tcp_stack does ack-war prevention how many acks can be sent in its time window?"); 152 153 struct rwlock tcp_function_lock; 154 155 static int 156 sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS) 157 { 158 int error, new; 159 160 new = V_tcp_mssdflt; 161 error = sysctl_handle_int(oidp, &new, 0, req); 162 if (error == 0 && req->newptr) { 163 if (new < TCP_MINMSS) 164 error = EINVAL; 165 else 166 V_tcp_mssdflt = new; 167 } 168 return (error); 169 } 170 171 SYSCTL_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, 172 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 173 &VNET_NAME(tcp_mssdflt), 0, &sysctl_net_inet_tcp_mss_check, "I", 174 "Default TCP Maximum Segment Size"); 175 176 #ifdef INET6 177 static int 178 sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS) 179 { 180 int error, new; 181 182 new = V_tcp_v6mssdflt; 183 error = sysctl_handle_int(oidp, &new, 0, req); 184 if (error == 0 && req->newptr) { 185 if (new < TCP_MINMSS) 186 error = EINVAL; 187 else 188 V_tcp_v6mssdflt = new; 189 } 190 return (error); 191 } 192 193 SYSCTL_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt, 194 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 195 &VNET_NAME(tcp_v6mssdflt), 0, &sysctl_net_inet_tcp_mss_v6_check, "I", 196 "Default TCP Maximum Segment Size for IPv6"); 197 #endif /* INET6 */ 198 199 /* 200 * Minimum MSS we accept and use. This prevents DoS attacks where 201 * we are forced to a ridiculous low MSS like 20 and send hundreds 202 * of packets instead of one. The effect scales with the available 203 * bandwidth and quickly saturates the CPU and network interface 204 * with packet generation and sending. Set to zero to disable MINMSS 205 * checking. This setting prevents us from sending too small packets. 206 */ 207 VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS; 208 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_VNET | CTLFLAG_RW, 209 &VNET_NAME(tcp_minmss), 0, 210 "Minimum TCP Maximum Segment Size"); 211 212 VNET_DEFINE(int, tcp_do_rfc1323) = 1; 213 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_VNET | CTLFLAG_RW, 214 &VNET_NAME(tcp_do_rfc1323), 0, 215 "Enable rfc1323 (high performance TCP) extensions"); 216 217 /* 218 * As of June 2021, several TCP stacks violate RFC 7323 from September 2014. 219 * Some stacks negotiate TS, but never send them after connection setup. Some 220 * stacks negotiate TS, but don't send them when sending keep-alive segments. 221 * These include modern widely deployed TCP stacks. 222 * Therefore tolerating violations for now... 223 */ 224 VNET_DEFINE(int, tcp_tolerate_missing_ts) = 1; 225 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tolerate_missing_ts, CTLFLAG_VNET | CTLFLAG_RW, 226 &VNET_NAME(tcp_tolerate_missing_ts), 0, 227 "Tolerate missing TCP timestamps"); 228 229 VNET_DEFINE(int, tcp_ts_offset_per_conn) = 1; 230 SYSCTL_INT(_net_inet_tcp, OID_AUTO, ts_offset_per_conn, CTLFLAG_VNET | CTLFLAG_RW, 231 &VNET_NAME(tcp_ts_offset_per_conn), 0, 232 "Initialize TCP timestamps per connection instead of per host pair"); 233 234 /* How many connections are pacing */ 235 static volatile uint32_t number_of_tcp_connections_pacing = 0; 236 static uint32_t shadow_num_connections = 0; 237 static counter_u64_t tcp_pacing_failures; 238 static counter_u64_t tcp_dgp_failures; 239 static uint32_t shadow_tcp_pacing_dgp = 0; 240 static volatile uint32_t number_of_dgp_connections = 0; 241 242 static int tcp_pacing_limit = 10000; 243 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pacing_limit, CTLFLAG_RW, 244 &tcp_pacing_limit, 1000, 245 "If the TCP stack does pacing, is there a limit (-1 = no, 0 = no pacing N = number of connections)"); 246 247 static int tcp_dgp_limit = -1; 248 SYSCTL_INT(_net_inet_tcp, OID_AUTO, dgp_limit, CTLFLAG_RW, 249 &tcp_dgp_limit, -1, 250 "If the TCP stack does DGP, is there a limit (-1 = no, 0 = no dgp N = number of connections)"); 251 252 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pacing_count, CTLFLAG_RD, 253 &shadow_num_connections, 0, "Number of TCP connections being paced"); 254 255 SYSCTL_COUNTER_U64(_net_inet_tcp, OID_AUTO, pacing_failures, CTLFLAG_RD, 256 &tcp_pacing_failures, "Number of times we failed to enable pacing to avoid exceeding the limit"); 257 258 SYSCTL_COUNTER_U64(_net_inet_tcp, OID_AUTO, dgp_failures, CTLFLAG_RD, 259 &tcp_dgp_failures, "Number of times we failed to enable dgp to avoid exceeding the limit"); 260 261 static int tcp_log_debug = 0; 262 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW, 263 &tcp_log_debug, 0, "Log errors caused by incoming TCP segments"); 264 265 /* 266 * Target size of TCP PCB hash tables. Must be a power of two. 267 * 268 * Note that this can be overridden by the kernel environment 269 * variable net.inet.tcp.tcbhashsize 270 */ 271 #ifndef TCBHASHSIZE 272 #define TCBHASHSIZE 0 273 #endif 274 static int tcp_tcbhashsize = TCBHASHSIZE; 275 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN, 276 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable"); 277 278 static int do_tcpdrain = 1; 279 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0, 280 "Enable tcp_drain routine for extra help when low on mbufs"); 281 282 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD, 283 &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs"); 284 285 VNET_DEFINE_STATIC(int, icmp_may_rst) = 1; 286 #define V_icmp_may_rst VNET(icmp_may_rst) 287 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW, 288 &VNET_NAME(icmp_may_rst), 0, 289 "Certain ICMP unreachable messages may abort connections in SYN_SENT"); 290 291 VNET_DEFINE_STATIC(int, tcp_isn_reseed_interval) = 0; 292 #define V_tcp_isn_reseed_interval VNET(tcp_isn_reseed_interval) 293 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW, 294 &VNET_NAME(tcp_isn_reseed_interval), 0, 295 "Seconds between reseeding of ISN secret"); 296 297 static int tcp_soreceive_stream; 298 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN, 299 &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets"); 300 301 VNET_DEFINE(uma_zone_t, sack_hole_zone); 302 #define V_sack_hole_zone VNET(sack_hole_zone) 303 VNET_DEFINE(uint32_t, tcp_map_entries_limit) = 0; /* unlimited */ 304 static int 305 sysctl_net_inet_tcp_map_limit_check(SYSCTL_HANDLER_ARGS) 306 { 307 int error; 308 uint32_t new; 309 310 new = V_tcp_map_entries_limit; 311 error = sysctl_handle_int(oidp, &new, 0, req); 312 if (error == 0 && req->newptr) { 313 /* only allow "0" and value > minimum */ 314 if (new > 0 && new < TCP_MIN_MAP_ENTRIES_LIMIT) 315 error = EINVAL; 316 else 317 V_tcp_map_entries_limit = new; 318 } 319 return (error); 320 } 321 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, map_limit, 322 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 323 &VNET_NAME(tcp_map_entries_limit), 0, 324 &sysctl_net_inet_tcp_map_limit_check, "IU", 325 "Total sendmap entries limit"); 326 327 VNET_DEFINE(uint32_t, tcp_map_split_limit) = 0; /* unlimited */ 328 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, split_limit, CTLFLAG_VNET | CTLFLAG_RW, 329 &VNET_NAME(tcp_map_split_limit), 0, 330 "Total sendmap split entries limit"); 331 332 #ifdef TCP_HHOOK 333 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]); 334 #endif 335 336 #define TS_OFFSET_SECRET_LENGTH SIPHASH_KEY_LENGTH 337 VNET_DEFINE_STATIC(u_char, ts_offset_secret[TS_OFFSET_SECRET_LENGTH]); 338 #define V_ts_offset_secret VNET(ts_offset_secret) 339 340 static int tcp_default_fb_init(struct tcpcb *tp, void **ptr); 341 static void tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged); 342 static int tcp_default_handoff_ok(struct tcpcb *tp); 343 static struct inpcb *tcp_notify(struct inpcb *, int); 344 static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int); 345 static struct inpcb *tcp_mtudisc(struct inpcb *, int); 346 static struct inpcb *tcp_drop_syn_sent(struct inpcb *, int); 347 static char * tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, 348 const void *ip4hdr, const void *ip6hdr); 349 static void tcp_default_switch_failed(struct tcpcb *tp); 350 static ipproto_ctlinput_t tcp_ctlinput; 351 static udp_tun_icmp_t tcp_ctlinput_viaudp; 352 353 static struct tcp_function_block tcp_def_funcblk = { 354 .tfb_tcp_block_name = "freebsd", 355 .tfb_tcp_output = tcp_default_output, 356 .tfb_tcp_do_segment = tcp_do_segment, 357 .tfb_tcp_ctloutput = tcp_default_ctloutput, 358 .tfb_tcp_handoff_ok = tcp_default_handoff_ok, 359 .tfb_tcp_fb_init = tcp_default_fb_init, 360 .tfb_tcp_fb_fini = tcp_default_fb_fini, 361 .tfb_switch_failed = tcp_default_switch_failed, 362 }; 363 364 static int tcp_fb_cnt = 0; 365 struct tcp_funchead t_functions; 366 VNET_DEFINE_STATIC(struct tcp_function_block *, tcp_func_set_ptr) = &tcp_def_funcblk; 367 #define V_tcp_func_set_ptr VNET(tcp_func_set_ptr) 368 369 void 370 tcp_record_dsack(struct tcpcb *tp, tcp_seq start, tcp_seq end, int tlp) 371 { 372 TCPSTAT_INC(tcps_dsack_count); 373 tp->t_dsack_pack++; 374 if (tlp == 0) { 375 if (SEQ_GT(end, start)) { 376 tp->t_dsack_bytes += (end - start); 377 TCPSTAT_ADD(tcps_dsack_bytes, (end - start)); 378 } else { 379 tp->t_dsack_tlp_bytes += (start - end); 380 TCPSTAT_ADD(tcps_dsack_bytes, (start - end)); 381 } 382 } else { 383 if (SEQ_GT(end, start)) { 384 tp->t_dsack_bytes += (end - start); 385 TCPSTAT_ADD(tcps_dsack_tlp_bytes, (end - start)); 386 } else { 387 tp->t_dsack_tlp_bytes += (start - end); 388 TCPSTAT_ADD(tcps_dsack_tlp_bytes, (start - end)); 389 } 390 } 391 } 392 393 static struct tcp_function_block * 394 find_tcp_functions_locked(struct tcp_function_set *fs) 395 { 396 struct tcp_function *f; 397 struct tcp_function_block *blk = NULL; 398 399 rw_assert(&tcp_function_lock, RA_LOCKED); 400 TAILQ_FOREACH(f, &t_functions, tf_next) { 401 if (strcmp(f->tf_name, fs->function_set_name) == 0) { 402 blk = f->tf_fb; 403 break; 404 } 405 } 406 return (blk); 407 } 408 409 static struct tcp_function_block * 410 find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s) 411 { 412 struct tcp_function_block *rblk = NULL; 413 struct tcp_function *f; 414 415 rw_assert(&tcp_function_lock, RA_LOCKED); 416 TAILQ_FOREACH(f, &t_functions, tf_next) { 417 if (f->tf_fb == blk) { 418 rblk = blk; 419 if (s) { 420 *s = f; 421 } 422 break; 423 } 424 } 425 return (rblk); 426 } 427 428 struct tcp_function_block * 429 find_and_ref_tcp_functions(struct tcp_function_set *fs) 430 { 431 struct tcp_function_block *blk; 432 433 rw_rlock(&tcp_function_lock); 434 blk = find_tcp_functions_locked(fs); 435 if (blk) 436 refcount_acquire(&blk->tfb_refcnt); 437 rw_runlock(&tcp_function_lock); 438 return (blk); 439 } 440 441 struct tcp_function_block * 442 find_and_ref_tcp_fb(struct tcp_function_block *blk) 443 { 444 struct tcp_function_block *rblk; 445 446 rw_rlock(&tcp_function_lock); 447 rblk = find_tcp_fb_locked(blk, NULL); 448 if (rblk) 449 refcount_acquire(&rblk->tfb_refcnt); 450 rw_runlock(&tcp_function_lock); 451 return (rblk); 452 } 453 454 /* Find a matching alias for the given tcp_function_block. */ 455 int 456 find_tcp_function_alias(struct tcp_function_block *blk, 457 struct tcp_function_set *fs) 458 { 459 struct tcp_function *f; 460 int found; 461 462 found = 0; 463 rw_rlock(&tcp_function_lock); 464 TAILQ_FOREACH(f, &t_functions, tf_next) { 465 if ((f->tf_fb == blk) && 466 (strncmp(f->tf_name, blk->tfb_tcp_block_name, 467 TCP_FUNCTION_NAME_LEN_MAX) != 0)) { 468 /* Matching function block with different name. */ 469 strncpy(fs->function_set_name, f->tf_name, 470 TCP_FUNCTION_NAME_LEN_MAX); 471 found = 1; 472 break; 473 } 474 } 475 /* Null terminate the string appropriately. */ 476 if (found) { 477 fs->function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0'; 478 } else { 479 fs->function_set_name[0] = '\0'; 480 } 481 rw_runlock(&tcp_function_lock); 482 return (found); 483 } 484 485 static struct tcp_function_block * 486 find_and_ref_tcp_default_fb(void) 487 { 488 struct tcp_function_block *rblk; 489 490 rw_rlock(&tcp_function_lock); 491 rblk = V_tcp_func_set_ptr; 492 refcount_acquire(&rblk->tfb_refcnt); 493 rw_runlock(&tcp_function_lock); 494 return (rblk); 495 } 496 497 void 498 tcp_switch_back_to_default(struct tcpcb *tp) 499 { 500 struct tcp_function_block *tfb; 501 void *ptr = NULL; 502 503 KASSERT(tp->t_fb != &tcp_def_funcblk, 504 ("%s: called by the built-in default stack", __func__)); 505 506 if (tp->t_fb->tfb_tcp_timer_stop_all != NULL) 507 tp->t_fb->tfb_tcp_timer_stop_all(tp); 508 509 /* 510 * Now, we'll find a new function block to use. 511 * Start by trying the current user-selected 512 * default, unless this stack is the user-selected 513 * default. 514 */ 515 tfb = find_and_ref_tcp_default_fb(); 516 if (tfb == tp->t_fb) { 517 refcount_release(&tfb->tfb_refcnt); 518 tfb = NULL; 519 } 520 /* Does the stack accept this connection? */ 521 if (tfb != NULL && (*tfb->tfb_tcp_handoff_ok)(tp)) { 522 refcount_release(&tfb->tfb_refcnt); 523 tfb = NULL; 524 } 525 /* Try to use that stack. */ 526 if (tfb != NULL) { 527 /* Initialize the new stack. If it succeeds, we are done. */ 528 if (tfb->tfb_tcp_fb_init == NULL || 529 (*tfb->tfb_tcp_fb_init)(tp, &ptr) == 0) { 530 /* Release the old stack */ 531 if (tp->t_fb->tfb_tcp_fb_fini != NULL) 532 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0); 533 refcount_release(&tp->t_fb->tfb_refcnt); 534 /* Now set in all the pointers */ 535 tp->t_fb = tfb; 536 tp->t_fb_ptr = ptr; 537 return; 538 } 539 /* 540 * Initialization failed. Release the reference count on 541 * the looked up default stack. 542 */ 543 refcount_release(&tfb->tfb_refcnt); 544 } 545 546 /* 547 * If that wasn't feasible, use the built-in default 548 * stack which is not allowed to reject anyone. 549 */ 550 tfb = find_and_ref_tcp_fb(&tcp_def_funcblk); 551 if (tfb == NULL) { 552 /* there always should be a default */ 553 panic("Can't refer to tcp_def_funcblk"); 554 } 555 if ((*tfb->tfb_tcp_handoff_ok)(tp)) { 556 /* The default stack cannot say no */ 557 panic("Default stack rejects a new session?"); 558 } 559 if (tfb->tfb_tcp_fb_init != NULL && 560 (*tfb->tfb_tcp_fb_init)(tp, &ptr)) { 561 /* The default stack cannot fail */ 562 panic("Default stack initialization failed"); 563 } 564 /* Now release the old stack */ 565 if (tp->t_fb->tfb_tcp_fb_fini != NULL) 566 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0); 567 refcount_release(&tp->t_fb->tfb_refcnt); 568 /* And set in the pointers to the new */ 569 tp->t_fb = tfb; 570 tp->t_fb_ptr = ptr; 571 } 572 573 static bool 574 tcp_recv_udp_tunneled_packet(struct mbuf *m, int off, struct inpcb *inp, 575 const struct sockaddr *sa, void *ctx) 576 { 577 struct ip *iph; 578 #ifdef INET6 579 struct ip6_hdr *ip6; 580 #endif 581 struct udphdr *uh; 582 struct tcphdr *th; 583 int thlen; 584 uint16_t port; 585 586 TCPSTAT_INC(tcps_tunneled_pkts); 587 if ((m->m_flags & M_PKTHDR) == 0) { 588 /* Can't handle one that is not a pkt hdr */ 589 TCPSTAT_INC(tcps_tunneled_errs); 590 goto out; 591 } 592 thlen = sizeof(struct tcphdr); 593 if (m->m_len < off + sizeof(struct udphdr) + thlen && 594 (m = m_pullup(m, off + sizeof(struct udphdr) + thlen)) == NULL) { 595 TCPSTAT_INC(tcps_tunneled_errs); 596 goto out; 597 } 598 iph = mtod(m, struct ip *); 599 uh = (struct udphdr *)((caddr_t)iph + off); 600 th = (struct tcphdr *)(uh + 1); 601 thlen = th->th_off << 2; 602 if (m->m_len < off + sizeof(struct udphdr) + thlen) { 603 m = m_pullup(m, off + sizeof(struct udphdr) + thlen); 604 if (m == NULL) { 605 TCPSTAT_INC(tcps_tunneled_errs); 606 goto out; 607 } else { 608 iph = mtod(m, struct ip *); 609 uh = (struct udphdr *)((caddr_t)iph + off); 610 th = (struct tcphdr *)(uh + 1); 611 } 612 } 613 m->m_pkthdr.tcp_tun_port = port = uh->uh_sport; 614 bcopy(th, uh, m->m_len - off); 615 m->m_len -= sizeof(struct udphdr); 616 m->m_pkthdr.len -= sizeof(struct udphdr); 617 /* 618 * We use the same algorithm for 619 * both UDP and TCP for c-sum. So 620 * the code in tcp_input will skip 621 * the checksum. So we do nothing 622 * with the flag (m->m_pkthdr.csum_flags). 623 */ 624 switch (iph->ip_v) { 625 #ifdef INET 626 case IPVERSION: 627 iph->ip_len = htons(ntohs(iph->ip_len) - sizeof(struct udphdr)); 628 tcp_input_with_port(&m, &off, IPPROTO_TCP, port); 629 break; 630 #endif 631 #ifdef INET6 632 case IPV6_VERSION >> 4: 633 ip6 = mtod(m, struct ip6_hdr *); 634 ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) - sizeof(struct udphdr)); 635 tcp6_input_with_port(&m, &off, IPPROTO_TCP, port); 636 break; 637 #endif 638 default: 639 goto out; 640 break; 641 } 642 return (true); 643 out: 644 m_freem(m); 645 646 return (true); 647 } 648 649 static int 650 sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS) 651 { 652 int error = ENOENT; 653 struct tcp_function_set fs; 654 struct tcp_function_block *blk; 655 656 memset(&fs, 0, sizeof(fs)); 657 rw_rlock(&tcp_function_lock); 658 blk = find_tcp_fb_locked(V_tcp_func_set_ptr, NULL); 659 if (blk) { 660 /* Found him */ 661 strcpy(fs.function_set_name, blk->tfb_tcp_block_name); 662 fs.pcbcnt = blk->tfb_refcnt; 663 } 664 rw_runlock(&tcp_function_lock); 665 error = sysctl_handle_string(oidp, fs.function_set_name, 666 sizeof(fs.function_set_name), req); 667 668 /* Check for error or no change */ 669 if (error != 0 || req->newptr == NULL) 670 return (error); 671 672 rw_wlock(&tcp_function_lock); 673 blk = find_tcp_functions_locked(&fs); 674 if ((blk == NULL) || 675 (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) { 676 error = ENOENT; 677 goto done; 678 } 679 V_tcp_func_set_ptr = blk; 680 done: 681 rw_wunlock(&tcp_function_lock); 682 return (error); 683 } 684 685 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default, 686 CTLFLAG_VNET | CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 687 NULL, 0, sysctl_net_inet_default_tcp_functions, "A", 688 "Set/get the default TCP functions"); 689 690 static int 691 sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS) 692 { 693 int error, cnt, linesz; 694 struct tcp_function *f; 695 char *buffer, *cp; 696 size_t bufsz, outsz; 697 bool alias; 698 699 cnt = 0; 700 rw_rlock(&tcp_function_lock); 701 TAILQ_FOREACH(f, &t_functions, tf_next) { 702 cnt++; 703 } 704 rw_runlock(&tcp_function_lock); 705 706 bufsz = (cnt+2) * ((TCP_FUNCTION_NAME_LEN_MAX * 2) + 13) + 1; 707 buffer = malloc(bufsz, M_TEMP, M_WAITOK); 708 709 error = 0; 710 cp = buffer; 711 712 linesz = snprintf(cp, bufsz, "\n%-32s%c %-32s %s\n", "Stack", 'D', 713 "Alias", "PCB count"); 714 cp += linesz; 715 bufsz -= linesz; 716 outsz = linesz; 717 718 rw_rlock(&tcp_function_lock); 719 TAILQ_FOREACH(f, &t_functions, tf_next) { 720 alias = (f->tf_name != f->tf_fb->tfb_tcp_block_name); 721 linesz = snprintf(cp, bufsz, "%-32s%c %-32s %u\n", 722 f->tf_fb->tfb_tcp_block_name, 723 (f->tf_fb == V_tcp_func_set_ptr) ? '*' : ' ', 724 alias ? f->tf_name : "-", 725 f->tf_fb->tfb_refcnt); 726 if (linesz >= bufsz) { 727 error = EOVERFLOW; 728 break; 729 } 730 cp += linesz; 731 bufsz -= linesz; 732 outsz += linesz; 733 } 734 rw_runlock(&tcp_function_lock); 735 if (error == 0) 736 error = sysctl_handle_string(oidp, buffer, outsz + 1, req); 737 free(buffer, M_TEMP); 738 return (error); 739 } 740 741 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available, 742 CTLFLAG_VNET | CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, 743 NULL, 0, sysctl_net_inet_list_available, "A", 744 "list available TCP Function sets"); 745 746 VNET_DEFINE(int, tcp_udp_tunneling_port) = TCP_TUNNELING_PORT_DEFAULT; 747 748 #ifdef INET 749 VNET_DEFINE(struct socket *, udp4_tun_socket) = NULL; 750 #define V_udp4_tun_socket VNET(udp4_tun_socket) 751 #endif 752 #ifdef INET6 753 VNET_DEFINE(struct socket *, udp6_tun_socket) = NULL; 754 #define V_udp6_tun_socket VNET(udp6_tun_socket) 755 #endif 756 757 static struct sx tcpoudp_lock; 758 759 static void 760 tcp_over_udp_stop(void) 761 { 762 763 sx_assert(&tcpoudp_lock, SA_XLOCKED); 764 765 #ifdef INET 766 if (V_udp4_tun_socket != NULL) { 767 soclose(V_udp4_tun_socket); 768 V_udp4_tun_socket = NULL; 769 } 770 #endif 771 #ifdef INET6 772 if (V_udp6_tun_socket != NULL) { 773 soclose(V_udp6_tun_socket); 774 V_udp6_tun_socket = NULL; 775 } 776 #endif 777 } 778 779 static int 780 tcp_over_udp_start(void) 781 { 782 uint16_t port; 783 int ret; 784 #ifdef INET 785 struct sockaddr_in sin; 786 #endif 787 #ifdef INET6 788 struct sockaddr_in6 sin6; 789 #endif 790 791 sx_assert(&tcpoudp_lock, SA_XLOCKED); 792 793 port = V_tcp_udp_tunneling_port; 794 if (ntohs(port) == 0) { 795 /* Must have a port set */ 796 return (EINVAL); 797 } 798 #ifdef INET 799 if (V_udp4_tun_socket != NULL) { 800 /* Already running -- must stop first */ 801 return (EALREADY); 802 } 803 #endif 804 #ifdef INET6 805 if (V_udp6_tun_socket != NULL) { 806 /* Already running -- must stop first */ 807 return (EALREADY); 808 } 809 #endif 810 #ifdef INET 811 if ((ret = socreate(PF_INET, &V_udp4_tun_socket, 812 SOCK_DGRAM, IPPROTO_UDP, 813 curthread->td_ucred, curthread))) { 814 tcp_over_udp_stop(); 815 return (ret); 816 } 817 /* Call the special UDP hook. */ 818 if ((ret = udp_set_kernel_tunneling(V_udp4_tun_socket, 819 tcp_recv_udp_tunneled_packet, 820 tcp_ctlinput_viaudp, 821 NULL))) { 822 tcp_over_udp_stop(); 823 return (ret); 824 } 825 /* Ok, we have a socket, bind it to the port. */ 826 memset(&sin, 0, sizeof(struct sockaddr_in)); 827 sin.sin_len = sizeof(struct sockaddr_in); 828 sin.sin_family = AF_INET; 829 sin.sin_port = htons(port); 830 if ((ret = sobind(V_udp4_tun_socket, 831 (struct sockaddr *)&sin, curthread))) { 832 tcp_over_udp_stop(); 833 return (ret); 834 } 835 #endif 836 #ifdef INET6 837 if ((ret = socreate(PF_INET6, &V_udp6_tun_socket, 838 SOCK_DGRAM, IPPROTO_UDP, 839 curthread->td_ucred, curthread))) { 840 tcp_over_udp_stop(); 841 return (ret); 842 } 843 /* Call the special UDP hook. */ 844 if ((ret = udp_set_kernel_tunneling(V_udp6_tun_socket, 845 tcp_recv_udp_tunneled_packet, 846 tcp6_ctlinput_viaudp, 847 NULL))) { 848 tcp_over_udp_stop(); 849 return (ret); 850 } 851 /* Ok, we have a socket, bind it to the port. */ 852 memset(&sin6, 0, sizeof(struct sockaddr_in6)); 853 sin6.sin6_len = sizeof(struct sockaddr_in6); 854 sin6.sin6_family = AF_INET6; 855 sin6.sin6_port = htons(port); 856 if ((ret = sobind(V_udp6_tun_socket, 857 (struct sockaddr *)&sin6, curthread))) { 858 tcp_over_udp_stop(); 859 return (ret); 860 } 861 #endif 862 return (0); 863 } 864 865 static int 866 sysctl_net_inet_tcp_udp_tunneling_port_check(SYSCTL_HANDLER_ARGS) 867 { 868 int error; 869 uint32_t old, new; 870 871 old = V_tcp_udp_tunneling_port; 872 new = old; 873 error = sysctl_handle_int(oidp, &new, 0, req); 874 if ((error == 0) && 875 (req->newptr != NULL)) { 876 if ((new < TCP_TUNNELING_PORT_MIN) || 877 (new > TCP_TUNNELING_PORT_MAX)) { 878 error = EINVAL; 879 } else { 880 sx_xlock(&tcpoudp_lock); 881 V_tcp_udp_tunneling_port = new; 882 if (old != 0) { 883 tcp_over_udp_stop(); 884 } 885 if (new != 0) { 886 error = tcp_over_udp_start(); 887 if (error != 0) { 888 V_tcp_udp_tunneling_port = 0; 889 } 890 } 891 sx_xunlock(&tcpoudp_lock); 892 } 893 } 894 return (error); 895 } 896 897 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_port, 898 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 899 &VNET_NAME(tcp_udp_tunneling_port), 900 0, &sysctl_net_inet_tcp_udp_tunneling_port_check, "IU", 901 "Tunneling port for tcp over udp"); 902 903 VNET_DEFINE(int, tcp_udp_tunneling_overhead) = TCP_TUNNELING_OVERHEAD_DEFAULT; 904 905 static int 906 sysctl_net_inet_tcp_udp_tunneling_overhead_check(SYSCTL_HANDLER_ARGS) 907 { 908 int error, new; 909 910 new = V_tcp_udp_tunneling_overhead; 911 error = sysctl_handle_int(oidp, &new, 0, req); 912 if (error == 0 && req->newptr) { 913 if ((new < TCP_TUNNELING_OVERHEAD_MIN) || 914 (new > TCP_TUNNELING_OVERHEAD_MAX)) 915 error = EINVAL; 916 else 917 V_tcp_udp_tunneling_overhead = new; 918 } 919 return (error); 920 } 921 922 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_overhead, 923 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 924 &VNET_NAME(tcp_udp_tunneling_overhead), 925 0, &sysctl_net_inet_tcp_udp_tunneling_overhead_check, "IU", 926 "MSS reduction when using tcp over udp"); 927 928 /* 929 * Exports one (struct tcp_function_info) for each alias/name. 930 */ 931 static int 932 sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS) 933 { 934 int cnt, error; 935 struct tcp_function *f; 936 struct tcp_function_info tfi; 937 938 /* 939 * We don't allow writes. 940 */ 941 if (req->newptr != NULL) 942 return (EINVAL); 943 944 /* 945 * Wire the old buffer so we can directly copy the functions to 946 * user space without dropping the lock. 947 */ 948 if (req->oldptr != NULL) { 949 error = sysctl_wire_old_buffer(req, 0); 950 if (error) 951 return (error); 952 } 953 954 /* 955 * Walk the list and copy out matching entries. If INVARIANTS 956 * is compiled in, also walk the list to verify the length of 957 * the list matches what we have recorded. 958 */ 959 rw_rlock(&tcp_function_lock); 960 961 cnt = 0; 962 #ifndef INVARIANTS 963 if (req->oldptr == NULL) { 964 cnt = tcp_fb_cnt; 965 goto skip_loop; 966 } 967 #endif 968 TAILQ_FOREACH(f, &t_functions, tf_next) { 969 #ifdef INVARIANTS 970 cnt++; 971 #endif 972 if (req->oldptr != NULL) { 973 bzero(&tfi, sizeof(tfi)); 974 tfi.tfi_refcnt = f->tf_fb->tfb_refcnt; 975 tfi.tfi_id = f->tf_fb->tfb_id; 976 (void)strlcpy(tfi.tfi_alias, f->tf_name, 977 sizeof(tfi.tfi_alias)); 978 (void)strlcpy(tfi.tfi_name, 979 f->tf_fb->tfb_tcp_block_name, sizeof(tfi.tfi_name)); 980 error = SYSCTL_OUT(req, &tfi, sizeof(tfi)); 981 /* 982 * Don't stop on error, as that is the 983 * mechanism we use to accumulate length 984 * information if the buffer was too short. 985 */ 986 } 987 } 988 KASSERT(cnt == tcp_fb_cnt, 989 ("%s: cnt (%d) != tcp_fb_cnt (%d)", __func__, cnt, tcp_fb_cnt)); 990 #ifndef INVARIANTS 991 skip_loop: 992 #endif 993 rw_runlock(&tcp_function_lock); 994 if (req->oldptr == NULL) 995 error = SYSCTL_OUT(req, NULL, 996 (cnt + 1) * sizeof(struct tcp_function_info)); 997 998 return (error); 999 } 1000 1001 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, function_info, 1002 CTLTYPE_OPAQUE | CTLFLAG_SKIP | CTLFLAG_RD | CTLFLAG_MPSAFE, 1003 NULL, 0, sysctl_net_inet_list_func_info, "S,tcp_function_info", 1004 "List TCP function block name-to-ID mappings"); 1005 1006 /* 1007 * tfb_tcp_handoff_ok() function for the default stack. 1008 * Note that we'll basically try to take all comers. 1009 */ 1010 static int 1011 tcp_default_handoff_ok(struct tcpcb *tp) 1012 { 1013 1014 return (0); 1015 } 1016 1017 /* 1018 * tfb_tcp_fb_init() function for the default stack. 1019 * 1020 * This handles making sure we have appropriate timers set if you are 1021 * transitioning a socket that has some amount of setup done. 1022 * 1023 * The init() fuction from the default can *never* return non-zero i.e. 1024 * it is required to always succeed since it is the stack of last resort! 1025 */ 1026 static int 1027 tcp_default_fb_init(struct tcpcb *tp, void **ptr) 1028 { 1029 struct socket *so = tptosocket(tp); 1030 int rexmt; 1031 1032 INP_WLOCK_ASSERT(tptoinpcb(tp)); 1033 /* We don't use the pointer */ 1034 *ptr = NULL; 1035 1036 KASSERT(tp->t_state < TCPS_TIME_WAIT, 1037 ("%s: connection %p in unexpected state %d", __func__, tp, 1038 tp->t_state)); 1039 1040 /* Make sure we get no interesting mbuf queuing behavior */ 1041 /* All mbuf queue/ack compress flags should be off */ 1042 tcp_lro_features_off(tp); 1043 1044 /* Cancel the GP measurement in progress */ 1045 tp->t_flags &= ~TF_GPUTINPROG; 1046 /* Validate the timers are not in usec, if they are convert */ 1047 tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS); 1048 if ((tp->t_state == TCPS_SYN_SENT) || 1049 (tp->t_state == TCPS_SYN_RECEIVED)) 1050 rexmt = tcp_rexmit_initial * tcp_backoff[tp->t_rxtshift]; 1051 else 1052 rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift]; 1053 if (tp->t_rxtshift == 0) 1054 tp->t_rxtcur = rexmt; 1055 else 1056 TCPT_RANGESET(tp->t_rxtcur, rexmt, tp->t_rttmin, TCPTV_REXMTMAX); 1057 1058 /* 1059 * Nothing to do for ESTABLISHED or LISTEN states. And, we don't 1060 * know what to do for unexpected states (which includes TIME_WAIT). 1061 */ 1062 if (tp->t_state <= TCPS_LISTEN || tp->t_state >= TCPS_TIME_WAIT) 1063 return (0); 1064 1065 /* 1066 * Make sure some kind of transmission timer is set if there is 1067 * outstanding data. 1068 */ 1069 if ((!TCPS_HAVEESTABLISHED(tp->t_state) || sbavail(&so->so_snd) || 1070 tp->snd_una != tp->snd_max) && !(tcp_timer_active(tp, TT_REXMT) || 1071 tcp_timer_active(tp, TT_PERSIST))) { 1072 /* 1073 * If the session has established and it looks like it should 1074 * be in the persist state, set the persist timer. Otherwise, 1075 * set the retransmit timer. 1076 */ 1077 if (TCPS_HAVEESTABLISHED(tp->t_state) && tp->snd_wnd == 0 && 1078 (int32_t)(tp->snd_nxt - tp->snd_una) < 1079 (int32_t)sbavail(&so->so_snd)) 1080 tcp_setpersist(tp); 1081 else 1082 tcp_timer_activate(tp, TT_REXMT, TP_RXTCUR(tp)); 1083 } 1084 1085 /* All non-embryonic sessions get a keepalive timer. */ 1086 if (!tcp_timer_active(tp, TT_KEEP)) 1087 tcp_timer_activate(tp, TT_KEEP, 1088 TCPS_HAVEESTABLISHED(tp->t_state) ? TP_KEEPIDLE(tp) : 1089 TP_KEEPINIT(tp)); 1090 1091 /* 1092 * Make sure critical variables are initialized 1093 * if transitioning while in Recovery. 1094 */ 1095 if IN_FASTRECOVERY(tp->t_flags) { 1096 if (tp->sackhint.recover_fs == 0) 1097 tp->sackhint.recover_fs = max(1, 1098 tp->snd_nxt - tp->snd_una); 1099 } 1100 1101 return (0); 1102 } 1103 1104 /* 1105 * tfb_tcp_fb_fini() function for the default stack. 1106 * 1107 * This changes state as necessary (or prudent) to prepare for another stack 1108 * to assume responsibility for the connection. 1109 */ 1110 static void 1111 tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged) 1112 { 1113 1114 INP_WLOCK_ASSERT(tptoinpcb(tp)); 1115 1116 #ifdef TCP_BLACKBOX 1117 tcp_log_flowend(tp); 1118 #endif 1119 tp->t_acktime = 0; 1120 return; 1121 } 1122 1123 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers"); 1124 MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory"); 1125 1126 static struct mtx isn_mtx; 1127 1128 #define ISN_LOCK_INIT() mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF) 1129 #define ISN_LOCK() mtx_lock(&isn_mtx) 1130 #define ISN_UNLOCK() mtx_unlock(&isn_mtx) 1131 1132 INPCBSTORAGE_DEFINE(tcpcbstor, tcpcb, "tcpinp", "tcp_inpcb", "tcp", "tcphash"); 1133 1134 /* 1135 * Take a value and get the next power of 2 that doesn't overflow. 1136 * Used to size the tcp_inpcb hash buckets. 1137 */ 1138 static int 1139 maketcp_hashsize(int size) 1140 { 1141 int hashsize; 1142 1143 /* 1144 * auto tune. 1145 * get the next power of 2 higher than maxsockets. 1146 */ 1147 hashsize = 1 << fls(size); 1148 /* catch overflow, and just go one power of 2 smaller */ 1149 if (hashsize < size) { 1150 hashsize = 1 << (fls(size) - 1); 1151 } 1152 return (hashsize); 1153 } 1154 1155 static volatile int next_tcp_stack_id = 1; 1156 1157 /* 1158 * Register a TCP function block with the name provided in the names 1159 * array. (Note that this function does NOT automatically register 1160 * blk->tfb_tcp_block_name as a stack name. Therefore, you should 1161 * explicitly include blk->tfb_tcp_block_name in the list of names if 1162 * you wish to register the stack with that name.) 1163 * 1164 * Either all name registrations will succeed or all will fail. If 1165 * a name registration fails, the function will update the num_names 1166 * argument to point to the array index of the name that encountered 1167 * the failure. 1168 * 1169 * Returns 0 on success, or an error code on failure. 1170 */ 1171 int 1172 register_tcp_functions_as_names(struct tcp_function_block *blk, int wait, 1173 const char *names[], int *num_names) 1174 { 1175 struct tcp_function *f[TCP_FUNCTION_NAME_NUM_MAX]; 1176 struct tcp_function_set fs; 1177 int error, i, num_registered; 1178 1179 KASSERT(names != NULL, ("%s: Called with NULL name list", __func__)); 1180 KASSERT(*num_names > 0, 1181 ("%s: Called with non-positive length of name list", __func__)); 1182 KASSERT(rw_initialized(&tcp_function_lock), 1183 ("%s: called too early", __func__)); 1184 1185 if (*num_names > TCP_FUNCTION_NAME_NUM_MAX) { 1186 /* Too many names. */ 1187 *num_names = 0; 1188 return (E2BIG); 1189 } 1190 if ((blk->tfb_tcp_output == NULL) || 1191 (blk->tfb_tcp_do_segment == NULL) || 1192 (blk->tfb_tcp_ctloutput == NULL) || 1193 (blk->tfb_tcp_handoff_ok == NULL) || 1194 (strlen(blk->tfb_tcp_block_name) == 0)) { 1195 /* These functions are required and a name is needed. */ 1196 *num_names = 0; 1197 return (EINVAL); 1198 } 1199 1200 for (i = 0; i < *num_names; i++) { 1201 f[i] = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait); 1202 if (f[i] == NULL) { 1203 while (--i >= 0) 1204 free(f[i], M_TCPFUNCTIONS); 1205 *num_names = 0; 1206 return (ENOMEM); 1207 } 1208 } 1209 1210 num_registered = 0; 1211 rw_wlock(&tcp_function_lock); 1212 if (find_tcp_fb_locked(blk, NULL) != NULL) { 1213 /* A TCP function block can only be registered once. */ 1214 error = EALREADY; 1215 goto cleanup; 1216 } 1217 if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) { 1218 error = EINVAL; 1219 goto cleanup; 1220 } 1221 refcount_init(&blk->tfb_refcnt, 0); 1222 blk->tfb_id = atomic_fetchadd_int(&next_tcp_stack_id, 1); 1223 for (i = 0; i < *num_names; i++) { 1224 (void)strlcpy(fs.function_set_name, names[i], 1225 sizeof(fs.function_set_name)); 1226 if (find_tcp_functions_locked(&fs) != NULL) { 1227 /* Duplicate name space not allowed */ 1228 error = EALREADY; 1229 goto cleanup; 1230 } 1231 f[i]->tf_fb = blk; 1232 (void)strlcpy(f[i]->tf_name, names[i], sizeof(f[i]->tf_name)); 1233 TAILQ_INSERT_TAIL(&t_functions, f[i], tf_next); 1234 tcp_fb_cnt++; 1235 num_registered++; 1236 } 1237 rw_wunlock(&tcp_function_lock); 1238 return (0); 1239 1240 cleanup: 1241 /* Remove the entries just added. */ 1242 for (i = 0; i < *num_names; i++) { 1243 if (i < num_registered) { 1244 TAILQ_REMOVE(&t_functions, f[i], tf_next); 1245 tcp_fb_cnt--; 1246 } 1247 f[i]->tf_fb = NULL; 1248 free(f[i], M_TCPFUNCTIONS); 1249 } 1250 rw_wunlock(&tcp_function_lock); 1251 *num_names = num_registered; 1252 return (error); 1253 } 1254 1255 /* 1256 * Register a TCP function block using the name provided in the name 1257 * argument. 1258 * 1259 * Returns 0 on success, or an error code on failure. 1260 */ 1261 int 1262 register_tcp_functions_as_name(struct tcp_function_block *blk, const char *name, 1263 int wait) 1264 { 1265 const char *name_list[1]; 1266 int num_names, rv; 1267 1268 num_names = 1; 1269 if (name != NULL) 1270 name_list[0] = name; 1271 else 1272 name_list[0] = blk->tfb_tcp_block_name; 1273 rv = register_tcp_functions_as_names(blk, wait, name_list, &num_names); 1274 return (rv); 1275 } 1276 1277 /* 1278 * Register a TCP function block using the name defined in 1279 * blk->tfb_tcp_block_name. 1280 * 1281 * Returns 0 on success, or an error code on failure. 1282 */ 1283 int 1284 register_tcp_functions(struct tcp_function_block *blk, int wait) 1285 { 1286 1287 return (register_tcp_functions_as_name(blk, NULL, wait)); 1288 } 1289 1290 /* 1291 * Deregister all names associated with a function block. This 1292 * functionally removes the function block from use within the system. 1293 * 1294 * When called with a true quiesce argument, mark the function block 1295 * as being removed so no more stacks will use it and determine 1296 * whether the removal would succeed. 1297 * 1298 * When called with a false quiesce argument, actually attempt the 1299 * removal. 1300 * 1301 * When called with a force argument, attempt to switch all TCBs to 1302 * use the default stack instead of returning EBUSY. 1303 * 1304 * Returns 0 on success (or if the removal would succeed), or an error 1305 * code on failure. 1306 */ 1307 int 1308 deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce, 1309 bool force) 1310 { 1311 struct tcp_function *f; 1312 VNET_ITERATOR_DECL(vnet_iter); 1313 1314 if (blk == &tcp_def_funcblk) { 1315 /* You can't un-register the default */ 1316 return (EPERM); 1317 } 1318 rw_wlock(&tcp_function_lock); 1319 VNET_LIST_RLOCK_NOSLEEP(); 1320 VNET_FOREACH(vnet_iter) { 1321 CURVNET_SET(vnet_iter); 1322 if (blk == V_tcp_func_set_ptr) { 1323 /* You can't free the current default in some vnet. */ 1324 CURVNET_RESTORE(); 1325 VNET_LIST_RUNLOCK_NOSLEEP(); 1326 rw_wunlock(&tcp_function_lock); 1327 return (EBUSY); 1328 } 1329 CURVNET_RESTORE(); 1330 } 1331 VNET_LIST_RUNLOCK_NOSLEEP(); 1332 /* Mark the block so no more stacks can use it. */ 1333 blk->tfb_flags |= TCP_FUNC_BEING_REMOVED; 1334 /* 1335 * If TCBs are still attached to the stack, attempt to switch them 1336 * to the default stack. 1337 */ 1338 if (force && blk->tfb_refcnt) { 1339 struct inpcb *inp; 1340 struct tcpcb *tp; 1341 VNET_ITERATOR_DECL(vnet_iter); 1342 1343 rw_wunlock(&tcp_function_lock); 1344 1345 VNET_LIST_RLOCK(); 1346 VNET_FOREACH(vnet_iter) { 1347 CURVNET_SET(vnet_iter); 1348 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo, 1349 INPLOOKUP_WLOCKPCB); 1350 1351 while ((inp = inp_next(&inpi)) != NULL) { 1352 tp = intotcpcb(inp); 1353 if (tp == NULL || tp->t_fb != blk) 1354 continue; 1355 tcp_switch_back_to_default(tp); 1356 } 1357 CURVNET_RESTORE(); 1358 } 1359 VNET_LIST_RUNLOCK(); 1360 1361 rw_wlock(&tcp_function_lock); 1362 } 1363 if (blk->tfb_refcnt) { 1364 /* TCBs still attached. */ 1365 rw_wunlock(&tcp_function_lock); 1366 return (EBUSY); 1367 } 1368 if (quiesce) { 1369 /* Skip removal. */ 1370 rw_wunlock(&tcp_function_lock); 1371 return (0); 1372 } 1373 /* Remove any function names that map to this function block. */ 1374 while (find_tcp_fb_locked(blk, &f) != NULL) { 1375 TAILQ_REMOVE(&t_functions, f, tf_next); 1376 tcp_fb_cnt--; 1377 f->tf_fb = NULL; 1378 free(f, M_TCPFUNCTIONS); 1379 } 1380 rw_wunlock(&tcp_function_lock); 1381 return (0); 1382 } 1383 1384 static void 1385 tcp_drain(void) 1386 { 1387 struct epoch_tracker et; 1388 VNET_ITERATOR_DECL(vnet_iter); 1389 1390 if (!do_tcpdrain) 1391 return; 1392 1393 NET_EPOCH_ENTER(et); 1394 VNET_LIST_RLOCK_NOSLEEP(); 1395 VNET_FOREACH(vnet_iter) { 1396 CURVNET_SET(vnet_iter); 1397 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo, 1398 INPLOOKUP_WLOCKPCB); 1399 struct inpcb *inpb; 1400 struct tcpcb *tcpb; 1401 1402 /* 1403 * Walk the tcpbs, if existing, and flush the reassembly queue, 1404 * if there is one... 1405 * XXX: The "Net/3" implementation doesn't imply that the TCP 1406 * reassembly queue should be flushed, but in a situation 1407 * where we're really low on mbufs, this is potentially 1408 * useful. 1409 */ 1410 while ((inpb = inp_next(&inpi)) != NULL) { 1411 if ((tcpb = intotcpcb(inpb)) != NULL) { 1412 tcp_reass_flush(tcpb); 1413 tcp_clean_sackreport(tcpb); 1414 #ifdef TCP_BLACKBOX 1415 tcp_log_drain(tcpb); 1416 #endif 1417 #ifdef TCPPCAP 1418 if (tcp_pcap_aggressive_free) { 1419 /* Free the TCP PCAP queues. */ 1420 tcp_pcap_drain(&(tcpb->t_inpkts)); 1421 tcp_pcap_drain(&(tcpb->t_outpkts)); 1422 } 1423 #endif 1424 } 1425 } 1426 CURVNET_RESTORE(); 1427 } 1428 VNET_LIST_RUNLOCK_NOSLEEP(); 1429 NET_EPOCH_EXIT(et); 1430 } 1431 1432 static void 1433 tcp_vnet_init(void *arg __unused) 1434 { 1435 1436 #ifdef TCP_HHOOK 1437 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, 1438 &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0) 1439 printf("%s: WARNING: unable to register helper hook\n", __func__); 1440 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, 1441 &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0) 1442 printf("%s: WARNING: unable to register helper hook\n", __func__); 1443 #endif 1444 #ifdef STATS 1445 if (tcp_stats_init()) 1446 printf("%s: WARNING: unable to initialise TCP stats\n", 1447 __func__); 1448 #endif 1449 in_pcbinfo_init(&V_tcbinfo, &tcpcbstor, tcp_tcbhashsize, 1450 tcp_tcbhashsize); 1451 1452 syncache_init(); 1453 tcp_hc_init(); 1454 1455 TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack); 1456 V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole), 1457 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); 1458 1459 tcp_fastopen_init(); 1460 1461 COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK); 1462 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK); 1463 1464 V_tcp_msl = TCPTV_MSL; 1465 } 1466 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, 1467 tcp_vnet_init, NULL); 1468 1469 static void 1470 tcp_init(void *arg __unused) 1471 { 1472 int hashsize; 1473 1474 tcp_reass_global_init(); 1475 1476 /* XXX virtualize those below? */ 1477 tcp_delacktime = TCPTV_DELACK; 1478 tcp_keepinit = TCPTV_KEEP_INIT; 1479 tcp_keepidle = TCPTV_KEEP_IDLE; 1480 tcp_keepintvl = TCPTV_KEEPINTVL; 1481 tcp_maxpersistidle = TCPTV_KEEP_IDLE; 1482 tcp_rexmit_initial = TCPTV_RTOBASE; 1483 if (tcp_rexmit_initial < 1) 1484 tcp_rexmit_initial = 1; 1485 tcp_rexmit_min = TCPTV_MIN; 1486 if (tcp_rexmit_min < 1) 1487 tcp_rexmit_min = 1; 1488 tcp_persmin = TCPTV_PERSMIN; 1489 tcp_persmax = TCPTV_PERSMAX; 1490 tcp_rexmit_slop = TCPTV_CPU_VAR; 1491 tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT; 1492 1493 /* Setup the tcp function block list */ 1494 TAILQ_INIT(&t_functions); 1495 rw_init(&tcp_function_lock, "tcp_func_lock"); 1496 register_tcp_functions(&tcp_def_funcblk, M_WAITOK); 1497 sx_init(&tcpoudp_lock, "TCP over UDP configuration"); 1498 #ifdef TCP_BLACKBOX 1499 /* Initialize the TCP logging data. */ 1500 tcp_log_init(); 1501 #endif 1502 arc4rand(&V_ts_offset_secret, sizeof(V_ts_offset_secret), 0); 1503 1504 if (tcp_soreceive_stream) { 1505 #ifdef INET 1506 tcp_protosw.pr_soreceive = soreceive_stream; 1507 #endif 1508 #ifdef INET6 1509 tcp6_protosw.pr_soreceive = soreceive_stream; 1510 #endif /* INET6 */ 1511 } 1512 1513 #ifdef INET6 1514 max_protohdr_grow(sizeof(struct ip6_hdr) + sizeof(struct tcphdr)); 1515 #else /* INET6 */ 1516 max_protohdr_grow(sizeof(struct tcpiphdr)); 1517 #endif /* INET6 */ 1518 1519 ISN_LOCK_INIT(); 1520 EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL, 1521 SHUTDOWN_PRI_DEFAULT); 1522 EVENTHANDLER_REGISTER(vm_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT); 1523 EVENTHANDLER_REGISTER(mbuf_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT); 1524 1525 tcp_inp_lro_direct_queue = counter_u64_alloc(M_WAITOK); 1526 tcp_inp_lro_wokeup_queue = counter_u64_alloc(M_WAITOK); 1527 tcp_inp_lro_compressed = counter_u64_alloc(M_WAITOK); 1528 tcp_inp_lro_locks_taken = counter_u64_alloc(M_WAITOK); 1529 tcp_extra_mbuf = counter_u64_alloc(M_WAITOK); 1530 tcp_would_have_but = counter_u64_alloc(M_WAITOK); 1531 tcp_comp_total = counter_u64_alloc(M_WAITOK); 1532 tcp_uncomp_total = counter_u64_alloc(M_WAITOK); 1533 tcp_bad_csums = counter_u64_alloc(M_WAITOK); 1534 tcp_pacing_failures = counter_u64_alloc(M_WAITOK); 1535 tcp_dgp_failures = counter_u64_alloc(M_WAITOK); 1536 #ifdef TCPPCAP 1537 tcp_pcap_init(); 1538 #endif 1539 1540 hashsize = tcp_tcbhashsize; 1541 if (hashsize == 0) { 1542 /* 1543 * Auto tune the hash size based on maxsockets. 1544 * A perfect hash would have a 1:1 mapping 1545 * (hashsize = maxsockets) however it's been 1546 * suggested that O(2) average is better. 1547 */ 1548 hashsize = maketcp_hashsize(maxsockets / 4); 1549 /* 1550 * Our historical default is 512, 1551 * do not autotune lower than this. 1552 */ 1553 if (hashsize < 512) 1554 hashsize = 512; 1555 if (bootverbose) 1556 printf("%s: %s auto tuned to %d\n", __func__, 1557 "net.inet.tcp.tcbhashsize", hashsize); 1558 } 1559 /* 1560 * We require a hashsize to be a power of two. 1561 * Previously if it was not a power of two we would just reset it 1562 * back to 512, which could be a nasty surprise if you did not notice 1563 * the error message. 1564 * Instead what we do is clip it to the closest power of two lower 1565 * than the specified hash value. 1566 */ 1567 if (!powerof2(hashsize)) { 1568 int oldhashsize = hashsize; 1569 1570 hashsize = maketcp_hashsize(hashsize); 1571 /* prevent absurdly low value */ 1572 if (hashsize < 16) 1573 hashsize = 16; 1574 printf("%s: WARNING: TCB hash size not a power of 2, " 1575 "clipped from %d to %d.\n", __func__, oldhashsize, 1576 hashsize); 1577 } 1578 tcp_tcbhashsize = hashsize; 1579 1580 #ifdef INET 1581 IPPROTO_REGISTER(IPPROTO_TCP, tcp_input, tcp_ctlinput); 1582 #endif 1583 #ifdef INET6 1584 IP6PROTO_REGISTER(IPPROTO_TCP, tcp6_input, tcp6_ctlinput); 1585 #endif 1586 } 1587 SYSINIT(tcp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, tcp_init, NULL); 1588 1589 #ifdef VIMAGE 1590 static void 1591 tcp_destroy(void *unused __unused) 1592 { 1593 int n; 1594 #ifdef TCP_HHOOK 1595 int error; 1596 #endif 1597 1598 /* 1599 * All our processes are gone, all our sockets should be cleaned 1600 * up, which means, we should be past the tcp_discardcb() calls. 1601 * Sleep to let all tcpcb timers really disappear and cleanup. 1602 */ 1603 for (;;) { 1604 INP_INFO_WLOCK(&V_tcbinfo); 1605 n = V_tcbinfo.ipi_count; 1606 INP_INFO_WUNLOCK(&V_tcbinfo); 1607 if (n == 0) 1608 break; 1609 pause("tcpdes", hz / 10); 1610 } 1611 tcp_hc_destroy(); 1612 syncache_destroy(); 1613 in_pcbinfo_destroy(&V_tcbinfo); 1614 /* tcp_discardcb() clears the sack_holes up. */ 1615 uma_zdestroy(V_sack_hole_zone); 1616 1617 /* 1618 * Cannot free the zone until all tcpcbs are released as we attach 1619 * the allocations to them. 1620 */ 1621 tcp_fastopen_destroy(); 1622 1623 COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES); 1624 VNET_PCPUSTAT_FREE(tcpstat); 1625 1626 #ifdef TCP_HHOOK 1627 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]); 1628 if (error != 0) { 1629 printf("%s: WARNING: unable to deregister helper hook " 1630 "type=%d, id=%d: error %d returned\n", __func__, 1631 HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error); 1632 } 1633 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]); 1634 if (error != 0) { 1635 printf("%s: WARNING: unable to deregister helper hook " 1636 "type=%d, id=%d: error %d returned\n", __func__, 1637 HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error); 1638 } 1639 #endif 1640 } 1641 VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_destroy, NULL); 1642 #endif 1643 1644 void 1645 tcp_fini(void *xtp) 1646 { 1647 1648 } 1649 1650 /* 1651 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb. 1652 * tcp_template used to store this data in mbufs, but we now recopy it out 1653 * of the tcpcb each time to conserve mbufs. 1654 */ 1655 void 1656 tcpip_fillheaders(struct inpcb *inp, uint16_t port, void *ip_ptr, void *tcp_ptr) 1657 { 1658 struct tcphdr *th = (struct tcphdr *)tcp_ptr; 1659 1660 INP_WLOCK_ASSERT(inp); 1661 1662 #ifdef INET6 1663 if ((inp->inp_vflag & INP_IPV6) != 0) { 1664 struct ip6_hdr *ip6; 1665 1666 ip6 = (struct ip6_hdr *)ip_ptr; 1667 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) | 1668 (inp->inp_flow & IPV6_FLOWINFO_MASK); 1669 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) | 1670 (IPV6_VERSION & IPV6_VERSION_MASK); 1671 if (port == 0) 1672 ip6->ip6_nxt = IPPROTO_TCP; 1673 else 1674 ip6->ip6_nxt = IPPROTO_UDP; 1675 ip6->ip6_plen = htons(sizeof(struct tcphdr)); 1676 ip6->ip6_src = inp->in6p_laddr; 1677 ip6->ip6_dst = inp->in6p_faddr; 1678 } 1679 #endif /* INET6 */ 1680 #if defined(INET6) && defined(INET) 1681 else 1682 #endif 1683 #ifdef INET 1684 { 1685 struct ip *ip; 1686 1687 ip = (struct ip *)ip_ptr; 1688 ip->ip_v = IPVERSION; 1689 ip->ip_hl = 5; 1690 ip->ip_tos = inp->inp_ip_tos; 1691 ip->ip_len = 0; 1692 ip->ip_id = 0; 1693 ip->ip_off = 0; 1694 ip->ip_ttl = inp->inp_ip_ttl; 1695 ip->ip_sum = 0; 1696 if (port == 0) 1697 ip->ip_p = IPPROTO_TCP; 1698 else 1699 ip->ip_p = IPPROTO_UDP; 1700 ip->ip_src = inp->inp_laddr; 1701 ip->ip_dst = inp->inp_faddr; 1702 } 1703 #endif /* INET */ 1704 th->th_sport = inp->inp_lport; 1705 th->th_dport = inp->inp_fport; 1706 th->th_seq = 0; 1707 th->th_ack = 0; 1708 th->th_off = 5; 1709 tcp_set_flags(th, 0); 1710 th->th_win = 0; 1711 th->th_urp = 0; 1712 th->th_sum = 0; /* in_pseudo() is called later for ipv4 */ 1713 } 1714 1715 /* 1716 * Create template to be used to send tcp packets on a connection. 1717 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only 1718 * use for this function is in keepalives, which use tcp_respond. 1719 */ 1720 struct tcptemp * 1721 tcpip_maketemplate(struct inpcb *inp) 1722 { 1723 struct tcptemp *t; 1724 1725 t = malloc(sizeof(*t), M_TEMP, M_NOWAIT); 1726 if (t == NULL) 1727 return (NULL); 1728 tcpip_fillheaders(inp, 0, (void *)&t->tt_ipgen, (void *)&t->tt_t); 1729 return (t); 1730 } 1731 1732 /* 1733 * Send a single message to the TCP at address specified by 1734 * the given TCP/IP header. If m == NULL, then we make a copy 1735 * of the tcpiphdr at th and send directly to the addressed host. 1736 * This is used to force keep alive messages out using the TCP 1737 * template for a connection. If flags are given then we send 1738 * a message back to the TCP which originated the segment th, 1739 * and discard the mbuf containing it and any other attached mbufs. 1740 * 1741 * In any case the ack and sequence number of the transmitted 1742 * segment are as specified by the parameters. 1743 * 1744 * NOTE: If m != NULL, then th must point to *inside* the mbuf. 1745 */ 1746 1747 void 1748 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m, 1749 tcp_seq ack, tcp_seq seq, uint16_t flags) 1750 { 1751 struct tcpopt to; 1752 struct inpcb *inp; 1753 struct ip *ip; 1754 struct mbuf *optm; 1755 struct udphdr *uh = NULL; 1756 struct tcphdr *nth; 1757 struct tcp_log_buffer *lgb; 1758 u_char *optp; 1759 #ifdef INET6 1760 struct ip6_hdr *ip6; 1761 int isipv6; 1762 #endif /* INET6 */ 1763 int optlen, tlen, win, ulen; 1764 int ect = 0; 1765 bool incl_opts; 1766 uint16_t port; 1767 int output_ret; 1768 #ifdef INVARIANTS 1769 int thflags = tcp_get_flags(th); 1770 #endif 1771 1772 KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL")); 1773 NET_EPOCH_ASSERT(); 1774 1775 #ifdef INET6 1776 isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4); 1777 ip6 = ipgen; 1778 #endif /* INET6 */ 1779 ip = ipgen; 1780 1781 if (tp != NULL) { 1782 inp = tptoinpcb(tp); 1783 INP_LOCK_ASSERT(inp); 1784 } else 1785 inp = NULL; 1786 1787 if (m != NULL) { 1788 #ifdef INET6 1789 if (isipv6 && ip6 && (ip6->ip6_nxt == IPPROTO_UDP)) 1790 port = m->m_pkthdr.tcp_tun_port; 1791 else 1792 #endif 1793 if (ip && (ip->ip_p == IPPROTO_UDP)) 1794 port = m->m_pkthdr.tcp_tun_port; 1795 else 1796 port = 0; 1797 } else 1798 port = tp->t_port; 1799 1800 incl_opts = false; 1801 win = 0; 1802 if (tp != NULL) { 1803 if (!(flags & TH_RST)) { 1804 win = sbspace(&inp->inp_socket->so_rcv); 1805 if (win > TCP_MAXWIN << tp->rcv_scale) 1806 win = TCP_MAXWIN << tp->rcv_scale; 1807 } 1808 if ((tp->t_flags & TF_NOOPT) == 0) 1809 incl_opts = true; 1810 } 1811 if (m == NULL) { 1812 m = m_gethdr(M_NOWAIT, MT_DATA); 1813 if (m == NULL) 1814 return; 1815 m->m_data += max_linkhdr; 1816 #ifdef INET6 1817 if (isipv6) { 1818 bcopy((caddr_t)ip6, mtod(m, caddr_t), 1819 sizeof(struct ip6_hdr)); 1820 ip6 = mtod(m, struct ip6_hdr *); 1821 nth = (struct tcphdr *)(ip6 + 1); 1822 if (port) { 1823 /* Insert a UDP header */ 1824 uh = (struct udphdr *)nth; 1825 uh->uh_sport = htons(V_tcp_udp_tunneling_port); 1826 uh->uh_dport = port; 1827 nth = (struct tcphdr *)(uh + 1); 1828 } 1829 } else 1830 #endif /* INET6 */ 1831 { 1832 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip)); 1833 ip = mtod(m, struct ip *); 1834 nth = (struct tcphdr *)(ip + 1); 1835 if (port) { 1836 /* Insert a UDP header */ 1837 uh = (struct udphdr *)nth; 1838 uh->uh_sport = htons(V_tcp_udp_tunneling_port); 1839 uh->uh_dport = port; 1840 nth = (struct tcphdr *)(uh + 1); 1841 } 1842 } 1843 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr)); 1844 flags = TH_ACK; 1845 } else if ((!M_WRITABLE(m)) || (port != 0)) { 1846 struct mbuf *n; 1847 1848 /* Can't reuse 'm', allocate a new mbuf. */ 1849 n = m_gethdr(M_NOWAIT, MT_DATA); 1850 if (n == NULL) { 1851 m_freem(m); 1852 return; 1853 } 1854 1855 if (!m_dup_pkthdr(n, m, M_NOWAIT)) { 1856 m_freem(m); 1857 m_freem(n); 1858 return; 1859 } 1860 1861 n->m_data += max_linkhdr; 1862 /* m_len is set later */ 1863 #define xchg(a,b,type) { type t; t=a; a=b; b=t; } 1864 #ifdef INET6 1865 if (isipv6) { 1866 bcopy((caddr_t)ip6, mtod(n, caddr_t), 1867 sizeof(struct ip6_hdr)); 1868 ip6 = mtod(n, struct ip6_hdr *); 1869 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr); 1870 nth = (struct tcphdr *)(ip6 + 1); 1871 if (port) { 1872 /* Insert a UDP header */ 1873 uh = (struct udphdr *)nth; 1874 uh->uh_sport = htons(V_tcp_udp_tunneling_port); 1875 uh->uh_dport = port; 1876 nth = (struct tcphdr *)(uh + 1); 1877 } 1878 } else 1879 #endif /* INET6 */ 1880 { 1881 bcopy((caddr_t)ip, mtod(n, caddr_t), sizeof(struct ip)); 1882 ip = mtod(n, struct ip *); 1883 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t); 1884 nth = (struct tcphdr *)(ip + 1); 1885 if (port) { 1886 /* Insert a UDP header */ 1887 uh = (struct udphdr *)nth; 1888 uh->uh_sport = htons(V_tcp_udp_tunneling_port); 1889 uh->uh_dport = port; 1890 nth = (struct tcphdr *)(uh + 1); 1891 } 1892 } 1893 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr)); 1894 xchg(nth->th_dport, nth->th_sport, uint16_t); 1895 th = nth; 1896 m_freem(m); 1897 m = n; 1898 } else { 1899 /* 1900 * reuse the mbuf. 1901 * XXX MRT We inherit the FIB, which is lucky. 1902 */ 1903 m_freem(m->m_next); 1904 m->m_next = NULL; 1905 m->m_data = (caddr_t)ipgen; 1906 /* clear any receive flags for proper bpf timestamping */ 1907 m->m_flags &= ~(M_TSTMP | M_TSTMP_LRO); 1908 /* m_len is set later */ 1909 #ifdef INET6 1910 if (isipv6) { 1911 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr); 1912 nth = (struct tcphdr *)(ip6 + 1); 1913 } else 1914 #endif /* INET6 */ 1915 { 1916 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t); 1917 nth = (struct tcphdr *)(ip + 1); 1918 } 1919 if (th != nth) { 1920 /* 1921 * this is usually a case when an extension header 1922 * exists between the IPv6 header and the 1923 * TCP header. 1924 */ 1925 nth->th_sport = th->th_sport; 1926 nth->th_dport = th->th_dport; 1927 } 1928 xchg(nth->th_dport, nth->th_sport, uint16_t); 1929 #undef xchg 1930 } 1931 tlen = 0; 1932 #ifdef INET6 1933 if (isipv6) 1934 tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr); 1935 #endif 1936 #if defined(INET) && defined(INET6) 1937 else 1938 #endif 1939 #ifdef INET 1940 tlen = sizeof (struct tcpiphdr); 1941 #endif 1942 if (port) 1943 tlen += sizeof (struct udphdr); 1944 #ifdef INVARIANTS 1945 m->m_len = 0; 1946 KASSERT(M_TRAILINGSPACE(m) >= tlen, 1947 ("Not enough trailing space for message (m=%p, need=%d, have=%ld)", 1948 m, tlen, (long)M_TRAILINGSPACE(m))); 1949 #endif 1950 m->m_len = tlen; 1951 to.to_flags = 0; 1952 if (incl_opts) { 1953 ect = tcp_ecn_output_established(tp, &flags, 0, false); 1954 /* Make sure we have room. */ 1955 if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) { 1956 m->m_next = m_get(M_NOWAIT, MT_DATA); 1957 if (m->m_next) { 1958 optp = mtod(m->m_next, u_char *); 1959 optm = m->m_next; 1960 } else 1961 incl_opts = false; 1962 } else { 1963 optp = (u_char *) (nth + 1); 1964 optm = m; 1965 } 1966 } 1967 if (incl_opts) { 1968 /* Timestamps. */ 1969 if (tp->t_flags & TF_RCVD_TSTMP) { 1970 to.to_tsval = tcp_ts_getticks() + tp->ts_offset; 1971 to.to_tsecr = tp->ts_recent; 1972 to.to_flags |= TOF_TS; 1973 } 1974 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1975 /* TCP-MD5 (RFC2385). */ 1976 if (tp->t_flags & TF_SIGNATURE) 1977 to.to_flags |= TOF_SIGNATURE; 1978 #endif 1979 /* Add the options. */ 1980 tlen += optlen = tcp_addoptions(&to, optp); 1981 1982 /* Update m_len in the correct mbuf. */ 1983 optm->m_len += optlen; 1984 } else 1985 optlen = 0; 1986 #ifdef INET6 1987 if (isipv6) { 1988 if (uh) { 1989 ulen = tlen - sizeof(struct ip6_hdr); 1990 uh->uh_ulen = htons(ulen); 1991 } 1992 ip6->ip6_flow = htonl(ect << IPV6_FLOWLABEL_LEN); 1993 ip6->ip6_vfc = IPV6_VERSION; 1994 if (port) 1995 ip6->ip6_nxt = IPPROTO_UDP; 1996 else 1997 ip6->ip6_nxt = IPPROTO_TCP; 1998 ip6->ip6_plen = htons(tlen - sizeof(*ip6)); 1999 } 2000 #endif 2001 #if defined(INET) && defined(INET6) 2002 else 2003 #endif 2004 #ifdef INET 2005 { 2006 if (uh) { 2007 ulen = tlen - sizeof(struct ip); 2008 uh->uh_ulen = htons(ulen); 2009 } 2010 ip->ip_len = htons(tlen); 2011 if (inp != NULL) { 2012 ip->ip_tos = inp->inp_ip_tos & ~IPTOS_ECN_MASK; 2013 ip->ip_ttl = inp->inp_ip_ttl; 2014 } else { 2015 ip->ip_tos = 0; 2016 ip->ip_ttl = V_ip_defttl; 2017 } 2018 ip->ip_tos |= ect; 2019 if (port) { 2020 ip->ip_p = IPPROTO_UDP; 2021 } else { 2022 ip->ip_p = IPPROTO_TCP; 2023 } 2024 if (V_path_mtu_discovery) 2025 ip->ip_off |= htons(IP_DF); 2026 } 2027 #endif 2028 m->m_pkthdr.len = tlen; 2029 m->m_pkthdr.rcvif = NULL; 2030 #ifdef MAC 2031 if (inp != NULL) { 2032 /* 2033 * Packet is associated with a socket, so allow the 2034 * label of the response to reflect the socket label. 2035 */ 2036 INP_LOCK_ASSERT(inp); 2037 mac_inpcb_create_mbuf(inp, m); 2038 } else { 2039 /* 2040 * Packet is not associated with a socket, so possibly 2041 * update the label in place. 2042 */ 2043 mac_netinet_tcp_reply(m); 2044 } 2045 #endif 2046 nth->th_seq = htonl(seq); 2047 nth->th_ack = htonl(ack); 2048 nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2; 2049 tcp_set_flags(nth, flags); 2050 if (tp && (flags & TH_RST)) { 2051 /* Log the reset */ 2052 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST); 2053 } 2054 if (tp != NULL) 2055 nth->th_win = htons((u_short) (win >> tp->rcv_scale)); 2056 else 2057 nth->th_win = htons((u_short)win); 2058 nth->th_urp = 0; 2059 2060 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 2061 if (to.to_flags & TOF_SIGNATURE) { 2062 if (!TCPMD5_ENABLED() || 2063 TCPMD5_OUTPUT(m, nth, to.to_signature) != 0) { 2064 m_freem(m); 2065 return; 2066 } 2067 } 2068 #endif 2069 2070 #ifdef INET6 2071 if (isipv6) { 2072 if (port) { 2073 m->m_pkthdr.csum_flags = CSUM_UDP_IPV6; 2074 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum); 2075 uh->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0); 2076 nth->th_sum = 0; 2077 } else { 2078 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6; 2079 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 2080 nth->th_sum = in6_cksum_pseudo(ip6, 2081 tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0); 2082 } 2083 ip6->ip6_hlim = in6_selecthlim(inp, NULL); 2084 } 2085 #endif /* INET6 */ 2086 #if defined(INET6) && defined(INET) 2087 else 2088 #endif 2089 #ifdef INET 2090 { 2091 if (port) { 2092 uh->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 2093 htons(ulen + IPPROTO_UDP)); 2094 m->m_pkthdr.csum_flags = CSUM_UDP; 2095 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum); 2096 nth->th_sum = 0; 2097 } else { 2098 m->m_pkthdr.csum_flags = CSUM_TCP; 2099 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 2100 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 2101 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p))); 2102 } 2103 } 2104 #endif /* INET */ 2105 TCP_PROBE3(debug__output, tp, th, m); 2106 if (flags & TH_RST) 2107 TCP_PROBE5(accept__refused, NULL, NULL, m, tp, nth); 2108 lgb = NULL; 2109 if ((tp != NULL) && tcp_bblogging_on(tp)) { 2110 if (INP_WLOCKED(inp)) { 2111 union tcp_log_stackspecific log; 2112 struct timeval tv; 2113 2114 memset(&log.u_bbr, 0, sizeof(log.u_bbr)); 2115 log.u_bbr.inhpts = tcp_in_hpts(tp); 2116 log.u_bbr.flex8 = 4; 2117 log.u_bbr.pkts_out = tp->t_maxseg; 2118 log.u_bbr.timeStamp = tcp_get_usecs(&tv); 2119 log.u_bbr.delivered = 0; 2120 lgb = tcp_log_event(tp, nth, NULL, NULL, TCP_LOG_OUT, 2121 ERRNO_UNK, 0, &log, false, NULL, NULL, 0, &tv); 2122 } else { 2123 /* 2124 * We can not log the packet, since we only own the 2125 * read lock, but a write lock is needed. The read lock 2126 * is not upgraded to a write lock, since only getting 2127 * the read lock was done intentionally to improve the 2128 * handling of SYN flooding attacks. 2129 * This happens only for pure SYN segments received in 2130 * the initial CLOSED state, or received in a more 2131 * advanced state than listen and the UDP encapsulation 2132 * port is unexpected. 2133 * The incoming SYN segments do not really belong to 2134 * the TCP connection and the handling does not change 2135 * the state of the TCP connection. Therefore, the 2136 * sending of the RST segments is not logged. Please 2137 * note that also the incoming SYN segments are not 2138 * logged. 2139 * 2140 * The following code ensures that the above description 2141 * is and stays correct. 2142 */ 2143 KASSERT((thflags & (TH_ACK|TH_SYN)) == TH_SYN && 2144 (tp->t_state == TCPS_CLOSED || 2145 (tp->t_state > TCPS_LISTEN && tp->t_port != port)), 2146 ("%s: Logging of TCP segment with flags 0x%b and " 2147 "UDP encapsulation port %u skipped in state %s", 2148 __func__, thflags, PRINT_TH_FLAGS, 2149 ntohs(port), tcpstates[tp->t_state])); 2150 } 2151 } 2152 2153 if (flags & TH_ACK) 2154 TCPSTAT_INC(tcps_sndacks); 2155 else if (flags & (TH_SYN|TH_FIN|TH_RST)) 2156 TCPSTAT_INC(tcps_sndctrl); 2157 TCPSTAT_INC(tcps_sndtotal); 2158 2159 #ifdef INET6 2160 if (isipv6) { 2161 TCP_PROBE5(send, NULL, tp, ip6, tp, nth); 2162 output_ret = ip6_output(m, inp ? inp->in6p_outputopts : NULL, 2163 NULL, 0, NULL, NULL, inp); 2164 } 2165 #endif /* INET6 */ 2166 #if defined(INET) && defined(INET6) 2167 else 2168 #endif 2169 #ifdef INET 2170 { 2171 TCP_PROBE5(send, NULL, tp, ip, tp, nth); 2172 output_ret = ip_output(m, NULL, NULL, 0, NULL, inp); 2173 } 2174 #endif 2175 if (lgb != NULL) 2176 lgb->tlb_errno = output_ret; 2177 } 2178 2179 /* 2180 * Create a new TCP control block, making an empty reassembly queue and hooking 2181 * it to the argument protocol control block. The `inp' parameter must have 2182 * come from the zone allocator set up by tcpcbstor declaration. 2183 */ 2184 struct tcpcb * 2185 tcp_newtcpcb(struct inpcb *inp) 2186 { 2187 struct tcpcb *tp = intotcpcb(inp); 2188 #ifdef INET6 2189 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 2190 #endif /* INET6 */ 2191 2192 /* 2193 * Historically allocation was done with M_ZERO. There is a lot of 2194 * code that rely on that. For now take safe approach and zero whole 2195 * tcpcb. This definitely can be optimized. 2196 */ 2197 bzero(&tp->t_start_zero, t_zero_size); 2198 2199 /* Initialise cc_var struct for this tcpcb. */ 2200 tp->t_ccv.type = IPPROTO_TCP; 2201 tp->t_ccv.ccvc.tcp = tp; 2202 rw_rlock(&tcp_function_lock); 2203 tp->t_fb = V_tcp_func_set_ptr; 2204 refcount_acquire(&tp->t_fb->tfb_refcnt); 2205 rw_runlock(&tcp_function_lock); 2206 /* 2207 * Use the current system default CC algorithm. 2208 */ 2209 cc_attach(tp, CC_DEFAULT_ALGO()); 2210 2211 if (CC_ALGO(tp)->cb_init != NULL) 2212 if (CC_ALGO(tp)->cb_init(&tp->t_ccv, NULL) > 0) { 2213 cc_detach(tp); 2214 if (tp->t_fb->tfb_tcp_fb_fini) 2215 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 2216 refcount_release(&tp->t_fb->tfb_refcnt); 2217 return (NULL); 2218 } 2219 2220 #ifdef TCP_HHOOK 2221 if (khelp_init_osd(HELPER_CLASS_TCP, &tp->t_osd)) { 2222 if (CC_ALGO(tp)->cb_destroy != NULL) 2223 CC_ALGO(tp)->cb_destroy(&tp->t_ccv); 2224 CC_DATA(tp) = NULL; 2225 cc_detach(tp); 2226 if (tp->t_fb->tfb_tcp_fb_fini) 2227 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 2228 refcount_release(&tp->t_fb->tfb_refcnt); 2229 return (NULL); 2230 } 2231 #endif 2232 2233 TAILQ_INIT(&tp->t_segq); 2234 STAILQ_INIT(&tp->t_inqueue); 2235 tp->t_maxseg = 2236 #ifdef INET6 2237 isipv6 ? V_tcp_v6mssdflt : 2238 #endif /* INET6 */ 2239 V_tcp_mssdflt; 2240 2241 /* All mbuf queue/ack compress flags should be off */ 2242 tcp_lro_features_off(tp); 2243 2244 tp->t_hpts_cpu = HPTS_CPU_NONE; 2245 tp->t_lro_cpu = HPTS_CPU_NONE; 2246 2247 callout_init_rw(&tp->t_callout, &inp->inp_lock, CALLOUT_RETURNUNLOCKED); 2248 for (int i = 0; i < TT_N; i++) 2249 tp->t_timers[i] = SBT_MAX; 2250 2251 switch (V_tcp_do_rfc1323) { 2252 case 0: 2253 break; 2254 default: 2255 case 1: 2256 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP); 2257 break; 2258 case 2: 2259 tp->t_flags = TF_REQ_SCALE; 2260 break; 2261 case 3: 2262 tp->t_flags = TF_REQ_TSTMP; 2263 break; 2264 } 2265 if (V_tcp_do_sack) 2266 tp->t_flags |= TF_SACK_PERMIT; 2267 TAILQ_INIT(&tp->snd_holes); 2268 2269 /* 2270 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no 2271 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives 2272 * reasonable initial retransmit time. 2273 */ 2274 tp->t_srtt = TCPTV_SRTTBASE; 2275 tp->t_rttvar = ((tcp_rexmit_initial - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4; 2276 tp->t_rttmin = tcp_rexmit_min; 2277 tp->t_rxtcur = tcp_rexmit_initial; 2278 tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT; 2279 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT; 2280 tp->t_rcvtime = ticks; 2281 /* We always start with ticks granularity */ 2282 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS; 2283 /* 2284 * IPv4 TTL initialization is necessary for an IPv6 socket as well, 2285 * because the socket may be bound to an IPv6 wildcard address, 2286 * which may match an IPv4-mapped IPv6 address. 2287 */ 2288 inp->inp_ip_ttl = V_ip_defttl; 2289 #ifdef TCPPCAP 2290 /* 2291 * Init the TCP PCAP queues. 2292 */ 2293 tcp_pcap_tcpcb_init(tp); 2294 #endif 2295 #ifdef TCP_BLACKBOX 2296 /* Initialize the per-TCPCB log data. */ 2297 tcp_log_tcpcbinit(tp); 2298 #endif 2299 tp->t_pacing_rate = -1; 2300 if (tp->t_fb->tfb_tcp_fb_init) { 2301 if ((*tp->t_fb->tfb_tcp_fb_init)(tp, &tp->t_fb_ptr)) { 2302 if (CC_ALGO(tp)->cb_destroy != NULL) 2303 CC_ALGO(tp)->cb_destroy(&tp->t_ccv); 2304 CC_DATA(tp) = NULL; 2305 cc_detach(tp); 2306 #ifdef TCP_HHOOK 2307 khelp_destroy_osd(&tp->t_osd); 2308 #endif 2309 refcount_release(&tp->t_fb->tfb_refcnt); 2310 return (NULL); 2311 } 2312 } 2313 #ifdef STATS 2314 if (V_tcp_perconn_stats_enable == 1) 2315 tp->t_stats = stats_blob_alloc(V_tcp_perconn_stats_dflt_tpl, 0); 2316 #endif 2317 if (V_tcp_do_lrd) 2318 tp->t_flags |= TF_LRD; 2319 2320 return (tp); 2321 } 2322 2323 /* 2324 * Drop a TCP connection, reporting 2325 * the specified error. If connection is synchronized, 2326 * then send a RST to peer. 2327 */ 2328 struct tcpcb * 2329 tcp_drop(struct tcpcb *tp, int errno) 2330 { 2331 struct socket *so = tptosocket(tp); 2332 2333 NET_EPOCH_ASSERT(); 2334 INP_WLOCK_ASSERT(tptoinpcb(tp)); 2335 2336 if (TCPS_HAVERCVDSYN(tp->t_state)) { 2337 tcp_state_change(tp, TCPS_CLOSED); 2338 /* Don't use tcp_output() here due to possible recursion. */ 2339 (void)tcp_output_nodrop(tp); 2340 TCPSTAT_INC(tcps_drops); 2341 } else 2342 TCPSTAT_INC(tcps_conndrops); 2343 if (errno == ETIMEDOUT && tp->t_softerror) 2344 errno = tp->t_softerror; 2345 so->so_error = errno; 2346 return (tcp_close(tp)); 2347 } 2348 2349 void 2350 tcp_discardcb(struct tcpcb *tp) 2351 { 2352 struct inpcb *inp = tptoinpcb(tp); 2353 struct socket *so = tptosocket(tp); 2354 struct mbuf *m; 2355 #ifdef INET6 2356 bool isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 2357 #endif 2358 2359 INP_WLOCK_ASSERT(inp); 2360 MPASS(!callout_active(&tp->t_callout)); 2361 MPASS(TAILQ_EMPTY(&tp->snd_holes)); 2362 2363 /* free the reassembly queue, if any */ 2364 tcp_reass_flush(tp); 2365 2366 #ifdef TCP_OFFLOAD 2367 /* Disconnect offload device, if any. */ 2368 if (tp->t_flags & TF_TOE) 2369 tcp_offload_detach(tp); 2370 #endif 2371 #ifdef TCPPCAP 2372 /* Free the TCP PCAP queues. */ 2373 tcp_pcap_drain(&(tp->t_inpkts)); 2374 tcp_pcap_drain(&(tp->t_outpkts)); 2375 #endif 2376 2377 /* Allow the CC algorithm to clean up after itself. */ 2378 if (CC_ALGO(tp)->cb_destroy != NULL) 2379 CC_ALGO(tp)->cb_destroy(&tp->t_ccv); 2380 CC_DATA(tp) = NULL; 2381 /* Detach from the CC algorithm */ 2382 cc_detach(tp); 2383 2384 #ifdef TCP_HHOOK 2385 khelp_destroy_osd(&tp->t_osd); 2386 #endif 2387 #ifdef STATS 2388 stats_blob_destroy(tp->t_stats); 2389 #endif 2390 2391 CC_ALGO(tp) = NULL; 2392 if ((m = STAILQ_FIRST(&tp->t_inqueue)) != NULL) { 2393 struct mbuf *prev; 2394 2395 STAILQ_INIT(&tp->t_inqueue); 2396 STAILQ_FOREACH_FROM_SAFE(m, &tp->t_inqueue, m_stailqpkt, prev) 2397 m_freem(m); 2398 } 2399 TCPSTATES_DEC(tp->t_state); 2400 2401 if (tp->t_fb->tfb_tcp_fb_fini) 2402 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1); 2403 MPASS(!tcp_in_hpts(tp)); 2404 #ifdef TCP_BLACKBOX 2405 tcp_log_tcpcbfini(tp); 2406 #endif 2407 2408 /* 2409 * If we got enough samples through the srtt filter, 2410 * save the rtt and rttvar in the routing entry. 2411 * 'Enough' is arbitrarily defined as 4 rtt samples. 2412 * 4 samples is enough for the srtt filter to converge 2413 * to within enough % of the correct value; fewer samples 2414 * and we could save a bogus rtt. The danger is not high 2415 * as tcp quickly recovers from everything. 2416 * XXX: Works very well but needs some more statistics! 2417 * 2418 * XXXRRS: Updating must be after the stack fini() since 2419 * that may be converting some internal representation of 2420 * say srtt etc into the general one used by other stacks. 2421 * Lets also at least protect against the so being NULL 2422 * as RW stated below. 2423 */ 2424 if ((tp->t_rttupdated >= 4) && (so != NULL)) { 2425 struct hc_metrics_lite metrics; 2426 uint32_t ssthresh; 2427 2428 bzero(&metrics, sizeof(metrics)); 2429 /* 2430 * Update the ssthresh always when the conditions below 2431 * are satisfied. This gives us better new start value 2432 * for the congestion avoidance for new connections. 2433 * ssthresh is only set if packet loss occurred on a session. 2434 * 2435 * XXXRW: 'so' may be NULL here, and/or socket buffer may be 2436 * being torn down. Ideally this code would not use 'so'. 2437 */ 2438 ssthresh = tp->snd_ssthresh; 2439 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) { 2440 /* 2441 * convert the limit from user data bytes to 2442 * packets then to packet data bytes. 2443 */ 2444 ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg; 2445 if (ssthresh < 2) 2446 ssthresh = 2; 2447 ssthresh *= (tp->t_maxseg + 2448 #ifdef INET6 2449 (isipv6 ? sizeof (struct ip6_hdr) + 2450 sizeof (struct tcphdr) : 2451 #endif 2452 sizeof (struct tcpiphdr) 2453 #ifdef INET6 2454 ) 2455 #endif 2456 ); 2457 } else 2458 ssthresh = 0; 2459 metrics.rmx_ssthresh = ssthresh; 2460 2461 metrics.rmx_rtt = tp->t_srtt; 2462 metrics.rmx_rttvar = tp->t_rttvar; 2463 metrics.rmx_cwnd = tp->snd_cwnd; 2464 metrics.rmx_sendpipe = 0; 2465 metrics.rmx_recvpipe = 0; 2466 2467 tcp_hc_update(&inp->inp_inc, &metrics); 2468 } 2469 2470 refcount_release(&tp->t_fb->tfb_refcnt); 2471 } 2472 2473 /* 2474 * Attempt to close a TCP control block, marking it as dropped, and freeing 2475 * the socket if we hold the only reference. 2476 */ 2477 struct tcpcb * 2478 tcp_close(struct tcpcb *tp) 2479 { 2480 struct inpcb *inp = tptoinpcb(tp); 2481 struct socket *so = tptosocket(tp); 2482 2483 INP_WLOCK_ASSERT(inp); 2484 2485 #ifdef TCP_OFFLOAD 2486 if (tp->t_state == TCPS_LISTEN) 2487 tcp_offload_listen_stop(tp); 2488 #endif 2489 /* 2490 * This releases the TFO pending counter resource for TFO listen 2491 * sockets as well as passively-created TFO sockets that transition 2492 * from SYN_RECEIVED to CLOSED. 2493 */ 2494 if (tp->t_tfo_pending) { 2495 tcp_fastopen_decrement_counter(tp->t_tfo_pending); 2496 tp->t_tfo_pending = NULL; 2497 } 2498 tcp_timer_stop(tp); 2499 if (tp->t_fb->tfb_tcp_timer_stop_all != NULL) 2500 tp->t_fb->tfb_tcp_timer_stop_all(tp); 2501 in_pcbdrop(inp); 2502 TCPSTAT_INC(tcps_closed); 2503 if (tp->t_state != TCPS_CLOSED) 2504 tcp_state_change(tp, TCPS_CLOSED); 2505 KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL")); 2506 tcp_free_sackholes(tp); 2507 soisdisconnected(so); 2508 if (inp->inp_flags & INP_SOCKREF) { 2509 inp->inp_flags &= ~INP_SOCKREF; 2510 INP_WUNLOCK(inp); 2511 sorele(so); 2512 return (NULL); 2513 } 2514 return (tp); 2515 } 2516 2517 /* 2518 * Notify a tcp user of an asynchronous error; 2519 * store error as soft error, but wake up user 2520 * (for now, won't do anything until can select for soft error). 2521 * 2522 * Do not wake up user since there currently is no mechanism for 2523 * reporting soft errors (yet - a kqueue filter may be added). 2524 */ 2525 static struct inpcb * 2526 tcp_notify(struct inpcb *inp, int error) 2527 { 2528 struct tcpcb *tp; 2529 2530 INP_WLOCK_ASSERT(inp); 2531 2532 tp = intotcpcb(inp); 2533 KASSERT(tp != NULL, ("tcp_notify: tp == NULL")); 2534 2535 /* 2536 * Ignore some errors if we are hooked up. 2537 * If connection hasn't completed, has retransmitted several times, 2538 * and receives a second error, give up now. This is better 2539 * than waiting a long time to establish a connection that 2540 * can never complete. 2541 */ 2542 if (tp->t_state == TCPS_ESTABLISHED && 2543 (error == EHOSTUNREACH || error == ENETUNREACH || 2544 error == EHOSTDOWN)) { 2545 if (inp->inp_route.ro_nh) { 2546 NH_FREE(inp->inp_route.ro_nh); 2547 inp->inp_route.ro_nh = (struct nhop_object *)NULL; 2548 } 2549 return (inp); 2550 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 && 2551 tp->t_softerror) { 2552 tp = tcp_drop(tp, error); 2553 if (tp != NULL) 2554 return (inp); 2555 else 2556 return (NULL); 2557 } else { 2558 tp->t_softerror = error; 2559 return (inp); 2560 } 2561 #if 0 2562 wakeup( &so->so_timeo); 2563 sorwakeup(so); 2564 sowwakeup(so); 2565 #endif 2566 } 2567 2568 static int 2569 tcp_pcblist(SYSCTL_HANDLER_ARGS) 2570 { 2571 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo, 2572 INPLOOKUP_RLOCKPCB); 2573 struct xinpgen xig; 2574 struct inpcb *inp; 2575 int error; 2576 2577 if (req->newptr != NULL) 2578 return (EPERM); 2579 2580 if (req->oldptr == NULL) { 2581 int n; 2582 2583 n = V_tcbinfo.ipi_count + 2584 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]); 2585 n += imax(n / 8, 10); 2586 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb); 2587 return (0); 2588 } 2589 2590 if ((error = sysctl_wire_old_buffer(req, 0)) != 0) 2591 return (error); 2592 2593 bzero(&xig, sizeof(xig)); 2594 xig.xig_len = sizeof xig; 2595 xig.xig_count = V_tcbinfo.ipi_count + 2596 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]); 2597 xig.xig_gen = V_tcbinfo.ipi_gencnt; 2598 xig.xig_sogen = so_gencnt; 2599 error = SYSCTL_OUT(req, &xig, sizeof xig); 2600 if (error) 2601 return (error); 2602 2603 error = syncache_pcblist(req); 2604 if (error) 2605 return (error); 2606 2607 while ((inp = inp_next(&inpi)) != NULL) { 2608 if (inp->inp_gencnt <= xig.xig_gen && 2609 cr_canseeinpcb(req->td->td_ucred, inp) == 0) { 2610 struct xtcpcb xt; 2611 2612 tcp_inptoxtp(inp, &xt); 2613 error = SYSCTL_OUT(req, &xt, sizeof xt); 2614 if (error) { 2615 INP_RUNLOCK(inp); 2616 break; 2617 } else 2618 continue; 2619 } 2620 } 2621 2622 if (!error) { 2623 /* 2624 * Give the user an updated idea of our state. 2625 * If the generation differs from what we told 2626 * her before, she knows that something happened 2627 * while we were processing this request, and it 2628 * might be necessary to retry. 2629 */ 2630 xig.xig_gen = V_tcbinfo.ipi_gencnt; 2631 xig.xig_sogen = so_gencnt; 2632 xig.xig_count = V_tcbinfo.ipi_count + 2633 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]); 2634 error = SYSCTL_OUT(req, &xig, sizeof xig); 2635 } 2636 2637 return (error); 2638 } 2639 2640 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, 2641 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_NEEDGIANT, 2642 NULL, 0, tcp_pcblist, "S,xtcpcb", 2643 "List of active TCP connections"); 2644 2645 #ifdef INET 2646 static int 2647 tcp_getcred(SYSCTL_HANDLER_ARGS) 2648 { 2649 struct xucred xuc; 2650 struct sockaddr_in addrs[2]; 2651 struct epoch_tracker et; 2652 struct inpcb *inp; 2653 int error; 2654 2655 error = priv_check(req->td, PRIV_NETINET_GETCRED); 2656 if (error) 2657 return (error); 2658 error = SYSCTL_IN(req, addrs, sizeof(addrs)); 2659 if (error) 2660 return (error); 2661 NET_EPOCH_ENTER(et); 2662 inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port, 2663 addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL); 2664 NET_EPOCH_EXIT(et); 2665 if (inp != NULL) { 2666 if (error == 0) 2667 error = cr_canseeinpcb(req->td->td_ucred, inp); 2668 if (error == 0) 2669 cru2x(inp->inp_cred, &xuc); 2670 INP_RUNLOCK(inp); 2671 } else 2672 error = ENOENT; 2673 if (error == 0) 2674 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred)); 2675 return (error); 2676 } 2677 2678 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred, 2679 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT, 2680 0, 0, tcp_getcred, "S,xucred", 2681 "Get the xucred of a TCP connection"); 2682 #endif /* INET */ 2683 2684 #ifdef INET6 2685 static int 2686 tcp6_getcred(SYSCTL_HANDLER_ARGS) 2687 { 2688 struct epoch_tracker et; 2689 struct xucred xuc; 2690 struct sockaddr_in6 addrs[2]; 2691 struct inpcb *inp; 2692 int error; 2693 #ifdef INET 2694 int mapped = 0; 2695 #endif 2696 2697 error = priv_check(req->td, PRIV_NETINET_GETCRED); 2698 if (error) 2699 return (error); 2700 error = SYSCTL_IN(req, addrs, sizeof(addrs)); 2701 if (error) 2702 return (error); 2703 if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 || 2704 (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) { 2705 return (error); 2706 } 2707 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) { 2708 #ifdef INET 2709 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr)) 2710 mapped = 1; 2711 else 2712 #endif 2713 return (EINVAL); 2714 } 2715 2716 NET_EPOCH_ENTER(et); 2717 #ifdef INET 2718 if (mapped == 1) 2719 inp = in_pcblookup(&V_tcbinfo, 2720 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12], 2721 addrs[1].sin6_port, 2722 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12], 2723 addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL); 2724 else 2725 #endif 2726 inp = in6_pcblookup(&V_tcbinfo, 2727 &addrs[1].sin6_addr, addrs[1].sin6_port, 2728 &addrs[0].sin6_addr, addrs[0].sin6_port, 2729 INPLOOKUP_RLOCKPCB, NULL); 2730 NET_EPOCH_EXIT(et); 2731 if (inp != NULL) { 2732 if (error == 0) 2733 error = cr_canseeinpcb(req->td->td_ucred, inp); 2734 if (error == 0) 2735 cru2x(inp->inp_cred, &xuc); 2736 INP_RUNLOCK(inp); 2737 } else 2738 error = ENOENT; 2739 if (error == 0) 2740 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred)); 2741 return (error); 2742 } 2743 2744 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred, 2745 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT, 2746 0, 0, tcp6_getcred, "S,xucred", 2747 "Get the xucred of a TCP6 connection"); 2748 #endif /* INET6 */ 2749 2750 #ifdef INET 2751 /* Path MTU to try next when a fragmentation-needed message is received. */ 2752 static inline int 2753 tcp_next_pmtu(const struct icmp *icp, const struct ip *ip) 2754 { 2755 int mtu = ntohs(icp->icmp_nextmtu); 2756 2757 /* If no alternative MTU was proposed, try the next smaller one. */ 2758 if (!mtu) 2759 mtu = ip_next_mtu(ntohs(ip->ip_len), 1); 2760 if (mtu < V_tcp_minmss + sizeof(struct tcpiphdr)) 2761 mtu = V_tcp_minmss + sizeof(struct tcpiphdr); 2762 2763 return (mtu); 2764 } 2765 2766 static void 2767 tcp_ctlinput_with_port(struct icmp *icp, uint16_t port) 2768 { 2769 struct ip *ip; 2770 struct tcphdr *th; 2771 struct inpcb *inp; 2772 struct tcpcb *tp; 2773 struct inpcb *(*notify)(struct inpcb *, int); 2774 struct in_conninfo inc; 2775 tcp_seq icmp_tcp_seq; 2776 int errno, mtu; 2777 2778 errno = icmp_errmap(icp); 2779 switch (errno) { 2780 case 0: 2781 return; 2782 case EMSGSIZE: 2783 notify = tcp_mtudisc_notify; 2784 break; 2785 case ECONNREFUSED: 2786 if (V_icmp_may_rst) 2787 notify = tcp_drop_syn_sent; 2788 else 2789 notify = tcp_notify; 2790 break; 2791 case EHOSTUNREACH: 2792 if (V_icmp_may_rst && icp->icmp_type == ICMP_TIMXCEED) 2793 notify = tcp_drop_syn_sent; 2794 else 2795 notify = tcp_notify; 2796 break; 2797 default: 2798 notify = tcp_notify; 2799 } 2800 2801 ip = &icp->icmp_ip; 2802 th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2)); 2803 icmp_tcp_seq = th->th_seq; 2804 inp = in_pcblookup(&V_tcbinfo, ip->ip_dst, th->th_dport, ip->ip_src, 2805 th->th_sport, INPLOOKUP_WLOCKPCB, NULL); 2806 if (inp != NULL) { 2807 tp = intotcpcb(inp); 2808 #ifdef TCP_OFFLOAD 2809 if (tp->t_flags & TF_TOE && errno == EMSGSIZE) { 2810 /* 2811 * MTU discovery for offloaded connections. Let 2812 * the TOE driver verify seq# and process it. 2813 */ 2814 mtu = tcp_next_pmtu(icp, ip); 2815 tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu); 2816 goto out; 2817 } 2818 #endif 2819 if (tp->t_port != port) 2820 goto out; 2821 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) && 2822 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) { 2823 if (errno == EMSGSIZE) { 2824 /* 2825 * MTU discovery: we got a needfrag and 2826 * will potentially try a lower MTU. 2827 */ 2828 mtu = tcp_next_pmtu(icp, ip); 2829 2830 /* 2831 * Only process the offered MTU if it 2832 * is smaller than the current one. 2833 */ 2834 if (mtu < tp->t_maxseg + 2835 sizeof(struct tcpiphdr)) { 2836 bzero(&inc, sizeof(inc)); 2837 inc.inc_faddr = ip->ip_dst; 2838 inc.inc_fibnum = 2839 inp->inp_inc.inc_fibnum; 2840 tcp_hc_updatemtu(&inc, mtu); 2841 inp = tcp_mtudisc(inp, mtu); 2842 } 2843 } else 2844 inp = (*notify)(inp, errno); 2845 } 2846 } else { 2847 bzero(&inc, sizeof(inc)); 2848 inc.inc_fport = th->th_dport; 2849 inc.inc_lport = th->th_sport; 2850 inc.inc_faddr = ip->ip_dst; 2851 inc.inc_laddr = ip->ip_src; 2852 syncache_unreach(&inc, icmp_tcp_seq, port); 2853 } 2854 out: 2855 if (inp != NULL) 2856 INP_WUNLOCK(inp); 2857 } 2858 2859 static void 2860 tcp_ctlinput(struct icmp *icmp) 2861 { 2862 tcp_ctlinput_with_port(icmp, htons(0)); 2863 } 2864 2865 static void 2866 tcp_ctlinput_viaudp(udp_tun_icmp_param_t param) 2867 { 2868 /* Its a tunneled TCP over UDP icmp */ 2869 struct icmp *icmp = param.icmp; 2870 struct ip *outer_ip, *inner_ip; 2871 struct udphdr *udp; 2872 struct tcphdr *th, ttemp; 2873 int i_hlen, o_len; 2874 uint16_t port; 2875 2876 outer_ip = (struct ip *)((caddr_t)icmp - sizeof(struct ip)); 2877 inner_ip = &icmp->icmp_ip; 2878 i_hlen = inner_ip->ip_hl << 2; 2879 o_len = ntohs(outer_ip->ip_len); 2880 if (o_len < 2881 (sizeof(struct ip) + 8 + i_hlen + sizeof(struct udphdr) + offsetof(struct tcphdr, th_ack))) { 2882 /* Not enough data present */ 2883 return; 2884 } 2885 /* Ok lets strip out the inner udphdr header by copying up on top of it the tcp hdr */ 2886 udp = (struct udphdr *)(((caddr_t)inner_ip) + i_hlen); 2887 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) { 2888 return; 2889 } 2890 port = udp->uh_dport; 2891 th = (struct tcphdr *)(udp + 1); 2892 memcpy(&ttemp, th, sizeof(struct tcphdr)); 2893 memcpy(udp, &ttemp, sizeof(struct tcphdr)); 2894 /* Now adjust down the size of the outer IP header */ 2895 o_len -= sizeof(struct udphdr); 2896 outer_ip->ip_len = htons(o_len); 2897 /* Now call in to the normal handling code */ 2898 tcp_ctlinput_with_port(icmp, port); 2899 } 2900 #endif /* INET */ 2901 2902 #ifdef INET6 2903 static inline int 2904 tcp6_next_pmtu(const struct icmp6_hdr *icmp6) 2905 { 2906 int mtu = ntohl(icmp6->icmp6_mtu); 2907 2908 /* 2909 * If no alternative MTU was proposed, or the proposed MTU was too 2910 * small, set to the min. 2911 */ 2912 if (mtu < IPV6_MMTU) 2913 mtu = IPV6_MMTU - 8; /* XXXNP: what is the adjustment for? */ 2914 return (mtu); 2915 } 2916 2917 static void 2918 tcp6_ctlinput_with_port(struct ip6ctlparam *ip6cp, uint16_t port) 2919 { 2920 struct in6_addr *dst; 2921 struct inpcb *(*notify)(struct inpcb *, int); 2922 struct ip6_hdr *ip6; 2923 struct mbuf *m; 2924 struct inpcb *inp; 2925 struct tcpcb *tp; 2926 struct icmp6_hdr *icmp6; 2927 struct in_conninfo inc; 2928 struct tcp_ports { 2929 uint16_t th_sport; 2930 uint16_t th_dport; 2931 } t_ports; 2932 tcp_seq icmp_tcp_seq; 2933 unsigned int mtu; 2934 unsigned int off; 2935 int errno; 2936 2937 icmp6 = ip6cp->ip6c_icmp6; 2938 m = ip6cp->ip6c_m; 2939 ip6 = ip6cp->ip6c_ip6; 2940 off = ip6cp->ip6c_off; 2941 dst = &ip6cp->ip6c_finaldst->sin6_addr; 2942 2943 errno = icmp6_errmap(icmp6); 2944 switch (errno) { 2945 case 0: 2946 return; 2947 case EMSGSIZE: 2948 notify = tcp_mtudisc_notify; 2949 break; 2950 case ECONNREFUSED: 2951 if (V_icmp_may_rst) 2952 notify = tcp_drop_syn_sent; 2953 else 2954 notify = tcp_notify; 2955 break; 2956 case EHOSTUNREACH: 2957 /* 2958 * There are only four ICMPs that may reset connection: 2959 * - administratively prohibited 2960 * - port unreachable 2961 * - time exceeded in transit 2962 * - unknown next header 2963 */ 2964 if (V_icmp_may_rst && 2965 ((icmp6->icmp6_type == ICMP6_DST_UNREACH && 2966 (icmp6->icmp6_code == ICMP6_DST_UNREACH_ADMIN || 2967 icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT)) || 2968 (icmp6->icmp6_type == ICMP6_TIME_EXCEEDED && 2969 icmp6->icmp6_code == ICMP6_TIME_EXCEED_TRANSIT) || 2970 (icmp6->icmp6_type == ICMP6_PARAM_PROB && 2971 icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER))) 2972 notify = tcp_drop_syn_sent; 2973 else 2974 notify = tcp_notify; 2975 break; 2976 default: 2977 notify = tcp_notify; 2978 } 2979 2980 /* Check if we can safely get the ports from the tcp hdr */ 2981 if (m == NULL || 2982 (m->m_pkthdr.len < 2983 (int32_t) (off + sizeof(struct tcp_ports)))) { 2984 return; 2985 } 2986 bzero(&t_ports, sizeof(struct tcp_ports)); 2987 m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports); 2988 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport, 2989 &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL); 2990 off += sizeof(struct tcp_ports); 2991 if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) { 2992 goto out; 2993 } 2994 m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq); 2995 if (inp != NULL) { 2996 tp = intotcpcb(inp); 2997 #ifdef TCP_OFFLOAD 2998 if (tp->t_flags & TF_TOE && errno == EMSGSIZE) { 2999 /* MTU discovery for offloaded connections. */ 3000 mtu = tcp6_next_pmtu(icmp6); 3001 tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu); 3002 goto out; 3003 } 3004 #endif 3005 if (tp->t_port != port) 3006 goto out; 3007 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) && 3008 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) { 3009 if (errno == EMSGSIZE) { 3010 /* 3011 * MTU discovery: 3012 * If we got a needfrag set the MTU 3013 * in the route to the suggested new 3014 * value (if given) and then notify. 3015 */ 3016 mtu = tcp6_next_pmtu(icmp6); 3017 3018 bzero(&inc, sizeof(inc)); 3019 inc.inc_fibnum = M_GETFIB(m); 3020 inc.inc_flags |= INC_ISIPV6; 3021 inc.inc6_faddr = *dst; 3022 if (in6_setscope(&inc.inc6_faddr, 3023 m->m_pkthdr.rcvif, NULL)) 3024 goto out; 3025 /* 3026 * Only process the offered MTU if it 3027 * is smaller than the current one. 3028 */ 3029 if (mtu < tp->t_maxseg + 3030 sizeof (struct tcphdr) + 3031 sizeof (struct ip6_hdr)) { 3032 tcp_hc_updatemtu(&inc, mtu); 3033 tcp_mtudisc(inp, mtu); 3034 ICMP6STAT_INC(icp6s_pmtuchg); 3035 } 3036 } else 3037 inp = (*notify)(inp, errno); 3038 } 3039 } else { 3040 bzero(&inc, sizeof(inc)); 3041 inc.inc_fibnum = M_GETFIB(m); 3042 inc.inc_flags |= INC_ISIPV6; 3043 inc.inc_fport = t_ports.th_dport; 3044 inc.inc_lport = t_ports.th_sport; 3045 inc.inc6_faddr = *dst; 3046 inc.inc6_laddr = ip6->ip6_src; 3047 syncache_unreach(&inc, icmp_tcp_seq, port); 3048 } 3049 out: 3050 if (inp != NULL) 3051 INP_WUNLOCK(inp); 3052 } 3053 3054 static void 3055 tcp6_ctlinput(struct ip6ctlparam *ctl) 3056 { 3057 tcp6_ctlinput_with_port(ctl, htons(0)); 3058 } 3059 3060 static void 3061 tcp6_ctlinput_viaudp(udp_tun_icmp_param_t param) 3062 { 3063 struct ip6ctlparam *ip6cp = param.ip6cp; 3064 struct mbuf *m; 3065 struct udphdr *udp; 3066 uint16_t port; 3067 3068 m = m_pulldown(ip6cp->ip6c_m, ip6cp->ip6c_off, sizeof(struct udphdr), NULL); 3069 if (m == NULL) { 3070 return; 3071 } 3072 udp = mtod(m, struct udphdr *); 3073 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) { 3074 return; 3075 } 3076 port = udp->uh_dport; 3077 m_adj(m, sizeof(struct udphdr)); 3078 if ((m->m_flags & M_PKTHDR) == 0) { 3079 ip6cp->ip6c_m->m_pkthdr.len -= sizeof(struct udphdr); 3080 } 3081 /* Now call in to the normal handling code */ 3082 tcp6_ctlinput_with_port(ip6cp, port); 3083 } 3084 3085 #endif /* INET6 */ 3086 3087 static uint32_t 3088 tcp_keyed_hash(struct in_conninfo *inc, u_char *key, u_int len) 3089 { 3090 SIPHASH_CTX ctx; 3091 uint32_t hash[2]; 3092 3093 KASSERT(len >= SIPHASH_KEY_LENGTH, 3094 ("%s: keylen %u too short ", __func__, len)); 3095 SipHash24_Init(&ctx); 3096 SipHash_SetKey(&ctx, (uint8_t *)key); 3097 SipHash_Update(&ctx, &inc->inc_fport, sizeof(uint16_t)); 3098 SipHash_Update(&ctx, &inc->inc_lport, sizeof(uint16_t)); 3099 switch (inc->inc_flags & INC_ISIPV6) { 3100 #ifdef INET 3101 case 0: 3102 SipHash_Update(&ctx, &inc->inc_faddr, sizeof(struct in_addr)); 3103 SipHash_Update(&ctx, &inc->inc_laddr, sizeof(struct in_addr)); 3104 break; 3105 #endif 3106 #ifdef INET6 3107 case INC_ISIPV6: 3108 SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(struct in6_addr)); 3109 SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(struct in6_addr)); 3110 break; 3111 #endif 3112 } 3113 SipHash_Final((uint8_t *)hash, &ctx); 3114 3115 return (hash[0] ^ hash[1]); 3116 } 3117 3118 uint32_t 3119 tcp_new_ts_offset(struct in_conninfo *inc) 3120 { 3121 struct in_conninfo inc_store, *local_inc; 3122 3123 if (!V_tcp_ts_offset_per_conn) { 3124 memcpy(&inc_store, inc, sizeof(struct in_conninfo)); 3125 inc_store.inc_lport = 0; 3126 inc_store.inc_fport = 0; 3127 local_inc = &inc_store; 3128 } else { 3129 local_inc = inc; 3130 } 3131 return (tcp_keyed_hash(local_inc, V_ts_offset_secret, 3132 sizeof(V_ts_offset_secret))); 3133 } 3134 3135 /* 3136 * Following is where TCP initial sequence number generation occurs. 3137 * 3138 * There are two places where we must use initial sequence numbers: 3139 * 1. In SYN-ACK packets. 3140 * 2. In SYN packets. 3141 * 3142 * All ISNs for SYN-ACK packets are generated by the syncache. See 3143 * tcp_syncache.c for details. 3144 * 3145 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling 3146 * depends on this property. In addition, these ISNs should be 3147 * unguessable so as to prevent connection hijacking. To satisfy 3148 * the requirements of this situation, the algorithm outlined in 3149 * RFC 1948 is used, with only small modifications. 3150 * 3151 * Implementation details: 3152 * 3153 * Time is based off the system timer, and is corrected so that it 3154 * increases by one megabyte per second. This allows for proper 3155 * recycling on high speed LANs while still leaving over an hour 3156 * before rollover. 3157 * 3158 * As reading the *exact* system time is too expensive to be done 3159 * whenever setting up a TCP connection, we increment the time 3160 * offset in two ways. First, a small random positive increment 3161 * is added to isn_offset for each connection that is set up. 3162 * Second, the function tcp_isn_tick fires once per clock tick 3163 * and increments isn_offset as necessary so that sequence numbers 3164 * are incremented at approximately ISN_BYTES_PER_SECOND. The 3165 * random positive increments serve only to ensure that the same 3166 * exact sequence number is never sent out twice (as could otherwise 3167 * happen when a port is recycled in less than the system tick 3168 * interval.) 3169 * 3170 * net.inet.tcp.isn_reseed_interval controls the number of seconds 3171 * between seeding of isn_secret. This is normally set to zero, 3172 * as reseeding should not be necessary. 3173 * 3174 * Locking of the global variables isn_secret, isn_last_reseed, isn_offset, 3175 * isn_offset_old, and isn_ctx is performed using the ISN lock. In 3176 * general, this means holding an exclusive (write) lock. 3177 */ 3178 3179 #define ISN_BYTES_PER_SECOND 1048576 3180 #define ISN_STATIC_INCREMENT 4096 3181 #define ISN_RANDOM_INCREMENT (4096 - 1) 3182 #define ISN_SECRET_LENGTH SIPHASH_KEY_LENGTH 3183 3184 VNET_DEFINE_STATIC(u_char, isn_secret[ISN_SECRET_LENGTH]); 3185 VNET_DEFINE_STATIC(int, isn_last); 3186 VNET_DEFINE_STATIC(int, isn_last_reseed); 3187 VNET_DEFINE_STATIC(u_int32_t, isn_offset); 3188 VNET_DEFINE_STATIC(u_int32_t, isn_offset_old); 3189 3190 #define V_isn_secret VNET(isn_secret) 3191 #define V_isn_last VNET(isn_last) 3192 #define V_isn_last_reseed VNET(isn_last_reseed) 3193 #define V_isn_offset VNET(isn_offset) 3194 #define V_isn_offset_old VNET(isn_offset_old) 3195 3196 tcp_seq 3197 tcp_new_isn(struct in_conninfo *inc) 3198 { 3199 tcp_seq new_isn; 3200 u_int32_t projected_offset; 3201 3202 ISN_LOCK(); 3203 /* Seed if this is the first use, reseed if requested. */ 3204 if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) && 3205 (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz) 3206 < (u_int)ticks))) { 3207 arc4rand(&V_isn_secret, sizeof(V_isn_secret), 0); 3208 V_isn_last_reseed = ticks; 3209 } 3210 3211 /* Compute the hash and return the ISN. */ 3212 new_isn = (tcp_seq)tcp_keyed_hash(inc, V_isn_secret, 3213 sizeof(V_isn_secret)); 3214 V_isn_offset += ISN_STATIC_INCREMENT + 3215 (arc4random() & ISN_RANDOM_INCREMENT); 3216 if (ticks != V_isn_last) { 3217 projected_offset = V_isn_offset_old + 3218 ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last); 3219 if (SEQ_GT(projected_offset, V_isn_offset)) 3220 V_isn_offset = projected_offset; 3221 V_isn_offset_old = V_isn_offset; 3222 V_isn_last = ticks; 3223 } 3224 new_isn += V_isn_offset; 3225 ISN_UNLOCK(); 3226 return (new_isn); 3227 } 3228 3229 /* 3230 * When a specific ICMP unreachable message is received and the 3231 * connection state is SYN-SENT, drop the connection. This behavior 3232 * is controlled by the icmp_may_rst sysctl. 3233 */ 3234 static struct inpcb * 3235 tcp_drop_syn_sent(struct inpcb *inp, int errno) 3236 { 3237 struct tcpcb *tp; 3238 3239 NET_EPOCH_ASSERT(); 3240 INP_WLOCK_ASSERT(inp); 3241 3242 tp = intotcpcb(inp); 3243 if (tp->t_state != TCPS_SYN_SENT) 3244 return (inp); 3245 3246 if (tp->t_flags & TF_FASTOPEN) 3247 tcp_fastopen_disable_path(tp); 3248 3249 tp = tcp_drop(tp, errno); 3250 if (tp != NULL) 3251 return (inp); 3252 else 3253 return (NULL); 3254 } 3255 3256 /* 3257 * When `need fragmentation' ICMP is received, update our idea of the MSS 3258 * based on the new value. Also nudge TCP to send something, since we 3259 * know the packet we just sent was dropped. 3260 * This duplicates some code in the tcp_mss() function in tcp_input.c. 3261 */ 3262 static struct inpcb * 3263 tcp_mtudisc_notify(struct inpcb *inp, int error) 3264 { 3265 3266 return (tcp_mtudisc(inp, -1)); 3267 } 3268 3269 static struct inpcb * 3270 tcp_mtudisc(struct inpcb *inp, int mtuoffer) 3271 { 3272 struct tcpcb *tp; 3273 struct socket *so; 3274 3275 INP_WLOCK_ASSERT(inp); 3276 3277 tp = intotcpcb(inp); 3278 KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL")); 3279 3280 tcp_mss_update(tp, -1, mtuoffer, NULL, NULL); 3281 3282 so = inp->inp_socket; 3283 SOCKBUF_LOCK(&so->so_snd); 3284 /* If the mss is larger than the socket buffer, decrease the mss. */ 3285 if (so->so_snd.sb_hiwat < tp->t_maxseg) { 3286 tp->t_maxseg = so->so_snd.sb_hiwat; 3287 if (tp->t_maxseg < V_tcp_mssdflt) { 3288 /* 3289 * The MSS is so small we should not process incoming 3290 * SACK's since we are subject to attack in such a 3291 * case. 3292 */ 3293 tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT; 3294 } else { 3295 tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT; 3296 } 3297 } 3298 SOCKBUF_UNLOCK(&so->so_snd); 3299 3300 TCPSTAT_INC(tcps_mturesent); 3301 tp->t_rtttime = 0; 3302 tp->snd_nxt = tp->snd_una; 3303 tcp_free_sackholes(tp); 3304 tp->snd_recover = tp->snd_max; 3305 if (tp->t_flags & TF_SACK_PERMIT) 3306 EXIT_FASTRECOVERY(tp->t_flags); 3307 if (tp->t_fb->tfb_tcp_mtu_chg != NULL) { 3308 /* 3309 * Conceptually the snd_nxt setting 3310 * and freeing sack holes should 3311 * be done by the default stacks 3312 * own tfb_tcp_mtu_chg(). 3313 */ 3314 tp->t_fb->tfb_tcp_mtu_chg(tp); 3315 } 3316 if (tcp_output(tp) < 0) 3317 return (NULL); 3318 else 3319 return (inp); 3320 } 3321 3322 #ifdef INET 3323 /* 3324 * Look-up the routing entry to the peer of this inpcb. If no route 3325 * is found and it cannot be allocated, then return 0. This routine 3326 * is called by TCP routines that access the rmx structure and by 3327 * tcp_mss_update to get the peer/interface MTU. 3328 */ 3329 uint32_t 3330 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap) 3331 { 3332 struct nhop_object *nh; 3333 struct ifnet *ifp; 3334 uint32_t maxmtu = 0; 3335 3336 KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer")); 3337 3338 if (inc->inc_faddr.s_addr != INADDR_ANY) { 3339 nh = fib4_lookup(inc->inc_fibnum, inc->inc_faddr, 0, NHR_NONE, 0); 3340 if (nh == NULL) 3341 return (0); 3342 3343 ifp = nh->nh_ifp; 3344 maxmtu = nh->nh_mtu; 3345 3346 /* Report additional interface capabilities. */ 3347 if (cap != NULL) { 3348 if (ifp->if_capenable & IFCAP_TSO4 && 3349 ifp->if_hwassist & CSUM_TSO) { 3350 cap->ifcap |= CSUM_TSO; 3351 cap->tsomax = ifp->if_hw_tsomax; 3352 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount; 3353 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize; 3354 /* XXXKIB IFCAP2_IPSEC_OFFLOAD_TSO */ 3355 cap->ipsec_tso = (ifp->if_capenable2 & 3356 IFCAP2_BIT(IFCAP2_IPSEC_OFFLOAD)) != 0; 3357 } 3358 } 3359 } 3360 return (maxmtu); 3361 } 3362 #endif /* INET */ 3363 3364 #ifdef INET6 3365 uint32_t 3366 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap) 3367 { 3368 struct nhop_object *nh; 3369 struct in6_addr dst6; 3370 uint32_t scopeid; 3371 struct ifnet *ifp; 3372 uint32_t maxmtu = 0; 3373 3374 KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer")); 3375 3376 if (inc->inc_flags & INC_IPV6MINMTU) 3377 return (IPV6_MMTU); 3378 3379 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) { 3380 in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid); 3381 nh = fib6_lookup(inc->inc_fibnum, &dst6, scopeid, NHR_NONE, 0); 3382 if (nh == NULL) 3383 return (0); 3384 3385 ifp = nh->nh_ifp; 3386 maxmtu = nh->nh_mtu; 3387 3388 /* Report additional interface capabilities. */ 3389 if (cap != NULL) { 3390 if (ifp->if_capenable & IFCAP_TSO6 && 3391 ifp->if_hwassist & CSUM_TSO) { 3392 cap->ifcap |= CSUM_TSO; 3393 cap->tsomax = ifp->if_hw_tsomax; 3394 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount; 3395 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize; 3396 cap->ipsec_tso = false; /* XXXKIB */ 3397 } 3398 } 3399 } 3400 3401 return (maxmtu); 3402 } 3403 3404 /* 3405 * Handle setsockopt(IPV6_USE_MIN_MTU) by a TCP stack. 3406 * 3407 * XXXGL: we are updating inpcb here with INC_IPV6MINMTU flag. 3408 * The right place to do that is ip6_setpktopt() that has just been 3409 * executed. By the way it just filled ip6po_minmtu for us. 3410 */ 3411 void 3412 tcp6_use_min_mtu(struct tcpcb *tp) 3413 { 3414 struct inpcb *inp = tptoinpcb(tp); 3415 3416 INP_WLOCK_ASSERT(inp); 3417 /* 3418 * In case of the IPV6_USE_MIN_MTU socket 3419 * option, the INC_IPV6MINMTU flag to announce 3420 * a corresponding MSS during the initial 3421 * handshake. If the TCP connection is not in 3422 * the front states, just reduce the MSS being 3423 * used. This avoids the sending of TCP 3424 * segments which will be fragmented at the 3425 * IPv6 layer. 3426 */ 3427 inp->inp_inc.inc_flags |= INC_IPV6MINMTU; 3428 if ((tp->t_state >= TCPS_SYN_SENT) && 3429 (inp->inp_inc.inc_flags & INC_ISIPV6)) { 3430 struct ip6_pktopts *opt; 3431 3432 opt = inp->in6p_outputopts; 3433 if (opt != NULL && opt->ip6po_minmtu == IP6PO_MINMTU_ALL && 3434 tp->t_maxseg > TCP6_MSS) { 3435 tp->t_maxseg = TCP6_MSS; 3436 if (tp->t_maxseg < V_tcp_mssdflt) { 3437 /* 3438 * The MSS is so small we should not process incoming 3439 * SACK's since we are subject to attack in such a 3440 * case. 3441 */ 3442 tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT; 3443 } else { 3444 tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT; 3445 } 3446 } 3447 } 3448 } 3449 #endif /* INET6 */ 3450 3451 /* 3452 * Calculate effective SMSS per RFC5681 definition for a given TCP 3453 * connection at its current state, taking into account SACK and etc. 3454 */ 3455 u_int 3456 tcp_maxseg(const struct tcpcb *tp) 3457 { 3458 u_int optlen; 3459 3460 if (tp->t_flags & TF_NOOPT) 3461 return (tp->t_maxseg); 3462 3463 /* 3464 * Here we have a simplified code from tcp_addoptions(), 3465 * without a proper loop, and having most of paddings hardcoded. 3466 * We might make mistakes with padding here in some edge cases, 3467 * but this is harmless, since result of tcp_maxseg() is used 3468 * only in cwnd and ssthresh estimations. 3469 */ 3470 if (TCPS_HAVEESTABLISHED(tp->t_state)) { 3471 if (tp->t_flags & TF_RCVD_TSTMP) 3472 optlen = TCPOLEN_TSTAMP_APPA; 3473 else 3474 optlen = 0; 3475 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 3476 if (tp->t_flags & TF_SIGNATURE) 3477 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE); 3478 #endif 3479 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) { 3480 optlen += TCPOLEN_SACKHDR; 3481 optlen += tp->rcv_numsacks * TCPOLEN_SACK; 3482 optlen = PADTCPOLEN(optlen); 3483 } 3484 } else { 3485 if (tp->t_flags & TF_REQ_TSTMP) 3486 optlen = TCPOLEN_TSTAMP_APPA; 3487 else 3488 optlen = PADTCPOLEN(TCPOLEN_MAXSEG); 3489 if (tp->t_flags & TF_REQ_SCALE) 3490 optlen += PADTCPOLEN(TCPOLEN_WINDOW); 3491 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 3492 if (tp->t_flags & TF_SIGNATURE) 3493 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE); 3494 #endif 3495 if (tp->t_flags & TF_SACK_PERMIT) 3496 optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED); 3497 } 3498 optlen = min(optlen, TCP_MAXOLEN); 3499 return (tp->t_maxseg - optlen); 3500 } 3501 3502 3503 u_int 3504 tcp_fixed_maxseg(const struct tcpcb *tp) 3505 { 3506 int optlen; 3507 3508 if (tp->t_flags & TF_NOOPT) 3509 return (tp->t_maxseg); 3510 3511 /* 3512 * Here we have a simplified code from tcp_addoptions(), 3513 * without a proper loop, and having most of paddings hardcoded. 3514 * We only consider fixed options that we would send every 3515 * time I.e. SACK is not considered. This is important 3516 * for cc modules to figure out what the modulo of the 3517 * cwnd should be. 3518 */ 3519 if (TCPS_HAVEESTABLISHED(tp->t_state)) { 3520 if (tp->t_flags & TF_RCVD_TSTMP) 3521 optlen = TCPOLEN_TSTAMP_APPA; 3522 else 3523 optlen = 0; 3524 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 3525 if (tp->t_flags & TF_SIGNATURE) 3526 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE); 3527 #endif 3528 } else { 3529 if (tp->t_flags & TF_REQ_TSTMP) 3530 optlen = TCPOLEN_TSTAMP_APPA; 3531 else 3532 optlen = PADTCPOLEN(TCPOLEN_MAXSEG); 3533 if (tp->t_flags & TF_REQ_SCALE) 3534 optlen += PADTCPOLEN(TCPOLEN_WINDOW); 3535 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 3536 if (tp->t_flags & TF_SIGNATURE) 3537 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE); 3538 #endif 3539 if (tp->t_flags & TF_SACK_PERMIT) 3540 optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED); 3541 } 3542 optlen = min(optlen, TCP_MAXOLEN); 3543 return (tp->t_maxseg - optlen); 3544 } 3545 3546 3547 3548 static int 3549 sysctl_drop(SYSCTL_HANDLER_ARGS) 3550 { 3551 /* addrs[0] is a foreign socket, addrs[1] is a local one. */ 3552 struct sockaddr_storage addrs[2]; 3553 struct inpcb *inp; 3554 struct tcpcb *tp; 3555 #ifdef INET 3556 struct sockaddr_in *fin = NULL, *lin = NULL; 3557 #endif 3558 struct epoch_tracker et; 3559 #ifdef INET6 3560 struct sockaddr_in6 *fin6, *lin6; 3561 #endif 3562 int error; 3563 3564 inp = NULL; 3565 #ifdef INET6 3566 fin6 = lin6 = NULL; 3567 #endif 3568 error = 0; 3569 3570 if (req->oldptr != NULL || req->oldlen != 0) 3571 return (EINVAL); 3572 if (req->newptr == NULL) 3573 return (EPERM); 3574 if (req->newlen < sizeof(addrs)) 3575 return (ENOMEM); 3576 error = SYSCTL_IN(req, &addrs, sizeof(addrs)); 3577 if (error) 3578 return (error); 3579 3580 switch (addrs[0].ss_family) { 3581 #ifdef INET6 3582 case AF_INET6: 3583 fin6 = (struct sockaddr_in6 *)&addrs[0]; 3584 lin6 = (struct sockaddr_in6 *)&addrs[1]; 3585 if (fin6->sin6_len != sizeof(struct sockaddr_in6) || 3586 lin6->sin6_len != sizeof(struct sockaddr_in6)) 3587 return (EINVAL); 3588 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) { 3589 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr)) 3590 return (EINVAL); 3591 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]); 3592 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]); 3593 #ifdef INET 3594 fin = (struct sockaddr_in *)&addrs[0]; 3595 lin = (struct sockaddr_in *)&addrs[1]; 3596 #endif 3597 break; 3598 } 3599 error = sa6_embedscope(fin6, V_ip6_use_defzone); 3600 if (error) 3601 return (error); 3602 error = sa6_embedscope(lin6, V_ip6_use_defzone); 3603 if (error) 3604 return (error); 3605 break; 3606 #endif 3607 #ifdef INET 3608 case AF_INET: 3609 fin = (struct sockaddr_in *)&addrs[0]; 3610 lin = (struct sockaddr_in *)&addrs[1]; 3611 if (fin->sin_len != sizeof(struct sockaddr_in) || 3612 lin->sin_len != sizeof(struct sockaddr_in)) 3613 return (EINVAL); 3614 break; 3615 #endif 3616 default: 3617 return (EINVAL); 3618 } 3619 NET_EPOCH_ENTER(et); 3620 switch (addrs[0].ss_family) { 3621 #ifdef INET6 3622 case AF_INET6: 3623 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr, 3624 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port, 3625 INPLOOKUP_WLOCKPCB, NULL); 3626 break; 3627 #endif 3628 #ifdef INET 3629 case AF_INET: 3630 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port, 3631 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL); 3632 break; 3633 #endif 3634 } 3635 if (inp != NULL) { 3636 if (!SOLISTENING(inp->inp_socket)) { 3637 tp = intotcpcb(inp); 3638 tp = tcp_drop(tp, ECONNABORTED); 3639 if (tp != NULL) 3640 INP_WUNLOCK(inp); 3641 } else 3642 INP_WUNLOCK(inp); 3643 } else 3644 error = ESRCH; 3645 NET_EPOCH_EXIT(et); 3646 return (error); 3647 } 3648 3649 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop, 3650 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP | 3651 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_drop, "", 3652 "Drop TCP connection"); 3653 3654 static int 3655 tcp_sysctl_setsockopt(SYSCTL_HANDLER_ARGS) 3656 { 3657 return (sysctl_setsockopt(oidp, arg1, arg2, req, &V_tcbinfo, 3658 &tcp_ctloutput_set)); 3659 } 3660 3661 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, setsockopt, 3662 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP | 3663 CTLFLAG_MPSAFE, NULL, 0, tcp_sysctl_setsockopt, "", 3664 "Set socket option for TCP endpoint"); 3665 3666 #ifdef KERN_TLS 3667 static int 3668 sysctl_switch_tls(SYSCTL_HANDLER_ARGS) 3669 { 3670 /* addrs[0] is a foreign socket, addrs[1] is a local one. */ 3671 struct sockaddr_storage addrs[2]; 3672 struct inpcb *inp; 3673 #ifdef INET 3674 struct sockaddr_in *fin = NULL, *lin = NULL; 3675 #endif 3676 struct epoch_tracker et; 3677 #ifdef INET6 3678 struct sockaddr_in6 *fin6, *lin6; 3679 #endif 3680 int error; 3681 3682 inp = NULL; 3683 #ifdef INET6 3684 fin6 = lin6 = NULL; 3685 #endif 3686 error = 0; 3687 3688 if (req->oldptr != NULL || req->oldlen != 0) 3689 return (EINVAL); 3690 if (req->newptr == NULL) 3691 return (EPERM); 3692 if (req->newlen < sizeof(addrs)) 3693 return (ENOMEM); 3694 error = SYSCTL_IN(req, &addrs, sizeof(addrs)); 3695 if (error) 3696 return (error); 3697 3698 switch (addrs[0].ss_family) { 3699 #ifdef INET6 3700 case AF_INET6: 3701 fin6 = (struct sockaddr_in6 *)&addrs[0]; 3702 lin6 = (struct sockaddr_in6 *)&addrs[1]; 3703 if (fin6->sin6_len != sizeof(struct sockaddr_in6) || 3704 lin6->sin6_len != sizeof(struct sockaddr_in6)) 3705 return (EINVAL); 3706 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) { 3707 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr)) 3708 return (EINVAL); 3709 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]); 3710 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]); 3711 #ifdef INET 3712 fin = (struct sockaddr_in *)&addrs[0]; 3713 lin = (struct sockaddr_in *)&addrs[1]; 3714 #endif 3715 break; 3716 } 3717 error = sa6_embedscope(fin6, V_ip6_use_defzone); 3718 if (error) 3719 return (error); 3720 error = sa6_embedscope(lin6, V_ip6_use_defzone); 3721 if (error) 3722 return (error); 3723 break; 3724 #endif 3725 #ifdef INET 3726 case AF_INET: 3727 fin = (struct sockaddr_in *)&addrs[0]; 3728 lin = (struct sockaddr_in *)&addrs[1]; 3729 if (fin->sin_len != sizeof(struct sockaddr_in) || 3730 lin->sin_len != sizeof(struct sockaddr_in)) 3731 return (EINVAL); 3732 break; 3733 #endif 3734 default: 3735 return (EINVAL); 3736 } 3737 NET_EPOCH_ENTER(et); 3738 switch (addrs[0].ss_family) { 3739 #ifdef INET6 3740 case AF_INET6: 3741 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr, 3742 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port, 3743 INPLOOKUP_WLOCKPCB, NULL); 3744 break; 3745 #endif 3746 #ifdef INET 3747 case AF_INET: 3748 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port, 3749 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL); 3750 break; 3751 #endif 3752 } 3753 NET_EPOCH_EXIT(et); 3754 if (inp != NULL) { 3755 struct socket *so; 3756 3757 so = inp->inp_socket; 3758 soref(so); 3759 error = ktls_set_tx_mode(so, 3760 arg2 == 0 ? TCP_TLS_MODE_SW : TCP_TLS_MODE_IFNET); 3761 INP_WUNLOCK(inp); 3762 sorele(so); 3763 } else 3764 error = ESRCH; 3765 return (error); 3766 } 3767 3768 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_sw_tls, 3769 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP | 3770 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_switch_tls, "", 3771 "Switch TCP connection to SW TLS"); 3772 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_ifnet_tls, 3773 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP | 3774 CTLFLAG_NEEDGIANT, NULL, 1, sysctl_switch_tls, "", 3775 "Switch TCP connection to ifnet TLS"); 3776 #endif 3777 3778 /* 3779 * Generate a standardized TCP log line for use throughout the 3780 * tcp subsystem. Memory allocation is done with M_NOWAIT to 3781 * allow use in the interrupt context. 3782 * 3783 * NB: The caller MUST free(s, M_TCPLOG) the returned string. 3784 * NB: The function may return NULL if memory allocation failed. 3785 * 3786 * Due to header inclusion and ordering limitations the struct ip 3787 * and ip6_hdr pointers have to be passed as void pointers. 3788 */ 3789 char * 3790 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr, 3791 const void *ip6hdr) 3792 { 3793 3794 /* Is logging enabled? */ 3795 if (V_tcp_log_in_vain == 0) 3796 return (NULL); 3797 3798 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr)); 3799 } 3800 3801 char * 3802 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr, 3803 const void *ip6hdr) 3804 { 3805 3806 /* Is logging enabled? */ 3807 if (tcp_log_debug == 0) 3808 return (NULL); 3809 3810 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr)); 3811 } 3812 3813 static char * 3814 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr, 3815 const void *ip6hdr) 3816 { 3817 char *s, *sp; 3818 size_t size; 3819 #ifdef INET 3820 const struct ip *ip = (const struct ip *)ip4hdr; 3821 #endif 3822 #ifdef INET6 3823 const struct ip6_hdr *ip6 = (const struct ip6_hdr *)ip6hdr; 3824 #endif /* INET6 */ 3825 3826 /* 3827 * The log line looks like this: 3828 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>" 3829 */ 3830 size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") + 3831 sizeof(PRINT_TH_FLAGS) + 1 + 3832 #ifdef INET6 3833 2 * INET6_ADDRSTRLEN; 3834 #else 3835 2 * INET_ADDRSTRLEN; 3836 #endif /* INET6 */ 3837 3838 s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT); 3839 if (s == NULL) 3840 return (NULL); 3841 3842 strcat(s, "TCP: ["); 3843 sp = s + strlen(s); 3844 3845 if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) { 3846 inet_ntoa_r(inc->inc_faddr, sp); 3847 sp = s + strlen(s); 3848 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport)); 3849 sp = s + strlen(s); 3850 inet_ntoa_r(inc->inc_laddr, sp); 3851 sp = s + strlen(s); 3852 sprintf(sp, "]:%i", ntohs(inc->inc_lport)); 3853 #ifdef INET6 3854 } else if (inc) { 3855 ip6_sprintf(sp, &inc->inc6_faddr); 3856 sp = s + strlen(s); 3857 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport)); 3858 sp = s + strlen(s); 3859 ip6_sprintf(sp, &inc->inc6_laddr); 3860 sp = s + strlen(s); 3861 sprintf(sp, "]:%i", ntohs(inc->inc_lport)); 3862 } else if (ip6 && th) { 3863 ip6_sprintf(sp, &ip6->ip6_src); 3864 sp = s + strlen(s); 3865 sprintf(sp, "]:%i to [", ntohs(th->th_sport)); 3866 sp = s + strlen(s); 3867 ip6_sprintf(sp, &ip6->ip6_dst); 3868 sp = s + strlen(s); 3869 sprintf(sp, "]:%i", ntohs(th->th_dport)); 3870 #endif /* INET6 */ 3871 #ifdef INET 3872 } else if (ip && th) { 3873 inet_ntoa_r(ip->ip_src, sp); 3874 sp = s + strlen(s); 3875 sprintf(sp, "]:%i to [", ntohs(th->th_sport)); 3876 sp = s + strlen(s); 3877 inet_ntoa_r(ip->ip_dst, sp); 3878 sp = s + strlen(s); 3879 sprintf(sp, "]:%i", ntohs(th->th_dport)); 3880 #endif /* INET */ 3881 } else { 3882 free(s, M_TCPLOG); 3883 return (NULL); 3884 } 3885 sp = s + strlen(s); 3886 if (th) 3887 sprintf(sp, " tcpflags 0x%b", tcp_get_flags(th), PRINT_TH_FLAGS); 3888 if (*(s + size - 1) != '\0') 3889 panic("%s: string too long", __func__); 3890 return (s); 3891 } 3892 3893 /* 3894 * A subroutine which makes it easy to track TCP state changes with DTrace. 3895 * This function shouldn't be called for t_state initializations that don't 3896 * correspond to actual TCP state transitions. 3897 */ 3898 void 3899 tcp_state_change(struct tcpcb *tp, int newstate) 3900 { 3901 #if defined(KDTRACE_HOOKS) 3902 int pstate = tp->t_state; 3903 #endif 3904 3905 TCPSTATES_DEC(tp->t_state); 3906 TCPSTATES_INC(newstate); 3907 tp->t_state = newstate; 3908 TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate); 3909 } 3910 3911 /* 3912 * Create an external-format (``xtcpcb'') structure using the information in 3913 * the kernel-format tcpcb structure pointed to by tp. This is done to 3914 * reduce the spew of irrelevant information over this interface, to isolate 3915 * user code from changes in the kernel structure, and potentially to provide 3916 * information-hiding if we decide that some of this information should be 3917 * hidden from users. 3918 */ 3919 void 3920 tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt) 3921 { 3922 struct tcpcb *tp = intotcpcb(inp); 3923 sbintime_t now; 3924 3925 bzero(xt, sizeof(*xt)); 3926 xt->t_state = tp->t_state; 3927 xt->t_logstate = tcp_get_bblog_state(tp); 3928 xt->t_flags = tp->t_flags; 3929 xt->t_sndzerowin = tp->t_sndzerowin; 3930 xt->t_sndrexmitpack = tp->t_sndrexmitpack; 3931 xt->t_rcvoopack = tp->t_rcvoopack; 3932 xt->t_rcv_wnd = tp->rcv_wnd; 3933 xt->t_snd_wnd = tp->snd_wnd; 3934 xt->t_snd_cwnd = tp->snd_cwnd; 3935 xt->t_snd_ssthresh = tp->snd_ssthresh; 3936 xt->t_dsack_bytes = tp->t_dsack_bytes; 3937 xt->t_dsack_tlp_bytes = tp->t_dsack_tlp_bytes; 3938 xt->t_dsack_pack = tp->t_dsack_pack; 3939 xt->t_maxseg = tp->t_maxseg; 3940 xt->xt_ecn = (tp->t_flags2 & TF2_ECN_PERMIT) ? 1 : 0 + 3941 (tp->t_flags2 & TF2_ACE_PERMIT) ? 2 : 0; 3942 3943 now = getsbinuptime(); 3944 #define COPYTIMER(which,where) do { \ 3945 if (tp->t_timers[which] != SBT_MAX) \ 3946 xt->where = (tp->t_timers[which] - now) / SBT_1MS; \ 3947 else \ 3948 xt->where = 0; \ 3949 } while (0) 3950 COPYTIMER(TT_DELACK, tt_delack); 3951 COPYTIMER(TT_REXMT, tt_rexmt); 3952 COPYTIMER(TT_PERSIST, tt_persist); 3953 COPYTIMER(TT_KEEP, tt_keep); 3954 COPYTIMER(TT_2MSL, tt_2msl); 3955 #undef COPYTIMER 3956 xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz; 3957 3958 xt->xt_encaps_port = tp->t_port; 3959 bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack, 3960 TCP_FUNCTION_NAME_LEN_MAX); 3961 bcopy(CC_ALGO(tp)->name, xt->xt_cc, TCP_CA_NAME_MAX); 3962 #ifdef TCP_BLACKBOX 3963 (void)tcp_log_get_id(tp, xt->xt_logid); 3964 #endif 3965 3966 xt->xt_len = sizeof(struct xtcpcb); 3967 in_pcbtoxinpcb(inp, &xt->xt_inp); 3968 } 3969 3970 void 3971 tcp_log_end_status(struct tcpcb *tp, uint8_t status) 3972 { 3973 uint32_t bit, i; 3974 3975 if ((tp == NULL) || 3976 (status > TCP_EI_STATUS_MAX_VALUE) || 3977 (status == 0)) { 3978 /* Invalid */ 3979 return; 3980 } 3981 if (status > (sizeof(uint32_t) * 8)) { 3982 /* Should this be a KASSERT? */ 3983 return; 3984 } 3985 bit = 1U << (status - 1); 3986 if (bit & tp->t_end_info_status) { 3987 /* already logged */ 3988 return; 3989 } 3990 for (i = 0; i < TCP_END_BYTE_INFO; i++) { 3991 if (tp->t_end_info_bytes[i] == TCP_EI_EMPTY_SLOT) { 3992 tp->t_end_info_bytes[i] = status; 3993 tp->t_end_info_status |= bit; 3994 break; 3995 } 3996 } 3997 } 3998 3999 int 4000 tcp_can_enable_pacing(void) 4001 { 4002 4003 if ((tcp_pacing_limit == -1) || 4004 (tcp_pacing_limit > number_of_tcp_connections_pacing)) { 4005 atomic_fetchadd_int(&number_of_tcp_connections_pacing, 1); 4006 shadow_num_connections = number_of_tcp_connections_pacing; 4007 return (1); 4008 } else { 4009 counter_u64_add(tcp_pacing_failures, 1); 4010 return (0); 4011 } 4012 } 4013 4014 int 4015 tcp_incr_dgp_pacing_cnt(void) 4016 { 4017 if ((tcp_dgp_limit == -1) || 4018 (tcp_dgp_limit > number_of_dgp_connections)) { 4019 atomic_fetchadd_int(&number_of_dgp_connections, 1); 4020 shadow_tcp_pacing_dgp = number_of_dgp_connections; 4021 return (1); 4022 } else { 4023 counter_u64_add(tcp_dgp_failures, 1); 4024 return (0); 4025 } 4026 } 4027 4028 static uint8_t tcp_dgp_warning = 0; 4029 4030 void 4031 tcp_dec_dgp_pacing_cnt(void) 4032 { 4033 uint32_t ret; 4034 4035 ret = atomic_fetchadd_int(&number_of_dgp_connections, -1); 4036 shadow_tcp_pacing_dgp = number_of_dgp_connections; 4037 KASSERT(ret != 0, ("number_of_dgp_connections -1 would cause wrap?")); 4038 if (ret == 0) { 4039 if (tcp_dgp_limit != -1) { 4040 printf("Warning all DGP is now disabled, count decrements invalidly!\n"); 4041 tcp_dgp_limit = 0; 4042 tcp_dgp_warning = 1; 4043 } else if (tcp_dgp_warning == 0) { 4044 printf("Warning DGP pacing is invalid, invalid decrement\n"); 4045 tcp_dgp_warning = 1; 4046 } 4047 } 4048 4049 } 4050 4051 static uint8_t tcp_pacing_warning = 0; 4052 4053 void 4054 tcp_decrement_paced_conn(void) 4055 { 4056 uint32_t ret; 4057 4058 ret = atomic_fetchadd_int(&number_of_tcp_connections_pacing, -1); 4059 shadow_num_connections = number_of_tcp_connections_pacing; 4060 KASSERT(ret != 0, ("tcp_paced_connection_exits -1 would cause wrap?")); 4061 if (ret == 0) { 4062 if (tcp_pacing_limit != -1) { 4063 printf("Warning all pacing is now disabled, count decrements invalidly!\n"); 4064 tcp_pacing_limit = 0; 4065 } else if (tcp_pacing_warning == 0) { 4066 printf("Warning pacing count is invalid, invalid decrement\n"); 4067 tcp_pacing_warning = 1; 4068 } 4069 } 4070 } 4071 4072 static void 4073 tcp_default_switch_failed(struct tcpcb *tp) 4074 { 4075 /* 4076 * If a switch fails we only need to 4077 * care about two things: 4078 * a) The t_flags2 4079 * and 4080 * b) The timer granularity. 4081 * Timeouts, at least for now, don't use the 4082 * old callout system in the other stacks so 4083 * those are hopefully safe. 4084 */ 4085 tcp_lro_features_off(tp); 4086 tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS); 4087 } 4088 4089 #ifdef TCP_ACCOUNTING 4090 int 4091 tcp_do_ack_accounting(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to, uint32_t tiwin, int mss) 4092 { 4093 if (SEQ_LT(th->th_ack, tp->snd_una)) { 4094 /* Do we have a SACK? */ 4095 if (to->to_flags & TOF_SACK) { 4096 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4097 tp->tcp_cnt_counters[ACK_SACK]++; 4098 } 4099 return (ACK_SACK); 4100 } else { 4101 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4102 tp->tcp_cnt_counters[ACK_BEHIND]++; 4103 } 4104 return (ACK_BEHIND); 4105 } 4106 } else if (th->th_ack == tp->snd_una) { 4107 /* Do we have a SACK? */ 4108 if (to->to_flags & TOF_SACK) { 4109 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4110 tp->tcp_cnt_counters[ACK_SACK]++; 4111 } 4112 return (ACK_SACK); 4113 } else if (tiwin != tp->snd_wnd) { 4114 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4115 tp->tcp_cnt_counters[ACK_RWND]++; 4116 } 4117 return (ACK_RWND); 4118 } else { 4119 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4120 tp->tcp_cnt_counters[ACK_DUPACK]++; 4121 } 4122 return (ACK_DUPACK); 4123 } 4124 } else { 4125 if (!SEQ_GT(th->th_ack, tp->snd_max)) { 4126 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4127 tp->tcp_cnt_counters[CNT_OF_ACKS_IN] += (((th->th_ack - tp->snd_una) + mss - 1)/mss); 4128 } 4129 } 4130 if (to->to_flags & TOF_SACK) { 4131 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4132 tp->tcp_cnt_counters[ACK_CUMACK_SACK]++; 4133 } 4134 return (ACK_CUMACK_SACK); 4135 } else { 4136 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) { 4137 tp->tcp_cnt_counters[ACK_CUMACK]++; 4138 } 4139 return (ACK_CUMACK); 4140 } 4141 } 4142 } 4143 #endif 4144 4145 void 4146 tcp_change_time_units(struct tcpcb *tp, int granularity) 4147 { 4148 if (tp->t_tmr_granularity == granularity) { 4149 /* We are there */ 4150 return; 4151 } 4152 if (granularity == TCP_TMR_GRANULARITY_USEC) { 4153 KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS), 4154 ("Granularity is not TICKS its %u in tp:%p", 4155 tp->t_tmr_granularity, tp)); 4156 tp->t_rttlow = TICKS_2_USEC(tp->t_rttlow); 4157 if (tp->t_srtt > 1) { 4158 uint32_t val, frac; 4159 4160 val = tp->t_srtt >> TCP_RTT_SHIFT; 4161 frac = tp->t_srtt & 0x1f; 4162 tp->t_srtt = TICKS_2_USEC(val); 4163 /* 4164 * frac is the fractional part of the srtt (if any) 4165 * but its in ticks and every bit represents 4166 * 1/32nd of a hz. 4167 */ 4168 if (frac) { 4169 if (hz == 1000) { 4170 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE); 4171 } else { 4172 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE)); 4173 } 4174 tp->t_srtt += frac; 4175 } 4176 } 4177 if (tp->t_rttvar) { 4178 uint32_t val, frac; 4179 4180 val = tp->t_rttvar >> TCP_RTTVAR_SHIFT; 4181 frac = tp->t_rttvar & 0x1f; 4182 tp->t_rttvar = TICKS_2_USEC(val); 4183 /* 4184 * frac is the fractional part of the srtt (if any) 4185 * but its in ticks and every bit represents 4186 * 1/32nd of a hz. 4187 */ 4188 if (frac) { 4189 if (hz == 1000) { 4190 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE); 4191 } else { 4192 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE)); 4193 } 4194 tp->t_rttvar += frac; 4195 } 4196 } 4197 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_USEC; 4198 } else if (granularity == TCP_TMR_GRANULARITY_TICKS) { 4199 /* Convert back to ticks, with */ 4200 KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_USEC), 4201 ("Granularity is not USEC its %u in tp:%p", 4202 tp->t_tmr_granularity, tp)); 4203 if (tp->t_srtt > 1) { 4204 uint32_t val, frac; 4205 4206 val = USEC_2_TICKS(tp->t_srtt); 4207 frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz); 4208 tp->t_srtt = val << TCP_RTT_SHIFT; 4209 /* 4210 * frac is the fractional part here is left 4211 * over from converting to hz and shifting. 4212 * We need to convert this to the 5 bit 4213 * remainder. 4214 */ 4215 if (frac) { 4216 if (hz == 1000) { 4217 frac = (((uint64_t)frac * (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC); 4218 } else { 4219 frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC); 4220 } 4221 tp->t_srtt += frac; 4222 } 4223 } 4224 if (tp->t_rttvar) { 4225 uint32_t val, frac; 4226 4227 val = USEC_2_TICKS(tp->t_rttvar); 4228 frac = tp->t_rttvar % (HPTS_USEC_IN_SEC / hz); 4229 tp->t_rttvar = val << TCP_RTTVAR_SHIFT; 4230 /* 4231 * frac is the fractional part here is left 4232 * over from converting to hz and shifting. 4233 * We need to convert this to the 4 bit 4234 * remainder. 4235 */ 4236 if (frac) { 4237 if (hz == 1000) { 4238 frac = (((uint64_t)frac * (uint64_t)TCP_RTTVAR_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC); 4239 } else { 4240 frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTTVAR_SCALE) /(uint64_t)HPTS_USEC_IN_SEC); 4241 } 4242 tp->t_rttvar += frac; 4243 } 4244 } 4245 tp->t_rttlow = USEC_2_TICKS(tp->t_rttlow); 4246 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS; 4247 } 4248 #ifdef INVARIANTS 4249 else { 4250 panic("Unknown granularity:%d tp:%p", 4251 granularity, tp); 4252 } 4253 #endif 4254 } 4255 4256 void 4257 tcp_handle_orphaned_packets(struct tcpcb *tp) 4258 { 4259 struct mbuf *save, *m, *prev; 4260 /* 4261 * Called when a stack switch is occuring from the fini() 4262 * of the old stack. We assue the init() as already been 4263 * run of the new stack and it has set the t_flags2 to 4264 * what it supports. This function will then deal with any 4265 * differences i.e. cleanup packets that maybe queued that 4266 * the newstack does not support. 4267 */ 4268 4269 if (tp->t_flags2 & TF2_MBUF_L_ACKS) 4270 return; 4271 if ((tp->t_flags2 & TF2_SUPPORTS_MBUFQ) == 0 && 4272 !STAILQ_EMPTY(&tp->t_inqueue)) { 4273 /* 4274 * It is unsafe to process the packets since a 4275 * reset may be lurking in them (its rare but it 4276 * can occur). If we were to find a RST, then we 4277 * would end up dropping the connection and the 4278 * INP lock, so when we return the caller (tcp_usrreq) 4279 * will blow up when it trys to unlock the inp. 4280 * This new stack does not do any fancy LRO features 4281 * so all we can do is toss the packets. 4282 */ 4283 m = STAILQ_FIRST(&tp->t_inqueue); 4284 STAILQ_INIT(&tp->t_inqueue); 4285 STAILQ_FOREACH_FROM_SAFE(m, &tp->t_inqueue, m_stailqpkt, save) 4286 m_freem(m); 4287 } else { 4288 /* 4289 * Here we have a stack that does mbuf queuing but 4290 * does not support compressed ack's. We must 4291 * walk all the mbufs and discard any compressed acks. 4292 */ 4293 STAILQ_FOREACH_SAFE(m, &tp->t_inqueue, m_stailqpkt, save) { 4294 if (m->m_flags & M_ACKCMP) { 4295 if (m == STAILQ_FIRST(&tp->t_inqueue)) 4296 STAILQ_REMOVE_HEAD(&tp->t_inqueue, 4297 m_stailqpkt); 4298 else 4299 STAILQ_REMOVE_AFTER(&tp->t_inqueue, 4300 prev, m_stailqpkt); 4301 m_freem(m); 4302 } else 4303 prev = m; 4304 } 4305 } 4306 } 4307 4308 #ifdef TCP_REQUEST_TRK 4309 uint32_t 4310 tcp_estimate_tls_overhead(struct socket *so, uint64_t tls_usr_bytes) 4311 { 4312 #ifdef KERN_TLS 4313 struct ktls_session *tls; 4314 uint32_t rec_oh, records; 4315 4316 tls = so->so_snd.sb_tls_info; 4317 if (tls == NULL) 4318 return (0); 4319 4320 rec_oh = tls->params.tls_hlen + tls->params.tls_tlen; 4321 records = ((tls_usr_bytes + tls->params.max_frame_len - 1)/tls->params.max_frame_len); 4322 return (records * rec_oh); 4323 #else 4324 return (0); 4325 #endif 4326 } 4327 4328 extern uint32_t tcp_stale_entry_time; 4329 uint32_t tcp_stale_entry_time = 250000; 4330 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, usrlog_stale, CTLFLAG_RW, 4331 &tcp_stale_entry_time, 250000, "Time that a tcpreq entry without a sendfile ages out"); 4332 4333 void 4334 tcp_req_log_req_info(struct tcpcb *tp, struct tcp_sendfile_track *req, 4335 uint16_t slot, uint8_t val, uint64_t offset, uint64_t nbytes) 4336 { 4337 if (tcp_bblogging_on(tp)) { 4338 union tcp_log_stackspecific log; 4339 struct timeval tv; 4340 4341 memset(&log.u_bbr, 0, sizeof(log.u_bbr)); 4342 log.u_bbr.inhpts = tcp_in_hpts(tp); 4343 log.u_bbr.flex8 = val; 4344 log.u_bbr.rttProp = req->timestamp; 4345 log.u_bbr.delRate = req->start; 4346 log.u_bbr.cur_del_rate = req->end; 4347 log.u_bbr.flex1 = req->start_seq; 4348 log.u_bbr.flex2 = req->end_seq; 4349 log.u_bbr.flex3 = req->flags; 4350 log.u_bbr.flex4 = ((req->localtime >> 32) & 0x00000000ffffffff); 4351 log.u_bbr.flex5 = (req->localtime & 0x00000000ffffffff); 4352 log.u_bbr.flex7 = slot; 4353 log.u_bbr.bw_inuse = offset; 4354 /* nbytes = flex6 | epoch */ 4355 log.u_bbr.flex6 = ((nbytes >> 32) & 0x00000000ffffffff); 4356 log.u_bbr.epoch = (nbytes & 0x00000000ffffffff); 4357 /* cspr = lt_epoch | pkts_out */ 4358 log.u_bbr.lt_epoch = ((req->cspr >> 32) & 0x00000000ffffffff); 4359 log.u_bbr.pkts_out |= (req->cspr & 0x00000000ffffffff); 4360 log.u_bbr.applimited = tp->t_tcpreq_closed; 4361 log.u_bbr.applimited <<= 8; 4362 log.u_bbr.applimited |= tp->t_tcpreq_open; 4363 log.u_bbr.applimited <<= 8; 4364 log.u_bbr.applimited |= tp->t_tcpreq_req; 4365 log.u_bbr.timeStamp = tcp_get_usecs(&tv); 4366 TCP_LOG_EVENTP(tp, NULL, 4367 &tptosocket(tp)->so_rcv, 4368 &tptosocket(tp)->so_snd, 4369 TCP_LOG_REQ_T, 0, 4370 0, &log, false, &tv); 4371 } 4372 } 4373 4374 void 4375 tcp_req_free_a_slot(struct tcpcb *tp, struct tcp_sendfile_track *ent) 4376 { 4377 if (tp->t_tcpreq_req > 0) 4378 tp->t_tcpreq_req--; 4379 if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) { 4380 if (tp->t_tcpreq_open > 0) 4381 tp->t_tcpreq_open--; 4382 } else { 4383 if (tp->t_tcpreq_closed > 0) 4384 tp->t_tcpreq_closed--; 4385 } 4386 ent->flags = TCP_TRK_TRACK_FLG_EMPTY; 4387 } 4388 4389 static void 4390 tcp_req_check_for_stale_entries(struct tcpcb *tp, uint64_t ts, int rm_oldest) 4391 { 4392 struct tcp_sendfile_track *ent; 4393 uint64_t time_delta, oldest_delta; 4394 int i, oldest, oldest_set = 0, cnt_rm = 0; 4395 4396 for (i = 0; i < MAX_TCP_TRK_REQ; i++) { 4397 ent = &tp->t_tcpreq_info[i]; 4398 if (ent->flags != TCP_TRK_TRACK_FLG_USED) { 4399 /* 4400 * We only care about closed end ranges 4401 * that are allocated and have no sendfile 4402 * ever touching them. They would be in 4403 * state USED. 4404 */ 4405 continue; 4406 } 4407 if (ts >= ent->localtime) 4408 time_delta = ts - ent->localtime; 4409 else 4410 time_delta = 0; 4411 if (time_delta && 4412 ((oldest_delta < time_delta) || (oldest_set == 0))) { 4413 oldest_set = 1; 4414 oldest = i; 4415 oldest_delta = time_delta; 4416 } 4417 if (tcp_stale_entry_time && (time_delta >= tcp_stale_entry_time)) { 4418 /* 4419 * No sendfile in a our time-limit 4420 * time to purge it. 4421 */ 4422 cnt_rm++; 4423 tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], i, TCP_TRK_REQ_LOG_STALE, 4424 time_delta, 0); 4425 tcp_req_free_a_slot(tp, ent); 4426 } 4427 } 4428 if ((cnt_rm == 0) && rm_oldest && oldest_set) { 4429 ent = &tp->t_tcpreq_info[oldest]; 4430 tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], i, TCP_TRK_REQ_LOG_STALE, 4431 oldest_delta, 1); 4432 tcp_req_free_a_slot(tp, ent); 4433 } 4434 } 4435 4436 int 4437 tcp_req_check_for_comp(struct tcpcb *tp, tcp_seq ack_point) 4438 { 4439 int i, ret = 0; 4440 struct tcp_sendfile_track *ent; 4441 4442 /* Clean up any old closed end requests that are now completed */ 4443 if (tp->t_tcpreq_req == 0) 4444 return (0); 4445 if (tp->t_tcpreq_closed == 0) 4446 return (0); 4447 for (i = 0; i < MAX_TCP_TRK_REQ; i++) { 4448 ent = &tp->t_tcpreq_info[i]; 4449 /* Skip empty ones */ 4450 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) 4451 continue; 4452 /* Skip open ones */ 4453 if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) 4454 continue; 4455 if (SEQ_GEQ(ack_point, ent->end_seq)) { 4456 /* We are past it -- free it */ 4457 tcp_req_log_req_info(tp, ent, 4458 i, TCP_TRK_REQ_LOG_FREED, 0, 0); 4459 tcp_req_free_a_slot(tp, ent); 4460 ret++; 4461 } 4462 } 4463 return (ret); 4464 } 4465 4466 int 4467 tcp_req_is_entry_comp(struct tcpcb *tp, struct tcp_sendfile_track *ent, tcp_seq ack_point) 4468 { 4469 if (tp->t_tcpreq_req == 0) 4470 return (-1); 4471 if (tp->t_tcpreq_closed == 0) 4472 return (-1); 4473 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) 4474 return (-1); 4475 if (SEQ_GEQ(ack_point, ent->end_seq)) { 4476 return (1); 4477 } 4478 return (0); 4479 } 4480 4481 struct tcp_sendfile_track * 4482 tcp_req_find_a_req_that_is_completed_by(struct tcpcb *tp, tcp_seq th_ack, int *ip) 4483 { 4484 /* 4485 * Given an ack point (th_ack) walk through our entries and 4486 * return the first one found that th_ack goes past the 4487 * end_seq. 4488 */ 4489 struct tcp_sendfile_track *ent; 4490 int i; 4491 4492 if (tp->t_tcpreq_req == 0) { 4493 /* none open */ 4494 return (NULL); 4495 } 4496 for (i = 0; i < MAX_TCP_TRK_REQ; i++) { 4497 ent = &tp->t_tcpreq_info[i]; 4498 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) 4499 continue; 4500 if ((ent->flags & TCP_TRK_TRACK_FLG_OPEN) == 0) { 4501 if (SEQ_GEQ(th_ack, ent->end_seq)) { 4502 *ip = i; 4503 return (ent); 4504 } 4505 } 4506 } 4507 return (NULL); 4508 } 4509 4510 struct tcp_sendfile_track * 4511 tcp_req_find_req_for_seq(struct tcpcb *tp, tcp_seq seq) 4512 { 4513 struct tcp_sendfile_track *ent; 4514 int i; 4515 4516 if (tp->t_tcpreq_req == 0) { 4517 /* none open */ 4518 return (NULL); 4519 } 4520 for (i = 0; i < MAX_TCP_TRK_REQ; i++) { 4521 ent = &tp->t_tcpreq_info[i]; 4522 tcp_req_log_req_info(tp, ent, i, TCP_TRK_REQ_LOG_SEARCH, 4523 (uint64_t)seq, 0); 4524 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) { 4525 continue; 4526 } 4527 if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) { 4528 /* 4529 * An open end request only needs to 4530 * match the beginning seq or be 4531 * all we have (once we keep going on 4532 * a open end request we may have a seq 4533 * wrap). 4534 */ 4535 if ((SEQ_GEQ(seq, ent->start_seq)) || 4536 (tp->t_tcpreq_closed == 0)) 4537 return (ent); 4538 } else { 4539 /* 4540 * For this one we need to 4541 * be a bit more careful if its 4542 * completed at least. 4543 */ 4544 if ((SEQ_GEQ(seq, ent->start_seq)) && 4545 (SEQ_LT(seq, ent->end_seq))) { 4546 return (ent); 4547 } 4548 } 4549 } 4550 return (NULL); 4551 } 4552 4553 /* Should this be in its own file tcp_req.c ? */ 4554 struct tcp_sendfile_track * 4555 tcp_req_alloc_req_full(struct tcpcb *tp, struct tcp_snd_req *req, uint64_t ts, int rec_dups) 4556 { 4557 struct tcp_sendfile_track *fil; 4558 int i, allocated; 4559 4560 /* In case the stack does not check for completions do so now */ 4561 tcp_req_check_for_comp(tp, tp->snd_una); 4562 /* Check for stale entries */ 4563 if (tp->t_tcpreq_req) 4564 tcp_req_check_for_stale_entries(tp, ts, 4565 (tp->t_tcpreq_req >= MAX_TCP_TRK_REQ)); 4566 /* Check to see if this is a duplicate of one not started */ 4567 if (tp->t_tcpreq_req) { 4568 for (i = 0, allocated = 0; i < MAX_TCP_TRK_REQ; i++) { 4569 fil = &tp->t_tcpreq_info[i]; 4570 if ((fil->flags & TCP_TRK_TRACK_FLG_USED) == 0) 4571 continue; 4572 if ((fil->timestamp == req->timestamp) && 4573 (fil->start == req->start) && 4574 ((fil->flags & TCP_TRK_TRACK_FLG_OPEN) || 4575 (fil->end == req->end))) { 4576 /* 4577 * We already have this request 4578 * and it has not been started with sendfile. 4579 * This probably means the user was returned 4580 * a 4xx of some sort and its going to age 4581 * out, lets not duplicate it. 4582 */ 4583 return (fil); 4584 } 4585 } 4586 } 4587 /* Ok if there is no room at the inn we are in trouble */ 4588 if (tp->t_tcpreq_req >= MAX_TCP_TRK_REQ) { 4589 tcp_trace_point(tp, TCP_TP_REQ_LOG_FAIL); 4590 for (i = 0; i < MAX_TCP_TRK_REQ; i++) { 4591 tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], 4592 i, TCP_TRK_REQ_LOG_ALLOCFAIL, 0, 0); 4593 } 4594 return (NULL); 4595 } 4596 for (i = 0, allocated = 0; i < MAX_TCP_TRK_REQ; i++) { 4597 fil = &tp->t_tcpreq_info[i]; 4598 if (fil->flags == TCP_TRK_TRACK_FLG_EMPTY) { 4599 allocated = 1; 4600 fil->flags = TCP_TRK_TRACK_FLG_USED; 4601 fil->timestamp = req->timestamp; 4602 fil->playout_ms = req->playout_ms; 4603 fil->localtime = ts; 4604 fil->start = req->start; 4605 if (req->flags & TCP_LOG_HTTPD_RANGE_END) { 4606 fil->end = req->end; 4607 } else { 4608 fil->end = 0; 4609 fil->flags |= TCP_TRK_TRACK_FLG_OPEN; 4610 } 4611 /* 4612 * We can set the min boundaries to the TCP Sequence space, 4613 * but it might be found to be further up when sendfile 4614 * actually runs on this range (if it ever does). 4615 */ 4616 fil->sbcc_at_s = tptosocket(tp)->so_snd.sb_ccc; 4617 fil->start_seq = tp->snd_una + 4618 tptosocket(tp)->so_snd.sb_ccc; 4619 if (req->flags & TCP_LOG_HTTPD_RANGE_END) 4620 fil->end_seq = (fil->start_seq + ((uint32_t)(fil->end - fil->start))); 4621 else 4622 fil->end_seq = 0; 4623 if (tptosocket(tp)->so_snd.sb_tls_info) { 4624 /* 4625 * This session is doing TLS. Take a swag guess 4626 * at the overhead. 4627 */ 4628 fil->end_seq += tcp_estimate_tls_overhead( 4629 tptosocket(tp), (fil->end - fil->start)); 4630 } 4631 tp->t_tcpreq_req++; 4632 if (fil->flags & TCP_TRK_TRACK_FLG_OPEN) 4633 tp->t_tcpreq_open++; 4634 else 4635 tp->t_tcpreq_closed++; 4636 tcp_req_log_req_info(tp, fil, i, 4637 TCP_TRK_REQ_LOG_NEW, 0, 0); 4638 break; 4639 } else 4640 fil = NULL; 4641 } 4642 return (fil); 4643 } 4644 4645 void 4646 tcp_req_alloc_req(struct tcpcb *tp, union tcp_log_userdata *user, uint64_t ts) 4647 { 4648 (void)tcp_req_alloc_req_full(tp, &user->tcp_req, ts, 1); 4649 } 4650 #endif 4651 4652 void 4653 tcp_log_socket_option(struct tcpcb *tp, uint32_t option_num, uint32_t option_val, int err) 4654 { 4655 if (tcp_bblogging_on(tp)) { 4656 struct tcp_log_buffer *l; 4657 4658 l = tcp_log_event(tp, NULL, 4659 &tptosocket(tp)->so_rcv, 4660 &tptosocket(tp)->so_snd, 4661 TCP_LOG_SOCKET_OPT, 4662 err, 0, NULL, 1, 4663 NULL, NULL, 0, NULL); 4664 if (l) { 4665 l->tlb_flex1 = option_num; 4666 l->tlb_flex2 = option_val; 4667 } 4668 } 4669 } 4670 4671 uint32_t 4672 tcp_get_srtt(struct tcpcb *tp, int granularity) 4673 { 4674 uint32_t srtt; 4675 4676 KASSERT(granularity == TCP_TMR_GRANULARITY_USEC || 4677 granularity == TCP_TMR_GRANULARITY_TICKS, 4678 ("%s: called with unexpected granularity %d", __func__, 4679 granularity)); 4680 4681 srtt = tp->t_srtt; 4682 4683 /* 4684 * We only support two granularities. If the stored granularity 4685 * does not match the granularity requested by the caller, 4686 * convert the stored value to the requested unit of granularity. 4687 */ 4688 if (tp->t_tmr_granularity != granularity) { 4689 if (granularity == TCP_TMR_GRANULARITY_USEC) 4690 srtt = TICKS_2_USEC(srtt); 4691 else 4692 srtt = USEC_2_TICKS(srtt); 4693 } 4694 4695 /* 4696 * If the srtt is stored with ticks granularity, we need to 4697 * unshift to get the actual value. We do this after the 4698 * conversion above (if one was necessary) in order to maximize 4699 * precision. 4700 */ 4701 if (tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS) 4702 srtt = srtt >> TCP_RTT_SHIFT; 4703 4704 return (srtt); 4705 } 4706 4707 void 4708 tcp_account_for_send(struct tcpcb *tp, uint32_t len, uint8_t is_rxt, 4709 uint8_t is_tlp, bool hw_tls) 4710 { 4711 4712 if (is_tlp) { 4713 tp->t_sndtlppack++; 4714 tp->t_sndtlpbyte += len; 4715 } 4716 /* To get total bytes sent you must add t_snd_rxt_bytes to t_sndbytes */ 4717 if (is_rxt) 4718 tp->t_snd_rxt_bytes += len; 4719 else 4720 tp->t_sndbytes += len; 4721 4722 #ifdef KERN_TLS 4723 if (hw_tls && is_rxt && len != 0) { 4724 uint64_t rexmit_percent; 4725 4726 rexmit_percent = (1000ULL * tp->t_snd_rxt_bytes) / 4727 (10ULL * (tp->t_snd_rxt_bytes + tp->t_sndbytes)); 4728 if (rexmit_percent > ktls_ifnet_max_rexmit_pct) 4729 ktls_disable_ifnet(tp); 4730 } 4731 #endif 4732 } 4733