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