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