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