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