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