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