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