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