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