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