2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
40 #include "opt_kern_tls.h"
42 #include <sys/param.h>
43 #include <sys/systm.h>
45 #include <sys/callout.h>
46 #include <sys/eventhandler.h>
48 #include <sys/hhook.h>
50 #include <sys/kernel.h>
52 #include <sys/khelp.h>
57 #include <sys/qmath.h>
58 #include <sys/stats.h>
59 #include <sys/sysctl.h>
61 #include <sys/malloc.h>
62 #include <sys/refcount.h>
67 #include <sys/socket.h>
68 #include <sys/socketvar.h>
69 #include <sys/protosw.h>
70 #include <sys/random.h>
74 #include <net/route.h>
75 #include <net/route/nhop.h>
77 #include <net/if_var.h>
78 #include <net/if_private.h>
81 #include <netinet/in.h>
82 #include <netinet/in_fib.h>
83 #include <netinet/in_kdtrace.h>
84 #include <netinet/in_pcb.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/in_var.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h>
89 #include <netinet/ip_var.h>
91 #include <netinet/icmp6.h>
92 #include <netinet/ip6.h>
93 #include <netinet6/in6_fib.h>
94 #include <netinet6/in6_pcb.h>
95 #include <netinet6/ip6_var.h>
96 #include <netinet6/scope6_var.h>
97 #include <netinet6/nd6.h>
100 #include <netinet/tcp.h>
104 #include <netinet/tcp_fsm.h>
105 #include <netinet/tcp_seq.h>
106 #include <netinet/tcp_timer.h>
107 #include <netinet/tcp_var.h>
108 #include <netinet/tcp_ecn.h>
109 #include <netinet/tcp_log_buf.h>
110 #include <netinet/tcp_syncache.h>
111 #include <netinet/tcp_hpts.h>
112 #include <netinet/tcp_lro.h>
113 #include <netinet/cc/cc.h>
114 #include <netinet/tcpip.h>
115 #include <netinet/tcp_fastopen.h>
116 #include <netinet/tcp_accounting.h>
118 #include <netinet/tcp_pcap.h>
121 #include <netinet/tcp_offload.h>
123 #include <netinet/udp.h>
124 #include <netinet/udp_var.h>
126 #include <netinet6/tcp6_var.h>
129 #include <netipsec/ipsec_support.h>
131 #include <machine/in_cksum.h>
132 #include <crypto/siphash/siphash.h>
134 #include <security/mac/mac_framework.h>
137 static ip6proto_ctlinput_t tcp6_ctlinput;
138 static udp_tun_icmp_t tcp6_ctlinput_viaudp;
141 VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS;
143 VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS;
146 #ifdef TCP_SAD_DETECTION
147 /* Sack attack detection thresholds and such */
148 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, sack_attack,
149 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
150 "Sack Attack detection thresholds");
151 int32_t tcp_force_detection = 0;
152 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, force_detection,
154 &tcp_force_detection, 0,
155 "Do we force detection even if the INP has it off?");
156 int32_t tcp_sad_limit = 10000;
157 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, limit,
159 &tcp_sad_limit, 10000,
160 "If SaD is enabled, what is the limit to sendmap entries (0 = unlimited)?");
161 int32_t tcp_sack_to_ack_thresh = 700; /* 70 % */
162 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sack_to_ack_thresh,
164 &tcp_sack_to_ack_thresh, 700,
165 "Percentage of sacks to acks we must see above (10.1 percent is 101)?");
166 int32_t tcp_sack_to_move_thresh = 600; /* 60 % */
167 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, move_thresh,
169 &tcp_sack_to_move_thresh, 600,
170 "Percentage of sack moves we must see above (10.1 percent is 101)");
171 int32_t tcp_restoral_thresh = 650; /* 65 % (sack:2:ack -5%) */
172 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, restore_thresh,
174 &tcp_restoral_thresh, 550,
175 "Percentage of sack to ack percentage we must see below to restore(10.1 percent is 101)");
176 int32_t tcp_sad_decay_val = 800;
177 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, decay_per,
179 &tcp_sad_decay_val, 800,
180 "The decay percentage (10.1 percent equals 101 )");
181 int32_t tcp_map_minimum = 500;
182 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, nummaps,
184 &tcp_map_minimum, 500,
185 "Number of Map enteries before we start detection");
186 int32_t tcp_sad_pacing_interval = 2000;
187 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sad_pacing_int,
189 &tcp_sad_pacing_interval, 2000,
190 "What is the minimum pacing interval for a classified attacker?");
192 int32_t tcp_sad_low_pps = 100;
193 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sad_low_pps,
195 &tcp_sad_low_pps, 100,
196 "What is the input pps that below which we do not decay?");
198 uint32_t tcp_ack_war_time_window = 1000;
199 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_timewindow,
201 &tcp_ack_war_time_window, 1000,
202 "If the tcp_stack does ack-war prevention how many milliseconds are in its time window?");
203 uint32_t tcp_ack_war_cnt = 5;
204 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_cnt,
207 "If the tcp_stack does ack-war prevention how many acks can be sent in its time window?");
209 struct rwlock tcp_function_lock;
212 sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS)
217 error = sysctl_handle_int(oidp, &new, 0, req);
218 if (error == 0 && req->newptr) {
219 if (new < TCP_MINMSS)
227 SYSCTL_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt,
228 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
229 &VNET_NAME(tcp_mssdflt), 0, &sysctl_net_inet_tcp_mss_check, "I",
230 "Default TCP Maximum Segment Size");
234 sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS)
238 new = V_tcp_v6mssdflt;
239 error = sysctl_handle_int(oidp, &new, 0, req);
240 if (error == 0 && req->newptr) {
241 if (new < TCP_MINMSS)
244 V_tcp_v6mssdflt = new;
249 SYSCTL_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
250 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
251 &VNET_NAME(tcp_v6mssdflt), 0, &sysctl_net_inet_tcp_mss_v6_check, "I",
252 "Default TCP Maximum Segment Size for IPv6");
256 * Minimum MSS we accept and use. This prevents DoS attacks where
257 * we are forced to a ridiculous low MSS like 20 and send hundreds
258 * of packets instead of one. The effect scales with the available
259 * bandwidth and quickly saturates the CPU and network interface
260 * with packet generation and sending. Set to zero to disable MINMSS
261 * checking. This setting prevents us from sending too small packets.
263 VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS;
264 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_VNET | CTLFLAG_RW,
265 &VNET_NAME(tcp_minmss), 0,
266 "Minimum TCP Maximum Segment Size");
268 VNET_DEFINE(int, tcp_do_rfc1323) = 1;
269 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_VNET | CTLFLAG_RW,
270 &VNET_NAME(tcp_do_rfc1323), 0,
271 "Enable rfc1323 (high performance TCP) extensions");
274 * As of June 2021, several TCP stacks violate RFC 7323 from September 2014.
275 * Some stacks negotiate TS, but never send them after connection setup. Some
276 * stacks negotiate TS, but don't send them when sending keep-alive segments.
277 * These include modern widely deployed TCP stacks.
278 * Therefore tolerating violations for now...
280 VNET_DEFINE(int, tcp_tolerate_missing_ts) = 1;
281 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tolerate_missing_ts, CTLFLAG_VNET | CTLFLAG_RW,
282 &VNET_NAME(tcp_tolerate_missing_ts), 0,
283 "Tolerate missing TCP timestamps");
285 VNET_DEFINE(int, tcp_ts_offset_per_conn) = 1;
286 SYSCTL_INT(_net_inet_tcp, OID_AUTO, ts_offset_per_conn, CTLFLAG_VNET | CTLFLAG_RW,
287 &VNET_NAME(tcp_ts_offset_per_conn), 0,
288 "Initialize TCP timestamps per connection instead of per host pair");
290 /* How many connections are pacing */
291 static volatile uint32_t number_of_tcp_connections_pacing = 0;
292 static uint32_t shadow_num_connections = 0;
294 static int tcp_pacing_limit = 10000;
295 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pacing_limit, CTLFLAG_RW,
296 &tcp_pacing_limit, 1000,
297 "If the TCP stack does pacing, is there a limit (-1 = no, 0 = no pacing N = number of connections)");
299 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pacing_count, CTLFLAG_RD,
300 &shadow_num_connections, 0, "Number of TCP connections being paced");
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");
306 static int tcp_tcbhashsize;
307 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
308 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
310 static int do_tcpdrain = 1;
311 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
312 "Enable tcp_drain routine for extra help when low on mbufs");
314 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD,
315 &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs");
317 VNET_DEFINE_STATIC(int, icmp_may_rst) = 1;
318 #define V_icmp_may_rst VNET(icmp_may_rst)
319 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW,
320 &VNET_NAME(icmp_may_rst), 0,
321 "Certain ICMP unreachable messages may abort connections in SYN_SENT");
323 VNET_DEFINE_STATIC(int, tcp_isn_reseed_interval) = 0;
324 #define V_tcp_isn_reseed_interval VNET(tcp_isn_reseed_interval)
325 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW,
326 &VNET_NAME(tcp_isn_reseed_interval), 0,
327 "Seconds between reseeding of ISN secret");
329 static int tcp_soreceive_stream;
330 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN,
331 &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets");
333 VNET_DEFINE(uma_zone_t, sack_hole_zone);
334 #define V_sack_hole_zone VNET(sack_hole_zone)
335 VNET_DEFINE(uint32_t, tcp_map_entries_limit) = 0; /* unlimited */
337 sysctl_net_inet_tcp_map_limit_check(SYSCTL_HANDLER_ARGS)
342 new = V_tcp_map_entries_limit;
343 error = sysctl_handle_int(oidp, &new, 0, req);
344 if (error == 0 && req->newptr) {
345 /* only allow "0" and value > minimum */
346 if (new > 0 && new < TCP_MIN_MAP_ENTRIES_LIMIT)
349 V_tcp_map_entries_limit = new;
353 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, map_limit,
354 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
355 &VNET_NAME(tcp_map_entries_limit), 0,
356 &sysctl_net_inet_tcp_map_limit_check, "IU",
357 "Total sendmap entries limit");
359 VNET_DEFINE(uint32_t, tcp_map_split_limit) = 0; /* unlimited */
360 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, split_limit, CTLFLAG_VNET | CTLFLAG_RW,
361 &VNET_NAME(tcp_map_split_limit), 0,
362 "Total sendmap split entries limit");
365 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]);
368 #define TS_OFFSET_SECRET_LENGTH SIPHASH_KEY_LENGTH
369 VNET_DEFINE_STATIC(u_char, ts_offset_secret[TS_OFFSET_SECRET_LENGTH]);
370 #define V_ts_offset_secret VNET(ts_offset_secret)
372 static int tcp_default_fb_init(struct tcpcb *tp, void **ptr);
373 static void tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged);
374 static int tcp_default_handoff_ok(struct tcpcb *tp);
375 static struct inpcb *tcp_notify(struct inpcb *, int);
376 static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int);
377 static struct inpcb *tcp_mtudisc(struct inpcb *, int);
378 static struct inpcb *tcp_drop_syn_sent(struct inpcb *, int);
379 static char * tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th,
380 const void *ip4hdr, const void *ip6hdr);
381 static ipproto_ctlinput_t tcp_ctlinput;
382 static udp_tun_icmp_t tcp_ctlinput_viaudp;
384 static struct tcp_function_block tcp_def_funcblk = {
385 .tfb_tcp_block_name = "freebsd",
386 .tfb_tcp_output = tcp_default_output,
387 .tfb_tcp_do_segment = tcp_do_segment,
388 .tfb_tcp_ctloutput = tcp_default_ctloutput,
389 .tfb_tcp_handoff_ok = tcp_default_handoff_ok,
390 .tfb_tcp_fb_init = tcp_default_fb_init,
391 .tfb_tcp_fb_fini = tcp_default_fb_fini,
394 static int tcp_fb_cnt = 0;
395 struct tcp_funchead t_functions;
396 static struct tcp_function_block *tcp_func_set_ptr = &tcp_def_funcblk;
399 tcp_record_dsack(struct tcpcb *tp, tcp_seq start, tcp_seq end, int tlp)
401 TCPSTAT_INC(tcps_dsack_count);
404 if (SEQ_GT(end, start)) {
405 tp->t_dsack_bytes += (end - start);
406 TCPSTAT_ADD(tcps_dsack_bytes, (end - start));
408 tp->t_dsack_tlp_bytes += (start - end);
409 TCPSTAT_ADD(tcps_dsack_bytes, (start - end));
412 if (SEQ_GT(end, start)) {
413 tp->t_dsack_bytes += (end - start);
414 TCPSTAT_ADD(tcps_dsack_tlp_bytes, (end - start));
416 tp->t_dsack_tlp_bytes += (start - end);
417 TCPSTAT_ADD(tcps_dsack_tlp_bytes, (start - end));
422 static struct tcp_function_block *
423 find_tcp_functions_locked(struct tcp_function_set *fs)
425 struct tcp_function *f;
426 struct tcp_function_block *blk=NULL;
428 TAILQ_FOREACH(f, &t_functions, tf_next) {
429 if (strcmp(f->tf_name, fs->function_set_name) == 0) {
437 static struct tcp_function_block *
438 find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s)
440 struct tcp_function_block *rblk=NULL;
441 struct tcp_function *f;
443 TAILQ_FOREACH(f, &t_functions, tf_next) {
444 if (f->tf_fb == blk) {
455 struct tcp_function_block *
456 find_and_ref_tcp_functions(struct tcp_function_set *fs)
458 struct tcp_function_block *blk;
460 rw_rlock(&tcp_function_lock);
461 blk = find_tcp_functions_locked(fs);
463 refcount_acquire(&blk->tfb_refcnt);
464 rw_runlock(&tcp_function_lock);
468 struct tcp_function_block *
469 find_and_ref_tcp_fb(struct tcp_function_block *blk)
471 struct tcp_function_block *rblk;
473 rw_rlock(&tcp_function_lock);
474 rblk = find_tcp_fb_locked(blk, NULL);
476 refcount_acquire(&rblk->tfb_refcnt);
477 rw_runlock(&tcp_function_lock);
481 /* Find a matching alias for the given tcp_function_block. */
483 find_tcp_function_alias(struct tcp_function_block *blk,
484 struct tcp_function_set *fs)
486 struct tcp_function *f;
490 rw_rlock(&tcp_function_lock);
491 TAILQ_FOREACH(f, &t_functions, tf_next) {
492 if ((f->tf_fb == blk) &&
493 (strncmp(f->tf_name, blk->tfb_tcp_block_name,
494 TCP_FUNCTION_NAME_LEN_MAX) != 0)) {
495 /* Matching function block with different name. */
496 strncpy(fs->function_set_name, f->tf_name,
497 TCP_FUNCTION_NAME_LEN_MAX);
502 /* Null terminate the string appropriately. */
504 fs->function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
506 fs->function_set_name[0] = '\0';
508 rw_runlock(&tcp_function_lock);
512 static struct tcp_function_block *
513 find_and_ref_tcp_default_fb(void)
515 struct tcp_function_block *rblk;
517 rw_rlock(&tcp_function_lock);
518 rblk = tcp_func_set_ptr;
519 refcount_acquire(&rblk->tfb_refcnt);
520 rw_runlock(&tcp_function_lock);
525 tcp_switch_back_to_default(struct tcpcb *tp)
527 struct tcp_function_block *tfb;
530 KASSERT(tp->t_fb != &tcp_def_funcblk,
531 ("%s: called by the built-in default stack", __func__));
534 * Now, we'll find a new function block to use.
535 * Start by trying the current user-selected
536 * default, unless this stack is the user-selected
539 tfb = find_and_ref_tcp_default_fb();
540 if (tfb == tp->t_fb) {
541 refcount_release(&tfb->tfb_refcnt);
544 /* Does the stack accept this connection? */
545 if (tfb != NULL && tfb->tfb_tcp_handoff_ok != NULL &&
546 (*tfb->tfb_tcp_handoff_ok)(tp)) {
547 refcount_release(&tfb->tfb_refcnt);
550 /* Try to use that stack. */
552 /* Initialize the new stack. If it succeeds, we are done. */
553 if (tfb->tfb_tcp_fb_init == NULL ||
554 (*tfb->tfb_tcp_fb_init)(tp, &ptr) == 0) {
555 /* Release the old stack */
556 if (tp->t_fb->tfb_tcp_fb_fini != NULL)
557 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
558 refcount_release(&tp->t_fb->tfb_refcnt);
559 /* Now set in all the pointers */
565 * Initialization failed. Release the reference count on
566 * the looked up default stack.
568 refcount_release(&tfb->tfb_refcnt);
572 * If that wasn't feasible, use the built-in default
573 * stack which is not allowed to reject anyone.
575 tfb = find_and_ref_tcp_fb(&tcp_def_funcblk);
577 /* there always should be a default */
578 panic("Can't refer to tcp_def_funcblk");
580 if (tfb->tfb_tcp_handoff_ok != NULL) {
581 if ((*tfb->tfb_tcp_handoff_ok) (tp)) {
582 /* The default stack cannot say no */
583 panic("Default stack rejects a new session?");
586 if (tfb->tfb_tcp_fb_init != NULL &&
587 (*tfb->tfb_tcp_fb_init)(tp, &ptr)) {
588 /* The default stack cannot fail */
589 panic("Default stack initialization failed");
591 /* Now release the old stack */
592 if (tp->t_fb->tfb_tcp_fb_fini != NULL)
593 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
594 refcount_release(&tp->t_fb->tfb_refcnt);
595 /* And set in the pointers to the new */
601 tcp_recv_udp_tunneled_packet(struct mbuf *m, int off, struct inpcb *inp,
602 const struct sockaddr *sa, void *ctx)
613 TCPSTAT_INC(tcps_tunneled_pkts);
614 if ((m->m_flags & M_PKTHDR) == 0) {
615 /* Can't handle one that is not a pkt hdr */
616 TCPSTAT_INC(tcps_tunneled_errs);
619 thlen = sizeof(struct tcphdr);
620 if (m->m_len < off + sizeof(struct udphdr) + thlen &&
621 (m = m_pullup(m, off + sizeof(struct udphdr) + thlen)) == NULL) {
622 TCPSTAT_INC(tcps_tunneled_errs);
625 iph = mtod(m, struct ip *);
626 uh = (struct udphdr *)((caddr_t)iph + off);
627 th = (struct tcphdr *)(uh + 1);
628 thlen = th->th_off << 2;
629 if (m->m_len < off + sizeof(struct udphdr) + thlen) {
630 m = m_pullup(m, off + sizeof(struct udphdr) + thlen);
632 TCPSTAT_INC(tcps_tunneled_errs);
635 iph = mtod(m, struct ip *);
636 uh = (struct udphdr *)((caddr_t)iph + off);
637 th = (struct tcphdr *)(uh + 1);
640 m->m_pkthdr.tcp_tun_port = port = uh->uh_sport;
641 bcopy(th, uh, m->m_len - off);
642 m->m_len -= sizeof(struct udphdr);
643 m->m_pkthdr.len -= sizeof(struct udphdr);
645 * We use the same algorithm for
646 * both UDP and TCP for c-sum. So
647 * the code in tcp_input will skip
648 * the checksum. So we do nothing
649 * with the flag (m->m_pkthdr.csum_flags).
654 iph->ip_len = htons(ntohs(iph->ip_len) - sizeof(struct udphdr));
655 tcp_input_with_port(&m, &off, IPPROTO_TCP, port);
659 case IPV6_VERSION >> 4:
660 ip6 = mtod(m, struct ip6_hdr *);
661 ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) - sizeof(struct udphdr));
662 tcp6_input_with_port(&m, &off, IPPROTO_TCP, port);
677 sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS)
680 struct tcp_function_set fs;
681 struct tcp_function_block *blk;
683 memset(&fs, 0, sizeof(fs));
684 rw_rlock(&tcp_function_lock);
685 blk = find_tcp_fb_locked(tcp_func_set_ptr, NULL);
688 strcpy(fs.function_set_name, blk->tfb_tcp_block_name);
689 fs.pcbcnt = blk->tfb_refcnt;
691 rw_runlock(&tcp_function_lock);
692 error = sysctl_handle_string(oidp, fs.function_set_name,
693 sizeof(fs.function_set_name), req);
695 /* Check for error or no change */
696 if (error != 0 || req->newptr == NULL)
699 rw_wlock(&tcp_function_lock);
700 blk = find_tcp_functions_locked(&fs);
702 (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) {
706 tcp_func_set_ptr = blk;
708 rw_wunlock(&tcp_function_lock);
712 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default,
713 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
714 NULL, 0, sysctl_net_inet_default_tcp_functions, "A",
715 "Set/get the default TCP functions");
718 sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS)
720 int error, cnt, linesz;
721 struct tcp_function *f;
727 rw_rlock(&tcp_function_lock);
728 TAILQ_FOREACH(f, &t_functions, tf_next) {
731 rw_runlock(&tcp_function_lock);
733 bufsz = (cnt+2) * ((TCP_FUNCTION_NAME_LEN_MAX * 2) + 13) + 1;
734 buffer = malloc(bufsz, M_TEMP, M_WAITOK);
739 linesz = snprintf(cp, bufsz, "\n%-32s%c %-32s %s\n", "Stack", 'D',
740 "Alias", "PCB count");
745 rw_rlock(&tcp_function_lock);
746 TAILQ_FOREACH(f, &t_functions, tf_next) {
747 alias = (f->tf_name != f->tf_fb->tfb_tcp_block_name);
748 linesz = snprintf(cp, bufsz, "%-32s%c %-32s %u\n",
749 f->tf_fb->tfb_tcp_block_name,
750 (f->tf_fb == tcp_func_set_ptr) ? '*' : ' ',
751 alias ? f->tf_name : "-",
752 f->tf_fb->tfb_refcnt);
753 if (linesz >= bufsz) {
761 rw_runlock(&tcp_function_lock);
763 error = sysctl_handle_string(oidp, buffer, outsz + 1, req);
764 free(buffer, M_TEMP);
768 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available,
769 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
770 NULL, 0, sysctl_net_inet_list_available, "A",
771 "list available TCP Function sets");
773 VNET_DEFINE(int, tcp_udp_tunneling_port) = TCP_TUNNELING_PORT_DEFAULT;
776 VNET_DEFINE(struct socket *, udp4_tun_socket) = NULL;
777 #define V_udp4_tun_socket VNET(udp4_tun_socket)
780 VNET_DEFINE(struct socket *, udp6_tun_socket) = NULL;
781 #define V_udp6_tun_socket VNET(udp6_tun_socket)
784 static struct sx tcpoudp_lock;
787 tcp_over_udp_stop(void)
790 sx_assert(&tcpoudp_lock, SA_XLOCKED);
793 if (V_udp4_tun_socket != NULL) {
794 soclose(V_udp4_tun_socket);
795 V_udp4_tun_socket = NULL;
799 if (V_udp6_tun_socket != NULL) {
800 soclose(V_udp6_tun_socket);
801 V_udp6_tun_socket = NULL;
807 tcp_over_udp_start(void)
812 struct sockaddr_in sin;
815 struct sockaddr_in6 sin6;
818 sx_assert(&tcpoudp_lock, SA_XLOCKED);
820 port = V_tcp_udp_tunneling_port;
821 if (ntohs(port) == 0) {
822 /* Must have a port set */
826 if (V_udp4_tun_socket != NULL) {
827 /* Already running -- must stop first */
832 if (V_udp6_tun_socket != NULL) {
833 /* Already running -- must stop first */
838 if ((ret = socreate(PF_INET, &V_udp4_tun_socket,
839 SOCK_DGRAM, IPPROTO_UDP,
840 curthread->td_ucred, curthread))) {
844 /* Call the special UDP hook. */
845 if ((ret = udp_set_kernel_tunneling(V_udp4_tun_socket,
846 tcp_recv_udp_tunneled_packet,
852 /* Ok, we have a socket, bind it to the port. */
853 memset(&sin, 0, sizeof(struct sockaddr_in));
854 sin.sin_len = sizeof(struct sockaddr_in);
855 sin.sin_family = AF_INET;
856 sin.sin_port = htons(port);
857 if ((ret = sobind(V_udp4_tun_socket,
858 (struct sockaddr *)&sin, curthread))) {
864 if ((ret = socreate(PF_INET6, &V_udp6_tun_socket,
865 SOCK_DGRAM, IPPROTO_UDP,
866 curthread->td_ucred, curthread))) {
870 /* Call the special UDP hook. */
871 if ((ret = udp_set_kernel_tunneling(V_udp6_tun_socket,
872 tcp_recv_udp_tunneled_packet,
873 tcp6_ctlinput_viaudp,
878 /* Ok, we have a socket, bind it to the port. */
879 memset(&sin6, 0, sizeof(struct sockaddr_in6));
880 sin6.sin6_len = sizeof(struct sockaddr_in6);
881 sin6.sin6_family = AF_INET6;
882 sin6.sin6_port = htons(port);
883 if ((ret = sobind(V_udp6_tun_socket,
884 (struct sockaddr *)&sin6, curthread))) {
893 sysctl_net_inet_tcp_udp_tunneling_port_check(SYSCTL_HANDLER_ARGS)
898 old = V_tcp_udp_tunneling_port;
900 error = sysctl_handle_int(oidp, &new, 0, req);
902 (req->newptr != NULL)) {
903 if ((new < TCP_TUNNELING_PORT_MIN) ||
904 (new > TCP_TUNNELING_PORT_MAX)) {
907 sx_xlock(&tcpoudp_lock);
908 V_tcp_udp_tunneling_port = new;
913 error = tcp_over_udp_start();
915 V_tcp_udp_tunneling_port = 0;
918 sx_xunlock(&tcpoudp_lock);
924 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_port,
925 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
926 &VNET_NAME(tcp_udp_tunneling_port),
927 0, &sysctl_net_inet_tcp_udp_tunneling_port_check, "IU",
928 "Tunneling port for tcp over udp");
930 VNET_DEFINE(int, tcp_udp_tunneling_overhead) = TCP_TUNNELING_OVERHEAD_DEFAULT;
933 sysctl_net_inet_tcp_udp_tunneling_overhead_check(SYSCTL_HANDLER_ARGS)
937 new = V_tcp_udp_tunneling_overhead;
938 error = sysctl_handle_int(oidp, &new, 0, req);
939 if (error == 0 && req->newptr) {
940 if ((new < TCP_TUNNELING_OVERHEAD_MIN) ||
941 (new > TCP_TUNNELING_OVERHEAD_MAX))
944 V_tcp_udp_tunneling_overhead = new;
949 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_overhead,
950 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
951 &VNET_NAME(tcp_udp_tunneling_overhead),
952 0, &sysctl_net_inet_tcp_udp_tunneling_overhead_check, "IU",
953 "MSS reduction when using tcp over udp");
956 * Exports one (struct tcp_function_info) for each alias/name.
959 sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS)
962 struct tcp_function *f;
963 struct tcp_function_info tfi;
966 * We don't allow writes.
968 if (req->newptr != NULL)
972 * Wire the old buffer so we can directly copy the functions to
973 * user space without dropping the lock.
975 if (req->oldptr != NULL) {
976 error = sysctl_wire_old_buffer(req, 0);
982 * Walk the list and copy out matching entries. If INVARIANTS
983 * is compiled in, also walk the list to verify the length of
984 * the list matches what we have recorded.
986 rw_rlock(&tcp_function_lock);
990 if (req->oldptr == NULL) {
995 TAILQ_FOREACH(f, &t_functions, tf_next) {
999 if (req->oldptr != NULL) {
1000 bzero(&tfi, sizeof(tfi));
1001 tfi.tfi_refcnt = f->tf_fb->tfb_refcnt;
1002 tfi.tfi_id = f->tf_fb->tfb_id;
1003 (void)strlcpy(tfi.tfi_alias, f->tf_name,
1004 sizeof(tfi.tfi_alias));
1005 (void)strlcpy(tfi.tfi_name,
1006 f->tf_fb->tfb_tcp_block_name, sizeof(tfi.tfi_name));
1007 error = SYSCTL_OUT(req, &tfi, sizeof(tfi));
1009 * Don't stop on error, as that is the
1010 * mechanism we use to accumulate length
1011 * information if the buffer was too short.
1015 KASSERT(cnt == tcp_fb_cnt,
1016 ("%s: cnt (%d) != tcp_fb_cnt (%d)", __func__, cnt, tcp_fb_cnt));
1020 rw_runlock(&tcp_function_lock);
1021 if (req->oldptr == NULL)
1022 error = SYSCTL_OUT(req, NULL,
1023 (cnt + 1) * sizeof(struct tcp_function_info));
1028 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, function_info,
1029 CTLTYPE_OPAQUE | CTLFLAG_SKIP | CTLFLAG_RD | CTLFLAG_MPSAFE,
1030 NULL, 0, sysctl_net_inet_list_func_info, "S,tcp_function_info",
1031 "List TCP function block name-to-ID mappings");
1034 * tfb_tcp_handoff_ok() function for the default stack.
1035 * Note that we'll basically try to take all comers.
1038 tcp_default_handoff_ok(struct tcpcb *tp)
1045 * tfb_tcp_fb_init() function for the default stack.
1047 * This handles making sure we have appropriate timers set if you are
1048 * transitioning a socket that has some amount of setup done.
1050 * The init() fuction from the default can *never* return non-zero i.e.
1051 * it is required to always succeed since it is the stack of last resort!
1054 tcp_default_fb_init(struct tcpcb *tp, void **ptr)
1056 struct socket *so = tptosocket(tp);
1059 INP_WLOCK_ASSERT(tptoinpcb(tp));
1060 /* We don't use the pointer */
1063 KASSERT(tp->t_state >= 0 && tp->t_state < TCPS_TIME_WAIT,
1064 ("%s: connection %p in unexpected state %d", __func__, tp,
1067 /* Make sure we get no interesting mbuf queuing behavior */
1068 /* All mbuf queue/ack compress flags should be off */
1069 tcp_lro_features_off(tptoinpcb(tp));
1071 /* Cancel the GP measurement in progress */
1072 tp->t_flags &= ~TF_GPUTINPROG;
1073 /* Validate the timers are not in usec, if they are convert */
1074 tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
1075 if ((tp->t_state == TCPS_SYN_SENT) ||
1076 (tp->t_state == TCPS_SYN_RECEIVED))
1077 rexmt = tcp_rexmit_initial * tcp_backoff[tp->t_rxtshift];
1079 rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
1080 if (tp->t_rxtshift == 0)
1081 tp->t_rxtcur = rexmt;
1083 TCPT_RANGESET(tp->t_rxtcur, rexmt, tp->t_rttmin, TCPTV_REXMTMAX);
1086 * Nothing to do for ESTABLISHED or LISTEN states. And, we don't
1087 * know what to do for unexpected states (which includes TIME_WAIT).
1089 if (tp->t_state <= TCPS_LISTEN || tp->t_state >= TCPS_TIME_WAIT)
1093 * Make sure some kind of transmission timer is set if there is
1096 if ((!TCPS_HAVEESTABLISHED(tp->t_state) || sbavail(&so->so_snd) ||
1097 tp->snd_una != tp->snd_max) && !(tcp_timer_active(tp, TT_REXMT) ||
1098 tcp_timer_active(tp, TT_PERSIST))) {
1100 * If the session has established and it looks like it should
1101 * be in the persist state, set the persist timer. Otherwise,
1102 * set the retransmit timer.
1104 if (TCPS_HAVEESTABLISHED(tp->t_state) && tp->snd_wnd == 0 &&
1105 (int32_t)(tp->snd_nxt - tp->snd_una) <
1106 (int32_t)sbavail(&so->so_snd))
1109 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1112 /* All non-embryonic sessions get a keepalive timer. */
1113 if (!tcp_timer_active(tp, TT_KEEP))
1114 tcp_timer_activate(tp, TT_KEEP,
1115 TCPS_HAVEESTABLISHED(tp->t_state) ? TP_KEEPIDLE(tp) :
1119 * Make sure critical variables are initialized
1120 * if transitioning while in Recovery.
1122 if IN_FASTRECOVERY(tp->t_flags) {
1123 if (tp->sackhint.recover_fs == 0)
1124 tp->sackhint.recover_fs = max(1,
1125 tp->snd_nxt - tp->snd_una);
1132 * tfb_tcp_fb_fini() function for the default stack.
1134 * This changes state as necessary (or prudent) to prepare for another stack
1135 * to assume responsibility for the connection.
1138 tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged)
1141 INP_WLOCK_ASSERT(tptoinpcb(tp));
1145 * Target size of TCP PCB hash tables. Must be a power of two.
1147 * Note that this can be overridden by the kernel environment
1148 * variable net.inet.tcp.tcbhashsize
1151 #define TCBHASHSIZE 0
1154 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers");
1155 MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory");
1157 static struct mtx isn_mtx;
1159 #define ISN_LOCK_INIT() mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
1160 #define ISN_LOCK() mtx_lock(&isn_mtx)
1161 #define ISN_UNLOCK() mtx_unlock(&isn_mtx)
1163 INPCBSTORAGE_DEFINE(tcpcbstor, tcpcb, "tcpinp", "tcp_inpcb", "tcp", "tcphash");
1166 * Take a value and get the next power of 2 that doesn't overflow.
1167 * Used to size the tcp_inpcb hash buckets.
1170 maketcp_hashsize(int size)
1176 * get the next power of 2 higher than maxsockets.
1178 hashsize = 1 << fls(size);
1179 /* catch overflow, and just go one power of 2 smaller */
1180 if (hashsize < size) {
1181 hashsize = 1 << (fls(size) - 1);
1186 static volatile int next_tcp_stack_id = 1;
1189 * Register a TCP function block with the name provided in the names
1190 * array. (Note that this function does NOT automatically register
1191 * blk->tfb_tcp_block_name as a stack name. Therefore, you should
1192 * explicitly include blk->tfb_tcp_block_name in the list of names if
1193 * you wish to register the stack with that name.)
1195 * Either all name registrations will succeed or all will fail. If
1196 * a name registration fails, the function will update the num_names
1197 * argument to point to the array index of the name that encountered
1200 * Returns 0 on success, or an error code on failure.
1203 register_tcp_functions_as_names(struct tcp_function_block *blk, int wait,
1204 const char *names[], int *num_names)
1206 struct tcp_function *n;
1207 struct tcp_function_set fs;
1210 KASSERT(names != NULL && *num_names > 0,
1211 ("%s: Called with 0-length name list", __func__));
1212 KASSERT(names != NULL, ("%s: Called with NULL name list", __func__));
1213 KASSERT(rw_initialized(&tcp_function_lock),
1214 ("%s: called too early", __func__));
1216 if ((blk->tfb_tcp_output == NULL) ||
1217 (blk->tfb_tcp_do_segment == NULL) ||
1218 (blk->tfb_tcp_ctloutput == NULL) ||
1219 (strlen(blk->tfb_tcp_block_name) == 0)) {
1221 * These functions are required and you
1228 if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) {
1233 refcount_init(&blk->tfb_refcnt, 0);
1234 blk->tfb_id = atomic_fetchadd_int(&next_tcp_stack_id, 1);
1235 for (i = 0; i < *num_names; i++) {
1236 n = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait);
1243 (void)strlcpy(fs.function_set_name, names[i],
1244 sizeof(fs.function_set_name));
1245 rw_wlock(&tcp_function_lock);
1246 if (find_tcp_functions_locked(&fs) != NULL) {
1247 /* Duplicate name space not allowed */
1248 rw_wunlock(&tcp_function_lock);
1249 free(n, M_TCPFUNCTIONS);
1253 (void)strlcpy(n->tf_name, names[i], sizeof(n->tf_name));
1254 TAILQ_INSERT_TAIL(&t_functions, n, tf_next);
1256 rw_wunlock(&tcp_function_lock);
1262 * Deregister the names we just added. Because registration failed
1263 * for names[i], we don't need to deregister that name.
1266 rw_wlock(&tcp_function_lock);
1268 TAILQ_FOREACH(n, &t_functions, tf_next) {
1269 if (!strncmp(n->tf_name, names[i],
1270 TCP_FUNCTION_NAME_LEN_MAX)) {
1271 TAILQ_REMOVE(&t_functions, n, tf_next);
1274 free(n, M_TCPFUNCTIONS);
1279 rw_wunlock(&tcp_function_lock);
1284 * Register a TCP function block using the name provided in the name
1287 * Returns 0 on success, or an error code on failure.
1290 register_tcp_functions_as_name(struct tcp_function_block *blk, const char *name,
1293 const char *name_list[1];
1298 name_list[0] = name;
1300 name_list[0] = blk->tfb_tcp_block_name;
1301 rv = register_tcp_functions_as_names(blk, wait, name_list, &num_names);
1306 * Register a TCP function block using the name defined in
1307 * blk->tfb_tcp_block_name.
1309 * Returns 0 on success, or an error code on failure.
1312 register_tcp_functions(struct tcp_function_block *blk, int wait)
1315 return (register_tcp_functions_as_name(blk, NULL, wait));
1319 * Deregister all names associated with a function block. This
1320 * functionally removes the function block from use within the system.
1322 * When called with a true quiesce argument, mark the function block
1323 * as being removed so no more stacks will use it and determine
1324 * whether the removal would succeed.
1326 * When called with a false quiesce argument, actually attempt the
1329 * When called with a force argument, attempt to switch all TCBs to
1330 * use the default stack instead of returning EBUSY.
1332 * Returns 0 on success (or if the removal would succeed, or an error
1336 deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce,
1339 struct tcp_function *f;
1341 if (blk == &tcp_def_funcblk) {
1342 /* You can't un-register the default */
1345 rw_wlock(&tcp_function_lock);
1346 if (blk == tcp_func_set_ptr) {
1347 /* You can't free the current default */
1348 rw_wunlock(&tcp_function_lock);
1351 /* Mark the block so no more stacks can use it. */
1352 blk->tfb_flags |= TCP_FUNC_BEING_REMOVED;
1354 * If TCBs are still attached to the stack, attempt to switch them
1355 * to the default stack.
1357 if (force && blk->tfb_refcnt) {
1358 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
1359 INPLOOKUP_WLOCKPCB);
1362 VNET_ITERATOR_DECL(vnet_iter);
1364 rw_wunlock(&tcp_function_lock);
1367 VNET_FOREACH(vnet_iter) {
1368 CURVNET_SET(vnet_iter);
1369 while ((inp = inp_next(&inpi)) != NULL) {
1370 tp = intotcpcb(inp);
1371 if (tp == NULL || tp->t_fb != blk)
1373 tcp_switch_back_to_default(tp);
1377 VNET_LIST_RUNLOCK();
1379 rw_wlock(&tcp_function_lock);
1381 if (blk->tfb_refcnt) {
1382 /* TCBs still attached. */
1383 rw_wunlock(&tcp_function_lock);
1388 rw_wunlock(&tcp_function_lock);
1391 /* Remove any function names that map to this function block. */
1392 while (find_tcp_fb_locked(blk, &f) != NULL) {
1393 TAILQ_REMOVE(&t_functions, f, tf_next);
1396 free(f, M_TCPFUNCTIONS);
1398 rw_wunlock(&tcp_function_lock);
1405 struct epoch_tracker et;
1406 VNET_ITERATOR_DECL(vnet_iter);
1411 NET_EPOCH_ENTER(et);
1412 VNET_LIST_RLOCK_NOSLEEP();
1413 VNET_FOREACH(vnet_iter) {
1414 CURVNET_SET(vnet_iter);
1415 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
1416 INPLOOKUP_WLOCKPCB);
1421 * Walk the tcpbs, if existing, and flush the reassembly queue,
1422 * if there is one...
1423 * XXX: The "Net/3" implementation doesn't imply that the TCP
1424 * reassembly queue should be flushed, but in a situation
1425 * where we're really low on mbufs, this is potentially
1428 while ((inpb = inp_next(&inpi)) != NULL) {
1429 if ((tcpb = intotcpcb(inpb)) != NULL) {
1430 tcp_reass_flush(tcpb);
1431 tcp_clean_sackreport(tcpb);
1433 tcp_log_drain(tcpb);
1436 if (tcp_pcap_aggressive_free) {
1437 /* Free the TCP PCAP queues. */
1438 tcp_pcap_drain(&(tcpb->t_inpkts));
1439 tcp_pcap_drain(&(tcpb->t_outpkts));
1446 VNET_LIST_RUNLOCK_NOSLEEP();
1451 tcp_vnet_init(void *arg __unused)
1455 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN,
1456 &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1457 printf("%s: WARNING: unable to register helper hook\n", __func__);
1458 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT,
1459 &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1460 printf("%s: WARNING: unable to register helper hook\n", __func__);
1463 if (tcp_stats_init())
1464 printf("%s: WARNING: unable to initialise TCP stats\n",
1467 in_pcbinfo_init(&V_tcbinfo, &tcpcbstor, tcp_tcbhashsize,
1473 TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack);
1474 V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
1475 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1477 tcp_fastopen_init();
1479 COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK);
1480 VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK);
1482 V_tcp_msl = TCPTV_MSL;
1484 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
1485 tcp_vnet_init, NULL);
1488 tcp_init(void *arg __unused)
1490 const char *tcbhash_tuneable;
1493 tcp_reass_global_init();
1495 /* XXX virtualize those below? */
1496 tcp_delacktime = TCPTV_DELACK;
1497 tcp_keepinit = TCPTV_KEEP_INIT;
1498 tcp_keepidle = TCPTV_KEEP_IDLE;
1499 tcp_keepintvl = TCPTV_KEEPINTVL;
1500 tcp_maxpersistidle = TCPTV_KEEP_IDLE;
1501 tcp_rexmit_initial = TCPTV_RTOBASE;
1502 if (tcp_rexmit_initial < 1)
1503 tcp_rexmit_initial = 1;
1504 tcp_rexmit_min = TCPTV_MIN;
1505 if (tcp_rexmit_min < 1)
1507 tcp_persmin = TCPTV_PERSMIN;
1508 tcp_persmax = TCPTV_PERSMAX;
1509 tcp_rexmit_slop = TCPTV_CPU_VAR;
1510 tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT;
1512 /* Setup the tcp function block list */
1513 TAILQ_INIT(&t_functions);
1514 rw_init(&tcp_function_lock, "tcp_func_lock");
1515 register_tcp_functions(&tcp_def_funcblk, M_WAITOK);
1516 sx_init(&tcpoudp_lock, "TCP over UDP configuration");
1518 /* Initialize the TCP logging data. */
1521 arc4rand(&V_ts_offset_secret, sizeof(V_ts_offset_secret), 0);
1523 if (tcp_soreceive_stream) {
1525 tcp_protosw.pr_soreceive = soreceive_stream;
1528 tcp6_protosw.pr_soreceive = soreceive_stream;
1533 max_protohdr_grow(sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
1535 max_protohdr_grow(sizeof(struct tcpiphdr));
1539 EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
1540 SHUTDOWN_PRI_DEFAULT);
1541 EVENTHANDLER_REGISTER(vm_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT);
1542 EVENTHANDLER_REGISTER(mbuf_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT);
1544 tcp_inp_lro_direct_queue = counter_u64_alloc(M_WAITOK);
1545 tcp_inp_lro_wokeup_queue = counter_u64_alloc(M_WAITOK);
1546 tcp_inp_lro_compressed = counter_u64_alloc(M_WAITOK);
1547 tcp_inp_lro_locks_taken = counter_u64_alloc(M_WAITOK);
1548 tcp_extra_mbuf = counter_u64_alloc(M_WAITOK);
1549 tcp_would_have_but = counter_u64_alloc(M_WAITOK);
1550 tcp_comp_total = counter_u64_alloc(M_WAITOK);
1551 tcp_uncomp_total = counter_u64_alloc(M_WAITOK);
1552 tcp_bad_csums = counter_u64_alloc(M_WAITOK);
1557 hashsize = TCBHASHSIZE;
1558 tcbhash_tuneable = "net.inet.tcp.tcbhashsize";
1559 TUNABLE_INT_FETCH(tcbhash_tuneable, &hashsize);
1560 if (hashsize == 0) {
1562 * Auto tune the hash size based on maxsockets.
1563 * A perfect hash would have a 1:1 mapping
1564 * (hashsize = maxsockets) however it's been
1565 * suggested that O(2) average is better.
1567 hashsize = maketcp_hashsize(maxsockets / 4);
1569 * Our historical default is 512,
1570 * do not autotune lower than this.
1575 printf("%s: %s auto tuned to %d\n", __func__,
1576 tcbhash_tuneable, hashsize);
1579 * We require a hashsize to be a power of two.
1580 * Previously if it was not a power of two we would just reset it
1581 * back to 512, which could be a nasty surprise if you did not notice
1582 * the error message.
1583 * Instead what we do is clip it to the closest power of two lower
1584 * than the specified hash value.
1586 if (!powerof2(hashsize)) {
1587 int oldhashsize = hashsize;
1589 hashsize = maketcp_hashsize(hashsize);
1590 /* prevent absurdly low value */
1593 printf("%s: WARNING: TCB hash size not a power of 2, "
1594 "clipped from %d to %d.\n", __func__, oldhashsize,
1597 tcp_tcbhashsize = hashsize;
1600 IPPROTO_REGISTER(IPPROTO_TCP, tcp_input, tcp_ctlinput);
1603 IP6PROTO_REGISTER(IPPROTO_TCP, tcp6_input, tcp6_ctlinput);
1606 SYSINIT(tcp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, tcp_init, NULL);
1610 tcp_destroy(void *unused __unused)
1618 * All our processes are gone, all our sockets should be cleaned
1619 * up, which means, we should be past the tcp_discardcb() calls.
1620 * Sleep to let all tcpcb timers really disappear and cleanup.
1623 INP_INFO_WLOCK(&V_tcbinfo);
1624 n = V_tcbinfo.ipi_count;
1625 INP_INFO_WUNLOCK(&V_tcbinfo);
1628 pause("tcpdes", hz / 10);
1632 in_pcbinfo_destroy(&V_tcbinfo);
1633 /* tcp_discardcb() clears the sack_holes up. */
1634 uma_zdestroy(V_sack_hole_zone);
1637 * Cannot free the zone until all tcpcbs are released as we attach
1638 * the allocations to them.
1640 tcp_fastopen_destroy();
1642 COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES);
1643 VNET_PCPUSTAT_FREE(tcpstat);
1646 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]);
1648 printf("%s: WARNING: unable to deregister helper hook "
1649 "type=%d, id=%d: error %d returned\n", __func__,
1650 HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error);
1652 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]);
1654 printf("%s: WARNING: unable to deregister helper hook "
1655 "type=%d, id=%d: error %d returned\n", __func__,
1656 HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error);
1660 VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_destroy, NULL);
1670 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
1671 * tcp_template used to store this data in mbufs, but we now recopy it out
1672 * of the tcpcb each time to conserve mbufs.
1675 tcpip_fillheaders(struct inpcb *inp, uint16_t port, void *ip_ptr, void *tcp_ptr)
1677 struct tcphdr *th = (struct tcphdr *)tcp_ptr;
1679 INP_WLOCK_ASSERT(inp);
1682 if ((inp->inp_vflag & INP_IPV6) != 0) {
1683 struct ip6_hdr *ip6;
1685 ip6 = (struct ip6_hdr *)ip_ptr;
1686 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
1687 (inp->inp_flow & IPV6_FLOWINFO_MASK);
1688 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
1689 (IPV6_VERSION & IPV6_VERSION_MASK);
1691 ip6->ip6_nxt = IPPROTO_TCP;
1693 ip6->ip6_nxt = IPPROTO_UDP;
1694 ip6->ip6_plen = htons(sizeof(struct tcphdr));
1695 ip6->ip6_src = inp->in6p_laddr;
1696 ip6->ip6_dst = inp->in6p_faddr;
1699 #if defined(INET6) && defined(INET)
1706 ip = (struct ip *)ip_ptr;
1707 ip->ip_v = IPVERSION;
1709 ip->ip_tos = inp->inp_ip_tos;
1713 ip->ip_ttl = inp->inp_ip_ttl;
1716 ip->ip_p = IPPROTO_TCP;
1718 ip->ip_p = IPPROTO_UDP;
1719 ip->ip_src = inp->inp_laddr;
1720 ip->ip_dst = inp->inp_faddr;
1723 th->th_sport = inp->inp_lport;
1724 th->th_dport = inp->inp_fport;
1728 tcp_set_flags(th, 0);
1731 th->th_sum = 0; /* in_pseudo() is called later for ipv4 */
1735 * Create template to be used to send tcp packets on a connection.
1736 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only
1737 * use for this function is in keepalives, which use tcp_respond.
1740 tcpip_maketemplate(struct inpcb *inp)
1744 t = malloc(sizeof(*t), M_TEMP, M_NOWAIT);
1747 tcpip_fillheaders(inp, 0, (void *)&t->tt_ipgen, (void *)&t->tt_t);
1752 * Send a single message to the TCP at address specified by
1753 * the given TCP/IP header. If m == NULL, then we make a copy
1754 * of the tcpiphdr at th and send directly to the addressed host.
1755 * This is used to force keep alive messages out using the TCP
1756 * template for a connection. If flags are given then we send
1757 * a message back to the TCP which originated the segment th,
1758 * and discard the mbuf containing it and any other attached mbufs.
1760 * In any case the ack and sequence number of the transmitted
1761 * segment are as specified by the parameters.
1763 * NOTE: If m != NULL, then th must point to *inside* the mbuf.
1766 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
1767 tcp_seq ack, tcp_seq seq, uint16_t flags)
1773 struct udphdr *uh = NULL;
1775 struct tcp_log_buffer *lgb;
1778 struct ip6_hdr *ip6;
1781 int optlen, tlen, win, ulen;
1787 int thflags = tcp_get_flags(th);
1790 KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
1794 isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4);
1800 inp = tptoinpcb(tp);
1801 INP_LOCK_ASSERT(inp);
1807 if (isipv6 && ip6 && (ip6->ip6_nxt == IPPROTO_UDP))
1808 port = m->m_pkthdr.tcp_tun_port;
1811 if (ip && (ip->ip_p == IPPROTO_UDP))
1812 port = m->m_pkthdr.tcp_tun_port;
1821 if (!(flags & TH_RST)) {
1822 win = sbspace(&inp->inp_socket->so_rcv);
1823 if (win > TCP_MAXWIN << tp->rcv_scale)
1824 win = TCP_MAXWIN << tp->rcv_scale;
1826 if ((tp->t_flags & TF_NOOPT) == 0)
1830 m = m_gethdr(M_NOWAIT, MT_DATA);
1833 m->m_data += max_linkhdr;
1836 bcopy((caddr_t)ip6, mtod(m, caddr_t),
1837 sizeof(struct ip6_hdr));
1838 ip6 = mtod(m, struct ip6_hdr *);
1839 nth = (struct tcphdr *)(ip6 + 1);
1841 /* Insert a UDP header */
1842 uh = (struct udphdr *)nth;
1843 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1844 uh->uh_dport = port;
1845 nth = (struct tcphdr *)(uh + 1);
1850 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
1851 ip = mtod(m, struct ip *);
1852 nth = (struct tcphdr *)(ip + 1);
1854 /* Insert a UDP header */
1855 uh = (struct udphdr *)nth;
1856 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1857 uh->uh_dport = port;
1858 nth = (struct tcphdr *)(uh + 1);
1861 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
1863 } else if ((!M_WRITABLE(m)) || (port != 0)) {
1866 /* Can't reuse 'm', allocate a new mbuf. */
1867 n = m_gethdr(M_NOWAIT, MT_DATA);
1873 if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
1879 n->m_data += max_linkhdr;
1880 /* m_len is set later */
1881 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
1884 bcopy((caddr_t)ip6, mtod(n, caddr_t),
1885 sizeof(struct ip6_hdr));
1886 ip6 = mtod(n, struct ip6_hdr *);
1887 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1888 nth = (struct tcphdr *)(ip6 + 1);
1890 /* Insert a UDP header */
1891 uh = (struct udphdr *)nth;
1892 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1893 uh->uh_dport = port;
1894 nth = (struct tcphdr *)(uh + 1);
1899 bcopy((caddr_t)ip, mtod(n, caddr_t), sizeof(struct ip));
1900 ip = mtod(n, struct ip *);
1901 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1902 nth = (struct tcphdr *)(ip + 1);
1904 /* Insert a UDP header */
1905 uh = (struct udphdr *)nth;
1906 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1907 uh->uh_dport = port;
1908 nth = (struct tcphdr *)(uh + 1);
1911 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
1912 xchg(nth->th_dport, nth->th_sport, uint16_t);
1919 * XXX MRT We inherit the FIB, which is lucky.
1923 m->m_data = (caddr_t)ipgen;
1924 /* m_len is set later */
1927 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1928 nth = (struct tcphdr *)(ip6 + 1);
1932 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1933 nth = (struct tcphdr *)(ip + 1);
1937 * this is usually a case when an extension header
1938 * exists between the IPv6 header and the
1941 nth->th_sport = th->th_sport;
1942 nth->th_dport = th->th_dport;
1944 xchg(nth->th_dport, nth->th_sport, uint16_t);
1950 tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
1952 #if defined(INET) && defined(INET6)
1956 tlen = sizeof (struct tcpiphdr);
1959 tlen += sizeof (struct udphdr);
1962 KASSERT(M_TRAILINGSPACE(m) >= tlen,
1963 ("Not enough trailing space for message (m=%p, need=%d, have=%ld)",
1964 m, tlen, (long)M_TRAILINGSPACE(m)));
1969 ect = tcp_ecn_output_established(tp, &flags, 0, false);
1970 /* Make sure we have room. */
1971 if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) {
1972 m->m_next = m_get(M_NOWAIT, MT_DATA);
1974 optp = mtod(m->m_next, u_char *);
1979 optp = (u_char *) (nth + 1);
1985 if (tp->t_flags & TF_RCVD_TSTMP) {
1986 to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
1987 to.to_tsecr = tp->ts_recent;
1988 to.to_flags |= TOF_TS;
1990 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1991 /* TCP-MD5 (RFC2385). */
1992 if (tp->t_flags & TF_SIGNATURE)
1993 to.to_flags |= TOF_SIGNATURE;
1995 /* Add the options. */
1996 tlen += optlen = tcp_addoptions(&to, optp);
1998 /* Update m_len in the correct mbuf. */
1999 optm->m_len += optlen;
2005 ulen = tlen - sizeof(struct ip6_hdr);
2006 uh->uh_ulen = htons(ulen);
2008 ip6->ip6_flow = htonl(ect << 20);
2009 ip6->ip6_vfc = IPV6_VERSION;
2011 ip6->ip6_nxt = IPPROTO_UDP;
2013 ip6->ip6_nxt = IPPROTO_TCP;
2014 ip6->ip6_plen = htons(tlen - sizeof(*ip6));
2017 #if defined(INET) && defined(INET6)
2023 ulen = tlen - sizeof(struct ip);
2024 uh->uh_ulen = htons(ulen);
2027 ip->ip_len = htons(tlen);
2028 ip->ip_ttl = V_ip_defttl;
2030 ip->ip_p = IPPROTO_UDP;
2032 ip->ip_p = IPPROTO_TCP;
2034 if (V_path_mtu_discovery)
2035 ip->ip_off |= htons(IP_DF);
2038 m->m_pkthdr.len = tlen;
2039 m->m_pkthdr.rcvif = NULL;
2043 * Packet is associated with a socket, so allow the
2044 * label of the response to reflect the socket label.
2046 INP_LOCK_ASSERT(inp);
2047 mac_inpcb_create_mbuf(inp, m);
2050 * Packet is not associated with a socket, so possibly
2051 * update the label in place.
2053 mac_netinet_tcp_reply(m);
2056 nth->th_seq = htonl(seq);
2057 nth->th_ack = htonl(ack);
2058 nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
2059 tcp_set_flags(nth, flags);
2061 nth->th_win = htons((u_short) (win >> tp->rcv_scale));
2063 nth->th_win = htons((u_short)win);
2066 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2067 if (to.to_flags & TOF_SIGNATURE) {
2068 if (!TCPMD5_ENABLED() ||
2069 TCPMD5_OUTPUT(m, nth, to.to_signature) != 0) {
2079 m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
2080 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2081 uh->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
2084 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2085 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2086 nth->th_sum = in6_cksum_pseudo(ip6,
2087 tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0);
2089 ip6->ip6_hlim = in6_selecthlim(inp, NULL);
2092 #if defined(INET6) && defined(INET)
2098 uh->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2099 htons(ulen + IPPROTO_UDP));
2100 m->m_pkthdr.csum_flags = CSUM_UDP;
2101 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2104 m->m_pkthdr.csum_flags = CSUM_TCP;
2105 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2106 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2107 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
2111 TCP_PROBE3(debug__output, tp, th, m);
2113 TCP_PROBE5(accept__refused, NULL, NULL, m, tp, nth);
2115 if ((tp != NULL) && tcp_bblogging_on(tp)) {
2116 if (INP_WLOCKED(inp)) {
2117 union tcp_log_stackspecific log;
2120 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2121 log.u_bbr.inhpts = inp->inp_in_hpts;
2122 log.u_bbr.flex8 = 4;
2123 log.u_bbr.pkts_out = tp->t_maxseg;
2124 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2125 log.u_bbr.delivered = 0;
2126 lgb = tcp_log_event(tp, nth, NULL, NULL, TCP_LOG_OUT,
2127 ERRNO_UNK, 0, &log, false, NULL, NULL, 0, &tv);
2130 * We can not log the packet, since we only own the
2131 * read lock, but a write lock is needed. The read lock
2132 * is not upgraded to a write lock, since only getting
2133 * the read lock was done intentionally to improve the
2134 * handling of SYN flooding attacks.
2135 * This happens only for pure SYN segments received in
2136 * the initial CLOSED state, or received in a more
2137 * advanced state than listen and the UDP encapsulation
2138 * port is unexpected.
2139 * The incoming SYN segments do not really belong to
2140 * the TCP connection and the handling does not change
2141 * the state of the TCP connection. Therefore, the
2142 * sending of the RST segments is not logged. Please
2143 * note that also the incoming SYN segments are not
2146 * The following code ensures that the above description
2147 * is and stays correct.
2149 KASSERT((thflags & (TH_ACK|TH_SYN)) == TH_SYN &&
2150 (tp->t_state == TCPS_CLOSED ||
2151 (tp->t_state > TCPS_LISTEN && tp->t_port != port)),
2152 ("%s: Logging of TCP segment with flags 0x%b and "
2153 "UDP encapsulation port %u skipped in state %s",
2154 __func__, thflags, PRINT_TH_FLAGS,
2155 ntohs(port), tcpstates[tp->t_state]));
2160 TCPSTAT_INC(tcps_sndacks);
2161 else if (flags & (TH_SYN|TH_FIN|TH_RST))
2162 TCPSTAT_INC(tcps_sndctrl);
2163 TCPSTAT_INC(tcps_sndtotal);
2167 TCP_PROBE5(send, NULL, tp, ip6, tp, nth);
2168 output_ret = ip6_output(m, NULL, NULL, 0, NULL, NULL, inp);
2171 #if defined(INET) && defined(INET6)
2176 TCP_PROBE5(send, NULL, tp, ip, tp, nth);
2177 output_ret = ip_output(m, NULL, NULL, 0, NULL, inp);
2181 lgb->tlb_errno = output_ret;
2185 * Create a new TCP control block, making an empty reassembly queue and hooking
2186 * it to the argument protocol control block. The `inp' parameter must have
2187 * come from the zone allocator set up by tcpcbstor declaration.
2190 tcp_newtcpcb(struct inpcb *inp)
2192 struct tcpcb *tp = intotcpcb(inp);
2194 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2198 * Historically allocation was done with M_ZERO. There is a lot of
2199 * code that rely on that. For now take safe approach and zero whole
2200 * tcpcb. This definitely can be optimized.
2202 bzero(&tp->t_start_zero, t_zero_size);
2204 /* Initialise cc_var struct for this tcpcb. */
2205 tp->t_ccv.type = IPPROTO_TCP;
2206 tp->t_ccv.ccvc.tcp = tp;
2207 rw_rlock(&tcp_function_lock);
2208 tp->t_fb = tcp_func_set_ptr;
2209 refcount_acquire(&tp->t_fb->tfb_refcnt);
2210 rw_runlock(&tcp_function_lock);
2212 * Use the current system default CC algorithm.
2214 cc_attach(tp, CC_DEFAULT_ALGO());
2216 if (CC_ALGO(tp)->cb_init != NULL)
2217 if (CC_ALGO(tp)->cb_init(&tp->t_ccv, NULL) > 0) {
2219 if (tp->t_fb->tfb_tcp_fb_fini)
2220 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2221 refcount_release(&tp->t_fb->tfb_refcnt);
2226 if (khelp_init_osd(HELPER_CLASS_TCP, &tp->t_osd)) {
2227 if (tp->t_fb->tfb_tcp_fb_fini)
2228 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2229 refcount_release(&tp->t_fb->tfb_refcnt);
2234 TAILQ_INIT(&tp->t_segq);
2237 isipv6 ? V_tcp_v6mssdflt :
2241 callout_init_rw(&tp->t_callout, &inp->inp_lock, CALLOUT_RETURNUNLOCKED);
2242 for (int i = 0; i < TT_N; i++)
2243 tp->t_timers[i] = SBT_MAX;
2245 switch (V_tcp_do_rfc1323) {
2250 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
2253 tp->t_flags = TF_REQ_SCALE;
2256 tp->t_flags = TF_REQ_TSTMP;
2260 tp->t_flags |= TF_SACK_PERMIT;
2261 TAILQ_INIT(&tp->snd_holes);
2264 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
2265 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives
2266 * reasonable initial retransmit time.
2268 tp->t_srtt = TCPTV_SRTTBASE;
2269 tp->t_rttvar = ((tcp_rexmit_initial - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
2270 tp->t_rttmin = tcp_rexmit_min;
2271 tp->t_rxtcur = tcp_rexmit_initial;
2272 tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2273 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2274 tp->t_rcvtime = ticks;
2275 /* We always start with ticks granularity */
2276 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS;
2278 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
2279 * because the socket may be bound to an IPv6 wildcard address,
2280 * which may match an IPv4-mapped IPv6 address.
2282 inp->inp_ip_ttl = V_ip_defttl;
2285 * If using hpts lets drop a random number in so
2286 * not all new connections fall on the same CPU.
2288 inp->inp_hpts_cpu = hpts_random_cpu(inp);
2292 * Init the TCP PCAP queues.
2294 tcp_pcap_tcpcb_init(tp);
2297 /* Initialize the per-TCPCB log data. */
2298 tcp_log_tcpcbinit(tp);
2300 tp->t_pacing_rate = -1;
2301 if (tp->t_fb->tfb_tcp_fb_init) {
2302 if ((*tp->t_fb->tfb_tcp_fb_init)(tp, &tp->t_fb_ptr)) {
2303 refcount_release(&tp->t_fb->tfb_refcnt);
2308 if (V_tcp_perconn_stats_enable == 1)
2309 tp->t_stats = stats_blob_alloc(V_tcp_perconn_stats_dflt_tpl, 0);
2312 tp->t_flags |= TF_LRD;
2318 * Drop a TCP connection, reporting
2319 * the specified error. If connection is synchronized,
2320 * then send a RST to peer.
2323 tcp_drop(struct tcpcb *tp, int errno)
2325 struct socket *so = tptosocket(tp);
2328 INP_WLOCK_ASSERT(tptoinpcb(tp));
2330 if (TCPS_HAVERCVDSYN(tp->t_state)) {
2331 tcp_state_change(tp, TCPS_CLOSED);
2332 /* Don't use tcp_output() here due to possible recursion. */
2333 (void)tcp_output_nodrop(tp);
2334 TCPSTAT_INC(tcps_drops);
2336 TCPSTAT_INC(tcps_conndrops);
2337 if (errno == ETIMEDOUT && tp->t_softerror)
2338 errno = tp->t_softerror;
2339 so->so_error = errno;
2340 return (tcp_close(tp));
2344 tcp_discardcb(struct tcpcb *tp)
2346 struct inpcb *inp = tptoinpcb(tp);
2347 struct socket *so = tptosocket(tp);
2349 bool isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2352 INP_WLOCK_ASSERT(inp);
2355 if (tp->t_fb->tfb_tcp_timer_stop_all) {
2356 tp->t_fb->tfb_tcp_timer_stop_all(tp);
2359 /* free the reassembly queue, if any */
2360 tcp_reass_flush(tp);
2363 /* Disconnect offload device, if any. */
2364 if (tp->t_flags & TF_TOE)
2365 tcp_offload_detach(tp);
2368 tcp_free_sackholes(tp);
2371 /* Free the TCP PCAP queues. */
2372 tcp_pcap_drain(&(tp->t_inpkts));
2373 tcp_pcap_drain(&(tp->t_outpkts));
2376 /* Allow the CC algorithm to clean up after itself. */
2377 if (CC_ALGO(tp)->cb_destroy != NULL)
2378 CC_ALGO(tp)->cb_destroy(&tp->t_ccv);
2380 /* Detach from the CC algorithm */
2384 khelp_destroy_osd(&tp->t_osd);
2387 stats_blob_destroy(tp->t_stats);
2393 tcp_log_tcpcbfini(tp);
2395 TCPSTATES_DEC(tp->t_state);
2396 if (tp->t_fb->tfb_tcp_fb_fini)
2397 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2400 * If we got enough samples through the srtt filter,
2401 * save the rtt and rttvar in the routing entry.
2402 * 'Enough' is arbitrarily defined as 4 rtt samples.
2403 * 4 samples is enough for the srtt filter to converge
2404 * to within enough % of the correct value; fewer samples
2405 * and we could save a bogus rtt. The danger is not high
2406 * as tcp quickly recovers from everything.
2407 * XXX: Works very well but needs some more statistics!
2409 * XXXRRS: Updating must be after the stack fini() since
2410 * that may be converting some internal representation of
2411 * say srtt etc into the general one used by other stacks.
2412 * Lets also at least protect against the so being NULL
2413 * as RW stated below.
2415 if ((tp->t_rttupdated >= 4) && (so != NULL)) {
2416 struct hc_metrics_lite metrics;
2419 bzero(&metrics, sizeof(metrics));
2421 * Update the ssthresh always when the conditions below
2422 * are satisfied. This gives us better new start value
2423 * for the congestion avoidance for new connections.
2424 * ssthresh is only set if packet loss occurred on a session.
2426 * XXXRW: 'so' may be NULL here, and/or socket buffer may be
2427 * being torn down. Ideally this code would not use 'so'.
2429 ssthresh = tp->snd_ssthresh;
2430 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
2432 * convert the limit from user data bytes to
2433 * packets then to packet data bytes.
2435 ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
2438 ssthresh *= (tp->t_maxseg +
2440 (isipv6 ? sizeof (struct ip6_hdr) +
2441 sizeof (struct tcphdr) :
2443 sizeof (struct tcpiphdr)
2450 metrics.rmx_ssthresh = ssthresh;
2452 metrics.rmx_rtt = tp->t_srtt;
2453 metrics.rmx_rttvar = tp->t_rttvar;
2454 metrics.rmx_cwnd = tp->snd_cwnd;
2455 metrics.rmx_sendpipe = 0;
2456 metrics.rmx_recvpipe = 0;
2458 tcp_hc_update(&inp->inp_inc, &metrics);
2461 refcount_release(&tp->t_fb->tfb_refcnt);
2465 * Attempt to close a TCP control block, marking it as dropped, and freeing
2466 * the socket if we hold the only reference.
2469 tcp_close(struct tcpcb *tp)
2471 struct inpcb *inp = tptoinpcb(tp);
2472 struct socket *so = tptosocket(tp);
2474 INP_WLOCK_ASSERT(inp);
2477 if (tp->t_state == TCPS_LISTEN)
2478 tcp_offload_listen_stop(tp);
2481 * This releases the TFO pending counter resource for TFO listen
2482 * sockets as well as passively-created TFO sockets that transition
2483 * from SYN_RECEIVED to CLOSED.
2485 if (tp->t_tfo_pending) {
2486 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2487 tp->t_tfo_pending = NULL;
2490 tcp_hpts_remove(inp);
2493 TCPSTAT_INC(tcps_closed);
2494 if (tp->t_state != TCPS_CLOSED)
2495 tcp_state_change(tp, TCPS_CLOSED);
2496 KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
2497 soisdisconnected(so);
2498 if (inp->inp_flags & INP_SOCKREF) {
2499 inp->inp_flags &= ~INP_SOCKREF;
2508 * Notify a tcp user of an asynchronous error;
2509 * store error as soft error, but wake up user
2510 * (for now, won't do anything until can select for soft error).
2512 * Do not wake up user since there currently is no mechanism for
2513 * reporting soft errors (yet - a kqueue filter may be added).
2515 static struct inpcb *
2516 tcp_notify(struct inpcb *inp, int error)
2520 INP_WLOCK_ASSERT(inp);
2522 tp = intotcpcb(inp);
2523 KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
2526 * Ignore some errors if we are hooked up.
2527 * If connection hasn't completed, has retransmitted several times,
2528 * and receives a second error, give up now. This is better
2529 * than waiting a long time to establish a connection that
2530 * can never complete.
2532 if (tp->t_state == TCPS_ESTABLISHED &&
2533 (error == EHOSTUNREACH || error == ENETUNREACH ||
2534 error == EHOSTDOWN)) {
2535 if (inp->inp_route.ro_nh) {
2536 NH_FREE(inp->inp_route.ro_nh);
2537 inp->inp_route.ro_nh = (struct nhop_object *)NULL;
2540 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
2542 tp = tcp_drop(tp, error);
2548 tp->t_softerror = error;
2552 wakeup( &so->so_timeo);
2559 tcp_pcblist(SYSCTL_HANDLER_ARGS)
2561 struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
2562 INPLOOKUP_RLOCKPCB);
2567 if (req->newptr != NULL)
2570 if (req->oldptr == NULL) {
2573 n = V_tcbinfo.ipi_count +
2574 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2575 n += imax(n / 8, 10);
2576 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb);
2580 if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
2583 bzero(&xig, sizeof(xig));
2584 xig.xig_len = sizeof xig;
2585 xig.xig_count = V_tcbinfo.ipi_count +
2586 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2587 xig.xig_gen = V_tcbinfo.ipi_gencnt;
2588 xig.xig_sogen = so_gencnt;
2589 error = SYSCTL_OUT(req, &xig, sizeof xig);
2593 error = syncache_pcblist(req);
2597 while ((inp = inp_next(&inpi)) != NULL) {
2598 if (inp->inp_gencnt <= xig.xig_gen &&
2599 cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
2602 tcp_inptoxtp(inp, &xt);
2603 error = SYSCTL_OUT(req, &xt, sizeof xt);
2614 * Give the user an updated idea of our state.
2615 * If the generation differs from what we told
2616 * her before, she knows that something happened
2617 * while we were processing this request, and it
2618 * might be necessary to retry.
2620 xig.xig_gen = V_tcbinfo.ipi_gencnt;
2621 xig.xig_sogen = so_gencnt;
2622 xig.xig_count = V_tcbinfo.ipi_count +
2623 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2624 error = SYSCTL_OUT(req, &xig, sizeof xig);
2630 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist,
2631 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
2632 NULL, 0, tcp_pcblist, "S,xtcpcb",
2633 "List of active TCP connections");
2637 tcp_getcred(SYSCTL_HANDLER_ARGS)
2640 struct sockaddr_in addrs[2];
2641 struct epoch_tracker et;
2645 error = priv_check(req->td, PRIV_NETINET_GETCRED);
2648 error = SYSCTL_IN(req, addrs, sizeof(addrs));
2651 NET_EPOCH_ENTER(et);
2652 inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
2653 addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL);
2657 error = cr_canseeinpcb(req->td->td_ucred, inp);
2659 cru2x(inp->inp_cred, &xuc);
2664 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2668 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
2669 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
2670 0, 0, tcp_getcred, "S,xucred",
2671 "Get the xucred of a TCP connection");
2676 tcp6_getcred(SYSCTL_HANDLER_ARGS)
2678 struct epoch_tracker et;
2680 struct sockaddr_in6 addrs[2];
2687 error = priv_check(req->td, PRIV_NETINET_GETCRED);
2690 error = SYSCTL_IN(req, addrs, sizeof(addrs));
2693 if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
2694 (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
2697 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
2699 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
2706 NET_EPOCH_ENTER(et);
2709 inp = in_pcblookup(&V_tcbinfo,
2710 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
2712 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
2713 addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL);
2716 inp = in6_pcblookup(&V_tcbinfo,
2717 &addrs[1].sin6_addr, addrs[1].sin6_port,
2718 &addrs[0].sin6_addr, addrs[0].sin6_port,
2719 INPLOOKUP_RLOCKPCB, NULL);
2723 error = cr_canseeinpcb(req->td->td_ucred, inp);
2725 cru2x(inp->inp_cred, &xuc);
2730 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2734 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
2735 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
2736 0, 0, tcp6_getcred, "S,xucred",
2737 "Get the xucred of a TCP6 connection");
2741 /* Path MTU to try next when a fragmentation-needed message is received. */
2743 tcp_next_pmtu(const struct icmp *icp, const struct ip *ip)
2745 int mtu = ntohs(icp->icmp_nextmtu);
2747 /* If no alternative MTU was proposed, try the next smaller one. */
2749 mtu = ip_next_mtu(ntohs(ip->ip_len), 1);
2750 if (mtu < V_tcp_minmss + sizeof(struct tcpiphdr))
2751 mtu = V_tcp_minmss + sizeof(struct tcpiphdr);
2757 tcp_ctlinput_with_port(struct icmp *icp, uint16_t port)
2763 struct inpcb *(*notify)(struct inpcb *, int);
2764 struct in_conninfo inc;
2765 tcp_seq icmp_tcp_seq;
2768 errno = icmp_errmap(icp);
2773 notify = tcp_mtudisc_notify;
2777 notify = tcp_drop_syn_sent;
2779 notify = tcp_notify;
2782 if (V_icmp_may_rst && icp->icmp_type == ICMP_TIMXCEED)
2783 notify = tcp_drop_syn_sent;
2785 notify = tcp_notify;
2788 notify = tcp_notify;
2792 th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2793 icmp_tcp_seq = th->th_seq;
2794 inp = in_pcblookup(&V_tcbinfo, ip->ip_dst, th->th_dport, ip->ip_src,
2795 th->th_sport, INPLOOKUP_WLOCKPCB, NULL);
2797 tp = intotcpcb(inp);
2799 if (tp->t_flags & TF_TOE && errno == EMSGSIZE) {
2801 * MTU discovery for offloaded connections. Let
2802 * the TOE driver verify seq# and process it.
2804 mtu = tcp_next_pmtu(icp, ip);
2805 tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu);
2809 if (tp->t_port != port)
2811 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
2812 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
2813 if (errno == EMSGSIZE) {
2815 * MTU discovery: we got a needfrag and
2816 * will potentially try a lower MTU.
2818 mtu = tcp_next_pmtu(icp, ip);
2821 * Only process the offered MTU if it
2822 * is smaller than the current one.
2824 if (mtu < tp->t_maxseg +
2825 sizeof(struct tcpiphdr)) {
2826 bzero(&inc, sizeof(inc));
2827 inc.inc_faddr = ip->ip_dst;
2829 inp->inp_inc.inc_fibnum;
2830 tcp_hc_updatemtu(&inc, mtu);
2831 inp = tcp_mtudisc(inp, mtu);
2834 inp = (*notify)(inp, errno);
2837 bzero(&inc, sizeof(inc));
2838 inc.inc_fport = th->th_dport;
2839 inc.inc_lport = th->th_sport;
2840 inc.inc_faddr = ip->ip_dst;
2841 inc.inc_laddr = ip->ip_src;
2842 syncache_unreach(&inc, icmp_tcp_seq, port);
2850 tcp_ctlinput(struct icmp *icmp)
2852 tcp_ctlinput_with_port(icmp, htons(0));
2856 tcp_ctlinput_viaudp(udp_tun_icmp_param_t param)
2858 /* Its a tunneled TCP over UDP icmp */
2859 struct icmp *icmp = param.icmp;
2860 struct ip *outer_ip, *inner_ip;
2862 struct tcphdr *th, ttemp;
2866 outer_ip = (struct ip *)((caddr_t)icmp - sizeof(struct ip));
2867 inner_ip = &icmp->icmp_ip;
2868 i_hlen = inner_ip->ip_hl << 2;
2869 o_len = ntohs(outer_ip->ip_len);
2871 (sizeof(struct ip) + 8 + i_hlen + sizeof(struct udphdr) + offsetof(struct tcphdr, th_ack))) {
2872 /* Not enough data present */
2875 /* Ok lets strip out the inner udphdr header by copying up on top of it the tcp hdr */
2876 udp = (struct udphdr *)(((caddr_t)inner_ip) + i_hlen);
2877 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
2880 port = udp->uh_dport;
2881 th = (struct tcphdr *)(udp + 1);
2882 memcpy(&ttemp, th, sizeof(struct tcphdr));
2883 memcpy(udp, &ttemp, sizeof(struct tcphdr));
2884 /* Now adjust down the size of the outer IP header */
2885 o_len -= sizeof(struct udphdr);
2886 outer_ip->ip_len = htons(o_len);
2887 /* Now call in to the normal handling code */
2888 tcp_ctlinput_with_port(icmp, port);
2894 tcp6_next_pmtu(const struct icmp6_hdr *icmp6)
2896 int mtu = ntohl(icmp6->icmp6_mtu);
2899 * If no alternative MTU was proposed, or the proposed MTU was too
2900 * small, set to the min.
2902 if (mtu < IPV6_MMTU)
2903 mtu = IPV6_MMTU - 8; /* XXXNP: what is the adjustment for? */
2908 tcp6_ctlinput_with_port(struct ip6ctlparam *ip6cp, uint16_t port)
2910 struct in6_addr *dst;
2911 struct inpcb *(*notify)(struct inpcb *, int);
2912 struct ip6_hdr *ip6;
2916 struct icmp6_hdr *icmp6;
2917 struct in_conninfo inc;
2922 tcp_seq icmp_tcp_seq;
2927 icmp6 = ip6cp->ip6c_icmp6;
2929 ip6 = ip6cp->ip6c_ip6;
2930 off = ip6cp->ip6c_off;
2931 dst = &ip6cp->ip6c_finaldst->sin6_addr;
2933 errno = icmp6_errmap(icmp6);
2938 notify = tcp_mtudisc_notify;
2942 notify = tcp_drop_syn_sent;
2944 notify = tcp_notify;
2948 * There are only four ICMPs that may reset connection:
2949 * - administratively prohibited
2950 * - port unreachable
2951 * - time exceeded in transit
2952 * - unknown next header
2954 if (V_icmp_may_rst &&
2955 ((icmp6->icmp6_type == ICMP6_DST_UNREACH &&
2956 (icmp6->icmp6_code == ICMP6_DST_UNREACH_ADMIN ||
2957 icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT)) ||
2958 (icmp6->icmp6_type == ICMP6_TIME_EXCEEDED &&
2959 icmp6->icmp6_code == ICMP6_TIME_EXCEED_TRANSIT) ||
2960 (icmp6->icmp6_type == ICMP6_PARAM_PROB &&
2961 icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER)))
2962 notify = tcp_drop_syn_sent;
2964 notify = tcp_notify;
2967 notify = tcp_notify;
2970 /* Check if we can safely get the ports from the tcp hdr */
2973 (int32_t) (off + sizeof(struct tcp_ports)))) {
2976 bzero(&t_ports, sizeof(struct tcp_ports));
2977 m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports);
2978 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport,
2979 &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL);
2980 off += sizeof(struct tcp_ports);
2981 if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) {
2984 m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq);
2986 tp = intotcpcb(inp);
2988 if (tp->t_flags & TF_TOE && errno == EMSGSIZE) {
2989 /* MTU discovery for offloaded connections. */
2990 mtu = tcp6_next_pmtu(icmp6);
2991 tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu);
2995 if (tp->t_port != port)
2997 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
2998 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
2999 if (errno == EMSGSIZE) {
3002 * If we got a needfrag set the MTU
3003 * in the route to the suggested new
3004 * value (if given) and then notify.
3006 mtu = tcp6_next_pmtu(icmp6);
3008 bzero(&inc, sizeof(inc));
3009 inc.inc_fibnum = M_GETFIB(m);
3010 inc.inc_flags |= INC_ISIPV6;
3011 inc.inc6_faddr = *dst;
3012 if (in6_setscope(&inc.inc6_faddr,
3013 m->m_pkthdr.rcvif, NULL))
3016 * Only process the offered MTU if it
3017 * is smaller than the current one.
3019 if (mtu < tp->t_maxseg +
3020 sizeof (struct tcphdr) +
3021 sizeof (struct ip6_hdr)) {
3022 tcp_hc_updatemtu(&inc, mtu);
3023 tcp_mtudisc(inp, mtu);
3024 ICMP6STAT_INC(icp6s_pmtuchg);
3027 inp = (*notify)(inp, errno);
3030 bzero(&inc, sizeof(inc));
3031 inc.inc_fibnum = M_GETFIB(m);
3032 inc.inc_flags |= INC_ISIPV6;
3033 inc.inc_fport = t_ports.th_dport;
3034 inc.inc_lport = t_ports.th_sport;
3035 inc.inc6_faddr = *dst;
3036 inc.inc6_laddr = ip6->ip6_src;
3037 syncache_unreach(&inc, icmp_tcp_seq, port);
3045 tcp6_ctlinput(struct ip6ctlparam *ctl)
3047 tcp6_ctlinput_with_port(ctl, htons(0));
3051 tcp6_ctlinput_viaudp(udp_tun_icmp_param_t param)
3053 struct ip6ctlparam *ip6cp = param.ip6cp;
3058 m = m_pulldown(ip6cp->ip6c_m, ip6cp->ip6c_off, sizeof(struct udphdr), NULL);
3062 udp = mtod(m, struct udphdr *);
3063 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
3066 port = udp->uh_dport;
3067 m_adj(m, sizeof(struct udphdr));
3068 if ((m->m_flags & M_PKTHDR) == 0) {
3069 ip6cp->ip6c_m->m_pkthdr.len -= sizeof(struct udphdr);
3071 /* Now call in to the normal handling code */
3072 tcp6_ctlinput_with_port(ip6cp, port);
3078 tcp_keyed_hash(struct in_conninfo *inc, u_char *key, u_int len)
3083 KASSERT(len >= SIPHASH_KEY_LENGTH,
3084 ("%s: keylen %u too short ", __func__, len));
3085 SipHash24_Init(&ctx);
3086 SipHash_SetKey(&ctx, (uint8_t *)key);
3087 SipHash_Update(&ctx, &inc->inc_fport, sizeof(uint16_t));
3088 SipHash_Update(&ctx, &inc->inc_lport, sizeof(uint16_t));
3089 switch (inc->inc_flags & INC_ISIPV6) {
3092 SipHash_Update(&ctx, &inc->inc_faddr, sizeof(struct in_addr));
3093 SipHash_Update(&ctx, &inc->inc_laddr, sizeof(struct in_addr));
3098 SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(struct in6_addr));
3099 SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(struct in6_addr));
3103 SipHash_Final((uint8_t *)hash, &ctx);
3105 return (hash[0] ^ hash[1]);
3109 tcp_new_ts_offset(struct in_conninfo *inc)
3111 struct in_conninfo inc_store, *local_inc;
3113 if (!V_tcp_ts_offset_per_conn) {
3114 memcpy(&inc_store, inc, sizeof(struct in_conninfo));
3115 inc_store.inc_lport = 0;
3116 inc_store.inc_fport = 0;
3117 local_inc = &inc_store;
3121 return (tcp_keyed_hash(local_inc, V_ts_offset_secret,
3122 sizeof(V_ts_offset_secret)));
3126 * Following is where TCP initial sequence number generation occurs.
3128 * There are two places where we must use initial sequence numbers:
3129 * 1. In SYN-ACK packets.
3130 * 2. In SYN packets.
3132 * All ISNs for SYN-ACK packets are generated by the syncache. See
3133 * tcp_syncache.c for details.
3135 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
3136 * depends on this property. In addition, these ISNs should be
3137 * unguessable so as to prevent connection hijacking. To satisfy
3138 * the requirements of this situation, the algorithm outlined in
3139 * RFC 1948 is used, with only small modifications.
3141 * Implementation details:
3143 * Time is based off the system timer, and is corrected so that it
3144 * increases by one megabyte per second. This allows for proper
3145 * recycling on high speed LANs while still leaving over an hour
3148 * As reading the *exact* system time is too expensive to be done
3149 * whenever setting up a TCP connection, we increment the time
3150 * offset in two ways. First, a small random positive increment
3151 * is added to isn_offset for each connection that is set up.
3152 * Second, the function tcp_isn_tick fires once per clock tick
3153 * and increments isn_offset as necessary so that sequence numbers
3154 * are incremented at approximately ISN_BYTES_PER_SECOND. The
3155 * random positive increments serve only to ensure that the same
3156 * exact sequence number is never sent out twice (as could otherwise
3157 * happen when a port is recycled in less than the system tick
3160 * net.inet.tcp.isn_reseed_interval controls the number of seconds
3161 * between seeding of isn_secret. This is normally set to zero,
3162 * as reseeding should not be necessary.
3164 * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
3165 * isn_offset_old, and isn_ctx is performed using the ISN lock. In
3166 * general, this means holding an exclusive (write) lock.
3169 #define ISN_BYTES_PER_SECOND 1048576
3170 #define ISN_STATIC_INCREMENT 4096
3171 #define ISN_RANDOM_INCREMENT (4096 - 1)
3172 #define ISN_SECRET_LENGTH SIPHASH_KEY_LENGTH
3174 VNET_DEFINE_STATIC(u_char, isn_secret[ISN_SECRET_LENGTH]);
3175 VNET_DEFINE_STATIC(int, isn_last);
3176 VNET_DEFINE_STATIC(int, isn_last_reseed);
3177 VNET_DEFINE_STATIC(u_int32_t, isn_offset);
3178 VNET_DEFINE_STATIC(u_int32_t, isn_offset_old);
3180 #define V_isn_secret VNET(isn_secret)
3181 #define V_isn_last VNET(isn_last)
3182 #define V_isn_last_reseed VNET(isn_last_reseed)
3183 #define V_isn_offset VNET(isn_offset)
3184 #define V_isn_offset_old VNET(isn_offset_old)
3187 tcp_new_isn(struct in_conninfo *inc)
3190 u_int32_t projected_offset;
3193 /* Seed if this is the first use, reseed if requested. */
3194 if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) &&
3195 (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz)
3197 arc4rand(&V_isn_secret, sizeof(V_isn_secret), 0);
3198 V_isn_last_reseed = ticks;
3201 /* Compute the hash and return the ISN. */
3202 new_isn = (tcp_seq)tcp_keyed_hash(inc, V_isn_secret,
3203 sizeof(V_isn_secret));
3204 V_isn_offset += ISN_STATIC_INCREMENT +
3205 (arc4random() & ISN_RANDOM_INCREMENT);
3206 if (ticks != V_isn_last) {
3207 projected_offset = V_isn_offset_old +
3208 ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last);
3209 if (SEQ_GT(projected_offset, V_isn_offset))
3210 V_isn_offset = projected_offset;
3211 V_isn_offset_old = V_isn_offset;
3214 new_isn += V_isn_offset;
3220 * When a specific ICMP unreachable message is received and the
3221 * connection state is SYN-SENT, drop the connection. This behavior
3222 * is controlled by the icmp_may_rst sysctl.
3224 static struct inpcb *
3225 tcp_drop_syn_sent(struct inpcb *inp, int errno)
3230 INP_WLOCK_ASSERT(inp);
3232 tp = intotcpcb(inp);
3233 if (tp->t_state != TCPS_SYN_SENT)
3236 if (IS_FASTOPEN(tp->t_flags))
3237 tcp_fastopen_disable_path(tp);
3239 tp = tcp_drop(tp, errno);
3247 * When `need fragmentation' ICMP is received, update our idea of the MSS
3248 * based on the new value. Also nudge TCP to send something, since we
3249 * know the packet we just sent was dropped.
3250 * This duplicates some code in the tcp_mss() function in tcp_input.c.
3252 static struct inpcb *
3253 tcp_mtudisc_notify(struct inpcb *inp, int error)
3256 return (tcp_mtudisc(inp, -1));
3259 static struct inpcb *
3260 tcp_mtudisc(struct inpcb *inp, int mtuoffer)
3265 INP_WLOCK_ASSERT(inp);
3267 tp = intotcpcb(inp);
3268 KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
3270 tcp_mss_update(tp, -1, mtuoffer, NULL, NULL);
3272 so = inp->inp_socket;
3273 SOCKBUF_LOCK(&so->so_snd);
3274 /* If the mss is larger than the socket buffer, decrease the mss. */
3275 if (so->so_snd.sb_hiwat < tp->t_maxseg)
3276 tp->t_maxseg = so->so_snd.sb_hiwat;
3277 SOCKBUF_UNLOCK(&so->so_snd);
3279 TCPSTAT_INC(tcps_mturesent);
3281 tp->snd_nxt = tp->snd_una;
3282 tcp_free_sackholes(tp);
3283 tp->snd_recover = tp->snd_max;
3284 if (tp->t_flags & TF_SACK_PERMIT)
3285 EXIT_FASTRECOVERY(tp->t_flags);
3286 if (tp->t_fb->tfb_tcp_mtu_chg != NULL) {
3288 * Conceptually the snd_nxt setting
3289 * and freeing sack holes should
3290 * be done by the default stacks
3291 * own tfb_tcp_mtu_chg().
3293 tp->t_fb->tfb_tcp_mtu_chg(tp);
3295 if (tcp_output(tp) < 0)
3303 * Look-up the routing entry to the peer of this inpcb. If no route
3304 * is found and it cannot be allocated, then return 0. This routine
3305 * is called by TCP routines that access the rmx structure and by
3306 * tcp_mss_update to get the peer/interface MTU.
3309 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap)
3311 struct nhop_object *nh;
3313 uint32_t maxmtu = 0;
3315 KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
3317 if (inc->inc_faddr.s_addr != INADDR_ANY) {
3318 nh = fib4_lookup(inc->inc_fibnum, inc->inc_faddr, 0, NHR_NONE, 0);
3323 maxmtu = nh->nh_mtu;
3325 /* Report additional interface capabilities. */
3327 if (ifp->if_capenable & IFCAP_TSO4 &&
3328 ifp->if_hwassist & CSUM_TSO) {
3329 cap->ifcap |= CSUM_TSO;
3330 cap->tsomax = ifp->if_hw_tsomax;
3331 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3332 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3342 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap)
3344 struct nhop_object *nh;
3345 struct in6_addr dst6;
3348 uint32_t maxmtu = 0;
3350 KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
3352 if (inc->inc_flags & INC_IPV6MINMTU)
3355 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
3356 in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid);
3357 nh = fib6_lookup(inc->inc_fibnum, &dst6, scopeid, NHR_NONE, 0);
3362 maxmtu = nh->nh_mtu;
3364 /* Report additional interface capabilities. */
3366 if (ifp->if_capenable & IFCAP_TSO6 &&
3367 ifp->if_hwassist & CSUM_TSO) {
3368 cap->ifcap |= CSUM_TSO;
3369 cap->tsomax = ifp->if_hw_tsomax;
3370 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3371 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3380 * Handle setsockopt(IPV6_USE_MIN_MTU) by a TCP stack.
3382 * XXXGL: we are updating inpcb here with INC_IPV6MINMTU flag.
3383 * The right place to do that is ip6_setpktopt() that has just been
3384 * executed. By the way it just filled ip6po_minmtu for us.
3387 tcp6_use_min_mtu(struct tcpcb *tp)
3389 struct inpcb *inp = tptoinpcb(tp);
3391 INP_WLOCK_ASSERT(inp);
3393 * In case of the IPV6_USE_MIN_MTU socket
3394 * option, the INC_IPV6MINMTU flag to announce
3395 * a corresponding MSS during the initial
3396 * handshake. If the TCP connection is not in
3397 * the front states, just reduce the MSS being
3398 * used. This avoids the sending of TCP
3399 * segments which will be fragmented at the
3402 inp->inp_inc.inc_flags |= INC_IPV6MINMTU;
3403 if ((tp->t_state >= TCPS_SYN_SENT) &&
3404 (inp->inp_inc.inc_flags & INC_ISIPV6)) {
3405 struct ip6_pktopts *opt;
3407 opt = inp->in6p_outputopts;
3408 if (opt != NULL && opt->ip6po_minmtu == IP6PO_MINMTU_ALL &&
3409 tp->t_maxseg > TCP6_MSS)
3410 tp->t_maxseg = TCP6_MSS;
3416 * Calculate effective SMSS per RFC5681 definition for a given TCP
3417 * connection at its current state, taking into account SACK and etc.
3420 tcp_maxseg(const struct tcpcb *tp)
3424 if (tp->t_flags & TF_NOOPT)
3425 return (tp->t_maxseg);
3428 * Here we have a simplified code from tcp_addoptions(),
3429 * without a proper loop, and having most of paddings hardcoded.
3430 * We might make mistakes with padding here in some edge cases,
3431 * but this is harmless, since result of tcp_maxseg() is used
3432 * only in cwnd and ssthresh estimations.
3434 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3435 if (tp->t_flags & TF_RCVD_TSTMP)
3436 optlen = TCPOLEN_TSTAMP_APPA;
3439 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3440 if (tp->t_flags & TF_SIGNATURE)
3441 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3443 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) {
3444 optlen += TCPOLEN_SACKHDR;
3445 optlen += tp->rcv_numsacks * TCPOLEN_SACK;
3446 optlen = PADTCPOLEN(optlen);
3449 if (tp->t_flags & TF_REQ_TSTMP)
3450 optlen = TCPOLEN_TSTAMP_APPA;
3452 optlen = PADTCPOLEN(TCPOLEN_MAXSEG);
3453 if (tp->t_flags & TF_REQ_SCALE)
3454 optlen += PADTCPOLEN(TCPOLEN_WINDOW);
3455 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3456 if (tp->t_flags & TF_SIGNATURE)
3457 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3459 if (tp->t_flags & TF_SACK_PERMIT)
3460 optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED);
3463 optlen = min(optlen, TCP_MAXOLEN);
3464 return (tp->t_maxseg - optlen);
3469 tcp_fixed_maxseg(const struct tcpcb *tp)
3473 if (tp->t_flags & TF_NOOPT)
3474 return (tp->t_maxseg);
3477 * Here we have a simplified code from tcp_addoptions(),
3478 * without a proper loop, and having most of paddings hardcoded.
3479 * We only consider fixed options that we would send every
3480 * time I.e. SACK is not considered. This is important
3481 * for cc modules to figure out what the modulo of the
3484 #define PAD(len) ((((len) / 4) + !!((len) % 4)) * 4)
3485 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3486 if (tp->t_flags & TF_RCVD_TSTMP)
3487 optlen = TCPOLEN_TSTAMP_APPA;
3490 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3491 if (tp->t_flags & TF_SIGNATURE)
3492 optlen += PAD(TCPOLEN_SIGNATURE);
3495 if (tp->t_flags & TF_REQ_TSTMP)
3496 optlen = TCPOLEN_TSTAMP_APPA;
3498 optlen = PAD(TCPOLEN_MAXSEG);
3499 if (tp->t_flags & TF_REQ_SCALE)
3500 optlen += PAD(TCPOLEN_WINDOW);
3501 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3502 if (tp->t_flags & TF_SIGNATURE)
3503 optlen += PAD(TCPOLEN_SIGNATURE);
3505 if (tp->t_flags & TF_SACK_PERMIT)
3506 optlen += PAD(TCPOLEN_SACK_PERMITTED);
3509 optlen = min(optlen, TCP_MAXOLEN);
3510 return (tp->t_maxseg - optlen);
3516 sysctl_drop(SYSCTL_HANDLER_ARGS)
3518 /* addrs[0] is a foreign socket, addrs[1] is a local one. */
3519 struct sockaddr_storage addrs[2];
3523 struct sockaddr_in *fin = NULL, *lin = NULL;
3525 struct epoch_tracker et;
3527 struct sockaddr_in6 *fin6, *lin6;
3537 if (req->oldptr != NULL || req->oldlen != 0)
3539 if (req->newptr == NULL)
3541 if (req->newlen < sizeof(addrs))
3543 error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3547 switch (addrs[0].ss_family) {
3550 fin6 = (struct sockaddr_in6 *)&addrs[0];
3551 lin6 = (struct sockaddr_in6 *)&addrs[1];
3552 if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3553 lin6->sin6_len != sizeof(struct sockaddr_in6))
3555 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3556 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3558 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3559 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3561 fin = (struct sockaddr_in *)&addrs[0];
3562 lin = (struct sockaddr_in *)&addrs[1];
3566 error = sa6_embedscope(fin6, V_ip6_use_defzone);
3569 error = sa6_embedscope(lin6, V_ip6_use_defzone);
3576 fin = (struct sockaddr_in *)&addrs[0];
3577 lin = (struct sockaddr_in *)&addrs[1];
3578 if (fin->sin_len != sizeof(struct sockaddr_in) ||
3579 lin->sin_len != sizeof(struct sockaddr_in))
3586 NET_EPOCH_ENTER(et);
3587 switch (addrs[0].ss_family) {
3590 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3591 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3592 INPLOOKUP_WLOCKPCB, NULL);
3597 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3598 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3603 if (!SOLISTENING(inp->inp_socket)) {
3604 tp = intotcpcb(inp);
3605 tp = tcp_drop(tp, ECONNABORTED);
3616 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
3617 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3618 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_drop, "",
3619 "Drop TCP connection");
3622 tcp_sysctl_setsockopt(SYSCTL_HANDLER_ARGS)
3624 return (sysctl_setsockopt(oidp, arg1, arg2, req, &V_tcbinfo,
3625 &tcp_ctloutput_set));
3628 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, setsockopt,
3629 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3630 CTLFLAG_MPSAFE, NULL, 0, tcp_sysctl_setsockopt, "",
3631 "Set socket option for TCP endpoint");
3635 sysctl_switch_tls(SYSCTL_HANDLER_ARGS)
3637 /* addrs[0] is a foreign socket, addrs[1] is a local one. */
3638 struct sockaddr_storage addrs[2];
3641 struct sockaddr_in *fin = NULL, *lin = NULL;
3643 struct epoch_tracker et;
3645 struct sockaddr_in6 *fin6, *lin6;
3655 if (req->oldptr != NULL || req->oldlen != 0)
3657 if (req->newptr == NULL)
3659 if (req->newlen < sizeof(addrs))
3661 error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3665 switch (addrs[0].ss_family) {
3668 fin6 = (struct sockaddr_in6 *)&addrs[0];
3669 lin6 = (struct sockaddr_in6 *)&addrs[1];
3670 if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3671 lin6->sin6_len != sizeof(struct sockaddr_in6))
3673 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3674 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3676 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3677 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3679 fin = (struct sockaddr_in *)&addrs[0];
3680 lin = (struct sockaddr_in *)&addrs[1];
3684 error = sa6_embedscope(fin6, V_ip6_use_defzone);
3687 error = sa6_embedscope(lin6, V_ip6_use_defzone);
3694 fin = (struct sockaddr_in *)&addrs[0];
3695 lin = (struct sockaddr_in *)&addrs[1];
3696 if (fin->sin_len != sizeof(struct sockaddr_in) ||
3697 lin->sin_len != sizeof(struct sockaddr_in))
3704 NET_EPOCH_ENTER(et);
3705 switch (addrs[0].ss_family) {
3708 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3709 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3710 INPLOOKUP_WLOCKPCB, NULL);
3715 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3716 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3724 so = inp->inp_socket;
3726 error = ktls_set_tx_mode(so,
3727 arg2 == 0 ? TCP_TLS_MODE_SW : TCP_TLS_MODE_IFNET);
3735 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_sw_tls,
3736 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3737 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_switch_tls, "",
3738 "Switch TCP connection to SW TLS");
3739 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_ifnet_tls,
3740 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3741 CTLFLAG_NEEDGIANT, NULL, 1, sysctl_switch_tls, "",
3742 "Switch TCP connection to ifnet TLS");
3746 * Generate a standardized TCP log line for use throughout the
3747 * tcp subsystem. Memory allocation is done with M_NOWAIT to
3748 * allow use in the interrupt context.
3750 * NB: The caller MUST free(s, M_TCPLOG) the returned string.
3751 * NB: The function may return NULL if memory allocation failed.
3753 * Due to header inclusion and ordering limitations the struct ip
3754 * and ip6_hdr pointers have to be passed as void pointers.
3757 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3761 /* Is logging enabled? */
3762 if (V_tcp_log_in_vain == 0)
3765 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3769 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3773 /* Is logging enabled? */
3774 if (tcp_log_debug == 0)
3777 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3781 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3787 const struct ip *ip = (const struct ip *)ip4hdr;
3790 const struct ip6_hdr *ip6 = (const struct ip6_hdr *)ip6hdr;
3794 * The log line looks like this:
3795 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>"
3797 size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") +
3798 sizeof(PRINT_TH_FLAGS) + 1 +
3800 2 * INET6_ADDRSTRLEN;
3802 2 * INET_ADDRSTRLEN;
3805 s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT);
3809 strcat(s, "TCP: [");
3812 if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) {
3813 inet_ntoa_r(inc->inc_faddr, sp);
3815 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3817 inet_ntoa_r(inc->inc_laddr, sp);
3819 sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3822 ip6_sprintf(sp, &inc->inc6_faddr);
3824 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3826 ip6_sprintf(sp, &inc->inc6_laddr);
3828 sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3829 } else if (ip6 && th) {
3830 ip6_sprintf(sp, &ip6->ip6_src);
3832 sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3834 ip6_sprintf(sp, &ip6->ip6_dst);
3836 sprintf(sp, "]:%i", ntohs(th->th_dport));
3839 } else if (ip && th) {
3840 inet_ntoa_r(ip->ip_src, sp);
3842 sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3844 inet_ntoa_r(ip->ip_dst, sp);
3846 sprintf(sp, "]:%i", ntohs(th->th_dport));
3854 sprintf(sp, " tcpflags 0x%b", tcp_get_flags(th), PRINT_TH_FLAGS);
3855 if (*(s + size - 1) != '\0')
3856 panic("%s: string too long", __func__);
3861 * A subroutine which makes it easy to track TCP state changes with DTrace.
3862 * This function shouldn't be called for t_state initializations that don't
3863 * correspond to actual TCP state transitions.
3866 tcp_state_change(struct tcpcb *tp, int newstate)
3868 #if defined(KDTRACE_HOOKS)
3869 int pstate = tp->t_state;
3872 TCPSTATES_DEC(tp->t_state);
3873 TCPSTATES_INC(newstate);
3874 tp->t_state = newstate;
3875 TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate);
3879 * Create an external-format (``xtcpcb'') structure using the information in
3880 * the kernel-format tcpcb structure pointed to by tp. This is done to
3881 * reduce the spew of irrelevant information over this interface, to isolate
3882 * user code from changes in the kernel structure, and potentially to provide
3883 * information-hiding if we decide that some of this information should be
3884 * hidden from users.
3887 tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt)
3889 struct tcpcb *tp = intotcpcb(inp);
3892 bzero(xt, sizeof(*xt));
3893 xt->t_state = tp->t_state;
3894 xt->t_logstate = tcp_get_bblog_state(tp);
3895 xt->t_flags = tp->t_flags;
3896 xt->t_sndzerowin = tp->t_sndzerowin;
3897 xt->t_sndrexmitpack = tp->t_sndrexmitpack;
3898 xt->t_rcvoopack = tp->t_rcvoopack;
3899 xt->t_rcv_wnd = tp->rcv_wnd;
3900 xt->t_snd_wnd = tp->snd_wnd;
3901 xt->t_snd_cwnd = tp->snd_cwnd;
3902 xt->t_snd_ssthresh = tp->snd_ssthresh;
3903 xt->t_dsack_bytes = tp->t_dsack_bytes;
3904 xt->t_dsack_tlp_bytes = tp->t_dsack_tlp_bytes;
3905 xt->t_dsack_pack = tp->t_dsack_pack;
3906 xt->t_maxseg = tp->t_maxseg;
3907 xt->xt_ecn = (tp->t_flags2 & TF2_ECN_PERMIT) ? 1 : 0 +
3908 (tp->t_flags2 & TF2_ACE_PERMIT) ? 2 : 0;
3910 now = getsbinuptime();
3911 #define COPYTIMER(which,where) do { \
3912 if (tp->t_timers[which] != SBT_MAX) \
3913 xt->where = (tp->t_timers[which] - now) / SBT_1MS; \
3917 COPYTIMER(TT_DELACK, tt_delack);
3918 COPYTIMER(TT_REXMT, tt_rexmt);
3919 COPYTIMER(TT_PERSIST, tt_persist);
3920 COPYTIMER(TT_KEEP, tt_keep);
3921 COPYTIMER(TT_2MSL, tt_2msl);
3923 xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz;
3925 xt->xt_encaps_port = tp->t_port;
3926 bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack,
3927 TCP_FUNCTION_NAME_LEN_MAX);
3928 bcopy(CC_ALGO(tp)->name, xt->xt_cc, TCP_CA_NAME_MAX);
3930 (void)tcp_log_get_id(tp, xt->xt_logid);
3933 xt->xt_len = sizeof(struct xtcpcb);
3934 in_pcbtoxinpcb(inp, &xt->xt_inp);
3938 tcp_log_end_status(struct tcpcb *tp, uint8_t status)
3943 (status > TCP_EI_STATUS_MAX_VALUE) ||
3948 if (status > (sizeof(uint32_t) * 8)) {
3949 /* Should this be a KASSERT? */
3952 bit = 1U << (status - 1);
3953 if (bit & tp->t_end_info_status) {
3954 /* already logged */
3957 for (i = 0; i < TCP_END_BYTE_INFO; i++) {
3958 if (tp->t_end_info_bytes[i] == TCP_EI_EMPTY_SLOT) {
3959 tp->t_end_info_bytes[i] = status;
3960 tp->t_end_info_status |= bit;
3967 tcp_can_enable_pacing(void)
3970 if ((tcp_pacing_limit == -1) ||
3971 (tcp_pacing_limit > number_of_tcp_connections_pacing)) {
3972 atomic_fetchadd_int(&number_of_tcp_connections_pacing, 1);
3973 shadow_num_connections = number_of_tcp_connections_pacing;
3980 static uint8_t tcp_pacing_warning = 0;
3983 tcp_decrement_paced_conn(void)
3987 ret = atomic_fetchadd_int(&number_of_tcp_connections_pacing, -1);
3988 shadow_num_connections = number_of_tcp_connections_pacing;
3989 KASSERT(ret != 0, ("tcp_paced_connection_exits -1 would cause wrap?"));
3991 if (tcp_pacing_limit != -1) {
3992 printf("Warning all pacing is now disabled, count decrements invalidly!\n");
3993 tcp_pacing_limit = 0;
3994 } else if (tcp_pacing_warning == 0) {
3995 printf("Warning pacing count is invalid, invalid decrement\n");
3996 tcp_pacing_warning = 1;
4001 #ifdef TCP_ACCOUNTING
4003 tcp_do_ack_accounting(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to, uint32_t tiwin, int mss)
4005 if (SEQ_LT(th->th_ack, tp->snd_una)) {
4006 /* Do we have a SACK? */
4007 if (to->to_flags & TOF_SACK) {
4008 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4009 tp->tcp_cnt_counters[ACK_SACK]++;
4013 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4014 tp->tcp_cnt_counters[ACK_BEHIND]++;
4016 return (ACK_BEHIND);
4018 } else if (th->th_ack == tp->snd_una) {
4019 /* Do we have a SACK? */
4020 if (to->to_flags & TOF_SACK) {
4021 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4022 tp->tcp_cnt_counters[ACK_SACK]++;
4025 } else if (tiwin != tp->snd_wnd) {
4026 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4027 tp->tcp_cnt_counters[ACK_RWND]++;
4031 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4032 tp->tcp_cnt_counters[ACK_DUPACK]++;
4034 return (ACK_DUPACK);
4037 if (!SEQ_GT(th->th_ack, tp->snd_max)) {
4038 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4039 tp->tcp_cnt_counters[CNT_OF_ACKS_IN] += (((th->th_ack - tp->snd_una) + mss - 1)/mss);
4042 if (to->to_flags & TOF_SACK) {
4043 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4044 tp->tcp_cnt_counters[ACK_CUMACK_SACK]++;
4046 return (ACK_CUMACK_SACK);
4048 if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4049 tp->tcp_cnt_counters[ACK_CUMACK]++;
4051 return (ACK_CUMACK);
4058 tcp_change_time_units(struct tcpcb *tp, int granularity)
4060 if (tp->t_tmr_granularity == granularity) {
4064 if (granularity == TCP_TMR_GRANULARITY_USEC) {
4065 KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS),
4066 ("Granularity is not TICKS its %u in tp:%p",
4067 tp->t_tmr_granularity, tp));
4068 tp->t_rttlow = TICKS_2_USEC(tp->t_rttlow);
4069 if (tp->t_srtt > 1) {
4072 val = tp->t_srtt >> TCP_RTT_SHIFT;
4073 frac = tp->t_srtt & 0x1f;
4074 tp->t_srtt = TICKS_2_USEC(val);
4076 * frac is the fractional part of the srtt (if any)
4077 * but its in ticks and every bit represents
4082 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
4084 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
4092 val = tp->t_rttvar >> TCP_RTTVAR_SHIFT;
4093 frac = tp->t_rttvar & 0x1f;
4094 tp->t_rttvar = TICKS_2_USEC(val);
4096 * frac is the fractional part of the srtt (if any)
4097 * but its in ticks and every bit represents
4102 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
4104 frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
4106 tp->t_rttvar += frac;
4109 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_USEC;
4110 } else if (granularity == TCP_TMR_GRANULARITY_TICKS) {
4111 /* Convert back to ticks, with */
4112 KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_USEC),
4113 ("Granularity is not USEC its %u in tp:%p",
4114 tp->t_tmr_granularity, tp));
4115 if (tp->t_srtt > 1) {
4118 val = USEC_2_TICKS(tp->t_srtt);
4119 frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
4120 tp->t_srtt = val << TCP_RTT_SHIFT;
4122 * frac is the fractional part here is left
4123 * over from converting to hz and shifting.
4124 * We need to convert this to the 5 bit
4129 frac = (((uint64_t)frac * (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
4131 frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
4139 val = USEC_2_TICKS(tp->t_rttvar);
4140 frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
4141 tp->t_rttvar = val << TCP_RTTVAR_SHIFT;
4143 * frac is the fractional part here is left
4144 * over from converting to hz and shifting.
4145 * We need to convert this to the 5 bit
4150 frac = (((uint64_t)frac * (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
4152 frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
4154 tp->t_rttvar += frac;
4157 tp->t_rttlow = USEC_2_TICKS(tp->t_rttlow);
4158 tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS;
4162 panic("Unknown granularity:%d tp:%p",
4169 tcp_handle_orphaned_packets(struct tcpcb *tp)
4171 struct mbuf *save, *m, *prev;
4173 * Called when a stack switch is occuring from the fini()
4174 * of the old stack. We assue the init() as already been
4175 * run of the new stack and it has set the inp_flags2 to
4176 * what it supports. This function will then deal with any
4177 * differences i.e. cleanup packets that maybe queued that
4178 * the newstack does not support.
4181 if (tptoinpcb(tp)->inp_flags2 & INP_MBUF_L_ACKS)
4183 if ((tptoinpcb(tp)->inp_flags2 & INP_SUPPORTS_MBUFQ) == 0) {
4185 * It is unsafe to process the packets since a
4186 * reset may be lurking in them (its rare but it
4187 * can occur). If we were to find a RST, then we
4188 * would end up dropping the connection and the
4189 * INP lock, so when we return the caller (tcp_usrreq)
4190 * will blow up when it trys to unlock the inp.
4191 * This new stack does not do any fancy LRO features
4192 * so all we can do is toss the packets.
4195 tp->t_in_pkt = NULL;
4196 tp->t_tail_pkt = NULL;
4198 save = m->m_nextpkt;
4199 m->m_nextpkt = NULL;
4205 * Here we have a stack that does mbuf queuing but
4206 * does not support compressed ack's. We must
4207 * walk all the mbufs and discard any compressed acks.
4212 if (m->m_flags & M_ACKCMP) {
4213 /* We must toss this packet */
4214 if (tp->t_tail_pkt == m)
4215 tp->t_tail_pkt = prev;
4217 prev->m_nextpkt = m->m_nextpkt;
4219 tp->t_in_pkt = m->m_nextpkt;
4220 m->m_nextpkt = NULL;
4224 m = prev->m_nextpkt;
4228 /* this one is ok */
4236 #ifdef TCP_REQUEST_TRK
4238 tcp_estimate_tls_overhead(struct socket *so, uint64_t tls_usr_bytes)
4241 struct ktls_session *tls;
4242 uint32_t rec_oh, records;
4244 tls = so->so_snd.sb_tls_info;
4248 rec_oh = tls->params.tls_hlen + tls->params.tls_tlen;
4249 records = ((tls_usr_bytes + tls->params.max_frame_len - 1)/tls->params.max_frame_len);
4250 return (records * rec_oh);
4256 extern uint32_t tcp_stale_entry_time;
4257 uint32_t tcp_stale_entry_time = 250000;
4258 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, usrlog_stale, CTLFLAG_RW,
4259 &tcp_stale_entry_time, 250000, "Time that a http entry without a sendfile ages out");
4262 tcp_http_log_req_info(struct tcpcb *tp, struct http_sendfile_track *http,
4263 uint16_t slot, uint8_t val, uint64_t offset, uint64_t nbytes)
4265 if (tcp_bblogging_on(tp)) {
4266 union tcp_log_stackspecific log;
4269 memset(&log.u_bbr, 0, sizeof(log.u_bbr));
4271 log.u_bbr.inhpts = tcp_in_hpts(tptoinpcb(tp));
4273 log.u_bbr.flex8 = val;
4274 log.u_bbr.rttProp = http->timestamp;
4275 log.u_bbr.delRate = http->start;
4276 log.u_bbr.cur_del_rate = http->end;
4277 log.u_bbr.flex1 = http->start_seq;
4278 log.u_bbr.flex2 = http->end_seq;
4279 log.u_bbr.flex3 = http->flags;
4280 log.u_bbr.flex4 = ((http->localtime >> 32) & 0x00000000ffffffff);
4281 log.u_bbr.flex5 = (http->localtime & 0x00000000ffffffff);
4282 log.u_bbr.flex7 = slot;
4283 log.u_bbr.bw_inuse = offset;
4284 /* nbytes = flex6 | epoch */
4285 log.u_bbr.flex6 = ((nbytes >> 32) & 0x00000000ffffffff);
4286 log.u_bbr.epoch = (nbytes & 0x00000000ffffffff);
4287 /* cspr = lt_epoch | pkts_out */
4288 log.u_bbr.lt_epoch = ((http->cspr >> 32) & 0x00000000ffffffff);
4289 log.u_bbr.pkts_out |= (http->cspr & 0x00000000ffffffff);
4290 log.u_bbr.applimited = tp->t_http_closed;
4291 log.u_bbr.applimited <<= 8;
4292 log.u_bbr.applimited |= tp->t_http_open;
4293 log.u_bbr.applimited <<= 8;
4294 log.u_bbr.applimited |= tp->t_http_req;
4295 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
4296 TCP_LOG_EVENTP(tp, NULL,
4297 &tptosocket(tp)->so_rcv,
4298 &tptosocket(tp)->so_snd,
4300 0, &log, false, &tv);
4305 tcp_http_free_a_slot(struct tcpcb *tp, struct http_sendfile_track *ent)
4307 if (tp->t_http_req > 0)
4309 if (ent->flags & TCP_HTTP_TRACK_FLG_OPEN) {
4310 if (tp->t_http_open > 0)
4313 if (tp->t_http_closed > 0)
4314 tp->t_http_closed--;
4316 ent->flags = TCP_HTTP_TRACK_FLG_EMPTY;
4320 tcp_http_check_for_stale_entries(struct tcpcb *tp, uint64_t ts, int rm_oldest)
4322 struct http_sendfile_track *ent;
4323 uint64_t time_delta, oldest_delta;
4324 int i, oldest, oldest_set = 0, cnt_rm = 0;
4326 for(i = 0; i < MAX_TCP_HTTP_REQ; i++) {
4327 ent = &tp->t_http_info[i];
4328 if (ent->flags != TCP_HTTP_TRACK_FLG_USED) {
4330 * We only care about closed end ranges
4331 * that are allocated and have no sendfile
4332 * ever touching them. They would be in
4337 if (ts >= ent->localtime)
4338 time_delta = ts - ent->localtime;
4342 ((oldest_delta < time_delta) || (oldest_set == 0))) {
4345 oldest_delta = time_delta;
4347 if (tcp_stale_entry_time && (time_delta >= tcp_stale_entry_time)) {
4349 * No sendfile in a our time-limit
4353 tcp_http_log_req_info(tp, &tp->t_http_info[i], i, TCP_HTTP_REQ_LOG_STALE,
4355 tcp_http_free_a_slot(tp, ent);
4358 if ((cnt_rm == 0) && rm_oldest && oldest_set) {
4359 ent = &tp->t_http_info[oldest];
4360 tcp_http_log_req_info(tp, &tp->t_http_info[i], i, TCP_HTTP_REQ_LOG_STALE,
4362 tcp_http_free_a_slot(tp, ent);
4367 tcp_http_check_for_comp(struct tcpcb *tp, tcp_seq ack_point)
4370 struct http_sendfile_track *ent;
4372 /* Clean up any old closed end requests that are now completed */
4373 if (tp->t_http_req == 0)
4375 if (tp->t_http_closed == 0)
4377 for(i = 0; i < MAX_TCP_HTTP_REQ; i++) {
4378 ent = &tp->t_http_info[i];
4379 /* Skip empty ones */
4380 if (ent->flags == TCP_HTTP_TRACK_FLG_EMPTY)
4382 /* Skip open ones */
4383 if (ent->flags & TCP_HTTP_TRACK_FLG_OPEN)
4385 if (SEQ_GEQ(ack_point, ent->end_seq)) {
4386 /* We are past it -- free it */
4387 tcp_http_log_req_info(tp, ent,
4388 i, TCP_HTTP_REQ_LOG_FREED, 0, 0);
4389 tcp_http_free_a_slot(tp, ent);
4397 tcp_http_is_entry_comp(struct tcpcb *tp, struct http_sendfile_track *ent, tcp_seq ack_point)
4399 if (tp->t_http_req == 0)
4401 if (tp->t_http_closed == 0)
4403 if (ent->flags == TCP_HTTP_TRACK_FLG_EMPTY)
4405 if (SEQ_GEQ(ack_point, ent->end_seq)) {
4411 struct http_sendfile_track *
4412 tcp_http_find_a_req_that_is_completed_by(struct tcpcb *tp, tcp_seq th_ack, int *ip)
4415 * Given an ack point (th_ack) walk through our entries and
4416 * return the first one found that th_ack goes past the
4419 struct http_sendfile_track *ent;
4422 if (tp->t_http_req == 0) {
4426 for(i = 0; i < MAX_TCP_HTTP_REQ; i++) {
4427 ent = &tp->t_http_info[i];
4428 if (ent->flags == TCP_HTTP_TRACK_FLG_EMPTY)
4430 if ((ent->flags & TCP_HTTP_TRACK_FLG_OPEN) == 0) {
4431 if (SEQ_GEQ(th_ack, ent->end_seq)) {
4440 struct http_sendfile_track *
4441 tcp_http_find_req_for_seq(struct tcpcb *tp, tcp_seq seq)
4443 struct http_sendfile_track *ent;
4446 if (tp->t_http_req == 0) {
4450 for(i = 0; i < MAX_TCP_HTTP_REQ; i++) {
4451 ent = &tp->t_http_info[i];
4452 tcp_http_log_req_info(tp, ent, i, TCP_HTTP_REQ_LOG_SEARCH,
4454 if (ent->flags == TCP_HTTP_TRACK_FLG_EMPTY) {
4457 if (ent->flags & TCP_HTTP_TRACK_FLG_OPEN) {
4459 * An open end request only needs to
4460 * match the beginning seq or be
4461 * all we have (once we keep going on
4462 * a open end request we may have a seq
4465 if ((SEQ_GEQ(seq, ent->start_seq)) ||
4466 (tp->t_http_closed == 0))
4470 * For this one we need to
4471 * be a bit more careful if its
4472 * completed at least.
4474 if ((SEQ_GEQ(seq, ent->start_seq)) &&
4475 (SEQ_LT(seq, ent->end_seq))) {
4483 /* Should this be in its own file tcp_http.c ? */
4484 struct http_sendfile_track *
4485 tcp_http_alloc_req_full(struct tcpcb *tp, struct http_req *req, uint64_t ts, int rec_dups)
4487 struct http_sendfile_track *fil;
4490 /* In case the stack does not check for completions do so now */
4491 tcp_http_check_for_comp(tp, tp->snd_una);
4492 /* Check for stale entries */
4494 tcp_http_check_for_stale_entries(tp, ts,
4495 (tp->t_http_req >= MAX_TCP_HTTP_REQ));
4496 /* Check to see if this is a duplicate of one not started */
4497 if (tp->t_http_req) {
4498 for(i = 0, allocated = 0; i < MAX_TCP_HTTP_REQ; i++) {
4499 fil = &tp->t_http_info[i];
4500 if (fil->flags != TCP_HTTP_TRACK_FLG_USED)
4502 if ((fil->timestamp == req->timestamp) &&
4503 (fil->start == req->start) &&
4504 ((fil->flags & TCP_HTTP_TRACK_FLG_OPEN) ||
4505 (fil->end == req->end))) {
4507 * We already have this request
4508 * and it has not been started with sendfile.
4509 * This probably means the user was returned
4510 * a 4xx of some sort and its going to age
4511 * out, lets not duplicate it.
4517 /* Ok if there is no room at the inn we are in trouble */
4518 if (tp->t_http_req >= MAX_TCP_HTTP_REQ) {
4519 tcp_trace_point(tp, TCP_TP_HTTP_LOG_FAIL);
4520 for(i = 0; i < MAX_TCP_HTTP_REQ; i++) {
4521 tcp_http_log_req_info(tp, &tp->t_http_info[i],
4522 i, TCP_HTTP_REQ_LOG_ALLOCFAIL, 0, 0);
4526 for(i = 0, allocated = 0; i < MAX_TCP_HTTP_REQ; i++) {
4527 fil = &tp->t_http_info[i];
4528 if (fil->flags == TCP_HTTP_TRACK_FLG_EMPTY) {
4530 fil->flags = TCP_HTTP_TRACK_FLG_USED;
4531 fil->timestamp = req->timestamp;
4532 fil->localtime = ts;
4533 fil->start = req->start;
4534 if (req->flags & TCP_LOG_HTTPD_RANGE_END) {
4535 fil->end = req->end;
4538 fil->flags |= TCP_HTTP_TRACK_FLG_OPEN;
4541 * We can set the min boundaries to the TCP Sequence space,
4542 * but it might be found to be further up when sendfile
4543 * actually runs on this range (if it ever does).
4545 fil->sbcc_at_s = tptosocket(tp)->so_snd.sb_ccc;
4546 fil->start_seq = tp->snd_una +
4547 tptosocket(tp)->so_snd.sb_ccc;
4548 fil->end_seq = (fil->start_seq + ((uint32_t)(fil->end - fil->start)));
4549 if (tptosocket(tp)->so_snd.sb_tls_info) {
4551 * This session is doing TLS. Take a swag guess
4554 fil->end_seq += tcp_estimate_tls_overhead(
4555 tptosocket(tp), (fil->end - fil->start));
4558 if (fil->flags & TCP_HTTP_TRACK_FLG_OPEN)
4561 tp->t_http_closed++;
4562 tcp_http_log_req_info(tp, fil, i,
4563 TCP_HTTP_REQ_LOG_NEW, 0, 0);
4572 tcp_http_alloc_req(struct tcpcb *tp, union tcp_log_userdata *user, uint64_t ts)
4574 (void)tcp_http_alloc_req_full(tp, &user->http_req, ts, 1);
4579 tcp_log_socket_option(struct tcpcb *tp, uint32_t option_num, uint32_t option_val, int err)
4581 if (tcp_bblogging_on(tp)) {
4582 struct tcp_log_buffer *l;
4584 l = tcp_log_event(tp, NULL,
4585 &tptosocket(tp)->so_rcv,
4586 &tptosocket(tp)->so_snd,
4589 NULL, NULL, 0, NULL);
4591 l->tlb_flex1 = option_num;
4592 l->tlb_flex2 = option_val;