xref: /netbsd-src/sys/netinet/tcp_subr.c (revision a5847cc334d9a7029f6352b847e9e8d71a0f9e0c)
1 /*	$NetBSD: tcp_subr.c,v 1.242 2011/10/31 12:56:45 yamt Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*-
33  * Copyright (c) 1997, 1998, 2000, 2001, 2008 The NetBSD Foundation, Inc.
34  * All rights reserved.
35  *
36  * This code is derived from software contributed to The NetBSD Foundation
37  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
38  * Facility, NASA Ames Research Center.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
50  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
51  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
52  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
53  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
54  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
55  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
56  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
57  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
58  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
59  * POSSIBILITY OF SUCH DAMAGE.
60  */
61 
62 /*
63  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
64  *	The Regents of the University of California.  All rights reserved.
65  *
66  * Redistribution and use in source and binary forms, with or without
67  * modification, are permitted provided that the following conditions
68  * are met:
69  * 1. Redistributions of source code must retain the above copyright
70  *    notice, this list of conditions and the following disclaimer.
71  * 2. Redistributions in binary form must reproduce the above copyright
72  *    notice, this list of conditions and the following disclaimer in the
73  *    documentation and/or other materials provided with the distribution.
74  * 3. Neither the name of the University nor the names of its contributors
75  *    may be used to endorse or promote products derived from this software
76  *    without specific prior written permission.
77  *
78  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
79  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
82  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
83  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
84  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
85  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
86  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
87  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
88  * SUCH DAMAGE.
89  *
90  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
91  */
92 
93 #include <sys/cdefs.h>
94 __KERNEL_RCSID(0, "$NetBSD: tcp_subr.c,v 1.242 2011/10/31 12:56:45 yamt Exp $");
95 
96 #include "opt_inet.h"
97 #include "opt_ipsec.h"
98 #include "opt_tcp_compat_42.h"
99 #include "opt_inet_csum.h"
100 #include "opt_mbuftrace.h"
101 #include "rnd.h"
102 
103 #include <sys/param.h>
104 #include <sys/proc.h>
105 #include <sys/systm.h>
106 #include <sys/malloc.h>
107 #include <sys/mbuf.h>
108 #include <sys/socket.h>
109 #include <sys/socketvar.h>
110 #include <sys/protosw.h>
111 #include <sys/errno.h>
112 #include <sys/kernel.h>
113 #include <sys/pool.h>
114 #if NRND > 0
115 #include <sys/md5.h>
116 #include <sys/rnd.h>
117 #endif
118 
119 #include <net/route.h>
120 #include <net/if.h>
121 
122 #include <netinet/in.h>
123 #include <netinet/in_systm.h>
124 #include <netinet/ip.h>
125 #include <netinet/in_pcb.h>
126 #include <netinet/ip_var.h>
127 #include <netinet/ip_icmp.h>
128 
129 #ifdef INET6
130 #ifndef INET
131 #include <netinet/in.h>
132 #endif
133 #include <netinet/ip6.h>
134 #include <netinet6/in6_pcb.h>
135 #include <netinet6/ip6_var.h>
136 #include <netinet6/in6_var.h>
137 #include <netinet6/ip6protosw.h>
138 #include <netinet/icmp6.h>
139 #include <netinet6/nd6.h>
140 #endif
141 
142 #include <netinet/tcp.h>
143 #include <netinet/tcp_fsm.h>
144 #include <netinet/tcp_seq.h>
145 #include <netinet/tcp_timer.h>
146 #include <netinet/tcp_var.h>
147 #include <netinet/tcp_vtw.h>
148 #include <netinet/tcp_private.h>
149 #include <netinet/tcp_congctl.h>
150 #include <netinet/tcpip.h>
151 
152 #ifdef IPSEC
153 #include <netinet6/ipsec.h>
154 #include <netkey/key.h>
155 #endif /*IPSEC*/
156 
157 #ifdef FAST_IPSEC
158 #include <netipsec/ipsec.h>
159 #include <netipsec/xform.h>
160 #ifdef INET6
161 #include <netipsec/ipsec6.h>
162 #endif
163  #include <netipsec/key.h>
164 #endif	/* FAST_IPSEC*/
165 
166 
167 struct	inpcbtable tcbtable;	/* head of queue of active tcpcb's */
168 u_int32_t tcp_now;		/* slow ticks, for RFC 1323 timestamps */
169 
170 percpu_t *tcpstat_percpu;
171 
172 /* patchable/settable parameters for tcp */
173 int 	tcp_mssdflt = TCP_MSS;
174 int	tcp_minmss = TCP_MINMSS;
175 int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
176 int	tcp_do_rfc1323 = 1;	/* window scaling / timestamps (obsolete) */
177 #if NRND > 0
178 int	tcp_do_rfc1948 = 0;	/* ISS by cryptographic hash */
179 #endif
180 int	tcp_do_sack = 1;	/* selective acknowledgement */
181 int	tcp_do_win_scale = 1;	/* RFC1323 window scaling */
182 int	tcp_do_timestamps = 1;	/* RFC1323 timestamps */
183 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
184 int	tcp_do_ecn = 0;		/* Explicit Congestion Notification */
185 #ifndef TCP_INIT_WIN
186 #define	TCP_INIT_WIN	0	/* initial slow start window */
187 #endif
188 #ifndef TCP_INIT_WIN_LOCAL
189 #define	TCP_INIT_WIN_LOCAL 4	/* initial slow start window for local nets */
190 #endif
191 int	tcp_init_win = TCP_INIT_WIN;
192 int	tcp_init_win_local = TCP_INIT_WIN_LOCAL;
193 int	tcp_mss_ifmtu = 0;
194 #ifdef TCP_COMPAT_42
195 int	tcp_compat_42 = 1;
196 #else
197 int	tcp_compat_42 = 0;
198 #endif
199 int	tcp_rst_ppslim = 100;	/* 100pps */
200 int	tcp_ackdrop_ppslim = 100;	/* 100pps */
201 int	tcp_do_loopback_cksum = 0;
202 int	tcp_do_abc = 1;		/* RFC3465 Appropriate byte counting. */
203 int	tcp_abc_aggressive = 1;	/* 1: L=2*SMSS  0: L=1*SMSS */
204 int	tcp_sack_tp_maxholes = 32;
205 int	tcp_sack_globalmaxholes = 1024;
206 int	tcp_sack_globalholes = 0;
207 int	tcp_ecn_maxretries = 1;
208 int	tcp_msl_enable = 1;		/* enable TIME_WAIT truncation	*/
209 int	tcp_msl_loop   = PR_SLOWHZ;	/* MSL for loopback		*/
210 int	tcp_msl_local  = 5 * PR_SLOWHZ;	/* MSL for 'local'		*/
211 int	tcp_msl_remote = TCPTV_MSL;	/* MSL otherwise		*/
212 int	tcp_msl_remote_threshold = TCPTV_SRTTDFLT;	/* RTT threshold */
213 int	tcp_rttlocal = 0;		/* Use RTT to decide who's 'local' */
214 
215 int	tcp4_vtw_enable = 0;		/* 1 to enable */
216 int	tcp6_vtw_enable = 0;		/* 1 to enable */
217 int	tcp_vtw_was_enabled = 0;
218 int	tcp_vtw_entries = 1 << 16;	/* 64K vestigial TIME_WAIT entries */
219 
220 /* tcb hash */
221 #ifndef TCBHASHSIZE
222 #define	TCBHASHSIZE	128
223 #endif
224 int	tcbhashsize = TCBHASHSIZE;
225 
226 /* syn hash parameters */
227 #define	TCP_SYN_HASH_SIZE	293
228 #define	TCP_SYN_BUCKET_SIZE	35
229 int	tcp_syn_cache_size = TCP_SYN_HASH_SIZE;
230 int	tcp_syn_cache_limit = TCP_SYN_HASH_SIZE*TCP_SYN_BUCKET_SIZE;
231 int	tcp_syn_bucket_limit = 3*TCP_SYN_BUCKET_SIZE;
232 struct	syn_cache_head tcp_syn_cache[TCP_SYN_HASH_SIZE];
233 
234 int	tcp_freeq(struct tcpcb *);
235 
236 #ifdef INET
237 void	tcp_mtudisc_callback(struct in_addr);
238 #endif
239 #ifdef INET6
240 void	tcp6_mtudisc_callback(struct in6_addr *);
241 #endif
242 
243 #ifdef INET6
244 void	tcp6_mtudisc(struct in6pcb *, int);
245 #endif
246 
247 static struct pool tcpcb_pool;
248 
249 static int tcp_drainwanted;
250 
251 #ifdef TCP_CSUM_COUNTERS
252 #include <sys/device.h>
253 
254 #if defined(INET)
255 struct evcnt tcp_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
256     NULL, "tcp", "hwcsum bad");
257 struct evcnt tcp_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
258     NULL, "tcp", "hwcsum ok");
259 struct evcnt tcp_hwcsum_data = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
260     NULL, "tcp", "hwcsum data");
261 struct evcnt tcp_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
262     NULL, "tcp", "swcsum");
263 
264 EVCNT_ATTACH_STATIC(tcp_hwcsum_bad);
265 EVCNT_ATTACH_STATIC(tcp_hwcsum_ok);
266 EVCNT_ATTACH_STATIC(tcp_hwcsum_data);
267 EVCNT_ATTACH_STATIC(tcp_swcsum);
268 #endif /* defined(INET) */
269 
270 #if defined(INET6)
271 struct evcnt tcp6_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
272     NULL, "tcp6", "hwcsum bad");
273 struct evcnt tcp6_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
274     NULL, "tcp6", "hwcsum ok");
275 struct evcnt tcp6_hwcsum_data = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
276     NULL, "tcp6", "hwcsum data");
277 struct evcnt tcp6_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
278     NULL, "tcp6", "swcsum");
279 
280 EVCNT_ATTACH_STATIC(tcp6_hwcsum_bad);
281 EVCNT_ATTACH_STATIC(tcp6_hwcsum_ok);
282 EVCNT_ATTACH_STATIC(tcp6_hwcsum_data);
283 EVCNT_ATTACH_STATIC(tcp6_swcsum);
284 #endif /* defined(INET6) */
285 #endif /* TCP_CSUM_COUNTERS */
286 
287 
288 #ifdef TCP_OUTPUT_COUNTERS
289 #include <sys/device.h>
290 
291 struct evcnt tcp_output_bigheader = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
292     NULL, "tcp", "output big header");
293 struct evcnt tcp_output_predict_hit = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
294     NULL, "tcp", "output predict hit");
295 struct evcnt tcp_output_predict_miss = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
296     NULL, "tcp", "output predict miss");
297 struct evcnt tcp_output_copysmall = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
298     NULL, "tcp", "output copy small");
299 struct evcnt tcp_output_copybig = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
300     NULL, "tcp", "output copy big");
301 struct evcnt tcp_output_refbig = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
302     NULL, "tcp", "output reference big");
303 
304 EVCNT_ATTACH_STATIC(tcp_output_bigheader);
305 EVCNT_ATTACH_STATIC(tcp_output_predict_hit);
306 EVCNT_ATTACH_STATIC(tcp_output_predict_miss);
307 EVCNT_ATTACH_STATIC(tcp_output_copysmall);
308 EVCNT_ATTACH_STATIC(tcp_output_copybig);
309 EVCNT_ATTACH_STATIC(tcp_output_refbig);
310 
311 #endif /* TCP_OUTPUT_COUNTERS */
312 
313 #ifdef TCP_REASS_COUNTERS
314 #include <sys/device.h>
315 
316 struct evcnt tcp_reass_ = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
317     NULL, "tcp_reass", "calls");
318 struct evcnt tcp_reass_empty = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
319     &tcp_reass_, "tcp_reass", "insert into empty queue");
320 struct evcnt tcp_reass_iteration[8] = {
321     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", ">7 iterations"),
322     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "1 iteration"),
323     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "2 iterations"),
324     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "3 iterations"),
325     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "4 iterations"),
326     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "5 iterations"),
327     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "6 iterations"),
328     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "7 iterations"),
329 };
330 struct evcnt tcp_reass_prependfirst = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
331     &tcp_reass_, "tcp_reass", "prepend to first");
332 struct evcnt tcp_reass_prepend = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
333     &tcp_reass_, "tcp_reass", "prepend");
334 struct evcnt tcp_reass_insert = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
335     &tcp_reass_, "tcp_reass", "insert");
336 struct evcnt tcp_reass_inserttail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
337     &tcp_reass_, "tcp_reass", "insert at tail");
338 struct evcnt tcp_reass_append = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
339     &tcp_reass_, "tcp_reass", "append");
340 struct evcnt tcp_reass_appendtail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
341     &tcp_reass_, "tcp_reass", "append to tail fragment");
342 struct evcnt tcp_reass_overlaptail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
343     &tcp_reass_, "tcp_reass", "overlap at end");
344 struct evcnt tcp_reass_overlapfront = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
345     &tcp_reass_, "tcp_reass", "overlap at start");
346 struct evcnt tcp_reass_segdup = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
347     &tcp_reass_, "tcp_reass", "duplicate segment");
348 struct evcnt tcp_reass_fragdup = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
349     &tcp_reass_, "tcp_reass", "duplicate fragment");
350 
351 EVCNT_ATTACH_STATIC(tcp_reass_);
352 EVCNT_ATTACH_STATIC(tcp_reass_empty);
353 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 0);
354 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 1);
355 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 2);
356 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 3);
357 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 4);
358 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 5);
359 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 6);
360 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 7);
361 EVCNT_ATTACH_STATIC(tcp_reass_prependfirst);
362 EVCNT_ATTACH_STATIC(tcp_reass_prepend);
363 EVCNT_ATTACH_STATIC(tcp_reass_insert);
364 EVCNT_ATTACH_STATIC(tcp_reass_inserttail);
365 EVCNT_ATTACH_STATIC(tcp_reass_append);
366 EVCNT_ATTACH_STATIC(tcp_reass_appendtail);
367 EVCNT_ATTACH_STATIC(tcp_reass_overlaptail);
368 EVCNT_ATTACH_STATIC(tcp_reass_overlapfront);
369 EVCNT_ATTACH_STATIC(tcp_reass_segdup);
370 EVCNT_ATTACH_STATIC(tcp_reass_fragdup);
371 
372 #endif /* TCP_REASS_COUNTERS */
373 
374 #ifdef MBUFTRACE
375 struct mowner tcp_mowner = MOWNER_INIT("tcp", "");
376 struct mowner tcp_rx_mowner = MOWNER_INIT("tcp", "rx");
377 struct mowner tcp_tx_mowner = MOWNER_INIT("tcp", "tx");
378 struct mowner tcp_sock_mowner = MOWNER_INIT("tcp", "sock");
379 struct mowner tcp_sock_rx_mowner = MOWNER_INIT("tcp", "sock rx");
380 struct mowner tcp_sock_tx_mowner = MOWNER_INIT("tcp", "sock tx");
381 #endif
382 
383 /*
384  * Tcp initialization
385  */
386 void
387 tcp_init(void)
388 {
389 	int hlen;
390 
391 	in_pcbinit(&tcbtable, tcbhashsize, tcbhashsize);
392 	pool_init(&tcpcb_pool, sizeof(struct tcpcb), 0, 0, 0, "tcpcbpl",
393 	    NULL, IPL_SOFTNET);
394 
395 	hlen = sizeof(struct ip) + sizeof(struct tcphdr);
396 #ifdef INET6
397 	if (sizeof(struct ip) < sizeof(struct ip6_hdr))
398 		hlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
399 #endif
400 	if (max_protohdr < hlen)
401 		max_protohdr = hlen;
402 	if (max_linkhdr + hlen > MHLEN)
403 		panic("tcp_init");
404 
405 #ifdef INET
406 	icmp_mtudisc_callback_register(tcp_mtudisc_callback);
407 #endif
408 #ifdef INET6
409 	icmp6_mtudisc_callback_register(tcp6_mtudisc_callback);
410 #endif
411 
412 	tcp_usrreq_init();
413 
414 	/* Initialize timer state. */
415 	tcp_timer_init();
416 
417 	/* Initialize the compressed state engine. */
418 	syn_cache_init();
419 
420 	/* Initialize the congestion control algorithms. */
421 	tcp_congctl_init();
422 
423 	/* Initialize the TCPCB template. */
424 	tcp_tcpcb_template();
425 
426 	/* Initialize reassembly queue */
427 	tcpipqent_init();
428 
429 	/* SACK */
430 	tcp_sack_init();
431 
432 	MOWNER_ATTACH(&tcp_tx_mowner);
433 	MOWNER_ATTACH(&tcp_rx_mowner);
434 	MOWNER_ATTACH(&tcp_reass_mowner);
435 	MOWNER_ATTACH(&tcp_sock_mowner);
436 	MOWNER_ATTACH(&tcp_sock_tx_mowner);
437 	MOWNER_ATTACH(&tcp_sock_rx_mowner);
438 	MOWNER_ATTACH(&tcp_mowner);
439 
440 	tcpstat_percpu = percpu_alloc(sizeof(uint64_t) * TCP_NSTATS);
441 
442 	vtw_earlyinit();
443 }
444 
445 /*
446  * Create template to be used to send tcp packets on a connection.
447  * Call after host entry created, allocates an mbuf and fills
448  * in a skeletal tcp/ip header, minimizing the amount of work
449  * necessary when the connection is used.
450  */
451 struct mbuf *
452 tcp_template(struct tcpcb *tp)
453 {
454 	struct inpcb *inp = tp->t_inpcb;
455 #ifdef INET6
456 	struct in6pcb *in6p = tp->t_in6pcb;
457 #endif
458 	struct tcphdr *n;
459 	struct mbuf *m;
460 	int hlen;
461 
462 	switch (tp->t_family) {
463 	case AF_INET:
464 		hlen = sizeof(struct ip);
465 		if (inp)
466 			break;
467 #ifdef INET6
468 		if (in6p) {
469 			/* mapped addr case */
470 			if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_laddr)
471 			 && IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr))
472 				break;
473 		}
474 #endif
475 		return NULL;	/*EINVAL*/
476 #ifdef INET6
477 	case AF_INET6:
478 		hlen = sizeof(struct ip6_hdr);
479 		if (in6p) {
480 			/* more sainty check? */
481 			break;
482 		}
483 		return NULL;	/*EINVAL*/
484 #endif
485 	default:
486 		hlen = 0;	/*pacify gcc*/
487 		return NULL;	/*EAFNOSUPPORT*/
488 	}
489 #ifdef DIAGNOSTIC
490 	if (hlen + sizeof(struct tcphdr) > MCLBYTES)
491 		panic("mclbytes too small for t_template");
492 #endif
493 	m = tp->t_template;
494 	if (m && m->m_len == hlen + sizeof(struct tcphdr))
495 		;
496 	else {
497 		if (m)
498 			m_freem(m);
499 		m = tp->t_template = NULL;
500 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
501 		if (m && hlen + sizeof(struct tcphdr) > MHLEN) {
502 			MCLGET(m, M_DONTWAIT);
503 			if ((m->m_flags & M_EXT) == 0) {
504 				m_free(m);
505 				m = NULL;
506 			}
507 		}
508 		if (m == NULL)
509 			return NULL;
510 		MCLAIM(m, &tcp_mowner);
511 		m->m_pkthdr.len = m->m_len = hlen + sizeof(struct tcphdr);
512 	}
513 
514 	memset(mtod(m, void *), 0, m->m_len);
515 
516 	n = (struct tcphdr *)(mtod(m, char *) + hlen);
517 
518 	switch (tp->t_family) {
519 	case AF_INET:
520 	    {
521 		struct ipovly *ipov;
522 		mtod(m, struct ip *)->ip_v = 4;
523 		mtod(m, struct ip *)->ip_hl = hlen >> 2;
524 		ipov = mtod(m, struct ipovly *);
525 		ipov->ih_pr = IPPROTO_TCP;
526 		ipov->ih_len = htons(sizeof(struct tcphdr));
527 		if (inp) {
528 			ipov->ih_src = inp->inp_laddr;
529 			ipov->ih_dst = inp->inp_faddr;
530 		}
531 #ifdef INET6
532 		else if (in6p) {
533 			/* mapped addr case */
534 			bcopy(&in6p->in6p_laddr.s6_addr32[3], &ipov->ih_src,
535 				sizeof(ipov->ih_src));
536 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &ipov->ih_dst,
537 				sizeof(ipov->ih_dst));
538 		}
539 #endif
540 		/*
541 		 * Compute the pseudo-header portion of the checksum
542 		 * now.  We incrementally add in the TCP option and
543 		 * payload lengths later, and then compute the TCP
544 		 * checksum right before the packet is sent off onto
545 		 * the wire.
546 		 */
547 		n->th_sum = in_cksum_phdr(ipov->ih_src.s_addr,
548 		    ipov->ih_dst.s_addr,
549 		    htons(sizeof(struct tcphdr) + IPPROTO_TCP));
550 		break;
551 	    }
552 #ifdef INET6
553 	case AF_INET6:
554 	    {
555 		struct ip6_hdr *ip6;
556 		mtod(m, struct ip *)->ip_v = 6;
557 		ip6 = mtod(m, struct ip6_hdr *);
558 		ip6->ip6_nxt = IPPROTO_TCP;
559 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
560 		ip6->ip6_src = in6p->in6p_laddr;
561 		ip6->ip6_dst = in6p->in6p_faddr;
562 		ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK;
563 		if (ip6_auto_flowlabel) {
564 			ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
565 			ip6->ip6_flow |=
566 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
567 		}
568 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
569 		ip6->ip6_vfc |= IPV6_VERSION;
570 
571 		/*
572 		 * Compute the pseudo-header portion of the checksum
573 		 * now.  We incrementally add in the TCP option and
574 		 * payload lengths later, and then compute the TCP
575 		 * checksum right before the packet is sent off onto
576 		 * the wire.
577 		 */
578 		n->th_sum = in6_cksum_phdr(&in6p->in6p_laddr,
579 		    &in6p->in6p_faddr, htonl(sizeof(struct tcphdr)),
580 		    htonl(IPPROTO_TCP));
581 		break;
582 	    }
583 #endif
584 	}
585 	if (inp) {
586 		n->th_sport = inp->inp_lport;
587 		n->th_dport = inp->inp_fport;
588 	}
589 #ifdef INET6
590 	else if (in6p) {
591 		n->th_sport = in6p->in6p_lport;
592 		n->th_dport = in6p->in6p_fport;
593 	}
594 #endif
595 	n->th_seq = 0;
596 	n->th_ack = 0;
597 	n->th_x2 = 0;
598 	n->th_off = 5;
599 	n->th_flags = 0;
600 	n->th_win = 0;
601 	n->th_urp = 0;
602 	return (m);
603 }
604 
605 /*
606  * Send a single message to the TCP at address specified by
607  * the given TCP/IP header.  If m == 0, then we make a copy
608  * of the tcpiphdr at ti and send directly to the addressed host.
609  * This is used to force keep alive messages out using the TCP
610  * template for a connection tp->t_template.  If flags are given
611  * then we send a message back to the TCP which originated the
612  * segment ti, and discard the mbuf containing it and any other
613  * attached mbufs.
614  *
615  * In any case the ack and sequence number of the transmitted
616  * segment are as specified by the parameters.
617  */
618 int
619 tcp_respond(struct tcpcb *tp, struct mbuf *template, struct mbuf *m,
620     struct tcphdr *th0, tcp_seq ack, tcp_seq seq, int flags)
621 {
622 #ifdef INET6
623 	struct rtentry *rt;
624 #endif
625 	struct route *ro;
626 	int error, tlen, win = 0;
627 	int hlen;
628 	struct ip *ip;
629 #ifdef INET6
630 	struct ip6_hdr *ip6;
631 #endif
632 	int family;	/* family on packet, not inpcb/in6pcb! */
633 	struct tcphdr *th;
634 	struct socket *so;
635 
636 	if (tp != NULL && (flags & TH_RST) == 0) {
637 #ifdef DIAGNOSTIC
638 		if (tp->t_inpcb && tp->t_in6pcb)
639 			panic("tcp_respond: both t_inpcb and t_in6pcb are set");
640 #endif
641 #ifdef INET
642 		if (tp->t_inpcb)
643 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
644 #endif
645 #ifdef INET6
646 		if (tp->t_in6pcb)
647 			win = sbspace(&tp->t_in6pcb->in6p_socket->so_rcv);
648 #endif
649 	}
650 
651 	th = NULL;	/* Quell uninitialized warning */
652 	ip = NULL;
653 #ifdef INET6
654 	ip6 = NULL;
655 #endif
656 	if (m == 0) {
657 		if (!template)
658 			return EINVAL;
659 
660 		/* get family information from template */
661 		switch (mtod(template, struct ip *)->ip_v) {
662 		case 4:
663 			family = AF_INET;
664 			hlen = sizeof(struct ip);
665 			break;
666 #ifdef INET6
667 		case 6:
668 			family = AF_INET6;
669 			hlen = sizeof(struct ip6_hdr);
670 			break;
671 #endif
672 		default:
673 			return EAFNOSUPPORT;
674 		}
675 
676 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
677 		if (m) {
678 			MCLAIM(m, &tcp_tx_mowner);
679 			MCLGET(m, M_DONTWAIT);
680 			if ((m->m_flags & M_EXT) == 0) {
681 				m_free(m);
682 				m = NULL;
683 			}
684 		}
685 		if (m == NULL)
686 			return (ENOBUFS);
687 
688 		if (tcp_compat_42)
689 			tlen = 1;
690 		else
691 			tlen = 0;
692 
693 		m->m_data += max_linkhdr;
694 		bcopy(mtod(template, void *), mtod(m, void *),
695 			template->m_len);
696 		switch (family) {
697 		case AF_INET:
698 			ip = mtod(m, struct ip *);
699 			th = (struct tcphdr *)(ip + 1);
700 			break;
701 #ifdef INET6
702 		case AF_INET6:
703 			ip6 = mtod(m, struct ip6_hdr *);
704 			th = (struct tcphdr *)(ip6 + 1);
705 			break;
706 #endif
707 #if 0
708 		default:
709 			/* noone will visit here */
710 			m_freem(m);
711 			return EAFNOSUPPORT;
712 #endif
713 		}
714 		flags = TH_ACK;
715 	} else {
716 
717 		if ((m->m_flags & M_PKTHDR) == 0) {
718 #if 0
719 			printf("non PKTHDR to tcp_respond\n");
720 #endif
721 			m_freem(m);
722 			return EINVAL;
723 		}
724 #ifdef DIAGNOSTIC
725 		if (!th0)
726 			panic("th0 == NULL in tcp_respond");
727 #endif
728 
729 		/* get family information from m */
730 		switch (mtod(m, struct ip *)->ip_v) {
731 		case 4:
732 			family = AF_INET;
733 			hlen = sizeof(struct ip);
734 			ip = mtod(m, struct ip *);
735 			break;
736 #ifdef INET6
737 		case 6:
738 			family = AF_INET6;
739 			hlen = sizeof(struct ip6_hdr);
740 			ip6 = mtod(m, struct ip6_hdr *);
741 			break;
742 #endif
743 		default:
744 			m_freem(m);
745 			return EAFNOSUPPORT;
746 		}
747 		/* clear h/w csum flags inherited from rx packet */
748 		m->m_pkthdr.csum_flags = 0;
749 
750 		if ((flags & TH_SYN) == 0 || sizeof(*th0) > (th0->th_off << 2))
751 			tlen = sizeof(*th0);
752 		else
753 			tlen = th0->th_off << 2;
754 
755 		if (m->m_len > hlen + tlen && (m->m_flags & M_EXT) == 0 &&
756 		    mtod(m, char *) + hlen == (char *)th0) {
757 			m->m_len = hlen + tlen;
758 			m_freem(m->m_next);
759 			m->m_next = NULL;
760 		} else {
761 			struct mbuf *n;
762 
763 #ifdef DIAGNOSTIC
764 			if (max_linkhdr + hlen + tlen > MCLBYTES) {
765 				m_freem(m);
766 				return EMSGSIZE;
767 			}
768 #endif
769 			MGETHDR(n, M_DONTWAIT, MT_HEADER);
770 			if (n && max_linkhdr + hlen + tlen > MHLEN) {
771 				MCLGET(n, M_DONTWAIT);
772 				if ((n->m_flags & M_EXT) == 0) {
773 					m_freem(n);
774 					n = NULL;
775 				}
776 			}
777 			if (!n) {
778 				m_freem(m);
779 				return ENOBUFS;
780 			}
781 
782 			MCLAIM(n, &tcp_tx_mowner);
783 			n->m_data += max_linkhdr;
784 			n->m_len = hlen + tlen;
785 			m_copyback(n, 0, hlen, mtod(m, void *));
786 			m_copyback(n, hlen, tlen, (void *)th0);
787 
788 			m_freem(m);
789 			m = n;
790 			n = NULL;
791 		}
792 
793 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
794 		switch (family) {
795 		case AF_INET:
796 			ip = mtod(m, struct ip *);
797 			th = (struct tcphdr *)(ip + 1);
798 			ip->ip_p = IPPROTO_TCP;
799 			xchg(ip->ip_dst, ip->ip_src, struct in_addr);
800 			ip->ip_p = IPPROTO_TCP;
801 			break;
802 #ifdef INET6
803 		case AF_INET6:
804 			ip6 = mtod(m, struct ip6_hdr *);
805 			th = (struct tcphdr *)(ip6 + 1);
806 			ip6->ip6_nxt = IPPROTO_TCP;
807 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
808 			ip6->ip6_nxt = IPPROTO_TCP;
809 			break;
810 #endif
811 #if 0
812 		default:
813 			/* noone will visit here */
814 			m_freem(m);
815 			return EAFNOSUPPORT;
816 #endif
817 		}
818 		xchg(th->th_dport, th->th_sport, u_int16_t);
819 #undef xchg
820 		tlen = 0;	/*be friendly with the following code*/
821 	}
822 	th->th_seq = htonl(seq);
823 	th->th_ack = htonl(ack);
824 	th->th_x2 = 0;
825 	if ((flags & TH_SYN) == 0) {
826 		if (tp)
827 			win >>= tp->rcv_scale;
828 		if (win > TCP_MAXWIN)
829 			win = TCP_MAXWIN;
830 		th->th_win = htons((u_int16_t)win);
831 		th->th_off = sizeof (struct tcphdr) >> 2;
832 		tlen += sizeof(*th);
833 	} else
834 		tlen += th->th_off << 2;
835 	m->m_len = hlen + tlen;
836 	m->m_pkthdr.len = hlen + tlen;
837 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
838 	th->th_flags = flags;
839 	th->th_urp = 0;
840 
841 	switch (family) {
842 #ifdef INET
843 	case AF_INET:
844 	    {
845 		struct ipovly *ipov = (struct ipovly *)ip;
846 		memset(ipov->ih_x1, 0, sizeof ipov->ih_x1);
847 		ipov->ih_len = htons((u_int16_t)tlen);
848 
849 		th->th_sum = 0;
850 		th->th_sum = in_cksum(m, hlen + tlen);
851 		ip->ip_len = htons(hlen + tlen);
852 		ip->ip_ttl = ip_defttl;
853 		break;
854 	    }
855 #endif
856 #ifdef INET6
857 	case AF_INET6:
858 	    {
859 		th->th_sum = 0;
860 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
861 				tlen);
862 		ip6->ip6_plen = htons(tlen);
863 		if (tp && tp->t_in6pcb) {
864 			struct ifnet *oifp;
865 			ro = &tp->t_in6pcb->in6p_route;
866 			oifp = (rt = rtcache_validate(ro)) != NULL ? rt->rt_ifp
867 			                                           : NULL;
868 			ip6->ip6_hlim = in6_selecthlim(tp->t_in6pcb, oifp);
869 		} else
870 			ip6->ip6_hlim = ip6_defhlim;
871 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
872 		if (ip6_auto_flowlabel) {
873 			ip6->ip6_flow |=
874 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
875 		}
876 		break;
877 	    }
878 #endif
879 	}
880 
881 	if (tp && tp->t_inpcb)
882 		so = tp->t_inpcb->inp_socket;
883 #ifdef INET6
884 	else if (tp && tp->t_in6pcb)
885 		so = tp->t_in6pcb->in6p_socket;
886 #endif
887 	else
888 		so = NULL;
889 
890 	if (tp != NULL && tp->t_inpcb != NULL) {
891 		ro = &tp->t_inpcb->inp_route;
892 #ifdef DIAGNOSTIC
893 		if (family != AF_INET)
894 			panic("tcp_respond: address family mismatch");
895 		if (!in_hosteq(ip->ip_dst, tp->t_inpcb->inp_faddr)) {
896 			panic("tcp_respond: ip_dst %x != inp_faddr %x",
897 			    ntohl(ip->ip_dst.s_addr),
898 			    ntohl(tp->t_inpcb->inp_faddr.s_addr));
899 		}
900 #endif
901 	}
902 #ifdef INET6
903 	else if (tp != NULL && tp->t_in6pcb != NULL) {
904 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
905 #ifdef DIAGNOSTIC
906 		if (family == AF_INET) {
907 			if (!IN6_IS_ADDR_V4MAPPED(&tp->t_in6pcb->in6p_faddr))
908 				panic("tcp_respond: not mapped addr");
909 			if (memcmp(&ip->ip_dst,
910 			    &tp->t_in6pcb->in6p_faddr.s6_addr32[3],
911 			    sizeof(ip->ip_dst)) != 0) {
912 				panic("tcp_respond: ip_dst != in6p_faddr");
913 			}
914 		} else if (family == AF_INET6) {
915 			if (!IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
916 			    &tp->t_in6pcb->in6p_faddr))
917 				panic("tcp_respond: ip6_dst != in6p_faddr");
918 		} else
919 			panic("tcp_respond: address family mismatch");
920 #endif
921 	}
922 #endif
923 	else
924 		ro = NULL;
925 
926 	switch (family) {
927 #ifdef INET
928 	case AF_INET:
929 		error = ip_output(m, NULL, ro,
930 		    (tp && tp->t_mtudisc ? IP_MTUDISC : 0),
931 		    (struct ip_moptions *)0, so);
932 		break;
933 #endif
934 #ifdef INET6
935 	case AF_INET6:
936 		error = ip6_output(m, NULL, ro, 0, NULL, so, NULL);
937 		break;
938 #endif
939 	default:
940 		error = EAFNOSUPPORT;
941 		break;
942 	}
943 
944 	return (error);
945 }
946 
947 /*
948  * Template TCPCB.  Rather than zeroing a new TCPCB and initializing
949  * a bunch of members individually, we maintain this template for the
950  * static and mostly-static components of the TCPCB, and copy it into
951  * the new TCPCB instead.
952  */
953 static struct tcpcb tcpcb_template = {
954 	.t_srtt = TCPTV_SRTTBASE,
955 	.t_rttmin = TCPTV_MIN,
956 
957 	.snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT,
958 	.snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT,
959 	.snd_numholes = 0,
960 
961 	.t_partialacks = -1,
962 	.t_bytes_acked = 0,
963 };
964 
965 /*
966  * Updates the TCPCB template whenever a parameter that would affect
967  * the template is changed.
968  */
969 void
970 tcp_tcpcb_template(void)
971 {
972 	struct tcpcb *tp = &tcpcb_template;
973 	int flags;
974 
975 	tp->t_peermss = tcp_mssdflt;
976 	tp->t_ourmss = tcp_mssdflt;
977 	tp->t_segsz = tcp_mssdflt;
978 
979 	flags = 0;
980 	if (tcp_do_rfc1323 && tcp_do_win_scale)
981 		flags |= TF_REQ_SCALE;
982 	if (tcp_do_rfc1323 && tcp_do_timestamps)
983 		flags |= TF_REQ_TSTMP;
984 	tp->t_flags = flags;
985 
986 	/*
987 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
988 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
989 	 * reasonable initial retransmit time.
990 	 */
991 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ << (TCP_RTTVAR_SHIFT + 2 - 1);
992 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
993 	    TCPTV_MIN, TCPTV_REXMTMAX);
994 
995 	/* Keep Alive */
996 	tp->t_keepinit = tcp_keepinit;
997 	tp->t_keepidle = tcp_keepidle;
998 	tp->t_keepintvl = tcp_keepintvl;
999 	tp->t_keepcnt = tcp_keepcnt;
1000 	tp->t_maxidle = tp->t_keepcnt * tp->t_keepintvl;
1001 
1002 	/* MSL */
1003 	tp->t_msl = TCPTV_MSL;
1004 }
1005 
1006 /*
1007  * Create a new TCP control block, making an
1008  * empty reassembly queue and hooking it to the argument
1009  * protocol control block.
1010  */
1011 /* family selects inpcb, or in6pcb */
1012 struct tcpcb *
1013 tcp_newtcpcb(int family, void *aux)
1014 {
1015 #ifdef INET6
1016 	struct rtentry *rt;
1017 #endif
1018 	struct tcpcb *tp;
1019 	int i;
1020 
1021 	/* XXX Consider using a pool_cache for speed. */
1022 	tp = pool_get(&tcpcb_pool, PR_NOWAIT);	/* splsoftnet via tcp_usrreq */
1023 	if (tp == NULL)
1024 		return (NULL);
1025 	memcpy(tp, &tcpcb_template, sizeof(*tp));
1026 	TAILQ_INIT(&tp->segq);
1027 	TAILQ_INIT(&tp->timeq);
1028 	tp->t_family = family;		/* may be overridden later on */
1029 	TAILQ_INIT(&tp->snd_holes);
1030 	LIST_INIT(&tp->t_sc);		/* XXX can template this */
1031 
1032 	/* Don't sweat this loop; hopefully the compiler will unroll it. */
1033 	for (i = 0; i < TCPT_NTIMERS; i++) {
1034 		callout_init(&tp->t_timer[i], CALLOUT_MPSAFE);
1035 		TCP_TIMER_INIT(tp, i);
1036 	}
1037 	callout_init(&tp->t_delack_ch, CALLOUT_MPSAFE);
1038 
1039 	switch (family) {
1040 	case AF_INET:
1041 	    {
1042 		struct inpcb *inp = (struct inpcb *)aux;
1043 
1044 		inp->inp_ip.ip_ttl = ip_defttl;
1045 		inp->inp_ppcb = (void *)tp;
1046 
1047 		tp->t_inpcb = inp;
1048 		tp->t_mtudisc = ip_mtudisc;
1049 		break;
1050 	    }
1051 #ifdef INET6
1052 	case AF_INET6:
1053 	    {
1054 		struct in6pcb *in6p = (struct in6pcb *)aux;
1055 
1056 		in6p->in6p_ip6.ip6_hlim = in6_selecthlim(in6p,
1057 			(rt = rtcache_validate(&in6p->in6p_route)) != NULL
1058 			    ? rt->rt_ifp
1059 			    : NULL);
1060 		in6p->in6p_ppcb = (void *)tp;
1061 
1062 		tp->t_in6pcb = in6p;
1063 		/* for IPv6, always try to run path MTU discovery */
1064 		tp->t_mtudisc = 1;
1065 		break;
1066 	    }
1067 #endif /* INET6 */
1068 	default:
1069 		for (i = 0; i < TCPT_NTIMERS; i++)
1070 			callout_destroy(&tp->t_timer[i]);
1071 		callout_destroy(&tp->t_delack_ch);
1072 		pool_put(&tcpcb_pool, tp);	/* splsoftnet via tcp_usrreq */
1073 		return (NULL);
1074 	}
1075 
1076 	/*
1077 	 * Initialize our timebase.  When we send timestamps, we take
1078 	 * the delta from tcp_now -- this means each connection always
1079 	 * gets a timebase of 1, which makes it, among other things,
1080 	 * more difficult to determine how long a system has been up,
1081 	 * and thus how many TCP sequence increments have occurred.
1082 	 *
1083 	 * We start with 1, because 0 doesn't work with linux, which
1084 	 * considers timestamp 0 in a SYN packet as a bug and disables
1085 	 * timestamps.
1086 	 */
1087 	tp->ts_timebase = tcp_now - 1;
1088 
1089 	tcp_congctl_select(tp, tcp_congctl_global_name);
1090 
1091 	return (tp);
1092 }
1093 
1094 /*
1095  * Drop a TCP connection, reporting
1096  * the specified error.  If connection is synchronized,
1097  * then send a RST to peer.
1098  */
1099 struct tcpcb *
1100 tcp_drop(struct tcpcb *tp, int errno)
1101 {
1102 	struct socket *so = NULL;
1103 
1104 #ifdef DIAGNOSTIC
1105 	if (tp->t_inpcb && tp->t_in6pcb)
1106 		panic("tcp_drop: both t_inpcb and t_in6pcb are set");
1107 #endif
1108 #ifdef INET
1109 	if (tp->t_inpcb)
1110 		so = tp->t_inpcb->inp_socket;
1111 #endif
1112 #ifdef INET6
1113 	if (tp->t_in6pcb)
1114 		so = tp->t_in6pcb->in6p_socket;
1115 #endif
1116 	if (!so)
1117 		return NULL;
1118 
1119 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
1120 		tp->t_state = TCPS_CLOSED;
1121 		(void) tcp_output(tp);
1122 		TCP_STATINC(TCP_STAT_DROPS);
1123 	} else
1124 		TCP_STATINC(TCP_STAT_CONNDROPS);
1125 	if (errno == ETIMEDOUT && tp->t_softerror)
1126 		errno = tp->t_softerror;
1127 	so->so_error = errno;
1128 	return (tcp_close(tp));
1129 }
1130 
1131 /*
1132  * Close a TCP control block:
1133  *	discard all space held by the tcp
1134  *	discard internet protocol block
1135  *	wake up any sleepers
1136  */
1137 struct tcpcb *
1138 tcp_close(struct tcpcb *tp)
1139 {
1140 	struct inpcb *inp;
1141 #ifdef INET6
1142 	struct in6pcb *in6p;
1143 #endif
1144 	struct socket *so;
1145 #ifdef RTV_RTT
1146 	struct rtentry *rt;
1147 #endif
1148 	struct route *ro;
1149 	int j;
1150 
1151 	inp = tp->t_inpcb;
1152 #ifdef INET6
1153 	in6p = tp->t_in6pcb;
1154 #endif
1155 	so = NULL;
1156 	ro = NULL;
1157 	if (inp) {
1158 		so = inp->inp_socket;
1159 		ro = &inp->inp_route;
1160 	}
1161 #ifdef INET6
1162 	else if (in6p) {
1163 		so = in6p->in6p_socket;
1164 		ro = (struct route *)&in6p->in6p_route;
1165 	}
1166 #endif
1167 
1168 #ifdef RTV_RTT
1169 	/*
1170 	 * If we sent enough data to get some meaningful characteristics,
1171 	 * save them in the routing entry.  'Enough' is arbitrarily
1172 	 * defined as the sendpipesize (default 4K) * 16.  This would
1173 	 * give us 16 rtt samples assuming we only get one sample per
1174 	 * window (the usual case on a long haul net).  16 samples is
1175 	 * enough for the srtt filter to converge to within 5% of the correct
1176 	 * value; fewer samples and we could save a very bogus rtt.
1177 	 *
1178 	 * Don't update the default route's characteristics and don't
1179 	 * update anything that the user "locked".
1180 	 */
1181 	if (SEQ_LT(tp->iss + so->so_snd.sb_hiwat * 16, tp->snd_max) &&
1182 	    ro && (rt = rtcache_validate(ro)) != NULL &&
1183 	    !in_nullhost(satocsin(rt_getkey(rt))->sin_addr)) {
1184 		u_long i = 0;
1185 
1186 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
1187 			i = tp->t_srtt *
1188 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
1189 			if (rt->rt_rmx.rmx_rtt && i)
1190 				/*
1191 				 * filter this update to half the old & half
1192 				 * the new values, converting scale.
1193 				 * See route.h and tcp_var.h for a
1194 				 * description of the scaling constants.
1195 				 */
1196 				rt->rt_rmx.rmx_rtt =
1197 				    (rt->rt_rmx.rmx_rtt + i) / 2;
1198 			else
1199 				rt->rt_rmx.rmx_rtt = i;
1200 		}
1201 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
1202 			i = tp->t_rttvar *
1203 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTTVAR_SHIFT + 2));
1204 			if (rt->rt_rmx.rmx_rttvar && i)
1205 				rt->rt_rmx.rmx_rttvar =
1206 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
1207 			else
1208 				rt->rt_rmx.rmx_rttvar = i;
1209 		}
1210 		/*
1211 		 * update the pipelimit (ssthresh) if it has been updated
1212 		 * already or if a pipesize was specified & the threshhold
1213 		 * got below half the pipesize.  I.e., wait for bad news
1214 		 * before we start updating, then update on both good
1215 		 * and bad news.
1216 		 */
1217 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
1218 		    (i = tp->snd_ssthresh) && rt->rt_rmx.rmx_ssthresh) ||
1219 		    i < (rt->rt_rmx.rmx_sendpipe / 2)) {
1220 			/*
1221 			 * convert the limit from user data bytes to
1222 			 * packets then to packet data bytes.
1223 			 */
1224 			i = (i + tp->t_segsz / 2) / tp->t_segsz;
1225 			if (i < 2)
1226 				i = 2;
1227 			i *= (u_long)(tp->t_segsz + sizeof (struct tcpiphdr));
1228 			if (rt->rt_rmx.rmx_ssthresh)
1229 				rt->rt_rmx.rmx_ssthresh =
1230 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
1231 			else
1232 				rt->rt_rmx.rmx_ssthresh = i;
1233 		}
1234 	}
1235 #endif /* RTV_RTT */
1236 	/* free the reassembly queue, if any */
1237 	TCP_REASS_LOCK(tp);
1238 	(void) tcp_freeq(tp);
1239 	TCP_REASS_UNLOCK(tp);
1240 
1241 	/* free the SACK holes list. */
1242 	tcp_free_sackholes(tp);
1243 	tcp_congctl_release(tp);
1244 	syn_cache_cleanup(tp);
1245 
1246 	if (tp->t_template) {
1247 		m_free(tp->t_template);
1248 		tp->t_template = NULL;
1249 	}
1250 
1251 	/*
1252 	 * Detaching the pcb will unlock the socket/tcpcb, and stopping
1253 	 * the timers can also drop the lock.  We need to prevent access
1254 	 * to the tcpcb as it's half torn down.  Flag the pcb as dead
1255 	 * (prevents access by timers) and only then detach it.
1256 	 */
1257 	tp->t_flags |= TF_DEAD;
1258 	if (inp) {
1259 		inp->inp_ppcb = 0;
1260 		soisdisconnected(so);
1261 		in_pcbdetach(inp);
1262 	}
1263 #ifdef INET6
1264 	else if (in6p) {
1265 		in6p->in6p_ppcb = 0;
1266 		soisdisconnected(so);
1267 		in6_pcbdetach(in6p);
1268 	}
1269 #endif
1270 	/*
1271 	 * pcb is no longer visble elsewhere, so we can safely release
1272 	 * the lock in callout_halt() if needed.
1273 	 */
1274 	TCP_STATINC(TCP_STAT_CLOSED);
1275 	for (j = 0; j < TCPT_NTIMERS; j++) {
1276 		callout_halt(&tp->t_timer[j], softnet_lock);
1277 		callout_destroy(&tp->t_timer[j]);
1278 	}
1279 	callout_halt(&tp->t_delack_ch, softnet_lock);
1280 	callout_destroy(&tp->t_delack_ch);
1281 	pool_put(&tcpcb_pool, tp);
1282 
1283 	return ((struct tcpcb *)0);
1284 }
1285 
1286 int
1287 tcp_freeq(struct tcpcb *tp)
1288 {
1289 	struct ipqent *qe;
1290 	int rv = 0;
1291 #ifdef TCPREASS_DEBUG
1292 	int i = 0;
1293 #endif
1294 
1295 	TCP_REASS_LOCK_CHECK(tp);
1296 
1297 	while ((qe = TAILQ_FIRST(&tp->segq)) != NULL) {
1298 #ifdef TCPREASS_DEBUG
1299 		printf("tcp_freeq[%p,%d]: %u:%u(%u) 0x%02x\n",
1300 			tp, i++, qe->ipqe_seq, qe->ipqe_seq + qe->ipqe_len,
1301 			qe->ipqe_len, qe->ipqe_flags & (TH_SYN|TH_FIN|TH_RST));
1302 #endif
1303 		TAILQ_REMOVE(&tp->segq, qe, ipqe_q);
1304 		TAILQ_REMOVE(&tp->timeq, qe, ipqe_timeq);
1305 		m_freem(qe->ipqe_m);
1306 		tcpipqent_free(qe);
1307 		rv = 1;
1308 	}
1309 	tp->t_segqlen = 0;
1310 	KASSERT(TAILQ_EMPTY(&tp->timeq));
1311 	return (rv);
1312 }
1313 
1314 void
1315 tcp_fasttimo(void)
1316 {
1317 	if (tcp_drainwanted) {
1318 		tcp_drain();
1319 		tcp_drainwanted = 0;
1320 	}
1321 }
1322 
1323 void
1324 tcp_drainstub(void)
1325 {
1326 	tcp_drainwanted = 1;
1327 }
1328 
1329 /*
1330  * Protocol drain routine.  Called when memory is in short supply.
1331  * Called from pr_fasttimo thus a callout context.
1332  */
1333 void
1334 tcp_drain(void)
1335 {
1336 	struct inpcb_hdr *inph;
1337 	struct tcpcb *tp;
1338 
1339 	mutex_enter(softnet_lock);
1340 	KERNEL_LOCK(1, NULL);
1341 
1342 	/*
1343 	 * Free the sequence queue of all TCP connections.
1344 	 */
1345 	CIRCLEQ_FOREACH(inph, &tcbtable.inpt_queue, inph_queue) {
1346 		switch (inph->inph_af) {
1347 		case AF_INET:
1348 			tp = intotcpcb((struct inpcb *)inph);
1349 			break;
1350 #ifdef INET6
1351 		case AF_INET6:
1352 			tp = in6totcpcb((struct in6pcb *)inph);
1353 			break;
1354 #endif
1355 		default:
1356 			tp = NULL;
1357 			break;
1358 		}
1359 		if (tp != NULL) {
1360 			/*
1361 			 * We may be called from a device's interrupt
1362 			 * context.  If the tcpcb is already busy,
1363 			 * just bail out now.
1364 			 */
1365 			if (tcp_reass_lock_try(tp) == 0)
1366 				continue;
1367 			if (tcp_freeq(tp))
1368 				TCP_STATINC(TCP_STAT_CONNSDRAINED);
1369 			TCP_REASS_UNLOCK(tp);
1370 		}
1371 	}
1372 
1373 	KERNEL_UNLOCK_ONE(NULL);
1374 	mutex_exit(softnet_lock);
1375 }
1376 
1377 /*
1378  * Notify a tcp user of an asynchronous error;
1379  * store error as soft error, but wake up user
1380  * (for now, won't do anything until can select for soft error).
1381  */
1382 void
1383 tcp_notify(struct inpcb *inp, int error)
1384 {
1385 	struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
1386 	struct socket *so = inp->inp_socket;
1387 
1388 	/*
1389 	 * Ignore some errors if we are hooked up.
1390 	 * If connection hasn't completed, has retransmitted several times,
1391 	 * and receives a second error, give up now.  This is better
1392 	 * than waiting a long time to establish a connection that
1393 	 * can never complete.
1394 	 */
1395 	if (tp->t_state == TCPS_ESTABLISHED &&
1396 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1397 	      error == EHOSTDOWN)) {
1398 		return;
1399 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1400 	    tp->t_rxtshift > 3 && tp->t_softerror)
1401 		so->so_error = error;
1402 	else
1403 		tp->t_softerror = error;
1404 	cv_broadcast(&so->so_cv);
1405 	sorwakeup(so);
1406 	sowwakeup(so);
1407 }
1408 
1409 #ifdef INET6
1410 void
1411 tcp6_notify(struct in6pcb *in6p, int error)
1412 {
1413 	struct tcpcb *tp = (struct tcpcb *)in6p->in6p_ppcb;
1414 	struct socket *so = in6p->in6p_socket;
1415 
1416 	/*
1417 	 * Ignore some errors if we are hooked up.
1418 	 * If connection hasn't completed, has retransmitted several times,
1419 	 * and receives a second error, give up now.  This is better
1420 	 * than waiting a long time to establish a connection that
1421 	 * can never complete.
1422 	 */
1423 	if (tp->t_state == TCPS_ESTABLISHED &&
1424 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1425 	      error == EHOSTDOWN)) {
1426 		return;
1427 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1428 	    tp->t_rxtshift > 3 && tp->t_softerror)
1429 		so->so_error = error;
1430 	else
1431 		tp->t_softerror = error;
1432 	cv_broadcast(&so->so_cv);
1433 	sorwakeup(so);
1434 	sowwakeup(so);
1435 }
1436 #endif
1437 
1438 #ifdef INET6
1439 void *
1440 tcp6_ctlinput(int cmd, const struct sockaddr *sa, void *d)
1441 {
1442 	struct tcphdr th;
1443 	void (*notify)(struct in6pcb *, int) = tcp6_notify;
1444 	int nmatch;
1445 	struct ip6_hdr *ip6;
1446 	const struct sockaddr_in6 *sa6_src = NULL;
1447 	const struct sockaddr_in6 *sa6 = (const struct sockaddr_in6 *)sa;
1448 	struct mbuf *m;
1449 	int off;
1450 
1451 	if (sa->sa_family != AF_INET6 ||
1452 	    sa->sa_len != sizeof(struct sockaddr_in6))
1453 		return NULL;
1454 	if ((unsigned)cmd >= PRC_NCMDS)
1455 		return NULL;
1456 	else if (cmd == PRC_QUENCH) {
1457 		/*
1458 		 * Don't honor ICMP Source Quench messages meant for
1459 		 * TCP connections.
1460 		 */
1461 		return NULL;
1462 	} else if (PRC_IS_REDIRECT(cmd))
1463 		notify = in6_rtchange, d = NULL;
1464 	else if (cmd == PRC_MSGSIZE)
1465 		; /* special code is present, see below */
1466 	else if (cmd == PRC_HOSTDEAD)
1467 		d = NULL;
1468 	else if (inet6ctlerrmap[cmd] == 0)
1469 		return NULL;
1470 
1471 	/* if the parameter is from icmp6, decode it. */
1472 	if (d != NULL) {
1473 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
1474 		m = ip6cp->ip6c_m;
1475 		ip6 = ip6cp->ip6c_ip6;
1476 		off = ip6cp->ip6c_off;
1477 		sa6_src = ip6cp->ip6c_src;
1478 	} else {
1479 		m = NULL;
1480 		ip6 = NULL;
1481 		sa6_src = &sa6_any;
1482 		off = 0;
1483 	}
1484 
1485 	if (ip6) {
1486 		/*
1487 		 * XXX: We assume that when ip6 is non NULL,
1488 		 * M and OFF are valid.
1489 		 */
1490 
1491 		/* check if we can safely examine src and dst ports */
1492 		if (m->m_pkthdr.len < off + sizeof(th)) {
1493 			if (cmd == PRC_MSGSIZE)
1494 				icmp6_mtudisc_update((struct ip6ctlparam *)d, 0);
1495 			return NULL;
1496 		}
1497 
1498 		memset(&th, 0, sizeof(th));
1499 		m_copydata(m, off, sizeof(th), (void *)&th);
1500 
1501 		if (cmd == PRC_MSGSIZE) {
1502 			int valid = 0;
1503 
1504 			/*
1505 			 * Check to see if we have a valid TCP connection
1506 			 * corresponding to the address in the ICMPv6 message
1507 			 * payload.
1508 			 */
1509 			if (in6_pcblookup_connect(&tcbtable, &sa6->sin6_addr,
1510 			    th.th_dport,
1511 			    (const struct in6_addr *)&sa6_src->sin6_addr,
1512 						  th.th_sport, 0, 0))
1513 				valid++;
1514 
1515 			/*
1516 			 * Depending on the value of "valid" and routing table
1517 			 * size (mtudisc_{hi,lo}wat), we will:
1518 			 * - recalcurate the new MTU and create the
1519 			 *   corresponding routing entry, or
1520 			 * - ignore the MTU change notification.
1521 			 */
1522 			icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
1523 
1524 			/*
1525 			 * no need to call in6_pcbnotify, it should have been
1526 			 * called via callback if necessary
1527 			 */
1528 			return NULL;
1529 		}
1530 
1531 		nmatch = in6_pcbnotify(&tcbtable, sa, th.th_dport,
1532 		    (const struct sockaddr *)sa6_src, th.th_sport, cmd, NULL, notify);
1533 		if (nmatch == 0 && syn_cache_count &&
1534 		    (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
1535 		     inet6ctlerrmap[cmd] == ENETUNREACH ||
1536 		     inet6ctlerrmap[cmd] == EHOSTDOWN))
1537 			syn_cache_unreach((const struct sockaddr *)sa6_src,
1538 					  sa, &th);
1539 	} else {
1540 		(void) in6_pcbnotify(&tcbtable, sa, 0,
1541 		    (const struct sockaddr *)sa6_src, 0, cmd, NULL, notify);
1542 	}
1543 
1544 	return NULL;
1545 }
1546 #endif
1547 
1548 #ifdef INET
1549 /* assumes that ip header and tcp header are contiguous on mbuf */
1550 void *
1551 tcp_ctlinput(int cmd, const struct sockaddr *sa, void *v)
1552 {
1553 	struct ip *ip = v;
1554 	struct tcphdr *th;
1555 	struct icmp *icp;
1556 	extern const int inetctlerrmap[];
1557 	void (*notify)(struct inpcb *, int) = tcp_notify;
1558 	int errno;
1559 	int nmatch;
1560 	struct tcpcb *tp;
1561 	u_int mtu;
1562 	tcp_seq seq;
1563 	struct inpcb *inp;
1564 #ifdef INET6
1565 	struct in6pcb *in6p;
1566 	struct in6_addr src6, dst6;
1567 #endif
1568 
1569 	if (sa->sa_family != AF_INET ||
1570 	    sa->sa_len != sizeof(struct sockaddr_in))
1571 		return NULL;
1572 	if ((unsigned)cmd >= PRC_NCMDS)
1573 		return NULL;
1574 	errno = inetctlerrmap[cmd];
1575 	if (cmd == PRC_QUENCH)
1576 		/*
1577 		 * Don't honor ICMP Source Quench messages meant for
1578 		 * TCP connections.
1579 		 */
1580 		return NULL;
1581 	else if (PRC_IS_REDIRECT(cmd))
1582 		notify = in_rtchange, ip = 0;
1583 	else if (cmd == PRC_MSGSIZE && ip && ip->ip_v == 4) {
1584 		/*
1585 		 * Check to see if we have a valid TCP connection
1586 		 * corresponding to the address in the ICMP message
1587 		 * payload.
1588 		 *
1589 		 * Boundary check is made in icmp_input(), with ICMP_ADVLENMIN.
1590 		 */
1591 		th = (struct tcphdr *)((char *)ip + (ip->ip_hl << 2));
1592 #ifdef INET6
1593 		memset(&src6, 0, sizeof(src6));
1594 		memset(&dst6, 0, sizeof(dst6));
1595 		src6.s6_addr16[5] = dst6.s6_addr16[5] = 0xffff;
1596 		memcpy(&src6.s6_addr32[3], &ip->ip_src, sizeof(struct in_addr));
1597 		memcpy(&dst6.s6_addr32[3], &ip->ip_dst, sizeof(struct in_addr));
1598 #endif
1599 		if ((inp = in_pcblookup_connect(&tcbtable, ip->ip_dst,
1600 						th->th_dport, ip->ip_src, th->th_sport, 0)) != NULL)
1601 #ifdef INET6
1602 			in6p = NULL;
1603 #else
1604 			;
1605 #endif
1606 #ifdef INET6
1607 		else if ((in6p = in6_pcblookup_connect(&tcbtable, &dst6,
1608 						       th->th_dport, &src6, th->th_sport, 0, 0)) != NULL)
1609 			;
1610 #endif
1611 		else
1612 			return NULL;
1613 
1614 		/*
1615 		 * Now that we've validated that we are actually communicating
1616 		 * with the host indicated in the ICMP message, locate the
1617 		 * ICMP header, recalculate the new MTU, and create the
1618 		 * corresponding routing entry.
1619 		 */
1620 		icp = (struct icmp *)((char *)ip -
1621 		    offsetof(struct icmp, icmp_ip));
1622 		if (inp) {
1623 			if ((tp = intotcpcb(inp)) == NULL)
1624 				return NULL;
1625 		}
1626 #ifdef INET6
1627 		else if (in6p) {
1628 			if ((tp = in6totcpcb(in6p)) == NULL)
1629 				return NULL;
1630 		}
1631 #endif
1632 		else
1633 			return NULL;
1634 		seq = ntohl(th->th_seq);
1635 		if (SEQ_LT(seq, tp->snd_una) || SEQ_GT(seq, tp->snd_max))
1636 			return NULL;
1637 		/*
1638 		 * If the ICMP message advertises a Next-Hop MTU
1639 		 * equal or larger than the maximum packet size we have
1640 		 * ever sent, drop the message.
1641 		 */
1642 		mtu = (u_int)ntohs(icp->icmp_nextmtu);
1643 		if (mtu >= tp->t_pmtud_mtu_sent)
1644 			return NULL;
1645 		if (mtu >= tcp_hdrsz(tp) + tp->t_pmtud_mss_acked) {
1646 			/*
1647 			 * Calculate new MTU, and create corresponding
1648 			 * route (traditional PMTUD).
1649 			 */
1650 			tp->t_flags &= ~TF_PMTUD_PEND;
1651 			icmp_mtudisc(icp, ip->ip_dst);
1652 		} else {
1653 			/*
1654 			 * Record the information got in the ICMP
1655 			 * message; act on it later.
1656 			 * If we had already recorded an ICMP message,
1657 			 * replace the old one only if the new message
1658 			 * refers to an older TCP segment
1659 			 */
1660 			if (tp->t_flags & TF_PMTUD_PEND) {
1661 				if (SEQ_LT(tp->t_pmtud_th_seq, seq))
1662 					return NULL;
1663 			} else
1664 				tp->t_flags |= TF_PMTUD_PEND;
1665 			tp->t_pmtud_th_seq = seq;
1666 			tp->t_pmtud_nextmtu = icp->icmp_nextmtu;
1667 			tp->t_pmtud_ip_len = icp->icmp_ip.ip_len;
1668 			tp->t_pmtud_ip_hl = icp->icmp_ip.ip_hl;
1669 		}
1670 		return NULL;
1671 	} else if (cmd == PRC_HOSTDEAD)
1672 		ip = 0;
1673 	else if (errno == 0)
1674 		return NULL;
1675 	if (ip && ip->ip_v == 4 && sa->sa_family == AF_INET) {
1676 		th = (struct tcphdr *)((char *)ip + (ip->ip_hl << 2));
1677 		nmatch = in_pcbnotify(&tcbtable, satocsin(sa)->sin_addr,
1678 		    th->th_dport, ip->ip_src, th->th_sport, errno, notify);
1679 		if (nmatch == 0 && syn_cache_count &&
1680 		    (inetctlerrmap[cmd] == EHOSTUNREACH ||
1681 		    inetctlerrmap[cmd] == ENETUNREACH ||
1682 		    inetctlerrmap[cmd] == EHOSTDOWN)) {
1683 			struct sockaddr_in sin;
1684 			memset(&sin, 0, sizeof(sin));
1685 			sin.sin_len = sizeof(sin);
1686 			sin.sin_family = AF_INET;
1687 			sin.sin_port = th->th_sport;
1688 			sin.sin_addr = ip->ip_src;
1689 			syn_cache_unreach((struct sockaddr *)&sin, sa, th);
1690 		}
1691 
1692 		/* XXX mapped address case */
1693 	} else
1694 		in_pcbnotifyall(&tcbtable, satocsin(sa)->sin_addr, errno,
1695 		    notify);
1696 	return NULL;
1697 }
1698 
1699 /*
1700  * When a source quench is received, we are being notified of congestion.
1701  * Close the congestion window down to the Loss Window (one segment).
1702  * We will gradually open it again as we proceed.
1703  */
1704 void
1705 tcp_quench(struct inpcb *inp, int errno)
1706 {
1707 	struct tcpcb *tp = intotcpcb(inp);
1708 
1709 	if (tp) {
1710 		tp->snd_cwnd = tp->t_segsz;
1711 		tp->t_bytes_acked = 0;
1712 	}
1713 }
1714 #endif
1715 
1716 #ifdef INET6
1717 void
1718 tcp6_quench(struct in6pcb *in6p, int errno)
1719 {
1720 	struct tcpcb *tp = in6totcpcb(in6p);
1721 
1722 	if (tp) {
1723 		tp->snd_cwnd = tp->t_segsz;
1724 		tp->t_bytes_acked = 0;
1725 	}
1726 }
1727 #endif
1728 
1729 #ifdef INET
1730 /*
1731  * Path MTU Discovery handlers.
1732  */
1733 void
1734 tcp_mtudisc_callback(struct in_addr faddr)
1735 {
1736 #ifdef INET6
1737 	struct in6_addr in6;
1738 #endif
1739 
1740 	in_pcbnotifyall(&tcbtable, faddr, EMSGSIZE, tcp_mtudisc);
1741 #ifdef INET6
1742 	memset(&in6, 0, sizeof(in6));
1743 	in6.s6_addr16[5] = 0xffff;
1744 	memcpy(&in6.s6_addr32[3], &faddr, sizeof(struct in_addr));
1745 	tcp6_mtudisc_callback(&in6);
1746 #endif
1747 }
1748 
1749 /*
1750  * On receipt of path MTU corrections, flush old route and replace it
1751  * with the new one.  Retransmit all unacknowledged packets, to ensure
1752  * that all packets will be received.
1753  */
1754 void
1755 tcp_mtudisc(struct inpcb *inp, int errno)
1756 {
1757 	struct tcpcb *tp = intotcpcb(inp);
1758 	struct rtentry *rt = in_pcbrtentry(inp);
1759 
1760 	if (tp != 0) {
1761 		if (rt != 0) {
1762 			/*
1763 			 * If this was not a host route, remove and realloc.
1764 			 */
1765 			if ((rt->rt_flags & RTF_HOST) == 0) {
1766 				in_rtchange(inp, errno);
1767 				if ((rt = in_pcbrtentry(inp)) == 0)
1768 					return;
1769 			}
1770 
1771 			/*
1772 			 * Slow start out of the error condition.  We
1773 			 * use the MTU because we know it's smaller
1774 			 * than the previously transmitted segment.
1775 			 *
1776 			 * Note: This is more conservative than the
1777 			 * suggestion in draft-floyd-incr-init-win-03.
1778 			 */
1779 			if (rt->rt_rmx.rmx_mtu != 0)
1780 				tp->snd_cwnd =
1781 				    TCP_INITIAL_WINDOW(tcp_init_win,
1782 				    rt->rt_rmx.rmx_mtu);
1783 		}
1784 
1785 		/*
1786 		 * Resend unacknowledged packets.
1787 		 */
1788 		tp->snd_nxt = tp->sack_newdata = tp->snd_una;
1789 		tcp_output(tp);
1790 	}
1791 }
1792 #endif
1793 
1794 #ifdef INET6
1795 /*
1796  * Path MTU Discovery handlers.
1797  */
1798 void
1799 tcp6_mtudisc_callback(struct in6_addr *faddr)
1800 {
1801 	struct sockaddr_in6 sin6;
1802 
1803 	memset(&sin6, 0, sizeof(sin6));
1804 	sin6.sin6_family = AF_INET6;
1805 	sin6.sin6_len = sizeof(struct sockaddr_in6);
1806 	sin6.sin6_addr = *faddr;
1807 	(void) in6_pcbnotify(&tcbtable, (struct sockaddr *)&sin6, 0,
1808 	    (const struct sockaddr *)&sa6_any, 0, PRC_MSGSIZE, NULL, tcp6_mtudisc);
1809 }
1810 
1811 void
1812 tcp6_mtudisc(struct in6pcb *in6p, int errno)
1813 {
1814 	struct tcpcb *tp = in6totcpcb(in6p);
1815 	struct rtentry *rt = in6_pcbrtentry(in6p);
1816 
1817 	if (tp != 0) {
1818 		if (rt != 0) {
1819 			/*
1820 			 * If this was not a host route, remove and realloc.
1821 			 */
1822 			if ((rt->rt_flags & RTF_HOST) == 0) {
1823 				in6_rtchange(in6p, errno);
1824 				if ((rt = in6_pcbrtentry(in6p)) == 0)
1825 					return;
1826 			}
1827 
1828 			/*
1829 			 * Slow start out of the error condition.  We
1830 			 * use the MTU because we know it's smaller
1831 			 * than the previously transmitted segment.
1832 			 *
1833 			 * Note: This is more conservative than the
1834 			 * suggestion in draft-floyd-incr-init-win-03.
1835 			 */
1836 			if (rt->rt_rmx.rmx_mtu != 0)
1837 				tp->snd_cwnd =
1838 				    TCP_INITIAL_WINDOW(tcp_init_win,
1839 				    rt->rt_rmx.rmx_mtu);
1840 		}
1841 
1842 		/*
1843 		 * Resend unacknowledged packets.
1844 		 */
1845 		tp->snd_nxt = tp->sack_newdata = tp->snd_una;
1846 		tcp_output(tp);
1847 	}
1848 }
1849 #endif /* INET6 */
1850 
1851 /*
1852  * Compute the MSS to advertise to the peer.  Called only during
1853  * the 3-way handshake.  If we are the server (peer initiated
1854  * connection), we are called with a pointer to the interface
1855  * on which the SYN packet arrived.  If we are the client (we
1856  * initiated connection), we are called with a pointer to the
1857  * interface out which this connection should go.
1858  *
1859  * NOTE: Do not subtract IP option/extension header size nor IPsec
1860  * header size from MSS advertisement.  MSS option must hold the maximum
1861  * segment size we can accept, so it must always be:
1862  *	 max(if mtu) - ip header - tcp header
1863  */
1864 u_long
1865 tcp_mss_to_advertise(const struct ifnet *ifp, int af)
1866 {
1867 	extern u_long in_maxmtu;
1868 	u_long mss = 0;
1869 	u_long hdrsiz;
1870 
1871 	/*
1872 	 * In order to avoid defeating path MTU discovery on the peer,
1873 	 * we advertise the max MTU of all attached networks as our MSS,
1874 	 * per RFC 1191, section 3.1.
1875 	 *
1876 	 * We provide the option to advertise just the MTU of
1877 	 * the interface on which we hope this connection will
1878 	 * be receiving.  If we are responding to a SYN, we
1879 	 * will have a pretty good idea about this, but when
1880 	 * initiating a connection there is a bit more doubt.
1881 	 *
1882 	 * We also need to ensure that loopback has a large enough
1883 	 * MSS, as the loopback MTU is never included in in_maxmtu.
1884 	 */
1885 
1886 	if (ifp != NULL)
1887 		switch (af) {
1888 		case AF_INET:
1889 			mss = ifp->if_mtu;
1890 			break;
1891 #ifdef INET6
1892 		case AF_INET6:
1893 			mss = IN6_LINKMTU(ifp);
1894 			break;
1895 #endif
1896 		}
1897 
1898 	if (tcp_mss_ifmtu == 0)
1899 		switch (af) {
1900 		case AF_INET:
1901 			mss = max(in_maxmtu, mss);
1902 			break;
1903 #ifdef INET6
1904 		case AF_INET6:
1905 			mss = max(in6_maxmtu, mss);
1906 			break;
1907 #endif
1908 		}
1909 
1910 	switch (af) {
1911 	case AF_INET:
1912 		hdrsiz = sizeof(struct ip);
1913 		break;
1914 #ifdef INET6
1915 	case AF_INET6:
1916 		hdrsiz = sizeof(struct ip6_hdr);
1917 		break;
1918 #endif
1919 	default:
1920 		hdrsiz = 0;
1921 		break;
1922 	}
1923 	hdrsiz += sizeof(struct tcphdr);
1924 	if (mss > hdrsiz)
1925 		mss -= hdrsiz;
1926 
1927 	mss = max(tcp_mssdflt, mss);
1928 	return (mss);
1929 }
1930 
1931 /*
1932  * Set connection variables based on the peer's advertised MSS.
1933  * We are passed the TCPCB for the actual connection.  If we
1934  * are the server, we are called by the compressed state engine
1935  * when the 3-way handshake is complete.  If we are the client,
1936  * we are called when we receive the SYN,ACK from the server.
1937  *
1938  * NOTE: Our advertised MSS value must be initialized in the TCPCB
1939  * before this routine is called!
1940  */
1941 void
1942 tcp_mss_from_peer(struct tcpcb *tp, int offer)
1943 {
1944 	struct socket *so;
1945 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1946 	struct rtentry *rt;
1947 #endif
1948 	u_long bufsize;
1949 	int mss;
1950 
1951 #ifdef DIAGNOSTIC
1952 	if (tp->t_inpcb && tp->t_in6pcb)
1953 		panic("tcp_mss_from_peer: both t_inpcb and t_in6pcb are set");
1954 #endif
1955 	so = NULL;
1956 	rt = NULL;
1957 #ifdef INET
1958 	if (tp->t_inpcb) {
1959 		so = tp->t_inpcb->inp_socket;
1960 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1961 		rt = in_pcbrtentry(tp->t_inpcb);
1962 #endif
1963 	}
1964 #endif
1965 #ifdef INET6
1966 	if (tp->t_in6pcb) {
1967 		so = tp->t_in6pcb->in6p_socket;
1968 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1969 		rt = in6_pcbrtentry(tp->t_in6pcb);
1970 #endif
1971 	}
1972 #endif
1973 
1974 	/*
1975 	 * As per RFC1122, use the default MSS value, unless they
1976 	 * sent us an offer.  Do not accept offers less than 256 bytes.
1977 	 */
1978 	mss = tcp_mssdflt;
1979 	if (offer)
1980 		mss = offer;
1981 	mss = max(mss, 256);		/* sanity */
1982 	tp->t_peermss = mss;
1983 	mss -= tcp_optlen(tp);
1984 #ifdef INET
1985 	if (tp->t_inpcb)
1986 		mss -= ip_optlen(tp->t_inpcb);
1987 #endif
1988 #ifdef INET6
1989 	if (tp->t_in6pcb)
1990 		mss -= ip6_optlen(tp->t_in6pcb);
1991 #endif
1992 
1993 	/*
1994 	 * If there's a pipesize, change the socket buffer to that size.
1995 	 * Make the socket buffer an integral number of MSS units.  If
1996 	 * the MSS is larger than the socket buffer, artificially decrease
1997 	 * the MSS.
1998 	 */
1999 #ifdef RTV_SPIPE
2000 	if (rt != NULL && rt->rt_rmx.rmx_sendpipe != 0)
2001 		bufsize = rt->rt_rmx.rmx_sendpipe;
2002 	else
2003 #endif
2004 	{
2005 		KASSERT(so != NULL);
2006 		bufsize = so->so_snd.sb_hiwat;
2007 	}
2008 	if (bufsize < mss)
2009 		mss = bufsize;
2010 	else {
2011 		bufsize = roundup(bufsize, mss);
2012 		if (bufsize > sb_max)
2013 			bufsize = sb_max;
2014 		(void) sbreserve(&so->so_snd, bufsize, so);
2015 	}
2016 	tp->t_segsz = mss;
2017 
2018 #ifdef RTV_SSTHRESH
2019 	if (rt != NULL && rt->rt_rmx.rmx_ssthresh) {
2020 		/*
2021 		 * There's some sort of gateway or interface buffer
2022 		 * limit on the path.  Use this to set the slow
2023 		 * start threshold, but set the threshold to no less
2024 		 * than 2 * MSS.
2025 		 */
2026 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2027 	}
2028 #endif
2029 }
2030 
2031 /*
2032  * Processing necessary when a TCP connection is established.
2033  */
2034 void
2035 tcp_established(struct tcpcb *tp)
2036 {
2037 	struct socket *so;
2038 #ifdef RTV_RPIPE
2039 	struct rtentry *rt;
2040 #endif
2041 	u_long bufsize;
2042 
2043 #ifdef DIAGNOSTIC
2044 	if (tp->t_inpcb && tp->t_in6pcb)
2045 		panic("tcp_established: both t_inpcb and t_in6pcb are set");
2046 #endif
2047 	so = NULL;
2048 	rt = NULL;
2049 #ifdef INET
2050 	/* This is a while() to reduce the dreadful stairstepping below */
2051 	while (tp->t_inpcb) {
2052 		so = tp->t_inpcb->inp_socket;
2053 #if defined(RTV_RPIPE)
2054 		rt = in_pcbrtentry(tp->t_inpcb);
2055 #endif
2056 		if (__predict_true(tcp_msl_enable)) {
2057 			if (tp->t_inpcb->inp_laddr.s_addr == INADDR_LOOPBACK) {
2058 				tp->t_msl = tcp_msl_loop ? tcp_msl_loop : (TCPTV_MSL >> 2);
2059 				break;
2060 			}
2061 
2062 			if (__predict_false(tcp_rttlocal)) {
2063 				/* This may be adjusted by tcp_input */
2064 				tp->t_msl = tcp_msl_local ? tcp_msl_local : (TCPTV_MSL >> 1);
2065 				break;
2066 			}
2067 			if (in_localaddr(tp->t_inpcb->inp_faddr)) {
2068 				tp->t_msl = tcp_msl_local ? tcp_msl_local : (TCPTV_MSL >> 1);
2069 				break;
2070 			}
2071 		}
2072 		tp->t_msl = tcp_msl_remote ? tcp_msl_remote : TCPTV_MSL;
2073 		break;
2074 	}
2075 #endif
2076 #ifdef INET6
2077 	/* The !tp->t_inpcb lets the compiler know it can't be v4 *and* v6 */
2078 	while (!tp->t_inpcb && tp->t_in6pcb) {
2079 		so = tp->t_in6pcb->in6p_socket;
2080 #if defined(RTV_RPIPE)
2081 		rt = in6_pcbrtentry(tp->t_in6pcb);
2082 #endif
2083 		if (__predict_true(tcp_msl_enable)) {
2084 			extern const struct in6_addr in6addr_loopback;
2085 
2086 			if (IN6_ARE_ADDR_EQUAL(&tp->t_in6pcb->in6p_laddr,
2087 					       &in6addr_loopback)) {
2088 				tp->t_msl = tcp_msl_loop ? tcp_msl_loop : (TCPTV_MSL >> 2);
2089 				break;
2090 			}
2091 
2092 			if (__predict_false(tcp_rttlocal)) {
2093 				/* This may be adjusted by tcp_input */
2094 				tp->t_msl = tcp_msl_local ? tcp_msl_local : (TCPTV_MSL >> 1);
2095 				break;
2096 			}
2097 			if (in6_localaddr(&tp->t_in6pcb->in6p_faddr)) {
2098 				tp->t_msl = tcp_msl_local ? tcp_msl_local : (TCPTV_MSL >> 1);
2099 				break;
2100 			}
2101 		}
2102 		tp->t_msl = tcp_msl_remote ? tcp_msl_remote : TCPTV_MSL;
2103 		break;
2104 	}
2105 #endif
2106 
2107 	tp->t_state = TCPS_ESTABLISHED;
2108 	TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepidle);
2109 
2110 #ifdef RTV_RPIPE
2111 	if (rt != NULL && rt->rt_rmx.rmx_recvpipe != 0)
2112 		bufsize = rt->rt_rmx.rmx_recvpipe;
2113 	else
2114 #endif
2115 	{
2116 		KASSERT(so != NULL);
2117 		bufsize = so->so_rcv.sb_hiwat;
2118 	}
2119 	if (bufsize > tp->t_ourmss) {
2120 		bufsize = roundup(bufsize, tp->t_ourmss);
2121 		if (bufsize > sb_max)
2122 			bufsize = sb_max;
2123 		(void) sbreserve(&so->so_rcv, bufsize, so);
2124 	}
2125 }
2126 
2127 /*
2128  * Check if there's an initial rtt or rttvar.  Convert from the
2129  * route-table units to scaled multiples of the slow timeout timer.
2130  * Called only during the 3-way handshake.
2131  */
2132 void
2133 tcp_rmx_rtt(struct tcpcb *tp)
2134 {
2135 #ifdef RTV_RTT
2136 	struct rtentry *rt = NULL;
2137 	int rtt;
2138 
2139 #ifdef DIAGNOSTIC
2140 	if (tp->t_inpcb && tp->t_in6pcb)
2141 		panic("tcp_rmx_rtt: both t_inpcb and t_in6pcb are set");
2142 #endif
2143 #ifdef INET
2144 	if (tp->t_inpcb)
2145 		rt = in_pcbrtentry(tp->t_inpcb);
2146 #endif
2147 #ifdef INET6
2148 	if (tp->t_in6pcb)
2149 		rt = in6_pcbrtentry(tp->t_in6pcb);
2150 #endif
2151 	if (rt == NULL)
2152 		return;
2153 
2154 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2155 		/*
2156 		 * XXX The lock bit for MTU indicates that the value
2157 		 * is also a minimum value; this is subject to time.
2158 		 */
2159 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
2160 			TCPT_RANGESET(tp->t_rttmin,
2161 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
2162 			    TCPTV_MIN, TCPTV_REXMTMAX);
2163 		tp->t_srtt = rtt /
2164 		    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
2165 		if (rt->rt_rmx.rmx_rttvar) {
2166 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2167 			    ((RTM_RTTUNIT / PR_SLOWHZ) >>
2168 				(TCP_RTTVAR_SHIFT + 2));
2169 		} else {
2170 			/* Default variation is +- 1 rtt */
2171 			tp->t_rttvar =
2172 			    tp->t_srtt >> (TCP_RTT_SHIFT - TCP_RTTVAR_SHIFT);
2173 		}
2174 		TCPT_RANGESET(tp->t_rxtcur,
2175 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2),
2176 		    tp->t_rttmin, TCPTV_REXMTMAX);
2177 	}
2178 #endif
2179 }
2180 
2181 tcp_seq	 tcp_iss_seq = 0;	/* tcp initial seq # */
2182 #if NRND > 0
2183 u_int8_t tcp_iss_secret[16];	/* 128 bits; should be plenty */
2184 #endif
2185 
2186 /*
2187  * Get a new sequence value given a tcp control block
2188  */
2189 tcp_seq
2190 tcp_new_iss(struct tcpcb *tp, tcp_seq addin)
2191 {
2192 
2193 #ifdef INET
2194 	if (tp->t_inpcb != NULL) {
2195 		return (tcp_new_iss1(&tp->t_inpcb->inp_laddr,
2196 		    &tp->t_inpcb->inp_faddr, tp->t_inpcb->inp_lport,
2197 		    tp->t_inpcb->inp_fport, sizeof(tp->t_inpcb->inp_laddr),
2198 		    addin));
2199 	}
2200 #endif
2201 #ifdef INET6
2202 	if (tp->t_in6pcb != NULL) {
2203 		return (tcp_new_iss1(&tp->t_in6pcb->in6p_laddr,
2204 		    &tp->t_in6pcb->in6p_faddr, tp->t_in6pcb->in6p_lport,
2205 		    tp->t_in6pcb->in6p_fport, sizeof(tp->t_in6pcb->in6p_laddr),
2206 		    addin));
2207 	}
2208 #endif
2209 	/* Not possible. */
2210 	panic("tcp_new_iss");
2211 }
2212 
2213 /*
2214  * This routine actually generates a new TCP initial sequence number.
2215  */
2216 tcp_seq
2217 tcp_new_iss1(void *laddr, void *faddr, u_int16_t lport, u_int16_t fport,
2218     size_t addrsz, tcp_seq addin)
2219 {
2220 	tcp_seq tcp_iss;
2221 
2222 #if NRND > 0
2223 	static bool tcp_iss_gotten_secret;
2224 
2225 	/*
2226 	 * If we haven't been here before, initialize our cryptographic
2227 	 * hash secret.
2228 	 */
2229 	if (tcp_iss_gotten_secret == false) {
2230 		rnd_extract_data(tcp_iss_secret, sizeof(tcp_iss_secret),
2231 		    RND_EXTRACT_ANY);
2232 		tcp_iss_gotten_secret = true;
2233 	}
2234 
2235 	if (tcp_do_rfc1948) {
2236 		MD5_CTX ctx;
2237 		u_int8_t hash[16];	/* XXX MD5 knowledge */
2238 
2239 		/*
2240 		 * Compute the base value of the ISS.  It is a hash
2241 		 * of (saddr, sport, daddr, dport, secret).
2242 		 */
2243 		MD5Init(&ctx);
2244 
2245 		MD5Update(&ctx, (u_char *) laddr, addrsz);
2246 		MD5Update(&ctx, (u_char *) &lport, sizeof(lport));
2247 
2248 		MD5Update(&ctx, (u_char *) faddr, addrsz);
2249 		MD5Update(&ctx, (u_char *) &fport, sizeof(fport));
2250 
2251 		MD5Update(&ctx, tcp_iss_secret, sizeof(tcp_iss_secret));
2252 
2253 		MD5Final(hash, &ctx);
2254 
2255 		memcpy(&tcp_iss, hash, sizeof(tcp_iss));
2256 
2257 		/*
2258 		 * Now increment our "timer", and add it in to
2259 		 * the computed value.
2260 		 *
2261 		 * XXX Use `addin'?
2262 		 * XXX TCP_ISSINCR too large to use?
2263 		 */
2264 		tcp_iss_seq += TCP_ISSINCR;
2265 #ifdef TCPISS_DEBUG
2266 		printf("ISS hash 0x%08x, ", tcp_iss);
2267 #endif
2268 		tcp_iss += tcp_iss_seq + addin;
2269 #ifdef TCPISS_DEBUG
2270 		printf("new ISS 0x%08x\n", tcp_iss);
2271 #endif
2272 	} else
2273 #endif /* NRND > 0 */
2274 	{
2275 		/*
2276 		 * Randomize.
2277 		 */
2278 #if NRND > 0
2279 		rnd_extract_data(&tcp_iss, sizeof(tcp_iss), RND_EXTRACT_ANY);
2280 #else
2281 		tcp_iss = arc4random();
2282 #endif
2283 
2284 		/*
2285 		 * If we were asked to add some amount to a known value,
2286 		 * we will take a random value obtained above, mask off
2287 		 * the upper bits, and add in the known value.  We also
2288 		 * add in a constant to ensure that we are at least a
2289 		 * certain distance from the original value.
2290 		 *
2291 		 * This is used when an old connection is in timed wait
2292 		 * and we have a new one coming in, for instance.
2293 		 */
2294 		if (addin != 0) {
2295 #ifdef TCPISS_DEBUG
2296 			printf("Random %08x, ", tcp_iss);
2297 #endif
2298 			tcp_iss &= TCP_ISS_RANDOM_MASK;
2299 			tcp_iss += addin + TCP_ISSINCR;
2300 #ifdef TCPISS_DEBUG
2301 			printf("Old ISS %08x, ISS %08x\n", addin, tcp_iss);
2302 #endif
2303 		} else {
2304 			tcp_iss &= TCP_ISS_RANDOM_MASK;
2305 			tcp_iss += tcp_iss_seq;
2306 			tcp_iss_seq += TCP_ISSINCR;
2307 #ifdef TCPISS_DEBUG
2308 			printf("ISS %08x\n", tcp_iss);
2309 #endif
2310 		}
2311 	}
2312 
2313 	if (tcp_compat_42) {
2314 		/*
2315 		 * Limit it to the positive range for really old TCP
2316 		 * implementations.
2317 		 * Just AND off the top bit instead of checking if
2318 		 * is set first - saves a branch 50% of the time.
2319 		 */
2320 		tcp_iss &= 0x7fffffff;		/* XXX */
2321 	}
2322 
2323 	return (tcp_iss);
2324 }
2325 
2326 #if defined(IPSEC) || defined(FAST_IPSEC)
2327 /* compute ESP/AH header size for TCP, including outer IP header. */
2328 size_t
2329 ipsec4_hdrsiz_tcp(struct tcpcb *tp)
2330 {
2331 	struct inpcb *inp;
2332 	size_t hdrsiz;
2333 
2334 	/* XXX mapped addr case (tp->t_in6pcb) */
2335 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
2336 		return 0;
2337 	switch (tp->t_family) {
2338 	case AF_INET:
2339 		/* XXX: should use currect direction. */
2340 		hdrsiz = ipsec4_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, inp);
2341 		break;
2342 	default:
2343 		hdrsiz = 0;
2344 		break;
2345 	}
2346 
2347 	return hdrsiz;
2348 }
2349 
2350 #ifdef INET6
2351 size_t
2352 ipsec6_hdrsiz_tcp(struct tcpcb *tp)
2353 {
2354 	struct in6pcb *in6p;
2355 	size_t hdrsiz;
2356 
2357 	if (!tp || !tp->t_template || !(in6p = tp->t_in6pcb))
2358 		return 0;
2359 	switch (tp->t_family) {
2360 	case AF_INET6:
2361 		/* XXX: should use currect direction. */
2362 		hdrsiz = ipsec6_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, in6p);
2363 		break;
2364 	case AF_INET:
2365 		/* mapped address case - tricky */
2366 	default:
2367 		hdrsiz = 0;
2368 		break;
2369 	}
2370 
2371 	return hdrsiz;
2372 }
2373 #endif
2374 #endif /*IPSEC*/
2375 
2376 /*
2377  * Determine the length of the TCP options for this connection.
2378  *
2379  * XXX:  What do we do for SACK, when we add that?  Just reserve
2380  *       all of the space?  Otherwise we can't exactly be incrementing
2381  *       cwnd by an amount that varies depending on the amount we last
2382  *       had to SACK!
2383  */
2384 
2385 u_int
2386 tcp_optlen(struct tcpcb *tp)
2387 {
2388 	u_int optlen;
2389 
2390 	optlen = 0;
2391 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
2392 	    (TF_REQ_TSTMP | TF_RCVD_TSTMP))
2393 		optlen += TCPOLEN_TSTAMP_APPA;
2394 
2395 #ifdef TCP_SIGNATURE
2396 	if (tp->t_flags & TF_SIGNATURE)
2397 		optlen += TCPOLEN_SIGNATURE + 2;
2398 #endif /* TCP_SIGNATURE */
2399 
2400 	return optlen;
2401 }
2402 
2403 u_int
2404 tcp_hdrsz(struct tcpcb *tp)
2405 {
2406 	u_int hlen;
2407 
2408 	switch (tp->t_family) {
2409 #ifdef INET6
2410 	case AF_INET6:
2411 		hlen = sizeof(struct ip6_hdr);
2412 		break;
2413 #endif
2414 	case AF_INET:
2415 		hlen = sizeof(struct ip);
2416 		break;
2417 	default:
2418 		hlen = 0;
2419 		break;
2420 	}
2421 	hlen += sizeof(struct tcphdr);
2422 
2423 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2424 	    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
2425 		hlen += TCPOLEN_TSTAMP_APPA;
2426 #ifdef TCP_SIGNATURE
2427 	if (tp->t_flags & TF_SIGNATURE)
2428 		hlen += TCPOLEN_SIGLEN;
2429 #endif
2430 	return hlen;
2431 }
2432 
2433 void
2434 tcp_statinc(u_int stat)
2435 {
2436 
2437 	KASSERT(stat < TCP_NSTATS);
2438 	TCP_STATINC(stat);
2439 }
2440 
2441 void
2442 tcp_statadd(u_int stat, uint64_t val)
2443 {
2444 
2445 	KASSERT(stat < TCP_NSTATS);
2446 	TCP_STATADD(stat, val);
2447 }
2448