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