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