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