xref: /freebsd/sys/netinet/tcp_subr.c (revision 95eb4b873b6a8b527c5bd78d7191975dfca38998)
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  * Send a challenge ack (no data, no SACK option), but not more than
2186  * tcp_ack_war_cnt per tcp_ack_war_time_window (per TCP connection).
2187  */
2188 void
2189 tcp_send_challenge_ack(struct tcpcb *tp, struct tcphdr *th, struct mbuf *m)
2190 {
2191 	sbintime_t now;
2192 	bool send_challenge_ack;
2193 
2194 	if (tcp_ack_war_time_window == 0 || tcp_ack_war_cnt == 0) {
2195 		/* ACK war protection is disabled. */
2196 		send_challenge_ack = true;
2197 	} else {
2198 		/* Start new epoch, if the previous one is already over. */
2199 		now = getsbinuptime();
2200 		if (tp->t_challenge_ack_end < now) {
2201 			tp->t_challenge_ack_cnt = 0;
2202 			tp->t_challenge_ack_end = now +
2203 			    tcp_ack_war_time_window * SBT_1MS;
2204 		}
2205 		/*
2206 		 * Send a challenge ACK, if less than tcp_ack_war_cnt have been
2207 		 * sent in the current epoch.
2208 		 */
2209 		if (tp->t_challenge_ack_cnt < tcp_ack_war_cnt) {
2210 			send_challenge_ack = true;
2211 			tp->t_challenge_ack_cnt++;
2212 		} else {
2213 			send_challenge_ack = false;
2214 		}
2215 	}
2216 	if (send_challenge_ack) {
2217 		tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2218 		    tp->snd_nxt, TH_ACK);
2219 		tp->last_ack_sent = tp->rcv_nxt;
2220 	}
2221 }
2222 
2223 /*
2224  * Create a new TCP control block, making an empty reassembly queue and hooking
2225  * it to the argument protocol control block.  The `inp' parameter must have
2226  * come from the zone allocator set up by tcpcbstor declaration.
2227  * The caller can provide a pointer to a tcpcb of the listener to inherit the
2228  * TCP function block from the listener.
2229  */
2230 struct tcpcb *
2231 tcp_newtcpcb(struct inpcb *inp, struct tcpcb *listening_tcb)
2232 {
2233 	struct tcpcb *tp = intotcpcb(inp);
2234 #ifdef INET6
2235 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2236 #endif /* INET6 */
2237 
2238 	/*
2239 	 * Historically allocation was done with M_ZERO.  There is a lot of
2240 	 * code that rely on that.  For now take safe approach and zero whole
2241 	 * tcpcb.  This definitely can be optimized.
2242 	 */
2243 	bzero(&tp->t_start_zero, t_zero_size);
2244 
2245 	/* Initialise cc_var struct for this tcpcb. */
2246 	tp->t_ccv.type = IPPROTO_TCP;
2247 	tp->t_ccv.ccvc.tcp = tp;
2248 	rw_rlock(&tcp_function_lock);
2249 	if (listening_tcb != NULL) {
2250 		INP_LOCK_ASSERT(tptoinpcb(listening_tcb));
2251 		KASSERT(listening_tcb->t_fb != NULL,
2252 		    ("tcp_newtcpcb: listening_tcb->t_fb is NULL"));
2253 		if (listening_tcb->t_fb->tfb_flags & TCP_FUNC_BEING_REMOVED) {
2254 			rw_runlock(&tcp_function_lock);
2255 			return (NULL);
2256 		}
2257 		tp->t_fb = listening_tcb->t_fb;
2258 	} else {
2259 		tp->t_fb = V_tcp_func_set_ptr;
2260 	}
2261 	refcount_acquire(&tp->t_fb->tfb_refcnt);
2262 	KASSERT((tp->t_fb->tfb_flags & TCP_FUNC_BEING_REMOVED) == 0,
2263 	    ("tcp_newtcpcb: using TFB being removed"));
2264 	rw_runlock(&tcp_function_lock);
2265 	/*
2266 	 * Use the current system default CC algorithm.
2267 	 */
2268 	cc_attach(tp, CC_DEFAULT_ALGO());
2269 
2270 	if (CC_ALGO(tp)->cb_init != NULL)
2271 		if (CC_ALGO(tp)->cb_init(&tp->t_ccv, NULL) > 0) {
2272 			cc_detach(tp);
2273 			if (tp->t_fb->tfb_tcp_fb_fini)
2274 				(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2275 			refcount_release(&tp->t_fb->tfb_refcnt);
2276 			return (NULL);
2277 		}
2278 
2279 #ifdef TCP_HHOOK
2280 	if (khelp_init_osd(HELPER_CLASS_TCP, &tp->t_osd)) {
2281 		if (CC_ALGO(tp)->cb_destroy != NULL)
2282 			CC_ALGO(tp)->cb_destroy(&tp->t_ccv);
2283 		CC_DATA(tp) = NULL;
2284 		cc_detach(tp);
2285 		if (tp->t_fb->tfb_tcp_fb_fini)
2286 			(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2287 		refcount_release(&tp->t_fb->tfb_refcnt);
2288 		return (NULL);
2289 	}
2290 #endif
2291 
2292 	TAILQ_INIT(&tp->t_segq);
2293 	STAILQ_INIT(&tp->t_inqueue);
2294 	tp->t_maxseg =
2295 #ifdef INET6
2296 		isipv6 ? V_tcp_v6mssdflt :
2297 #endif /* INET6 */
2298 		V_tcp_mssdflt;
2299 
2300 	/* All mbuf queue/ack compress flags should be off */
2301 	tcp_lro_features_off(tp);
2302 
2303 	tp->t_hpts_cpu = HPTS_CPU_NONE;
2304 	tp->t_lro_cpu = HPTS_CPU_NONE;
2305 
2306 	callout_init_rw(&tp->t_callout, &inp->inp_lock, CALLOUT_RETURNUNLOCKED);
2307 	for (int i = 0; i < TT_N; i++)
2308 		tp->t_timers[i] = SBT_MAX;
2309 
2310 	switch (V_tcp_do_rfc1323) {
2311 		case 0:
2312 			break;
2313 		default:
2314 		case 1:
2315 			tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
2316 			break;
2317 		case 2:
2318 			tp->t_flags = TF_REQ_SCALE;
2319 			break;
2320 		case 3:
2321 			tp->t_flags = TF_REQ_TSTMP;
2322 			break;
2323 	}
2324 	if (V_tcp_do_sack)
2325 		tp->t_flags |= TF_SACK_PERMIT;
2326 	TAILQ_INIT(&tp->snd_holes);
2327 
2328 	/*
2329 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
2330 	 * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
2331 	 * reasonable initial retransmit time.
2332 	 */
2333 	tp->t_srtt = TCPTV_SRTTBASE;
2334 	tp->t_rttvar = ((tcp_rexmit_initial - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
2335 	tp->t_rttmin = tcp_rexmit_min;
2336 	tp->t_rxtcur = tcp_rexmit_initial;
2337 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2338 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2339 	tp->t_rcvtime = ticks;
2340 	/* We always start with ticks granularity */
2341 	tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS;
2342 	/*
2343 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
2344 	 * because the socket may be bound to an IPv6 wildcard address,
2345 	 * which may match an IPv4-mapped IPv6 address.
2346 	 */
2347 	inp->inp_ip_ttl = V_ip_defttl;
2348 #ifdef TCPPCAP
2349 	/*
2350 	 * Init the TCP PCAP queues.
2351 	 */
2352 	tcp_pcap_tcpcb_init(tp);
2353 #endif
2354 #ifdef TCP_BLACKBOX
2355 	/* Initialize the per-TCPCB log data. */
2356 	tcp_log_tcpcbinit(tp);
2357 #endif
2358 	tp->t_pacing_rate = -1;
2359 	if (tp->t_fb->tfb_tcp_fb_init) {
2360 		if ((*tp->t_fb->tfb_tcp_fb_init)(tp, &tp->t_fb_ptr)) {
2361 			if (CC_ALGO(tp)->cb_destroy != NULL)
2362 				CC_ALGO(tp)->cb_destroy(&tp->t_ccv);
2363 			CC_DATA(tp) = NULL;
2364 			cc_detach(tp);
2365 #ifdef TCP_HHOOK
2366 			khelp_destroy_osd(&tp->t_osd);
2367 #endif
2368 			refcount_release(&tp->t_fb->tfb_refcnt);
2369 			return (NULL);
2370 		}
2371 	}
2372 #ifdef STATS
2373 	if (V_tcp_perconn_stats_enable == 1)
2374 		tp->t_stats = stats_blob_alloc(V_tcp_perconn_stats_dflt_tpl, 0);
2375 #endif
2376 	if (V_tcp_do_lrd)
2377 		tp->t_flags |= TF_LRD;
2378 
2379 	return (tp);
2380 }
2381 
2382 /*
2383  * Drop a TCP connection, reporting
2384  * the specified error.  If connection is synchronized,
2385  * then send a RST to peer.
2386  */
2387 struct tcpcb *
2388 tcp_drop(struct tcpcb *tp, int errno)
2389 {
2390 	struct socket *so = tptosocket(tp);
2391 
2392 	NET_EPOCH_ASSERT();
2393 	INP_WLOCK_ASSERT(tptoinpcb(tp));
2394 
2395 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
2396 		tcp_state_change(tp, TCPS_CLOSED);
2397 		/* Don't use tcp_output() here due to possible recursion. */
2398 		(void)tcp_output_nodrop(tp);
2399 		TCPSTAT_INC(tcps_drops);
2400 	} else
2401 		TCPSTAT_INC(tcps_conndrops);
2402 	if (errno == ETIMEDOUT && tp->t_softerror)
2403 		errno = tp->t_softerror;
2404 	so->so_error = errno;
2405 	return (tcp_close(tp));
2406 }
2407 
2408 void
2409 tcp_discardcb(struct tcpcb *tp)
2410 {
2411 	struct inpcb *inp = tptoinpcb(tp);
2412 	struct socket *so = tptosocket(tp);
2413 	struct mbuf *m;
2414 #ifdef INET6
2415 	bool isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2416 #endif
2417 
2418 	INP_WLOCK_ASSERT(inp);
2419 	MPASS(!callout_active(&tp->t_callout));
2420 	MPASS(TAILQ_EMPTY(&tp->snd_holes));
2421 
2422 	/* free the reassembly queue, if any */
2423 	tcp_reass_flush(tp);
2424 
2425 #ifdef TCP_OFFLOAD
2426 	/* Disconnect offload device, if any. */
2427 	if (tp->t_flags & TF_TOE)
2428 		tcp_offload_detach(tp);
2429 #endif
2430 #ifdef TCPPCAP
2431 	/* Free the TCP PCAP queues. */
2432 	tcp_pcap_drain(&(tp->t_inpkts));
2433 	tcp_pcap_drain(&(tp->t_outpkts));
2434 #endif
2435 
2436 	/* Allow the CC algorithm to clean up after itself. */
2437 	if (CC_ALGO(tp)->cb_destroy != NULL)
2438 		CC_ALGO(tp)->cb_destroy(&tp->t_ccv);
2439 	CC_DATA(tp) = NULL;
2440 	/* Detach from the CC algorithm */
2441 	cc_detach(tp);
2442 
2443 #ifdef TCP_HHOOK
2444 	khelp_destroy_osd(&tp->t_osd);
2445 #endif
2446 #ifdef STATS
2447 	stats_blob_destroy(tp->t_stats);
2448 #endif
2449 
2450 	CC_ALGO(tp) = NULL;
2451 	if ((m = STAILQ_FIRST(&tp->t_inqueue)) != NULL) {
2452 		struct mbuf *prev;
2453 
2454 		STAILQ_INIT(&tp->t_inqueue);
2455 		STAILQ_FOREACH_FROM_SAFE(m, &tp->t_inqueue, m_stailqpkt, prev)
2456 			m_freem(m);
2457 	}
2458 	TCPSTATES_DEC(tp->t_state);
2459 
2460 	if (tp->t_fb->tfb_tcp_fb_fini)
2461 		(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2462 	MPASS(!tcp_in_hpts(tp));
2463 #ifdef TCP_BLACKBOX
2464 	tcp_log_tcpcbfini(tp);
2465 #endif
2466 
2467 	/*
2468 	 * If we got enough samples through the srtt filter,
2469 	 * save the rtt and rttvar in the routing entry.
2470 	 * 'Enough' is arbitrarily defined as 4 rtt samples.
2471 	 * 4 samples is enough for the srtt filter to converge
2472 	 * to within enough % of the correct value; fewer samples
2473 	 * and we could save a bogus rtt. The danger is not high
2474 	 * as tcp quickly recovers from everything.
2475 	 * XXX: Works very well but needs some more statistics!
2476 	 *
2477 	 * XXXRRS: Updating must be after the stack fini() since
2478 	 * that may be converting some internal representation of
2479 	 * say srtt etc into the general one used by other stacks.
2480 	 * Lets also at least protect against the so being NULL
2481 	 * as RW stated below.
2482 	 */
2483 	if ((tp->t_rttupdated >= 4) && (so != NULL)) {
2484 		struct hc_metrics_lite metrics;
2485 		uint32_t ssthresh;
2486 
2487 		bzero(&metrics, sizeof(metrics));
2488 		/*
2489 		 * Update the ssthresh always when the conditions below
2490 		 * are satisfied. This gives us better new start value
2491 		 * for the congestion avoidance for new connections.
2492 		 * ssthresh is only set if packet loss occurred on a session.
2493 		 *
2494 		 * XXXRW: 'so' may be NULL here, and/or socket buffer may be
2495 		 * being torn down.  Ideally this code would not use 'so'.
2496 		 */
2497 		ssthresh = tp->snd_ssthresh;
2498 		if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
2499 			/*
2500 			 * convert the limit from user data bytes to
2501 			 * packets then to packet data bytes.
2502 			 */
2503 			ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
2504 			if (ssthresh < 2)
2505 				ssthresh = 2;
2506 			ssthresh *= (tp->t_maxseg +
2507 #ifdef INET6
2508 			    (isipv6 ? sizeof (struct ip6_hdr) +
2509 			    sizeof (struct tcphdr) :
2510 #endif
2511 			    sizeof (struct tcpiphdr)
2512 #ifdef INET6
2513 			    )
2514 #endif
2515 			    );
2516 		} else
2517 			ssthresh = 0;
2518 		metrics.rmx_ssthresh = ssthresh;
2519 
2520 		metrics.rmx_rtt = tp->t_srtt;
2521 		metrics.rmx_rttvar = tp->t_rttvar;
2522 		metrics.rmx_cwnd = tp->snd_cwnd;
2523 		metrics.rmx_sendpipe = 0;
2524 		metrics.rmx_recvpipe = 0;
2525 
2526 		tcp_hc_update(&inp->inp_inc, &metrics);
2527 	}
2528 
2529 	refcount_release(&tp->t_fb->tfb_refcnt);
2530 }
2531 
2532 /*
2533  * Attempt to close a TCP control block, marking it as dropped, and freeing
2534  * the socket if we hold the only reference.
2535  */
2536 struct tcpcb *
2537 tcp_close(struct tcpcb *tp)
2538 {
2539 	struct inpcb *inp = tptoinpcb(tp);
2540 	struct socket *so = tptosocket(tp);
2541 
2542 	INP_WLOCK_ASSERT(inp);
2543 
2544 #ifdef TCP_OFFLOAD
2545 	if (tp->t_state == TCPS_LISTEN)
2546 		tcp_offload_listen_stop(tp);
2547 #endif
2548 	/*
2549 	 * This releases the TFO pending counter resource for TFO listen
2550 	 * sockets as well as passively-created TFO sockets that transition
2551 	 * from SYN_RECEIVED to CLOSED.
2552 	 */
2553 	if (tp->t_tfo_pending) {
2554 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2555 		tp->t_tfo_pending = NULL;
2556 	}
2557 	tcp_timer_stop(tp);
2558 	if (tp->t_fb->tfb_tcp_timer_stop_all != NULL)
2559 		tp->t_fb->tfb_tcp_timer_stop_all(tp);
2560 	in_pcbdrop(inp);
2561 	TCPSTAT_INC(tcps_closed);
2562 	if (tp->t_state != TCPS_CLOSED)
2563 		tcp_state_change(tp, TCPS_CLOSED);
2564 	KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
2565 	tcp_free_sackholes(tp);
2566 	soisdisconnected(so);
2567 	if (inp->inp_flags & INP_SOCKREF) {
2568 		inp->inp_flags &= ~INP_SOCKREF;
2569 		INP_WUNLOCK(inp);
2570 		sorele(so);
2571 		return (NULL);
2572 	}
2573 	return (tp);
2574 }
2575 
2576 /*
2577  * Notify a tcp user of an asynchronous error;
2578  * store error as soft error, but wake up user
2579  * (for now, won't do anything until can select for soft error).
2580  *
2581  * Do not wake up user since there currently is no mechanism for
2582  * reporting soft errors (yet - a kqueue filter may be added).
2583  */
2584 static struct inpcb *
2585 tcp_notify(struct inpcb *inp, int error)
2586 {
2587 	struct tcpcb *tp;
2588 
2589 	INP_WLOCK_ASSERT(inp);
2590 
2591 	tp = intotcpcb(inp);
2592 	KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
2593 
2594 	/*
2595 	 * Ignore some errors if we are hooked up.
2596 	 * If connection hasn't completed, has retransmitted several times,
2597 	 * and receives a second error, give up now.  This is better
2598 	 * than waiting a long time to establish a connection that
2599 	 * can never complete.
2600 	 */
2601 	if (tp->t_state == TCPS_ESTABLISHED &&
2602 	    (error == EHOSTUNREACH || error == ENETUNREACH ||
2603 	     error == EHOSTDOWN)) {
2604 		if (inp->inp_route.ro_nh) {
2605 			NH_FREE(inp->inp_route.ro_nh);
2606 			inp->inp_route.ro_nh = (struct nhop_object *)NULL;
2607 		}
2608 		return (inp);
2609 	} else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
2610 	    tp->t_softerror) {
2611 		tp = tcp_drop(tp, error);
2612 		if (tp != NULL)
2613 			return (inp);
2614 		else
2615 			return (NULL);
2616 	} else {
2617 		tp->t_softerror = error;
2618 		return (inp);
2619 	}
2620 #if 0
2621 	wakeup( &so->so_timeo);
2622 	sorwakeup(so);
2623 	sowwakeup(so);
2624 #endif
2625 }
2626 
2627 static int
2628 tcp_pcblist(SYSCTL_HANDLER_ARGS)
2629 {
2630 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
2631 	    INPLOOKUP_RLOCKPCB);
2632 	struct xinpgen xig;
2633 	struct inpcb *inp;
2634 	int error;
2635 
2636 	if (req->newptr != NULL)
2637 		return (EPERM);
2638 
2639 	if (req->oldptr == NULL) {
2640 		int n;
2641 
2642 		n = V_tcbinfo.ipi_count +
2643 		    counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2644 		n += imax(n / 8, 10);
2645 		req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb);
2646 		return (0);
2647 	}
2648 
2649 	if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
2650 		return (error);
2651 
2652 	bzero(&xig, sizeof(xig));
2653 	xig.xig_len = sizeof xig;
2654 	xig.xig_count = V_tcbinfo.ipi_count +
2655 	    counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2656 	xig.xig_gen = V_tcbinfo.ipi_gencnt;
2657 	xig.xig_sogen = so_gencnt;
2658 	error = SYSCTL_OUT(req, &xig, sizeof xig);
2659 	if (error)
2660 		return (error);
2661 
2662 	error = syncache_pcblist(req);
2663 	if (error)
2664 		return (error);
2665 
2666 	while ((inp = inp_next(&inpi)) != NULL) {
2667 		if (inp->inp_gencnt <= xig.xig_gen &&
2668 		    cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
2669 			struct xtcpcb xt;
2670 
2671 			tcp_inptoxtp(inp, &xt);
2672 			error = SYSCTL_OUT(req, &xt, sizeof xt);
2673 			if (error) {
2674 				INP_RUNLOCK(inp);
2675 				break;
2676 			} else
2677 				continue;
2678 		}
2679 	}
2680 
2681 	if (!error) {
2682 		/*
2683 		 * Give the user an updated idea of our state.
2684 		 * If the generation differs from what we told
2685 		 * her before, she knows that something happened
2686 		 * while we were processing this request, and it
2687 		 * might be necessary to retry.
2688 		 */
2689 		xig.xig_gen = V_tcbinfo.ipi_gencnt;
2690 		xig.xig_sogen = so_gencnt;
2691 		xig.xig_count = V_tcbinfo.ipi_count +
2692 		    counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2693 		error = SYSCTL_OUT(req, &xig, sizeof xig);
2694 	}
2695 
2696 	return (error);
2697 }
2698 
2699 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist,
2700     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
2701     NULL, 0, tcp_pcblist, "S,xtcpcb",
2702     "List of active TCP connections");
2703 
2704 #ifdef INET
2705 static int
2706 tcp_getcred(SYSCTL_HANDLER_ARGS)
2707 {
2708 	struct xucred xuc;
2709 	struct sockaddr_in addrs[2];
2710 	struct epoch_tracker et;
2711 	struct inpcb *inp;
2712 	int error;
2713 
2714 	error = priv_check(req->td, PRIV_NETINET_GETCRED);
2715 	if (error)
2716 		return (error);
2717 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
2718 	if (error)
2719 		return (error);
2720 	NET_EPOCH_ENTER(et);
2721 	inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
2722 	    addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL);
2723 	NET_EPOCH_EXIT(et);
2724 	if (inp != NULL) {
2725 		if (error == 0)
2726 			error = cr_canseeinpcb(req->td->td_ucred, inp);
2727 		if (error == 0)
2728 			cru2x(inp->inp_cred, &xuc);
2729 		INP_RUNLOCK(inp);
2730 	} else
2731 		error = ENOENT;
2732 	if (error == 0)
2733 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2734 	return (error);
2735 }
2736 
2737 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
2738     CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
2739     0, 0, tcp_getcred, "S,xucred",
2740     "Get the xucred of a TCP connection");
2741 #endif /* INET */
2742 
2743 #ifdef INET6
2744 static int
2745 tcp6_getcred(SYSCTL_HANDLER_ARGS)
2746 {
2747 	struct epoch_tracker et;
2748 	struct xucred xuc;
2749 	struct sockaddr_in6 addrs[2];
2750 	struct inpcb *inp;
2751 	int error;
2752 #ifdef INET
2753 	int mapped = 0;
2754 #endif
2755 
2756 	error = priv_check(req->td, PRIV_NETINET_GETCRED);
2757 	if (error)
2758 		return (error);
2759 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
2760 	if (error)
2761 		return (error);
2762 	if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
2763 	    (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
2764 		return (error);
2765 	}
2766 	if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
2767 #ifdef INET
2768 		if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
2769 			mapped = 1;
2770 		else
2771 #endif
2772 			return (EINVAL);
2773 	}
2774 
2775 	NET_EPOCH_ENTER(et);
2776 #ifdef INET
2777 	if (mapped == 1)
2778 		inp = in_pcblookup(&V_tcbinfo,
2779 			*(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
2780 			addrs[1].sin6_port,
2781 			*(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
2782 			addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL);
2783 	else
2784 #endif
2785 		inp = in6_pcblookup(&V_tcbinfo,
2786 			&addrs[1].sin6_addr, addrs[1].sin6_port,
2787 			&addrs[0].sin6_addr, addrs[0].sin6_port,
2788 			INPLOOKUP_RLOCKPCB, NULL);
2789 	NET_EPOCH_EXIT(et);
2790 	if (inp != NULL) {
2791 		if (error == 0)
2792 			error = cr_canseeinpcb(req->td->td_ucred, inp);
2793 		if (error == 0)
2794 			cru2x(inp->inp_cred, &xuc);
2795 		INP_RUNLOCK(inp);
2796 	} else
2797 		error = ENOENT;
2798 	if (error == 0)
2799 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2800 	return (error);
2801 }
2802 
2803 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
2804     CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
2805     0, 0, tcp6_getcred, "S,xucred",
2806     "Get the xucred of a TCP6 connection");
2807 #endif /* INET6 */
2808 
2809 #ifdef INET
2810 /* Path MTU to try next when a fragmentation-needed message is received. */
2811 static inline int
2812 tcp_next_pmtu(const struct icmp *icp, const struct ip *ip)
2813 {
2814 	int mtu = ntohs(icp->icmp_nextmtu);
2815 
2816 	/* If no alternative MTU was proposed, try the next smaller one. */
2817 	if (!mtu)
2818 		mtu = ip_next_mtu(ntohs(ip->ip_len), 1);
2819 	if (mtu < V_tcp_minmss + sizeof(struct tcpiphdr))
2820 		mtu = V_tcp_minmss + sizeof(struct tcpiphdr);
2821 
2822 	return (mtu);
2823 }
2824 
2825 static void
2826 tcp_ctlinput_with_port(struct icmp *icp, uint16_t port)
2827 {
2828 	struct ip *ip;
2829 	struct tcphdr *th;
2830 	struct inpcb *inp;
2831 	struct tcpcb *tp;
2832 	struct inpcb *(*notify)(struct inpcb *, int);
2833 	struct in_conninfo inc;
2834 	tcp_seq icmp_tcp_seq;
2835 	int errno, mtu;
2836 
2837 	errno = icmp_errmap(icp);
2838 	switch (errno) {
2839 	case 0:
2840 		return;
2841 	case EMSGSIZE:
2842 		notify = tcp_mtudisc_notify;
2843 		break;
2844 	case ECONNREFUSED:
2845 		if (V_icmp_may_rst)
2846 			notify = tcp_drop_syn_sent;
2847 		else
2848 			notify = tcp_notify;
2849 		break;
2850 	case EHOSTUNREACH:
2851 		if (V_icmp_may_rst && icp->icmp_type == ICMP_TIMXCEED)
2852 			notify = tcp_drop_syn_sent;
2853 		else
2854 			notify = tcp_notify;
2855 		break;
2856 	default:
2857 		notify = tcp_notify;
2858 	}
2859 
2860 	ip = &icp->icmp_ip;
2861 	th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2862 	icmp_tcp_seq = th->th_seq;
2863 	inp = in_pcblookup(&V_tcbinfo, ip->ip_dst, th->th_dport, ip->ip_src,
2864 	    th->th_sport, INPLOOKUP_WLOCKPCB, NULL);
2865 	if (inp != NULL)  {
2866 		tp = intotcpcb(inp);
2867 #ifdef TCP_OFFLOAD
2868 		if (tp->t_flags & TF_TOE && errno == EMSGSIZE) {
2869 			/*
2870 			 * MTU discovery for offloaded connections.  Let
2871 			 * the TOE driver verify seq# and process it.
2872 			 */
2873 			mtu = tcp_next_pmtu(icp, ip);
2874 			tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu);
2875 			goto out;
2876 		}
2877 #endif
2878 		if (tp->t_port != port)
2879 			goto out;
2880 		if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
2881 		    SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
2882 			if (errno == EMSGSIZE) {
2883 				/*
2884 				 * MTU discovery: we got a needfrag and
2885 				 * will potentially try a lower MTU.
2886 				 */
2887 				mtu = tcp_next_pmtu(icp, ip);
2888 
2889 				/*
2890 				 * Only process the offered MTU if it
2891 				 * is smaller than the current one.
2892 				 */
2893 				if (mtu < tp->t_maxseg +
2894 				    sizeof(struct tcpiphdr)) {
2895 					bzero(&inc, sizeof(inc));
2896 					inc.inc_faddr = ip->ip_dst;
2897 					inc.inc_fibnum =
2898 					    inp->inp_inc.inc_fibnum;
2899 					tcp_hc_updatemtu(&inc, mtu);
2900 					inp = tcp_mtudisc(inp, mtu);
2901 				}
2902 			} else
2903 				inp = (*notify)(inp, errno);
2904 		}
2905 	} else {
2906 		bzero(&inc, sizeof(inc));
2907 		inc.inc_fport = th->th_dport;
2908 		inc.inc_lport = th->th_sport;
2909 		inc.inc_faddr = ip->ip_dst;
2910 		inc.inc_laddr = ip->ip_src;
2911 		syncache_unreach(&inc, icmp_tcp_seq, port);
2912 	}
2913 out:
2914 	if (inp != NULL)
2915 		INP_WUNLOCK(inp);
2916 }
2917 
2918 static void
2919 tcp_ctlinput(struct icmp *icmp)
2920 {
2921 	tcp_ctlinput_with_port(icmp, htons(0));
2922 }
2923 
2924 static void
2925 tcp_ctlinput_viaudp(udp_tun_icmp_param_t param)
2926 {
2927 	/* Its a tunneled TCP over UDP icmp */
2928 	struct icmp *icmp = param.icmp;
2929 	struct ip *outer_ip, *inner_ip;
2930 	struct udphdr *udp;
2931 	struct tcphdr *th, ttemp;
2932 	int i_hlen, o_len;
2933 	uint16_t port;
2934 
2935 	outer_ip = (struct ip *)((caddr_t)icmp - sizeof(struct ip));
2936 	inner_ip = &icmp->icmp_ip;
2937 	i_hlen = inner_ip->ip_hl << 2;
2938 	o_len = ntohs(outer_ip->ip_len);
2939 	if (o_len <
2940 	    (sizeof(struct ip) + 8 + i_hlen + sizeof(struct udphdr) + offsetof(struct tcphdr, th_ack))) {
2941 		/* Not enough data present */
2942 		return;
2943 	}
2944 	/* Ok lets strip out the inner udphdr header by copying up on top of it the tcp hdr */
2945 	udp = (struct udphdr *)(((caddr_t)inner_ip) + i_hlen);
2946 	if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
2947 		return;
2948 	}
2949 	port = udp->uh_dport;
2950 	th = (struct tcphdr *)(udp + 1);
2951 	memcpy(&ttemp, th, sizeof(struct tcphdr));
2952 	memcpy(udp, &ttemp, sizeof(struct tcphdr));
2953 	/* Now adjust down the size of the outer IP header */
2954 	o_len -= sizeof(struct udphdr);
2955 	outer_ip->ip_len = htons(o_len);
2956 	/* Now call in to the normal handling code */
2957 	tcp_ctlinput_with_port(icmp, port);
2958 }
2959 #endif /* INET */
2960 
2961 #ifdef INET6
2962 static inline int
2963 tcp6_next_pmtu(const struct icmp6_hdr *icmp6)
2964 {
2965 	int mtu = ntohl(icmp6->icmp6_mtu);
2966 
2967 	/*
2968 	 * If no alternative MTU was proposed, or the proposed MTU was too
2969 	 * small, set to the min.
2970 	 */
2971 	if (mtu < IPV6_MMTU)
2972 		mtu = IPV6_MMTU - 8;	/* XXXNP: what is the adjustment for? */
2973 	return (mtu);
2974 }
2975 
2976 static void
2977 tcp6_ctlinput_with_port(struct ip6ctlparam *ip6cp, uint16_t port)
2978 {
2979 	struct in6_addr *dst;
2980 	struct inpcb *(*notify)(struct inpcb *, int);
2981 	struct ip6_hdr *ip6;
2982 	struct mbuf *m;
2983 	struct inpcb *inp;
2984 	struct tcpcb *tp;
2985 	struct icmp6_hdr *icmp6;
2986 	struct in_conninfo inc;
2987 	struct tcp_ports {
2988 		uint16_t th_sport;
2989 		uint16_t th_dport;
2990 	} t_ports;
2991 	tcp_seq icmp_tcp_seq;
2992 	unsigned int mtu;
2993 	unsigned int off;
2994 	int errno;
2995 
2996 	icmp6 = ip6cp->ip6c_icmp6;
2997 	m = ip6cp->ip6c_m;
2998 	ip6 = ip6cp->ip6c_ip6;
2999 	off = ip6cp->ip6c_off;
3000 	dst = &ip6cp->ip6c_finaldst->sin6_addr;
3001 
3002 	errno = icmp6_errmap(icmp6);
3003 	switch (errno) {
3004 	case 0:
3005 		return;
3006 	case EMSGSIZE:
3007 		notify = tcp_mtudisc_notify;
3008 		break;
3009 	case ECONNREFUSED:
3010 		if (V_icmp_may_rst)
3011 			notify = tcp_drop_syn_sent;
3012 		else
3013 			notify = tcp_notify;
3014 		break;
3015 	case EHOSTUNREACH:
3016 		/*
3017 		 * There are only four ICMPs that may reset connection:
3018 		 * - administratively prohibited
3019 		 * - port unreachable
3020 		 * - time exceeded in transit
3021 		 * - unknown next header
3022 		 */
3023 		if (V_icmp_may_rst &&
3024 		    ((icmp6->icmp6_type == ICMP6_DST_UNREACH &&
3025 		     (icmp6->icmp6_code == ICMP6_DST_UNREACH_ADMIN ||
3026 		      icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT)) ||
3027 		    (icmp6->icmp6_type == ICMP6_TIME_EXCEEDED &&
3028 		      icmp6->icmp6_code == ICMP6_TIME_EXCEED_TRANSIT) ||
3029 		    (icmp6->icmp6_type == ICMP6_PARAM_PROB &&
3030 		      icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER)))
3031 			notify = tcp_drop_syn_sent;
3032 		else
3033 			notify = tcp_notify;
3034 		break;
3035 	default:
3036 		notify = tcp_notify;
3037 	}
3038 
3039 	/* Check if we can safely get the ports from the tcp hdr */
3040 	if (m == NULL ||
3041 	    (m->m_pkthdr.len <
3042 		(int32_t) (off + sizeof(struct tcp_ports)))) {
3043 		return;
3044 	}
3045 	bzero(&t_ports, sizeof(struct tcp_ports));
3046 	m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports);
3047 	inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport,
3048 	    &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL);
3049 	off += sizeof(struct tcp_ports);
3050 	if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) {
3051 		goto out;
3052 	}
3053 	m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq);
3054 	if (inp != NULL)  {
3055 		tp = intotcpcb(inp);
3056 #ifdef TCP_OFFLOAD
3057 		if (tp->t_flags & TF_TOE && errno == EMSGSIZE) {
3058 			/* MTU discovery for offloaded connections. */
3059 			mtu = tcp6_next_pmtu(icmp6);
3060 			tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu);
3061 			goto out;
3062 		}
3063 #endif
3064 		if (tp->t_port != port)
3065 			goto out;
3066 		if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
3067 		    SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
3068 			if (errno == EMSGSIZE) {
3069 				/*
3070 				 * MTU discovery:
3071 				 * If we got a needfrag set the MTU
3072 				 * in the route to the suggested new
3073 				 * value (if given) and then notify.
3074 				 */
3075 				mtu = tcp6_next_pmtu(icmp6);
3076 
3077 				bzero(&inc, sizeof(inc));
3078 				inc.inc_fibnum = M_GETFIB(m);
3079 				inc.inc_flags |= INC_ISIPV6;
3080 				inc.inc6_faddr = *dst;
3081 				if (in6_setscope(&inc.inc6_faddr,
3082 					m->m_pkthdr.rcvif, NULL))
3083 					goto out;
3084 				/*
3085 				 * Only process the offered MTU if it
3086 				 * is smaller than the current one.
3087 				 */
3088 				if (mtu < tp->t_maxseg +
3089 				    sizeof (struct tcphdr) +
3090 				    sizeof (struct ip6_hdr)) {
3091 					tcp_hc_updatemtu(&inc, mtu);
3092 					tcp_mtudisc(inp, mtu);
3093 					ICMP6STAT_INC(icp6s_pmtuchg);
3094 				}
3095 			} else
3096 				inp = (*notify)(inp, errno);
3097 		}
3098 	} else {
3099 		bzero(&inc, sizeof(inc));
3100 		inc.inc_fibnum = M_GETFIB(m);
3101 		inc.inc_flags |= INC_ISIPV6;
3102 		inc.inc_fport = t_ports.th_dport;
3103 		inc.inc_lport = t_ports.th_sport;
3104 		inc.inc6_faddr = *dst;
3105 		inc.inc6_laddr = ip6->ip6_src;
3106 		syncache_unreach(&inc, icmp_tcp_seq, port);
3107 	}
3108 out:
3109 	if (inp != NULL)
3110 		INP_WUNLOCK(inp);
3111 }
3112 
3113 static void
3114 tcp6_ctlinput(struct ip6ctlparam *ctl)
3115 {
3116 	tcp6_ctlinput_with_port(ctl, htons(0));
3117 }
3118 
3119 static void
3120 tcp6_ctlinput_viaudp(udp_tun_icmp_param_t param)
3121 {
3122 	struct ip6ctlparam *ip6cp = param.ip6cp;
3123 	struct mbuf *m;
3124 	struct udphdr *udp;
3125 	uint16_t port;
3126 
3127 	m = m_pulldown(ip6cp->ip6c_m, ip6cp->ip6c_off, sizeof(struct udphdr), NULL);
3128 	if (m == NULL) {
3129 		return;
3130 	}
3131 	udp = mtod(m, struct udphdr *);
3132 	if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
3133 		return;
3134 	}
3135 	port = udp->uh_dport;
3136 	m_adj(m, sizeof(struct udphdr));
3137 	if ((m->m_flags & M_PKTHDR) == 0) {
3138 		ip6cp->ip6c_m->m_pkthdr.len -= sizeof(struct udphdr);
3139 	}
3140 	/* Now call in to the normal handling code */
3141 	tcp6_ctlinput_with_port(ip6cp, port);
3142 }
3143 
3144 #endif /* INET6 */
3145 
3146 static uint32_t
3147 tcp_keyed_hash(struct in_conninfo *inc, u_char *key, u_int len)
3148 {
3149 	SIPHASH_CTX ctx;
3150 	uint32_t hash[2];
3151 
3152 	KASSERT(len >= SIPHASH_KEY_LENGTH,
3153 	    ("%s: keylen %u too short ", __func__, len));
3154 	SipHash24_Init(&ctx);
3155 	SipHash_SetKey(&ctx, (uint8_t *)key);
3156 	SipHash_Update(&ctx, &inc->inc_fport, sizeof(uint16_t));
3157 	SipHash_Update(&ctx, &inc->inc_lport, sizeof(uint16_t));
3158 	switch (inc->inc_flags & INC_ISIPV6) {
3159 #ifdef INET
3160 	case 0:
3161 		SipHash_Update(&ctx, &inc->inc_faddr, sizeof(struct in_addr));
3162 		SipHash_Update(&ctx, &inc->inc_laddr, sizeof(struct in_addr));
3163 		break;
3164 #endif
3165 #ifdef INET6
3166 	case INC_ISIPV6:
3167 		SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(struct in6_addr));
3168 		SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(struct in6_addr));
3169 		break;
3170 #endif
3171 	}
3172 	SipHash_Final((uint8_t *)hash, &ctx);
3173 
3174 	return (hash[0] ^ hash[1]);
3175 }
3176 
3177 uint32_t
3178 tcp_new_ts_offset(struct in_conninfo *inc)
3179 {
3180 	struct in_conninfo inc_store, *local_inc;
3181 
3182 	if (!V_tcp_ts_offset_per_conn) {
3183 		memcpy(&inc_store, inc, sizeof(struct in_conninfo));
3184 		inc_store.inc_lport = 0;
3185 		inc_store.inc_fport = 0;
3186 		local_inc = &inc_store;
3187 	} else {
3188 		local_inc = inc;
3189 	}
3190 	return (tcp_keyed_hash(local_inc, V_ts_offset_secret,
3191 	    sizeof(V_ts_offset_secret)));
3192 }
3193 
3194 /*
3195  * Following is where TCP initial sequence number generation occurs.
3196  *
3197  * There are two places where we must use initial sequence numbers:
3198  * 1.  In SYN-ACK packets.
3199  * 2.  In SYN packets.
3200  *
3201  * All ISNs for SYN-ACK packets are generated by the syncache.  See
3202  * tcp_syncache.c for details.
3203  *
3204  * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
3205  * depends on this property.  In addition, these ISNs should be
3206  * unguessable so as to prevent connection hijacking.  To satisfy
3207  * the requirements of this situation, the algorithm outlined in
3208  * RFC 1948 is used, with only small modifications.
3209  *
3210  * Implementation details:
3211  *
3212  * Time is based off the system timer, and is corrected so that it
3213  * increases by one megabyte per second.  This allows for proper
3214  * recycling on high speed LANs while still leaving over an hour
3215  * before rollover.
3216  *
3217  * As reading the *exact* system time is too expensive to be done
3218  * whenever setting up a TCP connection, we increment the time
3219  * offset in two ways.  First, a small random positive increment
3220  * is added to isn_offset for each connection that is set up.
3221  * Second, the function tcp_isn_tick fires once per clock tick
3222  * and increments isn_offset as necessary so that sequence numbers
3223  * are incremented at approximately ISN_BYTES_PER_SECOND.  The
3224  * random positive increments serve only to ensure that the same
3225  * exact sequence number is never sent out twice (as could otherwise
3226  * happen when a port is recycled in less than the system tick
3227  * interval.)
3228  *
3229  * net.inet.tcp.isn_reseed_interval controls the number of seconds
3230  * between seeding of isn_secret.  This is normally set to zero,
3231  * as reseeding should not be necessary.
3232  *
3233  * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
3234  * isn_offset_old, and isn_ctx is performed using the ISN lock.  In
3235  * general, this means holding an exclusive (write) lock.
3236  */
3237 
3238 #define ISN_BYTES_PER_SECOND 1048576
3239 #define ISN_STATIC_INCREMENT 4096
3240 #define ISN_RANDOM_INCREMENT (4096 - 1)
3241 #define ISN_SECRET_LENGTH    SIPHASH_KEY_LENGTH
3242 
3243 VNET_DEFINE_STATIC(u_char, isn_secret[ISN_SECRET_LENGTH]);
3244 VNET_DEFINE_STATIC(int, isn_last);
3245 VNET_DEFINE_STATIC(int, isn_last_reseed);
3246 VNET_DEFINE_STATIC(u_int32_t, isn_offset);
3247 VNET_DEFINE_STATIC(u_int32_t, isn_offset_old);
3248 
3249 #define	V_isn_secret			VNET(isn_secret)
3250 #define	V_isn_last			VNET(isn_last)
3251 #define	V_isn_last_reseed		VNET(isn_last_reseed)
3252 #define	V_isn_offset			VNET(isn_offset)
3253 #define	V_isn_offset_old		VNET(isn_offset_old)
3254 
3255 tcp_seq
3256 tcp_new_isn(struct in_conninfo *inc)
3257 {
3258 	tcp_seq new_isn;
3259 	u_int32_t projected_offset;
3260 
3261 	ISN_LOCK();
3262 	/* Seed if this is the first use, reseed if requested. */
3263 	if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) &&
3264 	     (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz)
3265 		< (u_int)ticks))) {
3266 		arc4rand(&V_isn_secret, sizeof(V_isn_secret), 0);
3267 		V_isn_last_reseed = ticks;
3268 	}
3269 
3270 	/* Compute the hash and return the ISN. */
3271 	new_isn = (tcp_seq)tcp_keyed_hash(inc, V_isn_secret,
3272 	    sizeof(V_isn_secret));
3273 	V_isn_offset += ISN_STATIC_INCREMENT +
3274 		(arc4random() & ISN_RANDOM_INCREMENT);
3275 	if (ticks != V_isn_last) {
3276 		projected_offset = V_isn_offset_old +
3277 		    ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last);
3278 		if (SEQ_GT(projected_offset, V_isn_offset))
3279 			V_isn_offset = projected_offset;
3280 		V_isn_offset_old = V_isn_offset;
3281 		V_isn_last = ticks;
3282 	}
3283 	new_isn += V_isn_offset;
3284 	ISN_UNLOCK();
3285 	return (new_isn);
3286 }
3287 
3288 /*
3289  * When a specific ICMP unreachable message is received and the
3290  * connection state is SYN-SENT, drop the connection.  This behavior
3291  * is controlled by the icmp_may_rst sysctl.
3292  */
3293 static struct inpcb *
3294 tcp_drop_syn_sent(struct inpcb *inp, int errno)
3295 {
3296 	struct tcpcb *tp;
3297 
3298 	NET_EPOCH_ASSERT();
3299 	INP_WLOCK_ASSERT(inp);
3300 
3301 	tp = intotcpcb(inp);
3302 	if (tp->t_state != TCPS_SYN_SENT)
3303 		return (inp);
3304 
3305 	if (tp->t_flags & TF_FASTOPEN)
3306 		tcp_fastopen_disable_path(tp);
3307 
3308 	tp = tcp_drop(tp, errno);
3309 	if (tp != NULL)
3310 		return (inp);
3311 	else
3312 		return (NULL);
3313 }
3314 
3315 /*
3316  * When `need fragmentation' ICMP is received, update our idea of the MSS
3317  * based on the new value. Also nudge TCP to send something, since we
3318  * know the packet we just sent was dropped.
3319  * This duplicates some code in the tcp_mss() function in tcp_input.c.
3320  */
3321 static struct inpcb *
3322 tcp_mtudisc_notify(struct inpcb *inp, int error)
3323 {
3324 
3325 	return (tcp_mtudisc(inp, -1));
3326 }
3327 
3328 static struct inpcb *
3329 tcp_mtudisc(struct inpcb *inp, int mtuoffer)
3330 {
3331 	struct tcpcb *tp;
3332 	struct socket *so;
3333 
3334 	INP_WLOCK_ASSERT(inp);
3335 
3336 	tp = intotcpcb(inp);
3337 	KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
3338 
3339 	tcp_mss_update(tp, -1, mtuoffer, NULL, NULL);
3340 
3341 	so = inp->inp_socket;
3342 	SOCKBUF_LOCK(&so->so_snd);
3343 	/* If the mss is larger than the socket buffer, decrease the mss. */
3344 	if (so->so_snd.sb_hiwat < tp->t_maxseg) {
3345 		tp->t_maxseg = so->so_snd.sb_hiwat;
3346 		if (tp->t_maxseg < V_tcp_mssdflt) {
3347 			/*
3348 			 * The MSS is so small we should not process incoming
3349 			 * SACK's since we are subject to attack in such a
3350 			 * case.
3351 			 */
3352 			tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT;
3353 		} else {
3354 			tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT;
3355 		}
3356 	}
3357 	SOCKBUF_UNLOCK(&so->so_snd);
3358 
3359 	TCPSTAT_INC(tcps_mturesent);
3360 	tp->t_rtttime = 0;
3361 	tp->snd_nxt = tp->snd_una;
3362 	tcp_free_sackholes(tp);
3363 	tp->snd_recover = tp->snd_max;
3364 	if (tp->t_flags & TF_SACK_PERMIT)
3365 		EXIT_FASTRECOVERY(tp->t_flags);
3366 	if (tp->t_fb->tfb_tcp_mtu_chg != NULL) {
3367 		/*
3368 		 * Conceptually the snd_nxt setting
3369 		 * and freeing sack holes should
3370 		 * be done by the default stacks
3371 		 * own tfb_tcp_mtu_chg().
3372 		 */
3373 		tp->t_fb->tfb_tcp_mtu_chg(tp);
3374 	}
3375 	if (tcp_output(tp) < 0)
3376 		return (NULL);
3377 	else
3378 		return (inp);
3379 }
3380 
3381 #ifdef INET
3382 /*
3383  * Look-up the routing entry to the peer of this inpcb.  If no route
3384  * is found and it cannot be allocated, then return 0.  This routine
3385  * is called by TCP routines that access the rmx structure and by
3386  * tcp_mss_update to get the peer/interface MTU.
3387  */
3388 uint32_t
3389 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap)
3390 {
3391 	struct nhop_object *nh;
3392 	struct ifnet *ifp;
3393 	uint32_t maxmtu = 0;
3394 
3395 	KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
3396 
3397 	if (inc->inc_faddr.s_addr != INADDR_ANY) {
3398 		nh = fib4_lookup(inc->inc_fibnum, inc->inc_faddr, 0, NHR_NONE, 0);
3399 		if (nh == NULL)
3400 			return (0);
3401 
3402 		ifp = nh->nh_ifp;
3403 		maxmtu = nh->nh_mtu;
3404 
3405 		/* Report additional interface capabilities. */
3406 		if (cap != NULL) {
3407 			if (ifp->if_capenable & IFCAP_TSO4 &&
3408 			    ifp->if_hwassist & CSUM_TSO) {
3409 				cap->ifcap |= CSUM_TSO;
3410 				cap->tsomax = ifp->if_hw_tsomax;
3411 				cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3412 				cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3413 				/* XXXKIB IFCAP2_IPSEC_OFFLOAD_TSO */
3414 				cap->ipsec_tso =  (ifp->if_capenable2 &
3415 				    IFCAP2_BIT(IFCAP2_IPSEC_OFFLOAD)) != 0;
3416 			}
3417 		}
3418 	}
3419 	return (maxmtu);
3420 }
3421 #endif /* INET */
3422 
3423 #ifdef INET6
3424 uint32_t
3425 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap)
3426 {
3427 	struct nhop_object *nh;
3428 	struct in6_addr dst6;
3429 	uint32_t scopeid;
3430 	struct ifnet *ifp;
3431 	uint32_t maxmtu = 0;
3432 
3433 	KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
3434 
3435 	if (inc->inc_flags & INC_IPV6MINMTU)
3436 		return (IPV6_MMTU);
3437 
3438 	if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
3439 		in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid);
3440 		nh = fib6_lookup(inc->inc_fibnum, &dst6, scopeid, NHR_NONE, 0);
3441 		if (nh == NULL)
3442 			return (0);
3443 
3444 		ifp = nh->nh_ifp;
3445 		maxmtu = nh->nh_mtu;
3446 
3447 		/* Report additional interface capabilities. */
3448 		if (cap != NULL) {
3449 			if (ifp->if_capenable & IFCAP_TSO6 &&
3450 			    ifp->if_hwassist & CSUM_TSO) {
3451 				cap->ifcap |= CSUM_TSO;
3452 				cap->tsomax = ifp->if_hw_tsomax;
3453 				cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3454 				cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3455 				cap->ipsec_tso = false; /* XXXKIB */
3456 			}
3457 		}
3458 	}
3459 
3460 	return (maxmtu);
3461 }
3462 
3463 /*
3464  * Handle setsockopt(IPV6_USE_MIN_MTU) by a TCP stack.
3465  *
3466  * XXXGL: we are updating inpcb here with INC_IPV6MINMTU flag.
3467  * The right place to do that is ip6_setpktopt() that has just been
3468  * executed.  By the way it just filled ip6po_minmtu for us.
3469  */
3470 void
3471 tcp6_use_min_mtu(struct tcpcb *tp)
3472 {
3473 	struct inpcb *inp = tptoinpcb(tp);
3474 
3475 	INP_WLOCK_ASSERT(inp);
3476 	/*
3477 	 * In case of the IPV6_USE_MIN_MTU socket
3478 	 * option, the INC_IPV6MINMTU flag to announce
3479 	 * a corresponding MSS during the initial
3480 	 * handshake.  If the TCP connection is not in
3481 	 * the front states, just reduce the MSS being
3482 	 * used.  This avoids the sending of TCP
3483 	 * segments which will be fragmented at the
3484 	 * IPv6 layer.
3485 	 */
3486 	inp->inp_inc.inc_flags |= INC_IPV6MINMTU;
3487 	if ((tp->t_state >= TCPS_SYN_SENT) &&
3488 	    (inp->inp_inc.inc_flags & INC_ISIPV6)) {
3489 		struct ip6_pktopts *opt;
3490 
3491 		opt = inp->in6p_outputopts;
3492 		if (opt != NULL && opt->ip6po_minmtu == IP6PO_MINMTU_ALL &&
3493 		    tp->t_maxseg > TCP6_MSS) {
3494 			tp->t_maxseg = TCP6_MSS;
3495 			if (tp->t_maxseg < V_tcp_mssdflt) {
3496 				/*
3497 				 * The MSS is so small we should not process incoming
3498 				 * SACK's since we are subject to attack in such a
3499 				 * case.
3500 				 */
3501 				tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT;
3502 			} else {
3503 				tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT;
3504 			}
3505 		}
3506 	}
3507 }
3508 #endif /* INET6 */
3509 
3510 /*
3511  * Calculate effective SMSS per RFC5681 definition for a given TCP
3512  * connection at its current state, taking into account SACK and etc.
3513  */
3514 u_int
3515 tcp_maxseg(const struct tcpcb *tp)
3516 {
3517 	u_int optlen;
3518 
3519 	if (tp->t_flags & TF_NOOPT)
3520 		return (tp->t_maxseg);
3521 
3522 	/*
3523 	 * Here we have a simplified code from tcp_addoptions(),
3524 	 * without a proper loop, and having most of paddings hardcoded.
3525 	 * We might make mistakes with padding here in some edge cases,
3526 	 * but this is harmless, since result of tcp_maxseg() is used
3527 	 * only in cwnd and ssthresh estimations.
3528 	 */
3529 	if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3530 		if (tp->t_flags & TF_RCVD_TSTMP)
3531 			optlen = TCPOLEN_TSTAMP_APPA;
3532 		else
3533 			optlen = 0;
3534 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3535 		if (tp->t_flags & TF_SIGNATURE)
3536 			optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3537 #endif
3538 		if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) {
3539 			optlen += TCPOLEN_SACKHDR;
3540 			optlen += tp->rcv_numsacks * TCPOLEN_SACK;
3541 			optlen = PADTCPOLEN(optlen);
3542 		}
3543 	} else {
3544 		if (tp->t_flags & TF_REQ_TSTMP)
3545 			optlen = TCPOLEN_TSTAMP_APPA;
3546 		else
3547 			optlen = PADTCPOLEN(TCPOLEN_MAXSEG);
3548 		if (tp->t_flags & TF_REQ_SCALE)
3549 			optlen += PADTCPOLEN(TCPOLEN_WINDOW);
3550 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3551 		if (tp->t_flags & TF_SIGNATURE)
3552 			optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3553 #endif
3554 		if (tp->t_flags & TF_SACK_PERMIT)
3555 			optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED);
3556 	}
3557 	optlen = min(optlen, TCP_MAXOLEN);
3558 	return (tp->t_maxseg - optlen);
3559 }
3560 
3561 
3562 u_int
3563 tcp_fixed_maxseg(const struct tcpcb *tp)
3564 {
3565 	int optlen;
3566 
3567 	if (tp->t_flags & TF_NOOPT)
3568 		return (tp->t_maxseg);
3569 
3570 	/*
3571 	 * Here we have a simplified code from tcp_addoptions(),
3572 	 * without a proper loop, and having most of paddings hardcoded.
3573 	 * We only consider fixed options that we would send every
3574 	 * time I.e. SACK is not considered. This is important
3575 	 * for cc modules to figure out what the modulo of the
3576 	 * cwnd should be.
3577 	 */
3578 	if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3579 		if (tp->t_flags & TF_RCVD_TSTMP)
3580 			optlen = TCPOLEN_TSTAMP_APPA;
3581 		else
3582 			optlen = 0;
3583 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3584 		if (tp->t_flags & TF_SIGNATURE)
3585 			optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3586 #endif
3587 	} else {
3588 		if (tp->t_flags & TF_REQ_TSTMP)
3589 			optlen = TCPOLEN_TSTAMP_APPA;
3590 		else
3591 			optlen = PADTCPOLEN(TCPOLEN_MAXSEG);
3592 		if (tp->t_flags & TF_REQ_SCALE)
3593 			optlen += PADTCPOLEN(TCPOLEN_WINDOW);
3594 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3595 		if (tp->t_flags & TF_SIGNATURE)
3596 			optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3597 #endif
3598 		if (tp->t_flags & TF_SACK_PERMIT)
3599 			optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED);
3600 	}
3601 	optlen = min(optlen, TCP_MAXOLEN);
3602 	return (tp->t_maxseg - optlen);
3603 }
3604 
3605 
3606 
3607 static int
3608 sysctl_drop(SYSCTL_HANDLER_ARGS)
3609 {
3610 	/* addrs[0] is a foreign socket, addrs[1] is a local one. */
3611 	struct sockaddr_storage addrs[2];
3612 	struct inpcb *inp;
3613 	struct tcpcb *tp;
3614 #ifdef INET
3615 	struct sockaddr_in *fin = NULL, *lin = NULL;
3616 #endif
3617 	struct epoch_tracker et;
3618 #ifdef INET6
3619 	struct sockaddr_in6 *fin6, *lin6;
3620 #endif
3621 	int error;
3622 
3623 	inp = NULL;
3624 #ifdef INET6
3625 	fin6 = lin6 = NULL;
3626 #endif
3627 	error = 0;
3628 
3629 	if (req->oldptr != NULL || req->oldlen != 0)
3630 		return (EINVAL);
3631 	if (req->newptr == NULL)
3632 		return (EPERM);
3633 	if (req->newlen < sizeof(addrs))
3634 		return (ENOMEM);
3635 	error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3636 	if (error)
3637 		return (error);
3638 
3639 	switch (addrs[0].ss_family) {
3640 #ifdef INET6
3641 	case AF_INET6:
3642 		fin6 = (struct sockaddr_in6 *)&addrs[0];
3643 		lin6 = (struct sockaddr_in6 *)&addrs[1];
3644 		if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3645 		    lin6->sin6_len != sizeof(struct sockaddr_in6))
3646 			return (EINVAL);
3647 		if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3648 			if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3649 				return (EINVAL);
3650 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3651 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3652 #ifdef INET
3653 			fin = (struct sockaddr_in *)&addrs[0];
3654 			lin = (struct sockaddr_in *)&addrs[1];
3655 #endif
3656 			break;
3657 		}
3658 		error = sa6_embedscope(fin6, V_ip6_use_defzone);
3659 		if (error)
3660 			return (error);
3661 		error = sa6_embedscope(lin6, V_ip6_use_defzone);
3662 		if (error)
3663 			return (error);
3664 		break;
3665 #endif
3666 #ifdef INET
3667 	case AF_INET:
3668 		fin = (struct sockaddr_in *)&addrs[0];
3669 		lin = (struct sockaddr_in *)&addrs[1];
3670 		if (fin->sin_len != sizeof(struct sockaddr_in) ||
3671 		    lin->sin_len != sizeof(struct sockaddr_in))
3672 			return (EINVAL);
3673 		break;
3674 #endif
3675 	default:
3676 		return (EINVAL);
3677 	}
3678 	NET_EPOCH_ENTER(et);
3679 	switch (addrs[0].ss_family) {
3680 #ifdef INET6
3681 	case AF_INET6:
3682 		inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3683 		    fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3684 		    INPLOOKUP_WLOCKPCB, NULL);
3685 		break;
3686 #endif
3687 #ifdef INET
3688 	case AF_INET:
3689 		inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3690 		    lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3691 		break;
3692 #endif
3693 	}
3694 	if (inp != NULL) {
3695 		if (!SOLISTENING(inp->inp_socket)) {
3696 			tp = intotcpcb(inp);
3697 			tp = tcp_drop(tp, ECONNABORTED);
3698 			if (tp != NULL)
3699 				INP_WUNLOCK(inp);
3700 		} else
3701 			INP_WUNLOCK(inp);
3702 	} else
3703 		error = ESRCH;
3704 	NET_EPOCH_EXIT(et);
3705 	return (error);
3706 }
3707 
3708 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
3709     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3710     CTLFLAG_NEEDGIANT, NULL, 0, sysctl_drop, "",
3711     "Drop TCP connection");
3712 
3713 static int
3714 tcp_sysctl_setsockopt(SYSCTL_HANDLER_ARGS)
3715 {
3716 	return (sysctl_setsockopt(oidp, arg1, arg2, req, &V_tcbinfo,
3717 	    &tcp_ctloutput_set));
3718 }
3719 
3720 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, setsockopt,
3721     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3722     CTLFLAG_MPSAFE, NULL, 0, tcp_sysctl_setsockopt, "",
3723     "Set socket option for TCP endpoint");
3724 
3725 #ifdef KERN_TLS
3726 static int
3727 sysctl_switch_tls(SYSCTL_HANDLER_ARGS)
3728 {
3729 	/* addrs[0] is a foreign socket, addrs[1] is a local one. */
3730 	struct sockaddr_storage addrs[2];
3731 	struct inpcb *inp;
3732 #ifdef INET
3733 	struct sockaddr_in *fin = NULL, *lin = NULL;
3734 #endif
3735 	struct epoch_tracker et;
3736 #ifdef INET6
3737 	struct sockaddr_in6 *fin6, *lin6;
3738 #endif
3739 	int error;
3740 
3741 	inp = NULL;
3742 #ifdef INET6
3743 	fin6 = lin6 = NULL;
3744 #endif
3745 	error = 0;
3746 
3747 	if (req->oldptr != NULL || req->oldlen != 0)
3748 		return (EINVAL);
3749 	if (req->newptr == NULL)
3750 		return (EPERM);
3751 	if (req->newlen < sizeof(addrs))
3752 		return (ENOMEM);
3753 	error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3754 	if (error)
3755 		return (error);
3756 
3757 	switch (addrs[0].ss_family) {
3758 #ifdef INET6
3759 	case AF_INET6:
3760 		fin6 = (struct sockaddr_in6 *)&addrs[0];
3761 		lin6 = (struct sockaddr_in6 *)&addrs[1];
3762 		if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3763 		    lin6->sin6_len != sizeof(struct sockaddr_in6))
3764 			return (EINVAL);
3765 		if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3766 			if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3767 				return (EINVAL);
3768 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3769 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3770 #ifdef INET
3771 			fin = (struct sockaddr_in *)&addrs[0];
3772 			lin = (struct sockaddr_in *)&addrs[1];
3773 #endif
3774 			break;
3775 		}
3776 		error = sa6_embedscope(fin6, V_ip6_use_defzone);
3777 		if (error)
3778 			return (error);
3779 		error = sa6_embedscope(lin6, V_ip6_use_defzone);
3780 		if (error)
3781 			return (error);
3782 		break;
3783 #endif
3784 #ifdef INET
3785 	case AF_INET:
3786 		fin = (struct sockaddr_in *)&addrs[0];
3787 		lin = (struct sockaddr_in *)&addrs[1];
3788 		if (fin->sin_len != sizeof(struct sockaddr_in) ||
3789 		    lin->sin_len != sizeof(struct sockaddr_in))
3790 			return (EINVAL);
3791 		break;
3792 #endif
3793 	default:
3794 		return (EINVAL);
3795 	}
3796 	NET_EPOCH_ENTER(et);
3797 	switch (addrs[0].ss_family) {
3798 #ifdef INET6
3799 	case AF_INET6:
3800 		inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3801 		    fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3802 		    INPLOOKUP_WLOCKPCB, NULL);
3803 		break;
3804 #endif
3805 #ifdef INET
3806 	case AF_INET:
3807 		inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3808 		    lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3809 		break;
3810 #endif
3811 	}
3812 	NET_EPOCH_EXIT(et);
3813 	if (inp != NULL) {
3814 		struct socket *so;
3815 
3816 		so = inp->inp_socket;
3817 		soref(so);
3818 		error = ktls_set_tx_mode(so,
3819 		    arg2 == 0 ? TCP_TLS_MODE_SW : TCP_TLS_MODE_IFNET);
3820 		INP_WUNLOCK(inp);
3821 		sorele(so);
3822 	} else
3823 		error = ESRCH;
3824 	return (error);
3825 }
3826 
3827 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_sw_tls,
3828     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3829     CTLFLAG_NEEDGIANT, NULL, 0, sysctl_switch_tls, "",
3830     "Switch TCP connection to SW TLS");
3831 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_ifnet_tls,
3832     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3833     CTLFLAG_NEEDGIANT, NULL, 1, sysctl_switch_tls, "",
3834     "Switch TCP connection to ifnet TLS");
3835 #endif
3836 
3837 /*
3838  * Generate a standardized TCP log line for use throughout the
3839  * tcp subsystem.  Memory allocation is done with M_NOWAIT to
3840  * allow use in the interrupt context.
3841  *
3842  * NB: The caller MUST free(s, M_TCPLOG) the returned string.
3843  * NB: The function may return NULL if memory allocation failed.
3844  *
3845  * Due to header inclusion and ordering limitations the struct ip
3846  * and ip6_hdr pointers have to be passed as void pointers.
3847  */
3848 char *
3849 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3850     const void *ip6hdr)
3851 {
3852 
3853 	/* Is logging enabled? */
3854 	if (V_tcp_log_in_vain == 0)
3855 		return (NULL);
3856 
3857 	return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3858 }
3859 
3860 char *
3861 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3862     const void *ip6hdr)
3863 {
3864 
3865 	/* Is logging enabled? */
3866 	if (tcp_log_debug == 0)
3867 		return (NULL);
3868 
3869 	return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3870 }
3871 
3872 static char *
3873 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
3874     const void *ip6hdr)
3875 {
3876 	char *s, *sp;
3877 	size_t size;
3878 #ifdef INET
3879 	const struct ip *ip = (const struct ip *)ip4hdr;
3880 #endif
3881 #ifdef INET6
3882 	const struct ip6_hdr *ip6 = (const struct ip6_hdr *)ip6hdr;
3883 #endif /* INET6 */
3884 
3885 	/*
3886 	 * The log line looks like this:
3887 	 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>"
3888 	 */
3889 	size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") +
3890 	    sizeof(PRINT_TH_FLAGS) + 1 +
3891 #ifdef INET6
3892 	    2 * INET6_ADDRSTRLEN;
3893 #else
3894 	    2 * INET_ADDRSTRLEN;
3895 #endif /* INET6 */
3896 
3897 	s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT);
3898 	if (s == NULL)
3899 		return (NULL);
3900 
3901 	strcat(s, "TCP: [");
3902 	sp = s + strlen(s);
3903 
3904 	if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) {
3905 		inet_ntoa_r(inc->inc_faddr, sp);
3906 		sp = s + strlen(s);
3907 		sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3908 		sp = s + strlen(s);
3909 		inet_ntoa_r(inc->inc_laddr, sp);
3910 		sp = s + strlen(s);
3911 		sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3912 #ifdef INET6
3913 	} else if (inc) {
3914 		ip6_sprintf(sp, &inc->inc6_faddr);
3915 		sp = s + strlen(s);
3916 		sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3917 		sp = s + strlen(s);
3918 		ip6_sprintf(sp, &inc->inc6_laddr);
3919 		sp = s + strlen(s);
3920 		sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3921 	} else if (ip6 && th) {
3922 		ip6_sprintf(sp, &ip6->ip6_src);
3923 		sp = s + strlen(s);
3924 		sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3925 		sp = s + strlen(s);
3926 		ip6_sprintf(sp, &ip6->ip6_dst);
3927 		sp = s + strlen(s);
3928 		sprintf(sp, "]:%i", ntohs(th->th_dport));
3929 #endif /* INET6 */
3930 #ifdef INET
3931 	} else if (ip && th) {
3932 		inet_ntoa_r(ip->ip_src, sp);
3933 		sp = s + strlen(s);
3934 		sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3935 		sp = s + strlen(s);
3936 		inet_ntoa_r(ip->ip_dst, sp);
3937 		sp = s + strlen(s);
3938 		sprintf(sp, "]:%i", ntohs(th->th_dport));
3939 #endif /* INET */
3940 	} else {
3941 		free(s, M_TCPLOG);
3942 		return (NULL);
3943 	}
3944 	sp = s + strlen(s);
3945 	if (th)
3946 		sprintf(sp, " tcpflags 0x%b", tcp_get_flags(th), PRINT_TH_FLAGS);
3947 	if (*(s + size - 1) != '\0')
3948 		panic("%s: string too long", __func__);
3949 	return (s);
3950 }
3951 
3952 /*
3953  * A subroutine which makes it easy to track TCP state changes with DTrace.
3954  * This function shouldn't be called for t_state initializations that don't
3955  * correspond to actual TCP state transitions.
3956  */
3957 void
3958 tcp_state_change(struct tcpcb *tp, int newstate)
3959 {
3960 #if defined(KDTRACE_HOOKS)
3961 	int pstate = tp->t_state;
3962 #endif
3963 
3964 	TCPSTATES_DEC(tp->t_state);
3965 	TCPSTATES_INC(newstate);
3966 	tp->t_state = newstate;
3967 	TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate);
3968 }
3969 
3970 /*
3971  * Create an external-format (``xtcpcb'') structure using the information in
3972  * the kernel-format tcpcb structure pointed to by tp.  This is done to
3973  * reduce the spew of irrelevant information over this interface, to isolate
3974  * user code from changes in the kernel structure, and potentially to provide
3975  * information-hiding if we decide that some of this information should be
3976  * hidden from users.
3977  */
3978 void
3979 tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt)
3980 {
3981 	struct tcpcb *tp = intotcpcb(inp);
3982 	sbintime_t now;
3983 
3984 	bzero(xt, sizeof(*xt));
3985 	xt->t_state = tp->t_state;
3986 	xt->t_logstate = tcp_get_bblog_state(tp);
3987 	xt->t_flags = tp->t_flags;
3988 	xt->t_sndzerowin = tp->t_sndzerowin;
3989 	xt->t_sndrexmitpack = tp->t_sndrexmitpack;
3990 	xt->t_rcvoopack = tp->t_rcvoopack;
3991 	xt->t_rcv_wnd = tp->rcv_wnd;
3992 	xt->t_snd_wnd = tp->snd_wnd;
3993 	xt->t_snd_cwnd = tp->snd_cwnd;
3994 	xt->t_snd_ssthresh = tp->snd_ssthresh;
3995 	xt->t_dsack_bytes = tp->t_dsack_bytes;
3996 	xt->t_dsack_tlp_bytes = tp->t_dsack_tlp_bytes;
3997 	xt->t_dsack_pack = tp->t_dsack_pack;
3998 	xt->t_maxseg = tp->t_maxseg;
3999 	xt->xt_ecn = (tp->t_flags2 & TF2_ECN_PERMIT) ? 1 : 0 +
4000 		     (tp->t_flags2 & TF2_ACE_PERMIT) ? 2 : 0;
4001 
4002 	now = getsbinuptime();
4003 #define	COPYTIMER(which,where)	do {					\
4004 	if (tp->t_timers[which] != SBT_MAX)				\
4005 		xt->where = (tp->t_timers[which] - now) / SBT_1MS;	\
4006 	else								\
4007 		xt->where = 0;						\
4008 } while (0)
4009 	COPYTIMER(TT_DELACK, tt_delack);
4010 	COPYTIMER(TT_REXMT, tt_rexmt);
4011 	COPYTIMER(TT_PERSIST, tt_persist);
4012 	COPYTIMER(TT_KEEP, tt_keep);
4013 	COPYTIMER(TT_2MSL, tt_2msl);
4014 #undef COPYTIMER
4015 	xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz;
4016 
4017 	xt->xt_encaps_port = tp->t_port;
4018 	bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack,
4019 	    TCP_FUNCTION_NAME_LEN_MAX);
4020 	bcopy(CC_ALGO(tp)->name, xt->xt_cc, TCP_CA_NAME_MAX);
4021 #ifdef TCP_BLACKBOX
4022 	(void)tcp_log_get_id(tp, xt->xt_logid);
4023 #endif
4024 
4025 	xt->xt_len = sizeof(struct xtcpcb);
4026 	in_pcbtoxinpcb(inp, &xt->xt_inp);
4027 }
4028 
4029 void
4030 tcp_log_end_status(struct tcpcb *tp, uint8_t status)
4031 {
4032 	uint32_t bit, i;
4033 
4034 	if ((tp == NULL) ||
4035 	    (status > TCP_EI_STATUS_MAX_VALUE) ||
4036 	    (status == 0)) {
4037 		/* Invalid */
4038 		return;
4039 	}
4040 	if (status > (sizeof(uint32_t) * 8)) {
4041 		/* Should this be a KASSERT? */
4042 		return;
4043 	}
4044 	bit = 1U << (status - 1);
4045 	if (bit & tp->t_end_info_status) {
4046 		/* already logged */
4047 		return;
4048 	}
4049 	for (i = 0; i < TCP_END_BYTE_INFO; i++) {
4050 		if (tp->t_end_info_bytes[i] == TCP_EI_EMPTY_SLOT) {
4051 			tp->t_end_info_bytes[i] = status;
4052 			tp->t_end_info_status |= bit;
4053 			break;
4054 		}
4055 	}
4056 }
4057 
4058 int
4059 tcp_can_enable_pacing(void)
4060 {
4061 
4062 	if ((tcp_pacing_limit == -1) ||
4063 	    (tcp_pacing_limit > number_of_tcp_connections_pacing)) {
4064 		atomic_fetchadd_int(&number_of_tcp_connections_pacing, 1);
4065 		shadow_num_connections = number_of_tcp_connections_pacing;
4066 		return (1);
4067 	} else {
4068 		counter_u64_add(tcp_pacing_failures, 1);
4069 		return (0);
4070 	}
4071 }
4072 
4073 int
4074 tcp_incr_dgp_pacing_cnt(void)
4075 {
4076 	if ((tcp_dgp_limit == -1) ||
4077 	    (tcp_dgp_limit > number_of_dgp_connections)) {
4078 		atomic_fetchadd_int(&number_of_dgp_connections, 1);
4079 		shadow_tcp_pacing_dgp = number_of_dgp_connections;
4080 		return (1);
4081 	} else {
4082 		counter_u64_add(tcp_dgp_failures, 1);
4083 		return (0);
4084 	}
4085 }
4086 
4087 static uint8_t tcp_dgp_warning = 0;
4088 
4089 void
4090 tcp_dec_dgp_pacing_cnt(void)
4091 {
4092 	uint32_t ret;
4093 
4094 	ret = atomic_fetchadd_int(&number_of_dgp_connections, -1);
4095 	shadow_tcp_pacing_dgp = number_of_dgp_connections;
4096 	KASSERT(ret != 0, ("number_of_dgp_connections -1 would cause wrap?"));
4097 	if (ret == 0) {
4098 		if (tcp_dgp_limit != -1) {
4099 			printf("Warning all DGP is now disabled, count decrements invalidly!\n");
4100 			tcp_dgp_limit = 0;
4101 			tcp_dgp_warning = 1;
4102 		} else if (tcp_dgp_warning == 0) {
4103 			printf("Warning DGP pacing is invalid, invalid decrement\n");
4104 			tcp_dgp_warning = 1;
4105 		}
4106 	}
4107 
4108 }
4109 
4110 static uint8_t tcp_pacing_warning = 0;
4111 
4112 void
4113 tcp_decrement_paced_conn(void)
4114 {
4115 	uint32_t ret;
4116 
4117 	ret = atomic_fetchadd_int(&number_of_tcp_connections_pacing, -1);
4118 	shadow_num_connections = number_of_tcp_connections_pacing;
4119 	KASSERT(ret != 0, ("tcp_paced_connection_exits -1 would cause wrap?"));
4120 	if (ret == 0) {
4121 		if (tcp_pacing_limit != -1) {
4122 			printf("Warning all pacing is now disabled, count decrements invalidly!\n");
4123 			tcp_pacing_limit = 0;
4124 		} else if (tcp_pacing_warning == 0) {
4125 			printf("Warning pacing count is invalid, invalid decrement\n");
4126 			tcp_pacing_warning = 1;
4127 		}
4128 	}
4129 }
4130 
4131 static void
4132 tcp_default_switch_failed(struct tcpcb *tp)
4133 {
4134 	/*
4135 	 * If a switch fails we only need to
4136 	 * care about two things:
4137 	 * a) The t_flags2
4138 	 * and
4139 	 * b) The timer granularity.
4140 	 * Timeouts, at least for now, don't use the
4141 	 * old callout system in the other stacks so
4142 	 * those are hopefully safe.
4143 	 */
4144 	tcp_lro_features_off(tp);
4145 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
4146 }
4147 
4148 #ifdef TCP_ACCOUNTING
4149 int
4150 tcp_do_ack_accounting(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to, uint32_t tiwin, int mss)
4151 {
4152 	if (SEQ_LT(th->th_ack, tp->snd_una)) {
4153 		/* Do we have a SACK? */
4154 		if (to->to_flags & TOF_SACK) {
4155 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4156 				tp->tcp_cnt_counters[ACK_SACK]++;
4157 			}
4158 			return (ACK_SACK);
4159 		} else {
4160 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4161 				tp->tcp_cnt_counters[ACK_BEHIND]++;
4162 			}
4163 			return (ACK_BEHIND);
4164 		}
4165 	} else if (th->th_ack == tp->snd_una) {
4166 		/* Do we have a SACK? */
4167 		if (to->to_flags & TOF_SACK) {
4168 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4169 				tp->tcp_cnt_counters[ACK_SACK]++;
4170 			}
4171 			return (ACK_SACK);
4172 		} else if (tiwin != tp->snd_wnd) {
4173 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4174 				tp->tcp_cnt_counters[ACK_RWND]++;
4175 			}
4176 			return (ACK_RWND);
4177 		} else {
4178 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4179 				tp->tcp_cnt_counters[ACK_DUPACK]++;
4180 			}
4181 			return (ACK_DUPACK);
4182 		}
4183 	} else {
4184 		if (!SEQ_GT(th->th_ack, tp->snd_max)) {
4185 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4186 				tp->tcp_cnt_counters[CNT_OF_ACKS_IN] += (((th->th_ack - tp->snd_una) + mss - 1)/mss);
4187 			}
4188 		}
4189 		if (to->to_flags & TOF_SACK) {
4190 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4191 				tp->tcp_cnt_counters[ACK_CUMACK_SACK]++;
4192 			}
4193 			return (ACK_CUMACK_SACK);
4194 		} else {
4195 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4196 				tp->tcp_cnt_counters[ACK_CUMACK]++;
4197 			}
4198 			return (ACK_CUMACK);
4199 		}
4200 	}
4201 }
4202 #endif
4203 
4204 void
4205 tcp_change_time_units(struct tcpcb *tp, int granularity)
4206 {
4207 	if (tp->t_tmr_granularity == granularity) {
4208 		/* We are there */
4209 		return;
4210 	}
4211 	if (granularity == TCP_TMR_GRANULARITY_USEC) {
4212 		KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS),
4213 			("Granularity is not TICKS its %u in tp:%p",
4214 			 tp->t_tmr_granularity, tp));
4215 		tp->t_rttlow = TICKS_2_USEC(tp->t_rttlow);
4216 		if (tp->t_srtt > 1) {
4217 			uint32_t val, frac;
4218 
4219 			val = tp->t_srtt >> TCP_RTT_SHIFT;
4220 			frac = tp->t_srtt & 0x1f;
4221 			tp->t_srtt = TICKS_2_USEC(val);
4222 			/*
4223 			 * frac is the fractional part of the srtt (if any)
4224 			 * but its in ticks and every bit represents
4225 			 * 1/32nd of a hz.
4226 			 */
4227 			if (frac) {
4228 				if (hz == 1000) {
4229 					frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
4230 				} else {
4231 					frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
4232 				}
4233 				tp->t_srtt += frac;
4234 			}
4235 		}
4236 		if (tp->t_rttvar) {
4237 			uint32_t val, frac;
4238 
4239 			val = tp->t_rttvar >> TCP_RTTVAR_SHIFT;
4240 			frac = tp->t_rttvar & 0x1f;
4241 			tp->t_rttvar = TICKS_2_USEC(val);
4242 			/*
4243 			 * frac is the fractional part of the srtt (if any)
4244 			 * but its in ticks and every bit represents
4245 			 * 1/32nd of a hz.
4246 			 */
4247 			if (frac) {
4248 				if (hz == 1000) {
4249 					frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
4250 				} else {
4251 					frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
4252 				}
4253 				tp->t_rttvar += frac;
4254 			}
4255 		}
4256 		tp->t_tmr_granularity = TCP_TMR_GRANULARITY_USEC;
4257 	} else if (granularity == TCP_TMR_GRANULARITY_TICKS) {
4258 		/* Convert back to ticks, with  */
4259 		KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_USEC),
4260 			("Granularity is not USEC its %u in tp:%p",
4261 			 tp->t_tmr_granularity, tp));
4262 		if (tp->t_srtt > 1) {
4263 			uint32_t val, frac;
4264 
4265 			val = USEC_2_TICKS(tp->t_srtt);
4266 			frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
4267 			tp->t_srtt = val << TCP_RTT_SHIFT;
4268 			/*
4269 			 * frac is the fractional part here is left
4270 			 * over from converting to hz and shifting.
4271 			 * We need to convert this to the 5 bit
4272 			 * remainder.
4273 			 */
4274 			if (frac) {
4275 				if (hz == 1000) {
4276 					frac = (((uint64_t)frac *  (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
4277 				} else {
4278 					frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
4279 				}
4280 				tp->t_srtt += frac;
4281 			}
4282 		}
4283 		if (tp->t_rttvar) {
4284 			uint32_t val, frac;
4285 
4286 			val = USEC_2_TICKS(tp->t_rttvar);
4287 			frac = tp->t_rttvar % (HPTS_USEC_IN_SEC / hz);
4288 			tp->t_rttvar = val <<  TCP_RTTVAR_SHIFT;
4289 			/*
4290 			 * frac is the fractional part here is left
4291 			 * over from converting to hz and shifting.
4292 			 * We need to convert this to the 4 bit
4293 			 * remainder.
4294 			 */
4295 			if (frac) {
4296 				if (hz == 1000) {
4297 					frac = (((uint64_t)frac *  (uint64_t)TCP_RTTVAR_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
4298 				} else {
4299 					frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTTVAR_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
4300 				}
4301 				tp->t_rttvar += frac;
4302 			}
4303 		}
4304 		tp->t_rttlow = USEC_2_TICKS(tp->t_rttlow);
4305 		tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS;
4306 	}
4307 #ifdef INVARIANTS
4308 	else {
4309 		panic("Unknown granularity:%d tp:%p",
4310 		      granularity, tp);
4311 	}
4312 #endif
4313 }
4314 
4315 void
4316 tcp_handle_orphaned_packets(struct tcpcb *tp)
4317 {
4318 	struct mbuf *save, *m, *prev;
4319 	/*
4320 	 * Called when a stack switch is occuring from the fini()
4321 	 * of the old stack. We assue the init() as already been
4322 	 * run of the new stack and it has set the t_flags2 to
4323 	 * what it supports. This function will then deal with any
4324 	 * differences i.e. cleanup packets that maybe queued that
4325 	 * the newstack does not support.
4326 	 */
4327 
4328 	if (tp->t_flags2 & TF2_MBUF_L_ACKS)
4329 		return;
4330 	if ((tp->t_flags2 & TF2_SUPPORTS_MBUFQ) == 0 &&
4331 	    !STAILQ_EMPTY(&tp->t_inqueue)) {
4332 		/*
4333 		 * It is unsafe to process the packets since a
4334 		 * reset may be lurking in them (its rare but it
4335 		 * can occur). If we were to find a RST, then we
4336 		 * would end up dropping the connection and the
4337 		 * INP lock, so when we return the caller (tcp_usrreq)
4338 		 * will blow up when it trys to unlock the inp.
4339 		 * This new stack does not do any fancy LRO features
4340 		 * so all we can do is toss the packets.
4341 		 */
4342 		m = STAILQ_FIRST(&tp->t_inqueue);
4343 		STAILQ_INIT(&tp->t_inqueue);
4344 		STAILQ_FOREACH_FROM_SAFE(m, &tp->t_inqueue, m_stailqpkt, save)
4345 			m_freem(m);
4346 	} else {
4347 		/*
4348 		 * Here we have a stack that does mbuf queuing but
4349 		 * does not support compressed ack's. We must
4350 		 * walk all the mbufs and discard any compressed acks.
4351 		 */
4352 		STAILQ_FOREACH_SAFE(m, &tp->t_inqueue, m_stailqpkt, save) {
4353 			if (m->m_flags & M_ACKCMP) {
4354 				if (m == STAILQ_FIRST(&tp->t_inqueue))
4355 					STAILQ_REMOVE_HEAD(&tp->t_inqueue,
4356 					    m_stailqpkt);
4357 				else
4358 					STAILQ_REMOVE_AFTER(&tp->t_inqueue,
4359 					    prev, m_stailqpkt);
4360 				m_freem(m);
4361 			} else
4362 				prev = m;
4363 		}
4364 	}
4365 }
4366 
4367 #ifdef TCP_REQUEST_TRK
4368 uint32_t
4369 tcp_estimate_tls_overhead(struct socket *so, uint64_t tls_usr_bytes)
4370 {
4371 #ifdef KERN_TLS
4372 	struct ktls_session *tls;
4373 	uint32_t rec_oh, records;
4374 
4375 	tls = so->so_snd.sb_tls_info;
4376 	if (tls == NULL)
4377 	    return (0);
4378 
4379 	rec_oh = tls->params.tls_hlen + tls->params.tls_tlen;
4380 	records = ((tls_usr_bytes + tls->params.max_frame_len - 1)/tls->params.max_frame_len);
4381 	return (records * rec_oh);
4382 #else
4383 	return (0);
4384 #endif
4385 }
4386 
4387 extern uint32_t tcp_stale_entry_time;
4388 uint32_t tcp_stale_entry_time = 250000;
4389 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, usrlog_stale, CTLFLAG_RW,
4390     &tcp_stale_entry_time, 250000, "Time that a tcpreq entry without a sendfile ages out");
4391 
4392 void
4393 tcp_req_log_req_info(struct tcpcb *tp, struct tcp_sendfile_track *req,
4394     uint16_t slot, uint8_t val, uint64_t offset, uint64_t nbytes)
4395 {
4396 	if (tcp_bblogging_on(tp)) {
4397 		union tcp_log_stackspecific log;
4398 		struct timeval tv;
4399 
4400 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
4401 		log.u_bbr.inhpts = tcp_in_hpts(tp);
4402 		log.u_bbr.flex8 = val;
4403 		log.u_bbr.rttProp = req->timestamp;
4404 		log.u_bbr.delRate = req->start;
4405 		log.u_bbr.cur_del_rate = req->end;
4406 		log.u_bbr.flex1 = req->start_seq;
4407 		log.u_bbr.flex2 = req->end_seq;
4408 		log.u_bbr.flex3 = req->flags;
4409 		log.u_bbr.flex4 = ((req->localtime >> 32) & 0x00000000ffffffff);
4410 		log.u_bbr.flex5 = (req->localtime & 0x00000000ffffffff);
4411 		log.u_bbr.flex7 = slot;
4412 		log.u_bbr.bw_inuse = offset;
4413 		/* nbytes = flex6 | epoch */
4414 		log.u_bbr.flex6 = ((nbytes >> 32) & 0x00000000ffffffff);
4415 		log.u_bbr.epoch = (nbytes & 0x00000000ffffffff);
4416 		/* cspr =  lt_epoch | pkts_out */
4417 		log.u_bbr.lt_epoch = ((req->cspr >> 32) & 0x00000000ffffffff);
4418 		log.u_bbr.pkts_out |= (req->cspr & 0x00000000ffffffff);
4419 		log.u_bbr.applimited = tp->t_tcpreq_closed;
4420 		log.u_bbr.applimited <<= 8;
4421 		log.u_bbr.applimited |= tp->t_tcpreq_open;
4422 		log.u_bbr.applimited <<= 8;
4423 		log.u_bbr.applimited |= tp->t_tcpreq_req;
4424 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
4425 		TCP_LOG_EVENTP(tp, NULL,
4426 		    &tptosocket(tp)->so_rcv,
4427 		    &tptosocket(tp)->so_snd,
4428 		    TCP_LOG_REQ_T, 0,
4429 		    0, &log, false, &tv);
4430 	}
4431 }
4432 
4433 void
4434 tcp_req_free_a_slot(struct tcpcb *tp, struct tcp_sendfile_track *ent)
4435 {
4436 	if (tp->t_tcpreq_req > 0)
4437 		tp->t_tcpreq_req--;
4438 	if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) {
4439 		if (tp->t_tcpreq_open > 0)
4440 			tp->t_tcpreq_open--;
4441 	} else {
4442 		if (tp->t_tcpreq_closed > 0)
4443 			tp->t_tcpreq_closed--;
4444 	}
4445 	ent->flags = TCP_TRK_TRACK_FLG_EMPTY;
4446 }
4447 
4448 static void
4449 tcp_req_check_for_stale_entries(struct tcpcb *tp, uint64_t ts, int rm_oldest)
4450 {
4451 	struct tcp_sendfile_track *ent;
4452 	uint64_t time_delta, oldest_delta;
4453 	int i, oldest, oldest_set = 0, cnt_rm = 0;
4454 
4455 	for (i = 0; i < MAX_TCP_TRK_REQ; i++) {
4456 		ent = &tp->t_tcpreq_info[i];
4457 		if (ent->flags != TCP_TRK_TRACK_FLG_USED) {
4458 			/*
4459 			 * We only care about closed end ranges
4460 			 * that are allocated and have no sendfile
4461 			 * ever touching them. They would be in
4462 			 * state USED.
4463 			 */
4464 			continue;
4465 		}
4466 		if (ts >= ent->localtime)
4467 			time_delta = ts - ent->localtime;
4468 		else
4469 			time_delta = 0;
4470 		if (time_delta &&
4471 		    ((oldest_delta < time_delta) || (oldest_set == 0))) {
4472 			oldest_set = 1;
4473 			oldest = i;
4474 			oldest_delta = time_delta;
4475 		}
4476 		if (tcp_stale_entry_time && (time_delta >= tcp_stale_entry_time)) {
4477 			/*
4478 			 * No sendfile in a our time-limit
4479 			 * time to purge it.
4480 			 */
4481 			cnt_rm++;
4482 			tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], i, TCP_TRK_REQ_LOG_STALE,
4483 					      time_delta, 0);
4484 			tcp_req_free_a_slot(tp, ent);
4485 		}
4486 	}
4487 	if ((cnt_rm == 0) && rm_oldest && oldest_set) {
4488 		ent = &tp->t_tcpreq_info[oldest];
4489 		tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], i, TCP_TRK_REQ_LOG_STALE,
4490 				      oldest_delta, 1);
4491 		tcp_req_free_a_slot(tp, ent);
4492 	}
4493 }
4494 
4495 int
4496 tcp_req_check_for_comp(struct tcpcb *tp, tcp_seq ack_point)
4497 {
4498 	int i, ret = 0;
4499 	struct tcp_sendfile_track *ent;
4500 
4501 	/* Clean up any old closed end requests that are now completed */
4502 	if (tp->t_tcpreq_req == 0)
4503 		return (0);
4504 	if (tp->t_tcpreq_closed == 0)
4505 		return (0);
4506 	for (i = 0; i < MAX_TCP_TRK_REQ; i++) {
4507 		ent = &tp->t_tcpreq_info[i];
4508 		/* Skip empty ones */
4509 		if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY)
4510 			continue;
4511 		/* Skip open ones */
4512 		if (ent->flags & TCP_TRK_TRACK_FLG_OPEN)
4513 			continue;
4514 		if (SEQ_GEQ(ack_point, ent->end_seq)) {
4515 			/* We are past it -- free it */
4516 			tcp_req_log_req_info(tp, ent,
4517 					      i, TCP_TRK_REQ_LOG_FREED, 0, 0);
4518 			tcp_req_free_a_slot(tp, ent);
4519 			ret++;
4520 		}
4521 	}
4522 	return (ret);
4523 }
4524 
4525 int
4526 tcp_req_is_entry_comp(struct tcpcb *tp, struct tcp_sendfile_track *ent, tcp_seq ack_point)
4527 {
4528 	if (tp->t_tcpreq_req == 0)
4529 		return (-1);
4530 	if (tp->t_tcpreq_closed == 0)
4531 		return (-1);
4532 	if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY)
4533 		return (-1);
4534 	if (SEQ_GEQ(ack_point, ent->end_seq)) {
4535 		return (1);
4536 	}
4537 	return (0);
4538 }
4539 
4540 struct tcp_sendfile_track *
4541 tcp_req_find_a_req_that_is_completed_by(struct tcpcb *tp, tcp_seq th_ack, int *ip)
4542 {
4543 	/*
4544 	 * Given an ack point (th_ack) walk through our entries and
4545 	 * return the first one found that th_ack goes past the
4546 	 * end_seq.
4547 	 */
4548 	struct tcp_sendfile_track *ent;
4549 	int i;
4550 
4551 	if (tp->t_tcpreq_req == 0) {
4552 		/* none open */
4553 		return (NULL);
4554 	}
4555 	for (i = 0; i < MAX_TCP_TRK_REQ; i++) {
4556 		ent = &tp->t_tcpreq_info[i];
4557 		if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY)
4558 			continue;
4559 		if ((ent->flags & TCP_TRK_TRACK_FLG_OPEN) == 0) {
4560 			if (SEQ_GEQ(th_ack, ent->end_seq)) {
4561 				*ip = i;
4562 				return (ent);
4563 			}
4564 		}
4565 	}
4566 	return (NULL);
4567 }
4568 
4569 struct tcp_sendfile_track *
4570 tcp_req_find_req_for_seq(struct tcpcb *tp, tcp_seq seq)
4571 {
4572 	struct tcp_sendfile_track *ent;
4573 	int i;
4574 
4575 	if (tp->t_tcpreq_req == 0) {
4576 		/* none open */
4577 		return (NULL);
4578 	}
4579 	for (i = 0; i < MAX_TCP_TRK_REQ; i++) {
4580 		ent = &tp->t_tcpreq_info[i];
4581 		tcp_req_log_req_info(tp, ent, i, TCP_TRK_REQ_LOG_SEARCH,
4582 				      (uint64_t)seq, 0);
4583 		if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) {
4584 			continue;
4585 		}
4586 		if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) {
4587 			/*
4588 			 * An open end request only needs to
4589 			 * match the beginning seq or be
4590 			 * all we have (once we keep going on
4591 			 * a open end request we may have a seq
4592 			 * wrap).
4593 			 */
4594 			if ((SEQ_GEQ(seq, ent->start_seq)) ||
4595 			    (tp->t_tcpreq_closed == 0))
4596 				return (ent);
4597 		} else {
4598 			/*
4599 			 * For this one we need to
4600 			 * be a bit more careful if its
4601 			 * completed at least.
4602 			 */
4603 			if ((SEQ_GEQ(seq, ent->start_seq)) &&
4604 			    (SEQ_LT(seq, ent->end_seq))) {
4605 				return (ent);
4606 			}
4607 		}
4608 	}
4609 	return (NULL);
4610 }
4611 
4612 /* Should this be in its own file tcp_req.c ? */
4613 struct tcp_sendfile_track *
4614 tcp_req_alloc_req_full(struct tcpcb *tp, struct tcp_snd_req *req, uint64_t ts, int rec_dups)
4615 {
4616 	struct tcp_sendfile_track *fil;
4617 	int i, allocated;
4618 
4619 	/* In case the stack does not check for completions do so now */
4620 	tcp_req_check_for_comp(tp, tp->snd_una);
4621 	/* Check for stale entries */
4622 	if (tp->t_tcpreq_req)
4623 		tcp_req_check_for_stale_entries(tp, ts,
4624 		    (tp->t_tcpreq_req >= MAX_TCP_TRK_REQ));
4625 	/* Check to see if this is a duplicate of one not started */
4626 	if (tp->t_tcpreq_req) {
4627 		for (i = 0, allocated = 0; i < MAX_TCP_TRK_REQ; i++) {
4628 			fil = &tp->t_tcpreq_info[i];
4629 			if ((fil->flags & TCP_TRK_TRACK_FLG_USED) == 0)
4630 				continue;
4631 			if ((fil->timestamp == req->timestamp) &&
4632 			    (fil->start == req->start) &&
4633 			    ((fil->flags & TCP_TRK_TRACK_FLG_OPEN) ||
4634 			     (fil->end == req->end))) {
4635 				/*
4636 				 * We already have this request
4637 				 * and it has not been started with sendfile.
4638 				 * This probably means the user was returned
4639 				 * a 4xx of some sort and its going to age
4640 				 * out, lets not duplicate it.
4641 				 */
4642 				return (fil);
4643 			}
4644 		}
4645 	}
4646 	/* Ok if there is no room at the inn we are in trouble */
4647 	if (tp->t_tcpreq_req >= MAX_TCP_TRK_REQ) {
4648 		tcp_trace_point(tp, TCP_TP_REQ_LOG_FAIL);
4649 		for (i = 0; i < MAX_TCP_TRK_REQ; i++) {
4650 			tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i],
4651 			    i, TCP_TRK_REQ_LOG_ALLOCFAIL, 0, 0);
4652 		}
4653 		return (NULL);
4654 	}
4655 	for (i = 0, allocated = 0; i < MAX_TCP_TRK_REQ; i++) {
4656 		fil = &tp->t_tcpreq_info[i];
4657 		if (fil->flags == TCP_TRK_TRACK_FLG_EMPTY) {
4658 			allocated = 1;
4659 			fil->flags = TCP_TRK_TRACK_FLG_USED;
4660 			fil->timestamp = req->timestamp;
4661 			fil->playout_ms = req->playout_ms;
4662 			fil->localtime = ts;
4663 			fil->start = req->start;
4664 			if (req->flags & TCP_LOG_HTTPD_RANGE_END) {
4665 				fil->end = req->end;
4666 			} else {
4667 				fil->end = 0;
4668 				fil->flags |= TCP_TRK_TRACK_FLG_OPEN;
4669 			}
4670 			/*
4671 			 * We can set the min boundaries to the TCP Sequence space,
4672 			 * but it might be found to be further up when sendfile
4673 			 * actually runs on this range (if it ever does).
4674 			 */
4675 			fil->sbcc_at_s = tptosocket(tp)->so_snd.sb_ccc;
4676 			fil->start_seq = tp->snd_una +
4677 			    tptosocket(tp)->so_snd.sb_ccc;
4678 			if (req->flags & TCP_LOG_HTTPD_RANGE_END)
4679 				fil->end_seq = (fil->start_seq + ((uint32_t)(fil->end - fil->start)));
4680 			else
4681 				fil->end_seq = 0;
4682 			if (tptosocket(tp)->so_snd.sb_tls_info) {
4683 				/*
4684 				 * This session is doing TLS. Take a swag guess
4685 				 * at the overhead.
4686 				 */
4687 				fil->end_seq += tcp_estimate_tls_overhead(
4688 				    tptosocket(tp), (fil->end - fil->start));
4689 			}
4690 			tp->t_tcpreq_req++;
4691 			if (fil->flags & TCP_TRK_TRACK_FLG_OPEN)
4692 				tp->t_tcpreq_open++;
4693 			else
4694 				tp->t_tcpreq_closed++;
4695 			tcp_req_log_req_info(tp, fil, i,
4696 			    TCP_TRK_REQ_LOG_NEW, 0, 0);
4697 			break;
4698 		} else
4699 			fil = NULL;
4700 	}
4701 	return (fil);
4702 }
4703 
4704 void
4705 tcp_req_alloc_req(struct tcpcb *tp, union tcp_log_userdata *user, uint64_t ts)
4706 {
4707 	(void)tcp_req_alloc_req_full(tp, &user->tcp_req, ts, 1);
4708 }
4709 #endif
4710 
4711 void
4712 tcp_log_socket_option(struct tcpcb *tp, uint32_t option_num, uint32_t option_val, int err)
4713 {
4714 	if (tcp_bblogging_on(tp)) {
4715 		struct tcp_log_buffer *l;
4716 
4717 		l = tcp_log_event(tp, NULL,
4718 		        &tptosocket(tp)->so_rcv,
4719 		        &tptosocket(tp)->so_snd,
4720 		        TCP_LOG_SOCKET_OPT,
4721 		        err, 0, NULL, 1,
4722 		        NULL, NULL, 0, NULL);
4723 		if (l) {
4724 			l->tlb_flex1 = option_num;
4725 			l->tlb_flex2 = option_val;
4726 		}
4727 	}
4728 }
4729 
4730 uint32_t
4731 tcp_get_srtt(struct tcpcb *tp, int granularity)
4732 {
4733 	uint32_t srtt;
4734 
4735 	KASSERT(granularity == TCP_TMR_GRANULARITY_USEC ||
4736 	    granularity == TCP_TMR_GRANULARITY_TICKS,
4737 	    ("%s: called with unexpected granularity %d", __func__,
4738 	    granularity));
4739 
4740 	srtt = tp->t_srtt;
4741 
4742 	/*
4743 	 * We only support two granularities. If the stored granularity
4744 	 * does not match the granularity requested by the caller,
4745 	 * convert the stored value to the requested unit of granularity.
4746 	 */
4747 	if (tp->t_tmr_granularity != granularity) {
4748 		if (granularity == TCP_TMR_GRANULARITY_USEC)
4749 			srtt = TICKS_2_USEC(srtt);
4750 		else
4751 			srtt = USEC_2_TICKS(srtt);
4752 	}
4753 
4754 	/*
4755 	 * If the srtt is stored with ticks granularity, we need to
4756 	 * unshift to get the actual value. We do this after the
4757 	 * conversion above (if one was necessary) in order to maximize
4758 	 * precision.
4759 	 */
4760 	if (tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS)
4761 		srtt = srtt >> TCP_RTT_SHIFT;
4762 
4763 	return (srtt);
4764 }
4765 
4766 void
4767 tcp_account_for_send(struct tcpcb *tp, uint32_t len, uint8_t is_rxt,
4768     uint8_t is_tlp, bool hw_tls)
4769 {
4770 
4771 	if (is_tlp) {
4772 		tp->t_sndtlppack++;
4773 		tp->t_sndtlpbyte += len;
4774 	}
4775 	/* To get total bytes sent you must add t_snd_rxt_bytes to t_sndbytes */
4776 	if (is_rxt)
4777 		tp->t_snd_rxt_bytes += len;
4778 	else
4779 		tp->t_sndbytes += len;
4780 
4781 #ifdef KERN_TLS
4782 	if (hw_tls && is_rxt && len != 0) {
4783 		uint64_t rexmit_percent;
4784 
4785 		rexmit_percent = (1000ULL * tp->t_snd_rxt_bytes) /
4786 		    (10ULL * (tp->t_snd_rxt_bytes + tp->t_sndbytes));
4787 		if (rexmit_percent > ktls_ifnet_max_rexmit_pct)
4788 			ktls_disable_ifnet(tp);
4789 	}
4790 #endif
4791 }
4792