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
32 #include <sys/cdefs.h>
34 #include "opt_inet6.h"
35 #include "opt_ipsec.h"
36 #include "opt_kern_tls.h"
38 #include <sys/param.h>
39 #include <sys/systm.h>
41 #include <sys/callout.h>
42 #include <sys/eventhandler.h>
44 #include <sys/hhook.h>
46 #include <sys/kernel.h>
48 #include <sys/khelp.h>
53 #include <sys/qmath.h>
54 #include <sys/stats.h>
55 #include <sys/sysctl.h>
57 #include <sys/malloc.h>
58 #include <sys/refcount.h>
63 #include <sys/socket.h>
64 #include <sys/socketvar.h>
65 #include <sys/protosw.h>
66 #include <sys/random.h>
70 #include <net/route.h>
71 #include <net/route/nhop.h>
73 #include <net/if_var.h>
74 #include <net/if_private.h>
77 #include <netinet/in.h>
78 #include <netinet/in_fib.h>
79 #include <netinet/in_kdtrace.h>
80 #include <netinet/in_pcb.h>
81 #include <netinet/in_systm.h>
82 #include <netinet/in_var.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_icmp.h>
85 #include <netinet/ip_var.h>
87 #include <netinet/icmp6.h>
88 #include <netinet/ip6.h>
89 #include <netinet6/in6_fib.h>
90 #include <netinet6/in6_pcb.h>
91 #include <netinet6/ip6_var.h>
92 #include <netinet6/scope6_var.h>
93 #include <netinet6/nd6.h>
96 #include <netinet/tcp.h>
100 #include <netinet/tcp_fsm.h>
101 #include <netinet/tcp_seq.h>
102 #include <netinet/tcp_timer.h>
103 #include <netinet/tcp_var.h>
104 #include <netinet/tcp_ecn.h>
105 #include <netinet/tcp_log_buf.h>
106 #include <netinet/tcp_syncache.h>
107 #include <netinet/tcp_hpts.h>
108 #include <netinet/tcp_lro.h>
109 #include <netinet/cc/cc.h>
110 #include <netinet/tcpip.h>
111 #include <netinet/tcp_fastopen.h>
112 #include <netinet/tcp_accounting.h>
114 #include <netinet/tcp_pcap.h>
117 #include <netinet/tcp_offload.h>
119 #include <netinet/udp.h>
120 #include <netinet/udp_var.h>
122 #include <netinet6/tcp6_var.h>
125 #include <netipsec/ipsec_support.h>
127 #include <machine/in_cksum.h>
128 #include <crypto/siphash/siphash.h>
130 #include <security/mac/mac_framework.h>
133 static ip6proto_ctlinput_t tcp6_ctlinput;
134 static udp_tun_icmp_t tcp6_ctlinput_viaudp;
137 VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS;
139 VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS;
142 #ifdef TCP_SAD_DETECTION
143 /* Sack attack detection thresholds and such */
144 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, sack_attack,
145 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
146 "Sack Attack detection thresholds");
147 int32_t tcp_force_detection = 0;
148 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, force_detection,
150 &tcp_force_detection, 0,
151 "Do we force detection even if the INP has it off?");
152 int32_t tcp_sad_limit = 10000;
153 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, limit,
155 &tcp_sad_limit, 10000,
156 "If SaD is enabled, what is the limit to sendmap entries (0 = unlimited)?");
157 int32_t tcp_sack_to_ack_thresh = 700; /* 70 % */
158 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sack_to_ack_thresh,
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 = 450; /* 45 % (sack:2:ack -25%) (mv:ratio -15%) **/
168 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, restore_thresh,
170 &tcp_restoral_thresh, 450,
171 "Percentage of sack to ack percentage we must see below to restore(10.1 percent is 101)");
172 int32_t tcp_sad_decay_val = 800;
173 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, decay_per,
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_sad_pacing_interval = 2000;
183 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sad_pacing_int,
185 &tcp_sad_pacing_interval, 2000,
186 "What is the minimum pacing interval for a classified attacker?");
188 int32_t tcp_sad_low_pps = 100;
189 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sad_low_pps,
191 &tcp_sad_low_pps, 100,
192 "What is the input pps that below which we do not decay?");
194 uint32_t tcp_ack_war_time_window = 1000;
195 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_timewindow,
197 &tcp_ack_war_time_window, 1000,
198 "If the tcp_stack does ack-war prevention how many milliseconds are in its time window?");
199 uint32_t tcp_ack_war_cnt = 5;
200 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_cnt,
203 "If the tcp_stack does ack-war prevention how many acks can be sent in its time window?");
205 struct rwlock tcp_function_lock;
208 sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS)
213 error = sysctl_handle_int(oidp, &new, 0, req);
214 if (error == 0 && req->newptr) {
215 if (new < TCP_MINMSS)
223 SYSCTL_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt,
224 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
225 &VNET_NAME(tcp_mssdflt), 0, &sysctl_net_inet_tcp_mss_check, "I",
226 "Default TCP Maximum Segment Size");
230 sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS)
234 new = V_tcp_v6mssdflt;
235 error = sysctl_handle_int(oidp, &new, 0, req);
236 if (error == 0 && req->newptr) {
237 if (new < TCP_MINMSS)
240 V_tcp_v6mssdflt = new;
245 SYSCTL_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
246 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
247 &VNET_NAME(tcp_v6mssdflt), 0, &sysctl_net_inet_tcp_mss_v6_check, "I",
248 "Default TCP Maximum Segment Size for IPv6");
252 * Minimum MSS we accept and use. This prevents DoS attacks where
253 * we are forced to a ridiculous low MSS like 20 and send hundreds
254 * of packets instead of one. The effect scales with the available
255 * bandwidth and quickly saturates the CPU and network interface
256 * with packet generation and sending. Set to zero to disable MINMSS
257 * checking. This setting prevents us from sending too small packets.
259 VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS;
260 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_VNET | CTLFLAG_RW,
261 &VNET_NAME(tcp_minmss), 0,
262 "Minimum TCP Maximum Segment Size");
264 VNET_DEFINE(int, tcp_do_rfc1323) = 1;
265 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_VNET | CTLFLAG_RW,
266 &VNET_NAME(tcp_do_rfc1323), 0,
267 "Enable rfc1323 (high performance TCP) extensions");
270 * As of June 2021, several TCP stacks violate RFC 7323 from September 2014.
271 * Some stacks negotiate TS, but never send them after connection setup. Some
272 * stacks negotiate TS, but don't send them when sending keep-alive segments.
273 * These include modern widely deployed TCP stacks.
274 * Therefore tolerating violations for now...
276 VNET_DEFINE(int, tcp_tolerate_missing_ts) = 1;
277 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tolerate_missing_ts, CTLFLAG_VNET | CTLFLAG_RW,
278 &VNET_NAME(tcp_tolerate_missing_ts), 0,
279 "Tolerate missing TCP timestamps");
281 VNET_DEFINE(int, tcp_ts_offset_per_conn) = 1;
282 SYSCTL_INT(_net_inet_tcp, OID_AUTO, ts_offset_per_conn, CTLFLAG_VNET | CTLFLAG_RW,
283 &VNET_NAME(tcp_ts_offset_per_conn), 0,
284 "Initialize TCP timestamps per connection instead of per host pair");
286 /* How many connections are pacing */
287 static volatile uint32_t number_of_tcp_connections_pacing = 0;
288 static uint32_t shadow_num_connections = 0;
289 static counter_u64_t tcp_pacing_failures;
291 static int tcp_pacing_limit = 10000;
292 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pacing_limit, CTLFLAG_RW,
293 &tcp_pacing_limit, 1000,
294 "If the TCP stack does pacing, is there a limit (-1 = no, 0 = no pacing N = number of connections)");
296 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pacing_count, CTLFLAG_RD,
297 &shadow_num_connections, 0, "Number of TCP connections being paced");
299 SYSCTL_COUNTER_U64(_net_inet_tcp, OID_AUTO, pacing_failures, CTLFLAG_RD,
300 &tcp_pacing_failures, "Number of times we failed to enable pacing to avoid exceeding the limit");
302 static int tcp_log_debug = 0;
303 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW,
304 &tcp_log_debug, 0, "Log errors caused by incoming TCP segments");
307 * Target size of TCP PCB hash tables. Must be a power of two.
309 * Note that this can be overridden by the kernel environment
310 * variable net.inet.tcp.tcbhashsize
313 #define TCBHASHSIZE 0
315 static int tcp_tcbhashsize = TCBHASHSIZE;
316 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN,
317 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
319 static int do_tcpdrain = 1;
320 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
321 "Enable tcp_drain routine for extra help when low on mbufs");
323 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD,
324 &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs");
326 VNET_DEFINE_STATIC(int, icmp_may_rst) = 1;
327 #define V_icmp_may_rst VNET(icmp_may_rst)
328 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW,
329 &VNET_NAME(icmp_may_rst), 0,
330 "Certain ICMP unreachable messages may abort connections in SYN_SENT");
332 VNET_DEFINE_STATIC(int, tcp_isn_reseed_interval) = 0;
333 #define V_tcp_isn_reseed_interval VNET(tcp_isn_reseed_interval)
334 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW,
335 &VNET_NAME(tcp_isn_reseed_interval), 0,
336 "Seconds between reseeding of ISN secret");
338 static int tcp_soreceive_stream;
339 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN,
340 &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets");
342 VNET_DEFINE(uma_zone_t, sack_hole_zone);
343 #define V_sack_hole_zone VNET(sack_hole_zone)
344 VNET_DEFINE(uint32_t, tcp_map_entries_limit) = 0; /* unlimited */
346 sysctl_net_inet_tcp_map_limit_check(SYSCTL_HANDLER_ARGS)
351 new = V_tcp_map_entries_limit;
352 error = sysctl_handle_int(oidp, &new, 0, req);
353 if (error == 0 && req->newptr) {
354 /* only allow "0" and value > minimum */
355 if (new > 0 && new < TCP_MIN_MAP_ENTRIES_LIMIT)
358 V_tcp_map_entries_limit = new;
362 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, map_limit,
363 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
364 &VNET_NAME(tcp_map_entries_limit), 0,
365 &sysctl_net_inet_tcp_map_limit_check, "IU",
366 "Total sendmap entries limit");
368 VNET_DEFINE(uint32_t, tcp_map_split_limit) = 0; /* unlimited */
369 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, split_limit, CTLFLAG_VNET | CTLFLAG_RW,
370 &VNET_NAME(tcp_map_split_limit), 0,
371 "Total sendmap split entries limit");
374 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]);
377 #define TS_OFFSET_SECRET_LENGTH SIPHASH_KEY_LENGTH
378 VNET_DEFINE_STATIC(u_char, ts_offset_secret[TS_OFFSET_SECRET_LENGTH]);
379 #define V_ts_offset_secret VNET(ts_offset_secret)
381 static int tcp_default_fb_init(struct tcpcb *tp, void **ptr);
382 static void tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged);
383 static int tcp_default_handoff_ok(struct tcpcb *tp);
384 static struct inpcb *tcp_notify(struct inpcb *, int);
385 static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int);
386 static struct inpcb *tcp_mtudisc(struct inpcb *, int);
387 static struct inpcb *tcp_drop_syn_sent(struct inpcb *, int);
388 static char * tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th,
389 const void *ip4hdr, const void *ip6hdr);
390 static void tcp_default_switch_failed(struct tcpcb *tp);
391 static ipproto_ctlinput_t tcp_ctlinput;
392 static udp_tun_icmp_t tcp_ctlinput_viaudp;
394 static struct tcp_function_block tcp_def_funcblk = {
395 .tfb_tcp_block_name = "freebsd",
396 .tfb_tcp_output = tcp_default_output,
397 .tfb_tcp_do_segment = tcp_do_segment,
398 .tfb_tcp_ctloutput = tcp_default_ctloutput,
399 .tfb_tcp_handoff_ok = tcp_default_handoff_ok,
400 .tfb_tcp_fb_init = tcp_default_fb_init,
401 .tfb_tcp_fb_fini = tcp_default_fb_fini,
402 .tfb_switch_failed = tcp_default_switch_failed,
405 static int tcp_fb_cnt = 0;
406 struct tcp_funchead t_functions;
407 VNET_DEFINE_STATIC(struct tcp_function_block *, tcp_func_set_ptr) = &tcp_def_funcblk;
408 #define V_tcp_func_set_ptr VNET(tcp_func_set_ptr)
411 tcp_record_dsack(struct tcpcb *tp, tcp_seq start, tcp_seq end, int tlp)
413 TCPSTAT_INC(tcps_dsack_count);
416 if (SEQ_GT(end, start)) {
417 tp->t_dsack_bytes += (end - start);
418 TCPSTAT_ADD(tcps_dsack_bytes, (end - start));
420 tp->t_dsack_tlp_bytes += (start - end);
421 TCPSTAT_ADD(tcps_dsack_bytes, (start - end));
424 if (SEQ_GT(end, start)) {
425 tp->t_dsack_bytes += (end - start);
426 TCPSTAT_ADD(tcps_dsack_tlp_bytes, (end - start));
428 tp->t_dsack_tlp_bytes += (start - end);
429 TCPSTAT_ADD(tcps_dsack_tlp_bytes, (start - end));
434 static struct tcp_function_block *
435 find_tcp_functions_locked(struct tcp_function_set *fs)
437 struct tcp_function *f;
438 struct tcp_function_block *blk=NULL;
440 TAILQ_FOREACH(f, &t_functions, tf_next) {
441 if (strcmp(f->tf_name, fs->function_set_name) == 0) {
449 static struct tcp_function_block *
450 find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s)
452 struct tcp_function_block *rblk=NULL;
453 struct tcp_function *f;
455 TAILQ_FOREACH(f, &t_functions, tf_next) {
456 if (f->tf_fb == blk) {
467 struct tcp_function_block *
468 find_and_ref_tcp_functions(struct tcp_function_set *fs)
470 struct tcp_function_block *blk;
472 rw_rlock(&tcp_function_lock);
473 blk = find_tcp_functions_locked(fs);
475 refcount_acquire(&blk->tfb_refcnt);
476 rw_runlock(&tcp_function_lock);
480 struct tcp_function_block *
481 find_and_ref_tcp_fb(struct tcp_function_block *blk)
483 struct tcp_function_block *rblk;
485 rw_rlock(&tcp_function_lock);
486 rblk = find_tcp_fb_locked(blk, NULL);
488 refcount_acquire(&rblk->tfb_refcnt);
489 rw_runlock(&tcp_function_lock);
493 /* Find a matching alias for the given tcp_function_block. */
495 find_tcp_function_alias(struct tcp_function_block *blk,
496 struct tcp_function_set *fs)
498 struct tcp_function *f;
502 rw_rlock(&tcp_function_lock);
503 TAILQ_FOREACH(f, &t_functions, tf_next) {
504 if ((f->tf_fb == blk) &&
505 (strncmp(f->tf_name, blk->tfb_tcp_block_name,
506 TCP_FUNCTION_NAME_LEN_MAX) != 0)) {
507 /* Matching function block with different name. */
508 strncpy(fs->function_set_name, f->tf_name,
509 TCP_FUNCTION_NAME_LEN_MAX);
514 /* Null terminate the string appropriately. */
516 fs->function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
518 fs->function_set_name[0] = '\0';
520 rw_runlock(&tcp_function_lock);
524 static struct tcp_function_block *
525 find_and_ref_tcp_default_fb(void)
527 struct tcp_function_block *rblk;
529 rw_rlock(&tcp_function_lock);
530 rblk = V_tcp_func_set_ptr;
531 refcount_acquire(&rblk->tfb_refcnt);
532 rw_runlock(&tcp_function_lock);
537 tcp_switch_back_to_default(struct tcpcb *tp)
539 struct tcp_function_block *tfb;
542 KASSERT(tp->t_fb != &tcp_def_funcblk,
543 ("%s: called by the built-in default stack", __func__));
546 * Now, we'll find a new function block to use.
547 * Start by trying the current user-selected
548 * default, unless this stack is the user-selected
551 tfb = find_and_ref_tcp_default_fb();
552 if (tfb == tp->t_fb) {
553 refcount_release(&tfb->tfb_refcnt);
556 /* Does the stack accept this connection? */
557 if (tfb != NULL && tfb->tfb_tcp_handoff_ok != NULL &&
558 (*tfb->tfb_tcp_handoff_ok)(tp)) {
559 refcount_release(&tfb->tfb_refcnt);
562 /* Try to use that stack. */
564 /* Initialize the new stack. If it succeeds, we are done. */
565 if (tfb->tfb_tcp_fb_init == NULL ||
566 (*tfb->tfb_tcp_fb_init)(tp, &ptr) == 0) {
567 /* Release the old stack */
568 if (tp->t_fb->tfb_tcp_fb_fini != NULL)
569 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
570 refcount_release(&tp->t_fb->tfb_refcnt);
571 /* Now set in all the pointers */
577 * Initialization failed. Release the reference count on
578 * the looked up default stack.
580 refcount_release(&tfb->tfb_refcnt);
584 * If that wasn't feasible, use the built-in default
585 * stack which is not allowed to reject anyone.
587 tfb = find_and_ref_tcp_fb(&tcp_def_funcblk);
589 /* there always should be a default */
590 panic("Can't refer to tcp_def_funcblk");
592 if (tfb->tfb_tcp_handoff_ok != NULL) {
593 if ((*tfb->tfb_tcp_handoff_ok) (tp)) {
594 /* The default stack cannot say no */
595 panic("Default stack rejects a new session?");
598 if (tfb->tfb_tcp_fb_init != NULL &&
599 (*tfb->tfb_tcp_fb_init)(tp, &ptr)) {
600 /* The default stack cannot fail */
601 panic("Default stack initialization failed");
603 /* Now release the old stack */
604 if (tp->t_fb->tfb_tcp_fb_fini != NULL)
605 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
606 refcount_release(&tp->t_fb->tfb_refcnt);
607 /* And set in the pointers to the new */
613 tcp_recv_udp_tunneled_packet(struct mbuf *m, int off, struct inpcb *inp,
614 const struct sockaddr *sa, void *ctx)
625 TCPSTAT_INC(tcps_tunneled_pkts);
626 if ((m->m_flags & M_PKTHDR) == 0) {
627 /* Can't handle one that is not a pkt hdr */
628 TCPSTAT_INC(tcps_tunneled_errs);
631 thlen = sizeof(struct tcphdr);
632 if (m->m_len < off + sizeof(struct udphdr) + thlen &&
633 (m = m_pullup(m, off + sizeof(struct udphdr) + thlen)) == NULL) {
634 TCPSTAT_INC(tcps_tunneled_errs);
637 iph = mtod(m, struct ip *);
638 uh = (struct udphdr *)((caddr_t)iph + off);
639 th = (struct tcphdr *)(uh + 1);
640 thlen = th->th_off << 2;
641 if (m->m_len < off + sizeof(struct udphdr) + thlen) {
642 m = m_pullup(m, off + sizeof(struct udphdr) + thlen);
644 TCPSTAT_INC(tcps_tunneled_errs);
647 iph = mtod(m, struct ip *);
648 uh = (struct udphdr *)((caddr_t)iph + off);
649 th = (struct tcphdr *)(uh + 1);
652 m->m_pkthdr.tcp_tun_port = port = uh->uh_sport;
653 bcopy(th, uh, m->m_len - off);
654 m->m_len -= sizeof(struct udphdr);
655 m->m_pkthdr.len -= sizeof(struct udphdr);
657 * We use the same algorithm for
658 * both UDP and TCP for c-sum. So
659 * the code in tcp_input will skip
660 * the checksum. So we do nothing
661 * with the flag (m->m_pkthdr.csum_flags).
666 iph->ip_len = htons(ntohs(iph->ip_len) - sizeof(struct udphdr));
667 tcp_input_with_port(&m, &off, IPPROTO_TCP, port);
671 case IPV6_VERSION >> 4:
672 ip6 = mtod(m, struct ip6_hdr *);
673 ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) - sizeof(struct udphdr));
674 tcp6_input_with_port(&m, &off, IPPROTO_TCP, port);
689 sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS)
692 struct tcp_function_set fs;
693 struct tcp_function_block *blk;
695 memset(&fs, 0, sizeof(fs));
696 rw_rlock(&tcp_function_lock);
697 blk = find_tcp_fb_locked(V_tcp_func_set_ptr, NULL);
700 strcpy(fs.function_set_name, blk->tfb_tcp_block_name);
701 fs.pcbcnt = blk->tfb_refcnt;
703 rw_runlock(&tcp_function_lock);
704 error = sysctl_handle_string(oidp, fs.function_set_name,
705 sizeof(fs.function_set_name), req);
707 /* Check for error or no change */
708 if (error != 0 || req->newptr == NULL)
711 rw_wlock(&tcp_function_lock);
712 blk = find_tcp_functions_locked(&fs);
714 (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) {
718 V_tcp_func_set_ptr = blk;
720 rw_wunlock(&tcp_function_lock);
724 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default,
725 CTLFLAG_VNET | CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
726 NULL, 0, sysctl_net_inet_default_tcp_functions, "A",
727 "Set/get the default TCP functions");
730 sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS)
732 int error, cnt, linesz;
733 struct tcp_function *f;
739 rw_rlock(&tcp_function_lock);
740 TAILQ_FOREACH(f, &t_functions, tf_next) {
743 rw_runlock(&tcp_function_lock);
745 bufsz = (cnt+2) * ((TCP_FUNCTION_NAME_LEN_MAX * 2) + 13) + 1;
746 buffer = malloc(bufsz, M_TEMP, M_WAITOK);
751 linesz = snprintf(cp, bufsz, "\n%-32s%c %-32s %s\n", "Stack", 'D',
752 "Alias", "PCB count");
757 rw_rlock(&tcp_function_lock);
758 TAILQ_FOREACH(f, &t_functions, tf_next) {
759 alias = (f->tf_name != f->tf_fb->tfb_tcp_block_name);
760 linesz = snprintf(cp, bufsz, "%-32s%c %-32s %u\n",
761 f->tf_fb->tfb_tcp_block_name,
762 (f->tf_fb == V_tcp_func_set_ptr) ? '*' : ' ',
763 alias ? f->tf_name : "-",
764 f->tf_fb->tfb_refcnt);
765 if (linesz >= bufsz) {
773 rw_runlock(&tcp_function_lock);
775 error = sysctl_handle_string(oidp, buffer, outsz + 1, req);
776 free(buffer, M_TEMP);
780 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available,
781 CTLFLAG_VNET | CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
782 NULL, 0, sysctl_net_inet_list_available, "A",
783 "list available TCP Function sets");
785 VNET_DEFINE(int, tcp_udp_tunneling_port) = TCP_TUNNELING_PORT_DEFAULT;
788 VNET_DEFINE(struct socket *, udp4_tun_socket) = NULL;
789 #define V_udp4_tun_socket VNET(udp4_tun_socket)
792 VNET_DEFINE(struct socket *, udp6_tun_socket) = NULL;
793 #define V_udp6_tun_socket VNET(udp6_tun_socket)
796 static struct sx tcpoudp_lock;
799 tcp_over_udp_stop(void)
802 sx_assert(&tcpoudp_lock, SA_XLOCKED);
805 if (V_udp4_tun_socket != NULL) {
806 soclose(V_udp4_tun_socket);
807 V_udp4_tun_socket = NULL;
811 if (V_udp6_tun_socket != NULL) {
812 soclose(V_udp6_tun_socket);
813 V_udp6_tun_socket = NULL;
819 tcp_over_udp_start(void)
824 struct sockaddr_in sin;
827 struct sockaddr_in6 sin6;
830 sx_assert(&tcpoudp_lock, SA_XLOCKED);
832 port = V_tcp_udp_tunneling_port;
833 if (ntohs(port) == 0) {
834 /* Must have a port set */
838 if (V_udp4_tun_socket != NULL) {
839 /* Already running -- must stop first */
844 if (V_udp6_tun_socket != NULL) {
845 /* Already running -- must stop first */
850 if ((ret = socreate(PF_INET, &V_udp4_tun_socket,
851 SOCK_DGRAM, IPPROTO_UDP,
852 curthread->td_ucred, curthread))) {
856 /* Call the special UDP hook. */
857 if ((ret = udp_set_kernel_tunneling(V_udp4_tun_socket,
858 tcp_recv_udp_tunneled_packet,
864 /* Ok, we have a socket, bind it to the port. */
865 memset(&sin, 0, sizeof(struct sockaddr_in));
866 sin.sin_len = sizeof(struct sockaddr_in);
867 sin.sin_family = AF_INET;
868 sin.sin_port = htons(port);
869 if ((ret = sobind(V_udp4_tun_socket,
870 (struct sockaddr *)&sin, curthread))) {
876 if ((ret = socreate(PF_INET6, &V_udp6_tun_socket,
877 SOCK_DGRAM, IPPROTO_UDP,
878 curthread->td_ucred, curthread))) {
882 /* Call the special UDP hook. */
883 if ((ret = udp_set_kernel_tunneling(V_udp6_tun_socket,
884 tcp_recv_udp_tunneled_packet,
885 tcp6_ctlinput_viaudp,
890 /* Ok, we have a socket, bind it to the port. */
891 memset(&sin6, 0, sizeof(struct sockaddr_in6));
892 sin6.sin6_len = sizeof(struct sockaddr_in6);
893 sin6.sin6_family = AF_INET6;
894 sin6.sin6_port = htons(port);
895 if ((ret = sobind(V_udp6_tun_socket,
896 (struct sockaddr *)&sin6, curthread))) {
905 sysctl_net_inet_tcp_udp_tunneling_port_check(SYSCTL_HANDLER_ARGS)
910 old = V_tcp_udp_tunneling_port;
912 error = sysctl_handle_int(oidp, &new, 0, req);
914 (req->newptr != NULL)) {
915 if ((new < TCP_TUNNELING_PORT_MIN) ||
916 (new > TCP_TUNNELING_PORT_MAX)) {
919 sx_xlock(&tcpoudp_lock);
920 V_tcp_udp_tunneling_port = new;
925 error = tcp_over_udp_start();
927 V_tcp_udp_tunneling_port = 0;
930 sx_xunlock(&tcpoudp_lock);
936 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_port,
937 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
938 &VNET_NAME(tcp_udp_tunneling_port),
939 0, &sysctl_net_inet_tcp_udp_tunneling_port_check, "IU",
940 "Tunneling port for tcp over udp");
942 VNET_DEFINE(int, tcp_udp_tunneling_overhead) = TCP_TUNNELING_OVERHEAD_DEFAULT;
945 sysctl_net_inet_tcp_udp_tunneling_overhead_check(SYSCTL_HANDLER_ARGS)
949 new = V_tcp_udp_tunneling_overhead;
950 error = sysctl_handle_int(oidp, &new, 0, req);
951 if (error == 0 && req->newptr) {
952 if ((new < TCP_TUNNELING_OVERHEAD_MIN) ||
953 (new > TCP_TUNNELING_OVERHEAD_MAX))
956 V_tcp_udp_tunneling_overhead = new;
961 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_overhead,
962 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
963 &VNET_NAME(tcp_udp_tunneling_overhead),
964 0, &sysctl_net_inet_tcp_udp_tunneling_overhead_check, "IU",
965 "MSS reduction when using tcp over udp");
968 * Exports one (struct tcp_function_info) for each alias/name.
971 sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS)
974 struct tcp_function *f;
975 struct tcp_function_info tfi;
978 * We don't allow writes.
980 if (req->newptr != NULL)
984 * Wire the old buffer so we can directly copy the functions to
985 * user space without dropping the lock.
987 if (req->oldptr != NULL) {
988 error = sysctl_wire_old_buffer(req, 0);
994 * Walk the list and copy out matching entries. If INVARIANTS
995 * is compiled in, also walk the list to verify the length of
996 * the list matches what we have recorded.
998 rw_rlock(&tcp_function_lock);
1002 if (req->oldptr == NULL) {
1007 TAILQ_FOREACH(f, &t_functions, tf_next) {
1011 if (req->oldptr != NULL) {
1012 bzero(&tfi, sizeof(tfi));
1013 tfi.tfi_refcnt = f->tf_fb->tfb_refcnt;
1014 tfi.tfi_id = f->tf_fb->tfb_id;
1015 (void)strlcpy(tfi.tfi_alias, f->tf_name,
1016 sizeof(tfi.tfi_alias));
1017 (void)strlcpy(tfi.tfi_name,
1018 f->tf_fb->tfb_tcp_block_name, sizeof(tfi.tfi_name));
1019 error = SYSCTL_OUT(req, &tfi, sizeof(tfi));
1021 * Don't stop on error, as that is the
1022 * mechanism we use to accumulate length
1023 * information if the buffer was too short.
1027 KASSERT(cnt == tcp_fb_cnt,
1028 ("%s: cnt (%d) != tcp_fb_cnt (%d)", __func__, cnt, tcp_fb_cnt));
1032 rw_runlock(&tcp_function_lock);
1033 if (req->oldptr == NULL)
1034 error = SYSCTL_OUT(req, NULL,
1035 (cnt + 1) * sizeof(struct tcp_function_info));
1040 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, function_info,
1041 CTLTYPE_OPAQUE | CTLFLAG_SKIP | CTLFLAG_RD | CTLFLAG_MPSAFE,
1042 NULL, 0, sysctl_net_inet_list_func_info, "S,tcp_function_info",
1043 "List TCP function block name-to-ID mappings");
1046 * tfb_tcp_handoff_ok() function for the default stack.
1047 * Note that we'll basically try to take all comers.
1050 tcp_default_handoff_ok(struct tcpcb *tp)
1057 * tfb_tcp_fb_init() function for the default stack.
1059 * This handles making sure we have appropriate timers set if you are
1060 * transitioning a socket that has some amount of setup done.
1062 * The init() fuction from the default can *never* return non-zero i.e.
1063 * it is required to always succeed since it is the stack of last resort!
1066 tcp_default_fb_init(struct tcpcb *tp, void **ptr)
1068 struct socket *so = tptosocket(tp);
1071 INP_WLOCK_ASSERT(tptoinpcb(tp));
1072 /* We don't use the pointer */
1075 KASSERT(tp->t_state >= 0 && tp->t_state < TCPS_TIME_WAIT,
1076 ("%s: connection %p in unexpected state %d", __func__, tp,
1079 /* Make sure we get no interesting mbuf queuing behavior */
1080 /* All mbuf queue/ack compress flags should be off */
1081 tcp_lro_features_off(tp);
1083 /* Cancel the GP measurement in progress */
1084 tp->t_flags &= ~TF_GPUTINPROG;
1085 /* Validate the timers are not in usec, if they are convert */
1086 tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
1087 if ((tp->t_state == TCPS_SYN_SENT) ||
1088 (tp->t_state == TCPS_SYN_RECEIVED))
1089 rexmt = tcp_rexmit_initial * tcp_backoff[tp->t_rxtshift];
1091 rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
1092 if (tp->t_rxtshift == 0)
1093 tp->t_rxtcur = rexmt;
1095 TCPT_RANGESET(tp->t_rxtcur, rexmt, tp->t_rttmin, TCPTV_REXMTMAX);
1098 * Nothing to do for ESTABLISHED or LISTEN states. And, we don't
1099 * know what to do for unexpected states (which includes TIME_WAIT).
1101 if (tp->t_state <= TCPS_LISTEN || tp->t_state >= TCPS_TIME_WAIT)
1105 * Make sure some kind of transmission timer is set if there is
1108 if ((!TCPS_HAVEESTABLISHED(tp->t_state) || sbavail(&so->so_snd) ||
1109 tp->snd_una != tp->snd_max) && !(tcp_timer_active(tp, TT_REXMT) ||
1110 tcp_timer_active(tp, TT_PERSIST))) {
1112 * If the session has established and it looks like it should
1113 * be in the persist state, set the persist timer. Otherwise,
1114 * set the retransmit timer.
1116 if (TCPS_HAVEESTABLISHED(tp->t_state) && tp->snd_wnd == 0 &&
1117 (int32_t)(tp->snd_nxt - tp->snd_una) <
1118 (int32_t)sbavail(&so->so_snd))
1121 tcp_timer_activate(tp, TT_REXMT, TP_RXTCUR(tp));
1124 /* All non-embryonic sessions get a keepalive timer. */
1125 if (!tcp_timer_active(tp, TT_KEEP))
1126 tcp_timer_activate(tp, TT_KEEP,
1127 TCPS_HAVEESTABLISHED(tp->t_state) ? TP_KEEPIDLE(tp) :
1131 * Make sure critical variables are initialized
1132 * if transitioning while in Recovery.
1134 if IN_FASTRECOVERY(tp->t_flags) {
1135 if (tp->sackhint.recover_fs == 0)
1136 tp->sackhint.recover_fs = max(1,
1137 tp->snd_nxt - tp->snd_una);
1144 * tfb_tcp_fb_fini() function for the default stack.
1146 * This changes state as necessary (or prudent) to prepare for another stack
1147 * to assume responsibility for the connection.
1150 tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged)
1153 INP_WLOCK_ASSERT(tptoinpcb(tp));
1156 tcp_log_flowend(tp);
1162 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers");
1163 MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory");
1165 static struct mtx isn_mtx;
1167 #define ISN_LOCK_INIT() mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
1168 #define ISN_LOCK() mtx_lock(&isn_mtx)
1169 #define ISN_UNLOCK() mtx_unlock(&isn_mtx)
1171 INPCBSTORAGE_DEFINE(tcpcbstor, tcpcb, "tcpinp", "tcp_inpcb", "tcp", "tcphash");
1174 * Take a value and get the next power of 2 that doesn't overflow.
1175 * Used to size the tcp_inpcb hash buckets.
1178 maketcp_hashsize(int size)
1184 * get the next power of 2 higher than maxsockets.
1186 hashsize = 1 << fls(size);
1187 /* catch overflow, and just go one power of 2 smaller */
1188 if (hashsize < size) {
1189 hashsize = 1 << (fls(size) - 1);
1194 static volatile int next_tcp_stack_id = 1;
1197 * Register a TCP function block with the name provided in the names
1198 * array. (Note that this function does NOT automatically register
1199 * blk->tfb_tcp_block_name as a stack name. Therefore, you should
1200 * explicitly include blk->tfb_tcp_block_name in the list of names if
1201 * you wish to register the stack with that name.)
1203 * Either all name registrations will succeed or all will fail. If
1204 * a name registration fails, the function will update the num_names
1205 * argument to point to the array index of the name that encountered
1208 * Returns 0 on success, or an error code on failure.
1211 register_tcp_functions_as_names(struct tcp_function_block *blk, int wait,
1212 const char *names[], int *num_names)
1214 struct tcp_function *n;
1215 struct tcp_function_set fs;
1218 KASSERT(names != NULL && *num_names > 0,
1219 ("%s: Called with 0-length name list", __func__));
1220 KASSERT(names != NULL, ("%s: Called with NULL name list", __func__));
1221 KASSERT(rw_initialized(&tcp_function_lock),
1222 ("%s: called too early", __func__));
1224 if ((blk->tfb_tcp_output == NULL) ||
1225 (blk->tfb_tcp_do_segment == NULL) ||
1226 (blk->tfb_tcp_ctloutput == NULL) ||
1227 (strlen(blk->tfb_tcp_block_name) == 0)) {
1229 * These functions are required and you
1236 if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) {
1241 refcount_init(&blk->tfb_refcnt, 0);
1242 blk->tfb_id = atomic_fetchadd_int(&next_tcp_stack_id, 1);
1243 for (i = 0; i < *num_names; i++) {
1244 n = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait);
1251 (void)strlcpy(fs.function_set_name, names[i],
1252 sizeof(fs.function_set_name));
1253 rw_wlock(&tcp_function_lock);
1254 if (find_tcp_functions_locked(&fs) != NULL) {
1255 /* Duplicate name space not allowed */
1256 rw_wunlock(&tcp_function_lock);
1257 free(n, M_TCPFUNCTIONS);
1261 (void)strlcpy(n->tf_name, names[i], sizeof(n->tf_name));
1262 TAILQ_INSERT_TAIL(&t_functions, n, tf_next);
1264 rw_wunlock(&tcp_function_lock);
1270 * Deregister the names we just added. Because registration failed
1271 * for names[i], we don't need to deregister that name.
1274 rw_wlock(&tcp_function_lock);
1276 TAILQ_FOREACH(n, &t_functions, tf_next) {
1277 if (!strncmp(n->tf_name, names[i],
1278 TCP_FUNCTION_NAME_LEN_MAX)) {
1279 TAILQ_REMOVE(&t_functions, n, tf_next);
1282 free(n, M_TCPFUNCTIONS);
1287 rw_wunlock(&tcp_function_lock);
1292 * Register a TCP function block using the name provided in the name
1295 * Returns 0 on success, or an error code on failure.
1298 register_tcp_functions_as_name(struct tcp_function_block *blk, const char *name,
1301 const char *name_list[1];
1306 name_list[0] = name;
1308 name_list[0] = blk->tfb_tcp_block_name;
1309 rv = register_tcp_functions_as_names(blk, wait, name_list, &num_names);
1314 * Register a TCP function block using the name defined in
1315 * blk->tfb_tcp_block_name.
1317 * Returns 0 on success, or an error code on failure.
1320 register_tcp_functions(struct tcp_function_block *blk, int wait)
1323 return (register_tcp_functions_as_name(blk, NULL, wait));
1327 * Deregister all names associated with a function block. This
1328 * functionally removes the function block from use within the system.
1330 * When called with a true quiesce argument, mark the function block
1331 * as being removed so no more stacks will use it and determine
1332 * whether the removal would succeed.
1334 * When called with a false quiesce argument, actually attempt the
1337 * When called with a force argument, attempt to switch all TCBs to
1338 * use the default stack instead of returning EBUSY.
1340 * Returns 0 on success (or if the removal would succeed), or an error
1344 deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce,
1347 struct tcp_function *f;
1348 VNET_ITERATOR_DECL(vnet_iter);
1350 if (blk == &tcp_def_funcblk) {
1351 /* You can't un-register the default */
1354 rw_wlock(&tcp_function_lock);
1355 VNET_LIST_RLOCK_NOSLEEP();
1356 VNET_FOREACH(vnet_iter) {
1357 CURVNET_SET(vnet_iter);
1358 if (blk == V_tcp_func_set_ptr) {
1359 /* You can't free the current default in some vnet. */
1361 VNET_LIST_RUNLOCK_NOSLEEP();
1362 rw_wunlock(&tcp_function_lock);
1367 VNET_LIST_RUNLOCK_NOSLEEP();
1368 /* Mark the block so no more stacks can use it. */
1369 blk->tfb_flags |= TCP_FUNC_BEING_REMOVED;
1371 * If TCBs are still attached to the stack, attempt to switch them
1372 * to the default stack.
1374 if (force && blk->tfb_refcnt) {
1377 VNET_ITERATOR_DECL(vnet_iter);
1379 rw_wunlock(&tcp_function_lock);
1382 VNET_FOREACH(vnet_iter) {
1383 CURVNET_SET(vnet_iter);
1384 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
1385 INPLOOKUP_WLOCKPCB);
1387 while ((inp = inp_next(&inpi)) != NULL) {
1388 tp = intotcpcb(inp);
1389 if (tp == NULL || tp->t_fb != blk)
1391 tcp_switch_back_to_default(tp);
1395 VNET_LIST_RUNLOCK();
1397 rw_wlock(&tcp_function_lock);
1399 if (blk->tfb_refcnt) {
1400 /* TCBs still attached. */
1401 rw_wunlock(&tcp_function_lock);
1406 rw_wunlock(&tcp_function_lock);
1409 /* Remove any function names that map to this function block. */
1410 while (find_tcp_fb_locked(blk, &f) != NULL) {
1411 TAILQ_REMOVE(&t_functions, f, tf_next);
1414 free(f, M_TCPFUNCTIONS);
1416 rw_wunlock(&tcp_function_lock);
1423 struct epoch_tracker et;
1424 VNET_ITERATOR_DECL(vnet_iter);
1429 NET_EPOCH_ENTER(et);
1430 VNET_LIST_RLOCK_NOSLEEP();
1431 VNET_FOREACH(vnet_iter) {
1432 CURVNET_SET(vnet_iter);
1433 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
1434 INPLOOKUP_WLOCKPCB);
1439 * Walk the tcpbs, if existing, and flush the reassembly queue,
1440 * if there is one...
1441 * XXX: The "Net/3" implementation doesn't imply that the TCP
1442 * reassembly queue should be flushed, but in a situation
1443 * where we're really low on mbufs, this is potentially
1446 while ((inpb = inp_next(&inpi)) != NULL) {
1447 if ((tcpb = intotcpcb(inpb)) != NULL) {
1448 tcp_reass_flush(tcpb);
1449 tcp_clean_sackreport(tcpb);
1451 tcp_log_drain(tcpb);
1454 if (tcp_pcap_aggressive_free) {
1455 /* Free the TCP PCAP queues. */
1456 tcp_pcap_drain(&(tcpb->t_inpkts));
1457 tcp_pcap_drain(&(tcpb->t_outpkts));
1464 VNET_LIST_RUNLOCK_NOSLEEP();
1469 tcp_vnet_init(void *arg __unused)
1473 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN,
1474 &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1475 printf("%s: WARNING: unable to register helper hook\n", __func__);
1476 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT,
1477 &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1478 printf("%s: WARNING: unable to register helper hook\n", __func__);
1481 if (tcp_stats_init())
1482 printf("%s: WARNING: unable to initialise TCP stats\n",
1485 in_pcbinfo_init(&V_tcbinfo, &tcpcbstor, tcp_tcbhashsize,
1491 TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack);
1492 V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
1493 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1495 tcp_fastopen_init();
1497 COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK);
1498 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK);
1500 V_tcp_msl = TCPTV_MSL;
1502 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
1503 tcp_vnet_init, NULL);
1506 tcp_init(void *arg __unused)
1510 tcp_reass_global_init();
1512 /* XXX virtualize those below? */
1513 tcp_delacktime = TCPTV_DELACK;
1514 tcp_keepinit = TCPTV_KEEP_INIT;
1515 tcp_keepidle = TCPTV_KEEP_IDLE;
1516 tcp_keepintvl = TCPTV_KEEPINTVL;
1517 tcp_maxpersistidle = TCPTV_KEEP_IDLE;
1518 tcp_rexmit_initial = TCPTV_RTOBASE;
1519 if (tcp_rexmit_initial < 1)
1520 tcp_rexmit_initial = 1;
1521 tcp_rexmit_min = TCPTV_MIN;
1522 if (tcp_rexmit_min < 1)
1524 tcp_persmin = TCPTV_PERSMIN;
1525 tcp_persmax = TCPTV_PERSMAX;
1526 tcp_rexmit_slop = TCPTV_CPU_VAR;
1527 tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT;
1529 /* Setup the tcp function block list */
1530 TAILQ_INIT(&t_functions);
1531 rw_init(&tcp_function_lock, "tcp_func_lock");
1532 register_tcp_functions(&tcp_def_funcblk, M_WAITOK);
1533 sx_init(&tcpoudp_lock, "TCP over UDP configuration");
1535 /* Initialize the TCP logging data. */
1538 arc4rand(&V_ts_offset_secret, sizeof(V_ts_offset_secret), 0);
1540 if (tcp_soreceive_stream) {
1542 tcp_protosw.pr_soreceive = soreceive_stream;
1545 tcp6_protosw.pr_soreceive = soreceive_stream;
1550 max_protohdr_grow(sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
1552 max_protohdr_grow(sizeof(struct tcpiphdr));
1556 EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
1557 SHUTDOWN_PRI_DEFAULT);
1558 EVENTHANDLER_REGISTER(vm_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT);
1559 EVENTHANDLER_REGISTER(mbuf_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT);
1561 tcp_inp_lro_direct_queue = counter_u64_alloc(M_WAITOK);
1562 tcp_inp_lro_wokeup_queue = counter_u64_alloc(M_WAITOK);
1563 tcp_inp_lro_compressed = counter_u64_alloc(M_WAITOK);
1564 tcp_inp_lro_locks_taken = counter_u64_alloc(M_WAITOK);
1565 tcp_extra_mbuf = counter_u64_alloc(M_WAITOK);
1566 tcp_would_have_but = counter_u64_alloc(M_WAITOK);
1567 tcp_comp_total = counter_u64_alloc(M_WAITOK);
1568 tcp_uncomp_total = counter_u64_alloc(M_WAITOK);
1569 tcp_bad_csums = counter_u64_alloc(M_WAITOK);
1570 tcp_pacing_failures = counter_u64_alloc(M_WAITOK);
1575 hashsize = tcp_tcbhashsize;
1576 if (hashsize == 0) {
1578 * Auto tune the hash size based on maxsockets.
1579 * A perfect hash would have a 1:1 mapping
1580 * (hashsize = maxsockets) however it's been
1581 * suggested that O(2) average is better.
1583 hashsize = maketcp_hashsize(maxsockets / 4);
1585 * Our historical default is 512,
1586 * do not autotune lower than this.
1591 printf("%s: %s auto tuned to %d\n", __func__,
1592 "net.inet.tcp.tcbhashsize", hashsize);
1595 * We require a hashsize to be a power of two.
1596 * Previously if it was not a power of two we would just reset it
1597 * back to 512, which could be a nasty surprise if you did not notice
1598 * the error message.
1599 * Instead what we do is clip it to the closest power of two lower
1600 * than the specified hash value.
1602 if (!powerof2(hashsize)) {
1603 int oldhashsize = hashsize;
1605 hashsize = maketcp_hashsize(hashsize);
1606 /* prevent absurdly low value */
1609 printf("%s: WARNING: TCB hash size not a power of 2, "
1610 "clipped from %d to %d.\n", __func__, oldhashsize,
1613 tcp_tcbhashsize = hashsize;
1616 IPPROTO_REGISTER(IPPROTO_TCP, tcp_input, tcp_ctlinput);
1619 IP6PROTO_REGISTER(IPPROTO_TCP, tcp6_input, tcp6_ctlinput);
1622 SYSINIT(tcp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, tcp_init, NULL);
1626 tcp_destroy(void *unused __unused)
1634 * All our processes are gone, all our sockets should be cleaned
1635 * up, which means, we should be past the tcp_discardcb() calls.
1636 * Sleep to let all tcpcb timers really disappear and cleanup.
1639 INP_INFO_WLOCK(&V_tcbinfo);
1640 n = V_tcbinfo.ipi_count;
1641 INP_INFO_WUNLOCK(&V_tcbinfo);
1644 pause("tcpdes", hz / 10);
1648 in_pcbinfo_destroy(&V_tcbinfo);
1649 /* tcp_discardcb() clears the sack_holes up. */
1650 uma_zdestroy(V_sack_hole_zone);
1653 * Cannot free the zone until all tcpcbs are released as we attach
1654 * the allocations to them.
1656 tcp_fastopen_destroy();
1658 COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES);
1659 VNET_PCPUSTAT_FREE(tcpstat);
1662 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]);
1664 printf("%s: WARNING: unable to deregister helper hook "
1665 "type=%d, id=%d: error %d returned\n", __func__,
1666 HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error);
1668 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]);
1670 printf("%s: WARNING: unable to deregister helper hook "
1671 "type=%d, id=%d: error %d returned\n", __func__,
1672 HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error);
1676 VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_destroy, NULL);
1686 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
1687 * tcp_template used to store this data in mbufs, but we now recopy it out
1688 * of the tcpcb each time to conserve mbufs.
1691 tcpip_fillheaders(struct inpcb *inp, uint16_t port, void *ip_ptr, void *tcp_ptr)
1693 struct tcphdr *th = (struct tcphdr *)tcp_ptr;
1695 INP_WLOCK_ASSERT(inp);
1698 if ((inp->inp_vflag & INP_IPV6) != 0) {
1699 struct ip6_hdr *ip6;
1701 ip6 = (struct ip6_hdr *)ip_ptr;
1702 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
1703 (inp->inp_flow & IPV6_FLOWINFO_MASK);
1704 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
1705 (IPV6_VERSION & IPV6_VERSION_MASK);
1707 ip6->ip6_nxt = IPPROTO_TCP;
1709 ip6->ip6_nxt = IPPROTO_UDP;
1710 ip6->ip6_plen = htons(sizeof(struct tcphdr));
1711 ip6->ip6_src = inp->in6p_laddr;
1712 ip6->ip6_dst = inp->in6p_faddr;
1715 #if defined(INET6) && defined(INET)
1722 ip = (struct ip *)ip_ptr;
1723 ip->ip_v = IPVERSION;
1725 ip->ip_tos = inp->inp_ip_tos;
1729 ip->ip_ttl = inp->inp_ip_ttl;
1732 ip->ip_p = IPPROTO_TCP;
1734 ip->ip_p = IPPROTO_UDP;
1735 ip->ip_src = inp->inp_laddr;
1736 ip->ip_dst = inp->inp_faddr;
1739 th->th_sport = inp->inp_lport;
1740 th->th_dport = inp->inp_fport;
1744 tcp_set_flags(th, 0);
1747 th->th_sum = 0; /* in_pseudo() is called later for ipv4 */
1751 * Create template to be used to send tcp packets on a connection.
1752 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only
1753 * use for this function is in keepalives, which use tcp_respond.
1756 tcpip_maketemplate(struct inpcb *inp)
1760 t = malloc(sizeof(*t), M_TEMP, M_NOWAIT);
1763 tcpip_fillheaders(inp, 0, (void *)&t->tt_ipgen, (void *)&t->tt_t);
1768 * Send a single message to the TCP at address specified by
1769 * the given TCP/IP header. If m == NULL, then we make a copy
1770 * of the tcpiphdr at th and send directly to the addressed host.
1771 * This is used to force keep alive messages out using the TCP
1772 * template for a connection. If flags are given then we send
1773 * a message back to the TCP which originated the segment th,
1774 * and discard the mbuf containing it and any other attached mbufs.
1776 * In any case the ack and sequence number of the transmitted
1777 * segment are as specified by the parameters.
1779 * NOTE: If m != NULL, then th must point to *inside* the mbuf.
1782 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
1783 tcp_seq ack, tcp_seq seq, uint16_t flags)
1789 struct udphdr *uh = NULL;
1791 struct tcp_log_buffer *lgb;
1794 struct ip6_hdr *ip6;
1797 int optlen, tlen, win, ulen;
1803 int thflags = tcp_get_flags(th);
1806 KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
1810 isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4);
1816 inp = tptoinpcb(tp);
1817 INP_LOCK_ASSERT(inp);
1823 if (isipv6 && ip6 && (ip6->ip6_nxt == IPPROTO_UDP))
1824 port = m->m_pkthdr.tcp_tun_port;
1827 if (ip && (ip->ip_p == IPPROTO_UDP))
1828 port = m->m_pkthdr.tcp_tun_port;
1837 if (!(flags & TH_RST)) {
1838 win = sbspace(&inp->inp_socket->so_rcv);
1839 if (win > TCP_MAXWIN << tp->rcv_scale)
1840 win = TCP_MAXWIN << tp->rcv_scale;
1842 if ((tp->t_flags & TF_NOOPT) == 0)
1846 m = m_gethdr(M_NOWAIT, MT_DATA);
1849 m->m_data += max_linkhdr;
1852 bcopy((caddr_t)ip6, mtod(m, caddr_t),
1853 sizeof(struct ip6_hdr));
1854 ip6 = mtod(m, struct ip6_hdr *);
1855 nth = (struct tcphdr *)(ip6 + 1);
1857 /* Insert a UDP header */
1858 uh = (struct udphdr *)nth;
1859 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1860 uh->uh_dport = port;
1861 nth = (struct tcphdr *)(uh + 1);
1866 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
1867 ip = mtod(m, struct ip *);
1868 nth = (struct tcphdr *)(ip + 1);
1870 /* Insert a UDP header */
1871 uh = (struct udphdr *)nth;
1872 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1873 uh->uh_dport = port;
1874 nth = (struct tcphdr *)(uh + 1);
1877 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
1879 } else if ((!M_WRITABLE(m)) || (port != 0)) {
1882 /* Can't reuse 'm', allocate a new mbuf. */
1883 n = m_gethdr(M_NOWAIT, MT_DATA);
1889 if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
1895 n->m_data += max_linkhdr;
1896 /* m_len is set later */
1897 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
1900 bcopy((caddr_t)ip6, mtod(n, caddr_t),
1901 sizeof(struct ip6_hdr));
1902 ip6 = mtod(n, struct ip6_hdr *);
1903 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1904 nth = (struct tcphdr *)(ip6 + 1);
1906 /* Insert a UDP header */
1907 uh = (struct udphdr *)nth;
1908 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1909 uh->uh_dport = port;
1910 nth = (struct tcphdr *)(uh + 1);
1915 bcopy((caddr_t)ip, mtod(n, caddr_t), sizeof(struct ip));
1916 ip = mtod(n, struct ip *);
1917 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1918 nth = (struct tcphdr *)(ip + 1);
1920 /* Insert a UDP header */
1921 uh = (struct udphdr *)nth;
1922 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1923 uh->uh_dport = port;
1924 nth = (struct tcphdr *)(uh + 1);
1927 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
1928 xchg(nth->th_dport, nth->th_sport, uint16_t);
1935 * XXX MRT We inherit the FIB, which is lucky.
1939 m->m_data = (caddr_t)ipgen;
1940 /* clear any receive flags for proper bpf timestamping */
1941 m->m_flags &= ~(M_TSTMP | M_TSTMP_LRO);
1942 /* m_len is set later */
1945 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1946 nth = (struct tcphdr *)(ip6 + 1);
1950 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1951 nth = (struct tcphdr *)(ip + 1);
1955 * this is usually a case when an extension header
1956 * exists between the IPv6 header and the
1959 nth->th_sport = th->th_sport;
1960 nth->th_dport = th->th_dport;
1962 xchg(nth->th_dport, nth->th_sport, uint16_t);
1968 tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
1970 #if defined(INET) && defined(INET6)
1974 tlen = sizeof (struct tcpiphdr);
1977 tlen += sizeof (struct udphdr);
1980 KASSERT(M_TRAILINGSPACE(m) >= tlen,
1981 ("Not enough trailing space for message (m=%p, need=%d, have=%ld)",
1982 m, tlen, (long)M_TRAILINGSPACE(m)));
1987 ect = tcp_ecn_output_established(tp, &flags, 0, false);
1988 /* Make sure we have room. */
1989 if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) {
1990 m->m_next = m_get(M_NOWAIT, MT_DATA);
1992 optp = mtod(m->m_next, u_char *);
1997 optp = (u_char *) (nth + 1);
2003 if (tp->t_flags & TF_RCVD_TSTMP) {
2004 to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
2005 to.to_tsecr = tp->ts_recent;
2006 to.to_flags |= TOF_TS;
2008 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2009 /* TCP-MD5 (RFC2385). */
2010 if (tp->t_flags & TF_SIGNATURE)
2011 to.to_flags |= TOF_SIGNATURE;
2013 /* Add the options. */
2014 tlen += optlen = tcp_addoptions(&to, optp);
2016 /* Update m_len in the correct mbuf. */
2017 optm->m_len += optlen;
2023 ulen = tlen - sizeof(struct ip6_hdr);
2024 uh->uh_ulen = htons(ulen);
2026 ip6->ip6_flow = htonl(ect << IPV6_FLOWLABEL_LEN);
2027 ip6->ip6_vfc = IPV6_VERSION;
2029 ip6->ip6_nxt = IPPROTO_UDP;
2031 ip6->ip6_nxt = IPPROTO_TCP;
2032 ip6->ip6_plen = htons(tlen - sizeof(*ip6));
2035 #if defined(INET) && defined(INET6)
2041 ulen = tlen - sizeof(struct ip);
2042 uh->uh_ulen = htons(ulen);
2044 ip->ip_len = htons(tlen);
2046 ip->ip_tos = inp->inp_ip_tos & ~IPTOS_ECN_MASK;
2047 ip->ip_ttl = inp->inp_ip_ttl;
2050 ip->ip_ttl = V_ip_defttl;
2054 ip->ip_p = IPPROTO_UDP;
2056 ip->ip_p = IPPROTO_TCP;
2058 if (V_path_mtu_discovery)
2059 ip->ip_off |= htons(IP_DF);
2062 m->m_pkthdr.len = tlen;
2063 m->m_pkthdr.rcvif = NULL;
2067 * Packet is associated with a socket, so allow the
2068 * label of the response to reflect the socket label.
2070 INP_LOCK_ASSERT(inp);
2071 mac_inpcb_create_mbuf(inp, m);
2074 * Packet is not associated with a socket, so possibly
2075 * update the label in place.
2077 mac_netinet_tcp_reply(m);
2080 nth->th_seq = htonl(seq);
2081 nth->th_ack = htonl(ack);
2082 nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
2083 tcp_set_flags(nth, flags);
2084 if (tp && (flags & TH_RST)) {
2086 tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
2089 nth->th_win = htons((u_short) (win >> tp->rcv_scale));
2091 nth->th_win = htons((u_short)win);
2094 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2095 if (to.to_flags & TOF_SIGNATURE) {
2096 if (!TCPMD5_ENABLED() ||
2097 TCPMD5_OUTPUT(m, nth, to.to_signature) != 0) {
2107 m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
2108 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2109 uh->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
2112 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2113 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2114 nth->th_sum = in6_cksum_pseudo(ip6,
2115 tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0);
2117 ip6->ip6_hlim = in6_selecthlim(inp, NULL);
2120 #if defined(INET6) && defined(INET)
2126 uh->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2127 htons(ulen + IPPROTO_UDP));
2128 m->m_pkthdr.csum_flags = CSUM_UDP;
2129 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2132 m->m_pkthdr.csum_flags = CSUM_TCP;
2133 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2134 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2135 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
2139 TCP_PROBE3(debug__output, tp, th, m);
2141 TCP_PROBE5(accept__refused, NULL, NULL, m, tp, nth);
2143 if ((tp != NULL) && tcp_bblogging_on(tp)) {
2144 if (INP_WLOCKED(inp)) {
2145 union tcp_log_stackspecific log;
2148 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2149 log.u_bbr.inhpts = tcp_in_hpts(tp);
2150 log.u_bbr.flex8 = 4;
2151 log.u_bbr.pkts_out = tp->t_maxseg;
2152 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2153 log.u_bbr.delivered = 0;
2154 lgb = tcp_log_event(tp, nth, NULL, NULL, TCP_LOG_OUT,
2155 ERRNO_UNK, 0, &log, false, NULL, NULL, 0, &tv);
2158 * We can not log the packet, since we only own the
2159 * read lock, but a write lock is needed. The read lock
2160 * is not upgraded to a write lock, since only getting
2161 * the read lock was done intentionally to improve the
2162 * handling of SYN flooding attacks.
2163 * This happens only for pure SYN segments received in
2164 * the initial CLOSED state, or received in a more
2165 * advanced state than listen and the UDP encapsulation
2166 * port is unexpected.
2167 * The incoming SYN segments do not really belong to
2168 * the TCP connection and the handling does not change
2169 * the state of the TCP connection. Therefore, the
2170 * sending of the RST segments is not logged. Please
2171 * note that also the incoming SYN segments are not
2174 * The following code ensures that the above description
2175 * is and stays correct.
2177 KASSERT((thflags & (TH_ACK|TH_SYN)) == TH_SYN &&
2178 (tp->t_state == TCPS_CLOSED ||
2179 (tp->t_state > TCPS_LISTEN && tp->t_port != port)),
2180 ("%s: Logging of TCP segment with flags 0x%b and "
2181 "UDP encapsulation port %u skipped in state %s",
2182 __func__, thflags, PRINT_TH_FLAGS,
2183 ntohs(port), tcpstates[tp->t_state]));
2188 TCPSTAT_INC(tcps_sndacks);
2189 else if (flags & (TH_SYN|TH_FIN|TH_RST))
2190 TCPSTAT_INC(tcps_sndctrl);
2191 TCPSTAT_INC(tcps_sndtotal);
2195 TCP_PROBE5(send, NULL, tp, ip6, tp, nth);
2196 output_ret = ip6_output(m, inp ? inp->in6p_outputopts : NULL,
2197 NULL, 0, NULL, NULL, inp);
2200 #if defined(INET) && defined(INET6)
2205 TCP_PROBE5(send, NULL, tp, ip, tp, nth);
2206 output_ret = ip_output(m, NULL, NULL, 0, NULL, inp);
2210 lgb->tlb_errno = output_ret;
2214 * Create a new TCP control block, making an empty reassembly queue and hooking
2215 * it to the argument protocol control block. The `inp' parameter must have
2216 * come from the zone allocator set up by tcpcbstor declaration.
2219 tcp_newtcpcb(struct inpcb *inp)
2221 struct tcpcb *tp = intotcpcb(inp);
2223 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2227 * Historically allocation was done with M_ZERO. There is a lot of
2228 * code that rely on that. For now take safe approach and zero whole
2229 * tcpcb. This definitely can be optimized.
2231 bzero(&tp->t_start_zero, t_zero_size);
2233 /* Initialise cc_var struct for this tcpcb. */
2234 tp->t_ccv.type = IPPROTO_TCP;
2235 tp->t_ccv.ccvc.tcp = tp;
2236 rw_rlock(&tcp_function_lock);
2237 tp->t_fb = V_tcp_func_set_ptr;
2238 refcount_acquire(&tp->t_fb->tfb_refcnt);
2239 rw_runlock(&tcp_function_lock);
2241 * Use the current system default CC algorithm.
2243 cc_attach(tp, CC_DEFAULT_ALGO());
2245 if (CC_ALGO(tp)->cb_init != NULL)
2246 if (CC_ALGO(tp)->cb_init(&tp->t_ccv, NULL) > 0) {
2248 if (tp->t_fb->tfb_tcp_fb_fini)
2249 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2250 refcount_release(&tp->t_fb->tfb_refcnt);
2255 if (khelp_init_osd(HELPER_CLASS_TCP, &tp->t_osd)) {
2256 if (tp->t_fb->tfb_tcp_fb_fini)
2257 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2258 refcount_release(&tp->t_fb->tfb_refcnt);
2263 TAILQ_INIT(&tp->t_segq);
2264 STAILQ_INIT(&tp->t_inqueue);
2267 isipv6 ? V_tcp_v6mssdflt :
2271 /* All mbuf queue/ack compress flags should be off */
2272 tcp_lro_features_off(tp);
2274 callout_init_rw(&tp->t_callout, &inp->inp_lock, CALLOUT_RETURNUNLOCKED);
2275 for (int i = 0; i < TT_N; i++)
2276 tp->t_timers[i] = SBT_MAX;
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;
2308 /* We always start with ticks granularity */
2309 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS;
2311 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
2312 * because the socket may be bound to an IPv6 wildcard address,
2313 * which may match an IPv4-mapped IPv6 address.
2315 inp->inp_ip_ttl = V_ip_defttl;
2321 * Init the TCP PCAP queues.
2323 tcp_pcap_tcpcb_init(tp);
2326 /* Initialize the per-TCPCB log data. */
2327 tcp_log_tcpcbinit(tp);
2329 tp->t_pacing_rate = -1;
2330 if (tp->t_fb->tfb_tcp_fb_init) {
2331 if ((*tp->t_fb->tfb_tcp_fb_init)(tp, &tp->t_fb_ptr)) {
2332 refcount_release(&tp->t_fb->tfb_refcnt);
2337 if (V_tcp_perconn_stats_enable == 1)
2338 tp->t_stats = stats_blob_alloc(V_tcp_perconn_stats_dflt_tpl, 0);
2341 tp->t_flags |= TF_LRD;
2347 * Drop a TCP connection, reporting
2348 * the specified error. If connection is synchronized,
2349 * then send a RST to peer.
2352 tcp_drop(struct tcpcb *tp, int errno)
2354 struct socket *so = tptosocket(tp);
2357 INP_WLOCK_ASSERT(tptoinpcb(tp));
2359 if (TCPS_HAVERCVDSYN(tp->t_state)) {
2360 tcp_state_change(tp, TCPS_CLOSED);
2361 /* Don't use tcp_output() here due to possible recursion. */
2362 (void)tcp_output_nodrop(tp);
2363 TCPSTAT_INC(tcps_drops);
2365 TCPSTAT_INC(tcps_conndrops);
2366 if (errno == ETIMEDOUT && tp->t_softerror)
2367 errno = tp->t_softerror;
2368 so->so_error = errno;
2369 return (tcp_close(tp));
2373 tcp_discardcb(struct tcpcb *tp)
2375 struct inpcb *inp = tptoinpcb(tp);
2376 struct socket *so = tptosocket(tp);
2379 bool isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2382 INP_WLOCK_ASSERT(inp);
2385 if (tp->t_fb->tfb_tcp_timer_stop_all) {
2386 tp->t_fb->tfb_tcp_timer_stop_all(tp);
2389 /* free the reassembly queue, if any */
2390 tcp_reass_flush(tp);
2393 /* Disconnect offload device, if any. */
2394 if (tp->t_flags & TF_TOE)
2395 tcp_offload_detach(tp);
2398 tcp_free_sackholes(tp);
2401 /* Free the TCP PCAP queues. */
2402 tcp_pcap_drain(&(tp->t_inpkts));
2403 tcp_pcap_drain(&(tp->t_outpkts));
2406 /* Allow the CC algorithm to clean up after itself. */
2407 if (CC_ALGO(tp)->cb_destroy != NULL)
2408 CC_ALGO(tp)->cb_destroy(&tp->t_ccv);
2410 /* Detach from the CC algorithm */
2414 khelp_destroy_osd(&tp->t_osd);
2417 stats_blob_destroy(tp->t_stats);
2421 if ((m = STAILQ_FIRST(&tp->t_inqueue)) != NULL) {
2424 STAILQ_INIT(&tp->t_inqueue);
2425 STAILQ_FOREACH_FROM_SAFE(m, &tp->t_inqueue, m_stailqpkt, prev)
2428 TCPSTATES_DEC(tp->t_state);
2430 if (tp->t_fb->tfb_tcp_fb_fini)
2431 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2432 MPASS(!tcp_in_hpts(tp));
2434 tcp_log_tcpcbfini(tp);
2438 * If we got enough samples through the srtt filter,
2439 * save the rtt and rttvar in the routing entry.
2440 * 'Enough' is arbitrarily defined as 4 rtt samples.
2441 * 4 samples is enough for the srtt filter to converge
2442 * to within enough % of the correct value; fewer samples
2443 * and we could save a bogus rtt. The danger is not high
2444 * as tcp quickly recovers from everything.
2445 * XXX: Works very well but needs some more statistics!
2447 * XXXRRS: Updating must be after the stack fini() since
2448 * that may be converting some internal representation of
2449 * say srtt etc into the general one used by other stacks.
2450 * Lets also at least protect against the so being NULL
2451 * as RW stated below.
2453 if ((tp->t_rttupdated >= 4) && (so != NULL)) {
2454 struct hc_metrics_lite metrics;
2457 bzero(&metrics, sizeof(metrics));
2459 * Update the ssthresh always when the conditions below
2460 * are satisfied. This gives us better new start value
2461 * for the congestion avoidance for new connections.
2462 * ssthresh is only set if packet loss occurred on a session.
2464 * XXXRW: 'so' may be NULL here, and/or socket buffer may be
2465 * being torn down. Ideally this code would not use 'so'.
2467 ssthresh = tp->snd_ssthresh;
2468 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
2470 * convert the limit from user data bytes to
2471 * packets then to packet data bytes.
2473 ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
2476 ssthresh *= (tp->t_maxseg +
2478 (isipv6 ? sizeof (struct ip6_hdr) +
2479 sizeof (struct tcphdr) :
2481 sizeof (struct tcpiphdr)
2488 metrics.rmx_ssthresh = ssthresh;
2490 metrics.rmx_rtt = tp->t_srtt;
2491 metrics.rmx_rttvar = tp->t_rttvar;
2492 metrics.rmx_cwnd = tp->snd_cwnd;
2493 metrics.rmx_sendpipe = 0;
2494 metrics.rmx_recvpipe = 0;
2496 tcp_hc_update(&inp->inp_inc, &metrics);
2499 refcount_release(&tp->t_fb->tfb_refcnt);
2503 * Attempt to close a TCP control block, marking it as dropped, and freeing
2504 * the socket if we hold the only reference.
2507 tcp_close(struct tcpcb *tp)
2509 struct inpcb *inp = tptoinpcb(tp);
2510 struct socket *so = tptosocket(tp);
2512 INP_WLOCK_ASSERT(inp);
2515 if (tp->t_state == TCPS_LISTEN)
2516 tcp_offload_listen_stop(tp);
2519 * This releases the TFO pending counter resource for TFO listen
2520 * sockets as well as passively-created TFO sockets that transition
2521 * from SYN_RECEIVED to CLOSED.
2523 if (tp->t_tfo_pending) {
2524 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2525 tp->t_tfo_pending = NULL;
2528 tcp_hpts_remove(tp);
2531 TCPSTAT_INC(tcps_closed);
2532 if (tp->t_state != TCPS_CLOSED)
2533 tcp_state_change(tp, TCPS_CLOSED);
2534 KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
2535 soisdisconnected(so);
2536 if (inp->inp_flags & INP_SOCKREF) {
2537 inp->inp_flags &= ~INP_SOCKREF;
2546 * Notify a tcp user of an asynchronous error;
2547 * store error as soft error, but wake up user
2548 * (for now, won't do anything until can select for soft error).
2550 * Do not wake up user since there currently is no mechanism for
2551 * reporting soft errors (yet - a kqueue filter may be added).
2553 static struct inpcb *
2554 tcp_notify(struct inpcb *inp, int error)
2558 INP_WLOCK_ASSERT(inp);
2560 tp = intotcpcb(inp);
2561 KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
2564 * Ignore some errors if we are hooked up.
2565 * If connection hasn't completed, has retransmitted several times,
2566 * and receives a second error, give up now. This is better
2567 * than waiting a long time to establish a connection that
2568 * can never complete.
2570 if (tp->t_state == TCPS_ESTABLISHED &&
2571 (error == EHOSTUNREACH || error == ENETUNREACH ||
2572 error == EHOSTDOWN)) {
2573 if (inp->inp_route.ro_nh) {
2574 NH_FREE(inp->inp_route.ro_nh);
2575 inp->inp_route.ro_nh = (struct nhop_object *)NULL;
2578 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
2580 tp = tcp_drop(tp, error);
2586 tp->t_softerror = error;
2590 wakeup( &so->so_timeo);
2597 tcp_pcblist(SYSCTL_HANDLER_ARGS)
2599 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
2600 INPLOOKUP_RLOCKPCB);
2605 if (req->newptr != NULL)
2608 if (req->oldptr == NULL) {
2611 n = V_tcbinfo.ipi_count +
2612 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2613 n += imax(n / 8, 10);
2614 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb);
2618 if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
2621 bzero(&xig, sizeof(xig));
2622 xig.xig_len = sizeof xig;
2623 xig.xig_count = V_tcbinfo.ipi_count +
2624 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2625 xig.xig_gen = V_tcbinfo.ipi_gencnt;
2626 xig.xig_sogen = so_gencnt;
2627 error = SYSCTL_OUT(req, &xig, sizeof xig);
2631 error = syncache_pcblist(req);
2635 while ((inp = inp_next(&inpi)) != NULL) {
2636 if (inp->inp_gencnt <= xig.xig_gen &&
2637 cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
2640 tcp_inptoxtp(inp, &xt);
2641 error = SYSCTL_OUT(req, &xt, sizeof xt);
2652 * Give the user an updated idea of our state.
2653 * If the generation differs from what we told
2654 * her before, she knows that something happened
2655 * while we were processing this request, and it
2656 * might be necessary to retry.
2658 xig.xig_gen = V_tcbinfo.ipi_gencnt;
2659 xig.xig_sogen = so_gencnt;
2660 xig.xig_count = V_tcbinfo.ipi_count +
2661 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2662 error = SYSCTL_OUT(req, &xig, sizeof xig);
2668 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist,
2669 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
2670 NULL, 0, tcp_pcblist, "S,xtcpcb",
2671 "List of active TCP connections");
2675 tcp_getcred(SYSCTL_HANDLER_ARGS)
2678 struct sockaddr_in addrs[2];
2679 struct epoch_tracker et;
2683 error = priv_check(req->td, PRIV_NETINET_GETCRED);
2686 error = SYSCTL_IN(req, addrs, sizeof(addrs));
2689 NET_EPOCH_ENTER(et);
2690 inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
2691 addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL);
2695 error = cr_canseeinpcb(req->td->td_ucred, inp);
2697 cru2x(inp->inp_cred, &xuc);
2702 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2706 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
2707 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
2708 0, 0, tcp_getcred, "S,xucred",
2709 "Get the xucred of a TCP connection");
2714 tcp6_getcred(SYSCTL_HANDLER_ARGS)
2716 struct epoch_tracker et;
2718 struct sockaddr_in6 addrs[2];
2725 error = priv_check(req->td, PRIV_NETINET_GETCRED);
2728 error = SYSCTL_IN(req, addrs, sizeof(addrs));
2731 if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
2732 (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
2735 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
2737 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
2744 NET_EPOCH_ENTER(et);
2747 inp = in_pcblookup(&V_tcbinfo,
2748 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
2750 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
2751 addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL);
2754 inp = in6_pcblookup(&V_tcbinfo,
2755 &addrs[1].sin6_addr, addrs[1].sin6_port,
2756 &addrs[0].sin6_addr, addrs[0].sin6_port,
2757 INPLOOKUP_RLOCKPCB, NULL);
2761 error = cr_canseeinpcb(req->td->td_ucred, inp);
2763 cru2x(inp->inp_cred, &xuc);
2768 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2772 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
2773 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
2774 0, 0, tcp6_getcred, "S,xucred",
2775 "Get the xucred of a TCP6 connection");
2779 /* Path MTU to try next when a fragmentation-needed message is received. */
2781 tcp_next_pmtu(const struct icmp *icp, const struct ip *ip)
2783 int mtu = ntohs(icp->icmp_nextmtu);
2785 /* If no alternative MTU was proposed, try the next smaller one. */
2787 mtu = ip_next_mtu(ntohs(ip->ip_len), 1);
2788 if (mtu < V_tcp_minmss + sizeof(struct tcpiphdr))
2789 mtu = V_tcp_minmss + sizeof(struct tcpiphdr);
2795 tcp_ctlinput_with_port(struct icmp *icp, uint16_t port)
2801 struct inpcb *(*notify)(struct inpcb *, int);
2802 struct in_conninfo inc;
2803 tcp_seq icmp_tcp_seq;
2806 errno = icmp_errmap(icp);
2811 notify = tcp_mtudisc_notify;
2815 notify = tcp_drop_syn_sent;
2817 notify = tcp_notify;
2820 if (V_icmp_may_rst && icp->icmp_type == ICMP_TIMXCEED)
2821 notify = tcp_drop_syn_sent;
2823 notify = tcp_notify;
2826 notify = tcp_notify;
2830 th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2831 icmp_tcp_seq = th->th_seq;
2832 inp = in_pcblookup(&V_tcbinfo, ip->ip_dst, th->th_dport, ip->ip_src,
2833 th->th_sport, INPLOOKUP_WLOCKPCB, NULL);
2835 tp = intotcpcb(inp);
2837 if (tp->t_flags & TF_TOE && errno == EMSGSIZE) {
2839 * MTU discovery for offloaded connections. Let
2840 * the TOE driver verify seq# and process it.
2842 mtu = tcp_next_pmtu(icp, ip);
2843 tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu);
2847 if (tp->t_port != port)
2849 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
2850 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
2851 if (errno == EMSGSIZE) {
2853 * MTU discovery: we got a needfrag and
2854 * will potentially try a lower MTU.
2856 mtu = tcp_next_pmtu(icp, ip);
2859 * Only process the offered MTU if it
2860 * is smaller than the current one.
2862 if (mtu < tp->t_maxseg +
2863 sizeof(struct tcpiphdr)) {
2864 bzero(&inc, sizeof(inc));
2865 inc.inc_faddr = ip->ip_dst;
2867 inp->inp_inc.inc_fibnum;
2868 tcp_hc_updatemtu(&inc, mtu);
2869 inp = tcp_mtudisc(inp, mtu);
2872 inp = (*notify)(inp, errno);
2875 bzero(&inc, sizeof(inc));
2876 inc.inc_fport = th->th_dport;
2877 inc.inc_lport = th->th_sport;
2878 inc.inc_faddr = ip->ip_dst;
2879 inc.inc_laddr = ip->ip_src;
2880 syncache_unreach(&inc, icmp_tcp_seq, port);
2888 tcp_ctlinput(struct icmp *icmp)
2890 tcp_ctlinput_with_port(icmp, htons(0));
2894 tcp_ctlinput_viaudp(udp_tun_icmp_param_t param)
2896 /* Its a tunneled TCP over UDP icmp */
2897 struct icmp *icmp = param.icmp;
2898 struct ip *outer_ip, *inner_ip;
2900 struct tcphdr *th, ttemp;
2904 outer_ip = (struct ip *)((caddr_t)icmp - sizeof(struct ip));
2905 inner_ip = &icmp->icmp_ip;
2906 i_hlen = inner_ip->ip_hl << 2;
2907 o_len = ntohs(outer_ip->ip_len);
2909 (sizeof(struct ip) + 8 + i_hlen + sizeof(struct udphdr) + offsetof(struct tcphdr, th_ack))) {
2910 /* Not enough data present */
2913 /* Ok lets strip out the inner udphdr header by copying up on top of it the tcp hdr */
2914 udp = (struct udphdr *)(((caddr_t)inner_ip) + i_hlen);
2915 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
2918 port = udp->uh_dport;
2919 th = (struct tcphdr *)(udp + 1);
2920 memcpy(&ttemp, th, sizeof(struct tcphdr));
2921 memcpy(udp, &ttemp, sizeof(struct tcphdr));
2922 /* Now adjust down the size of the outer IP header */
2923 o_len -= sizeof(struct udphdr);
2924 outer_ip->ip_len = htons(o_len);
2925 /* Now call in to the normal handling code */
2926 tcp_ctlinput_with_port(icmp, port);
2932 tcp6_next_pmtu(const struct icmp6_hdr *icmp6)
2934 int mtu = ntohl(icmp6->icmp6_mtu);
2937 * If no alternative MTU was proposed, or the proposed MTU was too
2938 * small, set to the min.
2940 if (mtu < IPV6_MMTU)
2941 mtu = IPV6_MMTU - 8; /* XXXNP: what is the adjustment for? */
2946 tcp6_ctlinput_with_port(struct ip6ctlparam *ip6cp, uint16_t port)
2948 struct in6_addr *dst;
2949 struct inpcb *(*notify)(struct inpcb *, int);
2950 struct ip6_hdr *ip6;
2954 struct icmp6_hdr *icmp6;
2955 struct in_conninfo inc;
2960 tcp_seq icmp_tcp_seq;
2965 icmp6 = ip6cp->ip6c_icmp6;
2967 ip6 = ip6cp->ip6c_ip6;
2968 off = ip6cp->ip6c_off;
2969 dst = &ip6cp->ip6c_finaldst->sin6_addr;
2971 errno = icmp6_errmap(icmp6);
2976 notify = tcp_mtudisc_notify;
2980 notify = tcp_drop_syn_sent;
2982 notify = tcp_notify;
2986 * There are only four ICMPs that may reset connection:
2987 * - administratively prohibited
2988 * - port unreachable
2989 * - time exceeded in transit
2990 * - unknown next header
2992 if (V_icmp_may_rst &&
2993 ((icmp6->icmp6_type == ICMP6_DST_UNREACH &&
2994 (icmp6->icmp6_code == ICMP6_DST_UNREACH_ADMIN ||
2995 icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT)) ||
2996 (icmp6->icmp6_type == ICMP6_TIME_EXCEEDED &&
2997 icmp6->icmp6_code == ICMP6_TIME_EXCEED_TRANSIT) ||
2998 (icmp6->icmp6_type == ICMP6_PARAM_PROB &&
2999 icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER)))
3000 notify = tcp_drop_syn_sent;
3002 notify = tcp_notify;
3005 notify = tcp_notify;
3008 /* Check if we can safely get the ports from the tcp hdr */
3011 (int32_t) (off + sizeof(struct tcp_ports)))) {
3014 bzero(&t_ports, sizeof(struct tcp_ports));
3015 m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports);
3016 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport,
3017 &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL);
3018 off += sizeof(struct tcp_ports);
3019 if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) {
3022 m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq);
3024 tp = intotcpcb(inp);
3026 if (tp->t_flags & TF_TOE && errno == EMSGSIZE) {
3027 /* MTU discovery for offloaded connections. */
3028 mtu = tcp6_next_pmtu(icmp6);
3029 tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu);
3033 if (tp->t_port != port)
3035 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
3036 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
3037 if (errno == EMSGSIZE) {
3040 * If we got a needfrag set the MTU
3041 * in the route to the suggested new
3042 * value (if given) and then notify.
3044 mtu = tcp6_next_pmtu(icmp6);
3046 bzero(&inc, sizeof(inc));
3047 inc.inc_fibnum = M_GETFIB(m);
3048 inc.inc_flags |= INC_ISIPV6;
3049 inc.inc6_faddr = *dst;
3050 if (in6_setscope(&inc.inc6_faddr,
3051 m->m_pkthdr.rcvif, NULL))
3054 * Only process the offered MTU if it
3055 * is smaller than the current one.
3057 if (mtu < tp->t_maxseg +
3058 sizeof (struct tcphdr) +
3059 sizeof (struct ip6_hdr)) {
3060 tcp_hc_updatemtu(&inc, mtu);
3061 tcp_mtudisc(inp, mtu);
3062 ICMP6STAT_INC(icp6s_pmtuchg);
3065 inp = (*notify)(inp, errno);
3068 bzero(&inc, sizeof(inc));
3069 inc.inc_fibnum = M_GETFIB(m);
3070 inc.inc_flags |= INC_ISIPV6;
3071 inc.inc_fport = t_ports.th_dport;
3072 inc.inc_lport = t_ports.th_sport;
3073 inc.inc6_faddr = *dst;
3074 inc.inc6_laddr = ip6->ip6_src;
3075 syncache_unreach(&inc, icmp_tcp_seq, port);
3083 tcp6_ctlinput(struct ip6ctlparam *ctl)
3085 tcp6_ctlinput_with_port(ctl, htons(0));
3089 tcp6_ctlinput_viaudp(udp_tun_icmp_param_t param)
3091 struct ip6ctlparam *ip6cp = param.ip6cp;
3096 m = m_pulldown(ip6cp->ip6c_m, ip6cp->ip6c_off, sizeof(struct udphdr), NULL);
3100 udp = mtod(m, struct udphdr *);
3101 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
3104 port = udp->uh_dport;
3105 m_adj(m, sizeof(struct udphdr));
3106 if ((m->m_flags & M_PKTHDR) == 0) {
3107 ip6cp->ip6c_m->m_pkthdr.len -= sizeof(struct udphdr);
3109 /* Now call in to the normal handling code */
3110 tcp6_ctlinput_with_port(ip6cp, port);
3116 tcp_keyed_hash(struct in_conninfo *inc, u_char *key, u_int len)
3121 KASSERT(len >= SIPHASH_KEY_LENGTH,
3122 ("%s: keylen %u too short ", __func__, len));
3123 SipHash24_Init(&ctx);
3124 SipHash_SetKey(&ctx, (uint8_t *)key);
3125 SipHash_Update(&ctx, &inc->inc_fport, sizeof(uint16_t));
3126 SipHash_Update(&ctx, &inc->inc_lport, sizeof(uint16_t));
3127 switch (inc->inc_flags & INC_ISIPV6) {
3130 SipHash_Update(&ctx, &inc->inc_faddr, sizeof(struct in_addr));
3131 SipHash_Update(&ctx, &inc->inc_laddr, sizeof(struct in_addr));
3136 SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(struct in6_addr));
3137 SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(struct in6_addr));
3141 SipHash_Final((uint8_t *)hash, &ctx);
3143 return (hash[0] ^ hash[1]);
3147 tcp_new_ts_offset(struct in_conninfo *inc)
3149 struct in_conninfo inc_store, *local_inc;
3151 if (!V_tcp_ts_offset_per_conn) {
3152 memcpy(&inc_store, inc, sizeof(struct in_conninfo));
3153 inc_store.inc_lport = 0;
3154 inc_store.inc_fport = 0;
3155 local_inc = &inc_store;
3159 return (tcp_keyed_hash(local_inc, V_ts_offset_secret,
3160 sizeof(V_ts_offset_secret)));
3164 * Following is where TCP initial sequence number generation occurs.
3166 * There are two places where we must use initial sequence numbers:
3167 * 1. In SYN-ACK packets.
3168 * 2. In SYN packets.
3170 * All ISNs for SYN-ACK packets are generated by the syncache. See
3171 * tcp_syncache.c for details.
3173 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
3174 * depends on this property. In addition, these ISNs should be
3175 * unguessable so as to prevent connection hijacking. To satisfy
3176 * the requirements of this situation, the algorithm outlined in
3177 * RFC 1948 is used, with only small modifications.
3179 * Implementation details:
3181 * Time is based off the system timer, and is corrected so that it
3182 * increases by one megabyte per second. This allows for proper
3183 * recycling on high speed LANs while still leaving over an hour
3186 * As reading the *exact* system time is too expensive to be done
3187 * whenever setting up a TCP connection, we increment the time
3188 * offset in two ways. First, a small random positive increment
3189 * is added to isn_offset for each connection that is set up.
3190 * Second, the function tcp_isn_tick fires once per clock tick
3191 * and increments isn_offset as necessary so that sequence numbers
3192 * are incremented at approximately ISN_BYTES_PER_SECOND. The
3193 * random positive increments serve only to ensure that the same
3194 * exact sequence number is never sent out twice (as could otherwise
3195 * happen when a port is recycled in less than the system tick
3198 * net.inet.tcp.isn_reseed_interval controls the number of seconds
3199 * between seeding of isn_secret. This is normally set to zero,
3200 * as reseeding should not be necessary.
3202 * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
3203 * isn_offset_old, and isn_ctx is performed using the ISN lock. In
3204 * general, this means holding an exclusive (write) lock.
3207 #define ISN_BYTES_PER_SECOND 1048576
3208 #define ISN_STATIC_INCREMENT 4096
3209 #define ISN_RANDOM_INCREMENT (4096 - 1)
3210 #define ISN_SECRET_LENGTH SIPHASH_KEY_LENGTH
3212 VNET_DEFINE_STATIC(u_char, isn_secret[ISN_SECRET_LENGTH]);
3213 VNET_DEFINE_STATIC(int, isn_last);
3214 VNET_DEFINE_STATIC(int, isn_last_reseed);
3215 VNET_DEFINE_STATIC(u_int32_t, isn_offset);
3216 VNET_DEFINE_STATIC(u_int32_t, isn_offset_old);
3218 #define V_isn_secret VNET(isn_secret)
3219 #define V_isn_last VNET(isn_last)
3220 #define V_isn_last_reseed VNET(isn_last_reseed)
3221 #define V_isn_offset VNET(isn_offset)
3222 #define V_isn_offset_old VNET(isn_offset_old)
3225 tcp_new_isn(struct in_conninfo *inc)
3228 u_int32_t projected_offset;
3231 /* Seed if this is the first use, reseed if requested. */
3232 if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) &&
3233 (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz)
3235 arc4rand(&V_isn_secret, sizeof(V_isn_secret), 0);
3236 V_isn_last_reseed = ticks;
3239 /* Compute the hash and return the ISN. */
3240 new_isn = (tcp_seq)tcp_keyed_hash(inc, V_isn_secret,
3241 sizeof(V_isn_secret));
3242 V_isn_offset += ISN_STATIC_INCREMENT +
3243 (arc4random() & ISN_RANDOM_INCREMENT);
3244 if (ticks != V_isn_last) {
3245 projected_offset = V_isn_offset_old +
3246 ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last);
3247 if (SEQ_GT(projected_offset, V_isn_offset))
3248 V_isn_offset = projected_offset;
3249 V_isn_offset_old = V_isn_offset;
3252 new_isn += V_isn_offset;
3258 * When a specific ICMP unreachable message is received and the
3259 * connection state is SYN-SENT, drop the connection. This behavior
3260 * is controlled by the icmp_may_rst sysctl.
3262 static struct inpcb *
3263 tcp_drop_syn_sent(struct inpcb *inp, int errno)
3268 INP_WLOCK_ASSERT(inp);
3270 tp = intotcpcb(inp);
3271 if (tp->t_state != TCPS_SYN_SENT)
3274 if (IS_FASTOPEN(tp->t_flags))
3275 tcp_fastopen_disable_path(tp);
3277 tp = tcp_drop(tp, errno);
3285 * When `need fragmentation' ICMP is received, update our idea of the MSS
3286 * based on the new value. Also nudge TCP to send something, since we
3287 * know the packet we just sent was dropped.
3288 * This duplicates some code in the tcp_mss() function in tcp_input.c.
3290 static struct inpcb *
3291 tcp_mtudisc_notify(struct inpcb *inp, int error)
3294 return (tcp_mtudisc(inp, -1));
3297 static struct inpcb *
3298 tcp_mtudisc(struct inpcb *inp, int mtuoffer)
3303 INP_WLOCK_ASSERT(inp);
3305 tp = intotcpcb(inp);
3306 KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
3308 tcp_mss_update(tp, -1, mtuoffer, NULL, NULL);
3310 so = inp->inp_socket;
3311 SOCKBUF_LOCK(&so->so_snd);
3312 /* If the mss is larger than the socket buffer, decrease the mss. */
3313 if (so->so_snd.sb_hiwat < tp->t_maxseg)
3314 tp->t_maxseg = so->so_snd.sb_hiwat;
3315 SOCKBUF_UNLOCK(&so->so_snd);
3317 TCPSTAT_INC(tcps_mturesent);
3319 tp->snd_nxt = tp->snd_una;
3320 tcp_free_sackholes(tp);
3321 tp->snd_recover = tp->snd_max;
3322 if (tp->t_flags & TF_SACK_PERMIT)
3323 EXIT_FASTRECOVERY(tp->t_flags);
3324 if (tp->t_fb->tfb_tcp_mtu_chg != NULL) {
3326 * Conceptually the snd_nxt setting
3327 * and freeing sack holes should
3328 * be done by the default stacks
3329 * own tfb_tcp_mtu_chg().
3331 tp->t_fb->tfb_tcp_mtu_chg(tp);
3333 if (tcp_output(tp) < 0)
3341 * Look-up the routing entry to the peer of this inpcb. If no route
3342 * is found and it cannot be allocated, then return 0. This routine
3343 * is called by TCP routines that access the rmx structure and by
3344 * tcp_mss_update to get the peer/interface MTU.
3347 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap)
3349 struct nhop_object *nh;
3351 uint32_t maxmtu = 0;
3353 KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
3355 if (inc->inc_faddr.s_addr != INADDR_ANY) {
3356 nh = fib4_lookup(inc->inc_fibnum, inc->inc_faddr, 0, NHR_NONE, 0);
3361 maxmtu = nh->nh_mtu;
3363 /* Report additional interface capabilities. */
3365 if (ifp->if_capenable & IFCAP_TSO4 &&
3366 ifp->if_hwassist & CSUM_TSO) {
3367 cap->ifcap |= CSUM_TSO;
3368 cap->tsomax = ifp->if_hw_tsomax;
3369 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3370 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3380 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap)
3382 struct nhop_object *nh;
3383 struct in6_addr dst6;
3386 uint32_t maxmtu = 0;
3388 KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
3390 if (inc->inc_flags & INC_IPV6MINMTU)
3393 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
3394 in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid);
3395 nh = fib6_lookup(inc->inc_fibnum, &dst6, scopeid, NHR_NONE, 0);
3400 maxmtu = nh->nh_mtu;
3402 /* Report additional interface capabilities. */
3404 if (ifp->if_capenable & IFCAP_TSO6 &&
3405 ifp->if_hwassist & CSUM_TSO) {
3406 cap->ifcap |= CSUM_TSO;
3407 cap->tsomax = ifp->if_hw_tsomax;
3408 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3409 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3418 * Handle setsockopt(IPV6_USE_MIN_MTU) by a TCP stack.
3420 * XXXGL: we are updating inpcb here with INC_IPV6MINMTU flag.
3421 * The right place to do that is ip6_setpktopt() that has just been
3422 * executed. By the way it just filled ip6po_minmtu for us.
3425 tcp6_use_min_mtu(struct tcpcb *tp)
3427 struct inpcb *inp = tptoinpcb(tp);
3429 INP_WLOCK_ASSERT(inp);
3431 * In case of the IPV6_USE_MIN_MTU socket
3432 * option, the INC_IPV6MINMTU flag to announce
3433 * a corresponding MSS during the initial
3434 * handshake. If the TCP connection is not in
3435 * the front states, just reduce the MSS being
3436 * used. This avoids the sending of TCP
3437 * segments which will be fragmented at the
3440 inp->inp_inc.inc_flags |= INC_IPV6MINMTU;
3441 if ((tp->t_state >= TCPS_SYN_SENT) &&
3442 (inp->inp_inc.inc_flags & INC_ISIPV6)) {
3443 struct ip6_pktopts *opt;
3445 opt = inp->in6p_outputopts;
3446 if (opt != NULL && opt->ip6po_minmtu == IP6PO_MINMTU_ALL &&
3447 tp->t_maxseg > TCP6_MSS)
3448 tp->t_maxseg = TCP6_MSS;
3454 * Calculate effective SMSS per RFC5681 definition for a given TCP
3455 * connection at its current state, taking into account SACK and etc.
3458 tcp_maxseg(const struct tcpcb *tp)
3462 if (tp->t_flags & TF_NOOPT)
3463 return (tp->t_maxseg);
3466 * Here we have a simplified code from tcp_addoptions(),
3467 * without a proper loop, and having most of paddings hardcoded.
3468 * We might make mistakes with padding here in some edge cases,
3469 * but this is harmless, since result of tcp_maxseg() is used
3470 * only in cwnd and ssthresh estimations.
3472 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3473 if (tp->t_flags & TF_RCVD_TSTMP)
3474 optlen = TCPOLEN_TSTAMP_APPA;
3477 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3478 if (tp->t_flags & TF_SIGNATURE)
3479 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3481 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) {
3482 optlen += TCPOLEN_SACKHDR;
3483 optlen += tp->rcv_numsacks * TCPOLEN_SACK;
3484 optlen = PADTCPOLEN(optlen);
3487 if (tp->t_flags & TF_REQ_TSTMP)
3488 optlen = TCPOLEN_TSTAMP_APPA;
3490 optlen = PADTCPOLEN(TCPOLEN_MAXSEG);
3491 if (tp->t_flags & TF_REQ_SCALE)
3492 optlen += PADTCPOLEN(TCPOLEN_WINDOW);
3493 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3494 if (tp->t_flags & TF_SIGNATURE)
3495 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3497 if (tp->t_flags & TF_SACK_PERMIT)
3498 optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED);
3501 optlen = min(optlen, TCP_MAXOLEN);
3502 return (tp->t_maxseg - optlen);
3507 tcp_fixed_maxseg(const struct tcpcb *tp)
3511 if (tp->t_flags & TF_NOOPT)
3512 return (tp->t_maxseg);
3515 * Here we have a simplified code from tcp_addoptions(),
3516 * without a proper loop, and having most of paddings hardcoded.
3517 * We only consider fixed options that we would send every
3518 * time I.e. SACK is not considered. This is important
3519 * for cc modules to figure out what the modulo of the
3522 #define PAD(len) ((((len) / 4) + !!((len) % 4)) * 4)
3523 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3524 if (tp->t_flags & TF_RCVD_TSTMP)
3525 optlen = TCPOLEN_TSTAMP_APPA;
3528 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3529 if (tp->t_flags & TF_SIGNATURE)
3530 optlen += PAD(TCPOLEN_SIGNATURE);
3533 if (tp->t_flags & TF_REQ_TSTMP)
3534 optlen = TCPOLEN_TSTAMP_APPA;
3536 optlen = PAD(TCPOLEN_MAXSEG);
3537 if (tp->t_flags & TF_REQ_SCALE)
3538 optlen += PAD(TCPOLEN_WINDOW);
3539 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3540 if (tp->t_flags & TF_SIGNATURE)
3541 optlen += PAD(TCPOLEN_SIGNATURE);
3543 if (tp->t_flags & TF_SACK_PERMIT)
3544 optlen += PAD(TCPOLEN_SACK_PERMITTED);
3547 optlen = min(optlen, TCP_MAXOLEN);
3548 return (tp->t_maxseg - optlen);
3554 sysctl_drop(SYSCTL_HANDLER_ARGS)
3556 /* addrs[0] is a foreign socket, addrs[1] is a local one. */
3557 struct sockaddr_storage addrs[2];
3561 struct sockaddr_in *fin = NULL, *lin = NULL;
3563 struct epoch_tracker et;
3565 struct sockaddr_in6 *fin6, *lin6;
3575 if (req->oldptr != NULL || req->oldlen != 0)
3577 if (req->newptr == NULL)
3579 if (req->newlen < sizeof(addrs))
3581 error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3585 switch (addrs[0].ss_family) {
3588 fin6 = (struct sockaddr_in6 *)&addrs[0];
3589 lin6 = (struct sockaddr_in6 *)&addrs[1];
3590 if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3591 lin6->sin6_len != sizeof(struct sockaddr_in6))
3593 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3594 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3596 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3597 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3599 fin = (struct sockaddr_in *)&addrs[0];
3600 lin = (struct sockaddr_in *)&addrs[1];
3604 error = sa6_embedscope(fin6, V_ip6_use_defzone);
3607 error = sa6_embedscope(lin6, V_ip6_use_defzone);
3614 fin = (struct sockaddr_in *)&addrs[0];
3615 lin = (struct sockaddr_in *)&addrs[1];
3616 if (fin->sin_len != sizeof(struct sockaddr_in) ||
3617 lin->sin_len != sizeof(struct sockaddr_in))
3624 NET_EPOCH_ENTER(et);
3625 switch (addrs[0].ss_family) {
3628 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3629 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3630 INPLOOKUP_WLOCKPCB, NULL);
3635 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3636 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3641 if (!SOLISTENING(inp->inp_socket)) {
3642 tp = intotcpcb(inp);
3643 tp = tcp_drop(tp, ECONNABORTED);
3654 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
3655 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3656 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_drop, "",
3657 "Drop TCP connection");
3660 tcp_sysctl_setsockopt(SYSCTL_HANDLER_ARGS)
3662 return (sysctl_setsockopt(oidp, arg1, arg2, req, &V_tcbinfo,
3663 &tcp_ctloutput_set));
3666 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, setsockopt,
3667 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3668 CTLFLAG_MPSAFE, NULL, 0, tcp_sysctl_setsockopt, "",
3669 "Set socket option for TCP endpoint");
3673 sysctl_switch_tls(SYSCTL_HANDLER_ARGS)
3675 /* addrs[0] is a foreign socket, addrs[1] is a local one. */
3676 struct sockaddr_storage addrs[2];
3679 struct sockaddr_in *fin = NULL, *lin = NULL;
3681 struct epoch_tracker et;
3683 struct sockaddr_in6 *fin6, *lin6;
3693 if (req->oldptr != NULL || req->oldlen != 0)
3695 if (req->newptr == NULL)
3697 if (req->newlen < sizeof(addrs))
3699 error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3703 switch (addrs[0].ss_family) {
3706 fin6 = (struct sockaddr_in6 *)&addrs[0];
3707 lin6 = (struct sockaddr_in6 *)&addrs[1];
3708 if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3709 lin6->sin6_len != sizeof(struct sockaddr_in6))
3711 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3712 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3714 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3715 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3717 fin = (struct sockaddr_in *)&addrs[0];
3718 lin = (struct sockaddr_in *)&addrs[1];
3722 error = sa6_embedscope(fin6, V_ip6_use_defzone);
3725 error = sa6_embedscope(lin6, V_ip6_use_defzone);
3732 fin = (struct sockaddr_in *)&addrs[0];
3733 lin = (struct sockaddr_in *)&addrs[1];
3734 if (fin->sin_len != sizeof(struct sockaddr_in) ||
3735 lin->sin_len != sizeof(struct sockaddr_in))
3742 NET_EPOCH_ENTER(et);
3743 switch (addrs[0].ss_family) {
3746 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3747 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3748 INPLOOKUP_WLOCKPCB, NULL);
3753 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3754 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3762 so = inp->inp_socket;
3764 error = ktls_set_tx_mode(so,
3765 arg2 == 0 ? TCP_TLS_MODE_SW : TCP_TLS_MODE_IFNET);
3773 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_sw_tls,
3774 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3775 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_switch_tls, "",
3776 "Switch TCP connection to SW TLS");
3777 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_ifnet_tls,
3778 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3779 CTLFLAG_NEEDGIANT, NULL, 1, sysctl_switch_tls, "",
3780 "Switch TCP connection to ifnet TLS");
3784 * Generate a standardized TCP log line for use throughout the
3785 * tcp subsystem. Memory allocation is done with M_NOWAIT to
3786 * allow use in the interrupt context.
3788 * NB: The caller MUST free(s, M_TCPLOG) the returned string.
3789 * NB: The function may return NULL if memory allocation failed.
3791 * Due to header inclusion and ordering limitations the struct ip
3792 * and ip6_hdr pointers have to be passed as void pointers.
3795 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3799 /* Is logging enabled? */
3800 if (V_tcp_log_in_vain == 0)
3803 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3807 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3811 /* Is logging enabled? */
3812 if (tcp_log_debug == 0)
3815 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3819 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3825 const struct ip *ip = (const struct ip *)ip4hdr;
3828 const struct ip6_hdr *ip6 = (const struct ip6_hdr *)ip6hdr;
3832 * The log line looks like this:
3833 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>"
3835 size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") +
3836 sizeof(PRINT_TH_FLAGS) + 1 +
3838 2 * INET6_ADDRSTRLEN;
3840 2 * INET_ADDRSTRLEN;
3843 s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT);
3847 strcat(s, "TCP: [");
3850 if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) {
3851 inet_ntoa_r(inc->inc_faddr, sp);
3853 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3855 inet_ntoa_r(inc->inc_laddr, sp);
3857 sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3860 ip6_sprintf(sp, &inc->inc6_faddr);
3862 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3864 ip6_sprintf(sp, &inc->inc6_laddr);
3866 sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3867 } else if (ip6 && th) {
3868 ip6_sprintf(sp, &ip6->ip6_src);
3870 sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3872 ip6_sprintf(sp, &ip6->ip6_dst);
3874 sprintf(sp, "]:%i", ntohs(th->th_dport));
3877 } else if (ip && th) {
3878 inet_ntoa_r(ip->ip_src, sp);
3880 sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3882 inet_ntoa_r(ip->ip_dst, sp);
3884 sprintf(sp, "]:%i", ntohs(th->th_dport));
3892 sprintf(sp, " tcpflags 0x%b", tcp_get_flags(th), PRINT_TH_FLAGS);
3893 if (*(s + size - 1) != '\0')
3894 panic("%s: string too long", __func__);
3899 * A subroutine which makes it easy to track TCP state changes with DTrace.
3900 * This function shouldn't be called for t_state initializations that don't
3901 * correspond to actual TCP state transitions.
3904 tcp_state_change(struct tcpcb *tp, int newstate)
3906 #if defined(KDTRACE_HOOKS)
3907 int pstate = tp->t_state;
3910 TCPSTATES_DEC(tp->t_state);
3911 TCPSTATES_INC(newstate);
3912 tp->t_state = newstate;
3913 TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate);
3917 * Create an external-format (``xtcpcb'') structure using the information in
3918 * the kernel-format tcpcb structure pointed to by tp. This is done to
3919 * reduce the spew of irrelevant information over this interface, to isolate
3920 * user code from changes in the kernel structure, and potentially to provide
3921 * information-hiding if we decide that some of this information should be
3922 * hidden from users.
3925 tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt)
3927 struct tcpcb *tp = intotcpcb(inp);
3930 bzero(xt, sizeof(*xt));
3931 xt->t_state = tp->t_state;
3932 xt->t_logstate = tcp_get_bblog_state(tp);
3933 xt->t_flags = tp->t_flags;
3934 xt->t_sndzerowin = tp->t_sndzerowin;
3935 xt->t_sndrexmitpack = tp->t_sndrexmitpack;
3936 xt->t_rcvoopack = tp->t_rcvoopack;
3937 xt->t_rcv_wnd = tp->rcv_wnd;
3938 xt->t_snd_wnd = tp->snd_wnd;
3939 xt->t_snd_cwnd = tp->snd_cwnd;
3940 xt->t_snd_ssthresh = tp->snd_ssthresh;
3941 xt->t_dsack_bytes = tp->t_dsack_bytes;
3942 xt->t_dsack_tlp_bytes = tp->t_dsack_tlp_bytes;
3943 xt->t_dsack_pack = tp->t_dsack_pack;
3944 xt->t_maxseg = tp->t_maxseg;
3945 xt->xt_ecn = (tp->t_flags2 & TF2_ECN_PERMIT) ? 1 : 0 +
3946 (tp->t_flags2 & TF2_ACE_PERMIT) ? 2 : 0;
3948 now = getsbinuptime();
3949 #define COPYTIMER(which,where) do { \
3950 if (tp->t_timers[which] != SBT_MAX) \
3951 xt->where = (tp->t_timers[which] - now) / SBT_1MS; \
3955 COPYTIMER(TT_DELACK, tt_delack);
3956 COPYTIMER(TT_REXMT, tt_rexmt);
3957 COPYTIMER(TT_PERSIST, tt_persist);
3958 COPYTIMER(TT_KEEP, tt_keep);
3959 COPYTIMER(TT_2MSL, tt_2msl);
3961 xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz;
3963 xt->xt_encaps_port = tp->t_port;
3964 bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack,
3965 TCP_FUNCTION_NAME_LEN_MAX);
3966 bcopy(CC_ALGO(tp)->name, xt->xt_cc, TCP_CA_NAME_MAX);
3968 (void)tcp_log_get_id(tp, xt->xt_logid);
3971 xt->xt_len = sizeof(struct xtcpcb);
3972 in_pcbtoxinpcb(inp, &xt->xt_inp);
3974 * TCP doesn't use inp_ppcb pointer, we embed inpcb into tcpcb.
3975 * Fixup the pointer that in_pcbtoxinpcb() has set. When printing
3976 * TCP netstat(1) used to use this pointer, so this fixup needs to
3977 * stay for stable/14.
3979 xt->xt_inp.inp_ppcb = (uintptr_t)tp;
3983 tcp_log_end_status(struct tcpcb *tp, uint8_t status)
3988 (status > TCP_EI_STATUS_MAX_VALUE) ||
3993 if (status > (sizeof(uint32_t) * 8)) {
3994 /* Should this be a KASSERT? */
3997 bit = 1U << (status - 1);
3998 if (bit & tp->t_end_info_status) {
3999 /* already logged */
4002 for (i = 0; i < TCP_END_BYTE_INFO; i++) {
4003 if (tp->t_end_info_bytes[i] == TCP_EI_EMPTY_SLOT) {
4004 tp->t_end_info_bytes[i] = status;
4005 tp->t_end_info_status |= bit;
4012 tcp_can_enable_pacing(void)
4015 if ((tcp_pacing_limit == -1) ||
4016 (tcp_pacing_limit > number_of_tcp_connections_pacing)) {
4017 atomic_fetchadd_int(&number_of_tcp_connections_pacing, 1);
4018 shadow_num_connections = number_of_tcp_connections_pacing;
4021 counter_u64_add(tcp_pacing_failures, 1);
4026 static uint8_t tcp_pacing_warning = 0;
4029 tcp_decrement_paced_conn(void)
4033 ret = atomic_fetchadd_int(&number_of_tcp_connections_pacing, -1);
4034 shadow_num_connections = number_of_tcp_connections_pacing;
4035 KASSERT(ret != 0, ("tcp_paced_connection_exits -1 would cause wrap?"));
4037 if (tcp_pacing_limit != -1) {
4038 printf("Warning all pacing is now disabled, count decrements invalidly!\n");
4039 tcp_pacing_limit = 0;
4040 } else if (tcp_pacing_warning == 0) {
4041 printf("Warning pacing count is invalid, invalid decrement\n");
4042 tcp_pacing_warning = 1;
4048 tcp_default_switch_failed(struct tcpcb *tp)
4051 * If a switch fails we only need to
4052 * care about two things:
4055 * b) The timer granularity.
4056 * Timeouts, at least for now, don't use the
4057 * old callout system in the other stacks so
4058 * those are hopefully safe.
4060 tcp_lro_features_off(tp);
4061 tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
4064 #ifdef TCP_ACCOUNTING
4066 tcp_do_ack_accounting(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to, uint32_t tiwin, int mss)
4068 if (SEQ_LT(th->th_ack, tp->snd_una)) {
4069 /* Do we have a SACK? */
4070 if (to->to_flags & TOF_SACK) {
4071 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4072 tp->tcp_cnt_counters[ACK_SACK]++;
4076 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4077 tp->tcp_cnt_counters[ACK_BEHIND]++;
4079 return (ACK_BEHIND);
4081 } else if (th->th_ack == tp->snd_una) {
4082 /* Do we have a SACK? */
4083 if (to->to_flags & TOF_SACK) {
4084 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4085 tp->tcp_cnt_counters[ACK_SACK]++;
4088 } else if (tiwin != tp->snd_wnd) {
4089 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4090 tp->tcp_cnt_counters[ACK_RWND]++;
4094 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4095 tp->tcp_cnt_counters[ACK_DUPACK]++;
4097 return (ACK_DUPACK);
4100 if (!SEQ_GT(th->th_ack, tp->snd_max)) {
4101 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4102 tp->tcp_cnt_counters[CNT_OF_ACKS_IN] += (((th->th_ack - tp->snd_una) + mss - 1)/mss);
4105 if (to->to_flags & TOF_SACK) {
4106 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4107 tp->tcp_cnt_counters[ACK_CUMACK_SACK]++;
4109 return (ACK_CUMACK_SACK);
4111 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4112 tp->tcp_cnt_counters[ACK_CUMACK]++;
4114 return (ACK_CUMACK);
4121 tcp_change_time_units(struct tcpcb *tp, int granularity)
4123 if (tp->t_tmr_granularity == granularity) {
4127 if (granularity == TCP_TMR_GRANULARITY_USEC) {
4128 KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS),
4129 ("Granularity is not TICKS its %u in tp:%p",
4130 tp->t_tmr_granularity, tp));
4131 tp->t_rttlow = TICKS_2_USEC(tp->t_rttlow);
4132 if (tp->t_srtt > 1) {
4135 val = tp->t_srtt >> TCP_RTT_SHIFT;
4136 frac = tp->t_srtt & 0x1f;
4137 tp->t_srtt = TICKS_2_USEC(val);
4139 * frac is the fractional part of the srtt (if any)
4140 * but its in ticks and every bit represents
4145 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
4147 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
4155 val = tp->t_rttvar >> TCP_RTTVAR_SHIFT;
4156 frac = tp->t_rttvar & 0x1f;
4157 tp->t_rttvar = TICKS_2_USEC(val);
4159 * frac is the fractional part of the srtt (if any)
4160 * but its in ticks and every bit represents
4165 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
4167 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
4169 tp->t_rttvar += frac;
4172 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_USEC;
4173 } else if (granularity == TCP_TMR_GRANULARITY_TICKS) {
4174 /* Convert back to ticks, with */
4175 KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_USEC),
4176 ("Granularity is not USEC its %u in tp:%p",
4177 tp->t_tmr_granularity, tp));
4178 if (tp->t_srtt > 1) {
4181 val = USEC_2_TICKS(tp->t_srtt);
4182 frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
4183 tp->t_srtt = val << TCP_RTT_SHIFT;
4185 * frac is the fractional part here is left
4186 * over from converting to hz and shifting.
4187 * We need to convert this to the 5 bit
4192 frac = (((uint64_t)frac * (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
4194 frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
4202 val = USEC_2_TICKS(tp->t_rttvar);
4203 frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
4204 tp->t_rttvar = val << TCP_RTTVAR_SHIFT;
4206 * frac is the fractional part here is left
4207 * over from converting to hz and shifting.
4208 * We need to convert this to the 5 bit
4213 frac = (((uint64_t)frac * (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
4215 frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
4217 tp->t_rttvar += frac;
4220 tp->t_rttlow = USEC_2_TICKS(tp->t_rttlow);
4221 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS;
4225 panic("Unknown granularity:%d tp:%p",
4232 tcp_handle_orphaned_packets(struct tcpcb *tp)
4234 struct mbuf *save, *m, *prev;
4236 * Called when a stack switch is occuring from the fini()
4237 * of the old stack. We assue the init() as already been
4238 * run of the new stack and it has set the t_flags2 to
4239 * what it supports. This function will then deal with any
4240 * differences i.e. cleanup packets that maybe queued that
4241 * the newstack does not support.
4244 if (tp->t_flags2 & TF2_MBUF_L_ACKS)
4246 if ((tp->t_flags2 & TF2_SUPPORTS_MBUFQ) == 0 &&
4247 !STAILQ_EMPTY(&tp->t_inqueue)) {
4249 * It is unsafe to process the packets since a
4250 * reset may be lurking in them (its rare but it
4251 * can occur). If we were to find a RST, then we
4252 * would end up dropping the connection and the
4253 * INP lock, so when we return the caller (tcp_usrreq)
4254 * will blow up when it trys to unlock the inp.
4255 * This new stack does not do any fancy LRO features
4256 * so all we can do is toss the packets.
4258 m = STAILQ_FIRST(&tp->t_inqueue);
4259 STAILQ_INIT(&tp->t_inqueue);
4260 STAILQ_FOREACH_FROM_SAFE(m, &tp->t_inqueue, m_stailqpkt, save)
4264 * Here we have a stack that does mbuf queuing but
4265 * does not support compressed ack's. We must
4266 * walk all the mbufs and discard any compressed acks.
4268 STAILQ_FOREACH_SAFE(m, &tp->t_inqueue, m_stailqpkt, save) {
4269 if (m->m_flags & M_ACKCMP) {
4270 if (m == STAILQ_FIRST(&tp->t_inqueue))
4271 STAILQ_REMOVE_HEAD(&tp->t_inqueue,
4274 STAILQ_REMOVE_AFTER(&tp->t_inqueue,
4283 #ifdef TCP_REQUEST_TRK
4285 tcp_estimate_tls_overhead(struct socket *so, uint64_t tls_usr_bytes)
4288 struct ktls_session *tls;
4289 uint32_t rec_oh, records;
4291 tls = so->so_snd.sb_tls_info;
4295 rec_oh = tls->params.tls_hlen + tls->params.tls_tlen;
4296 records = ((tls_usr_bytes + tls->params.max_frame_len - 1)/tls->params.max_frame_len);
4297 return (records * rec_oh);
4303 extern uint32_t tcp_stale_entry_time;
4304 uint32_t tcp_stale_entry_time = 250000;
4305 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, usrlog_stale, CTLFLAG_RW,
4306 &tcp_stale_entry_time, 250000, "Time that a tcpreq entry without a sendfile ages out");
4309 tcp_req_log_req_info(struct tcpcb *tp, struct tcp_sendfile_track *req,
4310 uint16_t slot, uint8_t val, uint64_t offset, uint64_t nbytes)
4312 if (tcp_bblogging_on(tp)) {
4313 union tcp_log_stackspecific log;
4316 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
4318 log.u_bbr.inhpts = tcp_in_hpts(tp);
4320 log.u_bbr.flex8 = val;
4321 log.u_bbr.rttProp = req->timestamp;
4322 log.u_bbr.delRate = req->start;
4323 log.u_bbr.cur_del_rate = req->end;
4324 log.u_bbr.flex1 = req->start_seq;
4325 log.u_bbr.flex2 = req->end_seq;
4326 log.u_bbr.flex3 = req->flags;
4327 log.u_bbr.flex4 = ((req->localtime >> 32) & 0x00000000ffffffff);
4328 log.u_bbr.flex5 = (req->localtime & 0x00000000ffffffff);
4329 log.u_bbr.flex7 = slot;
4330 log.u_bbr.bw_inuse = offset;
4331 /* nbytes = flex6 | epoch */
4332 log.u_bbr.flex6 = ((nbytes >> 32) & 0x00000000ffffffff);
4333 log.u_bbr.epoch = (nbytes & 0x00000000ffffffff);
4334 /* cspr = lt_epoch | pkts_out */
4335 log.u_bbr.lt_epoch = ((req->cspr >> 32) & 0x00000000ffffffff);
4336 log.u_bbr.pkts_out |= (req->cspr & 0x00000000ffffffff);
4337 log.u_bbr.applimited = tp->t_tcpreq_closed;
4338 log.u_bbr.applimited <<= 8;
4339 log.u_bbr.applimited |= tp->t_tcpreq_open;
4340 log.u_bbr.applimited <<= 8;
4341 log.u_bbr.applimited |= tp->t_tcpreq_req;
4342 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
4343 TCP_LOG_EVENTP(tp, NULL,
4344 &tptosocket(tp)->so_rcv,
4345 &tptosocket(tp)->so_snd,
4347 0, &log, false, &tv);
4352 tcp_req_free_a_slot(struct tcpcb *tp, struct tcp_sendfile_track *ent)
4354 if (tp->t_tcpreq_req > 0)
4356 if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) {
4357 if (tp->t_tcpreq_open > 0)
4358 tp->t_tcpreq_open--;
4360 if (tp->t_tcpreq_closed > 0)
4361 tp->t_tcpreq_closed--;
4363 ent->flags = TCP_TRK_TRACK_FLG_EMPTY;
4367 tcp_req_check_for_stale_entries(struct tcpcb *tp, uint64_t ts, int rm_oldest)
4369 struct tcp_sendfile_track *ent;
4370 uint64_t time_delta, oldest_delta;
4371 int i, oldest, oldest_set = 0, cnt_rm = 0;
4373 for(i = 0; i < MAX_TCP_TRK_REQ; i++) {
4374 ent = &tp->t_tcpreq_info[i];
4375 if (ent->flags != TCP_TRK_TRACK_FLG_USED) {
4377 * We only care about closed end ranges
4378 * that are allocated and have no sendfile
4379 * ever touching them. They would be in
4384 if (ts >= ent->localtime)
4385 time_delta = ts - ent->localtime;
4389 ((oldest_delta < time_delta) || (oldest_set == 0))) {
4392 oldest_delta = time_delta;
4394 if (tcp_stale_entry_time && (time_delta >= tcp_stale_entry_time)) {
4396 * No sendfile in a our time-limit
4400 tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], i, TCP_TRK_REQ_LOG_STALE,
4402 tcp_req_free_a_slot(tp, ent);
4405 if ((cnt_rm == 0) && rm_oldest && oldest_set) {
4406 ent = &tp->t_tcpreq_info[oldest];
4407 tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], i, TCP_TRK_REQ_LOG_STALE,
4409 tcp_req_free_a_slot(tp, ent);
4414 tcp_req_check_for_comp(struct tcpcb *tp, tcp_seq ack_point)
4417 struct tcp_sendfile_track *ent;
4419 /* Clean up any old closed end requests that are now completed */
4420 if (tp->t_tcpreq_req == 0)
4422 if (tp->t_tcpreq_closed == 0)
4424 for(i = 0; i < MAX_TCP_TRK_REQ; i++) {
4425 ent = &tp->t_tcpreq_info[i];
4426 /* Skip empty ones */
4427 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY)
4429 /* Skip open ones */
4430 if (ent->flags & TCP_TRK_TRACK_FLG_OPEN)
4432 if (SEQ_GEQ(ack_point, ent->end_seq)) {
4433 /* We are past it -- free it */
4434 tcp_req_log_req_info(tp, ent,
4435 i, TCP_TRK_REQ_LOG_FREED, 0, 0);
4436 tcp_req_free_a_slot(tp, ent);
4444 tcp_req_is_entry_comp(struct tcpcb *tp, struct tcp_sendfile_track *ent, tcp_seq ack_point)
4446 if (tp->t_tcpreq_req == 0)
4448 if (tp->t_tcpreq_closed == 0)
4450 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY)
4452 if (SEQ_GEQ(ack_point, ent->end_seq)) {
4458 struct tcp_sendfile_track *
4459 tcp_req_find_a_req_that_is_completed_by(struct tcpcb *tp, tcp_seq th_ack, int *ip)
4462 * Given an ack point (th_ack) walk through our entries and
4463 * return the first one found that th_ack goes past the
4466 struct tcp_sendfile_track *ent;
4469 if (tp->t_tcpreq_req == 0) {
4473 for(i = 0; i < MAX_TCP_TRK_REQ; i++) {
4474 ent = &tp->t_tcpreq_info[i];
4475 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY)
4477 if ((ent->flags & TCP_TRK_TRACK_FLG_OPEN) == 0) {
4478 if (SEQ_GEQ(th_ack, ent->end_seq)) {
4487 struct tcp_sendfile_track *
4488 tcp_req_find_req_for_seq(struct tcpcb *tp, tcp_seq seq)
4490 struct tcp_sendfile_track *ent;
4493 if (tp->t_tcpreq_req == 0) {
4497 for(i = 0; i < MAX_TCP_TRK_REQ; i++) {
4498 ent = &tp->t_tcpreq_info[i];
4499 tcp_req_log_req_info(tp, ent, i, TCP_TRK_REQ_LOG_SEARCH,
4501 if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) {
4504 if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) {
4506 * An open end request only needs to
4507 * match the beginning seq or be
4508 * all we have (once we keep going on
4509 * a open end request we may have a seq
4512 if ((SEQ_GEQ(seq, ent->start_seq)) ||
4513 (tp->t_tcpreq_closed == 0))
4517 * For this one we need to
4518 * be a bit more careful if its
4519 * completed at least.
4521 if ((SEQ_GEQ(seq, ent->start_seq)) &&
4522 (SEQ_LT(seq, ent->end_seq))) {
4530 /* Should this be in its own file tcp_req.c ? */
4531 struct tcp_sendfile_track *
4532 tcp_req_alloc_req_full(struct tcpcb *tp, struct tcp_snd_req *req, uint64_t ts, int rec_dups)
4534 struct tcp_sendfile_track *fil;
4537 /* In case the stack does not check for completions do so now */
4538 tcp_req_check_for_comp(tp, tp->snd_una);
4539 /* Check for stale entries */
4540 if (tp->t_tcpreq_req)
4541 tcp_req_check_for_stale_entries(tp, ts,
4542 (tp->t_tcpreq_req >= MAX_TCP_TRK_REQ));
4543 /* Check to see if this is a duplicate of one not started */
4544 if (tp->t_tcpreq_req) {
4545 for(i = 0, allocated = 0; i < MAX_TCP_TRK_REQ; i++) {
4546 fil = &tp->t_tcpreq_info[i];
4547 if (fil->flags != TCP_TRK_TRACK_FLG_USED)
4549 if ((fil->timestamp == req->timestamp) &&
4550 (fil->start == req->start) &&
4551 ((fil->flags & TCP_TRK_TRACK_FLG_OPEN) ||
4552 (fil->end == req->end))) {
4554 * We already have this request
4555 * and it has not been started with sendfile.
4556 * This probably means the user was returned
4557 * a 4xx of some sort and its going to age
4558 * out, lets not duplicate it.
4564 /* Ok if there is no room at the inn we are in trouble */
4565 if (tp->t_tcpreq_req >= MAX_TCP_TRK_REQ) {
4566 tcp_trace_point(tp, TCP_TP_REQ_LOG_FAIL);
4567 for(i = 0; i < MAX_TCP_TRK_REQ; i++) {
4568 tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i],
4569 i, TCP_TRK_REQ_LOG_ALLOCFAIL, 0, 0);
4573 for(i = 0, allocated = 0; i < MAX_TCP_TRK_REQ; i++) {
4574 fil = &tp->t_tcpreq_info[i];
4575 if (fil->flags == TCP_TRK_TRACK_FLG_EMPTY) {
4577 fil->flags = TCP_TRK_TRACK_FLG_USED;
4578 fil->timestamp = req->timestamp;
4579 fil->localtime = ts;
4580 fil->start = req->start;
4581 if (req->flags & TCP_LOG_HTTPD_RANGE_END) {
4582 fil->end = req->end;
4585 fil->flags |= TCP_TRK_TRACK_FLG_OPEN;
4588 * We can set the min boundaries to the TCP Sequence space,
4589 * but it might be found to be further up when sendfile
4590 * actually runs on this range (if it ever does).
4592 fil->sbcc_at_s = tptosocket(tp)->so_snd.sb_ccc;
4593 fil->start_seq = tp->snd_una +
4594 tptosocket(tp)->so_snd.sb_ccc;
4595 fil->end_seq = (fil->start_seq + ((uint32_t)(fil->end - fil->start)));
4596 if (tptosocket(tp)->so_snd.sb_tls_info) {
4598 * This session is doing TLS. Take a swag guess
4601 fil->end_seq += tcp_estimate_tls_overhead(
4602 tptosocket(tp), (fil->end - fil->start));
4605 if (fil->flags & TCP_TRK_TRACK_FLG_OPEN)
4606 tp->t_tcpreq_open++;
4608 tp->t_tcpreq_closed++;
4609 tcp_req_log_req_info(tp, fil, i,
4610 TCP_TRK_REQ_LOG_NEW, 0, 0);
4619 tcp_req_alloc_req(struct tcpcb *tp, union tcp_log_userdata *user, uint64_t ts)
4621 (void)tcp_req_alloc_req_full(tp, &user->tcp_req, ts, 1);
4626 tcp_log_socket_option(struct tcpcb *tp, uint32_t option_num, uint32_t option_val, int err)
4628 if (tcp_bblogging_on(tp)) {
4629 struct tcp_log_buffer *l;
4631 l = tcp_log_event(tp, NULL,
4632 &tptosocket(tp)->so_rcv,
4633 &tptosocket(tp)->so_snd,
4636 NULL, NULL, 0, NULL);
4638 l->tlb_flex1 = option_num;
4639 l->tlb_flex2 = option_val;
4645 tcp_get_srtt(struct tcpcb *tp, int granularity)
4649 KASSERT(granularity == TCP_TMR_GRANULARITY_USEC ||
4650 granularity == TCP_TMR_GRANULARITY_TICKS,
4651 ("%s: called with unexpected granularity %d", __func__,
4657 * We only support two granularities. If the stored granularity
4658 * does not match the granularity requested by the caller,
4659 * convert the stored value to the requested unit of granularity.
4661 if (tp->t_tmr_granularity != granularity) {
4662 if (granularity == TCP_TMR_GRANULARITY_USEC)
4663 srtt = TICKS_2_USEC(srtt);
4665 srtt = USEC_2_TICKS(srtt);
4669 * If the srtt is stored with ticks granularity, we need to
4670 * unshift to get the actual value. We do this after the
4671 * conversion above (if one was necessary) in order to maximize
4674 if (tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS)
4675 srtt = srtt >> TCP_RTT_SHIFT;
4681 tcp_account_for_send(struct tcpcb *tp, uint32_t len, uint8_t is_rxt,
4682 uint8_t is_tlp, bool hw_tls)
4687 tp->t_sndtlpbyte += len;
4689 /* To get total bytes sent you must add t_snd_rxt_bytes to t_sndbytes */
4691 tp->t_snd_rxt_bytes += len;
4693 tp->t_sndbytes += len;
4696 if (hw_tls && is_rxt && len != 0) {
4697 uint64_t rexmit_percent;
4699 rexmit_percent = (1000ULL * tp->t_snd_rxt_bytes) /
4700 (10ULL * (tp->t_snd_rxt_bytes + tp->t_sndbytes));
4701 if (rexmit_percent > ktls_ifnet_max_rexmit_pct)
4702 ktls_disable_ifnet(tp);