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