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