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