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