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