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