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