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