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