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