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