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