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