2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
31 * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
40 #include "opt_kern_tls.h"
41 #include "opt_tcpdebug.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
46 #include <sys/callout.h>
47 #include <sys/eventhandler.h>
49 #include <sys/hhook.h>
51 #include <sys/kernel.h>
53 #include <sys/khelp.h>
58 #include <sys/qmath.h>
59 #include <sys/stats.h>
60 #include <sys/sysctl.h>
62 #include <sys/malloc.h>
63 #include <sys/refcount.h>
68 #include <sys/socket.h>
69 #include <sys/socketvar.h>
70 #include <sys/protosw.h>
71 #include <sys/random.h>
75 #include <net/route.h>
76 #include <net/route/nhop.h>
78 #include <net/if_var.h>
81 #include <netinet/in.h>
82 #include <netinet/in_fib.h>
83 #include <netinet/in_kdtrace.h>
84 #include <netinet/in_pcb.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/in_var.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h>
89 #include <netinet/ip_var.h>
91 #include <netinet/icmp6.h>
92 #include <netinet/ip6.h>
93 #include <netinet6/in6_fib.h>
94 #include <netinet6/in6_pcb.h>
95 #include <netinet6/ip6_var.h>
96 #include <netinet6/scope6_var.h>
97 #include <netinet6/nd6.h>
100 #include <netinet/tcp.h>
104 #include <netinet/tcp_fsm.h>
105 #include <netinet/tcp_seq.h>
106 #include <netinet/tcp_timer.h>
107 #include <netinet/tcp_var.h>
108 #include <netinet/tcp_ecn.h>
109 #include <netinet/tcp_log_buf.h>
110 #include <netinet/tcp_syncache.h>
111 #include <netinet/tcp_hpts.h>
112 #include <netinet/cc/cc.h>
113 #include <netinet/tcpip.h>
114 #include <netinet/tcp_fastopen.h>
116 #include <netinet/tcp_pcap.h>
119 #include <netinet/tcp_debug.h>
122 #include <netinet/tcp_offload.h>
124 #include <netinet/udp.h>
125 #include <netinet/udp_var.h>
127 #include <netinet6/tcp6_var.h>
130 #include <netipsec/ipsec_support.h>
132 #include <machine/in_cksum.h>
133 #include <crypto/siphash/siphash.h>
135 #include <security/mac/mac_framework.h>
138 static ip6proto_ctlinput_t tcp6_ctlinput;
139 static udp_tun_icmp_t tcp6_ctlinput_viaudp;
142 VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS;
144 VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS;
147 #ifdef NETFLIX_EXP_DETECTION
148 /* Sack attack detection thresholds and such */
149 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, sack_attack,
150 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
151 "Sack Attack detection thresholds");
152 int32_t tcp_force_detection = 0;
153 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, force_detection,
155 &tcp_force_detection, 0,
156 "Do we force detection even if the INP has it off?");
157 int32_t tcp_sack_to_ack_thresh = 700; /* 70 % */
158 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sack_to_ack_thresh,
160 &tcp_sack_to_ack_thresh, 700,
161 "Percentage of sacks to acks we must see above (10.1 percent is 101)?");
162 int32_t tcp_sack_to_move_thresh = 600; /* 60 % */
163 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, move_thresh,
165 &tcp_sack_to_move_thresh, 600,
166 "Percentage of sack moves we must see above (10.1 percent is 101)");
167 int32_t tcp_restoral_thresh = 650; /* 65 % (sack:2:ack -5%) */
168 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, restore_thresh,
170 &tcp_restoral_thresh, 550,
171 "Percentage of sack to ack percentage we must see below to restore(10.1 percent is 101)");
172 int32_t tcp_sad_decay_val = 800;
173 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, decay_per,
175 &tcp_sad_decay_val, 800,
176 "The decay percentage (10.1 percent equals 101 )");
177 int32_t tcp_map_minimum = 500;
178 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, nummaps,
180 &tcp_map_minimum, 500,
181 "Number of Map enteries before we start detection");
182 int32_t tcp_attack_on_turns_on_logging = 0;
183 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, attacks_logged,
185 &tcp_attack_on_turns_on_logging, 0,
186 "When we have a positive hit on attack, do we turn on logging?");
187 int32_t tcp_sad_pacing_interval = 2000;
188 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sad_pacing_int,
190 &tcp_sad_pacing_interval, 2000,
191 "What is the minimum pacing interval for a classified attacker?");
193 int32_t tcp_sad_low_pps = 100;
194 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sad_low_pps,
196 &tcp_sad_low_pps, 100,
197 "What is the input pps that below which we do not decay?");
199 uint32_t tcp_ack_war_time_window = 1000;
200 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_timewindow,
202 &tcp_ack_war_time_window, 1000,
203 "If the tcp_stack does ack-war prevention how many milliseconds are in its time window?");
204 uint32_t tcp_ack_war_cnt = 5;
205 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_cnt,
208 "If the tcp_stack does ack-war prevention how many acks can be sent in its time window?");
210 struct rwlock tcp_function_lock;
213 sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS)
218 error = sysctl_handle_int(oidp, &new, 0, req);
219 if (error == 0 && req->newptr) {
220 if (new < TCP_MINMSS)
228 SYSCTL_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt,
229 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
230 &VNET_NAME(tcp_mssdflt), 0, &sysctl_net_inet_tcp_mss_check, "I",
231 "Default TCP Maximum Segment Size");
235 sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS)
239 new = V_tcp_v6mssdflt;
240 error = sysctl_handle_int(oidp, &new, 0, req);
241 if (error == 0 && req->newptr) {
242 if (new < TCP_MINMSS)
245 V_tcp_v6mssdflt = new;
250 SYSCTL_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
251 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
252 &VNET_NAME(tcp_v6mssdflt), 0, &sysctl_net_inet_tcp_mss_v6_check, "I",
253 "Default TCP Maximum Segment Size for IPv6");
257 * Minimum MSS we accept and use. This prevents DoS attacks where
258 * we are forced to a ridiculous low MSS like 20 and send hundreds
259 * of packets instead of one. The effect scales with the available
260 * bandwidth and quickly saturates the CPU and network interface
261 * with packet generation and sending. Set to zero to disable MINMSS
262 * checking. This setting prevents us from sending too small packets.
264 VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS;
265 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_VNET | CTLFLAG_RW,
266 &VNET_NAME(tcp_minmss), 0,
267 "Minimum TCP Maximum Segment Size");
269 VNET_DEFINE(int, tcp_do_rfc1323) = 1;
270 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_VNET | CTLFLAG_RW,
271 &VNET_NAME(tcp_do_rfc1323), 0,
272 "Enable rfc1323 (high performance TCP) extensions");
275 * As of June 2021, several TCP stacks violate RFC 7323 from September 2014.
276 * Some stacks negotiate TS, but never send them after connection setup. Some
277 * stacks negotiate TS, but don't send them when sending keep-alive segments.
278 * These include modern widely deployed TCP stacks.
279 * Therefore tolerating violations for now...
281 VNET_DEFINE(int, tcp_tolerate_missing_ts) = 1;
282 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tolerate_missing_ts, CTLFLAG_VNET | CTLFLAG_RW,
283 &VNET_NAME(tcp_tolerate_missing_ts), 0,
284 "Tolerate missing TCP timestamps");
286 VNET_DEFINE(int, tcp_ts_offset_per_conn) = 1;
287 SYSCTL_INT(_net_inet_tcp, OID_AUTO, ts_offset_per_conn, CTLFLAG_VNET | CTLFLAG_RW,
288 &VNET_NAME(tcp_ts_offset_per_conn), 0,
289 "Initialize TCP timestamps per connection instead of per host pair");
291 /* How many connections are pacing */
292 static volatile uint32_t number_of_tcp_connections_pacing = 0;
293 static uint32_t shadow_num_connections = 0;
295 static int tcp_pacing_limit = 10000;
296 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pacing_limit, CTLFLAG_RW,
297 &tcp_pacing_limit, 1000,
298 "If the TCP stack does pacing, is there a limit (-1 = no, 0 = no pacing N = number of connections)");
300 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pacing_count, CTLFLAG_RD,
301 &shadow_num_connections, 0, "Number of TCP connections being paced");
303 static int tcp_log_debug = 0;
304 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW,
305 &tcp_log_debug, 0, "Log errors caused by incoming TCP segments");
307 static int tcp_tcbhashsize;
308 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
309 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
311 static int do_tcpdrain = 1;
312 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
313 "Enable tcp_drain routine for extra help when low on mbufs");
315 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD,
316 &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs");
318 VNET_DEFINE_STATIC(int, icmp_may_rst) = 1;
319 #define V_icmp_may_rst VNET(icmp_may_rst)
320 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW,
321 &VNET_NAME(icmp_may_rst), 0,
322 "Certain ICMP unreachable messages may abort connections in SYN_SENT");
324 VNET_DEFINE_STATIC(int, tcp_isn_reseed_interval) = 0;
325 #define V_tcp_isn_reseed_interval VNET(tcp_isn_reseed_interval)
326 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW,
327 &VNET_NAME(tcp_isn_reseed_interval), 0,
328 "Seconds between reseeding of ISN secret");
330 static int tcp_soreceive_stream;
331 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN,
332 &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets");
334 VNET_DEFINE(uma_zone_t, sack_hole_zone);
335 #define V_sack_hole_zone VNET(sack_hole_zone)
336 VNET_DEFINE(uint32_t, tcp_map_entries_limit) = 0; /* unlimited */
338 sysctl_net_inet_tcp_map_limit_check(SYSCTL_HANDLER_ARGS)
343 new = V_tcp_map_entries_limit;
344 error = sysctl_handle_int(oidp, &new, 0, req);
345 if (error == 0 && req->newptr) {
346 /* only allow "0" and value > minimum */
347 if (new > 0 && new < TCP_MIN_MAP_ENTRIES_LIMIT)
350 V_tcp_map_entries_limit = new;
354 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, map_limit,
355 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
356 &VNET_NAME(tcp_map_entries_limit), 0,
357 &sysctl_net_inet_tcp_map_limit_check, "IU",
358 "Total sendmap entries limit");
360 VNET_DEFINE(uint32_t, tcp_map_split_limit) = 0; /* unlimited */
361 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, split_limit, CTLFLAG_VNET | CTLFLAG_RW,
362 &VNET_NAME(tcp_map_split_limit), 0,
363 "Total sendmap split entries limit");
366 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]);
369 #define TS_OFFSET_SECRET_LENGTH SIPHASH_KEY_LENGTH
370 VNET_DEFINE_STATIC(u_char, ts_offset_secret[TS_OFFSET_SECRET_LENGTH]);
371 #define V_ts_offset_secret VNET(ts_offset_secret)
373 static int tcp_default_fb_init(struct tcpcb *tp);
374 static void tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged);
375 static int tcp_default_handoff_ok(struct tcpcb *tp);
376 static struct inpcb *tcp_notify(struct inpcb *, int);
377 static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int);
378 static struct inpcb *tcp_mtudisc(struct inpcb *, int);
379 static struct inpcb *tcp_drop_syn_sent(struct inpcb *, int);
380 static char * tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th,
381 const void *ip4hdr, const void *ip6hdr);
382 static ipproto_ctlinput_t tcp_ctlinput;
383 static udp_tun_icmp_t tcp_ctlinput_viaudp;
385 static struct tcp_function_block tcp_def_funcblk = {
386 .tfb_tcp_block_name = "freebsd",
387 .tfb_tcp_output = tcp_default_output,
388 .tfb_tcp_do_segment = tcp_do_segment,
389 .tfb_tcp_ctloutput = tcp_default_ctloutput,
390 .tfb_tcp_handoff_ok = tcp_default_handoff_ok,
391 .tfb_tcp_fb_init = tcp_default_fb_init,
392 .tfb_tcp_fb_fini = tcp_default_fb_fini,
395 static int tcp_fb_cnt = 0;
396 struct tcp_funchead t_functions;
397 static struct tcp_function_block *tcp_func_set_ptr = &tcp_def_funcblk;
400 tcp_record_dsack(struct tcpcb *tp, tcp_seq start, tcp_seq end, int tlp)
402 TCPSTAT_INC(tcps_dsack_count);
405 if (SEQ_GT(end, start)) {
406 tp->t_dsack_bytes += (end - start);
407 TCPSTAT_ADD(tcps_dsack_bytes, (end - start));
409 tp->t_dsack_tlp_bytes += (start - end);
410 TCPSTAT_ADD(tcps_dsack_bytes, (start - end));
413 if (SEQ_GT(end, start)) {
414 tp->t_dsack_bytes += (end - start);
415 TCPSTAT_ADD(tcps_dsack_tlp_bytes, (end - start));
417 tp->t_dsack_tlp_bytes += (start - end);
418 TCPSTAT_ADD(tcps_dsack_tlp_bytes, (start - end));
423 static struct tcp_function_block *
424 find_tcp_functions_locked(struct tcp_function_set *fs)
426 struct tcp_function *f;
427 struct tcp_function_block *blk=NULL;
429 TAILQ_FOREACH(f, &t_functions, tf_next) {
430 if (strcmp(f->tf_name, fs->function_set_name) == 0) {
438 static struct tcp_function_block *
439 find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s)
441 struct tcp_function_block *rblk=NULL;
442 struct tcp_function *f;
444 TAILQ_FOREACH(f, &t_functions, tf_next) {
445 if (f->tf_fb == blk) {
456 struct tcp_function_block *
457 find_and_ref_tcp_functions(struct tcp_function_set *fs)
459 struct tcp_function_block *blk;
461 rw_rlock(&tcp_function_lock);
462 blk = find_tcp_functions_locked(fs);
464 refcount_acquire(&blk->tfb_refcnt);
465 rw_runlock(&tcp_function_lock);
469 struct tcp_function_block *
470 find_and_ref_tcp_fb(struct tcp_function_block *blk)
472 struct tcp_function_block *rblk;
474 rw_rlock(&tcp_function_lock);
475 rblk = find_tcp_fb_locked(blk, NULL);
477 refcount_acquire(&rblk->tfb_refcnt);
478 rw_runlock(&tcp_function_lock);
482 /* Find a matching alias for the given tcp_function_block. */
484 find_tcp_function_alias(struct tcp_function_block *blk,
485 struct tcp_function_set *fs)
487 struct tcp_function *f;
491 rw_rlock(&tcp_function_lock);
492 TAILQ_FOREACH(f, &t_functions, tf_next) {
493 if ((f->tf_fb == blk) &&
494 (strncmp(f->tf_name, blk->tfb_tcp_block_name,
495 TCP_FUNCTION_NAME_LEN_MAX) != 0)) {
496 /* Matching function block with different name. */
497 strncpy(fs->function_set_name, f->tf_name,
498 TCP_FUNCTION_NAME_LEN_MAX);
503 /* Null terminate the string appropriately. */
505 fs->function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
507 fs->function_set_name[0] = '\0';
509 rw_runlock(&tcp_function_lock);
513 static struct tcp_function_block *
514 find_and_ref_tcp_default_fb(void)
516 struct tcp_function_block *rblk;
518 rw_rlock(&tcp_function_lock);
519 rblk = tcp_func_set_ptr;
520 refcount_acquire(&rblk->tfb_refcnt);
521 rw_runlock(&tcp_function_lock);
526 tcp_switch_back_to_default(struct tcpcb *tp)
528 struct tcp_function_block *tfb;
530 KASSERT(tp->t_fb != &tcp_def_funcblk,
531 ("%s: called by the built-in default stack", __func__));
534 * Release the old stack. This function will either find a new one
537 if (tp->t_fb->tfb_tcp_fb_fini != NULL)
538 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
539 refcount_release(&tp->t_fb->tfb_refcnt);
542 * Now, we'll find a new function block to use.
543 * Start by trying the current user-selected
544 * default, unless this stack is the user-selected
547 tfb = find_and_ref_tcp_default_fb();
548 if (tfb == tp->t_fb) {
549 refcount_release(&tfb->tfb_refcnt);
552 /* Does the stack accept this connection? */
553 if (tfb != NULL && tfb->tfb_tcp_handoff_ok != NULL &&
554 (*tfb->tfb_tcp_handoff_ok)(tp)) {
555 refcount_release(&tfb->tfb_refcnt);
558 /* Try to use that stack. */
560 /* Initialize the new stack. If it succeeds, we are done. */
562 if (tp->t_fb->tfb_tcp_fb_init == NULL ||
563 (*tp->t_fb->tfb_tcp_fb_init)(tp) == 0)
567 * Initialization failed. Release the reference count on
570 refcount_release(&tfb->tfb_refcnt);
574 * If that wasn't feasible, use the built-in default
575 * stack which is not allowed to reject anyone.
577 tfb = find_and_ref_tcp_fb(&tcp_def_funcblk);
579 /* there always should be a default */
580 panic("Can't refer to tcp_def_funcblk");
582 if (tfb->tfb_tcp_handoff_ok != NULL) {
583 if ((*tfb->tfb_tcp_handoff_ok) (tp)) {
584 /* The default stack cannot say no */
585 panic("Default stack rejects a new session?");
589 if (tp->t_fb->tfb_tcp_fb_init != NULL &&
590 (*tp->t_fb->tfb_tcp_fb_init)(tp)) {
591 /* The default stack cannot fail */
592 panic("Default stack initialization failed");
597 tcp_recv_udp_tunneled_packet(struct mbuf *m, int off, struct inpcb *inp,
598 const struct sockaddr *sa, void *ctx)
609 TCPSTAT_INC(tcps_tunneled_pkts);
610 if ((m->m_flags & M_PKTHDR) == 0) {
611 /* Can't handle one that is not a pkt hdr */
612 TCPSTAT_INC(tcps_tunneled_errs);
615 thlen = sizeof(struct tcphdr);
616 if (m->m_len < off + sizeof(struct udphdr) + thlen &&
617 (m = m_pullup(m, off + sizeof(struct udphdr) + thlen)) == NULL) {
618 TCPSTAT_INC(tcps_tunneled_errs);
621 iph = mtod(m, struct ip *);
622 uh = (struct udphdr *)((caddr_t)iph + off);
623 th = (struct tcphdr *)(uh + 1);
624 thlen = th->th_off << 2;
625 if (m->m_len < off + sizeof(struct udphdr) + thlen) {
626 m = m_pullup(m, off + sizeof(struct udphdr) + thlen);
628 TCPSTAT_INC(tcps_tunneled_errs);
631 iph = mtod(m, struct ip *);
632 uh = (struct udphdr *)((caddr_t)iph + off);
633 th = (struct tcphdr *)(uh + 1);
636 m->m_pkthdr.tcp_tun_port = port = uh->uh_sport;
637 bcopy(th, uh, m->m_len - off);
638 m->m_len -= sizeof(struct udphdr);
639 m->m_pkthdr.len -= sizeof(struct udphdr);
641 * We use the same algorithm for
642 * both UDP and TCP for c-sum. So
643 * the code in tcp_input will skip
644 * the checksum. So we do nothing
645 * with the flag (m->m_pkthdr.csum_flags).
650 iph->ip_len = htons(ntohs(iph->ip_len) - sizeof(struct udphdr));
651 tcp_input_with_port(&m, &off, IPPROTO_TCP, port);
655 case IPV6_VERSION >> 4:
656 ip6 = mtod(m, struct ip6_hdr *);
657 ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) - sizeof(struct udphdr));
658 tcp6_input_with_port(&m, &off, IPPROTO_TCP, port);
673 sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS)
676 struct tcp_function_set fs;
677 struct tcp_function_block *blk;
679 memset(&fs, 0, sizeof(fs));
680 rw_rlock(&tcp_function_lock);
681 blk = find_tcp_fb_locked(tcp_func_set_ptr, NULL);
684 strcpy(fs.function_set_name, blk->tfb_tcp_block_name);
685 fs.pcbcnt = blk->tfb_refcnt;
687 rw_runlock(&tcp_function_lock);
688 error = sysctl_handle_string(oidp, fs.function_set_name,
689 sizeof(fs.function_set_name), req);
691 /* Check for error or no change */
692 if (error != 0 || req->newptr == NULL)
695 rw_wlock(&tcp_function_lock);
696 blk = find_tcp_functions_locked(&fs);
698 (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) {
702 tcp_func_set_ptr = blk;
704 rw_wunlock(&tcp_function_lock);
708 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default,
709 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
710 NULL, 0, sysctl_net_inet_default_tcp_functions, "A",
711 "Set/get the default TCP functions");
714 sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS)
716 int error, cnt, linesz;
717 struct tcp_function *f;
723 rw_rlock(&tcp_function_lock);
724 TAILQ_FOREACH(f, &t_functions, tf_next) {
727 rw_runlock(&tcp_function_lock);
729 bufsz = (cnt+2) * ((TCP_FUNCTION_NAME_LEN_MAX * 2) + 13) + 1;
730 buffer = malloc(bufsz, M_TEMP, M_WAITOK);
735 linesz = snprintf(cp, bufsz, "\n%-32s%c %-32s %s\n", "Stack", 'D',
736 "Alias", "PCB count");
741 rw_rlock(&tcp_function_lock);
742 TAILQ_FOREACH(f, &t_functions, tf_next) {
743 alias = (f->tf_name != f->tf_fb->tfb_tcp_block_name);
744 linesz = snprintf(cp, bufsz, "%-32s%c %-32s %u\n",
745 f->tf_fb->tfb_tcp_block_name,
746 (f->tf_fb == tcp_func_set_ptr) ? '*' : ' ',
747 alias ? f->tf_name : "-",
748 f->tf_fb->tfb_refcnt);
749 if (linesz >= bufsz) {
757 rw_runlock(&tcp_function_lock);
759 error = sysctl_handle_string(oidp, buffer, outsz + 1, req);
760 free(buffer, M_TEMP);
764 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available,
765 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
766 NULL, 0, sysctl_net_inet_list_available, "A",
767 "list available TCP Function sets");
769 VNET_DEFINE(int, tcp_udp_tunneling_port) = TCP_TUNNELING_PORT_DEFAULT;
772 VNET_DEFINE(struct socket *, udp4_tun_socket) = NULL;
773 #define V_udp4_tun_socket VNET(udp4_tun_socket)
776 VNET_DEFINE(struct socket *, udp6_tun_socket) = NULL;
777 #define V_udp6_tun_socket VNET(udp6_tun_socket)
781 tcp_over_udp_stop(void)
784 * This function assumes sysctl caller holds inp_rinfo_lock()
788 if (V_udp4_tun_socket != NULL) {
789 soclose(V_udp4_tun_socket);
790 V_udp4_tun_socket = NULL;
794 if (V_udp6_tun_socket != NULL) {
795 soclose(V_udp6_tun_socket);
796 V_udp6_tun_socket = NULL;
802 tcp_over_udp_start(void)
807 struct sockaddr_in sin;
810 struct sockaddr_in6 sin6;
813 * This function assumes sysctl caller holds inp_info_rlock()
816 port = V_tcp_udp_tunneling_port;
817 if (ntohs(port) == 0) {
818 /* Must have a port set */
822 if (V_udp4_tun_socket != NULL) {
823 /* Already running -- must stop first */
828 if (V_udp6_tun_socket != NULL) {
829 /* Already running -- must stop first */
834 if ((ret = socreate(PF_INET, &V_udp4_tun_socket,
835 SOCK_DGRAM, IPPROTO_UDP,
836 curthread->td_ucred, curthread))) {
840 /* Call the special UDP hook. */
841 if ((ret = udp_set_kernel_tunneling(V_udp4_tun_socket,
842 tcp_recv_udp_tunneled_packet,
848 /* Ok, we have a socket, bind it to the port. */
849 memset(&sin, 0, sizeof(struct sockaddr_in));
850 sin.sin_len = sizeof(struct sockaddr_in);
851 sin.sin_family = AF_INET;
852 sin.sin_port = htons(port);
853 if ((ret = sobind(V_udp4_tun_socket,
854 (struct sockaddr *)&sin, curthread))) {
860 if ((ret = socreate(PF_INET6, &V_udp6_tun_socket,
861 SOCK_DGRAM, IPPROTO_UDP,
862 curthread->td_ucred, curthread))) {
866 /* Call the special UDP hook. */
867 if ((ret = udp_set_kernel_tunneling(V_udp6_tun_socket,
868 tcp_recv_udp_tunneled_packet,
869 tcp6_ctlinput_viaudp,
874 /* Ok, we have a socket, bind it to the port. */
875 memset(&sin6, 0, sizeof(struct sockaddr_in6));
876 sin6.sin6_len = sizeof(struct sockaddr_in6);
877 sin6.sin6_family = AF_INET6;
878 sin6.sin6_port = htons(port);
879 if ((ret = sobind(V_udp6_tun_socket,
880 (struct sockaddr *)&sin6, curthread))) {
889 sysctl_net_inet_tcp_udp_tunneling_port_check(SYSCTL_HANDLER_ARGS)
894 old = V_tcp_udp_tunneling_port;
896 error = sysctl_handle_int(oidp, &new, 0, req);
898 (req->newptr != NULL)) {
899 if ((new < TCP_TUNNELING_PORT_MIN) ||
900 (new > TCP_TUNNELING_PORT_MAX)) {
903 V_tcp_udp_tunneling_port = new;
908 error = tcp_over_udp_start();
915 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_port,
916 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
917 &VNET_NAME(tcp_udp_tunneling_port),
918 0, &sysctl_net_inet_tcp_udp_tunneling_port_check, "IU",
919 "Tunneling port for tcp over udp");
921 VNET_DEFINE(int, tcp_udp_tunneling_overhead) = TCP_TUNNELING_OVERHEAD_DEFAULT;
924 sysctl_net_inet_tcp_udp_tunneling_overhead_check(SYSCTL_HANDLER_ARGS)
928 new = V_tcp_udp_tunneling_overhead;
929 error = sysctl_handle_int(oidp, &new, 0, req);
930 if (error == 0 && req->newptr) {
931 if ((new < TCP_TUNNELING_OVERHEAD_MIN) ||
932 (new > TCP_TUNNELING_OVERHEAD_MAX))
935 V_tcp_udp_tunneling_overhead = new;
940 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_overhead,
941 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
942 &VNET_NAME(tcp_udp_tunneling_overhead),
943 0, &sysctl_net_inet_tcp_udp_tunneling_overhead_check, "IU",
944 "MSS reduction when using tcp over udp");
947 * Exports one (struct tcp_function_info) for each alias/name.
950 sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS)
953 struct tcp_function *f;
954 struct tcp_function_info tfi;
957 * We don't allow writes.
959 if (req->newptr != NULL)
963 * Wire the old buffer so we can directly copy the functions to
964 * user space without dropping the lock.
966 if (req->oldptr != NULL) {
967 error = sysctl_wire_old_buffer(req, 0);
973 * Walk the list and copy out matching entries. If INVARIANTS
974 * is compiled in, also walk the list to verify the length of
975 * the list matches what we have recorded.
977 rw_rlock(&tcp_function_lock);
981 if (req->oldptr == NULL) {
986 TAILQ_FOREACH(f, &t_functions, tf_next) {
990 if (req->oldptr != NULL) {
991 bzero(&tfi, sizeof(tfi));
992 tfi.tfi_refcnt = f->tf_fb->tfb_refcnt;
993 tfi.tfi_id = f->tf_fb->tfb_id;
994 (void)strlcpy(tfi.tfi_alias, f->tf_name,
995 sizeof(tfi.tfi_alias));
996 (void)strlcpy(tfi.tfi_name,
997 f->tf_fb->tfb_tcp_block_name, sizeof(tfi.tfi_name));
998 error = SYSCTL_OUT(req, &tfi, sizeof(tfi));
1000 * Don't stop on error, as that is the
1001 * mechanism we use to accumulate length
1002 * information if the buffer was too short.
1006 KASSERT(cnt == tcp_fb_cnt,
1007 ("%s: cnt (%d) != tcp_fb_cnt (%d)", __func__, cnt, tcp_fb_cnt));
1011 rw_runlock(&tcp_function_lock);
1012 if (req->oldptr == NULL)
1013 error = SYSCTL_OUT(req, NULL,
1014 (cnt + 1) * sizeof(struct tcp_function_info));
1019 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, function_info,
1020 CTLTYPE_OPAQUE | CTLFLAG_SKIP | CTLFLAG_RD | CTLFLAG_MPSAFE,
1021 NULL, 0, sysctl_net_inet_list_func_info, "S,tcp_function_info",
1022 "List TCP function block name-to-ID mappings");
1025 * tfb_tcp_handoff_ok() function for the default stack.
1026 * Note that we'll basically try to take all comers.
1029 tcp_default_handoff_ok(struct tcpcb *tp)
1036 * tfb_tcp_fb_init() function for the default stack.
1038 * This handles making sure we have appropriate timers set if you are
1039 * transitioning a socket that has some amount of setup done.
1041 * The init() fuction from the default can *never* return non-zero i.e.
1042 * it is required to always succeed since it is the stack of last resort!
1045 tcp_default_fb_init(struct tcpcb *tp)
1047 struct socket *so = tptosocket(tp);
1049 INP_WLOCK_ASSERT(tptoinpcb(tp));
1051 KASSERT(tp->t_state >= 0 && tp->t_state < TCPS_TIME_WAIT,
1052 ("%s: connection %p in unexpected state %d", __func__, tp,
1056 * Nothing to do for ESTABLISHED or LISTEN states. And, we don't
1057 * know what to do for unexpected states (which includes TIME_WAIT).
1059 if (tp->t_state <= TCPS_LISTEN || tp->t_state >= TCPS_TIME_WAIT)
1063 * Make sure some kind of transmission timer is set if there is
1066 if ((!TCPS_HAVEESTABLISHED(tp->t_state) || sbavail(&so->so_snd) ||
1067 tp->snd_una != tp->snd_max) && !(tcp_timer_active(tp, TT_REXMT) ||
1068 tcp_timer_active(tp, TT_PERSIST))) {
1070 * If the session has established and it looks like it should
1071 * be in the persist state, set the persist timer. Otherwise,
1072 * set the retransmit timer.
1074 if (TCPS_HAVEESTABLISHED(tp->t_state) && tp->snd_wnd == 0 &&
1075 (int32_t)(tp->snd_nxt - tp->snd_una) <
1076 (int32_t)sbavail(&so->so_snd))
1079 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1082 /* All non-embryonic sessions get a keepalive timer. */
1083 if (!tcp_timer_active(tp, TT_KEEP))
1084 tcp_timer_activate(tp, TT_KEEP,
1085 TCPS_HAVEESTABLISHED(tp->t_state) ? TP_KEEPIDLE(tp) :
1089 * Make sure critical variables are initialized
1090 * if transitioning while in Recovery.
1092 if IN_FASTRECOVERY(tp->t_flags) {
1093 if (tp->sackhint.recover_fs == 0)
1094 tp->sackhint.recover_fs = max(1,
1095 tp->snd_nxt - tp->snd_una);
1102 * tfb_tcp_fb_fini() function for the default stack.
1104 * This changes state as necessary (or prudent) to prepare for another stack
1105 * to assume responsibility for the connection.
1108 tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged)
1111 INP_WLOCK_ASSERT(tptoinpcb(tp));
1115 * Target size of TCP PCB hash tables. Must be a power of two.
1117 * Note that this can be overridden by the kernel environment
1118 * variable net.inet.tcp.tcbhashsize
1121 #define TCBHASHSIZE 0
1126 * Callouts should be moved into struct tcp directly. They are currently
1127 * separate because the tcpcb structure is exported to userland for sysctl
1128 * parsing purposes, which do not know about callouts.
1132 struct tcp_timer tt;
1139 VNET_DEFINE_STATIC(uma_zone_t, tcpcb_zone);
1140 #define V_tcpcb_zone VNET(tcpcb_zone)
1142 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers");
1143 MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory");
1145 static struct mtx isn_mtx;
1147 #define ISN_LOCK_INIT() mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
1148 #define ISN_LOCK() mtx_lock(&isn_mtx)
1149 #define ISN_UNLOCK() mtx_unlock(&isn_mtx)
1151 INPCBSTORAGE_DEFINE(tcpcbstor, inpcb, "tcpinp", "tcp_inpcb", "tcp", "tcphash");
1154 * Take a value and get the next power of 2 that doesn't overflow.
1155 * Used to size the tcp_inpcb hash buckets.
1158 maketcp_hashsize(int size)
1164 * get the next power of 2 higher than maxsockets.
1166 hashsize = 1 << fls(size);
1167 /* catch overflow, and just go one power of 2 smaller */
1168 if (hashsize < size) {
1169 hashsize = 1 << (fls(size) - 1);
1174 static volatile int next_tcp_stack_id = 1;
1177 * Register a TCP function block with the name provided in the names
1178 * array. (Note that this function does NOT automatically register
1179 * blk->tfb_tcp_block_name as a stack name. Therefore, you should
1180 * explicitly include blk->tfb_tcp_block_name in the list of names if
1181 * you wish to register the stack with that name.)
1183 * Either all name registrations will succeed or all will fail. If
1184 * a name registration fails, the function will update the num_names
1185 * argument to point to the array index of the name that encountered
1188 * Returns 0 on success, or an error code on failure.
1191 register_tcp_functions_as_names(struct tcp_function_block *blk, int wait,
1192 const char *names[], int *num_names)
1194 struct tcp_function *n;
1195 struct tcp_function_set fs;
1198 KASSERT(names != NULL && *num_names > 0,
1199 ("%s: Called with 0-length name list", __func__));
1200 KASSERT(names != NULL, ("%s: Called with NULL name list", __func__));
1201 KASSERT(rw_initialized(&tcp_function_lock),
1202 ("%s: called too early", __func__));
1204 if ((blk->tfb_tcp_output == NULL) ||
1205 (blk->tfb_tcp_do_segment == NULL) ||
1206 (blk->tfb_tcp_ctloutput == NULL) ||
1207 (strlen(blk->tfb_tcp_block_name) == 0)) {
1209 * These functions are required and you
1215 if (blk->tfb_tcp_timer_stop_all ||
1216 blk->tfb_tcp_timer_activate ||
1217 blk->tfb_tcp_timer_active ||
1218 blk->tfb_tcp_timer_stop) {
1220 * If you define one timer function you
1221 * must have them all.
1223 if ((blk->tfb_tcp_timer_stop_all == NULL) ||
1224 (blk->tfb_tcp_timer_activate == NULL) ||
1225 (blk->tfb_tcp_timer_active == NULL) ||
1226 (blk->tfb_tcp_timer_stop == NULL)) {
1232 if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) {
1237 refcount_init(&blk->tfb_refcnt, 0);
1238 blk->tfb_id = atomic_fetchadd_int(&next_tcp_stack_id, 1);
1239 for (i = 0; i < *num_names; i++) {
1240 n = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait);
1247 (void)strlcpy(fs.function_set_name, names[i],
1248 sizeof(fs.function_set_name));
1249 rw_wlock(&tcp_function_lock);
1250 if (find_tcp_functions_locked(&fs) != NULL) {
1251 /* Duplicate name space not allowed */
1252 rw_wunlock(&tcp_function_lock);
1253 free(n, M_TCPFUNCTIONS);
1257 (void)strlcpy(n->tf_name, names[i], sizeof(n->tf_name));
1258 TAILQ_INSERT_TAIL(&t_functions, n, tf_next);
1260 rw_wunlock(&tcp_function_lock);
1266 * Deregister the names we just added. Because registration failed
1267 * for names[i], we don't need to deregister that name.
1270 rw_wlock(&tcp_function_lock);
1272 TAILQ_FOREACH(n, &t_functions, tf_next) {
1273 if (!strncmp(n->tf_name, names[i],
1274 TCP_FUNCTION_NAME_LEN_MAX)) {
1275 TAILQ_REMOVE(&t_functions, n, tf_next);
1278 free(n, M_TCPFUNCTIONS);
1283 rw_wunlock(&tcp_function_lock);
1288 * Register a TCP function block using the name provided in the name
1291 * Returns 0 on success, or an error code on failure.
1294 register_tcp_functions_as_name(struct tcp_function_block *blk, const char *name,
1297 const char *name_list[1];
1302 name_list[0] = name;
1304 name_list[0] = blk->tfb_tcp_block_name;
1305 rv = register_tcp_functions_as_names(blk, wait, name_list, &num_names);
1310 * Register a TCP function block using the name defined in
1311 * blk->tfb_tcp_block_name.
1313 * Returns 0 on success, or an error code on failure.
1316 register_tcp_functions(struct tcp_function_block *blk, int wait)
1319 return (register_tcp_functions_as_name(blk, NULL, wait));
1323 * Deregister all names associated with a function block. This
1324 * functionally removes the function block from use within the system.
1326 * When called with a true quiesce argument, mark the function block
1327 * as being removed so no more stacks will use it and determine
1328 * whether the removal would succeed.
1330 * When called with a false quiesce argument, actually attempt the
1333 * When called with a force argument, attempt to switch all TCBs to
1334 * use the default stack instead of returning EBUSY.
1336 * Returns 0 on success (or if the removal would succeed, or an error
1340 deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce,
1343 struct tcp_function *f;
1345 if (blk == &tcp_def_funcblk) {
1346 /* You can't un-register the default */
1349 rw_wlock(&tcp_function_lock);
1350 if (blk == tcp_func_set_ptr) {
1351 /* You can't free the current default */
1352 rw_wunlock(&tcp_function_lock);
1355 /* Mark the block so no more stacks can use it. */
1356 blk->tfb_flags |= TCP_FUNC_BEING_REMOVED;
1358 * If TCBs are still attached to the stack, attempt to switch them
1359 * to the default stack.
1361 if (force && blk->tfb_refcnt) {
1362 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
1363 INPLOOKUP_WLOCKPCB);
1366 VNET_ITERATOR_DECL(vnet_iter);
1368 rw_wunlock(&tcp_function_lock);
1371 VNET_FOREACH(vnet_iter) {
1372 CURVNET_SET(vnet_iter);
1373 while ((inp = inp_next(&inpi)) != NULL) {
1374 tp = intotcpcb(inp);
1375 if (tp == NULL || tp->t_fb != blk)
1377 tcp_switch_back_to_default(tp);
1381 VNET_LIST_RUNLOCK();
1383 rw_wlock(&tcp_function_lock);
1385 if (blk->tfb_refcnt) {
1386 /* TCBs still attached. */
1387 rw_wunlock(&tcp_function_lock);
1392 rw_wunlock(&tcp_function_lock);
1395 /* Remove any function names that map to this function block. */
1396 while (find_tcp_fb_locked(blk, &f) != NULL) {
1397 TAILQ_REMOVE(&t_functions, f, tf_next);
1400 free(f, M_TCPFUNCTIONS);
1402 rw_wunlock(&tcp_function_lock);
1409 struct epoch_tracker et;
1410 VNET_ITERATOR_DECL(vnet_iter);
1415 NET_EPOCH_ENTER(et);
1416 VNET_LIST_RLOCK_NOSLEEP();
1417 VNET_FOREACH(vnet_iter) {
1418 CURVNET_SET(vnet_iter);
1419 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
1420 INPLOOKUP_WLOCKPCB);
1425 * Walk the tcpbs, if existing, and flush the reassembly queue,
1426 * if there is one...
1427 * XXX: The "Net/3" implementation doesn't imply that the TCP
1428 * reassembly queue should be flushed, but in a situation
1429 * where we're really low on mbufs, this is potentially
1432 while ((inpb = inp_next(&inpi)) != NULL) {
1433 if ((tcpb = intotcpcb(inpb)) != NULL) {
1434 tcp_reass_flush(tcpb);
1435 tcp_clean_sackreport(tcpb);
1437 tcp_log_drain(tcpb);
1440 if (tcp_pcap_aggressive_free) {
1441 /* Free the TCP PCAP queues. */
1442 tcp_pcap_drain(&(tcpb->t_inpkts));
1443 tcp_pcap_drain(&(tcpb->t_outpkts));
1450 VNET_LIST_RUNLOCK_NOSLEEP();
1455 tcp_vnet_init(void *arg __unused)
1459 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN,
1460 &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1461 printf("%s: WARNING: unable to register helper hook\n", __func__);
1462 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT,
1463 &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1464 printf("%s: WARNING: unable to register helper hook\n", __func__);
1467 if (tcp_stats_init())
1468 printf("%s: WARNING: unable to initialise TCP stats\n",
1471 in_pcbinfo_init(&V_tcbinfo, &tcpcbstor, tcp_tcbhashsize,
1475 * These have to be type stable for the benefit of the timers.
1477 V_tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem),
1478 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1479 uma_zone_set_max(V_tcpcb_zone, maxsockets);
1480 uma_zone_set_warning(V_tcpcb_zone, "kern.ipc.maxsockets limit reached");
1485 TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack);
1486 V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
1487 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1489 tcp_fastopen_init();
1491 COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK);
1492 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK);
1494 V_tcp_msl = TCPTV_MSL;
1496 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
1497 tcp_vnet_init, NULL);
1500 tcp_init(void *arg __unused)
1502 const char *tcbhash_tuneable;
1505 tcp_reass_global_init();
1507 /* XXX virtualize those below? */
1508 tcp_delacktime = TCPTV_DELACK;
1509 tcp_keepinit = TCPTV_KEEP_INIT;
1510 tcp_keepidle = TCPTV_KEEP_IDLE;
1511 tcp_keepintvl = TCPTV_KEEPINTVL;
1512 tcp_maxpersistidle = TCPTV_KEEP_IDLE;
1513 tcp_rexmit_initial = TCPTV_RTOBASE;
1514 if (tcp_rexmit_initial < 1)
1515 tcp_rexmit_initial = 1;
1516 tcp_rexmit_min = TCPTV_MIN;
1517 if (tcp_rexmit_min < 1)
1519 tcp_persmin = TCPTV_PERSMIN;
1520 tcp_persmax = TCPTV_PERSMAX;
1521 tcp_rexmit_slop = TCPTV_CPU_VAR;
1522 tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT;
1524 /* Setup the tcp function block list */
1525 TAILQ_INIT(&t_functions);
1526 rw_init(&tcp_function_lock, "tcp_func_lock");
1527 register_tcp_functions(&tcp_def_funcblk, M_WAITOK);
1529 /* Initialize the TCP logging data. */
1532 arc4rand(&V_ts_offset_secret, sizeof(V_ts_offset_secret), 0);
1534 if (tcp_soreceive_stream) {
1536 tcp_protosw.pr_soreceive = soreceive_stream;
1539 tcp6_protosw.pr_soreceive = soreceive_stream;
1544 max_protohdr_grow(sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
1546 max_protohdr_grow(sizeof(struct tcpiphdr));
1550 EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
1551 SHUTDOWN_PRI_DEFAULT);
1552 EVENTHANDLER_REGISTER(vm_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT);
1553 EVENTHANDLER_REGISTER(mbuf_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT);
1555 tcp_inp_lro_direct_queue = counter_u64_alloc(M_WAITOK);
1556 tcp_inp_lro_wokeup_queue = counter_u64_alloc(M_WAITOK);
1557 tcp_inp_lro_compressed = counter_u64_alloc(M_WAITOK);
1558 tcp_inp_lro_locks_taken = counter_u64_alloc(M_WAITOK);
1559 tcp_extra_mbuf = counter_u64_alloc(M_WAITOK);
1560 tcp_would_have_but = counter_u64_alloc(M_WAITOK);
1561 tcp_comp_total = counter_u64_alloc(M_WAITOK);
1562 tcp_uncomp_total = counter_u64_alloc(M_WAITOK);
1563 tcp_bad_csums = counter_u64_alloc(M_WAITOK);
1568 hashsize = TCBHASHSIZE;
1569 tcbhash_tuneable = "net.inet.tcp.tcbhashsize";
1570 TUNABLE_INT_FETCH(tcbhash_tuneable, &hashsize);
1571 if (hashsize == 0) {
1573 * Auto tune the hash size based on maxsockets.
1574 * A perfect hash would have a 1:1 mapping
1575 * (hashsize = maxsockets) however it's been
1576 * suggested that O(2) average is better.
1578 hashsize = maketcp_hashsize(maxsockets / 4);
1580 * Our historical default is 512,
1581 * do not autotune lower than this.
1586 printf("%s: %s auto tuned to %d\n", __func__,
1587 tcbhash_tuneable, hashsize);
1590 * We require a hashsize to be a power of two.
1591 * Previously if it was not a power of two we would just reset it
1592 * back to 512, which could be a nasty surprise if you did not notice
1593 * the error message.
1594 * Instead what we do is clip it to the closest power of two lower
1595 * than the specified hash value.
1597 if (!powerof2(hashsize)) {
1598 int oldhashsize = hashsize;
1600 hashsize = maketcp_hashsize(hashsize);
1601 /* prevent absurdly low value */
1604 printf("%s: WARNING: TCB hash size not a power of 2, "
1605 "clipped from %d to %d.\n", __func__, oldhashsize,
1608 tcp_tcbhashsize = hashsize;
1611 IPPROTO_REGISTER(IPPROTO_TCP, tcp_input, tcp_ctlinput);
1614 IP6PROTO_REGISTER(IPPROTO_TCP, tcp6_input, tcp6_ctlinput);
1617 SYSINIT(tcp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, tcp_init, NULL);
1621 tcp_destroy(void *unused __unused)
1629 * All our processes are gone, all our sockets should be cleaned
1630 * up, which means, we should be past the tcp_discardcb() calls.
1631 * Sleep to let all tcpcb timers really disappear and cleanup.
1634 INP_INFO_WLOCK(&V_tcbinfo);
1635 n = V_tcbinfo.ipi_count;
1636 INP_INFO_WUNLOCK(&V_tcbinfo);
1639 pause("tcpdes", hz / 10);
1643 in_pcbinfo_destroy(&V_tcbinfo);
1644 /* tcp_discardcb() clears the sack_holes up. */
1645 uma_zdestroy(V_sack_hole_zone);
1646 uma_zdestroy(V_tcpcb_zone);
1649 * Cannot free the zone until all tcpcbs are released as we attach
1650 * the allocations to them.
1652 tcp_fastopen_destroy();
1654 COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES);
1655 VNET_PCPUSTAT_FREE(tcpstat);
1658 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]);
1660 printf("%s: WARNING: unable to deregister helper hook "
1661 "type=%d, id=%d: error %d returned\n", __func__,
1662 HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error);
1664 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]);
1666 printf("%s: WARNING: unable to deregister helper hook "
1667 "type=%d, id=%d: error %d returned\n", __func__,
1668 HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error);
1672 VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_destroy, NULL);
1682 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
1683 * tcp_template used to store this data in mbufs, but we now recopy it out
1684 * of the tcpcb each time to conserve mbufs.
1687 tcpip_fillheaders(struct inpcb *inp, uint16_t port, void *ip_ptr, void *tcp_ptr)
1689 struct tcphdr *th = (struct tcphdr *)tcp_ptr;
1691 INP_WLOCK_ASSERT(inp);
1694 if ((inp->inp_vflag & INP_IPV6) != 0) {
1695 struct ip6_hdr *ip6;
1697 ip6 = (struct ip6_hdr *)ip_ptr;
1698 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
1699 (inp->inp_flow & IPV6_FLOWINFO_MASK);
1700 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
1701 (IPV6_VERSION & IPV6_VERSION_MASK);
1703 ip6->ip6_nxt = IPPROTO_TCP;
1705 ip6->ip6_nxt = IPPROTO_UDP;
1706 ip6->ip6_plen = htons(sizeof(struct tcphdr));
1707 ip6->ip6_src = inp->in6p_laddr;
1708 ip6->ip6_dst = inp->in6p_faddr;
1711 #if defined(INET6) && defined(INET)
1718 ip = (struct ip *)ip_ptr;
1719 ip->ip_v = IPVERSION;
1721 ip->ip_tos = inp->inp_ip_tos;
1725 ip->ip_ttl = inp->inp_ip_ttl;
1728 ip->ip_p = IPPROTO_TCP;
1730 ip->ip_p = IPPROTO_UDP;
1731 ip->ip_src = inp->inp_laddr;
1732 ip->ip_dst = inp->inp_faddr;
1735 th->th_sport = inp->inp_lport;
1736 th->th_dport = inp->inp_fport;
1740 tcp_set_flags(th, 0);
1743 th->th_sum = 0; /* in_pseudo() is called later for ipv4 */
1747 * Create template to be used to send tcp packets on a connection.
1748 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only
1749 * use for this function is in keepalives, which use tcp_respond.
1752 tcpip_maketemplate(struct inpcb *inp)
1756 t = malloc(sizeof(*t), M_TEMP, M_NOWAIT);
1759 tcpip_fillheaders(inp, 0, (void *)&t->tt_ipgen, (void *)&t->tt_t);
1764 * Send a single message to the TCP at address specified by
1765 * the given TCP/IP header. If m == NULL, then we make a copy
1766 * of the tcpiphdr at th and send directly to the addressed host.
1767 * This is used to force keep alive messages out using the TCP
1768 * template for a connection. If flags are given then we send
1769 * a message back to the TCP which originated the segment th,
1770 * and discard the mbuf containing it and any other attached mbufs.
1772 * In any case the ack and sequence number of the transmitted
1773 * segment are as specified by the parameters.
1775 * NOTE: If m != NULL, then th must point to *inside* the mbuf.
1778 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
1779 tcp_seq ack, tcp_seq seq, uint16_t flags)
1785 struct udphdr *uh = NULL;
1787 struct tcp_log_buffer *lgb;
1790 struct ip6_hdr *ip6;
1793 int optlen, tlen, win, ulen;
1799 int thflags = tcp_get_flags(th);
1802 KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
1806 isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4);
1812 inp = tptoinpcb(tp);
1813 INP_LOCK_ASSERT(inp);
1819 if (isipv6 && ip6 && (ip6->ip6_nxt == IPPROTO_UDP))
1820 port = m->m_pkthdr.tcp_tun_port;
1823 if (ip && (ip->ip_p == IPPROTO_UDP))
1824 port = m->m_pkthdr.tcp_tun_port;
1833 if (!(flags & TH_RST)) {
1834 win = sbspace(&inp->inp_socket->so_rcv);
1835 if (win > TCP_MAXWIN << tp->rcv_scale)
1836 win = TCP_MAXWIN << tp->rcv_scale;
1838 if ((tp->t_flags & TF_NOOPT) == 0)
1842 m = m_gethdr(M_NOWAIT, MT_DATA);
1845 m->m_data += max_linkhdr;
1848 bcopy((caddr_t)ip6, mtod(m, caddr_t),
1849 sizeof(struct ip6_hdr));
1850 ip6 = mtod(m, struct ip6_hdr *);
1851 nth = (struct tcphdr *)(ip6 + 1);
1853 /* Insert a UDP header */
1854 uh = (struct udphdr *)nth;
1855 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1856 uh->uh_dport = port;
1857 nth = (struct tcphdr *)(uh + 1);
1862 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
1863 ip = mtod(m, struct ip *);
1864 nth = (struct tcphdr *)(ip + 1);
1866 /* Insert a UDP header */
1867 uh = (struct udphdr *)nth;
1868 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1869 uh->uh_dport = port;
1870 nth = (struct tcphdr *)(uh + 1);
1873 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
1875 } else if ((!M_WRITABLE(m)) || (port != 0)) {
1878 /* Can't reuse 'm', allocate a new mbuf. */
1879 n = m_gethdr(M_NOWAIT, MT_DATA);
1885 if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
1891 n->m_data += max_linkhdr;
1892 /* m_len is set later */
1893 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
1896 bcopy((caddr_t)ip6, mtod(n, caddr_t),
1897 sizeof(struct ip6_hdr));
1898 ip6 = mtod(n, struct ip6_hdr *);
1899 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1900 nth = (struct tcphdr *)(ip6 + 1);
1902 /* Insert a UDP header */
1903 uh = (struct udphdr *)nth;
1904 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1905 uh->uh_dport = port;
1906 nth = (struct tcphdr *)(uh + 1);
1911 bcopy((caddr_t)ip, mtod(n, caddr_t), sizeof(struct ip));
1912 ip = mtod(n, struct ip *);
1913 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1914 nth = (struct tcphdr *)(ip + 1);
1916 /* Insert a UDP header */
1917 uh = (struct udphdr *)nth;
1918 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1919 uh->uh_dport = port;
1920 nth = (struct tcphdr *)(uh + 1);
1923 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
1924 xchg(nth->th_dport, nth->th_sport, uint16_t);
1931 * XXX MRT We inherit the FIB, which is lucky.
1935 m->m_data = (caddr_t)ipgen;
1936 /* m_len is set later */
1939 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1940 nth = (struct tcphdr *)(ip6 + 1);
1944 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1945 nth = (struct tcphdr *)(ip + 1);
1949 * this is usually a case when an extension header
1950 * exists between the IPv6 header and the
1953 nth->th_sport = th->th_sport;
1954 nth->th_dport = th->th_dport;
1956 xchg(nth->th_dport, nth->th_sport, uint16_t);
1962 tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
1964 #if defined(INET) && defined(INET6)
1968 tlen = sizeof (struct tcpiphdr);
1971 tlen += sizeof (struct udphdr);
1974 KASSERT(M_TRAILINGSPACE(m) >= tlen,
1975 ("Not enough trailing space for message (m=%p, need=%d, have=%ld)",
1976 m, tlen, (long)M_TRAILINGSPACE(m)));
1981 ect = tcp_ecn_output_established(tp, &flags, 0, false);
1982 /* Make sure we have room. */
1983 if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) {
1984 m->m_next = m_get(M_NOWAIT, MT_DATA);
1986 optp = mtod(m->m_next, u_char *);
1991 optp = (u_char *) (nth + 1);
1997 if (tp->t_flags & TF_RCVD_TSTMP) {
1998 to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
1999 to.to_tsecr = tp->ts_recent;
2000 to.to_flags |= TOF_TS;
2002 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2003 /* TCP-MD5 (RFC2385). */
2004 if (tp->t_flags & TF_SIGNATURE)
2005 to.to_flags |= TOF_SIGNATURE;
2007 /* Add the options. */
2008 tlen += optlen = tcp_addoptions(&to, optp);
2010 /* Update m_len in the correct mbuf. */
2011 optm->m_len += optlen;
2017 ulen = tlen - sizeof(struct ip6_hdr);
2018 uh->uh_ulen = htons(ulen);
2020 ip6->ip6_flow = htonl(ect << 20);
2021 ip6->ip6_vfc = IPV6_VERSION;
2023 ip6->ip6_nxt = IPPROTO_UDP;
2025 ip6->ip6_nxt = IPPROTO_TCP;
2026 ip6->ip6_plen = htons(tlen - sizeof(*ip6));
2029 #if defined(INET) && defined(INET6)
2035 ulen = tlen - sizeof(struct ip);
2036 uh->uh_ulen = htons(ulen);
2039 ip->ip_len = htons(tlen);
2040 ip->ip_ttl = V_ip_defttl;
2042 ip->ip_p = IPPROTO_UDP;
2044 ip->ip_p = IPPROTO_TCP;
2046 if (V_path_mtu_discovery)
2047 ip->ip_off |= htons(IP_DF);
2050 m->m_pkthdr.len = tlen;
2051 m->m_pkthdr.rcvif = NULL;
2055 * Packet is associated with a socket, so allow the
2056 * label of the response to reflect the socket label.
2058 INP_LOCK_ASSERT(inp);
2059 mac_inpcb_create_mbuf(inp, m);
2062 * Packet is not associated with a socket, so possibly
2063 * update the label in place.
2065 mac_netinet_tcp_reply(m);
2068 nth->th_seq = htonl(seq);
2069 nth->th_ack = htonl(ack);
2070 nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
2071 tcp_set_flags(nth, flags);
2073 nth->th_win = htons((u_short) (win >> tp->rcv_scale));
2075 nth->th_win = htons((u_short)win);
2078 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2079 if (to.to_flags & TOF_SIGNATURE) {
2080 if (!TCPMD5_ENABLED() ||
2081 TCPMD5_OUTPUT(m, nth, to.to_signature) != 0) {
2091 m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
2092 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2093 uh->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
2096 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2097 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2098 nth->th_sum = in6_cksum_pseudo(ip6,
2099 tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0);
2101 ip6->ip6_hlim = in6_selecthlim(inp, NULL);
2104 #if defined(INET6) && defined(INET)
2110 uh->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2111 htons(ulen + IPPROTO_UDP));
2112 m->m_pkthdr.csum_flags = CSUM_UDP;
2113 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2116 m->m_pkthdr.csum_flags = CSUM_TCP;
2117 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2118 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2119 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
2124 if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG))
2125 tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
2127 TCP_PROBE3(debug__output, tp, th, m);
2129 TCP_PROBE5(accept__refused, NULL, NULL, m, tp, nth);
2131 if ((tp != NULL) && (tp->t_logstate != TCP_LOG_STATE_OFF)) {
2132 if (INP_WLOCKED(inp)) {
2133 union tcp_log_stackspecific log;
2136 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2137 log.u_bbr.inhpts = inp->inp_in_hpts;
2138 log.u_bbr.flex8 = 4;
2139 log.u_bbr.pkts_out = tp->t_maxseg;
2140 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2141 log.u_bbr.delivered = 0;
2142 lgb = tcp_log_event_(tp, nth, NULL, NULL, TCP_LOG_OUT,
2143 ERRNO_UNK, 0, &log, false, NULL, NULL, 0, &tv);
2146 * We can not log the packet, since we only own the
2147 * read lock, but a write lock is needed. The read lock
2148 * is not upgraded to a write lock, since only getting
2149 * the read lock was done intentionally to improve the
2150 * handling of SYN flooding attacks.
2151 * This happens only for pure SYN segments received in
2152 * the initial CLOSED state, or received in a more
2153 * advanced state than listen and the UDP encapsulation
2154 * port is unexpected.
2155 * The incoming SYN segments do not really belong to
2156 * the TCP connection and the handling does not change
2157 * the state of the TCP connection. Therefore, the
2158 * sending of the RST segments is not logged. Please
2159 * note that also the incoming SYN segments are not
2162 * The following code ensures that the above description
2163 * is and stays correct.
2165 KASSERT((thflags & (TH_ACK|TH_SYN)) == TH_SYN &&
2166 (tp->t_state == TCPS_CLOSED ||
2167 (tp->t_state > TCPS_LISTEN && tp->t_port != port)),
2168 ("%s: Logging of TCP segment with flags 0x%b and "
2169 "UDP encapsulation port %u skipped in state %s",
2170 __func__, thflags, PRINT_TH_FLAGS,
2171 ntohs(port), tcpstates[tp->t_state]));
2176 TCPSTAT_INC(tcps_sndacks);
2177 else if (flags & (TH_SYN|TH_FIN|TH_RST))
2178 TCPSTAT_INC(tcps_sndctrl);
2179 TCPSTAT_INC(tcps_sndtotal);
2183 TCP_PROBE5(send, NULL, tp, ip6, tp, nth);
2184 output_ret = ip6_output(m, NULL, NULL, 0, NULL, NULL, inp);
2187 #if defined(INET) && defined(INET6)
2192 TCP_PROBE5(send, NULL, tp, ip, tp, nth);
2193 output_ret = ip_output(m, NULL, NULL, 0, NULL, inp);
2197 lgb->tlb_errno = output_ret;
2201 * Create a new TCP control block, making an
2202 * empty reassembly queue and hooking it to the argument
2203 * protocol control block. The `inp' parameter must have
2204 * come from the zone allocator set up in tcp_init().
2207 tcp_newtcpcb(struct inpcb *inp)
2209 struct tcpcb_mem *tm;
2212 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2215 tm = uma_zalloc(V_tcpcb_zone, M_NOWAIT | M_ZERO);
2220 /* Initialise cc_var struct for this tcpcb. */
2222 tp->ccv->type = IPPROTO_TCP;
2223 tp->ccv->ccvc.tcp = tp;
2224 rw_rlock(&tcp_function_lock);
2225 tp->t_fb = tcp_func_set_ptr;
2226 refcount_acquire(&tp->t_fb->tfb_refcnt);
2227 rw_runlock(&tcp_function_lock);
2229 * Use the current system default CC algorithm.
2231 cc_attach(tp, CC_DEFAULT_ALGO());
2234 * The tcpcb will hold a reference on its inpcb until tcp_discardcb()
2237 in_pcbref(inp); /* Reference for tcpcb */
2240 if (CC_ALGO(tp)->cb_init != NULL)
2241 if (CC_ALGO(tp)->cb_init(tp->ccv, NULL) > 0) {
2243 if (tp->t_fb->tfb_tcp_fb_fini)
2244 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2245 in_pcbrele_wlocked(inp);
2246 refcount_release(&tp->t_fb->tfb_refcnt);
2247 uma_zfree(V_tcpcb_zone, tm);
2253 if (khelp_init_osd(HELPER_CLASS_TCP, tp->osd)) {
2254 if (tp->t_fb->tfb_tcp_fb_fini)
2255 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2256 in_pcbrele_wlocked(inp);
2257 refcount_release(&tp->t_fb->tfb_refcnt);
2258 uma_zfree(V_tcpcb_zone, tm);
2263 tp->t_timers = &tm->tt;
2264 TAILQ_INIT(&tp->t_segq);
2267 isipv6 ? V_tcp_v6mssdflt :
2271 /* Set up our timeouts. */
2272 callout_init(&tp->t_timers->tt_rexmt, 1);
2273 callout_init(&tp->t_timers->tt_persist, 1);
2274 callout_init(&tp->t_timers->tt_keep, 1);
2275 callout_init(&tp->t_timers->tt_2msl, 1);
2276 callout_init(&tp->t_timers->tt_delack, 1);
2278 switch (V_tcp_do_rfc1323) {
2283 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
2286 tp->t_flags = TF_REQ_SCALE;
2289 tp->t_flags = TF_REQ_TSTMP;
2293 tp->t_flags |= TF_SACK_PERMIT;
2294 TAILQ_INIT(&tp->snd_holes);
2297 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
2298 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives
2299 * reasonable initial retransmit time.
2301 tp->t_srtt = TCPTV_SRTTBASE;
2302 tp->t_rttvar = ((tcp_rexmit_initial - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
2303 tp->t_rttmin = tcp_rexmit_min;
2304 tp->t_rxtcur = tcp_rexmit_initial;
2305 tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2306 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2307 tp->t_rcvtime = ticks;
2309 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
2310 * because the socket may be bound to an IPv6 wildcard address,
2311 * which may match an IPv4-mapped IPv6 address.
2313 inp->inp_ip_ttl = V_ip_defttl;
2317 * If using hpts lets drop a random number in so
2318 * not all new connections fall on the same CPU.
2320 inp->inp_hpts_cpu = hpts_random_cpu(inp);
2324 * Init the TCP PCAP queues.
2326 tcp_pcap_tcpcb_init(tp);
2329 /* Initialize the per-TCPCB log data. */
2330 tcp_log_tcpcbinit(tp);
2332 tp->t_pacing_rate = -1;
2333 if (tp->t_fb->tfb_tcp_fb_init) {
2334 if ((*tp->t_fb->tfb_tcp_fb_init)(tp)) {
2335 refcount_release(&tp->t_fb->tfb_refcnt);
2336 in_pcbrele_wlocked(inp);
2337 uma_zfree(V_tcpcb_zone, tm);
2342 if (V_tcp_perconn_stats_enable == 1)
2343 tp->t_stats = stats_blob_alloc(V_tcp_perconn_stats_dflt_tpl, 0);
2346 tp->t_flags |= TF_LRD;
2347 return (tp); /* XXX */
2351 * Drop a TCP connection, reporting
2352 * the specified error. If connection is synchronized,
2353 * then send a RST to peer.
2356 tcp_drop(struct tcpcb *tp, int errno)
2358 struct socket *so = tptosocket(tp);
2361 INP_WLOCK_ASSERT(tptoinpcb(tp));
2363 if (TCPS_HAVERCVDSYN(tp->t_state)) {
2364 tcp_state_change(tp, TCPS_CLOSED);
2365 /* Don't use tcp_output() here due to possible recursion. */
2366 (void)tcp_output_nodrop(tp);
2367 TCPSTAT_INC(tcps_drops);
2369 TCPSTAT_INC(tcps_conndrops);
2370 if (errno == ETIMEDOUT && tp->t_softerror)
2371 errno = tp->t_softerror;
2372 so->so_error = errno;
2373 return (tcp_close(tp));
2377 tcp_discardcb(struct tcpcb *tp)
2379 struct inpcb *inp = tptoinpcb(tp);
2381 INP_WLOCK_ASSERT(inp);
2384 * Make sure that all of our timers are stopped before we delete the
2387 * If stopping a timer fails, we schedule a discard function in same
2388 * callout, and the last discard function called will take care of
2389 * deleting the tcpcb.
2391 tp->t_timers->tt_draincnt = 0;
2392 tcp_timer_stop(tp, TT_REXMT);
2393 tcp_timer_stop(tp, TT_PERSIST);
2394 tcp_timer_stop(tp, TT_KEEP);
2395 tcp_timer_stop(tp, TT_2MSL);
2396 tcp_timer_stop(tp, TT_DELACK);
2397 if (tp->t_fb->tfb_tcp_timer_stop_all) {
2399 * Call the stop-all function of the methods,
2400 * this function should call the tcp_timer_stop()
2401 * method with each of the function specific timeouts.
2402 * That stop will be called via the tfb_tcp_timer_stop()
2403 * which should use the async drain function of the
2404 * callout system (see tcp_var.h).
2406 tp->t_fb->tfb_tcp_timer_stop_all(tp);
2409 /* free the reassembly queue, if any */
2410 tcp_reass_flush(tp);
2413 /* Disconnect offload device, if any. */
2414 if (tp->t_flags & TF_TOE)
2415 tcp_offload_detach(tp);
2418 tcp_free_sackholes(tp);
2421 /* Free the TCP PCAP queues. */
2422 tcp_pcap_drain(&(tp->t_inpkts));
2423 tcp_pcap_drain(&(tp->t_outpkts));
2426 /* Allow the CC algorithm to clean up after itself. */
2427 if (CC_ALGO(tp)->cb_destroy != NULL)
2428 CC_ALGO(tp)->cb_destroy(tp->ccv);
2430 /* Detach from the CC algorithm */
2434 khelp_destroy_osd(tp->osd);
2437 stats_blob_destroy(tp->t_stats);
2441 inp->inp_ppcb = NULL;
2442 if (tp->t_timers->tt_draincnt == 0) {
2443 bool released __diagused;
2445 released = tcp_freecb(tp);
2446 KASSERT(!released, ("%s: inp %p should not have been released "
2447 "here", __func__, inp));
2452 tcp_freecb(struct tcpcb *tp)
2454 struct inpcb *inp = tptoinpcb(tp);
2455 struct socket *so = tptosocket(tp);
2457 bool isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2460 INP_WLOCK_ASSERT(inp);
2461 MPASS(tp->t_timers->tt_draincnt == 0);
2463 /* We own the last reference on tcpcb, let's free it. */
2465 tcp_log_tcpcbfini(tp);
2467 TCPSTATES_DEC(tp->t_state);
2468 if (tp->t_fb->tfb_tcp_fb_fini)
2469 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2472 * If we got enough samples through the srtt filter,
2473 * save the rtt and rttvar in the routing entry.
2474 * 'Enough' is arbitrarily defined as 4 rtt samples.
2475 * 4 samples is enough for the srtt filter to converge
2476 * to within enough % of the correct value; fewer samples
2477 * and we could save a bogus rtt. The danger is not high
2478 * as tcp quickly recovers from everything.
2479 * XXX: Works very well but needs some more statistics!
2481 * XXXRRS: Updating must be after the stack fini() since
2482 * that may be converting some internal representation of
2483 * say srtt etc into the general one used by other stacks.
2484 * Lets also at least protect against the so being NULL
2485 * as RW stated below.
2487 if ((tp->t_rttupdated >= 4) && (so != NULL)) {
2488 struct hc_metrics_lite metrics;
2491 bzero(&metrics, sizeof(metrics));
2493 * Update the ssthresh always when the conditions below
2494 * are satisfied. This gives us better new start value
2495 * for the congestion avoidance for new connections.
2496 * ssthresh is only set if packet loss occurred on a session.
2498 * XXXRW: 'so' may be NULL here, and/or socket buffer may be
2499 * being torn down. Ideally this code would not use 'so'.
2501 ssthresh = tp->snd_ssthresh;
2502 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
2504 * convert the limit from user data bytes to
2505 * packets then to packet data bytes.
2507 ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
2510 ssthresh *= (tp->t_maxseg +
2512 (isipv6 ? sizeof (struct ip6_hdr) +
2513 sizeof (struct tcphdr) :
2515 sizeof (struct tcpiphdr)
2522 metrics.rmx_ssthresh = ssthresh;
2524 metrics.rmx_rtt = tp->t_srtt;
2525 metrics.rmx_rttvar = tp->t_rttvar;
2526 metrics.rmx_cwnd = tp->snd_cwnd;
2527 metrics.rmx_sendpipe = 0;
2528 metrics.rmx_recvpipe = 0;
2530 tcp_hc_update(&inp->inp_inc, &metrics);
2533 refcount_release(&tp->t_fb->tfb_refcnt);
2534 uma_zfree(V_tcpcb_zone, tp);
2536 return (in_pcbrele_wlocked(inp));
2540 * Attempt to close a TCP control block, marking it as dropped, and freeing
2541 * the socket if we hold the only reference.
2544 tcp_close(struct tcpcb *tp)
2546 struct inpcb *inp = tptoinpcb(tp);
2547 struct socket *so = tptosocket(tp);
2549 INP_WLOCK_ASSERT(inp);
2552 if (tp->t_state == TCPS_LISTEN)
2553 tcp_offload_listen_stop(tp);
2556 * This releases the TFO pending counter resource for TFO listen
2557 * sockets as well as passively-created TFO sockets that transition
2558 * from SYN_RECEIVED to CLOSED.
2560 if (tp->t_tfo_pending) {
2561 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2562 tp->t_tfo_pending = NULL;
2565 tcp_hpts_remove(inp);
2568 TCPSTAT_INC(tcps_closed);
2569 if (tp->t_state != TCPS_CLOSED)
2570 tcp_state_change(tp, TCPS_CLOSED);
2571 KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
2572 soisdisconnected(so);
2573 if (inp->inp_flags & INP_SOCKREF) {
2574 inp->inp_flags &= ~INP_SOCKREF;
2583 * Notify a tcp user of an asynchronous error;
2584 * store error as soft error, but wake up user
2585 * (for now, won't do anything until can select for soft error).
2587 * Do not wake up user since there currently is no mechanism for
2588 * reporting soft errors (yet - a kqueue filter may be added).
2590 static struct inpcb *
2591 tcp_notify(struct inpcb *inp, int error)
2595 INP_WLOCK_ASSERT(inp);
2597 tp = intotcpcb(inp);
2598 KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
2601 * Ignore some errors if we are hooked up.
2602 * If connection hasn't completed, has retransmitted several times,
2603 * and receives a second error, give up now. This is better
2604 * than waiting a long time to establish a connection that
2605 * can never complete.
2607 if (tp->t_state == TCPS_ESTABLISHED &&
2608 (error == EHOSTUNREACH || error == ENETUNREACH ||
2609 error == EHOSTDOWN)) {
2610 if (inp->inp_route.ro_nh) {
2611 NH_FREE(inp->inp_route.ro_nh);
2612 inp->inp_route.ro_nh = (struct nhop_object *)NULL;
2615 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
2617 tp = tcp_drop(tp, error);
2623 tp->t_softerror = error;
2627 wakeup( &so->so_timeo);
2634 tcp_pcblist(SYSCTL_HANDLER_ARGS)
2636 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
2637 INPLOOKUP_RLOCKPCB);
2642 if (req->newptr != NULL)
2645 if (req->oldptr == NULL) {
2648 n = V_tcbinfo.ipi_count +
2649 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2650 n += imax(n / 8, 10);
2651 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb);
2655 if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
2658 bzero(&xig, sizeof(xig));
2659 xig.xig_len = sizeof xig;
2660 xig.xig_count = V_tcbinfo.ipi_count +
2661 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2662 xig.xig_gen = V_tcbinfo.ipi_gencnt;
2663 xig.xig_sogen = so_gencnt;
2664 error = SYSCTL_OUT(req, &xig, sizeof xig);
2668 error = syncache_pcblist(req);
2672 while ((inp = inp_next(&inpi)) != NULL) {
2673 if (inp->inp_gencnt <= xig.xig_gen &&
2674 cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
2677 tcp_inptoxtp(inp, &xt);
2678 error = SYSCTL_OUT(req, &xt, sizeof xt);
2689 * Give the user an updated idea of our state.
2690 * If the generation differs from what we told
2691 * her before, she knows that something happened
2692 * while we were processing this request, and it
2693 * might be necessary to retry.
2695 xig.xig_gen = V_tcbinfo.ipi_gencnt;
2696 xig.xig_sogen = so_gencnt;
2697 xig.xig_count = V_tcbinfo.ipi_count +
2698 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2699 error = SYSCTL_OUT(req, &xig, sizeof xig);
2705 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist,
2706 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
2707 NULL, 0, tcp_pcblist, "S,xtcpcb",
2708 "List of active TCP connections");
2712 tcp_getcred(SYSCTL_HANDLER_ARGS)
2715 struct sockaddr_in addrs[2];
2716 struct epoch_tracker et;
2720 error = priv_check(req->td, PRIV_NETINET_GETCRED);
2723 error = SYSCTL_IN(req, addrs, sizeof(addrs));
2726 NET_EPOCH_ENTER(et);
2727 inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
2728 addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL);
2732 error = cr_canseeinpcb(req->td->td_ucred, inp);
2734 cru2x(inp->inp_cred, &xuc);
2739 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2743 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
2744 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
2745 0, 0, tcp_getcred, "S,xucred",
2746 "Get the xucred of a TCP connection");
2751 tcp6_getcred(SYSCTL_HANDLER_ARGS)
2753 struct epoch_tracker et;
2755 struct sockaddr_in6 addrs[2];
2762 error = priv_check(req->td, PRIV_NETINET_GETCRED);
2765 error = SYSCTL_IN(req, addrs, sizeof(addrs));
2768 if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
2769 (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
2772 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
2774 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
2781 NET_EPOCH_ENTER(et);
2784 inp = in_pcblookup(&V_tcbinfo,
2785 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
2787 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
2788 addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL);
2791 inp = in6_pcblookup(&V_tcbinfo,
2792 &addrs[1].sin6_addr, addrs[1].sin6_port,
2793 &addrs[0].sin6_addr, addrs[0].sin6_port,
2794 INPLOOKUP_RLOCKPCB, NULL);
2798 error = cr_canseeinpcb(req->td->td_ucred, inp);
2800 cru2x(inp->inp_cred, &xuc);
2805 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2809 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
2810 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
2811 0, 0, tcp6_getcred, "S,xucred",
2812 "Get the xucred of a TCP6 connection");
2816 /* Path MTU to try next when a fragmentation-needed message is received. */
2818 tcp_next_pmtu(const struct icmp *icp, const struct ip *ip)
2820 int mtu = ntohs(icp->icmp_nextmtu);
2822 /* If no alternative MTU was proposed, try the next smaller one. */
2824 mtu = ip_next_mtu(ntohs(ip->ip_len), 1);
2825 if (mtu < V_tcp_minmss + sizeof(struct tcpiphdr))
2826 mtu = V_tcp_minmss + sizeof(struct tcpiphdr);
2832 tcp_ctlinput_with_port(struct icmp *icp, uint16_t port)
2838 struct inpcb *(*notify)(struct inpcb *, int);
2839 struct in_conninfo inc;
2840 tcp_seq icmp_tcp_seq;
2843 errno = icmp_errmap(icp);
2848 notify = tcp_mtudisc_notify;
2852 notify = tcp_drop_syn_sent;
2854 notify = tcp_notify;
2857 if (V_icmp_may_rst && icp->icmp_type == ICMP_TIMXCEED)
2858 notify = tcp_drop_syn_sent;
2860 notify = tcp_notify;
2863 notify = tcp_notify;
2867 th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2868 icmp_tcp_seq = th->th_seq;
2869 inp = in_pcblookup(&V_tcbinfo, ip->ip_dst, th->th_dport, ip->ip_src,
2870 th->th_sport, INPLOOKUP_WLOCKPCB, NULL);
2872 tp = intotcpcb(inp);
2874 if (tp->t_flags & TF_TOE && errno == EMSGSIZE) {
2876 * MTU discovery for offloaded connections. Let
2877 * the TOE driver verify seq# and process it.
2879 mtu = tcp_next_pmtu(icp, ip);
2880 tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu);
2884 if (tp->t_port != port)
2886 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
2887 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
2888 if (errno == EMSGSIZE) {
2890 * MTU discovery: we got a needfrag and
2891 * will potentially try a lower MTU.
2893 mtu = tcp_next_pmtu(icp, ip);
2896 * Only process the offered MTU if it
2897 * is smaller than the current one.
2899 if (mtu < tp->t_maxseg +
2900 sizeof(struct tcpiphdr)) {
2901 bzero(&inc, sizeof(inc));
2902 inc.inc_faddr = ip->ip_dst;
2904 inp->inp_inc.inc_fibnum;
2905 tcp_hc_updatemtu(&inc, mtu);
2906 inp = tcp_mtudisc(inp, mtu);
2909 inp = (*notify)(inp, errno);
2912 bzero(&inc, sizeof(inc));
2913 inc.inc_fport = th->th_dport;
2914 inc.inc_lport = th->th_sport;
2915 inc.inc_faddr = ip->ip_dst;
2916 inc.inc_laddr = ip->ip_src;
2917 syncache_unreach(&inc, icmp_tcp_seq, port);
2925 tcp_ctlinput(struct icmp *icmp)
2927 tcp_ctlinput_with_port(icmp, htons(0));
2931 tcp_ctlinput_viaudp(udp_tun_icmp_param_t param)
2933 /* Its a tunneled TCP over UDP icmp */
2934 struct icmp *icmp = param.icmp;
2935 struct ip *outer_ip, *inner_ip;
2937 struct tcphdr *th, ttemp;
2941 outer_ip = (struct ip *)((caddr_t)icmp - sizeof(struct ip));
2942 inner_ip = &icmp->icmp_ip;
2943 i_hlen = inner_ip->ip_hl << 2;
2944 o_len = ntohs(outer_ip->ip_len);
2946 (sizeof(struct ip) + 8 + i_hlen + sizeof(struct udphdr) + offsetof(struct tcphdr, th_ack))) {
2947 /* Not enough data present */
2950 /* Ok lets strip out the inner udphdr header by copying up on top of it the tcp hdr */
2951 udp = (struct udphdr *)(((caddr_t)inner_ip) + i_hlen);
2952 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
2955 port = udp->uh_dport;
2956 th = (struct tcphdr *)(udp + 1);
2957 memcpy(&ttemp, th, sizeof(struct tcphdr));
2958 memcpy(udp, &ttemp, sizeof(struct tcphdr));
2959 /* Now adjust down the size of the outer IP header */
2960 o_len -= sizeof(struct udphdr);
2961 outer_ip->ip_len = htons(o_len);
2962 /* Now call in to the normal handling code */
2963 tcp_ctlinput_with_port(icmp, port);
2969 tcp6_next_pmtu(const struct icmp6_hdr *icmp6)
2971 int mtu = ntohl(icmp6->icmp6_mtu);
2974 * If no alternative MTU was proposed, or the proposed MTU was too
2975 * small, set to the min.
2977 if (mtu < IPV6_MMTU)
2978 mtu = IPV6_MMTU - 8; /* XXXNP: what is the adjustment for? */
2983 tcp6_ctlinput_with_port(struct ip6ctlparam *ip6cp, uint16_t port)
2985 struct in6_addr *dst;
2986 struct inpcb *(*notify)(struct inpcb *, int);
2987 struct ip6_hdr *ip6;
2991 struct icmp6_hdr *icmp6;
2992 struct in_conninfo inc;
2997 tcp_seq icmp_tcp_seq;
3002 icmp6 = ip6cp->ip6c_icmp6;
3004 ip6 = ip6cp->ip6c_ip6;
3005 off = ip6cp->ip6c_off;
3006 dst = &ip6cp->ip6c_finaldst->sin6_addr;
3008 errno = icmp6_errmap(icmp6);
3013 notify = tcp_mtudisc_notify;
3017 notify = tcp_drop_syn_sent;
3019 notify = tcp_notify;
3023 * There are only four ICMPs that may reset connection:
3024 * - administratively prohibited
3025 * - port unreachable
3026 * - time exceeded in transit
3027 * - unknown next header
3029 if (V_icmp_may_rst &&
3030 ((icmp6->icmp6_type == ICMP6_DST_UNREACH &&
3031 (icmp6->icmp6_code == ICMP6_DST_UNREACH_ADMIN ||
3032 icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT)) ||
3033 (icmp6->icmp6_type == ICMP6_TIME_EXCEEDED &&
3034 icmp6->icmp6_code == ICMP6_TIME_EXCEED_TRANSIT) ||
3035 (icmp6->icmp6_type == ICMP6_PARAM_PROB &&
3036 icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER)))
3037 notify = tcp_drop_syn_sent;
3039 notify = tcp_notify;
3042 notify = tcp_notify;
3045 /* Check if we can safely get the ports from the tcp hdr */
3048 (int32_t) (off + sizeof(struct tcp_ports)))) {
3051 bzero(&t_ports, sizeof(struct tcp_ports));
3052 m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports);
3053 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport,
3054 &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL);
3055 off += sizeof(struct tcp_ports);
3056 if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) {
3059 m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq);
3061 tp = intotcpcb(inp);
3063 if (tp->t_flags & TF_TOE && errno == EMSGSIZE) {
3064 /* MTU discovery for offloaded connections. */
3065 mtu = tcp6_next_pmtu(icmp6);
3066 tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu);
3070 if (tp->t_port != port)
3072 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
3073 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
3074 if (errno == EMSGSIZE) {
3077 * If we got a needfrag set the MTU
3078 * in the route to the suggested new
3079 * value (if given) and then notify.
3081 mtu = tcp6_next_pmtu(icmp6);
3083 bzero(&inc, sizeof(inc));
3084 inc.inc_fibnum = M_GETFIB(m);
3085 inc.inc_flags |= INC_ISIPV6;
3086 inc.inc6_faddr = *dst;
3087 if (in6_setscope(&inc.inc6_faddr,
3088 m->m_pkthdr.rcvif, NULL))
3091 * Only process the offered MTU if it
3092 * is smaller than the current one.
3094 if (mtu < tp->t_maxseg +
3095 sizeof (struct tcphdr) +
3096 sizeof (struct ip6_hdr)) {
3097 tcp_hc_updatemtu(&inc, mtu);
3098 tcp_mtudisc(inp, mtu);
3099 ICMP6STAT_INC(icp6s_pmtuchg);
3102 inp = (*notify)(inp, errno);
3105 bzero(&inc, sizeof(inc));
3106 inc.inc_fibnum = M_GETFIB(m);
3107 inc.inc_flags |= INC_ISIPV6;
3108 inc.inc_fport = t_ports.th_dport;
3109 inc.inc_lport = t_ports.th_sport;
3110 inc.inc6_faddr = *dst;
3111 inc.inc6_laddr = ip6->ip6_src;
3112 syncache_unreach(&inc, icmp_tcp_seq, port);
3120 tcp6_ctlinput(struct ip6ctlparam *ctl)
3122 tcp6_ctlinput_with_port(ctl, htons(0));
3126 tcp6_ctlinput_viaudp(udp_tun_icmp_param_t param)
3128 struct ip6ctlparam *ip6cp = param.ip6cp;
3133 m = m_pulldown(ip6cp->ip6c_m, ip6cp->ip6c_off, sizeof(struct udphdr), NULL);
3137 udp = mtod(m, struct udphdr *);
3138 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
3141 port = udp->uh_dport;
3142 m_adj(m, sizeof(struct udphdr));
3143 if ((m->m_flags & M_PKTHDR) == 0) {
3144 ip6cp->ip6c_m->m_pkthdr.len -= sizeof(struct udphdr);
3146 /* Now call in to the normal handling code */
3147 tcp6_ctlinput_with_port(ip6cp, port);
3153 tcp_keyed_hash(struct in_conninfo *inc, u_char *key, u_int len)
3158 KASSERT(len >= SIPHASH_KEY_LENGTH,
3159 ("%s: keylen %u too short ", __func__, len));
3160 SipHash24_Init(&ctx);
3161 SipHash_SetKey(&ctx, (uint8_t *)key);
3162 SipHash_Update(&ctx, &inc->inc_fport, sizeof(uint16_t));
3163 SipHash_Update(&ctx, &inc->inc_lport, sizeof(uint16_t));
3164 switch (inc->inc_flags & INC_ISIPV6) {
3167 SipHash_Update(&ctx, &inc->inc_faddr, sizeof(struct in_addr));
3168 SipHash_Update(&ctx, &inc->inc_laddr, sizeof(struct in_addr));
3173 SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(struct in6_addr));
3174 SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(struct in6_addr));
3178 SipHash_Final((uint8_t *)hash, &ctx);
3180 return (hash[0] ^ hash[1]);
3184 tcp_new_ts_offset(struct in_conninfo *inc)
3186 struct in_conninfo inc_store, *local_inc;
3188 if (!V_tcp_ts_offset_per_conn) {
3189 memcpy(&inc_store, inc, sizeof(struct in_conninfo));
3190 inc_store.inc_lport = 0;
3191 inc_store.inc_fport = 0;
3192 local_inc = &inc_store;
3196 return (tcp_keyed_hash(local_inc, V_ts_offset_secret,
3197 sizeof(V_ts_offset_secret)));
3201 * Following is where TCP initial sequence number generation occurs.
3203 * There are two places where we must use initial sequence numbers:
3204 * 1. In SYN-ACK packets.
3205 * 2. In SYN packets.
3207 * All ISNs for SYN-ACK packets are generated by the syncache. See
3208 * tcp_syncache.c for details.
3210 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
3211 * depends on this property. In addition, these ISNs should be
3212 * unguessable so as to prevent connection hijacking. To satisfy
3213 * the requirements of this situation, the algorithm outlined in
3214 * RFC 1948 is used, with only small modifications.
3216 * Implementation details:
3218 * Time is based off the system timer, and is corrected so that it
3219 * increases by one megabyte per second. This allows for proper
3220 * recycling on high speed LANs while still leaving over an hour
3223 * As reading the *exact* system time is too expensive to be done
3224 * whenever setting up a TCP connection, we increment the time
3225 * offset in two ways. First, a small random positive increment
3226 * is added to isn_offset for each connection that is set up.
3227 * Second, the function tcp_isn_tick fires once per clock tick
3228 * and increments isn_offset as necessary so that sequence numbers
3229 * are incremented at approximately ISN_BYTES_PER_SECOND. The
3230 * random positive increments serve only to ensure that the same
3231 * exact sequence number is never sent out twice (as could otherwise
3232 * happen when a port is recycled in less than the system tick
3235 * net.inet.tcp.isn_reseed_interval controls the number of seconds
3236 * between seeding of isn_secret. This is normally set to zero,
3237 * as reseeding should not be necessary.
3239 * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
3240 * isn_offset_old, and isn_ctx is performed using the ISN lock. In
3241 * general, this means holding an exclusive (write) lock.
3244 #define ISN_BYTES_PER_SECOND 1048576
3245 #define ISN_STATIC_INCREMENT 4096
3246 #define ISN_RANDOM_INCREMENT (4096 - 1)
3247 #define ISN_SECRET_LENGTH SIPHASH_KEY_LENGTH
3249 VNET_DEFINE_STATIC(u_char, isn_secret[ISN_SECRET_LENGTH]);
3250 VNET_DEFINE_STATIC(int, isn_last);
3251 VNET_DEFINE_STATIC(int, isn_last_reseed);
3252 VNET_DEFINE_STATIC(u_int32_t, isn_offset);
3253 VNET_DEFINE_STATIC(u_int32_t, isn_offset_old);
3255 #define V_isn_secret VNET(isn_secret)
3256 #define V_isn_last VNET(isn_last)
3257 #define V_isn_last_reseed VNET(isn_last_reseed)
3258 #define V_isn_offset VNET(isn_offset)
3259 #define V_isn_offset_old VNET(isn_offset_old)
3262 tcp_new_isn(struct in_conninfo *inc)
3265 u_int32_t projected_offset;
3268 /* Seed if this is the first use, reseed if requested. */
3269 if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) &&
3270 (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz)
3272 arc4rand(&V_isn_secret, sizeof(V_isn_secret), 0);
3273 V_isn_last_reseed = ticks;
3276 /* Compute the hash and return the ISN. */
3277 new_isn = (tcp_seq)tcp_keyed_hash(inc, V_isn_secret,
3278 sizeof(V_isn_secret));
3279 V_isn_offset += ISN_STATIC_INCREMENT +
3280 (arc4random() & ISN_RANDOM_INCREMENT);
3281 if (ticks != V_isn_last) {
3282 projected_offset = V_isn_offset_old +
3283 ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last);
3284 if (SEQ_GT(projected_offset, V_isn_offset))
3285 V_isn_offset = projected_offset;
3286 V_isn_offset_old = V_isn_offset;
3289 new_isn += V_isn_offset;
3295 * When a specific ICMP unreachable message is received and the
3296 * connection state is SYN-SENT, drop the connection. This behavior
3297 * is controlled by the icmp_may_rst sysctl.
3299 static struct inpcb *
3300 tcp_drop_syn_sent(struct inpcb *inp, int errno)
3305 INP_WLOCK_ASSERT(inp);
3307 tp = intotcpcb(inp);
3308 if (tp->t_state != TCPS_SYN_SENT)
3311 if (IS_FASTOPEN(tp->t_flags))
3312 tcp_fastopen_disable_path(tp);
3314 tp = tcp_drop(tp, errno);
3322 * When `need fragmentation' ICMP is received, update our idea of the MSS
3323 * based on the new value. Also nudge TCP to send something, since we
3324 * know the packet we just sent was dropped.
3325 * This duplicates some code in the tcp_mss() function in tcp_input.c.
3327 static struct inpcb *
3328 tcp_mtudisc_notify(struct inpcb *inp, int error)
3331 return (tcp_mtudisc(inp, -1));
3334 static struct inpcb *
3335 tcp_mtudisc(struct inpcb *inp, int mtuoffer)
3340 INP_WLOCK_ASSERT(inp);
3342 tp = intotcpcb(inp);
3343 KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
3345 tcp_mss_update(tp, -1, mtuoffer, NULL, NULL);
3347 so = inp->inp_socket;
3348 SOCKBUF_LOCK(&so->so_snd);
3349 /* If the mss is larger than the socket buffer, decrease the mss. */
3350 if (so->so_snd.sb_hiwat < tp->t_maxseg)
3351 tp->t_maxseg = so->so_snd.sb_hiwat;
3352 SOCKBUF_UNLOCK(&so->so_snd);
3354 TCPSTAT_INC(tcps_mturesent);
3356 tp->snd_nxt = tp->snd_una;
3357 tcp_free_sackholes(tp);
3358 tp->snd_recover = tp->snd_max;
3359 if (tp->t_flags & TF_SACK_PERMIT)
3360 EXIT_FASTRECOVERY(tp->t_flags);
3361 if (tp->t_fb->tfb_tcp_mtu_chg != NULL) {
3363 * Conceptually the snd_nxt setting
3364 * and freeing sack holes should
3365 * be done by the default stacks
3366 * own tfb_tcp_mtu_chg().
3368 tp->t_fb->tfb_tcp_mtu_chg(tp);
3370 if (tcp_output(tp) < 0)
3378 * Look-up the routing entry to the peer of this inpcb. If no route
3379 * is found and it cannot be allocated, then return 0. This routine
3380 * is called by TCP routines that access the rmx structure and by
3381 * tcp_mss_update to get the peer/interface MTU.
3384 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap)
3386 struct nhop_object *nh;
3388 uint32_t maxmtu = 0;
3390 KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
3392 if (inc->inc_faddr.s_addr != INADDR_ANY) {
3393 nh = fib4_lookup(inc->inc_fibnum, inc->inc_faddr, 0, NHR_NONE, 0);
3398 maxmtu = nh->nh_mtu;
3400 /* Report additional interface capabilities. */
3402 if (ifp->if_capenable & IFCAP_TSO4 &&
3403 ifp->if_hwassist & CSUM_TSO) {
3404 cap->ifcap |= CSUM_TSO;
3405 cap->tsomax = ifp->if_hw_tsomax;
3406 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3407 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3417 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap)
3419 struct nhop_object *nh;
3420 struct in6_addr dst6;
3423 uint32_t maxmtu = 0;
3425 KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
3427 if (inc->inc_flags & INC_IPV6MINMTU)
3430 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
3431 in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid);
3432 nh = fib6_lookup(inc->inc_fibnum, &dst6, scopeid, NHR_NONE, 0);
3437 maxmtu = nh->nh_mtu;
3439 /* Report additional interface capabilities. */
3441 if (ifp->if_capenable & IFCAP_TSO6 &&
3442 ifp->if_hwassist & CSUM_TSO) {
3443 cap->ifcap |= CSUM_TSO;
3444 cap->tsomax = ifp->if_hw_tsomax;
3445 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3446 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3455 * Handle setsockopt(IPV6_USE_MIN_MTU) by a TCP stack.
3457 * XXXGL: we are updating inpcb here with INC_IPV6MINMTU flag.
3458 * The right place to do that is ip6_setpktopt() that has just been
3459 * executed. By the way it just filled ip6po_minmtu for us.
3462 tcp6_use_min_mtu(struct tcpcb *tp)
3464 struct inpcb *inp = tptoinpcb(tp);
3466 INP_WLOCK_ASSERT(inp);
3468 * In case of the IPV6_USE_MIN_MTU socket
3469 * option, the INC_IPV6MINMTU flag to announce
3470 * a corresponding MSS during the initial
3471 * handshake. If the TCP connection is not in
3472 * the front states, just reduce the MSS being
3473 * used. This avoids the sending of TCP
3474 * segments which will be fragmented at the
3477 inp->inp_inc.inc_flags |= INC_IPV6MINMTU;
3478 if ((tp->t_state >= TCPS_SYN_SENT) &&
3479 (inp->inp_inc.inc_flags & INC_ISIPV6)) {
3480 struct ip6_pktopts *opt;
3482 opt = inp->in6p_outputopts;
3483 if (opt != NULL && opt->ip6po_minmtu == IP6PO_MINMTU_ALL &&
3484 tp->t_maxseg > TCP6_MSS)
3485 tp->t_maxseg = TCP6_MSS;
3491 * Calculate effective SMSS per RFC5681 definition for a given TCP
3492 * connection at its current state, taking into account SACK and etc.
3495 tcp_maxseg(const struct tcpcb *tp)
3499 if (tp->t_flags & TF_NOOPT)
3500 return (tp->t_maxseg);
3503 * Here we have a simplified code from tcp_addoptions(),
3504 * without a proper loop, and having most of paddings hardcoded.
3505 * We might make mistakes with padding here in some edge cases,
3506 * but this is harmless, since result of tcp_maxseg() is used
3507 * only in cwnd and ssthresh estimations.
3509 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3510 if (tp->t_flags & TF_RCVD_TSTMP)
3511 optlen = TCPOLEN_TSTAMP_APPA;
3514 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3515 if (tp->t_flags & TF_SIGNATURE)
3516 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3518 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) {
3519 optlen += TCPOLEN_SACKHDR;
3520 optlen += tp->rcv_numsacks * TCPOLEN_SACK;
3521 optlen = PADTCPOLEN(optlen);
3524 if (tp->t_flags & TF_REQ_TSTMP)
3525 optlen = TCPOLEN_TSTAMP_APPA;
3527 optlen = PADTCPOLEN(TCPOLEN_MAXSEG);
3528 if (tp->t_flags & TF_REQ_SCALE)
3529 optlen += PADTCPOLEN(TCPOLEN_WINDOW);
3530 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3531 if (tp->t_flags & TF_SIGNATURE)
3532 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3534 if (tp->t_flags & TF_SACK_PERMIT)
3535 optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED);
3538 optlen = min(optlen, TCP_MAXOLEN);
3539 return (tp->t_maxseg - optlen);
3544 tcp_fixed_maxseg(const struct tcpcb *tp)
3548 if (tp->t_flags & TF_NOOPT)
3549 return (tp->t_maxseg);
3552 * Here we have a simplified code from tcp_addoptions(),
3553 * without a proper loop, and having most of paddings hardcoded.
3554 * We only consider fixed options that we would send every
3555 * time I.e. SACK is not considered. This is important
3556 * for cc modules to figure out what the modulo of the
3559 #define PAD(len) ((((len) / 4) + !!((len) % 4)) * 4)
3560 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3561 if (tp->t_flags & TF_RCVD_TSTMP)
3562 optlen = TCPOLEN_TSTAMP_APPA;
3565 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3566 if (tp->t_flags & TF_SIGNATURE)
3567 optlen += PAD(TCPOLEN_SIGNATURE);
3570 if (tp->t_flags & TF_REQ_TSTMP)
3571 optlen = TCPOLEN_TSTAMP_APPA;
3573 optlen = PAD(TCPOLEN_MAXSEG);
3574 if (tp->t_flags & TF_REQ_SCALE)
3575 optlen += PAD(TCPOLEN_WINDOW);
3576 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3577 if (tp->t_flags & TF_SIGNATURE)
3578 optlen += PAD(TCPOLEN_SIGNATURE);
3580 if (tp->t_flags & TF_SACK_PERMIT)
3581 optlen += PAD(TCPOLEN_SACK_PERMITTED);
3584 optlen = min(optlen, TCP_MAXOLEN);
3585 return (tp->t_maxseg - optlen);
3591 sysctl_drop(SYSCTL_HANDLER_ARGS)
3593 /* addrs[0] is a foreign socket, addrs[1] is a local one. */
3594 struct sockaddr_storage addrs[2];
3598 struct sockaddr_in *fin = NULL, *lin = NULL;
3600 struct epoch_tracker et;
3602 struct sockaddr_in6 *fin6, *lin6;
3612 if (req->oldptr != NULL || req->oldlen != 0)
3614 if (req->newptr == NULL)
3616 if (req->newlen < sizeof(addrs))
3618 error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3622 switch (addrs[0].ss_family) {
3625 fin6 = (struct sockaddr_in6 *)&addrs[0];
3626 lin6 = (struct sockaddr_in6 *)&addrs[1];
3627 if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3628 lin6->sin6_len != sizeof(struct sockaddr_in6))
3630 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3631 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3633 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3634 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3636 fin = (struct sockaddr_in *)&addrs[0];
3637 lin = (struct sockaddr_in *)&addrs[1];
3641 error = sa6_embedscope(fin6, V_ip6_use_defzone);
3644 error = sa6_embedscope(lin6, V_ip6_use_defzone);
3651 fin = (struct sockaddr_in *)&addrs[0];
3652 lin = (struct sockaddr_in *)&addrs[1];
3653 if (fin->sin_len != sizeof(struct sockaddr_in) ||
3654 lin->sin_len != sizeof(struct sockaddr_in))
3661 NET_EPOCH_ENTER(et);
3662 switch (addrs[0].ss_family) {
3665 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3666 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3667 INPLOOKUP_WLOCKPCB, NULL);
3672 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3673 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3678 if (!SOLISTENING(inp->inp_socket)) {
3679 tp = intotcpcb(inp);
3680 tp = tcp_drop(tp, ECONNABORTED);
3691 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
3692 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3693 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_drop, "",
3694 "Drop TCP connection");
3697 tcp_sysctl_setsockopt(SYSCTL_HANDLER_ARGS)
3699 return (sysctl_setsockopt(oidp, arg1, arg2, req, &V_tcbinfo,
3700 &tcp_ctloutput_set));
3703 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, setsockopt,
3704 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3705 CTLFLAG_MPSAFE, NULL, 0, tcp_sysctl_setsockopt, "",
3706 "Set socket option for TCP endpoint");
3710 sysctl_switch_tls(SYSCTL_HANDLER_ARGS)
3712 /* addrs[0] is a foreign socket, addrs[1] is a local one. */
3713 struct sockaddr_storage addrs[2];
3716 struct sockaddr_in *fin = NULL, *lin = NULL;
3718 struct epoch_tracker et;
3720 struct sockaddr_in6 *fin6, *lin6;
3730 if (req->oldptr != NULL || req->oldlen != 0)
3732 if (req->newptr == NULL)
3734 if (req->newlen < sizeof(addrs))
3736 error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3740 switch (addrs[0].ss_family) {
3743 fin6 = (struct sockaddr_in6 *)&addrs[0];
3744 lin6 = (struct sockaddr_in6 *)&addrs[1];
3745 if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3746 lin6->sin6_len != sizeof(struct sockaddr_in6))
3748 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3749 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3751 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3752 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3754 fin = (struct sockaddr_in *)&addrs[0];
3755 lin = (struct sockaddr_in *)&addrs[1];
3759 error = sa6_embedscope(fin6, V_ip6_use_defzone);
3762 error = sa6_embedscope(lin6, V_ip6_use_defzone);
3769 fin = (struct sockaddr_in *)&addrs[0];
3770 lin = (struct sockaddr_in *)&addrs[1];
3771 if (fin->sin_len != sizeof(struct sockaddr_in) ||
3772 lin->sin_len != sizeof(struct sockaddr_in))
3779 NET_EPOCH_ENTER(et);
3780 switch (addrs[0].ss_family) {
3783 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3784 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3785 INPLOOKUP_WLOCKPCB, NULL);
3790 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3791 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3799 so = inp->inp_socket;
3801 error = ktls_set_tx_mode(so,
3802 arg2 == 0 ? TCP_TLS_MODE_SW : TCP_TLS_MODE_IFNET);
3810 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_sw_tls,
3811 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3812 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_switch_tls, "",
3813 "Switch TCP connection to SW TLS");
3814 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_ifnet_tls,
3815 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3816 CTLFLAG_NEEDGIANT, NULL, 1, sysctl_switch_tls, "",
3817 "Switch TCP connection to ifnet TLS");
3821 * Generate a standardized TCP log line for use throughout the
3822 * tcp subsystem. Memory allocation is done with M_NOWAIT to
3823 * allow use in the interrupt context.
3825 * NB: The caller MUST free(s, M_TCPLOG) the returned string.
3826 * NB: The function may return NULL if memory allocation failed.
3828 * Due to header inclusion and ordering limitations the struct ip
3829 * and ip6_hdr pointers have to be passed as void pointers.
3832 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3836 /* Is logging enabled? */
3837 if (V_tcp_log_in_vain == 0)
3840 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3844 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3848 /* Is logging enabled? */
3849 if (tcp_log_debug == 0)
3852 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3856 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3862 const struct ip *ip = (const struct ip *)ip4hdr;
3865 const struct ip6_hdr *ip6 = (const struct ip6_hdr *)ip6hdr;
3869 * The log line looks like this:
3870 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>"
3872 size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") +
3873 sizeof(PRINT_TH_FLAGS) + 1 +
3875 2 * INET6_ADDRSTRLEN;
3877 2 * INET_ADDRSTRLEN;
3880 s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT);
3884 strcat(s, "TCP: [");
3887 if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) {
3888 inet_ntoa_r(inc->inc_faddr, sp);
3890 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3892 inet_ntoa_r(inc->inc_laddr, sp);
3894 sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3897 ip6_sprintf(sp, &inc->inc6_faddr);
3899 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3901 ip6_sprintf(sp, &inc->inc6_laddr);
3903 sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3904 } else if (ip6 && th) {
3905 ip6_sprintf(sp, &ip6->ip6_src);
3907 sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3909 ip6_sprintf(sp, &ip6->ip6_dst);
3911 sprintf(sp, "]:%i", ntohs(th->th_dport));
3914 } else if (ip && th) {
3915 inet_ntoa_r(ip->ip_src, sp);
3917 sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3919 inet_ntoa_r(ip->ip_dst, sp);
3921 sprintf(sp, "]:%i", ntohs(th->th_dport));
3929 sprintf(sp, " tcpflags 0x%b", tcp_get_flags(th), PRINT_TH_FLAGS);
3930 if (*(s + size - 1) != '\0')
3931 panic("%s: string too long", __func__);
3936 * A subroutine which makes it easy to track TCP state changes with DTrace.
3937 * This function shouldn't be called for t_state initializations that don't
3938 * correspond to actual TCP state transitions.
3941 tcp_state_change(struct tcpcb *tp, int newstate)
3943 #if defined(KDTRACE_HOOKS)
3944 int pstate = tp->t_state;
3947 TCPSTATES_DEC(tp->t_state);
3948 TCPSTATES_INC(newstate);
3949 tp->t_state = newstate;
3950 TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate);
3954 * Create an external-format (``xtcpcb'') structure using the information in
3955 * the kernel-format tcpcb structure pointed to by tp. This is done to
3956 * reduce the spew of irrelevant information over this interface, to isolate
3957 * user code from changes in the kernel structure, and potentially to provide
3958 * information-hiding if we decide that some of this information should be
3959 * hidden from users.
3962 tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt)
3964 struct tcpcb *tp = intotcpcb(inp);
3967 bzero(xt, sizeof(*xt));
3968 xt->t_state = tp->t_state;
3969 xt->t_logstate = tp->t_logstate;
3970 xt->t_flags = tp->t_flags;
3971 xt->t_sndzerowin = tp->t_sndzerowin;
3972 xt->t_sndrexmitpack = tp->t_sndrexmitpack;
3973 xt->t_rcvoopack = tp->t_rcvoopack;
3974 xt->t_rcv_wnd = tp->rcv_wnd;
3975 xt->t_snd_wnd = tp->snd_wnd;
3976 xt->t_snd_cwnd = tp->snd_cwnd;
3977 xt->t_snd_ssthresh = tp->snd_ssthresh;
3978 xt->t_dsack_bytes = tp->t_dsack_bytes;
3979 xt->t_dsack_tlp_bytes = tp->t_dsack_tlp_bytes;
3980 xt->t_dsack_pack = tp->t_dsack_pack;
3981 xt->t_maxseg = tp->t_maxseg;
3982 xt->xt_ecn = (tp->t_flags2 & TF2_ECN_PERMIT) ? 1 : 0 +
3983 (tp->t_flags2 & TF2_ACE_PERMIT) ? 2 : 0;
3985 now = getsbinuptime();
3986 #define COPYTIMER(ttt) do { \
3987 if (callout_active(&tp->t_timers->ttt)) \
3988 xt->ttt = (tp->t_timers->ttt.c_time - now) / \
3993 COPYTIMER(tt_delack);
3994 COPYTIMER(tt_rexmt);
3995 COPYTIMER(tt_persist);
3999 xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz;
4001 xt->xt_encaps_port = tp->t_port;
4002 bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack,
4003 TCP_FUNCTION_NAME_LEN_MAX);
4004 bcopy(CC_ALGO(tp)->name, xt->xt_cc, TCP_CA_NAME_MAX);
4006 (void)tcp_log_get_id(tp, xt->xt_logid);
4009 xt->xt_len = sizeof(struct xtcpcb);
4010 in_pcbtoxinpcb(inp, &xt->xt_inp);
4014 tcp_log_end_status(struct tcpcb *tp, uint8_t status)
4019 (status > TCP_EI_STATUS_MAX_VALUE) ||
4024 if (status > (sizeof(uint32_t) * 8)) {
4025 /* Should this be a KASSERT? */
4028 bit = 1U << (status - 1);
4029 if (bit & tp->t_end_info_status) {
4030 /* already logged */
4033 for (i = 0; i < TCP_END_BYTE_INFO; i++) {
4034 if (tp->t_end_info_bytes[i] == TCP_EI_EMPTY_SLOT) {
4035 tp->t_end_info_bytes[i] = status;
4036 tp->t_end_info_status |= bit;
4043 tcp_can_enable_pacing(void)
4046 if ((tcp_pacing_limit == -1) ||
4047 (tcp_pacing_limit > number_of_tcp_connections_pacing)) {
4048 atomic_fetchadd_int(&number_of_tcp_connections_pacing, 1);
4049 shadow_num_connections = number_of_tcp_connections_pacing;
4056 static uint8_t tcp_pacing_warning = 0;
4059 tcp_decrement_paced_conn(void)
4063 ret = atomic_fetchadd_int(&number_of_tcp_connections_pacing, -1);
4064 shadow_num_connections = number_of_tcp_connections_pacing;
4065 KASSERT(ret != 0, ("tcp_paced_connection_exits -1 would cause wrap?"));
4067 if (tcp_pacing_limit != -1) {
4068 printf("Warning all pacing is now disabled, count decrements invalidly!\n");
4069 tcp_pacing_limit = 0;
4070 } else if (tcp_pacing_warning == 0) {
4071 printf("Warning pacing count is invalid, invalid decrement\n");
4072 tcp_pacing_warning = 1;