xref: /netbsd-src/sys/netinet/tcp_subr.c (revision 1921cb5602567cfc8401cc953be22fe9d74238f2)
1 /*	$NetBSD: tcp_subr.c,v 1.200 2006/10/05 17:35:19 tls 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.200 2006/10/05 17:35:19 tls 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);	/* splsoftnet via tcp_usrreq */
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);	/* splsoftnet via tcp_usrreq */
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);	/* splsoftnet via tcp_timer.c */
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 	int s;
1122 
1123 	inp = tp->t_inpcb;
1124 #ifdef INET6
1125 	in6p = tp->t_in6pcb;
1126 #endif
1127 	so = NULL;
1128 	ro = NULL;
1129 	if (inp) {
1130 		so = inp->inp_socket;
1131 		ro = &inp->inp_route;
1132 	}
1133 #ifdef INET6
1134 	else if (in6p) {
1135 		so = in6p->in6p_socket;
1136 		ro = (struct route *)&in6p->in6p_route;
1137 	}
1138 #endif
1139 
1140 #ifdef RTV_RTT
1141 	/*
1142 	 * If we sent enough data to get some meaningful characteristics,
1143 	 * save them in the routing entry.  'Enough' is arbitrarily
1144 	 * defined as the sendpipesize (default 4K) * 16.  This would
1145 	 * give us 16 rtt samples assuming we only get one sample per
1146 	 * window (the usual case on a long haul net).  16 samples is
1147 	 * enough for the srtt filter to converge to within 5% of the correct
1148 	 * value; fewer samples and we could save a very bogus rtt.
1149 	 *
1150 	 * Don't update the default route's characteristics and don't
1151 	 * update anything that the user "locked".
1152 	 */
1153 	if (SEQ_LT(tp->iss + so->so_snd.sb_hiwat * 16, tp->snd_max) &&
1154 	    ro && (rt = ro->ro_rt) &&
1155 	    !in_nullhost(satosin(rt_key(rt))->sin_addr)) {
1156 		u_long i = 0;
1157 
1158 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
1159 			i = tp->t_srtt *
1160 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
1161 			if (rt->rt_rmx.rmx_rtt && i)
1162 				/*
1163 				 * filter this update to half the old & half
1164 				 * the new values, converting scale.
1165 				 * See route.h and tcp_var.h for a
1166 				 * description of the scaling constants.
1167 				 */
1168 				rt->rt_rmx.rmx_rtt =
1169 				    (rt->rt_rmx.rmx_rtt + i) / 2;
1170 			else
1171 				rt->rt_rmx.rmx_rtt = i;
1172 		}
1173 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
1174 			i = tp->t_rttvar *
1175 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTTVAR_SHIFT + 2));
1176 			if (rt->rt_rmx.rmx_rttvar && i)
1177 				rt->rt_rmx.rmx_rttvar =
1178 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
1179 			else
1180 				rt->rt_rmx.rmx_rttvar = i;
1181 		}
1182 		/*
1183 		 * update the pipelimit (ssthresh) if it has been updated
1184 		 * already or if a pipesize was specified & the threshhold
1185 		 * got below half the pipesize.  I.e., wait for bad news
1186 		 * before we start updating, then update on both good
1187 		 * and bad news.
1188 		 */
1189 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
1190 		    (i = tp->snd_ssthresh) && rt->rt_rmx.rmx_ssthresh) ||
1191 		    i < (rt->rt_rmx.rmx_sendpipe / 2)) {
1192 			/*
1193 			 * convert the limit from user data bytes to
1194 			 * packets then to packet data bytes.
1195 			 */
1196 			i = (i + tp->t_segsz / 2) / tp->t_segsz;
1197 			if (i < 2)
1198 				i = 2;
1199 			i *= (u_long)(tp->t_segsz + sizeof (struct tcpiphdr));
1200 			if (rt->rt_rmx.rmx_ssthresh)
1201 				rt->rt_rmx.rmx_ssthresh =
1202 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
1203 			else
1204 				rt->rt_rmx.rmx_ssthresh = i;
1205 		}
1206 	}
1207 #endif /* RTV_RTT */
1208 	/* free the reassembly queue, if any */
1209 	TCP_REASS_LOCK(tp);
1210 	(void) tcp_freeq(tp);
1211 	TCP_REASS_UNLOCK(tp);
1212 
1213 	/* free the SACK holes list. */
1214 	tcp_free_sackholes(tp);
1215 
1216 	tcp_canceltimers(tp);
1217 	TCP_CLEAR_DELACK(tp);
1218 	syn_cache_cleanup(tp);
1219 
1220 	if (tp->t_template) {
1221 		m_free(tp->t_template);
1222 		tp->t_template = NULL;
1223 	}
1224 	if (tcp_timers_invoking(tp))
1225 		tp->t_flags |= TF_DEAD;
1226 	else
1227 	{
1228 		s = splsoftnet(); /* do we trust all callers of tcp_close()? */
1229 		pool_put(&tcpcb_pool, tp);
1230 		splx(s);
1231 	}
1232 
1233 	if (inp) {
1234 		inp->inp_ppcb = 0;
1235 		soisdisconnected(so);
1236 		in_pcbdetach(inp);
1237 	}
1238 #ifdef INET6
1239 	else if (in6p) {
1240 		in6p->in6p_ppcb = 0;
1241 		soisdisconnected(so);
1242 		in6_pcbdetach(in6p);
1243 	}
1244 #endif
1245 	tcpstat.tcps_closed++;
1246 	return ((struct tcpcb *)0);
1247 }
1248 
1249 int
1250 tcp_freeq(tp)
1251 	struct tcpcb *tp;
1252 {
1253 	struct ipqent *qe;
1254 	int rv = 0;
1255 #ifdef TCPREASS_DEBUG
1256 	int i = 0;
1257 #endif
1258 
1259 	TCP_REASS_LOCK_CHECK(tp);
1260 
1261 	while ((qe = TAILQ_FIRST(&tp->segq)) != NULL) {
1262 #ifdef TCPREASS_DEBUG
1263 		printf("tcp_freeq[%p,%d]: %u:%u(%u) 0x%02x\n",
1264 			tp, i++, qe->ipqe_seq, qe->ipqe_seq + qe->ipqe_len,
1265 			qe->ipqe_len, qe->ipqe_flags & (TH_SYN|TH_FIN|TH_RST));
1266 #endif
1267 		TAILQ_REMOVE(&tp->segq, qe, ipqe_q);
1268 		TAILQ_REMOVE(&tp->timeq, qe, ipqe_timeq);
1269 		m_freem(qe->ipqe_m);
1270 		tcpipqent_free(qe);
1271 		rv = 1;
1272 	}
1273 	tp->t_segqlen = 0;
1274 	KASSERT(TAILQ_EMPTY(&tp->timeq));
1275 	return (rv);
1276 }
1277 
1278 /*
1279  * Protocol drain routine.  Called when memory is in short supply.
1280  */
1281 void
1282 tcp_drain(void)
1283 {
1284 	struct inpcb_hdr *inph;
1285 	struct tcpcb *tp;
1286 
1287 	/*
1288 	 * Free the sequence queue of all TCP connections.
1289 	 */
1290 	CIRCLEQ_FOREACH(inph, &tcbtable.inpt_queue, inph_queue) {
1291 		switch (inph->inph_af) {
1292 		case AF_INET:
1293 			tp = intotcpcb((struct inpcb *)inph);
1294 			break;
1295 #ifdef INET6
1296 		case AF_INET6:
1297 			tp = in6totcpcb((struct in6pcb *)inph);
1298 			break;
1299 #endif
1300 		default:
1301 			tp = NULL;
1302 			break;
1303 		}
1304 		if (tp != NULL) {
1305 			/*
1306 			 * We may be called from a device's interrupt
1307 			 * context.  If the tcpcb is already busy,
1308 			 * just bail out now.
1309 			 */
1310 			if (tcp_reass_lock_try(tp) == 0)
1311 				continue;
1312 			if (tcp_freeq(tp))
1313 				tcpstat.tcps_connsdrained++;
1314 			TCP_REASS_UNLOCK(tp);
1315 		}
1316 	}
1317 }
1318 
1319 /*
1320  * Notify a tcp user of an asynchronous error;
1321  * store error as soft error, but wake up user
1322  * (for now, won't do anything until can select for soft error).
1323  */
1324 void
1325 tcp_notify(struct inpcb *inp, int error)
1326 {
1327 	struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
1328 	struct socket *so = inp->inp_socket;
1329 
1330 	/*
1331 	 * Ignore some errors if we are hooked up.
1332 	 * If connection hasn't completed, has retransmitted several times,
1333 	 * and receives a second error, give up now.  This is better
1334 	 * than waiting a long time to establish a connection that
1335 	 * can never complete.
1336 	 */
1337 	if (tp->t_state == TCPS_ESTABLISHED &&
1338 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1339 	      error == EHOSTDOWN)) {
1340 		return;
1341 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1342 	    tp->t_rxtshift > 3 && tp->t_softerror)
1343 		so->so_error = error;
1344 	else
1345 		tp->t_softerror = error;
1346 	wakeup((caddr_t) &so->so_timeo);
1347 	sorwakeup(so);
1348 	sowwakeup(so);
1349 }
1350 
1351 #ifdef INET6
1352 void
1353 tcp6_notify(struct in6pcb *in6p, int error)
1354 {
1355 	struct tcpcb *tp = (struct tcpcb *)in6p->in6p_ppcb;
1356 	struct socket *so = in6p->in6p_socket;
1357 
1358 	/*
1359 	 * Ignore some errors if we are hooked up.
1360 	 * If connection hasn't completed, has retransmitted several times,
1361 	 * and receives a second error, give up now.  This is better
1362 	 * than waiting a long time to establish a connection that
1363 	 * can never complete.
1364 	 */
1365 	if (tp->t_state == TCPS_ESTABLISHED &&
1366 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1367 	      error == EHOSTDOWN)) {
1368 		return;
1369 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1370 	    tp->t_rxtshift > 3 && tp->t_softerror)
1371 		so->so_error = error;
1372 	else
1373 		tp->t_softerror = error;
1374 	wakeup((caddr_t) &so->so_timeo);
1375 	sorwakeup(so);
1376 	sowwakeup(so);
1377 }
1378 #endif
1379 
1380 #ifdef INET6
1381 void
1382 tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
1383 {
1384 	struct tcphdr th;
1385 	void (*notify)(struct in6pcb *, int) = tcp6_notify;
1386 	int nmatch;
1387 	struct ip6_hdr *ip6;
1388 	const struct sockaddr_in6 *sa6_src = NULL;
1389 	struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
1390 	struct mbuf *m;
1391 	int off;
1392 
1393 	if (sa->sa_family != AF_INET6 ||
1394 	    sa->sa_len != sizeof(struct sockaddr_in6))
1395 		return;
1396 	if ((unsigned)cmd >= PRC_NCMDS)
1397 		return;
1398 	else if (cmd == PRC_QUENCH) {
1399 		/*
1400 		 * Don't honor ICMP Source Quench messages meant for
1401 		 * TCP connections.
1402 		 */
1403 		return;
1404 	} else if (PRC_IS_REDIRECT(cmd))
1405 		notify = in6_rtchange, d = NULL;
1406 	else if (cmd == PRC_MSGSIZE)
1407 		; /* special code is present, see below */
1408 	else if (cmd == PRC_HOSTDEAD)
1409 		d = NULL;
1410 	else if (inet6ctlerrmap[cmd] == 0)
1411 		return;
1412 
1413 	/* if the parameter is from icmp6, decode it. */
1414 	if (d != NULL) {
1415 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
1416 		m = ip6cp->ip6c_m;
1417 		ip6 = ip6cp->ip6c_ip6;
1418 		off = ip6cp->ip6c_off;
1419 		sa6_src = ip6cp->ip6c_src;
1420 	} else {
1421 		m = NULL;
1422 		ip6 = NULL;
1423 		sa6_src = &sa6_any;
1424 		off = 0;
1425 	}
1426 
1427 	if (ip6) {
1428 		/*
1429 		 * XXX: We assume that when ip6 is non NULL,
1430 		 * M and OFF are valid.
1431 		 */
1432 
1433 		/* check if we can safely examine src and dst ports */
1434 		if (m->m_pkthdr.len < off + sizeof(th)) {
1435 			if (cmd == PRC_MSGSIZE)
1436 				icmp6_mtudisc_update((struct ip6ctlparam *)d, 0);
1437 			return;
1438 		}
1439 
1440 		bzero(&th, sizeof(th));
1441 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
1442 
1443 		if (cmd == PRC_MSGSIZE) {
1444 			int valid = 0;
1445 
1446 			/*
1447 			 * Check to see if we have a valid TCP connection
1448 			 * corresponding to the address in the ICMPv6 message
1449 			 * payload.
1450 			 */
1451 			if (in6_pcblookup_connect(&tcbtable, &sa6->sin6_addr,
1452 			    th.th_dport, (const struct in6_addr *)&sa6_src->sin6_addr,
1453 			    th.th_sport, 0))
1454 				valid++;
1455 
1456 			/*
1457 			 * Depending on the value of "valid" and routing table
1458 			 * size (mtudisc_{hi,lo}wat), we will:
1459 			 * - recalcurate the new MTU and create the
1460 			 *   corresponding routing entry, or
1461 			 * - ignore the MTU change notification.
1462 			 */
1463 			icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
1464 
1465 			/*
1466 			 * no need to call in6_pcbnotify, it should have been
1467 			 * called via callback if necessary
1468 			 */
1469 			return;
1470 		}
1471 
1472 		nmatch = in6_pcbnotify(&tcbtable, sa, th.th_dport,
1473 		    (const struct sockaddr *)sa6_src, th.th_sport, cmd, NULL, notify);
1474 		if (nmatch == 0 && syn_cache_count &&
1475 		    (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
1476 		     inet6ctlerrmap[cmd] == ENETUNREACH ||
1477 		     inet6ctlerrmap[cmd] == EHOSTDOWN))
1478 			syn_cache_unreach((const struct sockaddr *)sa6_src,
1479 					  sa, &th);
1480 	} else {
1481 		(void) in6_pcbnotify(&tcbtable, sa, 0,
1482 		    (const struct sockaddr *)sa6_src, 0, cmd, NULL, notify);
1483 	}
1484 }
1485 #endif
1486 
1487 #ifdef INET
1488 /* assumes that ip header and tcp header are contiguous on mbuf */
1489 void *
1490 tcp_ctlinput(int cmd, struct sockaddr *sa, void *v)
1491 {
1492 	struct ip *ip = v;
1493 	struct tcphdr *th;
1494 	struct icmp *icp;
1495 	extern const int inetctlerrmap[];
1496 	void (*notify)(struct inpcb *, int) = tcp_notify;
1497 	int errno;
1498 	int nmatch;
1499 	struct tcpcb *tp;
1500 	u_int mtu;
1501 	tcp_seq seq;
1502 	struct inpcb *inp;
1503 #ifdef INET6
1504 	struct in6pcb *in6p;
1505 	struct in6_addr src6, dst6;
1506 #endif
1507 
1508 	if (sa->sa_family != AF_INET ||
1509 	    sa->sa_len != sizeof(struct sockaddr_in))
1510 		return NULL;
1511 	if ((unsigned)cmd >= PRC_NCMDS)
1512 		return NULL;
1513 	errno = inetctlerrmap[cmd];
1514 	if (cmd == PRC_QUENCH)
1515 		/*
1516 		 * Don't honor ICMP Source Quench messages meant for
1517 		 * TCP connections.
1518 		 */
1519 		return NULL;
1520 	else if (PRC_IS_REDIRECT(cmd))
1521 		notify = in_rtchange, ip = 0;
1522 	else if (cmd == PRC_MSGSIZE && ip && ip->ip_v == 4) {
1523 		/*
1524 		 * Check to see if we have a valid TCP connection
1525 		 * corresponding to the address in the ICMP message
1526 		 * payload.
1527 		 *
1528 		 * Boundary check is made in icmp_input(), with ICMP_ADVLENMIN.
1529 		 */
1530 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
1531 #ifdef INET6
1532 		memset(&src6, 0, sizeof(src6));
1533 		memset(&dst6, 0, sizeof(dst6));
1534 		src6.s6_addr16[5] = dst6.s6_addr16[5] = 0xffff;
1535 		memcpy(&src6.s6_addr32[3], &ip->ip_src, sizeof(struct in_addr));
1536 		memcpy(&dst6.s6_addr32[3], &ip->ip_dst, sizeof(struct in_addr));
1537 #endif
1538 		if ((inp = in_pcblookup_connect(&tcbtable, ip->ip_dst,
1539 		    th->th_dport, ip->ip_src, th->th_sport)) != NULL)
1540 #ifdef INET6
1541 			in6p = NULL;
1542 #else
1543 			;
1544 #endif
1545 #ifdef INET6
1546 		else if ((in6p = in6_pcblookup_connect(&tcbtable, &dst6,
1547 		    th->th_dport, &src6, th->th_sport, 0)) != NULL)
1548 			;
1549 #endif
1550 		else
1551 			return NULL;
1552 
1553 		/*
1554 		 * Now that we've validated that we are actually communicating
1555 		 * with the host indicated in the ICMP message, locate the
1556 		 * ICMP header, recalculate the new MTU, and create the
1557 		 * corresponding routing entry.
1558 		 */
1559 		icp = (struct icmp *)((caddr_t)ip -
1560 		    offsetof(struct icmp, icmp_ip));
1561 		if (inp) {
1562 			if ((tp = intotcpcb(inp)) == NULL)
1563 				return NULL;
1564 		}
1565 #ifdef INET6
1566 		else if (in6p) {
1567 			if ((tp = in6totcpcb(in6p)) == NULL)
1568 				return NULL;
1569 		}
1570 #endif
1571 		else
1572 			return NULL;
1573 		seq = ntohl(th->th_seq);
1574 		if (SEQ_LT(seq, tp->snd_una) || SEQ_GT(seq, tp->snd_max))
1575 			return NULL;
1576 		/*
1577 		 * If the ICMP message advertises a Next-Hop MTU
1578 		 * equal or larger than the maximum packet size we have
1579 		 * ever sent, drop the message.
1580 		 */
1581 		mtu = (u_int)ntohs(icp->icmp_nextmtu);
1582 		if (mtu >= tp->t_pmtud_mtu_sent)
1583 			return NULL;
1584 		if (mtu >= tcp_hdrsz(tp) + tp->t_pmtud_mss_acked) {
1585 			/*
1586 			 * Calculate new MTU, and create corresponding
1587 			 * route (traditional PMTUD).
1588 			 */
1589 			tp->t_flags &= ~TF_PMTUD_PEND;
1590 			icmp_mtudisc(icp, ip->ip_dst);
1591 		} else {
1592 			/*
1593 			 * Record the information got in the ICMP
1594 			 * message; act on it later.
1595 			 * If we had already recorded an ICMP message,
1596 			 * replace the old one only if the new message
1597 			 * refers to an older TCP segment
1598 			 */
1599 			if (tp->t_flags & TF_PMTUD_PEND) {
1600 				if (SEQ_LT(tp->t_pmtud_th_seq, seq))
1601 					return NULL;
1602 			} else
1603 				tp->t_flags |= TF_PMTUD_PEND;
1604 			tp->t_pmtud_th_seq = seq;
1605 			tp->t_pmtud_nextmtu = icp->icmp_nextmtu;
1606 			tp->t_pmtud_ip_len = icp->icmp_ip.ip_len;
1607 			tp->t_pmtud_ip_hl = icp->icmp_ip.ip_hl;
1608 		}
1609 		return NULL;
1610 	} else if (cmd == PRC_HOSTDEAD)
1611 		ip = 0;
1612 	else if (errno == 0)
1613 		return NULL;
1614 	if (ip && ip->ip_v == 4 && sa->sa_family == AF_INET) {
1615 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
1616 		nmatch = in_pcbnotify(&tcbtable, satosin(sa)->sin_addr,
1617 		    th->th_dport, ip->ip_src, th->th_sport, errno, notify);
1618 		if (nmatch == 0 && syn_cache_count &&
1619 		    (inetctlerrmap[cmd] == EHOSTUNREACH ||
1620 		    inetctlerrmap[cmd] == ENETUNREACH ||
1621 		    inetctlerrmap[cmd] == EHOSTDOWN)) {
1622 			struct sockaddr_in sin;
1623 			bzero(&sin, sizeof(sin));
1624 			sin.sin_len = sizeof(sin);
1625 			sin.sin_family = AF_INET;
1626 			sin.sin_port = th->th_sport;
1627 			sin.sin_addr = ip->ip_src;
1628 			syn_cache_unreach((struct sockaddr *)&sin, sa, th);
1629 		}
1630 
1631 		/* XXX mapped address case */
1632 	} else
1633 		in_pcbnotifyall(&tcbtable, satosin(sa)->sin_addr, errno,
1634 		    notify);
1635 	return NULL;
1636 }
1637 
1638 /*
1639  * When a source quench is received, we are being notified of congestion.
1640  * Close the congestion window down to the Loss Window (one segment).
1641  * We will gradually open it again as we proceed.
1642  */
1643 void
1644 tcp_quench(struct inpcb *inp, int errno)
1645 {
1646 	struct tcpcb *tp = intotcpcb(inp);
1647 
1648 	if (tp)
1649 		tp->snd_cwnd = tp->t_segsz;
1650 }
1651 #endif
1652 
1653 #ifdef INET6
1654 void
1655 tcp6_quench(struct in6pcb *in6p, int errno)
1656 {
1657 	struct tcpcb *tp = in6totcpcb(in6p);
1658 
1659 	if (tp)
1660 		tp->snd_cwnd = tp->t_segsz;
1661 }
1662 #endif
1663 
1664 #ifdef INET
1665 /*
1666  * Path MTU Discovery handlers.
1667  */
1668 void
1669 tcp_mtudisc_callback(struct in_addr faddr)
1670 {
1671 #ifdef INET6
1672 	struct in6_addr in6;
1673 #endif
1674 
1675 	in_pcbnotifyall(&tcbtable, faddr, EMSGSIZE, tcp_mtudisc);
1676 #ifdef INET6
1677 	memset(&in6, 0, sizeof(in6));
1678 	in6.s6_addr16[5] = 0xffff;
1679 	memcpy(&in6.s6_addr32[3], &faddr, sizeof(struct in_addr));
1680 	tcp6_mtudisc_callback(&in6);
1681 #endif
1682 }
1683 
1684 /*
1685  * On receipt of path MTU corrections, flush old route and replace it
1686  * with the new one.  Retransmit all unacknowledged packets, to ensure
1687  * that all packets will be received.
1688  */
1689 void
1690 tcp_mtudisc(struct inpcb *inp, int errno)
1691 {
1692 	struct tcpcb *tp = intotcpcb(inp);
1693 	struct rtentry *rt = in_pcbrtentry(inp);
1694 
1695 	if (tp != 0) {
1696 		if (rt != 0) {
1697 			/*
1698 			 * If this was not a host route, remove and realloc.
1699 			 */
1700 			if ((rt->rt_flags & RTF_HOST) == 0) {
1701 				in_rtchange(inp, errno);
1702 				if ((rt = in_pcbrtentry(inp)) == 0)
1703 					return;
1704 			}
1705 
1706 			/*
1707 			 * Slow start out of the error condition.  We
1708 			 * use the MTU because we know it's smaller
1709 			 * than the previously transmitted segment.
1710 			 *
1711 			 * Note: This is more conservative than the
1712 			 * suggestion in draft-floyd-incr-init-win-03.
1713 			 */
1714 			if (rt->rt_rmx.rmx_mtu != 0)
1715 				tp->snd_cwnd =
1716 				    TCP_INITIAL_WINDOW(tcp_init_win,
1717 				    rt->rt_rmx.rmx_mtu);
1718 		}
1719 
1720 		/*
1721 		 * Resend unacknowledged packets.
1722 		 */
1723 		tp->snd_nxt = tp->snd_una;
1724 		tcp_output(tp);
1725 	}
1726 }
1727 #endif
1728 
1729 #ifdef INET6
1730 /*
1731  * Path MTU Discovery handlers.
1732  */
1733 void
1734 tcp6_mtudisc_callback(struct in6_addr *faddr)
1735 {
1736 	struct sockaddr_in6 sin6;
1737 
1738 	bzero(&sin6, sizeof(sin6));
1739 	sin6.sin6_family = AF_INET6;
1740 	sin6.sin6_len = sizeof(struct sockaddr_in6);
1741 	sin6.sin6_addr = *faddr;
1742 	(void) in6_pcbnotify(&tcbtable, (struct sockaddr *)&sin6, 0,
1743 	    (const struct sockaddr *)&sa6_any, 0, PRC_MSGSIZE, NULL, tcp6_mtudisc);
1744 }
1745 
1746 void
1747 tcp6_mtudisc(struct in6pcb *in6p, int errno)
1748 {
1749 	struct tcpcb *tp = in6totcpcb(in6p);
1750 	struct rtentry *rt = in6_pcbrtentry(in6p);
1751 
1752 	if (tp != 0) {
1753 		if (rt != 0) {
1754 			/*
1755 			 * If this was not a host route, remove and realloc.
1756 			 */
1757 			if ((rt->rt_flags & RTF_HOST) == 0) {
1758 				in6_rtchange(in6p, errno);
1759 				if ((rt = in6_pcbrtentry(in6p)) == 0)
1760 					return;
1761 			}
1762 
1763 			/*
1764 			 * Slow start out of the error condition.  We
1765 			 * use the MTU because we know it's smaller
1766 			 * than the previously transmitted segment.
1767 			 *
1768 			 * Note: This is more conservative than the
1769 			 * suggestion in draft-floyd-incr-init-win-03.
1770 			 */
1771 			if (rt->rt_rmx.rmx_mtu != 0)
1772 				tp->snd_cwnd =
1773 				    TCP_INITIAL_WINDOW(tcp_init_win,
1774 				    rt->rt_rmx.rmx_mtu);
1775 		}
1776 
1777 		/*
1778 		 * Resend unacknowledged packets.
1779 		 */
1780 		tp->snd_nxt = tp->snd_una;
1781 		tcp_output(tp);
1782 	}
1783 }
1784 #endif /* INET6 */
1785 
1786 /*
1787  * Compute the MSS to advertise to the peer.  Called only during
1788  * the 3-way handshake.  If we are the server (peer initiated
1789  * connection), we are called with a pointer to the interface
1790  * on which the SYN packet arrived.  If we are the client (we
1791  * initiated connection), we are called with a pointer to the
1792  * interface out which this connection should go.
1793  *
1794  * NOTE: Do not subtract IP option/extension header size nor IPsec
1795  * header size from MSS advertisement.  MSS option must hold the maximum
1796  * segment size we can accept, so it must always be:
1797  *	 max(if mtu) - ip header - tcp header
1798  */
1799 u_long
1800 tcp_mss_to_advertise(const struct ifnet *ifp, int af)
1801 {
1802 	extern u_long in_maxmtu;
1803 	u_long mss = 0;
1804 	u_long hdrsiz;
1805 
1806 	/*
1807 	 * In order to avoid defeating path MTU discovery on the peer,
1808 	 * we advertise the max MTU of all attached networks as our MSS,
1809 	 * per RFC 1191, section 3.1.
1810 	 *
1811 	 * We provide the option to advertise just the MTU of
1812 	 * the interface on which we hope this connection will
1813 	 * be receiving.  If we are responding to a SYN, we
1814 	 * will have a pretty good idea about this, but when
1815 	 * initiating a connection there is a bit more doubt.
1816 	 *
1817 	 * We also need to ensure that loopback has a large enough
1818 	 * MSS, as the loopback MTU is never included in in_maxmtu.
1819 	 */
1820 
1821 	if (ifp != NULL)
1822 		switch (af) {
1823 		case AF_INET:
1824 			mss = ifp->if_mtu;
1825 			break;
1826 #ifdef INET6
1827 		case AF_INET6:
1828 			mss = IN6_LINKMTU(ifp);
1829 			break;
1830 #endif
1831 		}
1832 
1833 	if (tcp_mss_ifmtu == 0)
1834 		switch (af) {
1835 		case AF_INET:
1836 			mss = max(in_maxmtu, mss);
1837 			break;
1838 #ifdef INET6
1839 		case AF_INET6:
1840 			mss = max(in6_maxmtu, mss);
1841 			break;
1842 #endif
1843 		}
1844 
1845 	switch (af) {
1846 	case AF_INET:
1847 		hdrsiz = sizeof(struct ip);
1848 		break;
1849 #ifdef INET6
1850 	case AF_INET6:
1851 		hdrsiz = sizeof(struct ip6_hdr);
1852 		break;
1853 #endif
1854 	default:
1855 		hdrsiz = 0;
1856 		break;
1857 	}
1858 	hdrsiz += sizeof(struct tcphdr);
1859 	if (mss > hdrsiz)
1860 		mss -= hdrsiz;
1861 
1862 	mss = max(tcp_mssdflt, mss);
1863 	return (mss);
1864 }
1865 
1866 /*
1867  * Set connection variables based on the peer's advertised MSS.
1868  * We are passed the TCPCB for the actual connection.  If we
1869  * are the server, we are called by the compressed state engine
1870  * when the 3-way handshake is complete.  If we are the client,
1871  * we are called when we receive the SYN,ACK from the server.
1872  *
1873  * NOTE: Our advertised MSS value must be initialized in the TCPCB
1874  * before this routine is called!
1875  */
1876 void
1877 tcp_mss_from_peer(struct tcpcb *tp, int offer)
1878 {
1879 	struct socket *so;
1880 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1881 	struct rtentry *rt;
1882 #endif
1883 	u_long bufsize;
1884 	int mss;
1885 
1886 #ifdef DIAGNOSTIC
1887 	if (tp->t_inpcb && tp->t_in6pcb)
1888 		panic("tcp_mss_from_peer: both t_inpcb and t_in6pcb are set");
1889 #endif
1890 	so = NULL;
1891 	rt = NULL;
1892 #ifdef INET
1893 	if (tp->t_inpcb) {
1894 		so = tp->t_inpcb->inp_socket;
1895 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1896 		rt = in_pcbrtentry(tp->t_inpcb);
1897 #endif
1898 	}
1899 #endif
1900 #ifdef INET6
1901 	if (tp->t_in6pcb) {
1902 		so = tp->t_in6pcb->in6p_socket;
1903 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1904 		rt = in6_pcbrtentry(tp->t_in6pcb);
1905 #endif
1906 	}
1907 #endif
1908 
1909 	/*
1910 	 * As per RFC1122, use the default MSS value, unless they
1911 	 * sent us an offer.  Do not accept offers less than 256 bytes.
1912 	 */
1913 	mss = tcp_mssdflt;
1914 	if (offer)
1915 		mss = offer;
1916 	mss = max(mss, 256);		/* sanity */
1917 	tp->t_peermss = mss;
1918 	mss -= tcp_optlen(tp);
1919 #ifdef INET
1920 	if (tp->t_inpcb)
1921 		mss -= ip_optlen(tp->t_inpcb);
1922 #endif
1923 #ifdef INET6
1924 	if (tp->t_in6pcb)
1925 		mss -= ip6_optlen(tp->t_in6pcb);
1926 #endif
1927 
1928 	/*
1929 	 * If there's a pipesize, change the socket buffer to that size.
1930 	 * Make the socket buffer an integral number of MSS units.  If
1931 	 * the MSS is larger than the socket buffer, artificially decrease
1932 	 * the MSS.
1933 	 */
1934 #ifdef RTV_SPIPE
1935 	if (rt != NULL && rt->rt_rmx.rmx_sendpipe != 0)
1936 		bufsize = rt->rt_rmx.rmx_sendpipe;
1937 	else
1938 #endif
1939 	{
1940 		KASSERT(so != NULL);
1941 		bufsize = so->so_snd.sb_hiwat;
1942 	}
1943 	if (bufsize < mss)
1944 		mss = bufsize;
1945 	else {
1946 		bufsize = roundup(bufsize, mss);
1947 		if (bufsize > sb_max)
1948 			bufsize = sb_max;
1949 		(void) sbreserve(&so->so_snd, bufsize, so);
1950 	}
1951 	tp->t_segsz = mss;
1952 
1953 #ifdef RTV_SSTHRESH
1954 	if (rt != NULL && rt->rt_rmx.rmx_ssthresh) {
1955 		/*
1956 		 * There's some sort of gateway or interface buffer
1957 		 * limit on the path.  Use this to set the slow
1958 		 * start threshold, but set the threshold to no less
1959 		 * than 2 * MSS.
1960 		 */
1961 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
1962 	}
1963 #endif
1964 }
1965 
1966 /*
1967  * Processing necessary when a TCP connection is established.
1968  */
1969 void
1970 tcp_established(struct tcpcb *tp)
1971 {
1972 	struct socket *so;
1973 #ifdef RTV_RPIPE
1974 	struct rtentry *rt;
1975 #endif
1976 	u_long bufsize;
1977 
1978 #ifdef DIAGNOSTIC
1979 	if (tp->t_inpcb && tp->t_in6pcb)
1980 		panic("tcp_established: both t_inpcb and t_in6pcb are set");
1981 #endif
1982 	so = NULL;
1983 	rt = NULL;
1984 #ifdef INET
1985 	if (tp->t_inpcb) {
1986 		so = tp->t_inpcb->inp_socket;
1987 #if defined(RTV_RPIPE)
1988 		rt = in_pcbrtentry(tp->t_inpcb);
1989 #endif
1990 	}
1991 #endif
1992 #ifdef INET6
1993 	if (tp->t_in6pcb) {
1994 		so = tp->t_in6pcb->in6p_socket;
1995 #if defined(RTV_RPIPE)
1996 		rt = in6_pcbrtentry(tp->t_in6pcb);
1997 #endif
1998 	}
1999 #endif
2000 
2001 	tp->t_state = TCPS_ESTABLISHED;
2002 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
2003 
2004 #ifdef RTV_RPIPE
2005 	if (rt != NULL && rt->rt_rmx.rmx_recvpipe != 0)
2006 		bufsize = rt->rt_rmx.rmx_recvpipe;
2007 	else
2008 #endif
2009 	{
2010 		KASSERT(so != NULL);
2011 		bufsize = so->so_rcv.sb_hiwat;
2012 	}
2013 	if (bufsize > tp->t_ourmss) {
2014 		bufsize = roundup(bufsize, tp->t_ourmss);
2015 		if (bufsize > sb_max)
2016 			bufsize = sb_max;
2017 		(void) sbreserve(&so->so_rcv, bufsize, so);
2018 	}
2019 }
2020 
2021 /*
2022  * Check if there's an initial rtt or rttvar.  Convert from the
2023  * route-table units to scaled multiples of the slow timeout timer.
2024  * Called only during the 3-way handshake.
2025  */
2026 void
2027 tcp_rmx_rtt(struct tcpcb *tp)
2028 {
2029 #ifdef RTV_RTT
2030 	struct rtentry *rt = NULL;
2031 	int rtt;
2032 
2033 #ifdef DIAGNOSTIC
2034 	if (tp->t_inpcb && tp->t_in6pcb)
2035 		panic("tcp_rmx_rtt: both t_inpcb and t_in6pcb are set");
2036 #endif
2037 #ifdef INET
2038 	if (tp->t_inpcb)
2039 		rt = in_pcbrtentry(tp->t_inpcb);
2040 #endif
2041 #ifdef INET6
2042 	if (tp->t_in6pcb)
2043 		rt = in6_pcbrtentry(tp->t_in6pcb);
2044 #endif
2045 	if (rt == NULL)
2046 		return;
2047 
2048 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2049 		/*
2050 		 * XXX The lock bit for MTU indicates that the value
2051 		 * is also a minimum value; this is subject to time.
2052 		 */
2053 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
2054 			TCPT_RANGESET(tp->t_rttmin,
2055 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
2056 			    TCPTV_MIN, TCPTV_REXMTMAX);
2057 		tp->t_srtt = rtt /
2058 		    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
2059 		if (rt->rt_rmx.rmx_rttvar) {
2060 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2061 			    ((RTM_RTTUNIT / PR_SLOWHZ) >>
2062 				(TCP_RTTVAR_SHIFT + 2));
2063 		} else {
2064 			/* Default variation is +- 1 rtt */
2065 			tp->t_rttvar =
2066 			    tp->t_srtt >> (TCP_RTT_SHIFT - TCP_RTTVAR_SHIFT);
2067 		}
2068 		TCPT_RANGESET(tp->t_rxtcur,
2069 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2),
2070 		    tp->t_rttmin, TCPTV_REXMTMAX);
2071 	}
2072 #endif
2073 }
2074 
2075 tcp_seq	 tcp_iss_seq = 0;	/* tcp initial seq # */
2076 #if NRND > 0
2077 u_int8_t tcp_iss_secret[16];	/* 128 bits; should be plenty */
2078 #endif
2079 
2080 /*
2081  * Get a new sequence value given a tcp control block
2082  */
2083 tcp_seq
2084 tcp_new_iss(struct tcpcb *tp, tcp_seq addin)
2085 {
2086 
2087 #ifdef INET
2088 	if (tp->t_inpcb != NULL) {
2089 		return (tcp_new_iss1(&tp->t_inpcb->inp_laddr,
2090 		    &tp->t_inpcb->inp_faddr, tp->t_inpcb->inp_lport,
2091 		    tp->t_inpcb->inp_fport, sizeof(tp->t_inpcb->inp_laddr),
2092 		    addin));
2093 	}
2094 #endif
2095 #ifdef INET6
2096 	if (tp->t_in6pcb != NULL) {
2097 		return (tcp_new_iss1(&tp->t_in6pcb->in6p_laddr,
2098 		    &tp->t_in6pcb->in6p_faddr, tp->t_in6pcb->in6p_lport,
2099 		    tp->t_in6pcb->in6p_fport, sizeof(tp->t_in6pcb->in6p_laddr),
2100 		    addin));
2101 	}
2102 #endif
2103 	/* Not possible. */
2104 	panic("tcp_new_iss");
2105 }
2106 
2107 /*
2108  * This routine actually generates a new TCP initial sequence number.
2109  */
2110 tcp_seq
2111 tcp_new_iss1(void *laddr, void *faddr, u_int16_t lport, u_int16_t fport,
2112     size_t addrsz, tcp_seq addin)
2113 {
2114 	tcp_seq tcp_iss;
2115 
2116 #if NRND > 0
2117 	static int beenhere;
2118 
2119 	/*
2120 	 * If we haven't been here before, initialize our cryptographic
2121 	 * hash secret.
2122 	 */
2123 	if (beenhere == 0) {
2124 		rnd_extract_data(tcp_iss_secret, sizeof(tcp_iss_secret),
2125 		    RND_EXTRACT_ANY);
2126 		beenhere = 1;
2127 	}
2128 
2129 	if (tcp_do_rfc1948) {
2130 		MD5_CTX ctx;
2131 		u_int8_t hash[16];	/* XXX MD5 knowledge */
2132 
2133 		/*
2134 		 * Compute the base value of the ISS.  It is a hash
2135 		 * of (saddr, sport, daddr, dport, secret).
2136 		 */
2137 		MD5Init(&ctx);
2138 
2139 		MD5Update(&ctx, (u_char *) laddr, addrsz);
2140 		MD5Update(&ctx, (u_char *) &lport, sizeof(lport));
2141 
2142 		MD5Update(&ctx, (u_char *) faddr, addrsz);
2143 		MD5Update(&ctx, (u_char *) &fport, sizeof(fport));
2144 
2145 		MD5Update(&ctx, tcp_iss_secret, sizeof(tcp_iss_secret));
2146 
2147 		MD5Final(hash, &ctx);
2148 
2149 		memcpy(&tcp_iss, hash, sizeof(tcp_iss));
2150 
2151 		/*
2152 		 * Now increment our "timer", and add it in to
2153 		 * the computed value.
2154 		 *
2155 		 * XXX Use `addin'?
2156 		 * XXX TCP_ISSINCR too large to use?
2157 		 */
2158 		tcp_iss_seq += TCP_ISSINCR;
2159 #ifdef TCPISS_DEBUG
2160 		printf("ISS hash 0x%08x, ", tcp_iss);
2161 #endif
2162 		tcp_iss += tcp_iss_seq + addin;
2163 #ifdef TCPISS_DEBUG
2164 		printf("new ISS 0x%08x\n", tcp_iss);
2165 #endif
2166 	} else
2167 #endif /* NRND > 0 */
2168 	{
2169 		/*
2170 		 * Randomize.
2171 		 */
2172 #if NRND > 0
2173 		rnd_extract_data(&tcp_iss, sizeof(tcp_iss), RND_EXTRACT_ANY);
2174 #else
2175 		tcp_iss = arc4random();
2176 #endif
2177 
2178 		/*
2179 		 * If we were asked to add some amount to a known value,
2180 		 * we will take a random value obtained above, mask off
2181 		 * the upper bits, and add in the known value.  We also
2182 		 * add in a constant to ensure that we are at least a
2183 		 * certain distance from the original value.
2184 		 *
2185 		 * This is used when an old connection is in timed wait
2186 		 * and we have a new one coming in, for instance.
2187 		 */
2188 		if (addin != 0) {
2189 #ifdef TCPISS_DEBUG
2190 			printf("Random %08x, ", tcp_iss);
2191 #endif
2192 			tcp_iss &= TCP_ISS_RANDOM_MASK;
2193 			tcp_iss += addin + TCP_ISSINCR;
2194 #ifdef TCPISS_DEBUG
2195 			printf("Old ISS %08x, ISS %08x\n", addin, tcp_iss);
2196 #endif
2197 		} else {
2198 			tcp_iss &= TCP_ISS_RANDOM_MASK;
2199 			tcp_iss += tcp_iss_seq;
2200 			tcp_iss_seq += TCP_ISSINCR;
2201 #ifdef TCPISS_DEBUG
2202 			printf("ISS %08x\n", tcp_iss);
2203 #endif
2204 		}
2205 	}
2206 
2207 	if (tcp_compat_42) {
2208 		/*
2209 		 * Limit it to the positive range for really old TCP
2210 		 * implementations.
2211 		 * Just AND off the top bit instead of checking if
2212 		 * is set first - saves a branch 50% of the time.
2213 		 */
2214 		tcp_iss &= 0x7fffffff;		/* XXX */
2215 	}
2216 
2217 	return (tcp_iss);
2218 }
2219 
2220 #if defined(IPSEC) || defined(FAST_IPSEC)
2221 /* compute ESP/AH header size for TCP, including outer IP header. */
2222 size_t
2223 ipsec4_hdrsiz_tcp(struct tcpcb *tp)
2224 {
2225 	struct inpcb *inp;
2226 	size_t hdrsiz;
2227 
2228 	/* XXX mapped addr case (tp->t_in6pcb) */
2229 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
2230 		return 0;
2231 	switch (tp->t_family) {
2232 	case AF_INET:
2233 		/* XXX: should use currect direction. */
2234 		hdrsiz = ipsec4_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, inp);
2235 		break;
2236 	default:
2237 		hdrsiz = 0;
2238 		break;
2239 	}
2240 
2241 	return hdrsiz;
2242 }
2243 
2244 #ifdef INET6
2245 size_t
2246 ipsec6_hdrsiz_tcp(struct tcpcb *tp)
2247 {
2248 	struct in6pcb *in6p;
2249 	size_t hdrsiz;
2250 
2251 	if (!tp || !tp->t_template || !(in6p = tp->t_in6pcb))
2252 		return 0;
2253 	switch (tp->t_family) {
2254 	case AF_INET6:
2255 		/* XXX: should use currect direction. */
2256 		hdrsiz = ipsec6_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, in6p);
2257 		break;
2258 	case AF_INET:
2259 		/* mapped address case - tricky */
2260 	default:
2261 		hdrsiz = 0;
2262 		break;
2263 	}
2264 
2265 	return hdrsiz;
2266 }
2267 #endif
2268 #endif /*IPSEC*/
2269 
2270 /*
2271  * Determine the length of the TCP options for this connection.
2272  *
2273  * XXX:  What do we do for SACK, when we add that?  Just reserve
2274  *       all of the space?  Otherwise we can't exactly be incrementing
2275  *       cwnd by an amount that varies depending on the amount we last
2276  *       had to SACK!
2277  */
2278 
2279 u_int
2280 tcp_optlen(struct tcpcb *tp)
2281 {
2282 	u_int optlen;
2283 
2284 	optlen = 0;
2285 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
2286 	    (TF_REQ_TSTMP | TF_RCVD_TSTMP))
2287 		optlen += TCPOLEN_TSTAMP_APPA;
2288 
2289 #ifdef TCP_SIGNATURE
2290 #if defined(INET6) && defined(FAST_IPSEC)
2291 	if (tp->t_family == AF_INET)
2292 #endif
2293 	if (tp->t_flags & TF_SIGNATURE)
2294 		optlen += TCPOLEN_SIGNATURE + 2;
2295 #endif /* TCP_SIGNATURE */
2296 
2297 	return optlen;
2298 }
2299 
2300 u_int
2301 tcp_hdrsz(struct tcpcb *tp)
2302 {
2303 	u_int hlen;
2304 
2305 	switch (tp->t_family) {
2306 #ifdef INET6
2307 	case AF_INET6:
2308 		hlen = sizeof(struct ip6_hdr);
2309 		break;
2310 #endif
2311 	case AF_INET:
2312 		hlen = sizeof(struct ip);
2313 		break;
2314 	default:
2315 		hlen = 0;
2316 		break;
2317 	}
2318 	hlen += sizeof(struct tcphdr);
2319 
2320 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2321 	    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
2322 		hlen += TCPOLEN_TSTAMP_APPA;
2323 #ifdef TCP_SIGNATURE
2324 	if (tp->t_flags & TF_SIGNATURE)
2325 		hlen += TCPOLEN_SIGLEN;
2326 #endif
2327 	return hlen;
2328 }
2329