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