xref: /freebsd/sys/netinet/tcp_subr.c (revision d01498defbe804f66435b44f22da9278acddf082)
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include "opt_compat.h"
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/callout.h>
44 #include <sys/eventhandler.h>
45 #ifdef TCP_HHOOK
46 #include <sys/hhook.h>
47 #endif
48 #include <sys/kernel.h>
49 #ifdef TCP_HHOOK
50 #include <sys/khelp.h>
51 #endif
52 #include <sys/sysctl.h>
53 #include <sys/jail.h>
54 #include <sys/malloc.h>
55 #include <sys/refcount.h>
56 #include <sys/mbuf.h>
57 #ifdef INET6
58 #include <sys/domain.h>
59 #endif
60 #include <sys/priv.h>
61 #include <sys/proc.h>
62 #include <sys/sdt.h>
63 #include <sys/socket.h>
64 #include <sys/socketvar.h>
65 #include <sys/protosw.h>
66 #include <sys/random.h>
67 
68 #include <vm/uma.h>
69 
70 #include <net/route.h>
71 #include <net/if.h>
72 #include <net/if_var.h>
73 #include <net/vnet.h>
74 
75 #include <netinet/in.h>
76 #include <netinet/in_fib.h>
77 #include <netinet/in_kdtrace.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/in_systm.h>
80 #include <netinet/in_var.h>
81 #include <netinet/ip.h>
82 #include <netinet/ip_icmp.h>
83 #include <netinet/ip_var.h>
84 #ifdef INET6
85 #include <netinet/icmp6.h>
86 #include <netinet/ip6.h>
87 #include <netinet6/in6_fib.h>
88 #include <netinet6/in6_pcb.h>
89 #include <netinet6/ip6_var.h>
90 #include <netinet6/scope6_var.h>
91 #include <netinet6/nd6.h>
92 #endif
93 
94 #ifdef TCP_RFC7413
95 #include <netinet/tcp_fastopen.h>
96 #endif
97 #include <netinet/tcp.h>
98 #include <netinet/tcp_fsm.h>
99 #include <netinet/tcp_seq.h>
100 #include <netinet/tcp_timer.h>
101 #include <netinet/tcp_var.h>
102 #include <netinet/tcp_syncache.h>
103 #include <netinet/cc/cc.h>
104 #ifdef INET6
105 #include <netinet6/tcp6_var.h>
106 #endif
107 #include <netinet/tcpip.h>
108 #ifdef TCPPCAP
109 #include <netinet/tcp_pcap.h>
110 #endif
111 #ifdef TCPDEBUG
112 #include <netinet/tcp_debug.h>
113 #endif
114 #ifdef INET6
115 #include <netinet6/ip6protosw.h>
116 #endif
117 #ifdef TCP_OFFLOAD
118 #include <netinet/tcp_offload.h>
119 #endif
120 
121 #ifdef IPSEC
122 #include <netipsec/ipsec.h>
123 #include <netipsec/xform.h>
124 #ifdef INET6
125 #include <netipsec/ipsec6.h>
126 #endif
127 #include <netipsec/key.h>
128 #include <sys/syslog.h>
129 #endif /*IPSEC*/
130 
131 #include <machine/in_cksum.h>
132 #include <sys/md5.h>
133 
134 #include <security/mac/mac_framework.h>
135 
136 VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS;
137 #ifdef INET6
138 VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS;
139 #endif
140 
141 struct rwlock tcp_function_lock;
142 
143 static int
144 sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS)
145 {
146 	int error, new;
147 
148 	new = V_tcp_mssdflt;
149 	error = sysctl_handle_int(oidp, &new, 0, req);
150 	if (error == 0 && req->newptr) {
151 		if (new < TCP_MINMSS)
152 			error = EINVAL;
153 		else
154 			V_tcp_mssdflt = new;
155 	}
156 	return (error);
157 }
158 
159 SYSCTL_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt,
160     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, &VNET_NAME(tcp_mssdflt), 0,
161     &sysctl_net_inet_tcp_mss_check, "I",
162     "Default TCP Maximum Segment Size");
163 
164 #ifdef INET6
165 static int
166 sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS)
167 {
168 	int error, new;
169 
170 	new = V_tcp_v6mssdflt;
171 	error = sysctl_handle_int(oidp, &new, 0, req);
172 	if (error == 0 && req->newptr) {
173 		if (new < TCP_MINMSS)
174 			error = EINVAL;
175 		else
176 			V_tcp_v6mssdflt = new;
177 	}
178 	return (error);
179 }
180 
181 SYSCTL_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
182     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, &VNET_NAME(tcp_v6mssdflt), 0,
183     &sysctl_net_inet_tcp_mss_v6_check, "I",
184    "Default TCP Maximum Segment Size for IPv6");
185 #endif /* INET6 */
186 
187 /*
188  * Minimum MSS we accept and use. This prevents DoS attacks where
189  * we are forced to a ridiculous low MSS like 20 and send hundreds
190  * of packets instead of one. The effect scales with the available
191  * bandwidth and quickly saturates the CPU and network interface
192  * with packet generation and sending. Set to zero to disable MINMSS
193  * checking. This setting prevents us from sending too small packets.
194  */
195 VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS;
196 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_VNET | CTLFLAG_RW,
197      &VNET_NAME(tcp_minmss), 0,
198     "Minimum TCP Maximum Segment Size");
199 
200 VNET_DEFINE(int, tcp_do_rfc1323) = 1;
201 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_VNET | CTLFLAG_RW,
202     &VNET_NAME(tcp_do_rfc1323), 0,
203     "Enable rfc1323 (high performance TCP) extensions");
204 
205 static int	tcp_log_debug = 0;
206 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW,
207     &tcp_log_debug, 0, "Log errors caused by incoming TCP segments");
208 
209 static int	tcp_tcbhashsize;
210 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
211     &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
212 
213 static int	do_tcpdrain = 1;
214 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
215     "Enable tcp_drain routine for extra help when low on mbufs");
216 
217 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD,
218     &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs");
219 
220 static VNET_DEFINE(int, icmp_may_rst) = 1;
221 #define	V_icmp_may_rst			VNET(icmp_may_rst)
222 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW,
223     &VNET_NAME(icmp_may_rst), 0,
224     "Certain ICMP unreachable messages may abort connections in SYN_SENT");
225 
226 static VNET_DEFINE(int, tcp_isn_reseed_interval) = 0;
227 #define	V_tcp_isn_reseed_interval	VNET(tcp_isn_reseed_interval)
228 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW,
229     &VNET_NAME(tcp_isn_reseed_interval), 0,
230     "Seconds between reseeding of ISN secret");
231 
232 static int	tcp_soreceive_stream;
233 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN,
234     &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets");
235 
236 #ifdef TCP_SIGNATURE
237 static int	tcp_sig_checksigs = 1;
238 SYSCTL_INT(_net_inet_tcp, OID_AUTO, signature_verify_input, CTLFLAG_RW,
239     &tcp_sig_checksigs, 0, "Verify RFC2385 digests on inbound traffic");
240 #endif
241 
242 VNET_DEFINE(uma_zone_t, sack_hole_zone);
243 #define	V_sack_hole_zone		VNET(sack_hole_zone)
244 
245 #ifdef TCP_HHOOK
246 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]);
247 #endif
248 
249 static struct inpcb *tcp_notify(struct inpcb *, int);
250 static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int);
251 static void tcp_mtudisc(struct inpcb *, int);
252 static char *	tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th,
253 		    void *ip4hdr, const void *ip6hdr);
254 
255 
256 static struct tcp_function_block tcp_def_funcblk = {
257 	"default",
258 	tcp_output,
259 	tcp_do_segment,
260 	tcp_default_ctloutput,
261 	NULL,
262 	NULL,
263 	NULL,
264 	NULL,
265 	NULL,
266 	NULL,
267 	0,
268 	0
269 };
270 
271 int t_functions_inited = 0;
272 struct tcp_funchead t_functions;
273 static struct tcp_function_block *tcp_func_set_ptr = &tcp_def_funcblk;
274 
275 static void
276 init_tcp_functions(void)
277 {
278 	if (t_functions_inited == 0) {
279 		TAILQ_INIT(&t_functions);
280 		rw_init_flags(&tcp_function_lock, "tcp_func_lock" , 0);
281 		t_functions_inited = 1;
282 	}
283 }
284 
285 static struct tcp_function_block *
286 find_tcp_functions_locked(struct tcp_function_set *fs)
287 {
288 	struct tcp_function *f;
289 	struct tcp_function_block *blk=NULL;
290 
291 	TAILQ_FOREACH(f, &t_functions, tf_next) {
292 		if (strcmp(f->tf_fb->tfb_tcp_block_name, fs->function_set_name) == 0) {
293 			blk = f->tf_fb;
294 			break;
295 		}
296 	}
297 	return(blk);
298 }
299 
300 static struct tcp_function_block *
301 find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s)
302 {
303 	struct tcp_function_block *rblk=NULL;
304 	struct tcp_function *f;
305 
306 	TAILQ_FOREACH(f, &t_functions, tf_next) {
307 		if (f->tf_fb == blk) {
308 			rblk = blk;
309 			if (s) {
310 				*s = f;
311 			}
312 			break;
313 		}
314 	}
315 	return (rblk);
316 }
317 
318 struct tcp_function_block *
319 find_and_ref_tcp_functions(struct tcp_function_set *fs)
320 {
321 	struct tcp_function_block *blk;
322 
323 	rw_rlock(&tcp_function_lock);
324 	blk = find_tcp_functions_locked(fs);
325 	if (blk)
326 		refcount_acquire(&blk->tfb_refcnt);
327 	rw_runlock(&tcp_function_lock);
328 	return(blk);
329 }
330 
331 struct tcp_function_block *
332 find_and_ref_tcp_fb(struct tcp_function_block *blk)
333 {
334 	struct tcp_function_block *rblk;
335 
336 	rw_rlock(&tcp_function_lock);
337 	rblk = find_tcp_fb_locked(blk, NULL);
338 	if (rblk)
339 		refcount_acquire(&rblk->tfb_refcnt);
340 	rw_runlock(&tcp_function_lock);
341 	return(rblk);
342 }
343 
344 
345 static int
346 sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS)
347 {
348 	int error=ENOENT;
349 	struct tcp_function_set fs;
350 	struct tcp_function_block *blk;
351 
352 	memset(&fs, 0, sizeof(fs));
353 	rw_rlock(&tcp_function_lock);
354 	blk = find_tcp_fb_locked(tcp_func_set_ptr, NULL);
355 	if (blk) {
356 		/* Found him */
357 		strcpy(fs.function_set_name, blk->tfb_tcp_block_name);
358 		fs.pcbcnt = blk->tfb_refcnt;
359 	}
360 	rw_runlock(&tcp_function_lock);
361 	error = sysctl_handle_string(oidp, fs.function_set_name,
362 				     sizeof(fs.function_set_name), req);
363 
364 	/* Check for error or no change */
365 	if (error != 0 || req->newptr == NULL)
366 		return(error);
367 
368 	rw_wlock(&tcp_function_lock);
369 	blk = find_tcp_functions_locked(&fs);
370 	if ((blk == NULL) ||
371 	    (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) {
372 		error = ENOENT;
373 		goto done;
374 	}
375 	tcp_func_set_ptr = blk;
376 done:
377 	rw_wunlock(&tcp_function_lock);
378 	return (error);
379 }
380 
381 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default,
382 	    CTLTYPE_STRING | CTLFLAG_RW,
383 	    NULL, 0, sysctl_net_inet_default_tcp_functions, "A",
384 	    "Set/get the default TCP functions");
385 
386 static int
387 sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS)
388 {
389 	int error, cnt, linesz;
390 	struct tcp_function *f;
391 	char *buffer, *cp;
392 	size_t bufsz, outsz;
393 
394 	cnt = 0;
395 	rw_rlock(&tcp_function_lock);
396 	TAILQ_FOREACH(f, &t_functions, tf_next) {
397 		cnt++;
398 	}
399 	rw_runlock(&tcp_function_lock);
400 
401 	bufsz = (cnt+2) * (TCP_FUNCTION_NAME_LEN_MAX + 12) + 1;
402 	buffer = malloc(bufsz, M_TEMP, M_WAITOK);
403 
404 	error = 0;
405 	cp = buffer;
406 
407 	linesz = snprintf(cp, bufsz, "\n%-32s%c %s\n", "Stack", 'D', "PCB count");
408 	cp += linesz;
409 	bufsz -= linesz;
410 	outsz = linesz;
411 
412 	rw_rlock(&tcp_function_lock);
413 	TAILQ_FOREACH(f, &t_functions, tf_next) {
414 		linesz = snprintf(cp, bufsz, "%-32s%c %u\n",
415 		    f->tf_fb->tfb_tcp_block_name,
416 		    (f->tf_fb == tcp_func_set_ptr) ? '*' : ' ',
417 		    f->tf_fb->tfb_refcnt);
418 		if (linesz >= bufsz) {
419 			error = EOVERFLOW;
420 			break;
421 		}
422 		cp += linesz;
423 		bufsz -= linesz;
424 		outsz += linesz;
425 	}
426 	rw_runlock(&tcp_function_lock);
427 	if (error == 0)
428 		error = sysctl_handle_string(oidp, buffer, outsz + 1, req);
429 	free(buffer, M_TEMP);
430 	return (error);
431 }
432 
433 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available,
434 	    CTLTYPE_STRING|CTLFLAG_RD,
435 	    NULL, 0, sysctl_net_inet_list_available, "A",
436 	    "list available TCP Function sets");
437 
438 /*
439  * Target size of TCP PCB hash tables. Must be a power of two.
440  *
441  * Note that this can be overridden by the kernel environment
442  * variable net.inet.tcp.tcbhashsize
443  */
444 #ifndef TCBHASHSIZE
445 #define TCBHASHSIZE	0
446 #endif
447 
448 /*
449  * XXX
450  * Callouts should be moved into struct tcp directly.  They are currently
451  * separate because the tcpcb structure is exported to userland for sysctl
452  * parsing purposes, which do not know about callouts.
453  */
454 struct tcpcb_mem {
455 	struct	tcpcb		tcb;
456 	struct	tcp_timer	tt;
457 	struct	cc_var		ccv;
458 #ifdef TCP_HHOOK
459 	struct	osd		osd;
460 #endif
461 };
462 
463 static VNET_DEFINE(uma_zone_t, tcpcb_zone);
464 #define	V_tcpcb_zone			VNET(tcpcb_zone)
465 
466 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers");
467 MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory");
468 
469 static struct mtx isn_mtx;
470 
471 #define	ISN_LOCK_INIT()	mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
472 #define	ISN_LOCK()	mtx_lock(&isn_mtx)
473 #define	ISN_UNLOCK()	mtx_unlock(&isn_mtx)
474 
475 /*
476  * TCP initialization.
477  */
478 static void
479 tcp_zone_change(void *tag)
480 {
481 
482 	uma_zone_set_max(V_tcbinfo.ipi_zone, maxsockets);
483 	uma_zone_set_max(V_tcpcb_zone, maxsockets);
484 	tcp_tw_zone_change();
485 }
486 
487 static int
488 tcp_inpcb_init(void *mem, int size, int flags)
489 {
490 	struct inpcb *inp = mem;
491 
492 	INP_LOCK_INIT(inp, "inp", "tcpinp");
493 	return (0);
494 }
495 
496 /*
497  * Take a value and get the next power of 2 that doesn't overflow.
498  * Used to size the tcp_inpcb hash buckets.
499  */
500 static int
501 maketcp_hashsize(int size)
502 {
503 	int hashsize;
504 
505 	/*
506 	 * auto tune.
507 	 * get the next power of 2 higher than maxsockets.
508 	 */
509 	hashsize = 1 << fls(size);
510 	/* catch overflow, and just go one power of 2 smaller */
511 	if (hashsize < size) {
512 		hashsize = 1 << (fls(size) - 1);
513 	}
514 	return (hashsize);
515 }
516 
517 int
518 register_tcp_functions(struct tcp_function_block *blk, int wait)
519 {
520 	struct tcp_function_block *lblk;
521 	struct tcp_function *n;
522 	struct tcp_function_set fs;
523 
524 	if (t_functions_inited == 0) {
525 		init_tcp_functions();
526 	}
527 	if ((blk->tfb_tcp_output == NULL) ||
528 	    (blk->tfb_tcp_do_segment == NULL) ||
529 	    (blk->tfb_tcp_ctloutput == NULL) ||
530 	    (strlen(blk->tfb_tcp_block_name) == 0)) {
531 		/*
532 		 * These functions are required and you
533 		 * need a name.
534 		 */
535 		return (EINVAL);
536 	}
537 	if (blk->tfb_tcp_timer_stop_all ||
538 	    blk->tfb_tcp_timer_activate ||
539 	    blk->tfb_tcp_timer_active ||
540 	    blk->tfb_tcp_timer_stop) {
541 		/*
542 		 * If you define one timer function you
543 		 * must have them all.
544 		 */
545 		if ((blk->tfb_tcp_timer_stop_all == NULL) ||
546 		    (blk->tfb_tcp_timer_activate == NULL) ||
547 		    (blk->tfb_tcp_timer_active == NULL) ||
548 		    (blk->tfb_tcp_timer_stop == NULL)) {
549 			return (EINVAL);
550 		}
551 	}
552 	n = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait);
553 	if (n == NULL) {
554 		return (ENOMEM);
555 	}
556 	n->tf_fb = blk;
557 	strcpy(fs.function_set_name, blk->tfb_tcp_block_name);
558 	rw_wlock(&tcp_function_lock);
559 	lblk = find_tcp_functions_locked(&fs);
560 	if (lblk) {
561 		/* Duplicate name space not allowed */
562 		rw_wunlock(&tcp_function_lock);
563 		free(n, M_TCPFUNCTIONS);
564 		return (EALREADY);
565 	}
566 	refcount_init(&blk->tfb_refcnt, 0);
567 	blk->tfb_flags = 0;
568 	TAILQ_INSERT_TAIL(&t_functions, n, tf_next);
569 	rw_wunlock(&tcp_function_lock);
570 	return(0);
571 }
572 
573 int
574 deregister_tcp_functions(struct tcp_function_block *blk)
575 {
576 	struct tcp_function_block *lblk;
577 	struct tcp_function *f;
578 	int error=ENOENT;
579 
580 	if (strcmp(blk->tfb_tcp_block_name, "default") == 0) {
581 		/* You can't un-register the default */
582 		return (EPERM);
583 	}
584 	rw_wlock(&tcp_function_lock);
585 	if (blk == tcp_func_set_ptr) {
586 		/* You can't free the current default */
587 		rw_wunlock(&tcp_function_lock);
588 		return (EBUSY);
589 	}
590 	if (blk->tfb_refcnt) {
591 		/* Still tcb attached, mark it. */
592 		blk->tfb_flags |= TCP_FUNC_BEING_REMOVED;
593 		rw_wunlock(&tcp_function_lock);
594 		return (EBUSY);
595 	}
596 	lblk = find_tcp_fb_locked(blk, &f);
597 	if (lblk) {
598 		/* Found */
599 		TAILQ_REMOVE(&t_functions, f, tf_next);
600 		f->tf_fb = NULL;
601 		free(f, M_TCPFUNCTIONS);
602 		error = 0;
603 	}
604 	rw_wunlock(&tcp_function_lock);
605 	return (error);
606 }
607 
608 void
609 tcp_init(void)
610 {
611 	const char *tcbhash_tuneable;
612 	int hashsize;
613 
614 	tcbhash_tuneable = "net.inet.tcp.tcbhashsize";
615 
616 #ifdef TCP_HHOOK
617 	if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN,
618 	    &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
619 		printf("%s: WARNING: unable to register helper hook\n", __func__);
620 	if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT,
621 	    &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
622 		printf("%s: WARNING: unable to register helper hook\n", __func__);
623 #endif
624 	hashsize = TCBHASHSIZE;
625 	TUNABLE_INT_FETCH(tcbhash_tuneable, &hashsize);
626 	if (hashsize == 0) {
627 		/*
628 		 * Auto tune the hash size based on maxsockets.
629 		 * A perfect hash would have a 1:1 mapping
630 		 * (hashsize = maxsockets) however it's been
631 		 * suggested that O(2) average is better.
632 		 */
633 		hashsize = maketcp_hashsize(maxsockets / 4);
634 		/*
635 		 * Our historical default is 512,
636 		 * do not autotune lower than this.
637 		 */
638 		if (hashsize < 512)
639 			hashsize = 512;
640 		if (bootverbose && IS_DEFAULT_VNET(curvnet))
641 			printf("%s: %s auto tuned to %d\n", __func__,
642 			    tcbhash_tuneable, hashsize);
643 	}
644 	/*
645 	 * We require a hashsize to be a power of two.
646 	 * Previously if it was not a power of two we would just reset it
647 	 * back to 512, which could be a nasty surprise if you did not notice
648 	 * the error message.
649 	 * Instead what we do is clip it to the closest power of two lower
650 	 * than the specified hash value.
651 	 */
652 	if (!powerof2(hashsize)) {
653 		int oldhashsize = hashsize;
654 
655 		hashsize = maketcp_hashsize(hashsize);
656 		/* prevent absurdly low value */
657 		if (hashsize < 16)
658 			hashsize = 16;
659 		printf("%s: WARNING: TCB hash size not a power of 2, "
660 		    "clipped from %d to %d.\n", __func__, oldhashsize,
661 		    hashsize);
662 	}
663 	in_pcbinfo_init(&V_tcbinfo, "tcp", &V_tcb, hashsize, hashsize,
664 	    "tcp_inpcb", tcp_inpcb_init, NULL, 0, IPI_HASHFIELDS_4TUPLE);
665 
666 	/*
667 	 * These have to be type stable for the benefit of the timers.
668 	 */
669 	V_tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem),
670 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
671 	uma_zone_set_max(V_tcpcb_zone, maxsockets);
672 	uma_zone_set_warning(V_tcpcb_zone, "kern.ipc.maxsockets limit reached");
673 
674 	tcp_tw_init();
675 	syncache_init();
676 	tcp_hc_init();
677 
678 	TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack);
679 	V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
680 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
681 
682 	/* Skip initialization of globals for non-default instances. */
683 	if (!IS_DEFAULT_VNET(curvnet))
684 		return;
685 
686 	tcp_reass_global_init();
687 
688 	/* XXX virtualize those bellow? */
689 	tcp_delacktime = TCPTV_DELACK;
690 	tcp_keepinit = TCPTV_KEEP_INIT;
691 	tcp_keepidle = TCPTV_KEEP_IDLE;
692 	tcp_keepintvl = TCPTV_KEEPINTVL;
693 	tcp_maxpersistidle = TCPTV_KEEP_IDLE;
694 	tcp_msl = TCPTV_MSL;
695 	tcp_rexmit_min = TCPTV_MIN;
696 	if (tcp_rexmit_min < 1)
697 		tcp_rexmit_min = 1;
698 	tcp_persmin = TCPTV_PERSMIN;
699 	tcp_persmax = TCPTV_PERSMAX;
700 	tcp_rexmit_slop = TCPTV_CPU_VAR;
701 	tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT;
702 	tcp_tcbhashsize = hashsize;
703 	/* Setup the tcp function block list */
704 	init_tcp_functions();
705 	register_tcp_functions(&tcp_def_funcblk, M_WAITOK);
706 
707 	if (tcp_soreceive_stream) {
708 #ifdef INET
709 		tcp_usrreqs.pru_soreceive = soreceive_stream;
710 #endif
711 #ifdef INET6
712 		tcp6_usrreqs.pru_soreceive = soreceive_stream;
713 #endif /* INET6 */
714 	}
715 
716 #ifdef INET6
717 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
718 #else /* INET6 */
719 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
720 #endif /* INET6 */
721 	if (max_protohdr < TCP_MINPROTOHDR)
722 		max_protohdr = TCP_MINPROTOHDR;
723 	if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
724 		panic("tcp_init");
725 #undef TCP_MINPROTOHDR
726 
727 	ISN_LOCK_INIT();
728 	EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
729 		SHUTDOWN_PRI_DEFAULT);
730 	EVENTHANDLER_REGISTER(maxsockets_change, tcp_zone_change, NULL,
731 		EVENTHANDLER_PRI_ANY);
732 #ifdef TCPPCAP
733 	tcp_pcap_init();
734 #endif
735 
736 #ifdef TCP_RFC7413
737 	tcp_fastopen_init();
738 #endif
739 }
740 
741 #ifdef VIMAGE
742 static void
743 tcp_destroy(void *unused __unused)
744 {
745 	int error, n;
746 
747 	/*
748 	 * All our processes are gone, all our sockets should be cleaned
749 	 * up, which means, we should be past the tcp_discardcb() calls.
750 	 * Sleep to let all tcpcb timers really disappear and cleanup.
751 	 */
752 	for (;;) {
753 		INP_LIST_RLOCK(&V_tcbinfo);
754 		n = V_tcbinfo.ipi_count;
755 		INP_LIST_RUNLOCK(&V_tcbinfo);
756 		if (n == 0)
757 			break;
758 		pause("tcpdes", hz / 10);
759 	}
760 	tcp_hc_destroy();
761 	syncache_destroy();
762 	tcp_tw_destroy();
763 	in_pcbinfo_destroy(&V_tcbinfo);
764 	/* tcp_discardcb() clears the sack_holes up. */
765 	uma_zdestroy(V_sack_hole_zone);
766 	uma_zdestroy(V_tcpcb_zone);
767 
768 #ifdef TCP_RFC7413
769 	/*
770 	 * Cannot free the zone until all tcpcbs are released as we attach
771 	 * the allocations to them.
772 	 */
773 	tcp_fastopen_destroy();
774 #endif
775 
776 #ifdef TCP_HHOOK
777 	error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]);
778 	if (error != 0) {
779 		printf("%s: WARNING: unable to deregister helper hook "
780 		    "type=%d, id=%d: error %d returned\n", __func__,
781 		    HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error);
782 	}
783 	error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]);
784 	if (error != 0) {
785 		printf("%s: WARNING: unable to deregister helper hook "
786 		    "type=%d, id=%d: error %d returned\n", __func__,
787 		    HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error);
788 	}
789 #endif
790 }
791 VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_destroy, NULL);
792 #endif
793 
794 void
795 tcp_fini(void *xtp)
796 {
797 
798 }
799 
800 /*
801  * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
802  * tcp_template used to store this data in mbufs, but we now recopy it out
803  * of the tcpcb each time to conserve mbufs.
804  */
805 void
806 tcpip_fillheaders(struct inpcb *inp, void *ip_ptr, void *tcp_ptr)
807 {
808 	struct tcphdr *th = (struct tcphdr *)tcp_ptr;
809 
810 	INP_WLOCK_ASSERT(inp);
811 
812 #ifdef INET6
813 	if ((inp->inp_vflag & INP_IPV6) != 0) {
814 		struct ip6_hdr *ip6;
815 
816 		ip6 = (struct ip6_hdr *)ip_ptr;
817 		ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
818 			(inp->inp_flow & IPV6_FLOWINFO_MASK);
819 		ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
820 			(IPV6_VERSION & IPV6_VERSION_MASK);
821 		ip6->ip6_nxt = IPPROTO_TCP;
822 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
823 		ip6->ip6_src = inp->in6p_laddr;
824 		ip6->ip6_dst = inp->in6p_faddr;
825 	}
826 #endif /* INET6 */
827 #if defined(INET6) && defined(INET)
828 	else
829 #endif
830 #ifdef INET
831 	{
832 		struct ip *ip;
833 
834 		ip = (struct ip *)ip_ptr;
835 		ip->ip_v = IPVERSION;
836 		ip->ip_hl = 5;
837 		ip->ip_tos = inp->inp_ip_tos;
838 		ip->ip_len = 0;
839 		ip->ip_id = 0;
840 		ip->ip_off = 0;
841 		ip->ip_ttl = inp->inp_ip_ttl;
842 		ip->ip_sum = 0;
843 		ip->ip_p = IPPROTO_TCP;
844 		ip->ip_src = inp->inp_laddr;
845 		ip->ip_dst = inp->inp_faddr;
846 	}
847 #endif /* INET */
848 	th->th_sport = inp->inp_lport;
849 	th->th_dport = inp->inp_fport;
850 	th->th_seq = 0;
851 	th->th_ack = 0;
852 	th->th_x2 = 0;
853 	th->th_off = 5;
854 	th->th_flags = 0;
855 	th->th_win = 0;
856 	th->th_urp = 0;
857 	th->th_sum = 0;		/* in_pseudo() is called later for ipv4 */
858 }
859 
860 /*
861  * Create template to be used to send tcp packets on a connection.
862  * Allocates an mbuf and fills in a skeletal tcp/ip header.  The only
863  * use for this function is in keepalives, which use tcp_respond.
864  */
865 struct tcptemp *
866 tcpip_maketemplate(struct inpcb *inp)
867 {
868 	struct tcptemp *t;
869 
870 	t = malloc(sizeof(*t), M_TEMP, M_NOWAIT);
871 	if (t == NULL)
872 		return (NULL);
873 	tcpip_fillheaders(inp, (void *)&t->tt_ipgen, (void *)&t->tt_t);
874 	return (t);
875 }
876 
877 /*
878  * Send a single message to the TCP at address specified by
879  * the given TCP/IP header.  If m == NULL, then we make a copy
880  * of the tcpiphdr at th and send directly to the addressed host.
881  * This is used to force keep alive messages out using the TCP
882  * template for a connection.  If flags are given then we send
883  * a message back to the TCP which originated the segment th,
884  * and discard the mbuf containing it and any other attached mbufs.
885  *
886  * In any case the ack and sequence number of the transmitted
887  * segment are as specified by the parameters.
888  *
889  * NOTE: If m != NULL, then th must point to *inside* the mbuf.
890  */
891 void
892 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
893     tcp_seq ack, tcp_seq seq, int flags)
894 {
895 	struct tcpopt to;
896 	struct inpcb *inp;
897 	struct ip *ip;
898 	struct mbuf *optm;
899 	struct tcphdr *nth;
900 	u_char *optp;
901 #ifdef INET6
902 	struct ip6_hdr *ip6;
903 	int isipv6;
904 #endif /* INET6 */
905 	int optlen, tlen, win;
906 	bool incl_opts;
907 
908 	KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
909 
910 #ifdef INET6
911 	isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4);
912 	ip6 = ipgen;
913 #endif /* INET6 */
914 	ip = ipgen;
915 
916 	if (tp != NULL) {
917 		inp = tp->t_inpcb;
918 		KASSERT(inp != NULL, ("tcp control block w/o inpcb"));
919 		INP_WLOCK_ASSERT(inp);
920 	} else
921 		inp = NULL;
922 
923 	incl_opts = false;
924 	win = 0;
925 	if (tp != NULL) {
926 		if (!(flags & TH_RST)) {
927 			win = sbspace(&inp->inp_socket->so_rcv);
928 			if (win > TCP_MAXWIN << tp->rcv_scale)
929 				win = TCP_MAXWIN << tp->rcv_scale;
930 		}
931 		if ((tp->t_flags & TF_NOOPT) == 0)
932 			incl_opts = true;
933 	}
934 	if (m == NULL) {
935 		m = m_gethdr(M_NOWAIT, MT_DATA);
936 		if (m == NULL)
937 			return;
938 		m->m_data += max_linkhdr;
939 #ifdef INET6
940 		if (isipv6) {
941 			bcopy((caddr_t)ip6, mtod(m, caddr_t),
942 			      sizeof(struct ip6_hdr));
943 			ip6 = mtod(m, struct ip6_hdr *);
944 			nth = (struct tcphdr *)(ip6 + 1);
945 		} else
946 #endif /* INET6 */
947 		{
948 			bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
949 			ip = mtod(m, struct ip *);
950 			nth = (struct tcphdr *)(ip + 1);
951 		}
952 		bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
953 		flags = TH_ACK;
954 	} else if (!M_WRITABLE(m)) {
955 		struct mbuf *n;
956 
957 		/* Can't reuse 'm', allocate a new mbuf. */
958 		n = m_gethdr(M_NOWAIT, MT_DATA);
959 		if (n == NULL) {
960 			m_freem(m);
961 			return;
962 		}
963 
964 		if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
965 			m_freem(m);
966 			m_freem(n);
967 			return;
968 		}
969 
970 		n->m_data += max_linkhdr;
971 		/* m_len is set later */
972 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
973 #ifdef INET6
974 		if (isipv6) {
975 			bcopy((caddr_t)ip6, mtod(n, caddr_t),
976 			      sizeof(struct ip6_hdr));
977 			ip6 = mtod(n, struct ip6_hdr *);
978 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
979 			nth = (struct tcphdr *)(ip6 + 1);
980 		} else
981 #endif /* INET6 */
982 		{
983 			bcopy((caddr_t)ip, mtod(n, caddr_t), sizeof(struct ip));
984 			ip = mtod(n, struct ip *);
985 			xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
986 			nth = (struct tcphdr *)(ip + 1);
987 		}
988 		bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
989 		xchg(nth->th_dport, nth->th_sport, uint16_t);
990 		th = nth;
991 		m_freem(m);
992 		m = n;
993 	} else {
994 		/*
995 		 *  reuse the mbuf.
996 		 * XXX MRT We inherit the FIB, which is lucky.
997 		 */
998 		m_freem(m->m_next);
999 		m->m_next = NULL;
1000 		m->m_data = (caddr_t)ipgen;
1001 		/* m_len is set later */
1002 #ifdef INET6
1003 		if (isipv6) {
1004 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1005 			nth = (struct tcphdr *)(ip6 + 1);
1006 		} else
1007 #endif /* INET6 */
1008 		{
1009 			xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1010 			nth = (struct tcphdr *)(ip + 1);
1011 		}
1012 		if (th != nth) {
1013 			/*
1014 			 * this is usually a case when an extension header
1015 			 * exists between the IPv6 header and the
1016 			 * TCP header.
1017 			 */
1018 			nth->th_sport = th->th_sport;
1019 			nth->th_dport = th->th_dport;
1020 		}
1021 		xchg(nth->th_dport, nth->th_sport, uint16_t);
1022 #undef xchg
1023 	}
1024 	tlen = 0;
1025 #ifdef INET6
1026 	if (isipv6)
1027 		tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
1028 #endif
1029 #if defined(INET) && defined(INET6)
1030 	else
1031 #endif
1032 #ifdef INET
1033 		tlen = sizeof (struct tcpiphdr);
1034 #endif
1035 #ifdef INVARIANTS
1036 	m->m_len = 0;
1037 	KASSERT(M_TRAILINGSPACE(m) >= tlen,
1038 	    ("Not enough trailing space for message (m=%p, need=%d, have=%ld)",
1039 	    m, tlen, (long)M_TRAILINGSPACE(m)));
1040 #endif
1041 	m->m_len = tlen;
1042 	to.to_flags = 0;
1043 	if (incl_opts) {
1044 		/* Make sure we have room. */
1045 		if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) {
1046 			m->m_next = m_get(M_NOWAIT, MT_DATA);
1047 			if (m->m_next) {
1048 				optp = mtod(m->m_next, u_char *);
1049 				optm = m->m_next;
1050 			} else
1051 				incl_opts = false;
1052 		} else {
1053 			optp = (u_char *) (nth + 1);
1054 			optm = m;
1055 		}
1056 	}
1057 	if (incl_opts) {
1058 		/* Timestamps. */
1059 		if (tp->t_flags & TF_RCVD_TSTMP) {
1060 			to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
1061 			to.to_tsecr = tp->ts_recent;
1062 			to.to_flags |= TOF_TS;
1063 		}
1064 #ifdef TCP_SIGNATURE
1065 		/* TCP-MD5 (RFC2385). */
1066 		if (tp->t_flags & TF_SIGNATURE)
1067 			to.to_flags |= TOF_SIGNATURE;
1068 #endif
1069 
1070 		/* Add the options. */
1071 		tlen += optlen = tcp_addoptions(&to, optp);
1072 
1073 		/* Update m_len in the correct mbuf. */
1074 		optm->m_len += optlen;
1075 	} else
1076 		optlen = 0;
1077 #ifdef INET6
1078 	if (isipv6) {
1079 		ip6->ip6_flow = 0;
1080 		ip6->ip6_vfc = IPV6_VERSION;
1081 		ip6->ip6_nxt = IPPROTO_TCP;
1082 		ip6->ip6_plen = htons(tlen - sizeof(*ip6));
1083 	}
1084 #endif
1085 #if defined(INET) && defined(INET6)
1086 	else
1087 #endif
1088 #ifdef INET
1089 	{
1090 		ip->ip_len = htons(tlen);
1091 		ip->ip_ttl = V_ip_defttl;
1092 		if (V_path_mtu_discovery)
1093 			ip->ip_off |= htons(IP_DF);
1094 	}
1095 #endif
1096 	m->m_pkthdr.len = tlen;
1097 	m->m_pkthdr.rcvif = NULL;
1098 #ifdef MAC
1099 	if (inp != NULL) {
1100 		/*
1101 		 * Packet is associated with a socket, so allow the
1102 		 * label of the response to reflect the socket label.
1103 		 */
1104 		INP_WLOCK_ASSERT(inp);
1105 		mac_inpcb_create_mbuf(inp, m);
1106 	} else {
1107 		/*
1108 		 * Packet is not associated with a socket, so possibly
1109 		 * update the label in place.
1110 		 */
1111 		mac_netinet_tcp_reply(m);
1112 	}
1113 #endif
1114 	nth->th_seq = htonl(seq);
1115 	nth->th_ack = htonl(ack);
1116 	nth->th_x2 = 0;
1117 	nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
1118 	nth->th_flags = flags;
1119 	if (tp != NULL)
1120 		nth->th_win = htons((u_short) (win >> tp->rcv_scale));
1121 	else
1122 		nth->th_win = htons((u_short)win);
1123 	nth->th_urp = 0;
1124 
1125 #ifdef TCP_SIGNATURE
1126 	if (to.to_flags & TOF_SIGNATURE) {
1127 		tcp_signature_compute(m, 0, 0, optlen, to.to_signature,
1128 		    IPSEC_DIR_OUTBOUND);
1129 	}
1130 #endif
1131 
1132 	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1133 #ifdef INET6
1134 	if (isipv6) {
1135 		m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
1136 		nth->th_sum = in6_cksum_pseudo(ip6,
1137 		    tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0);
1138 		ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb :
1139 		    NULL, NULL);
1140 	}
1141 #endif /* INET6 */
1142 #if defined(INET6) && defined(INET)
1143 	else
1144 #endif
1145 #ifdef INET
1146 	{
1147 		m->m_pkthdr.csum_flags = CSUM_TCP;
1148 		nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1149 		    htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
1150 	}
1151 #endif /* INET */
1152 #ifdef TCPDEBUG
1153 	if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG))
1154 		tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
1155 #endif
1156 	TCP_PROBE3(debug__output, tp, th, mtod(m, const char *));
1157 	if (flags & TH_RST)
1158 		TCP_PROBE5(accept__refused, NULL, NULL, mtod(m, const char *),
1159 		    tp, nth);
1160 
1161 	TCP_PROBE5(send, NULL, tp, mtod(m, const char *), tp, nth);
1162 #ifdef INET6
1163 	if (isipv6)
1164 		(void) ip6_output(m, NULL, NULL, 0, NULL, NULL, inp);
1165 #endif /* INET6 */
1166 #if defined(INET) && defined(INET6)
1167 	else
1168 #endif
1169 #ifdef INET
1170 		(void) ip_output(m, NULL, NULL, 0, NULL, inp);
1171 #endif
1172 }
1173 
1174 /*
1175  * Create a new TCP control block, making an
1176  * empty reassembly queue and hooking it to the argument
1177  * protocol control block.  The `inp' parameter must have
1178  * come from the zone allocator set up in tcp_init().
1179  */
1180 struct tcpcb *
1181 tcp_newtcpcb(struct inpcb *inp)
1182 {
1183 	struct tcpcb_mem *tm;
1184 	struct tcpcb *tp;
1185 #ifdef INET6
1186 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
1187 #endif /* INET6 */
1188 
1189 	tm = uma_zalloc(V_tcpcb_zone, M_NOWAIT | M_ZERO);
1190 	if (tm == NULL)
1191 		return (NULL);
1192 	tp = &tm->tcb;
1193 
1194 	/* Initialise cc_var struct for this tcpcb. */
1195 	tp->ccv = &tm->ccv;
1196 	tp->ccv->type = IPPROTO_TCP;
1197 	tp->ccv->ccvc.tcp = tp;
1198 	rw_rlock(&tcp_function_lock);
1199 	tp->t_fb = tcp_func_set_ptr;
1200 	refcount_acquire(&tp->t_fb->tfb_refcnt);
1201 	rw_runlock(&tcp_function_lock);
1202 	/*
1203 	 * Use the current system default CC algorithm.
1204 	 */
1205 	CC_LIST_RLOCK();
1206 	KASSERT(!STAILQ_EMPTY(&cc_list), ("cc_list is empty!"));
1207 	CC_ALGO(tp) = CC_DEFAULT();
1208 	CC_LIST_RUNLOCK();
1209 
1210 	if (CC_ALGO(tp)->cb_init != NULL)
1211 		if (CC_ALGO(tp)->cb_init(tp->ccv) > 0) {
1212 			if (tp->t_fb->tfb_tcp_fb_fini)
1213 				(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
1214 			refcount_release(&tp->t_fb->tfb_refcnt);
1215 			uma_zfree(V_tcpcb_zone, tm);
1216 			return (NULL);
1217 		}
1218 
1219 #ifdef TCP_HHOOK
1220 	tp->osd = &tm->osd;
1221 	if (khelp_init_osd(HELPER_CLASS_TCP, tp->osd)) {
1222 		if (tp->t_fb->tfb_tcp_fb_fini)
1223 			(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
1224 		refcount_release(&tp->t_fb->tfb_refcnt);
1225 		uma_zfree(V_tcpcb_zone, tm);
1226 		return (NULL);
1227 	}
1228 #endif
1229 
1230 #ifdef VIMAGE
1231 	tp->t_vnet = inp->inp_vnet;
1232 #endif
1233 	tp->t_timers = &tm->tt;
1234 	/*	LIST_INIT(&tp->t_segq); */	/* XXX covered by M_ZERO */
1235 	tp->t_maxseg =
1236 #ifdef INET6
1237 		isipv6 ? V_tcp_v6mssdflt :
1238 #endif /* INET6 */
1239 		V_tcp_mssdflt;
1240 
1241 	/* Set up our timeouts. */
1242 	callout_init(&tp->t_timers->tt_rexmt, 1);
1243 	callout_init(&tp->t_timers->tt_persist, 1);
1244 	callout_init(&tp->t_timers->tt_keep, 1);
1245 	callout_init(&tp->t_timers->tt_2msl, 1);
1246 	callout_init(&tp->t_timers->tt_delack, 1);
1247 
1248 	if (V_tcp_do_rfc1323)
1249 		tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
1250 	if (V_tcp_do_sack)
1251 		tp->t_flags |= TF_SACK_PERMIT;
1252 	TAILQ_INIT(&tp->snd_holes);
1253 	/*
1254 	 * The tcpcb will hold a reference on its inpcb until tcp_discardcb()
1255 	 * is called.
1256 	 */
1257 	in_pcbref(inp);	/* Reference for tcpcb */
1258 	tp->t_inpcb = inp;
1259 
1260 	/*
1261 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
1262 	 * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
1263 	 * reasonable initial retransmit time.
1264 	 */
1265 	tp->t_srtt = TCPTV_SRTTBASE;
1266 	tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
1267 	tp->t_rttmin = tcp_rexmit_min;
1268 	tp->t_rxtcur = TCPTV_RTOBASE;
1269 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
1270 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
1271 	tp->t_rcvtime = ticks;
1272 	/*
1273 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
1274 	 * because the socket may be bound to an IPv6 wildcard address,
1275 	 * which may match an IPv4-mapped IPv6 address.
1276 	 */
1277 	inp->inp_ip_ttl = V_ip_defttl;
1278 	inp->inp_ppcb = tp;
1279 #ifdef TCPPCAP
1280 	/*
1281 	 * Init the TCP PCAP queues.
1282 	 */
1283 	tcp_pcap_tcpcb_init(tp);
1284 #endif
1285 	if (tp->t_fb->tfb_tcp_fb_init) {
1286 		(*tp->t_fb->tfb_tcp_fb_init)(tp);
1287 	}
1288 	return (tp);		/* XXX */
1289 }
1290 
1291 /*
1292  * Switch the congestion control algorithm back to NewReno for any active
1293  * control blocks using an algorithm which is about to go away.
1294  * This ensures the CC framework can allow the unload to proceed without leaving
1295  * any dangling pointers which would trigger a panic.
1296  * Returning non-zero would inform the CC framework that something went wrong
1297  * and it would be unsafe to allow the unload to proceed. However, there is no
1298  * way for this to occur with this implementation so we always return zero.
1299  */
1300 int
1301 tcp_ccalgounload(struct cc_algo *unload_algo)
1302 {
1303 	struct cc_algo *tmpalgo;
1304 	struct inpcb *inp;
1305 	struct tcpcb *tp;
1306 	VNET_ITERATOR_DECL(vnet_iter);
1307 
1308 	/*
1309 	 * Check all active control blocks across all network stacks and change
1310 	 * any that are using "unload_algo" back to NewReno. If "unload_algo"
1311 	 * requires cleanup code to be run, call it.
1312 	 */
1313 	VNET_LIST_RLOCK();
1314 	VNET_FOREACH(vnet_iter) {
1315 		CURVNET_SET(vnet_iter);
1316 		INP_INFO_WLOCK(&V_tcbinfo);
1317 		/*
1318 		 * New connections already part way through being initialised
1319 		 * with the CC algo we're removing will not race with this code
1320 		 * because the INP_INFO_WLOCK is held during initialisation. We
1321 		 * therefore don't enter the loop below until the connection
1322 		 * list has stabilised.
1323 		 */
1324 		LIST_FOREACH(inp, &V_tcb, inp_list) {
1325 			INP_WLOCK(inp);
1326 			/* Important to skip tcptw structs. */
1327 			if (!(inp->inp_flags & INP_TIMEWAIT) &&
1328 			    (tp = intotcpcb(inp)) != NULL) {
1329 				/*
1330 				 * By holding INP_WLOCK here, we are assured
1331 				 * that the connection is not currently
1332 				 * executing inside the CC module's functions
1333 				 * i.e. it is safe to make the switch back to
1334 				 * NewReno.
1335 				 */
1336 				if (CC_ALGO(tp) == unload_algo) {
1337 					tmpalgo = CC_ALGO(tp);
1338 					/* NewReno does not require any init. */
1339 					CC_ALGO(tp) = &newreno_cc_algo;
1340 					if (tmpalgo->cb_destroy != NULL)
1341 						tmpalgo->cb_destroy(tp->ccv);
1342 				}
1343 			}
1344 			INP_WUNLOCK(inp);
1345 		}
1346 		INP_INFO_WUNLOCK(&V_tcbinfo);
1347 		CURVNET_RESTORE();
1348 	}
1349 	VNET_LIST_RUNLOCK();
1350 
1351 	return (0);
1352 }
1353 
1354 /*
1355  * Drop a TCP connection, reporting
1356  * the specified error.  If connection is synchronized,
1357  * then send a RST to peer.
1358  */
1359 struct tcpcb *
1360 tcp_drop(struct tcpcb *tp, int errno)
1361 {
1362 	struct socket *so = tp->t_inpcb->inp_socket;
1363 
1364 	INP_INFO_LOCK_ASSERT(&V_tcbinfo);
1365 	INP_WLOCK_ASSERT(tp->t_inpcb);
1366 
1367 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
1368 		tcp_state_change(tp, TCPS_CLOSED);
1369 		(void) tp->t_fb->tfb_tcp_output(tp);
1370 		TCPSTAT_INC(tcps_drops);
1371 	} else
1372 		TCPSTAT_INC(tcps_conndrops);
1373 	if (errno == ETIMEDOUT && tp->t_softerror)
1374 		errno = tp->t_softerror;
1375 	so->so_error = errno;
1376 	return (tcp_close(tp));
1377 }
1378 
1379 void
1380 tcp_discardcb(struct tcpcb *tp)
1381 {
1382 	struct inpcb *inp = tp->t_inpcb;
1383 	struct socket *so = inp->inp_socket;
1384 #ifdef INET6
1385 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
1386 #endif /* INET6 */
1387 	int released;
1388 
1389 	INP_WLOCK_ASSERT(inp);
1390 
1391 	/*
1392 	 * Make sure that all of our timers are stopped before we delete the
1393 	 * PCB.
1394 	 *
1395 	 * If stopping a timer fails, we schedule a discard function in same
1396 	 * callout, and the last discard function called will take care of
1397 	 * deleting the tcpcb.
1398 	 */
1399 	tp->t_timers->tt_draincnt = 0;
1400 	tcp_timer_stop(tp, TT_REXMT);
1401 	tcp_timer_stop(tp, TT_PERSIST);
1402 	tcp_timer_stop(tp, TT_KEEP);
1403 	tcp_timer_stop(tp, TT_2MSL);
1404 	tcp_timer_stop(tp, TT_DELACK);
1405 	if (tp->t_fb->tfb_tcp_timer_stop_all) {
1406 		/*
1407 		 * Call the stop-all function of the methods,
1408 		 * this function should call the tcp_timer_stop()
1409 		 * method with each of the function specific timeouts.
1410 		 * That stop will be called via the tfb_tcp_timer_stop()
1411 		 * which should use the async drain function of the
1412 		 * callout system (see tcp_var.h).
1413 		 */
1414 		tp->t_fb->tfb_tcp_timer_stop_all(tp);
1415 	}
1416 
1417 	/*
1418 	 * If we got enough samples through the srtt filter,
1419 	 * save the rtt and rttvar in the routing entry.
1420 	 * 'Enough' is arbitrarily defined as 4 rtt samples.
1421 	 * 4 samples is enough for the srtt filter to converge
1422 	 * to within enough % of the correct value; fewer samples
1423 	 * and we could save a bogus rtt. The danger is not high
1424 	 * as tcp quickly recovers from everything.
1425 	 * XXX: Works very well but needs some more statistics!
1426 	 */
1427 	if (tp->t_rttupdated >= 4) {
1428 		struct hc_metrics_lite metrics;
1429 		uint32_t ssthresh;
1430 
1431 		bzero(&metrics, sizeof(metrics));
1432 		/*
1433 		 * Update the ssthresh always when the conditions below
1434 		 * are satisfied. This gives us better new start value
1435 		 * for the congestion avoidance for new connections.
1436 		 * ssthresh is only set if packet loss occurred on a session.
1437 		 *
1438 		 * XXXRW: 'so' may be NULL here, and/or socket buffer may be
1439 		 * being torn down.  Ideally this code would not use 'so'.
1440 		 */
1441 		ssthresh = tp->snd_ssthresh;
1442 		if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
1443 			/*
1444 			 * convert the limit from user data bytes to
1445 			 * packets then to packet data bytes.
1446 			 */
1447 			ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
1448 			if (ssthresh < 2)
1449 				ssthresh = 2;
1450 			ssthresh *= (tp->t_maxseg +
1451 #ifdef INET6
1452 			    (isipv6 ? sizeof (struct ip6_hdr) +
1453 				sizeof (struct tcphdr) :
1454 #endif
1455 				sizeof (struct tcpiphdr)
1456 #ifdef INET6
1457 			    )
1458 #endif
1459 			    );
1460 		} else
1461 			ssthresh = 0;
1462 		metrics.rmx_ssthresh = ssthresh;
1463 
1464 		metrics.rmx_rtt = tp->t_srtt;
1465 		metrics.rmx_rttvar = tp->t_rttvar;
1466 		metrics.rmx_cwnd = tp->snd_cwnd;
1467 		metrics.rmx_sendpipe = 0;
1468 		metrics.rmx_recvpipe = 0;
1469 
1470 		tcp_hc_update(&inp->inp_inc, &metrics);
1471 	}
1472 
1473 	/* free the reassembly queue, if any */
1474 	tcp_reass_flush(tp);
1475 
1476 #ifdef TCP_OFFLOAD
1477 	/* Disconnect offload device, if any. */
1478 	if (tp->t_flags & TF_TOE)
1479 		tcp_offload_detach(tp);
1480 #endif
1481 
1482 	tcp_free_sackholes(tp);
1483 
1484 #ifdef TCPPCAP
1485 	/* Free the TCP PCAP queues. */
1486 	tcp_pcap_drain(&(tp->t_inpkts));
1487 	tcp_pcap_drain(&(tp->t_outpkts));
1488 #endif
1489 
1490 	/* Allow the CC algorithm to clean up after itself. */
1491 	if (CC_ALGO(tp)->cb_destroy != NULL)
1492 		CC_ALGO(tp)->cb_destroy(tp->ccv);
1493 
1494 #ifdef TCP_HHOOK
1495 	khelp_destroy_osd(tp->osd);
1496 #endif
1497 
1498 	CC_ALGO(tp) = NULL;
1499 	inp->inp_ppcb = NULL;
1500 	if (tp->t_timers->tt_draincnt == 0) {
1501 		/* We own the last reference on tcpcb, let's free it. */
1502 		if (tp->t_fb->tfb_tcp_fb_fini)
1503 			(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
1504 		refcount_release(&tp->t_fb->tfb_refcnt);
1505 		tp->t_inpcb = NULL;
1506 		uma_zfree(V_tcpcb_zone, tp);
1507 		released = in_pcbrele_wlocked(inp);
1508 		KASSERT(!released, ("%s: inp %p should not have been released "
1509 			"here", __func__, inp));
1510 	}
1511 }
1512 
1513 void
1514 tcp_timer_discard(void *ptp)
1515 {
1516 	struct inpcb *inp;
1517 	struct tcpcb *tp;
1518 
1519 	tp = (struct tcpcb *)ptp;
1520 	CURVNET_SET(tp->t_vnet);
1521 	INP_INFO_RLOCK(&V_tcbinfo);
1522 	inp = tp->t_inpcb;
1523 	KASSERT(inp != NULL, ("%s: tp %p tp->t_inpcb == NULL",
1524 		__func__, tp));
1525 	INP_WLOCK(inp);
1526 	KASSERT((tp->t_timers->tt_flags & TT_STOPPED) != 0,
1527 		("%s: tcpcb has to be stopped here", __func__));
1528 	tp->t_timers->tt_draincnt--;
1529 	if (tp->t_timers->tt_draincnt == 0) {
1530 		/* We own the last reference on this tcpcb, let's free it. */
1531 		if (tp->t_fb->tfb_tcp_fb_fini)
1532 			(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
1533 		refcount_release(&tp->t_fb->tfb_refcnt);
1534 		tp->t_inpcb = NULL;
1535 		uma_zfree(V_tcpcb_zone, tp);
1536 		if (in_pcbrele_wlocked(inp)) {
1537 			INP_INFO_RUNLOCK(&V_tcbinfo);
1538 			CURVNET_RESTORE();
1539 			return;
1540 		}
1541 	}
1542 	INP_WUNLOCK(inp);
1543 	INP_INFO_RUNLOCK(&V_tcbinfo);
1544 	CURVNET_RESTORE();
1545 }
1546 
1547 /*
1548  * Attempt to close a TCP control block, marking it as dropped, and freeing
1549  * the socket if we hold the only reference.
1550  */
1551 struct tcpcb *
1552 tcp_close(struct tcpcb *tp)
1553 {
1554 	struct inpcb *inp = tp->t_inpcb;
1555 	struct socket *so;
1556 
1557 	INP_INFO_LOCK_ASSERT(&V_tcbinfo);
1558 	INP_WLOCK_ASSERT(inp);
1559 
1560 #ifdef TCP_OFFLOAD
1561 	if (tp->t_state == TCPS_LISTEN)
1562 		tcp_offload_listen_stop(tp);
1563 #endif
1564 #ifdef TCP_RFC7413
1565 	/*
1566 	 * This releases the TFO pending counter resource for TFO listen
1567 	 * sockets as well as passively-created TFO sockets that transition
1568 	 * from SYN_RECEIVED to CLOSED.
1569 	 */
1570 	if (tp->t_tfo_pending) {
1571 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
1572 		tp->t_tfo_pending = NULL;
1573 	}
1574 #endif
1575 	in_pcbdrop(inp);
1576 	TCPSTAT_INC(tcps_closed);
1577 	TCPSTATES_DEC(tp->t_state);
1578 	KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
1579 	so = inp->inp_socket;
1580 	soisdisconnected(so);
1581 	if (inp->inp_flags & INP_SOCKREF) {
1582 		KASSERT(so->so_state & SS_PROTOREF,
1583 		    ("tcp_close: !SS_PROTOREF"));
1584 		inp->inp_flags &= ~INP_SOCKREF;
1585 		INP_WUNLOCK(inp);
1586 		ACCEPT_LOCK();
1587 		SOCK_LOCK(so);
1588 		so->so_state &= ~SS_PROTOREF;
1589 		sofree(so);
1590 		return (NULL);
1591 	}
1592 	return (tp);
1593 }
1594 
1595 void
1596 tcp_drain(void)
1597 {
1598 	VNET_ITERATOR_DECL(vnet_iter);
1599 
1600 	if (!do_tcpdrain)
1601 		return;
1602 
1603 	VNET_LIST_RLOCK_NOSLEEP();
1604 	VNET_FOREACH(vnet_iter) {
1605 		CURVNET_SET(vnet_iter);
1606 		struct inpcb *inpb;
1607 		struct tcpcb *tcpb;
1608 
1609 	/*
1610 	 * Walk the tcpbs, if existing, and flush the reassembly queue,
1611 	 * if there is one...
1612 	 * XXX: The "Net/3" implementation doesn't imply that the TCP
1613 	 *      reassembly queue should be flushed, but in a situation
1614 	 *	where we're really low on mbufs, this is potentially
1615 	 *	useful.
1616 	 */
1617 		INP_INFO_WLOCK(&V_tcbinfo);
1618 		LIST_FOREACH(inpb, V_tcbinfo.ipi_listhead, inp_list) {
1619 			if (inpb->inp_flags & INP_TIMEWAIT)
1620 				continue;
1621 			INP_WLOCK(inpb);
1622 			if ((tcpb = intotcpcb(inpb)) != NULL) {
1623 				tcp_reass_flush(tcpb);
1624 				tcp_clean_sackreport(tcpb);
1625 #ifdef TCPPCAP
1626 				if (tcp_pcap_aggressive_free) {
1627 					/* Free the TCP PCAP queues. */
1628 					tcp_pcap_drain(&(tcpb->t_inpkts));
1629 					tcp_pcap_drain(&(tcpb->t_outpkts));
1630 				}
1631 #endif
1632 			}
1633 			INP_WUNLOCK(inpb);
1634 		}
1635 		INP_INFO_WUNLOCK(&V_tcbinfo);
1636 		CURVNET_RESTORE();
1637 	}
1638 	VNET_LIST_RUNLOCK_NOSLEEP();
1639 }
1640 
1641 /*
1642  * Notify a tcp user of an asynchronous error;
1643  * store error as soft error, but wake up user
1644  * (for now, won't do anything until can select for soft error).
1645  *
1646  * Do not wake up user since there currently is no mechanism for
1647  * reporting soft errors (yet - a kqueue filter may be added).
1648  */
1649 static struct inpcb *
1650 tcp_notify(struct inpcb *inp, int error)
1651 {
1652 	struct tcpcb *tp;
1653 
1654 	INP_INFO_LOCK_ASSERT(&V_tcbinfo);
1655 	INP_WLOCK_ASSERT(inp);
1656 
1657 	if ((inp->inp_flags & INP_TIMEWAIT) ||
1658 	    (inp->inp_flags & INP_DROPPED))
1659 		return (inp);
1660 
1661 	tp = intotcpcb(inp);
1662 	KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
1663 
1664 	/*
1665 	 * Ignore some errors if we are hooked up.
1666 	 * If connection hasn't completed, has retransmitted several times,
1667 	 * and receives a second error, give up now.  This is better
1668 	 * than waiting a long time to establish a connection that
1669 	 * can never complete.
1670 	 */
1671 	if (tp->t_state == TCPS_ESTABLISHED &&
1672 	    (error == EHOSTUNREACH || error == ENETUNREACH ||
1673 	     error == EHOSTDOWN)) {
1674 		if (inp->inp_route.ro_rt) {
1675 			RTFREE(inp->inp_route.ro_rt);
1676 			inp->inp_route.ro_rt = (struct rtentry *)NULL;
1677 		}
1678 		return (inp);
1679 	} else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
1680 	    tp->t_softerror) {
1681 		tp = tcp_drop(tp, error);
1682 		if (tp != NULL)
1683 			return (inp);
1684 		else
1685 			return (NULL);
1686 	} else {
1687 		tp->t_softerror = error;
1688 		return (inp);
1689 	}
1690 #if 0
1691 	wakeup( &so->so_timeo);
1692 	sorwakeup(so);
1693 	sowwakeup(so);
1694 #endif
1695 }
1696 
1697 static int
1698 tcp_pcblist(SYSCTL_HANDLER_ARGS)
1699 {
1700 	int error, i, m, n, pcb_count;
1701 	struct inpcb *inp, **inp_list;
1702 	inp_gen_t gencnt;
1703 	struct xinpgen xig;
1704 
1705 	/*
1706 	 * The process of preparing the TCB list is too time-consuming and
1707 	 * resource-intensive to repeat twice on every request.
1708 	 */
1709 	if (req->oldptr == NULL) {
1710 		n = V_tcbinfo.ipi_count +
1711 		    counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
1712 		n += imax(n / 8, 10);
1713 		req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb);
1714 		return (0);
1715 	}
1716 
1717 	if (req->newptr != NULL)
1718 		return (EPERM);
1719 
1720 	/*
1721 	 * OK, now we're committed to doing something.
1722 	 */
1723 	INP_LIST_RLOCK(&V_tcbinfo);
1724 	gencnt = V_tcbinfo.ipi_gencnt;
1725 	n = V_tcbinfo.ipi_count;
1726 	INP_LIST_RUNLOCK(&V_tcbinfo);
1727 
1728 	m = counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
1729 
1730 	error = sysctl_wire_old_buffer(req, 2 * (sizeof xig)
1731 		+ (n + m) * sizeof(struct xtcpcb));
1732 	if (error != 0)
1733 		return (error);
1734 
1735 	xig.xig_len = sizeof xig;
1736 	xig.xig_count = n + m;
1737 	xig.xig_gen = gencnt;
1738 	xig.xig_sogen = so_gencnt;
1739 	error = SYSCTL_OUT(req, &xig, sizeof xig);
1740 	if (error)
1741 		return (error);
1742 
1743 	error = syncache_pcblist(req, m, &pcb_count);
1744 	if (error)
1745 		return (error);
1746 
1747 	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
1748 
1749 	INP_INFO_WLOCK(&V_tcbinfo);
1750 	for (inp = LIST_FIRST(V_tcbinfo.ipi_listhead), i = 0;
1751 	    inp != NULL && i < n; inp = LIST_NEXT(inp, inp_list)) {
1752 		INP_WLOCK(inp);
1753 		if (inp->inp_gencnt <= gencnt) {
1754 			/*
1755 			 * XXX: This use of cr_cansee(), introduced with
1756 			 * TCP state changes, is not quite right, but for
1757 			 * now, better than nothing.
1758 			 */
1759 			if (inp->inp_flags & INP_TIMEWAIT) {
1760 				if (intotw(inp) != NULL)
1761 					error = cr_cansee(req->td->td_ucred,
1762 					    intotw(inp)->tw_cred);
1763 				else
1764 					error = EINVAL;	/* Skip this inp. */
1765 			} else
1766 				error = cr_canseeinpcb(req->td->td_ucred, inp);
1767 			if (error == 0) {
1768 				in_pcbref(inp);
1769 				inp_list[i++] = inp;
1770 			}
1771 		}
1772 		INP_WUNLOCK(inp);
1773 	}
1774 	INP_INFO_WUNLOCK(&V_tcbinfo);
1775 	n = i;
1776 
1777 	error = 0;
1778 	for (i = 0; i < n; i++) {
1779 		inp = inp_list[i];
1780 		INP_RLOCK(inp);
1781 		if (inp->inp_gencnt <= gencnt) {
1782 			struct xtcpcb xt;
1783 			void *inp_ppcb;
1784 
1785 			bzero(&xt, sizeof(xt));
1786 			xt.xt_len = sizeof xt;
1787 			/* XXX should avoid extra copy */
1788 			bcopy(inp, &xt.xt_inp, sizeof *inp);
1789 			inp_ppcb = inp->inp_ppcb;
1790 			if (inp_ppcb == NULL)
1791 				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
1792 			else if (inp->inp_flags & INP_TIMEWAIT) {
1793 				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
1794 				xt.xt_tp.t_state = TCPS_TIME_WAIT;
1795 			} else {
1796 				bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp);
1797 				if (xt.xt_tp.t_timers)
1798 					tcp_timer_to_xtimer(&xt.xt_tp, xt.xt_tp.t_timers, &xt.xt_timer);
1799 			}
1800 			if (inp->inp_socket != NULL)
1801 				sotoxsocket(inp->inp_socket, &xt.xt_socket);
1802 			else {
1803 				bzero(&xt.xt_socket, sizeof xt.xt_socket);
1804 				xt.xt_socket.xso_protocol = IPPROTO_TCP;
1805 			}
1806 			xt.xt_inp.inp_gencnt = inp->inp_gencnt;
1807 			INP_RUNLOCK(inp);
1808 			error = SYSCTL_OUT(req, &xt, sizeof xt);
1809 		} else
1810 			INP_RUNLOCK(inp);
1811 	}
1812 	INP_INFO_RLOCK(&V_tcbinfo);
1813 	for (i = 0; i < n; i++) {
1814 		inp = inp_list[i];
1815 		INP_RLOCK(inp);
1816 		if (!in_pcbrele_rlocked(inp))
1817 			INP_RUNLOCK(inp);
1818 	}
1819 	INP_INFO_RUNLOCK(&V_tcbinfo);
1820 
1821 	if (!error) {
1822 		/*
1823 		 * Give the user an updated idea of our state.
1824 		 * If the generation differs from what we told
1825 		 * her before, she knows that something happened
1826 		 * while we were processing this request, and it
1827 		 * might be necessary to retry.
1828 		 */
1829 		INP_LIST_RLOCK(&V_tcbinfo);
1830 		xig.xig_gen = V_tcbinfo.ipi_gencnt;
1831 		xig.xig_sogen = so_gencnt;
1832 		xig.xig_count = V_tcbinfo.ipi_count + pcb_count;
1833 		INP_LIST_RUNLOCK(&V_tcbinfo);
1834 		error = SYSCTL_OUT(req, &xig, sizeof xig);
1835 	}
1836 	free(inp_list, M_TEMP);
1837 	return (error);
1838 }
1839 
1840 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist,
1841     CTLTYPE_OPAQUE | CTLFLAG_RD, NULL, 0,
1842     tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
1843 
1844 #ifdef INET
1845 static int
1846 tcp_getcred(SYSCTL_HANDLER_ARGS)
1847 {
1848 	struct xucred xuc;
1849 	struct sockaddr_in addrs[2];
1850 	struct inpcb *inp;
1851 	int error;
1852 
1853 	error = priv_check(req->td, PRIV_NETINET_GETCRED);
1854 	if (error)
1855 		return (error);
1856 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
1857 	if (error)
1858 		return (error);
1859 	inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
1860 	    addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL);
1861 	if (inp != NULL) {
1862 		if (inp->inp_socket == NULL)
1863 			error = ENOENT;
1864 		if (error == 0)
1865 			error = cr_canseeinpcb(req->td->td_ucred, inp);
1866 		if (error == 0)
1867 			cru2x(inp->inp_cred, &xuc);
1868 		INP_RUNLOCK(inp);
1869 	} else
1870 		error = ENOENT;
1871 	if (error == 0)
1872 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
1873 	return (error);
1874 }
1875 
1876 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
1877     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
1878     tcp_getcred, "S,xucred", "Get the xucred of a TCP connection");
1879 #endif /* INET */
1880 
1881 #ifdef INET6
1882 static int
1883 tcp6_getcred(SYSCTL_HANDLER_ARGS)
1884 {
1885 	struct xucred xuc;
1886 	struct sockaddr_in6 addrs[2];
1887 	struct inpcb *inp;
1888 	int error;
1889 #ifdef INET
1890 	int mapped = 0;
1891 #endif
1892 
1893 	error = priv_check(req->td, PRIV_NETINET_GETCRED);
1894 	if (error)
1895 		return (error);
1896 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
1897 	if (error)
1898 		return (error);
1899 	if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
1900 	    (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
1901 		return (error);
1902 	}
1903 	if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
1904 #ifdef INET
1905 		if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
1906 			mapped = 1;
1907 		else
1908 #endif
1909 			return (EINVAL);
1910 	}
1911 
1912 #ifdef INET
1913 	if (mapped == 1)
1914 		inp = in_pcblookup(&V_tcbinfo,
1915 			*(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
1916 			addrs[1].sin6_port,
1917 			*(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
1918 			addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL);
1919 	else
1920 #endif
1921 		inp = in6_pcblookup(&V_tcbinfo,
1922 			&addrs[1].sin6_addr, addrs[1].sin6_port,
1923 			&addrs[0].sin6_addr, addrs[0].sin6_port,
1924 			INPLOOKUP_RLOCKPCB, NULL);
1925 	if (inp != NULL) {
1926 		if (inp->inp_socket == NULL)
1927 			error = ENOENT;
1928 		if (error == 0)
1929 			error = cr_canseeinpcb(req->td->td_ucred, inp);
1930 		if (error == 0)
1931 			cru2x(inp->inp_cred, &xuc);
1932 		INP_RUNLOCK(inp);
1933 	} else
1934 		error = ENOENT;
1935 	if (error == 0)
1936 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
1937 	return (error);
1938 }
1939 
1940 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
1941     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
1942     tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection");
1943 #endif /* INET6 */
1944 
1945 
1946 #ifdef INET
1947 void
1948 tcp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
1949 {
1950 	struct ip *ip = vip;
1951 	struct tcphdr *th;
1952 	struct in_addr faddr;
1953 	struct inpcb *inp;
1954 	struct tcpcb *tp;
1955 	struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
1956 	struct icmp *icp;
1957 	struct in_conninfo inc;
1958 	tcp_seq icmp_tcp_seq;
1959 	int mtu;
1960 
1961 	faddr = ((struct sockaddr_in *)sa)->sin_addr;
1962 	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
1963 		return;
1964 
1965 	if (cmd == PRC_MSGSIZE)
1966 		notify = tcp_mtudisc_notify;
1967 	else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
1968 		cmd == PRC_UNREACH_PORT || cmd == PRC_TIMXCEED_INTRANS) && ip)
1969 		notify = tcp_drop_syn_sent;
1970 
1971 	/*
1972 	 * Hostdead is ugly because it goes linearly through all PCBs.
1973 	 * XXX: We never get this from ICMP, otherwise it makes an
1974 	 * excellent DoS attack on machines with many connections.
1975 	 */
1976 	else if (cmd == PRC_HOSTDEAD)
1977 		ip = NULL;
1978 	else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
1979 		return;
1980 
1981 	if (ip == NULL) {
1982 		in_pcbnotifyall(&V_tcbinfo, faddr, inetctlerrmap[cmd], notify);
1983 		return;
1984 	}
1985 
1986 	icp = (struct icmp *)((caddr_t)ip - offsetof(struct icmp, icmp_ip));
1987 	th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
1988 	INP_INFO_RLOCK(&V_tcbinfo);
1989 	inp = in_pcblookup(&V_tcbinfo, faddr, th->th_dport, ip->ip_src,
1990 	    th->th_sport, INPLOOKUP_WLOCKPCB, NULL);
1991 	if (inp != NULL && PRC_IS_REDIRECT(cmd)) {
1992 		/* signal EHOSTDOWN, as it flushes the cached route */
1993 		inp = (*notify)(inp, EHOSTDOWN);
1994 		if (inp != NULL)
1995 			INP_WUNLOCK(inp);
1996 	} else if (inp != NULL)  {
1997 		if (!(inp->inp_flags & INP_TIMEWAIT) &&
1998 		    !(inp->inp_flags & INP_DROPPED) &&
1999 		    !(inp->inp_socket == NULL)) {
2000 			icmp_tcp_seq = ntohl(th->th_seq);
2001 			tp = intotcpcb(inp);
2002 			if (SEQ_GEQ(icmp_tcp_seq, tp->snd_una) &&
2003 			    SEQ_LT(icmp_tcp_seq, tp->snd_max)) {
2004 				if (cmd == PRC_MSGSIZE) {
2005 					/*
2006 					 * MTU discovery:
2007 					 * If we got a needfrag set the MTU
2008 					 * in the route to the suggested new
2009 					 * value (if given) and then notify.
2010 					 */
2011 				    	mtu = ntohs(icp->icmp_nextmtu);
2012 					/*
2013 					 * If no alternative MTU was
2014 					 * proposed, try the next smaller
2015 					 * one.
2016 					 */
2017 					if (!mtu)
2018 						mtu = ip_next_mtu(
2019 						    ntohs(ip->ip_len), 1);
2020 					if (mtu < V_tcp_minmss +
2021 					    sizeof(struct tcpiphdr))
2022 						mtu = V_tcp_minmss +
2023 						    sizeof(struct tcpiphdr);
2024 					/*
2025 					 * Only process the offered MTU if it
2026 					 * is smaller than the current one.
2027 					 */
2028 					if (mtu < tp->t_maxseg +
2029 					    sizeof(struct tcpiphdr)) {
2030 						bzero(&inc, sizeof(inc));
2031 						inc.inc_faddr = faddr;
2032 						inc.inc_fibnum =
2033 						    inp->inp_inc.inc_fibnum;
2034 						tcp_hc_updatemtu(&inc, mtu);
2035 						tcp_mtudisc(inp, mtu);
2036 					}
2037 				} else
2038 					inp = (*notify)(inp,
2039 					    inetctlerrmap[cmd]);
2040 			}
2041 		}
2042 		if (inp != NULL)
2043 			INP_WUNLOCK(inp);
2044 	} else {
2045 		bzero(&inc, sizeof(inc));
2046 		inc.inc_fport = th->th_dport;
2047 		inc.inc_lport = th->th_sport;
2048 		inc.inc_faddr = faddr;
2049 		inc.inc_laddr = ip->ip_src;
2050 		syncache_unreach(&inc, th);
2051 	}
2052 	INP_INFO_RUNLOCK(&V_tcbinfo);
2053 }
2054 #endif /* INET */
2055 
2056 #ifdef INET6
2057 void
2058 tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
2059 {
2060 	struct in6_addr *dst;
2061 	struct tcphdr *th;
2062 	struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
2063 	struct ip6_hdr *ip6;
2064 	struct mbuf *m;
2065 	struct inpcb *inp;
2066 	struct tcpcb *tp;
2067 	struct icmp6_hdr *icmp6;
2068 	struct ip6ctlparam *ip6cp = NULL;
2069 	const struct sockaddr_in6 *sa6_src = NULL;
2070 	struct in_conninfo inc;
2071 	tcp_seq icmp_tcp_seq;
2072 	unsigned int mtu;
2073 	unsigned int off;
2074 
2075 
2076 	if (sa->sa_family != AF_INET6 ||
2077 	    sa->sa_len != sizeof(struct sockaddr_in6))
2078 		return;
2079 
2080 	/* if the parameter is from icmp6, decode it. */
2081 	if (d != NULL) {
2082 		ip6cp = (struct ip6ctlparam *)d;
2083 		icmp6 = ip6cp->ip6c_icmp6;
2084 		m = ip6cp->ip6c_m;
2085 		ip6 = ip6cp->ip6c_ip6;
2086 		off = ip6cp->ip6c_off;
2087 		sa6_src = ip6cp->ip6c_src;
2088 		dst = ip6cp->ip6c_finaldst;
2089 	} else {
2090 		m = NULL;
2091 		ip6 = NULL;
2092 		off = 0;	/* fool gcc */
2093 		sa6_src = &sa6_any;
2094 		dst = NULL;
2095 	}
2096 
2097 	if (cmd == PRC_MSGSIZE)
2098 		notify = tcp_mtudisc_notify;
2099 	else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
2100 		cmd == PRC_UNREACH_PORT || cmd == PRC_TIMXCEED_INTRANS) &&
2101 		ip6 != NULL)
2102 		notify = tcp_drop_syn_sent;
2103 
2104 	/*
2105 	 * Hostdead is ugly because it goes linearly through all PCBs.
2106 	 * XXX: We never get this from ICMP, otherwise it makes an
2107 	 * excellent DoS attack on machines with many connections.
2108 	 */
2109 	else if (cmd == PRC_HOSTDEAD)
2110 		ip6 = NULL;
2111 	else if ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0)
2112 		return;
2113 
2114 	if (ip6 == NULL) {
2115 		in6_pcbnotify(&V_tcbinfo, sa, 0,
2116 			      (const struct sockaddr *)sa6_src,
2117 			      0, cmd, NULL, notify);
2118 		return;
2119 	}
2120 
2121 	/* Check if we can safely get the ports from the tcp hdr */
2122 	if (m == NULL ||
2123 	    (m->m_pkthdr.len <
2124 		(int32_t) (off + offsetof(struct tcphdr, th_seq)))) {
2125 		return;
2126 	}
2127 
2128 	th = (struct tcphdr *) mtodo(ip6cp->ip6c_m, ip6cp->ip6c_off);
2129 	INP_INFO_RLOCK(&V_tcbinfo);
2130 	inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, th->th_dport,
2131 	    &ip6->ip6_src, th->th_sport, INPLOOKUP_WLOCKPCB, NULL);
2132 	if (inp != NULL && PRC_IS_REDIRECT(cmd)) {
2133 		/* signal EHOSTDOWN, as it flushes the cached route */
2134 		inp = (*notify)(inp, EHOSTDOWN);
2135 		if (inp != NULL)
2136 			INP_WUNLOCK(inp);
2137 	} else if (inp != NULL)  {
2138 		if (!(inp->inp_flags & INP_TIMEWAIT) &&
2139 		    !(inp->inp_flags & INP_DROPPED) &&
2140 		    !(inp->inp_socket == NULL)) {
2141 			icmp_tcp_seq = ntohl(th->th_seq);
2142 			tp = intotcpcb(inp);
2143 			if (SEQ_GEQ(icmp_tcp_seq, tp->snd_una) &&
2144 			    SEQ_LT(icmp_tcp_seq, tp->snd_max)) {
2145 				if (cmd == PRC_MSGSIZE) {
2146 					/*
2147 					 * MTU discovery:
2148 					 * If we got a needfrag set the MTU
2149 					 * in the route to the suggested new
2150 					 * value (if given) and then notify.
2151 					 */
2152 					mtu = ntohl(icmp6->icmp6_mtu);
2153 					/*
2154 					 * If no alternative MTU was
2155 					 * proposed, or the proposed
2156 					 * MTU was too small, set to
2157 					 * the min.
2158 					 */
2159 					if (mtu < IPV6_MMTU)
2160 						mtu = IPV6_MMTU - 8;
2161 
2162 
2163 					bzero(&inc, sizeof(inc));
2164 					inc.inc_fibnum = M_GETFIB(m);
2165 					inc.inc_flags |= INC_ISIPV6;
2166 					inc.inc6_faddr = *dst;
2167 					if (in6_setscope(&inc.inc6_faddr,
2168 						m->m_pkthdr.rcvif, NULL))
2169 						goto unlock_inp;
2170 
2171 					/*
2172 					 * Only process the offered MTU if it
2173 					 * is smaller than the current one.
2174 					 */
2175 					if (mtu < tp->t_maxseg +
2176 					    (sizeof (*th) + sizeof (*ip6))) {
2177 						tcp_hc_updatemtu(&inc, mtu);
2178 						tcp_mtudisc(inp, mtu);
2179 						ICMP6STAT_INC(icp6s_pmtuchg);
2180 					}
2181 				} else
2182 					inp = (*notify)(inp,
2183 					    inet6ctlerrmap[cmd]);
2184 			}
2185 		}
2186 unlock_inp:
2187 		if (inp != NULL)
2188 			INP_WUNLOCK(inp);
2189 	} else {
2190 		bzero(&inc, sizeof(inc));
2191 		inc.inc_fibnum = M_GETFIB(m);
2192 		inc.inc_flags |= INC_ISIPV6;
2193 		inc.inc_fport = th->th_dport;
2194 		inc.inc_lport = th->th_sport;
2195 		inc.inc6_faddr = *dst;
2196 		inc.inc6_laddr = ip6->ip6_src;
2197 		syncache_unreach(&inc, th);
2198 	}
2199 	INP_INFO_RUNLOCK(&V_tcbinfo);
2200 }
2201 #endif /* INET6 */
2202 
2203 
2204 /*
2205  * Following is where TCP initial sequence number generation occurs.
2206  *
2207  * There are two places where we must use initial sequence numbers:
2208  * 1.  In SYN-ACK packets.
2209  * 2.  In SYN packets.
2210  *
2211  * All ISNs for SYN-ACK packets are generated by the syncache.  See
2212  * tcp_syncache.c for details.
2213  *
2214  * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
2215  * depends on this property.  In addition, these ISNs should be
2216  * unguessable so as to prevent connection hijacking.  To satisfy
2217  * the requirements of this situation, the algorithm outlined in
2218  * RFC 1948 is used, with only small modifications.
2219  *
2220  * Implementation details:
2221  *
2222  * Time is based off the system timer, and is corrected so that it
2223  * increases by one megabyte per second.  This allows for proper
2224  * recycling on high speed LANs while still leaving over an hour
2225  * before rollover.
2226  *
2227  * As reading the *exact* system time is too expensive to be done
2228  * whenever setting up a TCP connection, we increment the time
2229  * offset in two ways.  First, a small random positive increment
2230  * is added to isn_offset for each connection that is set up.
2231  * Second, the function tcp_isn_tick fires once per clock tick
2232  * and increments isn_offset as necessary so that sequence numbers
2233  * are incremented at approximately ISN_BYTES_PER_SECOND.  The
2234  * random positive increments serve only to ensure that the same
2235  * exact sequence number is never sent out twice (as could otherwise
2236  * happen when a port is recycled in less than the system tick
2237  * interval.)
2238  *
2239  * net.inet.tcp.isn_reseed_interval controls the number of seconds
2240  * between seeding of isn_secret.  This is normally set to zero,
2241  * as reseeding should not be necessary.
2242  *
2243  * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
2244  * isn_offset_old, and isn_ctx is performed using the TCP pcbinfo lock.  In
2245  * general, this means holding an exclusive (write) lock.
2246  */
2247 
2248 #define ISN_BYTES_PER_SECOND 1048576
2249 #define ISN_STATIC_INCREMENT 4096
2250 #define ISN_RANDOM_INCREMENT (4096 - 1)
2251 
2252 static VNET_DEFINE(u_char, isn_secret[32]);
2253 static VNET_DEFINE(int, isn_last);
2254 static VNET_DEFINE(int, isn_last_reseed);
2255 static VNET_DEFINE(u_int32_t, isn_offset);
2256 static VNET_DEFINE(u_int32_t, isn_offset_old);
2257 
2258 #define	V_isn_secret			VNET(isn_secret)
2259 #define	V_isn_last			VNET(isn_last)
2260 #define	V_isn_last_reseed		VNET(isn_last_reseed)
2261 #define	V_isn_offset			VNET(isn_offset)
2262 #define	V_isn_offset_old		VNET(isn_offset_old)
2263 
2264 tcp_seq
2265 tcp_new_isn(struct tcpcb *tp)
2266 {
2267 	MD5_CTX isn_ctx;
2268 	u_int32_t md5_buffer[4];
2269 	tcp_seq new_isn;
2270 	u_int32_t projected_offset;
2271 
2272 	INP_WLOCK_ASSERT(tp->t_inpcb);
2273 
2274 	ISN_LOCK();
2275 	/* Seed if this is the first use, reseed if requested. */
2276 	if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) &&
2277 	     (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz)
2278 		< (u_int)ticks))) {
2279 		read_random(&V_isn_secret, sizeof(V_isn_secret));
2280 		V_isn_last_reseed = ticks;
2281 	}
2282 
2283 	/* Compute the md5 hash and return the ISN. */
2284 	MD5Init(&isn_ctx);
2285 	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short));
2286 	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short));
2287 #ifdef INET6
2288 	if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) {
2289 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr,
2290 			  sizeof(struct in6_addr));
2291 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr,
2292 			  sizeof(struct in6_addr));
2293 	} else
2294 #endif
2295 	{
2296 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr,
2297 			  sizeof(struct in_addr));
2298 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr,
2299 			  sizeof(struct in_addr));
2300 	}
2301 	MD5Update(&isn_ctx, (u_char *) &V_isn_secret, sizeof(V_isn_secret));
2302 	MD5Final((u_char *) &md5_buffer, &isn_ctx);
2303 	new_isn = (tcp_seq) md5_buffer[0];
2304 	V_isn_offset += ISN_STATIC_INCREMENT +
2305 		(arc4random() & ISN_RANDOM_INCREMENT);
2306 	if (ticks != V_isn_last) {
2307 		projected_offset = V_isn_offset_old +
2308 		    ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last);
2309 		if (SEQ_GT(projected_offset, V_isn_offset))
2310 			V_isn_offset = projected_offset;
2311 		V_isn_offset_old = V_isn_offset;
2312 		V_isn_last = ticks;
2313 	}
2314 	new_isn += V_isn_offset;
2315 	ISN_UNLOCK();
2316 	return (new_isn);
2317 }
2318 
2319 /*
2320  * When a specific ICMP unreachable message is received and the
2321  * connection state is SYN-SENT, drop the connection.  This behavior
2322  * is controlled by the icmp_may_rst sysctl.
2323  */
2324 struct inpcb *
2325 tcp_drop_syn_sent(struct inpcb *inp, int errno)
2326 {
2327 	struct tcpcb *tp;
2328 
2329 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2330 	INP_WLOCK_ASSERT(inp);
2331 
2332 	if ((inp->inp_flags & INP_TIMEWAIT) ||
2333 	    (inp->inp_flags & INP_DROPPED))
2334 		return (inp);
2335 
2336 	tp = intotcpcb(inp);
2337 	if (tp->t_state != TCPS_SYN_SENT)
2338 		return (inp);
2339 
2340 	tp = tcp_drop(tp, errno);
2341 	if (tp != NULL)
2342 		return (inp);
2343 	else
2344 		return (NULL);
2345 }
2346 
2347 /*
2348  * When `need fragmentation' ICMP is received, update our idea of the MSS
2349  * based on the new value. Also nudge TCP to send something, since we
2350  * know the packet we just sent was dropped.
2351  * This duplicates some code in the tcp_mss() function in tcp_input.c.
2352  */
2353 static struct inpcb *
2354 tcp_mtudisc_notify(struct inpcb *inp, int error)
2355 {
2356 
2357 	tcp_mtudisc(inp, -1);
2358 	return (inp);
2359 }
2360 
2361 static void
2362 tcp_mtudisc(struct inpcb *inp, int mtuoffer)
2363 {
2364 	struct tcpcb *tp;
2365 	struct socket *so;
2366 
2367 	INP_WLOCK_ASSERT(inp);
2368 	if ((inp->inp_flags & INP_TIMEWAIT) ||
2369 	    (inp->inp_flags & INP_DROPPED))
2370 		return;
2371 
2372 	tp = intotcpcb(inp);
2373 	KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
2374 
2375 	tcp_mss_update(tp, -1, mtuoffer, NULL, NULL);
2376 
2377 	so = inp->inp_socket;
2378 	SOCKBUF_LOCK(&so->so_snd);
2379 	/* If the mss is larger than the socket buffer, decrease the mss. */
2380 	if (so->so_snd.sb_hiwat < tp->t_maxseg)
2381 		tp->t_maxseg = so->so_snd.sb_hiwat;
2382 	SOCKBUF_UNLOCK(&so->so_snd);
2383 
2384 	TCPSTAT_INC(tcps_mturesent);
2385 	tp->t_rtttime = 0;
2386 	tp->snd_nxt = tp->snd_una;
2387 	tcp_free_sackholes(tp);
2388 	tp->snd_recover = tp->snd_max;
2389 	if (tp->t_flags & TF_SACK_PERMIT)
2390 		EXIT_FASTRECOVERY(tp->t_flags);
2391 	tp->t_fb->tfb_tcp_output(tp);
2392 }
2393 
2394 #ifdef INET
2395 /*
2396  * Look-up the routing entry to the peer of this inpcb.  If no route
2397  * is found and it cannot be allocated, then return 0.  This routine
2398  * is called by TCP routines that access the rmx structure and by
2399  * tcp_mss_update to get the peer/interface MTU.
2400  */
2401 uint32_t
2402 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap)
2403 {
2404 	struct nhop4_extended nh4;
2405 	struct ifnet *ifp;
2406 	uint32_t maxmtu = 0;
2407 
2408 	KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
2409 
2410 	if (inc->inc_faddr.s_addr != INADDR_ANY) {
2411 
2412 		if (fib4_lookup_nh_ext(inc->inc_fibnum, inc->inc_faddr,
2413 		    NHR_REF, 0, &nh4) != 0)
2414 			return (0);
2415 
2416 		ifp = nh4.nh_ifp;
2417 		maxmtu = nh4.nh_mtu;
2418 
2419 		/* Report additional interface capabilities. */
2420 		if (cap != NULL) {
2421 			if (ifp->if_capenable & IFCAP_TSO4 &&
2422 			    ifp->if_hwassist & CSUM_TSO) {
2423 				cap->ifcap |= CSUM_TSO;
2424 				cap->tsomax = ifp->if_hw_tsomax;
2425 				cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
2426 				cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
2427 			}
2428 		}
2429 		fib4_free_nh_ext(inc->inc_fibnum, &nh4);
2430 	}
2431 	return (maxmtu);
2432 }
2433 #endif /* INET */
2434 
2435 #ifdef INET6
2436 uint32_t
2437 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap)
2438 {
2439 	struct nhop6_extended nh6;
2440 	struct in6_addr dst6;
2441 	uint32_t scopeid;
2442 	struct ifnet *ifp;
2443 	uint32_t maxmtu = 0;
2444 
2445 	KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
2446 
2447 	if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
2448 		in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid);
2449 		if (fib6_lookup_nh_ext(inc->inc_fibnum, &dst6, scopeid, 0,
2450 		    0, &nh6) != 0)
2451 			return (0);
2452 
2453 		ifp = nh6.nh_ifp;
2454 		maxmtu = nh6.nh_mtu;
2455 
2456 		/* Report additional interface capabilities. */
2457 		if (cap != NULL) {
2458 			if (ifp->if_capenable & IFCAP_TSO6 &&
2459 			    ifp->if_hwassist & CSUM_TSO) {
2460 				cap->ifcap |= CSUM_TSO;
2461 				cap->tsomax = ifp->if_hw_tsomax;
2462 				cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
2463 				cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
2464 			}
2465 		}
2466 		fib6_free_nh_ext(inc->inc_fibnum, &nh6);
2467 	}
2468 
2469 	return (maxmtu);
2470 }
2471 #endif /* INET6 */
2472 
2473 /*
2474  * Calculate effective SMSS per RFC5681 definition for a given TCP
2475  * connection at its current state, taking into account SACK and etc.
2476  */
2477 u_int
2478 tcp_maxseg(const struct tcpcb *tp)
2479 {
2480 	u_int optlen;
2481 
2482 	if (tp->t_flags & TF_NOOPT)
2483 		return (tp->t_maxseg);
2484 
2485 	/*
2486 	 * Here we have a simplified code from tcp_addoptions(),
2487 	 * without a proper loop, and having most of paddings hardcoded.
2488 	 * We might make mistakes with padding here in some edge cases,
2489 	 * but this is harmless, since result of tcp_maxseg() is used
2490 	 * only in cwnd and ssthresh estimations.
2491 	 */
2492 #define	PAD(len)	((((len) / 4) + !!((len) % 4)) * 4)
2493 	if (TCPS_HAVEESTABLISHED(tp->t_state)) {
2494 		if (tp->t_flags & TF_RCVD_TSTMP)
2495 			optlen = TCPOLEN_TSTAMP_APPA;
2496 		else
2497 			optlen = 0;
2498 #ifdef TCP_SIGNATURE
2499 		if (tp->t_flags & TF_SIGNATURE)
2500 			optlen += PAD(TCPOLEN_SIGNATURE);
2501 #endif
2502 		if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) {
2503 			optlen += TCPOLEN_SACKHDR;
2504 			optlen += tp->rcv_numsacks * TCPOLEN_SACK;
2505 			optlen = PAD(optlen);
2506 		}
2507 	} else {
2508 		if (tp->t_flags & TF_REQ_TSTMP)
2509 			optlen = TCPOLEN_TSTAMP_APPA;
2510 		else
2511 			optlen = PAD(TCPOLEN_MAXSEG);
2512 		if (tp->t_flags & TF_REQ_SCALE)
2513 			optlen += PAD(TCPOLEN_WINDOW);
2514 #ifdef TCP_SIGNATURE
2515 		if (tp->t_flags & TF_SIGNATURE)
2516 			optlen += PAD(TCPOLEN_SIGNATURE);
2517 #endif
2518 		if (tp->t_flags & TF_SACK_PERMIT)
2519 			optlen += PAD(TCPOLEN_SACK_PERMITTED);
2520 	}
2521 #undef PAD
2522 	optlen = min(optlen, TCP_MAXOLEN);
2523 	return (tp->t_maxseg - optlen);
2524 }
2525 
2526 #ifdef IPSEC
2527 /* compute ESP/AH header size for TCP, including outer IP header. */
2528 size_t
2529 ipsec_hdrsiz_tcp(struct tcpcb *tp)
2530 {
2531 	struct inpcb *inp;
2532 	struct mbuf *m;
2533 	size_t hdrsiz;
2534 	struct ip *ip;
2535 #ifdef INET6
2536 	struct ip6_hdr *ip6;
2537 #endif
2538 	struct tcphdr *th;
2539 
2540 	if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL) ||
2541 		(!key_havesp(IPSEC_DIR_OUTBOUND)))
2542 		return (0);
2543 	m = m_gethdr(M_NOWAIT, MT_DATA);
2544 	if (!m)
2545 		return (0);
2546 
2547 #ifdef INET6
2548 	if ((inp->inp_vflag & INP_IPV6) != 0) {
2549 		ip6 = mtod(m, struct ip6_hdr *);
2550 		th = (struct tcphdr *)(ip6 + 1);
2551 		m->m_pkthdr.len = m->m_len =
2552 			sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
2553 		tcpip_fillheaders(inp, ip6, th);
2554 		hdrsiz = ipsec_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
2555 	} else
2556 #endif /* INET6 */
2557 	{
2558 		ip = mtod(m, struct ip *);
2559 		th = (struct tcphdr *)(ip + 1);
2560 		m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
2561 		tcpip_fillheaders(inp, ip, th);
2562 		hdrsiz = ipsec_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
2563 	}
2564 
2565 	m_free(m);
2566 	return (hdrsiz);
2567 }
2568 #endif /* IPSEC */
2569 
2570 #ifdef TCP_SIGNATURE
2571 /*
2572  * Callback function invoked by m_apply() to digest TCP segment data
2573  * contained within an mbuf chain.
2574  */
2575 static int
2576 tcp_signature_apply(void *fstate, void *data, u_int len)
2577 {
2578 
2579 	MD5Update(fstate, (u_char *)data, len);
2580 	return (0);
2581 }
2582 
2583 /*
2584  * XXX The key is retrieved from the system's PF_KEY SADB, by keying a
2585  * search with the destination IP address, and a 'magic SPI' to be
2586  * determined by the application. This is hardcoded elsewhere to 1179
2587 */
2588 struct secasvar *
2589 tcp_get_sav(struct mbuf *m, u_int direction)
2590 {
2591 	union sockaddr_union dst;
2592 	struct secasvar *sav;
2593 	struct ip *ip;
2594 #ifdef INET6
2595 	struct ip6_hdr *ip6;
2596 	char ip6buf[INET6_ADDRSTRLEN];
2597 #endif
2598 
2599 	/* Extract the destination from the IP header in the mbuf. */
2600 	bzero(&dst, sizeof(union sockaddr_union));
2601 	ip = mtod(m, struct ip *);
2602 #ifdef INET6
2603 	ip6 = NULL;	/* Make the compiler happy. */
2604 #endif
2605 	switch (ip->ip_v) {
2606 #ifdef INET
2607 	case IPVERSION:
2608 		dst.sa.sa_len = sizeof(struct sockaddr_in);
2609 		dst.sa.sa_family = AF_INET;
2610 		dst.sin.sin_addr = (direction == IPSEC_DIR_INBOUND) ?
2611 		    ip->ip_src : ip->ip_dst;
2612 		break;
2613 #endif
2614 #ifdef INET6
2615 	case (IPV6_VERSION >> 4):
2616 		ip6 = mtod(m, struct ip6_hdr *);
2617 		dst.sa.sa_len = sizeof(struct sockaddr_in6);
2618 		dst.sa.sa_family = AF_INET6;
2619 		dst.sin6.sin6_addr = (direction == IPSEC_DIR_INBOUND) ?
2620 		    ip6->ip6_src : ip6->ip6_dst;
2621 		break;
2622 #endif
2623 	default:
2624 		return (NULL);
2625 		/* NOTREACHED */
2626 		break;
2627 	}
2628 
2629 	/* Look up an SADB entry which matches the address of the peer. */
2630 	sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
2631 	if (sav == NULL) {
2632 		ipseclog((LOG_ERR, "%s: SADB lookup failed for %s\n", __func__,
2633 		    (ip->ip_v == IPVERSION) ? inet_ntoa(dst.sin.sin_addr) :
2634 #ifdef INET6
2635 			(ip->ip_v == (IPV6_VERSION >> 4)) ?
2636 			    ip6_sprintf(ip6buf, &dst.sin6.sin6_addr) :
2637 #endif
2638 			"(unsupported)"));
2639 	}
2640 
2641 	return (sav);
2642 }
2643 
2644 /*
2645  * Compute TCP-MD5 hash of a TCP segment. (RFC2385)
2646  *
2647  * Parameters:
2648  * m		pointer to head of mbuf chain
2649  * len		length of TCP segment data, excluding options
2650  * optlen	length of TCP segment options
2651  * buf		pointer to storage for computed MD5 digest
2652  * sav		pointer to security assosiation
2653  *
2654  * We do this over ip, tcphdr, segment data, and the key in the SADB.
2655  * When called from tcp_input(), we can be sure that th_sum has been
2656  * zeroed out and verified already.
2657  *
2658  * Releases reference to SADB key before return.
2659  *
2660  * Return 0 if successful, otherwise return -1.
2661  *
2662  */
2663 int
2664 tcp_signature_do_compute(struct mbuf *m, int len, int optlen,
2665     u_char *buf, struct secasvar *sav)
2666 {
2667 #ifdef INET
2668 	struct ippseudo ippseudo;
2669 #endif
2670 	MD5_CTX ctx;
2671 	int doff;
2672 	struct ip *ip;
2673 #ifdef INET
2674 	struct ipovly *ipovly;
2675 #endif
2676 	struct tcphdr *th;
2677 #ifdef INET6
2678 	struct ip6_hdr *ip6;
2679 	struct in6_addr in6;
2680 	uint32_t plen;
2681 	uint16_t nhdr;
2682 #endif
2683 	u_short savecsum;
2684 
2685 	KASSERT(m != NULL, ("NULL mbuf chain"));
2686 	KASSERT(buf != NULL, ("NULL signature pointer"));
2687 
2688 	/* Extract the destination from the IP header in the mbuf. */
2689 	ip = mtod(m, struct ip *);
2690 #ifdef INET6
2691 	ip6 = NULL;	/* Make the compiler happy. */
2692 #endif
2693 
2694 	MD5Init(&ctx);
2695 	/*
2696 	 * Step 1: Update MD5 hash with IP(v6) pseudo-header.
2697 	 *
2698 	 * XXX The ippseudo header MUST be digested in network byte order,
2699 	 * or else we'll fail the regression test. Assume all fields we've
2700 	 * been doing arithmetic on have been in host byte order.
2701 	 * XXX One cannot depend on ipovly->ih_len here. When called from
2702 	 * tcp_output(), the underlying ip_len member has not yet been set.
2703 	 */
2704 	switch (ip->ip_v) {
2705 #ifdef INET
2706 	case IPVERSION:
2707 		ipovly = (struct ipovly *)ip;
2708 		ippseudo.ippseudo_src = ipovly->ih_src;
2709 		ippseudo.ippseudo_dst = ipovly->ih_dst;
2710 		ippseudo.ippseudo_pad = 0;
2711 		ippseudo.ippseudo_p = IPPROTO_TCP;
2712 		ippseudo.ippseudo_len = htons(len + sizeof(struct tcphdr) +
2713 		    optlen);
2714 		MD5Update(&ctx, (char *)&ippseudo, sizeof(struct ippseudo));
2715 
2716 		th = (struct tcphdr *)((u_char *)ip + sizeof(struct ip));
2717 		doff = sizeof(struct ip) + sizeof(struct tcphdr) + optlen;
2718 		break;
2719 #endif
2720 #ifdef INET6
2721 	/*
2722 	 * RFC 2385, 2.0  Proposal
2723 	 * For IPv6, the pseudo-header is as described in RFC 2460, namely the
2724 	 * 128-bit source IPv6 address, 128-bit destination IPv6 address, zero-
2725 	 * extended next header value (to form 32 bits), and 32-bit segment
2726 	 * length.
2727 	 * Note: Upper-Layer Packet Length comes before Next Header.
2728 	 */
2729 	case (IPV6_VERSION >> 4):
2730 		in6 = ip6->ip6_src;
2731 		in6_clearscope(&in6);
2732 		MD5Update(&ctx, (char *)&in6, sizeof(struct in6_addr));
2733 		in6 = ip6->ip6_dst;
2734 		in6_clearscope(&in6);
2735 		MD5Update(&ctx, (char *)&in6, sizeof(struct in6_addr));
2736 		plen = htonl(len + sizeof(struct tcphdr) + optlen);
2737 		MD5Update(&ctx, (char *)&plen, sizeof(uint32_t));
2738 		nhdr = 0;
2739 		MD5Update(&ctx, (char *)&nhdr, sizeof(uint8_t));
2740 		MD5Update(&ctx, (char *)&nhdr, sizeof(uint8_t));
2741 		MD5Update(&ctx, (char *)&nhdr, sizeof(uint8_t));
2742 		nhdr = IPPROTO_TCP;
2743 		MD5Update(&ctx, (char *)&nhdr, sizeof(uint8_t));
2744 
2745 		th = (struct tcphdr *)((u_char *)ip6 + sizeof(struct ip6_hdr));
2746 		doff = sizeof(struct ip6_hdr) + sizeof(struct tcphdr) + optlen;
2747 		break;
2748 #endif
2749 	default:
2750 		KEY_FREESAV(&sav);
2751 		return (-1);
2752 		/* NOTREACHED */
2753 		break;
2754 	}
2755 
2756 
2757 	/*
2758 	 * Step 2: Update MD5 hash with TCP header, excluding options.
2759 	 * The TCP checksum must be set to zero.
2760 	 */
2761 	savecsum = th->th_sum;
2762 	th->th_sum = 0;
2763 	MD5Update(&ctx, (char *)th, sizeof(struct tcphdr));
2764 	th->th_sum = savecsum;
2765 
2766 	/*
2767 	 * Step 3: Update MD5 hash with TCP segment data.
2768 	 *         Use m_apply() to avoid an early m_pullup().
2769 	 */
2770 	if (len > 0)
2771 		m_apply(m, doff, len, tcp_signature_apply, &ctx);
2772 
2773 	/*
2774 	 * Step 4: Update MD5 hash with shared secret.
2775 	 */
2776 	MD5Update(&ctx, sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2777 	MD5Final(buf, &ctx);
2778 
2779 	key_sa_recordxfer(sav, m);
2780 	KEY_FREESAV(&sav);
2781 	return (0);
2782 }
2783 
2784 /*
2785  * Compute TCP-MD5 hash of a TCP segment. (RFC2385)
2786  *
2787  * Return 0 if successful, otherwise return -1.
2788  */
2789 int
2790 tcp_signature_compute(struct mbuf *m, int _unused, int len, int optlen,
2791     u_char *buf, u_int direction)
2792 {
2793 	struct secasvar *sav;
2794 
2795 	if ((sav = tcp_get_sav(m, direction)) == NULL)
2796 		return (-1);
2797 
2798 	return (tcp_signature_do_compute(m, len, optlen, buf, sav));
2799 }
2800 
2801 /*
2802  * Verify the TCP-MD5 hash of a TCP segment. (RFC2385)
2803  *
2804  * Parameters:
2805  * m		pointer to head of mbuf chain
2806  * len		length of TCP segment data, excluding options
2807  * optlen	length of TCP segment options
2808  * buf		pointer to storage for computed MD5 digest
2809  * direction	direction of flow (IPSEC_DIR_INBOUND or OUTBOUND)
2810  *
2811  * Return 1 if successful, otherwise return 0.
2812  */
2813 int
2814 tcp_signature_verify(struct mbuf *m, int off0, int tlen, int optlen,
2815     struct tcpopt *to, struct tcphdr *th, u_int tcpbflag)
2816 {
2817 	char tmpdigest[TCP_SIGLEN];
2818 
2819 	if (tcp_sig_checksigs == 0)
2820 		return (1);
2821 	if ((tcpbflag & TF_SIGNATURE) == 0) {
2822 		if ((to->to_flags & TOF_SIGNATURE) != 0) {
2823 
2824 			/*
2825 			 * If this socket is not expecting signature but
2826 			 * the segment contains signature just fail.
2827 			 */
2828 			TCPSTAT_INC(tcps_sig_err_sigopt);
2829 			TCPSTAT_INC(tcps_sig_rcvbadsig);
2830 			return (0);
2831 		}
2832 
2833 		/* Signature is not expected, and not present in segment. */
2834 		return (1);
2835 	}
2836 
2837 	/*
2838 	 * If this socket is expecting signature but the segment does not
2839 	 * contain any just fail.
2840 	 */
2841 	if ((to->to_flags & TOF_SIGNATURE) == 0) {
2842 		TCPSTAT_INC(tcps_sig_err_nosigopt);
2843 		TCPSTAT_INC(tcps_sig_rcvbadsig);
2844 		return (0);
2845 	}
2846 	if (tcp_signature_compute(m, off0, tlen, optlen, &tmpdigest[0],
2847 	    IPSEC_DIR_INBOUND) == -1) {
2848 		TCPSTAT_INC(tcps_sig_err_buildsig);
2849 		TCPSTAT_INC(tcps_sig_rcvbadsig);
2850 		return (0);
2851 	}
2852 
2853 	if (bcmp(to->to_signature, &tmpdigest[0], TCP_SIGLEN) != 0) {
2854 		TCPSTAT_INC(tcps_sig_rcvbadsig);
2855 		return (0);
2856 	}
2857 	TCPSTAT_INC(tcps_sig_rcvgoodsig);
2858 	return (1);
2859 }
2860 #endif /* TCP_SIGNATURE */
2861 
2862 static int
2863 sysctl_drop(SYSCTL_HANDLER_ARGS)
2864 {
2865 	/* addrs[0] is a foreign socket, addrs[1] is a local one. */
2866 	struct sockaddr_storage addrs[2];
2867 	struct inpcb *inp;
2868 	struct tcpcb *tp;
2869 	struct tcptw *tw;
2870 	struct sockaddr_in *fin, *lin;
2871 #ifdef INET6
2872 	struct sockaddr_in6 *fin6, *lin6;
2873 #endif
2874 	int error;
2875 
2876 	inp = NULL;
2877 	fin = lin = NULL;
2878 #ifdef INET6
2879 	fin6 = lin6 = NULL;
2880 #endif
2881 	error = 0;
2882 
2883 	if (req->oldptr != NULL || req->oldlen != 0)
2884 		return (EINVAL);
2885 	if (req->newptr == NULL)
2886 		return (EPERM);
2887 	if (req->newlen < sizeof(addrs))
2888 		return (ENOMEM);
2889 	error = SYSCTL_IN(req, &addrs, sizeof(addrs));
2890 	if (error)
2891 		return (error);
2892 
2893 	switch (addrs[0].ss_family) {
2894 #ifdef INET6
2895 	case AF_INET6:
2896 		fin6 = (struct sockaddr_in6 *)&addrs[0];
2897 		lin6 = (struct sockaddr_in6 *)&addrs[1];
2898 		if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
2899 		    lin6->sin6_len != sizeof(struct sockaddr_in6))
2900 			return (EINVAL);
2901 		if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
2902 			if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
2903 				return (EINVAL);
2904 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
2905 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
2906 			fin = (struct sockaddr_in *)&addrs[0];
2907 			lin = (struct sockaddr_in *)&addrs[1];
2908 			break;
2909 		}
2910 		error = sa6_embedscope(fin6, V_ip6_use_defzone);
2911 		if (error)
2912 			return (error);
2913 		error = sa6_embedscope(lin6, V_ip6_use_defzone);
2914 		if (error)
2915 			return (error);
2916 		break;
2917 #endif
2918 #ifdef INET
2919 	case AF_INET:
2920 		fin = (struct sockaddr_in *)&addrs[0];
2921 		lin = (struct sockaddr_in *)&addrs[1];
2922 		if (fin->sin_len != sizeof(struct sockaddr_in) ||
2923 		    lin->sin_len != sizeof(struct sockaddr_in))
2924 			return (EINVAL);
2925 		break;
2926 #endif
2927 	default:
2928 		return (EINVAL);
2929 	}
2930 	INP_INFO_RLOCK(&V_tcbinfo);
2931 	switch (addrs[0].ss_family) {
2932 #ifdef INET6
2933 	case AF_INET6:
2934 		inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
2935 		    fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
2936 		    INPLOOKUP_WLOCKPCB, NULL);
2937 		break;
2938 #endif
2939 #ifdef INET
2940 	case AF_INET:
2941 		inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
2942 		    lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
2943 		break;
2944 #endif
2945 	}
2946 	if (inp != NULL) {
2947 		if (inp->inp_flags & INP_TIMEWAIT) {
2948 			/*
2949 			 * XXXRW: There currently exists a state where an
2950 			 * inpcb is present, but its timewait state has been
2951 			 * discarded.  For now, don't allow dropping of this
2952 			 * type of inpcb.
2953 			 */
2954 			tw = intotw(inp);
2955 			if (tw != NULL)
2956 				tcp_twclose(tw, 0);
2957 			else
2958 				INP_WUNLOCK(inp);
2959 		} else if (!(inp->inp_flags & INP_DROPPED) &&
2960 			   !(inp->inp_socket->so_options & SO_ACCEPTCONN)) {
2961 			tp = intotcpcb(inp);
2962 			tp = tcp_drop(tp, ECONNABORTED);
2963 			if (tp != NULL)
2964 				INP_WUNLOCK(inp);
2965 		} else
2966 			INP_WUNLOCK(inp);
2967 	} else
2968 		error = ESRCH;
2969 	INP_INFO_RUNLOCK(&V_tcbinfo);
2970 	return (error);
2971 }
2972 
2973 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
2974     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP, NULL,
2975     0, sysctl_drop, "", "Drop TCP connection");
2976 
2977 /*
2978  * Generate a standardized TCP log line for use throughout the
2979  * tcp subsystem.  Memory allocation is done with M_NOWAIT to
2980  * allow use in the interrupt context.
2981  *
2982  * NB: The caller MUST free(s, M_TCPLOG) the returned string.
2983  * NB: The function may return NULL if memory allocation failed.
2984  *
2985  * Due to header inclusion and ordering limitations the struct ip
2986  * and ip6_hdr pointers have to be passed as void pointers.
2987  */
2988 char *
2989 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
2990     const void *ip6hdr)
2991 {
2992 
2993 	/* Is logging enabled? */
2994 	if (tcp_log_in_vain == 0)
2995 		return (NULL);
2996 
2997 	return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
2998 }
2999 
3000 char *
3001 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
3002     const void *ip6hdr)
3003 {
3004 
3005 	/* Is logging enabled? */
3006 	if (tcp_log_debug == 0)
3007 		return (NULL);
3008 
3009 	return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3010 }
3011 
3012 static char *
3013 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
3014     const void *ip6hdr)
3015 {
3016 	char *s, *sp;
3017 	size_t size;
3018 	struct ip *ip;
3019 #ifdef INET6
3020 	const struct ip6_hdr *ip6;
3021 
3022 	ip6 = (const struct ip6_hdr *)ip6hdr;
3023 #endif /* INET6 */
3024 	ip = (struct ip *)ip4hdr;
3025 
3026 	/*
3027 	 * The log line looks like this:
3028 	 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>"
3029 	 */
3030 	size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") +
3031 	    sizeof(PRINT_TH_FLAGS) + 1 +
3032 #ifdef INET6
3033 	    2 * INET6_ADDRSTRLEN;
3034 #else
3035 	    2 * INET_ADDRSTRLEN;
3036 #endif /* INET6 */
3037 
3038 	s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT);
3039 	if (s == NULL)
3040 		return (NULL);
3041 
3042 	strcat(s, "TCP: [");
3043 	sp = s + strlen(s);
3044 
3045 	if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) {
3046 		inet_ntoa_r(inc->inc_faddr, sp);
3047 		sp = s + strlen(s);
3048 		sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3049 		sp = s + strlen(s);
3050 		inet_ntoa_r(inc->inc_laddr, sp);
3051 		sp = s + strlen(s);
3052 		sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3053 #ifdef INET6
3054 	} else if (inc) {
3055 		ip6_sprintf(sp, &inc->inc6_faddr);
3056 		sp = s + strlen(s);
3057 		sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3058 		sp = s + strlen(s);
3059 		ip6_sprintf(sp, &inc->inc6_laddr);
3060 		sp = s + strlen(s);
3061 		sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3062 	} else if (ip6 && th) {
3063 		ip6_sprintf(sp, &ip6->ip6_src);
3064 		sp = s + strlen(s);
3065 		sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3066 		sp = s + strlen(s);
3067 		ip6_sprintf(sp, &ip6->ip6_dst);
3068 		sp = s + strlen(s);
3069 		sprintf(sp, "]:%i", ntohs(th->th_dport));
3070 #endif /* INET6 */
3071 #ifdef INET
3072 	} else if (ip && th) {
3073 		inet_ntoa_r(ip->ip_src, sp);
3074 		sp = s + strlen(s);
3075 		sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3076 		sp = s + strlen(s);
3077 		inet_ntoa_r(ip->ip_dst, sp);
3078 		sp = s + strlen(s);
3079 		sprintf(sp, "]:%i", ntohs(th->th_dport));
3080 #endif /* INET */
3081 	} else {
3082 		free(s, M_TCPLOG);
3083 		return (NULL);
3084 	}
3085 	sp = s + strlen(s);
3086 	if (th)
3087 		sprintf(sp, " tcpflags 0x%b", th->th_flags, PRINT_TH_FLAGS);
3088 	if (*(s + size - 1) != '\0')
3089 		panic("%s: string too long", __func__);
3090 	return (s);
3091 }
3092 
3093 /*
3094  * A subroutine which makes it easy to track TCP state changes with DTrace.
3095  * This function shouldn't be called for t_state initializations that don't
3096  * correspond to actual TCP state transitions.
3097  */
3098 void
3099 tcp_state_change(struct tcpcb *tp, int newstate)
3100 {
3101 #if defined(KDTRACE_HOOKS)
3102 	int pstate = tp->t_state;
3103 #endif
3104 
3105 	TCPSTATES_DEC(tp->t_state);
3106 	TCPSTATES_INC(newstate);
3107 	tp->t_state = newstate;
3108 	TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate);
3109 }
3110