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