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