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