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