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