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