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