Home | History | Annotate | Line # | Download | only in netinet
tcp_subr.c revision 1.71
      1 /*	$NetBSD: tcp_subr.c,v 1.71 1999/07/14 22:08:52 drochner 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 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 "rnd.h"
    108 
    109 #include <sys/param.h>
    110 #include <sys/proc.h>
    111 #include <sys/systm.h>
    112 #include <sys/malloc.h>
    113 #include <sys/mbuf.h>
    114 #include <sys/socket.h>
    115 #include <sys/socketvar.h>
    116 #include <sys/protosw.h>
    117 #include <sys/errno.h>
    118 #include <sys/kernel.h>
    119 #include <sys/pool.h>
    120 #if NRND > 0
    121 #include <sys/rnd.h>
    122 #endif
    123 
    124 #include <net/route.h>
    125 #include <net/if.h>
    126 
    127 #include <netinet/in.h>
    128 #include <netinet/in_systm.h>
    129 #include <netinet/ip.h>
    130 #include <netinet/in_pcb.h>
    131 #include <netinet/ip_var.h>
    132 #include <netinet/ip_icmp.h>
    133 
    134 #ifdef INET6
    135 #ifndef INET
    136 #include <netinet/in.h>
    137 #endif
    138 #include <netinet/ip6.h>
    139 #include <netinet6/in6_pcb.h>
    140 #include <netinet6/ip6_var.h>
    141 #endif
    142 
    143 #include <netinet/tcp.h>
    144 #include <netinet/tcp_fsm.h>
    145 #include <netinet/tcp_seq.h>
    146 #include <netinet/tcp_timer.h>
    147 #include <netinet/tcp_var.h>
    148 #include <netinet/tcpip.h>
    149 
    150 #ifdef IPSEC
    151 #include <netinet6/ipsec.h>
    152 #include <netinet6/ah.h>
    153 #ifdef IPSEC_ESP
    154 #include <netinet6/esp.h>
    155 #endif
    156 #endif /*IPSEC*/
    157 
    158 #ifdef INET6
    159 struct in6pcb tcb6;
    160 #endif
    161 
    162 /* patchable/settable parameters for tcp */
    163 int 	tcp_mssdflt = TCP_MSS;
    164 int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
    165 int	tcp_do_rfc1323 = 1;	/* window scaling / timestamps (obsolete) */
    166 int	tcp_do_sack = 1;	/* selective acknowledgement */
    167 int	tcp_do_win_scale = 1;	/* RFC1323 window scaling */
    168 int	tcp_do_timestamps = 1;	/* RFC1323 timestamps */
    169 int	tcp_do_newreno = 0;	/* Use the New Reno algorithms */
    170 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
    171 int	tcp_init_win = 1;
    172 int	tcp_mss_ifmtu = 0;
    173 #ifdef TCP_COMPAT_42
    174 int	tcp_compat_42 = 1;
    175 #else
    176 int	tcp_compat_42 = 0;
    177 #endif
    178 
    179 #ifndef TCBHASHSIZE
    180 #define	TCBHASHSIZE	128
    181 #endif
    182 int	tcbhashsize = TCBHASHSIZE;
    183 
    184 int	tcp_freeq __P((struct tcpcb *));
    185 
    186 struct pool tcpcb_pool;
    187 
    188 /*
    189  * Tcp initialization
    190  */
    191 void
    192 tcp_init()
    193 {
    194 	int hlen;
    195 
    196 	pool_init(&tcpcb_pool, sizeof(struct tcpcb), 0, 0, 0, "tcpcbpl",
    197 	    0, NULL, NULL, M_PCB);
    198 	in_pcbinit(&tcbtable, tcbhashsize, tcbhashsize);
    199 #ifdef INET6
    200 	tcb6.in6p_next = tcb6.in6p_prev = &tcb6;
    201 #endif
    202 	LIST_INIT(&tcp_delacks);
    203 
    204 	hlen = sizeof(struct ip) + sizeof(struct tcphdr);
    205 #ifdef INET6
    206 	if (sizeof(struct ip) < sizeof(struct ip6_hdr))
    207 		hlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
    208 #endif
    209 	if (max_protohdr < hlen)
    210 		max_protohdr = hlen;
    211 	if (max_linkhdr + hlen > MHLEN)
    212 		panic("tcp_init");
    213 
    214 	/* Initialize the compressed state engine. */
    215 	syn_cache_init();
    216 }
    217 
    218 /*
    219  * Create template to be used to send tcp packets on a connection.
    220  * Call after host entry created, allocates an mbuf and fills
    221  * in a skeletal tcp/ip header, minimizing the amount of work
    222  * necessary when the connection is used.
    223  */
    224 struct mbuf *
    225 tcp_template(tp)
    226 	struct tcpcb *tp;
    227 {
    228 	register struct inpcb *inp = tp->t_inpcb;
    229 #ifdef INET6
    230 	register struct in6pcb *in6p = tp->t_in6pcb;
    231 #endif
    232 	register struct tcphdr *n;
    233 	register struct mbuf *m;
    234 	int hlen;
    235 
    236 	switch (tp->t_family) {
    237 	case AF_INET:
    238 		hlen = sizeof(struct ip);
    239 		if (inp)
    240 			break;
    241 #ifdef INET6
    242 		if (in6p) {
    243 			/* mapped addr case */
    244 			if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_laddr)
    245 			 && IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr))
    246 				break;
    247 		}
    248 #endif
    249 		return NULL;	/*EINVAL*/
    250 #ifdef INET6
    251 	case AF_INET6:
    252 		hlen = sizeof(struct ip6_hdr);
    253 		if (in6p) {
    254 			/* more sainty check? */
    255 			break;
    256 		}
    257 		return NULL;	/*EINVAL*/
    258 #endif
    259 	default:
    260 		hlen = 0;	/*pacify gcc*/
    261 		return NULL;	/*EAFNOSUPPORT*/
    262 	}
    263 	if ((m = tp->t_template) == 0) {
    264 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    265 		if (m) {
    266 			MCLGET(m, M_DONTWAIT);
    267 			if ((m->m_flags & M_EXT) == 0) {
    268 				m_free(m);
    269 				m = NULL;
    270 			}
    271 		}
    272 		if (m == NULL)
    273 			return NULL;
    274 		m->m_len = hlen + sizeof(struct tcphdr);
    275 	}
    276 	bzero(mtod(m, caddr_t), m->m_len);
    277 	switch (tp->t_family) {
    278 	case AF_INET:
    279 	    {
    280 		struct ipovly *ipov;
    281 		mtod(m, struct ip *)->ip_v = 4;
    282 		ipov = mtod(m, struct ipovly *);
    283 		ipov->ih_pr = IPPROTO_TCP;
    284 		ipov->ih_len = htons(sizeof(struct tcphdr));
    285 		if (inp) {
    286 			ipov->ih_src = inp->inp_laddr;
    287 			ipov->ih_dst = inp->inp_faddr;
    288 		}
    289 #ifdef INET6
    290 		else if (in6p) {
    291 			/* mapped addr case */
    292 			bcopy(&in6p->in6p_laddr.s6_addr32[3], &ipov->ih_src,
    293 				sizeof(ipov->ih_src));
    294 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &ipov->ih_dst,
    295 				sizeof(ipov->ih_dst));
    296 		}
    297 #endif
    298 		break;
    299 	    }
    300 #ifdef INET6
    301 	case AF_INET6:
    302 	    {
    303 		struct ip6_hdr *ip6;
    304 		mtod(m, struct ip *)->ip_v = 6;
    305 		ip6 = mtod(m, struct ip6_hdr *);
    306 		ip6->ip6_nxt = IPPROTO_TCP;
    307 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
    308 		ip6->ip6_src = in6p->in6p_laddr;
    309 		ip6->ip6_dst = in6p->in6p_faddr;
    310 		ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK;
    311 		if (ip6_auto_flowlabel) {
    312 			ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
    313 			ip6->ip6_flow |=
    314 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
    315 		}
    316 		ip6->ip6_vfc = IPV6_VERSION;
    317 		break;
    318 	    }
    319 #endif
    320 	}
    321 	n = (struct tcphdr *)(mtod(m, caddr_t) + hlen);
    322 	if (inp) {
    323 		n->th_sport = inp->inp_lport;
    324 		n->th_dport = inp->inp_fport;
    325 	}
    326 #ifdef INET6
    327 	else if (in6p) {
    328 		n->th_sport = in6p->in6p_lport;
    329 		n->th_dport = in6p->in6p_fport;
    330 	}
    331 #endif
    332 	n->th_seq = 0;
    333 	n->th_ack = 0;
    334 	n->th_x2 = 0;
    335 	n->th_off = 5;
    336 	n->th_flags = 0;
    337 	n->th_win = 0;
    338 	n->th_sum = 0;
    339 	n->th_urp = 0;
    340 	return (m);
    341 }
    342 
    343 /*
    344  * Send a single message to the TCP at address specified by
    345  * the given TCP/IP header.  If m == 0, then we make a copy
    346  * of the tcpiphdr at ti and send directly to the addressed host.
    347  * This is used to force keep alive messages out using the TCP
    348  * template for a connection tp->t_template.  If flags are given
    349  * then we send a message back to the TCP which originated the
    350  * segment ti, and discard the mbuf containing it and any other
    351  * attached mbufs.
    352  *
    353  * In any case the ack and sequence number of the transmitted
    354  * segment are as specified by the parameters.
    355  */
    356 int
    357 tcp_respond(tp, template, m, ack, seq, flags)
    358 	struct tcpcb *tp;
    359 	struct mbuf *template;		/* XXX should be struct mbuf? */
    360 	register struct mbuf *m;
    361 	tcp_seq ack, seq;
    362 	int flags;
    363 {
    364 #ifndef INET6
    365 	struct route iproute;
    366 #else
    367 	struct route_in6 iproute;	/* sizeof(route_in6) > sizeof(route) */
    368 #endif
    369 	struct route *ro;
    370 	struct rtentry *rt;
    371 	int error, tlen, win = 0;
    372 	int hlen;
    373 	struct ip *ip;
    374 #ifdef INET6
    375 	struct ip6_hdr *ip6;
    376 #endif
    377 	int family;	/* family on packet, not inpcb/in6pcb! */
    378 	struct tcphdr *th;
    379 
    380 	if (tp != NULL && (flags & TH_RST) == 0) {
    381 		if (tp->t_inpcb)
    382 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
    383 #ifdef INET6
    384 		else if (tp->t_in6pcb)
    385 			win = sbspace(&tp->t_in6pcb->in6p_socket->so_rcv);
    386 #endif
    387 	}
    388 
    389 	ip = NULL;
    390 #ifdef INET6
    391 	ip6 = NULL;
    392 #endif
    393 	if (m == 0) {
    394 		/* get family information from template */
    395 		switch (mtod(template, struct ip *)->ip_v) {
    396 		case 4:
    397 			family = AF_INET;
    398 			hlen = sizeof(struct ip);
    399 			break;
    400 #ifdef INET6
    401 		case 6:
    402 			family = AF_INET6;
    403 			hlen = sizeof(struct ip6_hdr);
    404 			break;
    405 #endif
    406 		default:
    407 			return EAFNOSUPPORT;
    408 		}
    409 
    410 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    411 		if (m) {
    412 			MCLGET(m, M_DONTWAIT);
    413 			if (!(m->m_flags & M_EXT)) {
    414 				m_free(m);
    415 				m = NULL;
    416 			}
    417 		}
    418 		if (m == NULL)
    419 			return (ENOBUFS);
    420 
    421 		if (tcp_compat_42)
    422 			tlen = 1;
    423 		else
    424 			tlen = 0;
    425 
    426 		m->m_data += max_linkhdr;
    427 		bcopy(mtod(template, caddr_t), mtod(m, caddr_t),
    428 			template->m_len);
    429 		switch (family) {
    430 		case AF_INET:
    431 			ip = mtod(m, struct ip *);
    432 			th = (struct tcphdr *)(ip + 1);
    433 			break;
    434 #ifdef INET6
    435 		case AF_INET6:
    436 			ip6 = mtod(m, struct ip6_hdr *);
    437 			th = (struct tcphdr *)(ip6 + 1);
    438 			break;
    439 #endif
    440 		default:	/*pacify gcc*/
    441 			ip = NULL;
    442 #ifdef INET6
    443 			ip6 = NULL;
    444 #endif
    445 			th = NULL;
    446 			break;
    447 		}
    448 		flags = TH_ACK;
    449 	} else {
    450 		/* get family information from m */
    451 		switch (mtod(m, struct ip *)->ip_v) {
    452 		case 4:
    453 			family = AF_INET;
    454 			hlen = sizeof(struct ip);
    455 			break;
    456 #ifdef INET6
    457 		case 6:
    458 			family = AF_INET6;
    459 			hlen = sizeof(struct ip6_hdr);
    460 			break;
    461 #endif
    462 		default:
    463 			if (m)
    464 				m_freem(m);
    465 			return EAFNOSUPPORT;
    466 		}
    467 
    468 		/* template pointer almost has no meaning */
    469 		m_freem(m->m_next);
    470 		m->m_next = 0;
    471 		m->m_len = hlen + sizeof(struct tcphdr);
    472 		if ((m->m_flags & M_PKTHDR) == 0) {
    473 			printf("non PKTHDR to tcp_respond\n");
    474 			m_freem(m);
    475 			return EINVAL;
    476 		}
    477 
    478 		tlen = 0;
    479 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
    480 		switch (family) {
    481 		case AF_INET:
    482 			ip = mtod(m, struct ip *);
    483 			th = (struct tcphdr *)(ip + 1);
    484 			xchg(ip->ip_dst, ip->ip_src, struct in_addr);
    485 			break;
    486 #ifdef INET6
    487 		case AF_INET6:
    488 			ip6 = mtod(m, struct ip6_hdr *);
    489 			th = (struct tcphdr *)(ip6 + 1);
    490 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
    491 			break;
    492 #endif
    493 		}
    494 		xchg(th->th_dport, th->th_sport, u_int16_t);
    495 #undef xchg
    496 	}
    497 	th->th_seq = htonl(seq);
    498 	th->th_ack = htonl(ack);
    499 	th->th_x2 = 0;
    500 	if ((flags & TH_SYN) == 0) {
    501 		if (tp)
    502 			th->th_win = htons((u_int16_t) (win >> tp->rcv_scale));
    503 		else
    504 			th->th_win = htons((u_int16_t)win);
    505 		th->th_off = sizeof (struct tcphdr) >> 2;
    506 		tlen += sizeof (struct tcphdr);
    507 	} else
    508 		tlen += th->th_off << 2;
    509 	m->m_len = hlen + tlen;
    510 	m->m_pkthdr.len = hlen + tlen;
    511 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
    512 	th->th_flags = flags;
    513 	th->th_urp = 0;
    514 
    515 	switch (family) {
    516 	case AF_INET:
    517 	    {
    518 		struct ipovly *ipov = (struct ipovly *)ip;
    519 		bzero(ipov->ih_x1, sizeof ipov->ih_x1);
    520 		ipov->ih_len = htons((u_int16_t)tlen);
    521 
    522 		th->th_sum = 0;
    523 		th->th_sum = in_cksum(m, hlen + tlen);
    524 		ip->ip_len = hlen + tlen;	/*will be flipped on output*/
    525 		ip->ip_ttl = ip_defttl;
    526 		break;
    527 	    }
    528 #ifdef INET6
    529 	case AF_INET6:
    530 	    {
    531 		th->th_sum = 0;
    532 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
    533 				tlen);
    534 		ip6->ip6_plen = ntohs(tlen);
    535 		ip6->ip6_hlim = ip6_defhlim;
    536 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
    537 		if (ip6_auto_flowlabel) {
    538 			ip6->ip6_flow |=
    539 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
    540 		}
    541 		break;
    542 	    }
    543 #endif
    544 	}
    545 
    546 #ifdef IPSEC
    547 	m->m_pkthdr.rcvif = NULL;
    548 #endif /*IPSEC*/
    549 
    550 	/*
    551 	 * If we're doing Path MTU discovery, we need to set DF unless
    552 	 * the route's MTU is locked.  If we lack a route, we need to
    553 	 * look it up now.
    554 	 *
    555 	 * ip_output() could do this for us, but it's convenient to just
    556 	 * do it here unconditionally.
    557 	 */
    558 	if (tp != NULL && tp->t_inpcb != NULL) {
    559 		ro = &tp->t_inpcb->inp_route;
    560 #ifdef IPSEC
    561 		m->m_pkthdr.rcvif = (struct ifnet *)tp->t_inpcb->inp_socket;
    562 #endif
    563 #ifdef DIAGNOSTIC
    564 		if (family != AF_INET)
    565 			panic("tcp_respond: address family mismatch");
    566 		if (!in_hosteq(ip->ip_dst, tp->t_inpcb->inp_faddr)) {
    567 			panic("tcp_respond: ip_dst %x != inp_faddr %x",
    568 			    ntohl(ip->ip_dst.s_addr),
    569 			    ntohl(tp->t_inpcb->inp_faddr.s_addr));
    570 		}
    571 #endif
    572 	}
    573 #ifdef INET6
    574 	else if (tp != NULL && tp->t_in6pcb != NULL) {
    575 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
    576 #ifdef IPSEC
    577 		m->m_pkthdr.rcvif = (struct ifnet *)tp->t_in6pcb->in6p_socket;
    578 #endif
    579 #ifdef DIAGNOSTIC
    580 		if (family == AF_INET) {
    581 			if (!IN6_IS_ADDR_V4MAPPED(&tp->t_in6pcb->in6p_faddr))
    582 				panic("tcp_respond: not mapped addr");
    583 			if (bcmp(&ip->ip_dst,
    584 					&tp->t_in6pcb->in6p_faddr.s6_addr32[3],
    585 					sizeof(ip->ip_dst)) != 0) {
    586 				panic("tcp_respond: ip_dst != in6p_faddr");
    587 			}
    588 		} else if (family == AF_INET6) {
    589 			if (!IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &tp->t_in6pcb->in6p_faddr))
    590 				panic("tcp_respond: ip6_dst != in6p_faddr");
    591 		} else
    592 			panic("tcp_respond: address family mismatch");
    593 #endif
    594 	}
    595 #endif
    596 	else {
    597 		ro = (struct route *)&iproute;
    598 		bzero(ro, sizeof(iproute));
    599 	}
    600 	if ((rt = ro->ro_rt) == NULL || (rt->rt_flags & RTF_UP) == 0) {
    601 		if (ro->ro_rt != NULL) {
    602 			RTFREE(ro->ro_rt);
    603 			ro->ro_rt = NULL;
    604 		}
    605 		switch (family) {
    606 		case AF_INET:
    607 		    {
    608 			struct sockaddr_in *dst;
    609 			dst = satosin(&ro->ro_dst);
    610 			dst->sin_family = AF_INET;
    611 			dst->sin_len = sizeof(*dst);
    612 			dst->sin_addr = ip->ip_dst;
    613 			break;
    614 		    }
    615 #ifdef INET6
    616 		case AF_INET6:
    617 		    {
    618 			struct sockaddr_in6 *dst;
    619 			dst = satosin6(&ro->ro_dst);
    620 			bzero(dst, sizeof(*dst));
    621 			dst->sin6_family = AF_INET6;
    622 			dst->sin6_len = sizeof(*dst);
    623 			dst->sin6_addr = ip6->ip6_dst;
    624 			break;
    625 		    }
    626 #endif
    627 		}
    628 		rtalloc(ro);
    629 		if ((rt = ro->ro_rt) == NULL) {
    630 			m_freem(m);
    631 			switch (family) {
    632 			case AF_INET:
    633 				ipstat.ips_noroute++;
    634 				break;
    635 #ifdef INET6
    636 			case AF_INET6:
    637 				ip6stat.ip6s_noroute++;
    638 				break;
    639 #endif
    640 			}
    641 			return (EHOSTUNREACH);
    642 		}
    643 	}
    644 	switch (family) {
    645 	case AF_INET:
    646 		if (ip_mtudisc != 0 && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
    647 			ip->ip_off |= IP_DF;
    648 
    649 		error = ip_output(m, NULL, ro, 0, NULL);
    650 		break;
    651 #ifdef INET6
    652 	case AF_INET6:
    653 		error = ip6_output(m, NULL, (struct route_in6 *)ro, 0, NULL);
    654 		break;
    655 #endif
    656 	default:
    657 		error = EAFNOSUPPORT;
    658 		break;
    659 	}
    660 
    661 	if (ro == (struct route *)&iproute) {
    662 		RTFREE(ro->ro_rt);
    663 		ro->ro_rt = NULL;
    664 	}
    665 
    666 	return (error);
    667 }
    668 
    669 /*
    670  * Create a new TCP control block, making an
    671  * empty reassembly queue and hooking it to the argument
    672  * protocol control block.
    673  */
    674 struct tcpcb *
    675 tcp_newtcpcb(family, aux)
    676 	int family;	/* selects inpcb, or in6pcb */
    677 	void *aux;
    678 {
    679 	register struct tcpcb *tp;
    680 
    681 	switch (family) {
    682 	case PF_INET:
    683 		break;
    684 #ifdef INET6
    685 	case PF_INET6:
    686 		break;
    687 #endif
    688 	default:
    689 		return NULL;
    690 	}
    691 
    692 	tp = pool_get(&tcpcb_pool, PR_NOWAIT);
    693 	if (tp == NULL)
    694 		return (NULL);
    695 	bzero((caddr_t)tp, sizeof(struct tcpcb));
    696 	LIST_INIT(&tp->segq);
    697 	LIST_INIT(&tp->timeq);
    698 	tp->t_family = family;		/* may be overridden later on */
    699 	tp->t_peermss = tcp_mssdflt;
    700 	tp->t_ourmss = tcp_mssdflt;
    701 	tp->t_segsz = tcp_mssdflt;
    702 
    703 	tp->t_flags = 0;
    704 	if (tcp_do_rfc1323 && tcp_do_win_scale)
    705 		tp->t_flags |= TF_REQ_SCALE;
    706 	if (tcp_do_rfc1323 && tcp_do_timestamps)
    707 		tp->t_flags |= TF_REQ_TSTMP;
    708 	if (tcp_do_sack == 2)
    709 		tp->t_flags |= TF_WILL_SACK;
    710 	else if (tcp_do_sack == 1)
    711 		tp->t_flags |= TF_WILL_SACK|TF_IGNR_RXSACK;
    712 	tp->t_flags |= TF_CANT_TXSACK;
    713 	switch (family) {
    714 	case PF_INET:
    715 		tp->t_inpcb = (struct inpcb *)aux;
    716 		break;
    717 #ifdef INET6
    718 	case PF_INET6:
    719 		tp->t_in6pcb = (struct in6pcb *)aux;
    720 		break;
    721 #endif
    722 	}
    723 	/*
    724 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
    725 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
    726 	 * reasonable initial retransmit time.
    727 	 */
    728 	tp->t_srtt = TCPTV_SRTTBASE;
    729 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ << (TCP_RTTVAR_SHIFT + 2 - 1);
    730 	tp->t_rttmin = TCPTV_MIN;
    731 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
    732 	    TCPTV_MIN, TCPTV_REXMTMAX);
    733 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
    734 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
    735 	if (family == AF_INET) {
    736 		struct inpcb *inp = (struct inpcb *)aux;
    737 		inp->inp_ip.ip_ttl = ip_defttl;
    738 		inp->inp_ppcb = (caddr_t)tp;
    739 	}
    740 #ifdef INET6
    741 	else if (family == AF_INET6) {
    742 		struct in6pcb *in6p = (struct in6pcb *)aux;
    743 		in6p->in6p_ip6.ip6_hlim = ip6_defhlim;
    744 		in6p->in6p_ppcb = (caddr_t)tp;
    745 	}
    746 #endif
    747 	return (tp);
    748 }
    749 
    750 /*
    751  * Drop a TCP connection, reporting
    752  * the specified error.  If connection is synchronized,
    753  * then send a RST to peer.
    754  */
    755 struct tcpcb *
    756 tcp_drop(tp, errno)
    757 	register struct tcpcb *tp;
    758 	int errno;
    759 {
    760 	struct socket *so;
    761 
    762 	if (tp->t_inpcb)
    763 		so = tp->t_inpcb->inp_socket;
    764 #ifdef INET6
    765 	else if (tp->t_in6pcb)
    766 		so = tp->t_in6pcb->in6p_socket;
    767 #endif
    768 	else
    769 		return NULL;
    770 
    771 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
    772 		tp->t_state = TCPS_CLOSED;
    773 		(void) tcp_output(tp);
    774 		tcpstat.tcps_drops++;
    775 	} else
    776 		tcpstat.tcps_conndrops++;
    777 	if (errno == ETIMEDOUT && tp->t_softerror)
    778 		errno = tp->t_softerror;
    779 	so->so_error = errno;
    780 	return (tcp_close(tp));
    781 }
    782 
    783 /*
    784  * Close a TCP control block:
    785  *	discard all space held by the tcp
    786  *	discard internet protocol block
    787  *	wake up any sleepers
    788  */
    789 struct tcpcb *
    790 tcp_close(tp)
    791 	register struct tcpcb *tp;
    792 {
    793 	struct inpcb *inp;
    794 #ifdef INET6
    795 	struct in6pcb *in6p;
    796 #endif
    797 	struct socket *so;
    798 #ifdef RTV_RTT
    799 	register struct rtentry *rt;
    800 #endif
    801 	struct route *ro;
    802 
    803 	inp = tp->t_inpcb;
    804 #ifdef INET6
    805 	in6p = tp->t_in6pcb;
    806 #endif
    807 	so = NULL;
    808 	ro = NULL;
    809 	if (inp) {
    810 		so = inp->inp_socket;
    811 		ro = &inp->inp_route;
    812 	}
    813 #ifdef INET6
    814 	else if (in6p) {
    815 		so = in6p->in6p_socket;
    816 		ro = (struct route *)&in6p->in6p_route;
    817 	}
    818 #endif
    819 
    820 #ifdef RTV_RTT
    821 	/*
    822 	 * If we sent enough data to get some meaningful characteristics,
    823 	 * save them in the routing entry.  'Enough' is arbitrarily
    824 	 * defined as the sendpipesize (default 4K) * 16.  This would
    825 	 * give us 16 rtt samples assuming we only get one sample per
    826 	 * window (the usual case on a long haul net).  16 samples is
    827 	 * enough for the srtt filter to converge to within 5% of the correct
    828 	 * value; fewer samples and we could save a very bogus rtt.
    829 	 *
    830 	 * Don't update the default route's characteristics and don't
    831 	 * update anything that the user "locked".
    832 	 */
    833 	if (SEQ_LT(tp->iss + so->so_snd.sb_hiwat * 16, tp->snd_max) &&
    834 	    ro && (rt = ro->ro_rt) &&
    835 	    !in_nullhost(satosin(rt_key(rt))->sin_addr)) {
    836 		register u_long i = 0;
    837 
    838 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
    839 			i = tp->t_srtt *
    840 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
    841 			if (rt->rt_rmx.rmx_rtt && i)
    842 				/*
    843 				 * filter this update to half the old & half
    844 				 * the new values, converting scale.
    845 				 * See route.h and tcp_var.h for a
    846 				 * description of the scaling constants.
    847 				 */
    848 				rt->rt_rmx.rmx_rtt =
    849 				    (rt->rt_rmx.rmx_rtt + i) / 2;
    850 			else
    851 				rt->rt_rmx.rmx_rtt = i;
    852 		}
    853 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
    854 			i = tp->t_rttvar *
    855 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTTVAR_SHIFT + 2));
    856 			if (rt->rt_rmx.rmx_rttvar && i)
    857 				rt->rt_rmx.rmx_rttvar =
    858 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
    859 			else
    860 				rt->rt_rmx.rmx_rttvar = i;
    861 		}
    862 		/*
    863 		 * update the pipelimit (ssthresh) if it has been updated
    864 		 * already or if a pipesize was specified & the threshhold
    865 		 * got below half the pipesize.  I.e., wait for bad news
    866 		 * before we start updating, then update on both good
    867 		 * and bad news.
    868 		 */
    869 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
    870 		    (i = tp->snd_ssthresh) && rt->rt_rmx.rmx_ssthresh) ||
    871 		    i < (rt->rt_rmx.rmx_sendpipe / 2)) {
    872 			/*
    873 			 * convert the limit from user data bytes to
    874 			 * packets then to packet data bytes.
    875 			 */
    876 			i = (i + tp->t_segsz / 2) / tp->t_segsz;
    877 			if (i < 2)
    878 				i = 2;
    879 			i *= (u_long)(tp->t_segsz + sizeof (struct tcpiphdr));
    880 			if (rt->rt_rmx.rmx_ssthresh)
    881 				rt->rt_rmx.rmx_ssthresh =
    882 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
    883 			else
    884 				rt->rt_rmx.rmx_ssthresh = i;
    885 		}
    886 	}
    887 #endif /* RTV_RTT */
    888 	/* free the reassembly queue, if any */
    889 	TCP_REASS_LOCK(tp);
    890 	(void) tcp_freeq(tp);
    891 	TCP_REASS_UNLOCK(tp);
    892 
    893 	TCP_CLEAR_DELACK(tp);
    894 
    895 	if (tp->t_template) {
    896 		m_free(tp->t_template);
    897 		tp->t_template = NULL;
    898 	}
    899 	pool_put(&tcpcb_pool, tp);
    900 	if (inp) {
    901 		inp->inp_ppcb = 0;
    902 		soisdisconnected(so);
    903 		in_pcbdetach(inp);
    904 	}
    905 #ifdef INET6
    906 	else if (in6p) {
    907 		in6p->in6p_ppcb = 0;
    908 		soisdisconnected(so);
    909 		in6_pcbdetach(in6p);
    910 	}
    911 #endif
    912 	tcpstat.tcps_closed++;
    913 	return ((struct tcpcb *)0);
    914 }
    915 
    916 int
    917 tcp_freeq(tp)
    918 	struct tcpcb *tp;
    919 {
    920 	register struct ipqent *qe;
    921 	int rv = 0;
    922 #ifdef TCPREASS_DEBUG
    923 	int i = 0;
    924 #endif
    925 
    926 	TCP_REASS_LOCK_CHECK(tp);
    927 
    928 	while ((qe = tp->segq.lh_first) != NULL) {
    929 #ifdef TCPREASS_DEBUG
    930 		printf("tcp_freeq[%p,%d]: %u:%u(%u) 0x%02x\n",
    931 			tp, i++, qe->ipqe_seq, qe->ipqe_seq + qe->ipqe_len,
    932 			qe->ipqe_len, qe->ipqe_flags & (TH_SYN|TH_FIN|TH_RST));
    933 #endif
    934 		LIST_REMOVE(qe, ipqe_q);
    935 		LIST_REMOVE(qe, ipqe_timeq);
    936 		m_freem(qe->ipqe_m);
    937 		pool_put(&ipqent_pool, qe);
    938 		rv = 1;
    939 	}
    940 	return (rv);
    941 }
    942 
    943 /*
    944  * Protocol drain routine.  Called when memory is in short supply.
    945  */
    946 void
    947 tcp_drain()
    948 {
    949 	register struct inpcb *inp;
    950 	register struct tcpcb *tp;
    951 
    952 	/*
    953 	 * Free the sequence queue of all TCP connections.
    954 	 */
    955 	inp = tcbtable.inpt_queue.cqh_first;
    956 	if (inp)						/* XXX */
    957 	for (; inp != (struct inpcb *)&tcbtable.inpt_queue;
    958 	    inp = inp->inp_queue.cqe_next) {
    959 		if ((tp = intotcpcb(inp)) != NULL) {
    960 			/*
    961 			 * We may be called from a device's interrupt
    962 			 * context.  If the tcpcb is already busy,
    963 			 * just bail out now.
    964 			 */
    965 			if (tcp_reass_lock_try(tp) == 0)
    966 				continue;
    967 			if (tcp_freeq(tp))
    968 				tcpstat.tcps_connsdrained++;
    969 			TCP_REASS_UNLOCK(tp);
    970 		}
    971 	}
    972 }
    973 
    974 /*
    975  * Notify a tcp user of an asynchronous error;
    976  * store error as soft error, but wake up user
    977  * (for now, won't do anything until can select for soft error).
    978  */
    979 void
    980 tcp_notify(inp, error)
    981 	struct inpcb *inp;
    982 	int error;
    983 {
    984 	register struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
    985 	register struct socket *so = inp->inp_socket;
    986 
    987 	/*
    988 	 * Ignore some errors if we are hooked up.
    989 	 * If connection hasn't completed, has retransmitted several times,
    990 	 * and receives a second error, give up now.  This is better
    991 	 * than waiting a long time to establish a connection that
    992 	 * can never complete.
    993 	 */
    994 	if (tp->t_state == TCPS_ESTABLISHED &&
    995 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
    996 	      error == EHOSTDOWN)) {
    997 		return;
    998 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
    999 	    tp->t_rxtshift > 3 && tp->t_softerror)
   1000 		so->so_error = error;
   1001 	else
   1002 		tp->t_softerror = error;
   1003 	wakeup((caddr_t) &so->so_timeo);
   1004 	sorwakeup(so);
   1005 	sowwakeup(so);
   1006 }
   1007 
   1008 #if defined(INET6) && !defined(TCP6)
   1009 void
   1010 tcp6_ctlinput(cmd, sa, ip6, m, off)
   1011 	int cmd;
   1012 	struct sockaddr *sa;
   1013 	register struct ip6_hdr *ip6;
   1014 	struct mbuf *m;
   1015 	int off;
   1016 {
   1017 	(void)tcp_ctlinput(cmd, sa, (void *)ip6);
   1018 }
   1019 #endif
   1020 
   1021 /* assumes that ip header and tcp header are contiguous on mbuf */
   1022 void *
   1023 tcp_ctlinput(cmd, sa, v)
   1024 	int cmd;
   1025 	struct sockaddr *sa;
   1026 	register void *v;
   1027 {
   1028 	register struct ip *ip = v;
   1029 	register struct tcphdr *th;
   1030 	extern int inetctlerrmap[];
   1031 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
   1032 	int errno;
   1033 	int nmatch;
   1034 
   1035 	if ((unsigned)cmd >= PRC_NCMDS)
   1036 		return NULL;
   1037 	errno = inetctlerrmap[cmd];
   1038 	if (cmd == PRC_QUENCH)
   1039 		notify = tcp_quench;
   1040 	else if (PRC_IS_REDIRECT(cmd))
   1041 		notify = in_rtchange, ip = 0;
   1042 	else if (cmd == PRC_MSGSIZE && ip_mtudisc)
   1043 		notify = tcp_mtudisc, ip = 0;
   1044 	else if (cmd == PRC_HOSTDEAD)
   1045 		ip = 0;
   1046 	else if (errno == 0)
   1047 		return NULL;
   1048 	if (ip && ip->ip_v == 4 && sa->sa_family == AF_INET) {
   1049 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
   1050 		nmatch = in_pcbnotify(&tcbtable, satosin(sa)->sin_addr,
   1051 		    th->th_dport, ip->ip_src, th->th_sport, errno, notify);
   1052 		if (nmatch == 0 && syn_cache_count &&
   1053 		    (inetctlerrmap[cmd] == EHOSTUNREACH ||
   1054 		    inetctlerrmap[cmd] == ENETUNREACH ||
   1055 		    inetctlerrmap[cmd] == EHOSTDOWN)) {
   1056 			struct sockaddr_in sin;
   1057 			bzero(&sin, sizeof(sin));
   1058 			sin.sin_len = sizeof(sin);
   1059 			sin.sin_family = AF_INET;
   1060 			sin.sin_port = th->th_sport;
   1061 			sin.sin_addr = ip->ip_src;
   1062 			syn_cache_unreach((struct sockaddr *)&sin, sa, th);
   1063 		}
   1064 
   1065 		/* XXX mapped address case */
   1066 	}
   1067 #ifdef INET6
   1068 	else if (ip && ip->ip_v == 6 && sa->sa_family == AF_INET6) {
   1069 		/* XXX do something for ip6 */
   1070 	}
   1071 #endif
   1072 	else {
   1073 		(void)in_pcbnotifyall(&tcbtable, satosin(sa)->sin_addr, errno,
   1074 		    notify);
   1075 #ifdef INET6
   1076 		/* XXX do something for ip6 */
   1077 #endif
   1078 	}
   1079 	return NULL;
   1080 }
   1081 
   1082 /*
   1083  * When a source quence is received, we are being notifed of congestion.
   1084  * Close the congestion window down to the Loss Window (one segment).
   1085  * We will gradually open it again as we proceed.
   1086  */
   1087 void
   1088 tcp_quench(inp, errno)
   1089 	struct inpcb *inp;
   1090 	int errno;
   1091 {
   1092 	struct tcpcb *tp = intotcpcb(inp);
   1093 
   1094 	if (tp)
   1095 		tp->snd_cwnd = tp->t_segsz;
   1096 }
   1097 
   1098 /*
   1099  * On receipt of path MTU corrections, flush old route and replace it
   1100  * with the new one.  Retransmit all unacknowledged packets, to ensure
   1101  * that all packets will be received.
   1102  */
   1103 void
   1104 tcp_mtudisc(inp, errno)
   1105 	struct inpcb *inp;
   1106 	int errno;
   1107 {
   1108 	struct tcpcb *tp = intotcpcb(inp);
   1109 	struct rtentry *rt = in_pcbrtentry(inp);
   1110 
   1111 	if (tp != 0) {
   1112 		if (rt != 0) {
   1113 			/*
   1114 			 * If this was not a host route, remove and realloc.
   1115 			 */
   1116 			if ((rt->rt_flags & RTF_HOST) == 0) {
   1117 				in_rtchange(inp, errno);
   1118 				if ((rt = in_pcbrtentry(inp)) == 0)
   1119 					return;
   1120 			}
   1121 
   1122 			/*
   1123 			 * Slow start out of the error condition.  We
   1124 			 * use the MTU because we know it's smaller
   1125 			 * than the previously transmitted segment.
   1126 			 *
   1127 			 * Note: This is more conservative than the
   1128 			 * suggestion in draft-floyd-incr-init-win-03.
   1129 			 */
   1130 			if (rt->rt_rmx.rmx_mtu != 0)
   1131 				tp->snd_cwnd =
   1132 				    TCP_INITIAL_WINDOW(tcp_init_win,
   1133 				    rt->rt_rmx.rmx_mtu);
   1134 		}
   1135 
   1136 		/*
   1137 		 * Resend unacknowledged packets.
   1138 		 */
   1139 		tp->snd_nxt = tp->snd_una;
   1140 		tcp_output(tp);
   1141 	}
   1142 }
   1143 
   1144 
   1145 /*
   1146  * Compute the MSS to advertise to the peer.  Called only during
   1147  * the 3-way handshake.  If we are the server (peer initiated
   1148  * connection), we are called with a pointer to the interface
   1149  * on which the SYN packet arrived.  If we are the client (we
   1150  * initiated connection), we are called with a pointer to the
   1151  * interface out which this connection should go.
   1152  */
   1153 u_long
   1154 tcp_mss_to_advertise(ifp)
   1155 	const struct ifnet *ifp;
   1156 {
   1157 	extern u_long in_maxmtu;
   1158 	u_long mss = 0;
   1159 
   1160 	/*
   1161 	 * In order to avoid defeating path MTU discovery on the peer,
   1162 	 * we advertise the max MTU of all attached networks as our MSS,
   1163 	 * per RFC 1191, section 3.1.
   1164 	 *
   1165 	 * We provide the option to advertise just the MTU of
   1166 	 * the interface on which we hope this connection will
   1167 	 * be receiving.  If we are responding to a SYN, we
   1168 	 * will have a pretty good idea about this, but when
   1169 	 * initiating a connection there is a bit more doubt.
   1170 	 *
   1171 	 * We also need to ensure that loopback has a large enough
   1172 	 * MSS, as the loopback MTU is never included in in_maxmtu.
   1173 	 */
   1174 
   1175 	if (ifp != NULL)
   1176 		mss = ifp->if_mtu;
   1177 
   1178 	if (tcp_mss_ifmtu == 0)
   1179 		mss = max(in_maxmtu, mss);
   1180 
   1181 	if (mss > sizeof(struct tcpiphdr))
   1182 		mss -= sizeof(struct tcpiphdr);
   1183 
   1184 	mss = max(tcp_mssdflt, mss);
   1185 	return (mss);
   1186 }
   1187 
   1188 /*
   1189  * Set connection variables based on the peer's advertised MSS.
   1190  * We are passed the TCPCB for the actual connection.  If we
   1191  * are the server, we are called by the compressed state engine
   1192  * when the 3-way handshake is complete.  If we are the client,
   1193  * we are called when we recieve the SYN,ACK from the server.
   1194  *
   1195  * NOTE: Our advertised MSS value must be initialized in the TCPCB
   1196  * before this routine is called!
   1197  */
   1198 void
   1199 tcp_mss_from_peer(tp, offer)
   1200 	struct tcpcb *tp;
   1201 	int offer;
   1202 {
   1203 	struct socket *so;
   1204 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   1205 	struct rtentry *rt;
   1206 #endif
   1207 	u_long bufsize;
   1208 	int mss;
   1209 
   1210 	so = NULL;
   1211 	rt = NULL;
   1212 	if (tp->t_inpcb) {
   1213 		so = tp->t_inpcb->inp_socket;
   1214 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   1215 		rt = in_pcbrtentry(tp->t_inpcb);
   1216 #endif
   1217 	}
   1218 #ifdef INET6
   1219 	else if (tp->t_in6pcb) {
   1220 		so = tp->t_in6pcb->in6p_socket;
   1221 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   1222 #ifdef TCP6
   1223 		rt = NULL;
   1224 #else
   1225 		rt = in6_pcbrtentry(tp->t_in6pcb);
   1226 #endif
   1227 #endif
   1228 	}
   1229 #endif
   1230 
   1231 	/*
   1232 	 * As per RFC1122, use the default MSS value, unless they
   1233 	 * sent us an offer.  Do not accept offers less than 32 bytes.
   1234 	 */
   1235 	mss = tcp_mssdflt;
   1236 	if (offer)
   1237 		mss = offer;
   1238 	mss = max(mss, 32);		/* sanity */
   1239 	tp->t_peermss = mss;
   1240 	mss -= tcp_optlen(tp);
   1241 	if (tp->t_inpcb)
   1242 		mss -= ip_optlen(tp->t_inpcb);
   1243 #ifdef INET6
   1244 	else if (tp->t_in6pcb)
   1245 		mss -= ip6_optlen(tp->t_in6pcb);
   1246 #endif
   1247 
   1248 	/*
   1249 	 * If there's a pipesize, change the socket buffer to that size.
   1250 	 * Make the socket buffer an integral number of MSS units.  If
   1251 	 * the MSS is larger than the socket buffer, artificially decrease
   1252 	 * the MSS.
   1253 	 */
   1254 #ifdef RTV_SPIPE
   1255 	if (rt != NULL && rt->rt_rmx.rmx_sendpipe != 0)
   1256 		bufsize = rt->rt_rmx.rmx_sendpipe;
   1257 	else
   1258 #endif
   1259 		bufsize = so->so_snd.sb_hiwat;
   1260 	if (bufsize < mss)
   1261 		mss = bufsize;
   1262 	else {
   1263 		bufsize = roundup(bufsize, mss);
   1264 		if (bufsize > sb_max)
   1265 			bufsize = sb_max;
   1266 		(void) sbreserve(&so->so_snd, bufsize);
   1267 	}
   1268 	tp->t_segsz = mss;
   1269 
   1270 #ifdef RTV_SSTHRESH
   1271 	if (rt != NULL && rt->rt_rmx.rmx_ssthresh) {
   1272 		/*
   1273 		 * There's some sort of gateway or interface buffer
   1274 		 * limit on the path.  Use this to set the slow
   1275 		 * start threshold, but set the threshold to no less
   1276 		 * than 2 * MSS.
   1277 		 */
   1278 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
   1279 	}
   1280 #endif
   1281 }
   1282 
   1283 /*
   1284  * Processing necessary when a TCP connection is established.
   1285  */
   1286 void
   1287 tcp_established(tp)
   1288 	struct tcpcb *tp;
   1289 {
   1290 	struct socket *so;
   1291 #ifdef RTV_RPIPE
   1292 	struct rtentry *rt;
   1293 #endif
   1294 	u_long bufsize;
   1295 
   1296 	so = NULL;
   1297 	rt = NULL;
   1298 	if (tp->t_inpcb) {
   1299 		so = tp->t_inpcb->inp_socket;
   1300 #if defined(RTV_RPIPE)
   1301 		rt = in_pcbrtentry(tp->t_inpcb);
   1302 #endif
   1303 	}
   1304 #ifdef INET6
   1305 	else if (tp->t_in6pcb) {
   1306 		so = tp->t_in6pcb->in6p_socket;
   1307 #if defined(RTV_RPIPE)
   1308 #ifdef TCP6
   1309 		rt = NULL;
   1310 #else
   1311 		rt = in6_pcbrtentry(tp->t_in6pcb);
   1312 #endif
   1313 #endif
   1314 	}
   1315 #endif
   1316 
   1317 	tp->t_state = TCPS_ESTABLISHED;
   1318 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
   1319 
   1320 #ifdef RTV_RPIPE
   1321 	if (rt != NULL && rt->rt_rmx.rmx_recvpipe != 0)
   1322 		bufsize = rt->rt_rmx.rmx_recvpipe;
   1323 	else
   1324 #endif
   1325 		bufsize = so->so_rcv.sb_hiwat;
   1326 	if (bufsize > tp->t_ourmss) {
   1327 		bufsize = roundup(bufsize, tp->t_ourmss);
   1328 		if (bufsize > sb_max)
   1329 			bufsize = sb_max;
   1330 		(void) sbreserve(&so->so_rcv, bufsize);
   1331 	}
   1332 }
   1333 
   1334 /*
   1335  * Check if there's an initial rtt or rttvar.  Convert from the
   1336  * route-table units to scaled multiples of the slow timeout timer.
   1337  * Called only during the 3-way handshake.
   1338  */
   1339 void
   1340 tcp_rmx_rtt(tp)
   1341 	struct tcpcb *tp;
   1342 {
   1343 #ifdef RTV_RTT
   1344 	struct rtentry *rt = NULL;
   1345 	int rtt;
   1346 
   1347 	if (tp->t_inpcb)
   1348 		rt = in_pcbrtentry(tp->t_inpcb);
   1349 #ifdef INET6
   1350 	else if (tp->t_in6pcb) {
   1351 #ifdef TCP6
   1352 		rt = NULL;
   1353 #else
   1354 		rt = in6_pcbrtentry(tp->t_in6pcb);
   1355 #endif
   1356 	}
   1357 #endif
   1358 	if (rt == NULL)
   1359 		return;
   1360 
   1361 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
   1362 		/*
   1363 		 * XXX The lock bit for MTU indicates that the value
   1364 		 * is also a minimum value; this is subject to time.
   1365 		 */
   1366 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
   1367 			TCPT_RANGESET(tp->t_rttmin,
   1368 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
   1369 			    TCPTV_MIN, TCPTV_REXMTMAX);
   1370 		tp->t_srtt = rtt /
   1371 		    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
   1372 		if (rt->rt_rmx.rmx_rttvar) {
   1373 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
   1374 			    ((RTM_RTTUNIT / PR_SLOWHZ) >>
   1375 				(TCP_RTTVAR_SHIFT + 2));
   1376 		} else {
   1377 			/* Default variation is +- 1 rtt */
   1378 			tp->t_rttvar =
   1379 			    tp->t_srtt >> (TCP_RTT_SHIFT - TCP_RTTVAR_SHIFT);
   1380 		}
   1381 		TCPT_RANGESET(tp->t_rxtcur,
   1382 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2),
   1383 		    tp->t_rttmin, TCPTV_REXMTMAX);
   1384 	}
   1385 #endif
   1386 }
   1387 
   1388 tcp_seq	 tcp_iss_seq = 0;	/* tcp initial seq # */
   1389 
   1390 /*
   1391  * Get a new sequence value given a tcp control block
   1392  */
   1393 tcp_seq
   1394 tcp_new_iss(tp, len, addin)
   1395 	void            *tp;
   1396 	u_long           len;
   1397 	tcp_seq		 addin;
   1398 {
   1399 	tcp_seq          tcp_iss;
   1400 
   1401 	/*
   1402 	 * Randomize.
   1403 	 */
   1404 #if NRND > 0
   1405 	rnd_extract_data(&tcp_iss, sizeof(tcp_iss), RND_EXTRACT_ANY);
   1406 #else
   1407 	tcp_iss = random();
   1408 #endif
   1409 
   1410 	/*
   1411 	 * If we were asked to add some amount to a known value,
   1412 	 * we will take a random value obtained above, mask off the upper
   1413 	 * bits, and add in the known value.  We also add in a constant to
   1414 	 * ensure that we are at least a certain distance from the original
   1415 	 * value.
   1416 	 *
   1417 	 * This is used when an old connection is in timed wait
   1418 	 * and we have a new one coming in, for instance.
   1419 	 */
   1420 	if (addin != 0) {
   1421 #ifdef TCPISS_DEBUG
   1422 		printf("Random %08x, ", tcp_iss);
   1423 #endif
   1424 		tcp_iss &= TCP_ISS_RANDOM_MASK;
   1425 		tcp_iss += addin + TCP_ISSINCR;
   1426 #ifdef TCPISS_DEBUG
   1427 		printf("Old ISS %08x, ISS %08x\n", addin, tcp_iss);
   1428 #endif
   1429 	} else {
   1430 		tcp_iss &= TCP_ISS_RANDOM_MASK;
   1431 		tcp_iss += tcp_iss_seq;
   1432 		tcp_iss_seq += TCP_ISSINCR;
   1433 #ifdef TCPISS_DEBUG
   1434 		printf("ISS %08x\n", tcp_iss);
   1435 #endif
   1436 	}
   1437 
   1438 	if (tcp_compat_42) {
   1439 		/*
   1440 		 * Limit it to the positive range for really old TCP
   1441 		 * implementations.
   1442 		 */
   1443 		if (tcp_iss >= 0x80000000)
   1444 			tcp_iss &= 0x7fffffff;		/* XXX */
   1445 	}
   1446 
   1447 	return tcp_iss;
   1448 }
   1449 
   1450 #ifdef IPSEC
   1451 /* compute ESP/AH header size for TCP, including outer IP header. */
   1452 size_t
   1453 ipsec4_hdrsiz_tcp(tp)
   1454 	struct tcpcb *tp;
   1455 {
   1456 	struct inpcb *inp;
   1457 	size_t hdrsiz;
   1458 
   1459 	/* XXX mapped addr case (tp->t_in6pcb) */
   1460 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
   1461 		return 0;
   1462 	switch (tp->t_family) {
   1463 	case AF_INET:
   1464 		hdrsiz = ipsec4_hdrsiz(tp->t_template, inp);
   1465 		break;
   1466 	default:
   1467 		hdrsiz = 0;
   1468 		break;
   1469 	}
   1470 
   1471 	return hdrsiz;
   1472 }
   1473 
   1474 #if defined(INET6) && !defined(TCP6)
   1475 size_t
   1476 ipsec6_hdrsiz_tcp(tp)
   1477 	struct tcpcb *tp;
   1478 {
   1479 	struct in6pcb *in6p;
   1480 	size_t hdrsiz;
   1481 
   1482 	if (!tp || !tp->t_template || !(in6p = tp->t_in6pcb))
   1483 		return 0;
   1484 	switch (tp->t_family) {
   1485 	case AF_INET6:
   1486 		hdrsiz = ipsec6_hdrsiz(tp->t_template, in6p);
   1487 		break;
   1488 	case AF_INET:
   1489 		/* mapped address case - tricky */
   1490 	default:
   1491 		hdrsiz = 0;
   1492 		break;
   1493 	}
   1494 
   1495 	return hdrsiz;
   1496 }
   1497 #endif
   1498 #endif /*IPSEC*/
   1499 
   1500 /*
   1501  * Determine the length of the TCP options for this connection.
   1502  *
   1503  * XXX:  What do we do for SACK, when we add that?  Just reserve
   1504  *       all of the space?  Otherwise we can't exactly be incrementing
   1505  *       cwnd by an amount that varies depending on the amount we last
   1506  *       had to SACK!
   1507  */
   1508 
   1509 u_int
   1510 tcp_optlen(tp)
   1511 	struct tcpcb *tp;
   1512 {
   1513 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
   1514 	    (TF_REQ_TSTMP | TF_RCVD_TSTMP))
   1515 		return TCPOLEN_TSTAMP_APPA;
   1516 	else
   1517 		return 0;
   1518 }
   1519