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