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