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