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