Home | History | Annotate | Line # | Download | only in netinet
tcp_subr.c revision 1.209
      1 /*	$NetBSD: tcp_subr.c,v 1.209 2006/12/06 09:10:45 yamt 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. Neither the name of the University nor the names of its contributors
     82  *    may be used to endorse or promote products derived from this software
     83  *    without specific prior written permission.
     84  *
     85  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     86  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     87  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     88  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     89  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     90  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     91  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     92  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     93  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     94  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     95  * SUCH DAMAGE.
     96  *
     97  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
     98  */
     99 
    100 #include <sys/cdefs.h>
    101 __KERNEL_RCSID(0, "$NetBSD: tcp_subr.c,v 1.209 2006/12/06 09:10:45 yamt Exp $");
    102 
    103 #include "opt_inet.h"
    104 #include "opt_ipsec.h"
    105 #include "opt_tcp_compat_42.h"
    106 #include "opt_inet_csum.h"
    107 #include "opt_mbuftrace.h"
    108 #include "rnd.h"
    109 
    110 #include <sys/param.h>
    111 #include <sys/proc.h>
    112 #include <sys/systm.h>
    113 #include <sys/malloc.h>
    114 #include <sys/mbuf.h>
    115 #include <sys/socket.h>
    116 #include <sys/socketvar.h>
    117 #include <sys/protosw.h>
    118 #include <sys/errno.h>
    119 #include <sys/kernel.h>
    120 #include <sys/pool.h>
    121 #if NRND > 0
    122 #include <sys/md5.h>
    123 #include <sys/rnd.h>
    124 #endif
    125 
    126 #include <net/route.h>
    127 #include <net/if.h>
    128 
    129 #include <netinet/in.h>
    130 #include <netinet/in_systm.h>
    131 #include <netinet/ip.h>
    132 #include <netinet/in_pcb.h>
    133 #include <netinet/ip_var.h>
    134 #include <netinet/ip_icmp.h>
    135 
    136 #ifdef INET6
    137 #ifndef INET
    138 #include <netinet/in.h>
    139 #endif
    140 #include <netinet/ip6.h>
    141 #include <netinet6/in6_pcb.h>
    142 #include <netinet6/ip6_var.h>
    143 #include <netinet6/in6_var.h>
    144 #include <netinet6/ip6protosw.h>
    145 #include <netinet/icmp6.h>
    146 #include <netinet6/nd6.h>
    147 #endif
    148 
    149 #include <netinet/tcp.h>
    150 #include <netinet/tcp_fsm.h>
    151 #include <netinet/tcp_seq.h>
    152 #include <netinet/tcp_timer.h>
    153 #include <netinet/tcp_var.h>
    154 #include <netinet/tcp_congctl.h>
    155 #include <netinet/tcpip.h>
    156 
    157 #ifdef IPSEC
    158 #include <netinet6/ipsec.h>
    159 #include <netkey/key.h>
    160 #endif /*IPSEC*/
    161 
    162 #ifdef FAST_IPSEC
    163 #include <netipsec/ipsec.h>
    164 #include <netipsec/xform.h>
    165 #ifdef INET6
    166 #include <netipsec/ipsec6.h>
    167 #endif
    168  #include <netipsec/key.h>
    169 #endif	/* FAST_IPSEC*/
    170 
    171 
    172 struct	inpcbtable tcbtable;	/* head of queue of active tcpcb's */
    173 struct	tcpstat tcpstat;	/* tcp statistics */
    174 u_int32_t tcp_now;		/* for RFC 1323 timestamps */
    175 
    176 /* patchable/settable parameters for tcp */
    177 int 	tcp_mssdflt = TCP_MSS;
    178 int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
    179 int	tcp_do_rfc1323 = 1;	/* window scaling / timestamps (obsolete) */
    180 #if NRND > 0
    181 int	tcp_do_rfc1948 = 0;	/* ISS by cryptographic hash */
    182 #endif
    183 int	tcp_do_sack = 1;	/* selective acknowledgement */
    184 int	tcp_do_win_scale = 1;	/* RFC1323 window scaling */
    185 int	tcp_do_timestamps = 1;	/* RFC1323 timestamps */
    186 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
    187 int	tcp_do_ecn = 0;		/* Explicit Congestion Notification */
    188 #ifndef TCP_INIT_WIN
    189 #define	TCP_INIT_WIN	0	/* initial slow start window */
    190 #endif
    191 #ifndef TCP_INIT_WIN_LOCAL
    192 #define	TCP_INIT_WIN_LOCAL 4	/* initial slow start window for local nets */
    193 #endif
    194 int	tcp_init_win = TCP_INIT_WIN;
    195 int	tcp_init_win_local = TCP_INIT_WIN_LOCAL;
    196 int	tcp_mss_ifmtu = 0;
    197 #ifdef TCP_COMPAT_42
    198 int	tcp_compat_42 = 1;
    199 #else
    200 int	tcp_compat_42 = 0;
    201 #endif
    202 int	tcp_rst_ppslim = 100;	/* 100pps */
    203 int	tcp_ackdrop_ppslim = 100;	/* 100pps */
    204 int	tcp_do_loopback_cksum = 0;
    205 int	tcp_do_abc = 1;		/* RFC3465 Appropriate byte counting. */
    206 int	tcp_abc_aggressive = 1;	/* 1: L=2*SMSS  0: L=1*SMSS */
    207 int	tcp_sack_tp_maxholes = 32;
    208 int	tcp_sack_globalmaxholes = 1024;
    209 int	tcp_sack_globalholes = 0;
    210 int	tcp_ecn_maxretries = 1;
    211 
    212 /* tcb hash */
    213 #ifndef TCBHASHSIZE
    214 #define	TCBHASHSIZE	128
    215 #endif
    216 int	tcbhashsize = TCBHASHSIZE;
    217 
    218 /* syn hash parameters */
    219 #define	TCP_SYN_HASH_SIZE	293
    220 #define	TCP_SYN_BUCKET_SIZE	35
    221 int	tcp_syn_cache_size = TCP_SYN_HASH_SIZE;
    222 int	tcp_syn_cache_limit = TCP_SYN_HASH_SIZE*TCP_SYN_BUCKET_SIZE;
    223 int	tcp_syn_bucket_limit = 3*TCP_SYN_BUCKET_SIZE;
    224 struct	syn_cache_head tcp_syn_cache[TCP_SYN_HASH_SIZE];
    225 
    226 int	tcp_freeq(struct tcpcb *);
    227 
    228 #ifdef INET
    229 void	tcp_mtudisc_callback(struct in_addr);
    230 #endif
    231 #ifdef INET6
    232 void	tcp6_mtudisc_callback(struct in6_addr *);
    233 #endif
    234 
    235 #ifdef INET6
    236 void	tcp6_mtudisc(struct in6pcb *, int);
    237 #endif
    238 
    239 POOL_INIT(tcpcb_pool, sizeof(struct tcpcb), 0, 0, 0, "tcpcbpl", NULL);
    240 
    241 #ifdef TCP_CSUM_COUNTERS
    242 #include <sys/device.h>
    243 
    244 #if defined(INET)
    245 struct evcnt tcp_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    246     NULL, "tcp", "hwcsum bad");
    247 struct evcnt tcp_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    248     NULL, "tcp", "hwcsum ok");
    249 struct evcnt tcp_hwcsum_data = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    250     NULL, "tcp", "hwcsum data");
    251 struct evcnt tcp_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    252     NULL, "tcp", "swcsum");
    253 
    254 EVCNT_ATTACH_STATIC(tcp_hwcsum_bad);
    255 EVCNT_ATTACH_STATIC(tcp_hwcsum_ok);
    256 EVCNT_ATTACH_STATIC(tcp_hwcsum_data);
    257 EVCNT_ATTACH_STATIC(tcp_swcsum);
    258 #endif /* defined(INET) */
    259 
    260 #if defined(INET6)
    261 struct evcnt tcp6_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    262     NULL, "tcp6", "hwcsum bad");
    263 struct evcnt tcp6_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    264     NULL, "tcp6", "hwcsum ok");
    265 struct evcnt tcp6_hwcsum_data = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    266     NULL, "tcp6", "hwcsum data");
    267 struct evcnt tcp6_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    268     NULL, "tcp6", "swcsum");
    269 
    270 EVCNT_ATTACH_STATIC(tcp6_hwcsum_bad);
    271 EVCNT_ATTACH_STATIC(tcp6_hwcsum_ok);
    272 EVCNT_ATTACH_STATIC(tcp6_hwcsum_data);
    273 EVCNT_ATTACH_STATIC(tcp6_swcsum);
    274 #endif /* defined(INET6) */
    275 #endif /* TCP_CSUM_COUNTERS */
    276 
    277 
    278 #ifdef TCP_OUTPUT_COUNTERS
    279 #include <sys/device.h>
    280 
    281 struct evcnt tcp_output_bigheader = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    282     NULL, "tcp", "output big header");
    283 struct evcnt tcp_output_predict_hit = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    284     NULL, "tcp", "output predict hit");
    285 struct evcnt tcp_output_predict_miss = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    286     NULL, "tcp", "output predict miss");
    287 struct evcnt tcp_output_copysmall = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    288     NULL, "tcp", "output copy small");
    289 struct evcnt tcp_output_copybig = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    290     NULL, "tcp", "output copy big");
    291 struct evcnt tcp_output_refbig = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    292     NULL, "tcp", "output reference big");
    293 
    294 EVCNT_ATTACH_STATIC(tcp_output_bigheader);
    295 EVCNT_ATTACH_STATIC(tcp_output_predict_hit);
    296 EVCNT_ATTACH_STATIC(tcp_output_predict_miss);
    297 EVCNT_ATTACH_STATIC(tcp_output_copysmall);
    298 EVCNT_ATTACH_STATIC(tcp_output_copybig);
    299 EVCNT_ATTACH_STATIC(tcp_output_refbig);
    300 
    301 #endif /* TCP_OUTPUT_COUNTERS */
    302 
    303 #ifdef TCP_REASS_COUNTERS
    304 #include <sys/device.h>
    305 
    306 struct evcnt tcp_reass_ = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    307     NULL, "tcp_reass", "calls");
    308 struct evcnt tcp_reass_empty = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    309     &tcp_reass_, "tcp_reass", "insert into empty queue");
    310 struct evcnt tcp_reass_iteration[8] = {
    311     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", ">7 iterations"),
    312     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "1 iteration"),
    313     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "2 iterations"),
    314     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "3 iterations"),
    315     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "4 iterations"),
    316     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "5 iterations"),
    317     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "6 iterations"),
    318     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "7 iterations"),
    319 };
    320 struct evcnt tcp_reass_prependfirst = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    321     &tcp_reass_, "tcp_reass", "prepend to first");
    322 struct evcnt tcp_reass_prepend = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    323     &tcp_reass_, "tcp_reass", "prepend");
    324 struct evcnt tcp_reass_insert = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    325     &tcp_reass_, "tcp_reass", "insert");
    326 struct evcnt tcp_reass_inserttail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    327     &tcp_reass_, "tcp_reass", "insert at tail");
    328 struct evcnt tcp_reass_append = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    329     &tcp_reass_, "tcp_reass", "append");
    330 struct evcnt tcp_reass_appendtail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    331     &tcp_reass_, "tcp_reass", "append to tail fragment");
    332 struct evcnt tcp_reass_overlaptail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    333     &tcp_reass_, "tcp_reass", "overlap at end");
    334 struct evcnt tcp_reass_overlapfront = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    335     &tcp_reass_, "tcp_reass", "overlap at start");
    336 struct evcnt tcp_reass_segdup = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    337     &tcp_reass_, "tcp_reass", "duplicate segment");
    338 struct evcnt tcp_reass_fragdup = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    339     &tcp_reass_, "tcp_reass", "duplicate fragment");
    340 
    341 EVCNT_ATTACH_STATIC(tcp_reass_);
    342 EVCNT_ATTACH_STATIC(tcp_reass_empty);
    343 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 0);
    344 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 1);
    345 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 2);
    346 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 3);
    347 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 4);
    348 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 5);
    349 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 6);
    350 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 7);
    351 EVCNT_ATTACH_STATIC(tcp_reass_prependfirst);
    352 EVCNT_ATTACH_STATIC(tcp_reass_prepend);
    353 EVCNT_ATTACH_STATIC(tcp_reass_insert);
    354 EVCNT_ATTACH_STATIC(tcp_reass_inserttail);
    355 EVCNT_ATTACH_STATIC(tcp_reass_append);
    356 EVCNT_ATTACH_STATIC(tcp_reass_appendtail);
    357 EVCNT_ATTACH_STATIC(tcp_reass_overlaptail);
    358 EVCNT_ATTACH_STATIC(tcp_reass_overlapfront);
    359 EVCNT_ATTACH_STATIC(tcp_reass_segdup);
    360 EVCNT_ATTACH_STATIC(tcp_reass_fragdup);
    361 
    362 #endif /* TCP_REASS_COUNTERS */
    363 
    364 #ifdef MBUFTRACE
    365 struct mowner tcp_mowner = MOWNER_INIT("tcp", "");
    366 struct mowner tcp_rx_mowner = MOWNER_INIT("tcp", "rx");
    367 struct mowner tcp_tx_mowner = MOWNER_INIT("tcp", "tx");
    368 struct mowner tcp_sock_mowner = MOWNER_INIT("tcp", "sock");
    369 struct mowner tcp_sock_rx_mowner = MOWNER_INIT("tcp", "sock rx");
    370 struct mowner tcp_sock_tx_mowner = MOWNER_INIT("tcp", "sock tx");
    371 #endif
    372 
    373 /*
    374  * Tcp initialization
    375  */
    376 void
    377 tcp_init(void)
    378 {
    379 	int hlen;
    380 
    381 	/* Initialize the TCPCB template. */
    382 	tcp_tcpcb_template();
    383 
    384 	in_pcbinit(&tcbtable, tcbhashsize, tcbhashsize);
    385 
    386 	hlen = sizeof(struct ip) + sizeof(struct tcphdr);
    387 #ifdef INET6
    388 	if (sizeof(struct ip) < sizeof(struct ip6_hdr))
    389 		hlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
    390 #endif
    391 	if (max_protohdr < hlen)
    392 		max_protohdr = hlen;
    393 	if (max_linkhdr + hlen > MHLEN)
    394 		panic("tcp_init");
    395 
    396 #ifdef INET
    397 	icmp_mtudisc_callback_register(tcp_mtudisc_callback);
    398 #endif
    399 #ifdef INET6
    400 	icmp6_mtudisc_callback_register(tcp6_mtudisc_callback);
    401 #endif
    402 
    403 	/* Initialize timer state. */
    404 	tcp_timer_init();
    405 
    406 	/* Initialize the compressed state engine. */
    407 	syn_cache_init();
    408 
    409 	/* Initialize the congestion control algorithms. */
    410 	tcp_congctl_init();
    411 
    412 	MOWNER_ATTACH(&tcp_tx_mowner);
    413 	MOWNER_ATTACH(&tcp_rx_mowner);
    414 	MOWNER_ATTACH(&tcp_reass_mowner);
    415 	MOWNER_ATTACH(&tcp_sock_mowner);
    416 	MOWNER_ATTACH(&tcp_sock_tx_mowner);
    417 	MOWNER_ATTACH(&tcp_sock_rx_mowner);
    418 	MOWNER_ATTACH(&tcp_mowner);
    419 }
    420 
    421 /*
    422  * Create template to be used to send tcp packets on a connection.
    423  * Call after host entry created, allocates an mbuf and fills
    424  * in a skeletal tcp/ip header, minimizing the amount of work
    425  * necessary when the connection is used.
    426  */
    427 struct mbuf *
    428 tcp_template(struct tcpcb *tp)
    429 {
    430 	struct inpcb *inp = tp->t_inpcb;
    431 #ifdef INET6
    432 	struct in6pcb *in6p = tp->t_in6pcb;
    433 #endif
    434 	struct tcphdr *n;
    435 	struct mbuf *m;
    436 	int hlen;
    437 
    438 	switch (tp->t_family) {
    439 	case AF_INET:
    440 		hlen = sizeof(struct ip);
    441 		if (inp)
    442 			break;
    443 #ifdef INET6
    444 		if (in6p) {
    445 			/* mapped addr case */
    446 			if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_laddr)
    447 			 && IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr))
    448 				break;
    449 		}
    450 #endif
    451 		return NULL;	/*EINVAL*/
    452 #ifdef INET6
    453 	case AF_INET6:
    454 		hlen = sizeof(struct ip6_hdr);
    455 		if (in6p) {
    456 			/* more sainty check? */
    457 			break;
    458 		}
    459 		return NULL;	/*EINVAL*/
    460 #endif
    461 	default:
    462 		hlen = 0;	/*pacify gcc*/
    463 		return NULL;	/*EAFNOSUPPORT*/
    464 	}
    465 #ifdef DIAGNOSTIC
    466 	if (hlen + sizeof(struct tcphdr) > MCLBYTES)
    467 		panic("mclbytes too small for t_template");
    468 #endif
    469 	m = tp->t_template;
    470 	if (m && m->m_len == hlen + sizeof(struct tcphdr))
    471 		;
    472 	else {
    473 		if (m)
    474 			m_freem(m);
    475 		m = tp->t_template = NULL;
    476 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    477 		if (m && hlen + sizeof(struct tcphdr) > MHLEN) {
    478 			MCLGET(m, M_DONTWAIT);
    479 			if ((m->m_flags & M_EXT) == 0) {
    480 				m_free(m);
    481 				m = NULL;
    482 			}
    483 		}
    484 		if (m == NULL)
    485 			return NULL;
    486 		MCLAIM(m, &tcp_mowner);
    487 		m->m_pkthdr.len = m->m_len = hlen + sizeof(struct tcphdr);
    488 	}
    489 
    490 	bzero(mtod(m, caddr_t), m->m_len);
    491 
    492 	n = (struct tcphdr *)(mtod(m, caddr_t) + hlen);
    493 
    494 	switch (tp->t_family) {
    495 	case AF_INET:
    496 	    {
    497 		struct ipovly *ipov;
    498 		mtod(m, struct ip *)->ip_v = 4;
    499 		mtod(m, struct ip *)->ip_hl = hlen >> 2;
    500 		ipov = mtod(m, struct ipovly *);
    501 		ipov->ih_pr = IPPROTO_TCP;
    502 		ipov->ih_len = htons(sizeof(struct tcphdr));
    503 		if (inp) {
    504 			ipov->ih_src = inp->inp_laddr;
    505 			ipov->ih_dst = inp->inp_faddr;
    506 		}
    507 #ifdef INET6
    508 		else if (in6p) {
    509 			/* mapped addr case */
    510 			bcopy(&in6p->in6p_laddr.s6_addr32[3], &ipov->ih_src,
    511 				sizeof(ipov->ih_src));
    512 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &ipov->ih_dst,
    513 				sizeof(ipov->ih_dst));
    514 		}
    515 #endif
    516 		/*
    517 		 * Compute the pseudo-header portion of the checksum
    518 		 * now.  We incrementally add in the TCP option and
    519 		 * payload lengths later, and then compute the TCP
    520 		 * checksum right before the packet is sent off onto
    521 		 * the wire.
    522 		 */
    523 		n->th_sum = in_cksum_phdr(ipov->ih_src.s_addr,
    524 		    ipov->ih_dst.s_addr,
    525 		    htons(sizeof(struct tcphdr) + IPPROTO_TCP));
    526 		break;
    527 	    }
    528 #ifdef INET6
    529 	case AF_INET6:
    530 	    {
    531 		struct ip6_hdr *ip6;
    532 		mtod(m, struct ip *)->ip_v = 6;
    533 		ip6 = mtod(m, struct ip6_hdr *);
    534 		ip6->ip6_nxt = IPPROTO_TCP;
    535 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
    536 		ip6->ip6_src = in6p->in6p_laddr;
    537 		ip6->ip6_dst = in6p->in6p_faddr;
    538 		ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK;
    539 		if (ip6_auto_flowlabel) {
    540 			ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
    541 			ip6->ip6_flow |=
    542 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
    543 		}
    544 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
    545 		ip6->ip6_vfc |= IPV6_VERSION;
    546 
    547 		/*
    548 		 * Compute the pseudo-header portion of the checksum
    549 		 * now.  We incrementally add in the TCP option and
    550 		 * payload lengths later, and then compute the TCP
    551 		 * checksum right before the packet is sent off onto
    552 		 * the wire.
    553 		 */
    554 		n->th_sum = in6_cksum_phdr(&in6p->in6p_laddr,
    555 		    &in6p->in6p_faddr, htonl(sizeof(struct tcphdr)),
    556 		    htonl(IPPROTO_TCP));
    557 		break;
    558 	    }
    559 #endif
    560 	}
    561 	if (inp) {
    562 		n->th_sport = inp->inp_lport;
    563 		n->th_dport = inp->inp_fport;
    564 	}
    565 #ifdef INET6
    566 	else if (in6p) {
    567 		n->th_sport = in6p->in6p_lport;
    568 		n->th_dport = in6p->in6p_fport;
    569 	}
    570 #endif
    571 	n->th_seq = 0;
    572 	n->th_ack = 0;
    573 	n->th_x2 = 0;
    574 	n->th_off = 5;
    575 	n->th_flags = 0;
    576 	n->th_win = 0;
    577 	n->th_urp = 0;
    578 	return (m);
    579 }
    580 
    581 /*
    582  * Send a single message to the TCP at address specified by
    583  * the given TCP/IP header.  If m == 0, then we make a copy
    584  * of the tcpiphdr at ti and send directly to the addressed host.
    585  * This is used to force keep alive messages out using the TCP
    586  * template for a connection tp->t_template.  If flags are given
    587  * then we send a message back to the TCP which originated the
    588  * segment ti, and discard the mbuf containing it and any other
    589  * attached mbufs.
    590  *
    591  * In any case the ack and sequence number of the transmitted
    592  * segment are as specified by the parameters.
    593  */
    594 int
    595 tcp_respond(struct tcpcb *tp, struct mbuf *template, struct mbuf *m,
    596     struct tcphdr *th0, tcp_seq ack, tcp_seq seq, int flags)
    597 {
    598 	struct route *ro;
    599 	int error, tlen, win = 0;
    600 	int hlen;
    601 	struct ip *ip;
    602 #ifdef INET6
    603 	struct ip6_hdr *ip6;
    604 #endif
    605 	int family;	/* family on packet, not inpcb/in6pcb! */
    606 	struct tcphdr *th;
    607 	struct socket *so;
    608 
    609 	if (tp != NULL && (flags & TH_RST) == 0) {
    610 #ifdef DIAGNOSTIC
    611 		if (tp->t_inpcb && tp->t_in6pcb)
    612 			panic("tcp_respond: both t_inpcb and t_in6pcb are set");
    613 #endif
    614 #ifdef INET
    615 		if (tp->t_inpcb)
    616 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
    617 #endif
    618 #ifdef INET6
    619 		if (tp->t_in6pcb)
    620 			win = sbspace(&tp->t_in6pcb->in6p_socket->so_rcv);
    621 #endif
    622 	}
    623 
    624 	th = NULL;	/* Quell uninitialized warning */
    625 	ip = NULL;
    626 #ifdef INET6
    627 	ip6 = NULL;
    628 #endif
    629 	if (m == 0) {
    630 		if (!template)
    631 			return EINVAL;
    632 
    633 		/* get family information from template */
    634 		switch (mtod(template, struct ip *)->ip_v) {
    635 		case 4:
    636 			family = AF_INET;
    637 			hlen = sizeof(struct ip);
    638 			break;
    639 #ifdef INET6
    640 		case 6:
    641 			family = AF_INET6;
    642 			hlen = sizeof(struct ip6_hdr);
    643 			break;
    644 #endif
    645 		default:
    646 			return EAFNOSUPPORT;
    647 		}
    648 
    649 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    650 		if (m) {
    651 			MCLAIM(m, &tcp_tx_mowner);
    652 			MCLGET(m, M_DONTWAIT);
    653 			if ((m->m_flags & M_EXT) == 0) {
    654 				m_free(m);
    655 				m = NULL;
    656 			}
    657 		}
    658 		if (m == NULL)
    659 			return (ENOBUFS);
    660 
    661 		if (tcp_compat_42)
    662 			tlen = 1;
    663 		else
    664 			tlen = 0;
    665 
    666 		m->m_data += max_linkhdr;
    667 		bcopy(mtod(template, caddr_t), mtod(m, caddr_t),
    668 			template->m_len);
    669 		switch (family) {
    670 		case AF_INET:
    671 			ip = mtod(m, struct ip *);
    672 			th = (struct tcphdr *)(ip + 1);
    673 			break;
    674 #ifdef INET6
    675 		case AF_INET6:
    676 			ip6 = mtod(m, struct ip6_hdr *);
    677 			th = (struct tcphdr *)(ip6 + 1);
    678 			break;
    679 #endif
    680 #if 0
    681 		default:
    682 			/* noone will visit here */
    683 			m_freem(m);
    684 			return EAFNOSUPPORT;
    685 #endif
    686 		}
    687 		flags = TH_ACK;
    688 	} else {
    689 
    690 		if ((m->m_flags & M_PKTHDR) == 0) {
    691 #if 0
    692 			printf("non PKTHDR to tcp_respond\n");
    693 #endif
    694 			m_freem(m);
    695 			return EINVAL;
    696 		}
    697 #ifdef DIAGNOSTIC
    698 		if (!th0)
    699 			panic("th0 == NULL in tcp_respond");
    700 #endif
    701 
    702 		/* get family information from m */
    703 		switch (mtod(m, struct ip *)->ip_v) {
    704 		case 4:
    705 			family = AF_INET;
    706 			hlen = sizeof(struct ip);
    707 			ip = mtod(m, struct ip *);
    708 			break;
    709 #ifdef INET6
    710 		case 6:
    711 			family = AF_INET6;
    712 			hlen = sizeof(struct ip6_hdr);
    713 			ip6 = mtod(m, struct ip6_hdr *);
    714 			break;
    715 #endif
    716 		default:
    717 			m_freem(m);
    718 			return EAFNOSUPPORT;
    719 		}
    720 		/* clear h/w csum flags inherited from rx packet */
    721 		m->m_pkthdr.csum_flags = 0;
    722 
    723 		if ((flags & TH_SYN) == 0 || sizeof(*th0) > (th0->th_off << 2))
    724 			tlen = sizeof(*th0);
    725 		else
    726 			tlen = th0->th_off << 2;
    727 
    728 		if (m->m_len > hlen + tlen && (m->m_flags & M_EXT) == 0 &&
    729 		    mtod(m, caddr_t) + hlen == (caddr_t)th0) {
    730 			m->m_len = hlen + tlen;
    731 			m_freem(m->m_next);
    732 			m->m_next = NULL;
    733 		} else {
    734 			struct mbuf *n;
    735 
    736 #ifdef DIAGNOSTIC
    737 			if (max_linkhdr + hlen + tlen > MCLBYTES) {
    738 				m_freem(m);
    739 				return EMSGSIZE;
    740 			}
    741 #endif
    742 			MGETHDR(n, M_DONTWAIT, MT_HEADER);
    743 			if (n && max_linkhdr + hlen + tlen > MHLEN) {
    744 				MCLGET(n, M_DONTWAIT);
    745 				if ((n->m_flags & M_EXT) == 0) {
    746 					m_freem(n);
    747 					n = NULL;
    748 				}
    749 			}
    750 			if (!n) {
    751 				m_freem(m);
    752 				return ENOBUFS;
    753 			}
    754 
    755 			MCLAIM(n, &tcp_tx_mowner);
    756 			n->m_data += max_linkhdr;
    757 			n->m_len = hlen + tlen;
    758 			m_copyback(n, 0, hlen, mtod(m, caddr_t));
    759 			m_copyback(n, hlen, tlen, (caddr_t)th0);
    760 
    761 			m_freem(m);
    762 			m = n;
    763 			n = NULL;
    764 		}
    765 
    766 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
    767 		switch (family) {
    768 		case AF_INET:
    769 			ip = mtod(m, struct ip *);
    770 			th = (struct tcphdr *)(ip + 1);
    771 			ip->ip_p = IPPROTO_TCP;
    772 			xchg(ip->ip_dst, ip->ip_src, struct in_addr);
    773 			ip->ip_p = IPPROTO_TCP;
    774 			break;
    775 #ifdef INET6
    776 		case AF_INET6:
    777 			ip6 = mtod(m, struct ip6_hdr *);
    778 			th = (struct tcphdr *)(ip6 + 1);
    779 			ip6->ip6_nxt = IPPROTO_TCP;
    780 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
    781 			ip6->ip6_nxt = IPPROTO_TCP;
    782 			break;
    783 #endif
    784 #if 0
    785 		default:
    786 			/* noone will visit here */
    787 			m_freem(m);
    788 			return EAFNOSUPPORT;
    789 #endif
    790 		}
    791 		xchg(th->th_dport, th->th_sport, u_int16_t);
    792 #undef xchg
    793 		tlen = 0;	/*be friendly with the following code*/
    794 	}
    795 	th->th_seq = htonl(seq);
    796 	th->th_ack = htonl(ack);
    797 	th->th_x2 = 0;
    798 	if ((flags & TH_SYN) == 0) {
    799 		if (tp)
    800 			win >>= tp->rcv_scale;
    801 		if (win > TCP_MAXWIN)
    802 			win = TCP_MAXWIN;
    803 		th->th_win = htons((u_int16_t)win);
    804 		th->th_off = sizeof (struct tcphdr) >> 2;
    805 		tlen += sizeof(*th);
    806 	} else
    807 		tlen += th->th_off << 2;
    808 	m->m_len = hlen + tlen;
    809 	m->m_pkthdr.len = hlen + tlen;
    810 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
    811 	th->th_flags = flags;
    812 	th->th_urp = 0;
    813 
    814 	switch (family) {
    815 #ifdef INET
    816 	case AF_INET:
    817 	    {
    818 		struct ipovly *ipov = (struct ipovly *)ip;
    819 		bzero(ipov->ih_x1, sizeof ipov->ih_x1);
    820 		ipov->ih_len = htons((u_int16_t)tlen);
    821 
    822 		th->th_sum = 0;
    823 		th->th_sum = in_cksum(m, hlen + tlen);
    824 		ip->ip_len = htons(hlen + tlen);
    825 		ip->ip_ttl = ip_defttl;
    826 		break;
    827 	    }
    828 #endif
    829 #ifdef INET6
    830 	case AF_INET6:
    831 	    {
    832 		th->th_sum = 0;
    833 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
    834 				tlen);
    835 		ip6->ip6_plen = htons(tlen);
    836 		if (tp && tp->t_in6pcb) {
    837 			struct ifnet *oifp;
    838 			ro = (struct route *)&tp->t_in6pcb->in6p_route;
    839 			oifp = ro->ro_rt ? ro->ro_rt->rt_ifp : NULL;
    840 			ip6->ip6_hlim = in6_selecthlim(tp->t_in6pcb, oifp);
    841 		} else
    842 			ip6->ip6_hlim = ip6_defhlim;
    843 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
    844 		if (ip6_auto_flowlabel) {
    845 			ip6->ip6_flow |=
    846 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
    847 		}
    848 		break;
    849 	    }
    850 #endif
    851 	}
    852 
    853 	if (tp && tp->t_inpcb)
    854 		so = tp->t_inpcb->inp_socket;
    855 #ifdef INET6
    856 	else if (tp && tp->t_in6pcb)
    857 		so = tp->t_in6pcb->in6p_socket;
    858 #endif
    859 	else
    860 		so = NULL;
    861 
    862 	if (tp != NULL && tp->t_inpcb != NULL) {
    863 		ro = &tp->t_inpcb->inp_route;
    864 #ifdef DIAGNOSTIC
    865 		if (family != AF_INET)
    866 			panic("tcp_respond: address family mismatch");
    867 		if (!in_hosteq(ip->ip_dst, tp->t_inpcb->inp_faddr)) {
    868 			panic("tcp_respond: ip_dst %x != inp_faddr %x",
    869 			    ntohl(ip->ip_dst.s_addr),
    870 			    ntohl(tp->t_inpcb->inp_faddr.s_addr));
    871 		}
    872 #endif
    873 	}
    874 #ifdef INET6
    875 	else if (tp != NULL && tp->t_in6pcb != NULL) {
    876 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
    877 #ifdef DIAGNOSTIC
    878 		if (family == AF_INET) {
    879 			if (!IN6_IS_ADDR_V4MAPPED(&tp->t_in6pcb->in6p_faddr))
    880 				panic("tcp_respond: not mapped addr");
    881 			if (bcmp(&ip->ip_dst,
    882 			    &tp->t_in6pcb->in6p_faddr.s6_addr32[3],
    883 			    sizeof(ip->ip_dst)) != 0) {
    884 				panic("tcp_respond: ip_dst != in6p_faddr");
    885 			}
    886 		} else if (family == AF_INET6) {
    887 			if (!IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
    888 			    &tp->t_in6pcb->in6p_faddr))
    889 				panic("tcp_respond: ip6_dst != in6p_faddr");
    890 		} else
    891 			panic("tcp_respond: address family mismatch");
    892 #endif
    893 	}
    894 #endif
    895 	else
    896 		ro = NULL;
    897 
    898 	switch (family) {
    899 #ifdef INET
    900 	case AF_INET:
    901 		error = ip_output(m, NULL, ro,
    902 		    (tp && tp->t_mtudisc ? IP_MTUDISC : 0),
    903 		    (struct ip_moptions *)0, so);
    904 		break;
    905 #endif
    906 #ifdef INET6
    907 	case AF_INET6:
    908 		error = ip6_output(m, NULL, (struct route_in6 *)ro, 0,
    909 		    (struct ip6_moptions *)0, so, NULL);
    910 		break;
    911 #endif
    912 	default:
    913 		error = EAFNOSUPPORT;
    914 		break;
    915 	}
    916 
    917 	return (error);
    918 }
    919 
    920 /*
    921  * Template TCPCB.  Rather than zeroing a new TCPCB and initializing
    922  * a bunch of members individually, we maintain this template for the
    923  * static and mostly-static components of the TCPCB, and copy it into
    924  * the new TCPCB instead.
    925  */
    926 static struct tcpcb tcpcb_template = {
    927 	/*
    928 	 * If TCP_NTIMERS ever changes, we'll need to update this
    929 	 * initializer.
    930 	 */
    931 	.t_timer = {
    932 		CALLOUT_INITIALIZER,
    933 		CALLOUT_INITIALIZER,
    934 		CALLOUT_INITIALIZER,
    935 		CALLOUT_INITIALIZER,
    936 	},
    937 	.t_delack_ch = CALLOUT_INITIALIZER,
    938 
    939 	.t_srtt = TCPTV_SRTTBASE,
    940 	.t_rttmin = TCPTV_MIN,
    941 
    942 	.snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT,
    943 	.snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT,
    944 	.snd_numholes = 0,
    945 
    946 	.t_partialacks = -1,
    947 	.t_bytes_acked = 0,
    948 };
    949 
    950 /*
    951  * Updates the TCPCB template whenever a parameter that would affect
    952  * the template is changed.
    953  */
    954 void
    955 tcp_tcpcb_template(void)
    956 {
    957 	struct tcpcb *tp = &tcpcb_template;
    958 	int flags;
    959 
    960 	tp->t_peermss = tcp_mssdflt;
    961 	tp->t_ourmss = tcp_mssdflt;
    962 	tp->t_segsz = tcp_mssdflt;
    963 
    964 	flags = 0;
    965 	if (tcp_do_rfc1323 && tcp_do_win_scale)
    966 		flags |= TF_REQ_SCALE;
    967 	if (tcp_do_rfc1323 && tcp_do_timestamps)
    968 		flags |= TF_REQ_TSTMP;
    969 	tp->t_flags = flags;
    970 
    971 	/*
    972 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
    973 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
    974 	 * reasonable initial retransmit time.
    975 	 */
    976 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ << (TCP_RTTVAR_SHIFT + 2 - 1);
    977 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
    978 	    TCPTV_MIN, TCPTV_REXMTMAX);
    979 }
    980 
    981 /*
    982  * Create a new TCP control block, making an
    983  * empty reassembly queue and hooking it to the argument
    984  * protocol control block.
    985  */
    986 /* family selects inpcb, or in6pcb */
    987 struct tcpcb *
    988 tcp_newtcpcb(int family, void *aux)
    989 {
    990 	struct tcpcb *tp;
    991 	int i;
    992 
    993 	/* XXX Consider using a pool_cache for speed. */
    994 	tp = pool_get(&tcpcb_pool, PR_NOWAIT);	/* splsoftnet via tcp_usrreq */
    995 	if (tp == NULL)
    996 		return (NULL);
    997 	memcpy(tp, &tcpcb_template, sizeof(*tp));
    998 	TAILQ_INIT(&tp->segq);
    999 	TAILQ_INIT(&tp->timeq);
   1000 	tp->t_family = family;		/* may be overridden later on */
   1001 	TAILQ_INIT(&tp->snd_holes);
   1002 	LIST_INIT(&tp->t_sc);		/* XXX can template this */
   1003 
   1004 	/* Don't sweat this loop; hopefully the compiler will unroll it. */
   1005 	for (i = 0; i < TCPT_NTIMERS; i++)
   1006 		TCP_TIMER_INIT(tp, i);
   1007 
   1008 	switch (family) {
   1009 	case AF_INET:
   1010 	    {
   1011 		struct inpcb *inp = (struct inpcb *)aux;
   1012 
   1013 		inp->inp_ip.ip_ttl = ip_defttl;
   1014 		inp->inp_ppcb = (caddr_t)tp;
   1015 
   1016 		tp->t_inpcb = inp;
   1017 		tp->t_mtudisc = ip_mtudisc;
   1018 		break;
   1019 	    }
   1020 #ifdef INET6
   1021 	case AF_INET6:
   1022 	    {
   1023 		struct in6pcb *in6p = (struct in6pcb *)aux;
   1024 
   1025 		in6p->in6p_ip6.ip6_hlim = in6_selecthlim(in6p,
   1026 			in6p->in6p_route.ro_rt ? in6p->in6p_route.ro_rt->rt_ifp
   1027 					       : NULL);
   1028 		in6p->in6p_ppcb = (caddr_t)tp;
   1029 
   1030 		tp->t_in6pcb = in6p;
   1031 		/* for IPv6, always try to run path MTU discovery */
   1032 		tp->t_mtudisc = 1;
   1033 		break;
   1034 	    }
   1035 #endif /* INET6 */
   1036 	default:
   1037 		pool_put(&tcpcb_pool, tp);	/* splsoftnet via tcp_usrreq */
   1038 		return (NULL);
   1039 	}
   1040 
   1041 	/*
   1042 	 * Initialize our timebase.  When we send timestamps, we take
   1043 	 * the delta from tcp_now -- this means each connection always
   1044 	 * gets a timebase of 0, which makes it, among other things,
   1045 	 * more difficult to determine how long a system has been up,
   1046 	 * and thus how many TCP sequence increments have occurred.
   1047 	 */
   1048 	tp->ts_timebase = tcp_now;
   1049 
   1050 	tp->t_congctl = tcp_congctl_global;
   1051 	tp->t_congctl->refcnt++;
   1052 
   1053 	return (tp);
   1054 }
   1055 
   1056 /*
   1057  * Drop a TCP connection, reporting
   1058  * the specified error.  If connection is synchronized,
   1059  * then send a RST to peer.
   1060  */
   1061 struct tcpcb *
   1062 tcp_drop(struct tcpcb *tp, int errno)
   1063 {
   1064 	struct socket *so = NULL;
   1065 
   1066 #ifdef DIAGNOSTIC
   1067 	if (tp->t_inpcb && tp->t_in6pcb)
   1068 		panic("tcp_drop: both t_inpcb and t_in6pcb are set");
   1069 #endif
   1070 #ifdef INET
   1071 	if (tp->t_inpcb)
   1072 		so = tp->t_inpcb->inp_socket;
   1073 #endif
   1074 #ifdef INET6
   1075 	if (tp->t_in6pcb)
   1076 		so = tp->t_in6pcb->in6p_socket;
   1077 #endif
   1078 	if (!so)
   1079 		return NULL;
   1080 
   1081 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
   1082 		tp->t_state = TCPS_CLOSED;
   1083 		(void) tcp_output(tp);
   1084 		tcpstat.tcps_drops++;
   1085 	} else
   1086 		tcpstat.tcps_conndrops++;
   1087 	if (errno == ETIMEDOUT && tp->t_softerror)
   1088 		errno = tp->t_softerror;
   1089 	so->so_error = errno;
   1090 	return (tcp_close(tp));
   1091 }
   1092 
   1093 /*
   1094  * Return whether this tcpcb is marked as dead, indicating
   1095  * to the calling timer function that no further action should
   1096  * be taken, as we are about to release this tcpcb.  The release
   1097  * of the storage will be done if this is the last timer running.
   1098  *
   1099  * This should be called from the callout handler function after
   1100  * callout_ack() is done, so that the number of invoking timer
   1101  * functions is 0.
   1102  */
   1103 int
   1104 tcp_isdead(struct tcpcb *tp)
   1105 {
   1106 	int dead = (tp->t_flags & TF_DEAD);
   1107 
   1108 	if (__predict_false(dead)) {
   1109 		if (tcp_timers_invoking(tp) > 0)
   1110 				/* not quite there yet -- count separately? */
   1111 			return dead;
   1112 		tcpstat.tcps_delayed_free++;
   1113 		pool_put(&tcpcb_pool, tp);	/* splsoftnet via tcp_timer.c */
   1114 	}
   1115 	return dead;
   1116 }
   1117 
   1118 /*
   1119  * Close a TCP control block:
   1120  *	discard all space held by the tcp
   1121  *	discard internet protocol block
   1122  *	wake up any sleepers
   1123  */
   1124 struct tcpcb *
   1125 tcp_close(struct tcpcb *tp)
   1126 {
   1127 	struct inpcb *inp;
   1128 #ifdef INET6
   1129 	struct in6pcb *in6p;
   1130 #endif
   1131 	struct socket *so;
   1132 #ifdef RTV_RTT
   1133 	struct rtentry *rt;
   1134 #endif
   1135 	struct route *ro;
   1136 
   1137 	inp = tp->t_inpcb;
   1138 #ifdef INET6
   1139 	in6p = tp->t_in6pcb;
   1140 #endif
   1141 	so = NULL;
   1142 	ro = NULL;
   1143 	if (inp) {
   1144 		so = inp->inp_socket;
   1145 		ro = &inp->inp_route;
   1146 	}
   1147 #ifdef INET6
   1148 	else if (in6p) {
   1149 		so = in6p->in6p_socket;
   1150 		ro = (struct route *)&in6p->in6p_route;
   1151 	}
   1152 #endif
   1153 
   1154 #ifdef RTV_RTT
   1155 	/*
   1156 	 * If we sent enough data to get some meaningful characteristics,
   1157 	 * save them in the routing entry.  'Enough' is arbitrarily
   1158 	 * defined as the sendpipesize (default 4K) * 16.  This would
   1159 	 * give us 16 rtt samples assuming we only get one sample per
   1160 	 * window (the usual case on a long haul net).  16 samples is
   1161 	 * enough for the srtt filter to converge to within 5% of the correct
   1162 	 * value; fewer samples and we could save a very bogus rtt.
   1163 	 *
   1164 	 * Don't update the default route's characteristics and don't
   1165 	 * update anything that the user "locked".
   1166 	 */
   1167 	if (SEQ_LT(tp->iss + so->so_snd.sb_hiwat * 16, tp->snd_max) &&
   1168 	    ro && (rt = ro->ro_rt) &&
   1169 	    !in_nullhost(satosin(rt_key(rt))->sin_addr)) {
   1170 		u_long i = 0;
   1171 
   1172 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
   1173 			i = tp->t_srtt *
   1174 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
   1175 			if (rt->rt_rmx.rmx_rtt && i)
   1176 				/*
   1177 				 * filter this update to half the old & half
   1178 				 * the new values, converting scale.
   1179 				 * See route.h and tcp_var.h for a
   1180 				 * description of the scaling constants.
   1181 				 */
   1182 				rt->rt_rmx.rmx_rtt =
   1183 				    (rt->rt_rmx.rmx_rtt + i) / 2;
   1184 			else
   1185 				rt->rt_rmx.rmx_rtt = i;
   1186 		}
   1187 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
   1188 			i = tp->t_rttvar *
   1189 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTTVAR_SHIFT + 2));
   1190 			if (rt->rt_rmx.rmx_rttvar && i)
   1191 				rt->rt_rmx.rmx_rttvar =
   1192 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
   1193 			else
   1194 				rt->rt_rmx.rmx_rttvar = i;
   1195 		}
   1196 		/*
   1197 		 * update the pipelimit (ssthresh) if it has been updated
   1198 		 * already or if a pipesize was specified & the threshhold
   1199 		 * got below half the pipesize.  I.e., wait for bad news
   1200 		 * before we start updating, then update on both good
   1201 		 * and bad news.
   1202 		 */
   1203 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
   1204 		    (i = tp->snd_ssthresh) && rt->rt_rmx.rmx_ssthresh) ||
   1205 		    i < (rt->rt_rmx.rmx_sendpipe / 2)) {
   1206 			/*
   1207 			 * convert the limit from user data bytes to
   1208 			 * packets then to packet data bytes.
   1209 			 */
   1210 			i = (i + tp->t_segsz / 2) / tp->t_segsz;
   1211 			if (i < 2)
   1212 				i = 2;
   1213 			i *= (u_long)(tp->t_segsz + sizeof (struct tcpiphdr));
   1214 			if (rt->rt_rmx.rmx_ssthresh)
   1215 				rt->rt_rmx.rmx_ssthresh =
   1216 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
   1217 			else
   1218 				rt->rt_rmx.rmx_ssthresh = i;
   1219 		}
   1220 	}
   1221 #endif /* RTV_RTT */
   1222 	/* free the reassembly queue, if any */
   1223 	TCP_REASS_LOCK(tp);
   1224 	(void) tcp_freeq(tp);
   1225 	TCP_REASS_UNLOCK(tp);
   1226 
   1227 	/* free the SACK holes list. */
   1228 	tcp_free_sackholes(tp);
   1229 
   1230 	tp->t_congctl->refcnt--;
   1231 
   1232 	tcp_canceltimers(tp);
   1233 	TCP_CLEAR_DELACK(tp);
   1234 	syn_cache_cleanup(tp);
   1235 
   1236 	if (tp->t_template) {
   1237 		m_free(tp->t_template);
   1238 		tp->t_template = NULL;
   1239 	}
   1240 	if (tcp_timers_invoking(tp))
   1241 		tp->t_flags |= TF_DEAD;
   1242 	else
   1243 		pool_put(&tcpcb_pool, tp);
   1244 
   1245 	if (inp) {
   1246 		inp->inp_ppcb = 0;
   1247 		soisdisconnected(so);
   1248 		in_pcbdetach(inp);
   1249 	}
   1250 #ifdef INET6
   1251 	else if (in6p) {
   1252 		in6p->in6p_ppcb = 0;
   1253 		soisdisconnected(so);
   1254 		in6_pcbdetach(in6p);
   1255 	}
   1256 #endif
   1257 	tcpstat.tcps_closed++;
   1258 	return ((struct tcpcb *)0);
   1259 }
   1260 
   1261 int
   1262 tcp_freeq(tp)
   1263 	struct tcpcb *tp;
   1264 {
   1265 	struct ipqent *qe;
   1266 	int rv = 0;
   1267 #ifdef TCPREASS_DEBUG
   1268 	int i = 0;
   1269 #endif
   1270 
   1271 	TCP_REASS_LOCK_CHECK(tp);
   1272 
   1273 	while ((qe = TAILQ_FIRST(&tp->segq)) != NULL) {
   1274 #ifdef TCPREASS_DEBUG
   1275 		printf("tcp_freeq[%p,%d]: %u:%u(%u) 0x%02x\n",
   1276 			tp, i++, qe->ipqe_seq, qe->ipqe_seq + qe->ipqe_len,
   1277 			qe->ipqe_len, qe->ipqe_flags & (TH_SYN|TH_FIN|TH_RST));
   1278 #endif
   1279 		TAILQ_REMOVE(&tp->segq, qe, ipqe_q);
   1280 		TAILQ_REMOVE(&tp->timeq, qe, ipqe_timeq);
   1281 		m_freem(qe->ipqe_m);
   1282 		tcpipqent_free(qe);
   1283 		rv = 1;
   1284 	}
   1285 	tp->t_segqlen = 0;
   1286 	KASSERT(TAILQ_EMPTY(&tp->timeq));
   1287 	return (rv);
   1288 }
   1289 
   1290 /*
   1291  * Protocol drain routine.  Called when memory is in short supply.
   1292  */
   1293 void
   1294 tcp_drain(void)
   1295 {
   1296 	struct inpcb_hdr *inph;
   1297 	struct tcpcb *tp;
   1298 
   1299 	/*
   1300 	 * Free the sequence queue of all TCP connections.
   1301 	 */
   1302 	CIRCLEQ_FOREACH(inph, &tcbtable.inpt_queue, inph_queue) {
   1303 		switch (inph->inph_af) {
   1304 		case AF_INET:
   1305 			tp = intotcpcb((struct inpcb *)inph);
   1306 			break;
   1307 #ifdef INET6
   1308 		case AF_INET6:
   1309 			tp = in6totcpcb((struct in6pcb *)inph);
   1310 			break;
   1311 #endif
   1312 		default:
   1313 			tp = NULL;
   1314 			break;
   1315 		}
   1316 		if (tp != NULL) {
   1317 			/*
   1318 			 * We may be called from a device's interrupt
   1319 			 * context.  If the tcpcb is already busy,
   1320 			 * just bail out now.
   1321 			 */
   1322 			if (tcp_reass_lock_try(tp) == 0)
   1323 				continue;
   1324 			if (tcp_freeq(tp))
   1325 				tcpstat.tcps_connsdrained++;
   1326 			TCP_REASS_UNLOCK(tp);
   1327 		}
   1328 	}
   1329 }
   1330 
   1331 /*
   1332  * Notify a tcp user of an asynchronous error;
   1333  * store error as soft error, but wake up user
   1334  * (for now, won't do anything until can select for soft error).
   1335  */
   1336 void
   1337 tcp_notify(struct inpcb *inp, int error)
   1338 {
   1339 	struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
   1340 	struct socket *so = inp->inp_socket;
   1341 
   1342 	/*
   1343 	 * Ignore some errors if we are hooked up.
   1344 	 * If connection hasn't completed, has retransmitted several times,
   1345 	 * and receives a second error, give up now.  This is better
   1346 	 * than waiting a long time to establish a connection that
   1347 	 * can never complete.
   1348 	 */
   1349 	if (tp->t_state == TCPS_ESTABLISHED &&
   1350 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
   1351 	      error == EHOSTDOWN)) {
   1352 		return;
   1353 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
   1354 	    tp->t_rxtshift > 3 && tp->t_softerror)
   1355 		so->so_error = error;
   1356 	else
   1357 		tp->t_softerror = error;
   1358 	wakeup((caddr_t) &so->so_timeo);
   1359 	sorwakeup(so);
   1360 	sowwakeup(so);
   1361 }
   1362 
   1363 #ifdef INET6
   1364 void
   1365 tcp6_notify(struct in6pcb *in6p, int error)
   1366 {
   1367 	struct tcpcb *tp = (struct tcpcb *)in6p->in6p_ppcb;
   1368 	struct socket *so = in6p->in6p_socket;
   1369 
   1370 	/*
   1371 	 * Ignore some errors if we are hooked up.
   1372 	 * If connection hasn't completed, has retransmitted several times,
   1373 	 * and receives a second error, give up now.  This is better
   1374 	 * than waiting a long time to establish a connection that
   1375 	 * can never complete.
   1376 	 */
   1377 	if (tp->t_state == TCPS_ESTABLISHED &&
   1378 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
   1379 	      error == EHOSTDOWN)) {
   1380 		return;
   1381 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
   1382 	    tp->t_rxtshift > 3 && tp->t_softerror)
   1383 		so->so_error = error;
   1384 	else
   1385 		tp->t_softerror = error;
   1386 	wakeup((caddr_t) &so->so_timeo);
   1387 	sorwakeup(so);
   1388 	sowwakeup(so);
   1389 }
   1390 #endif
   1391 
   1392 #ifdef INET6
   1393 void
   1394 tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
   1395 {
   1396 	struct tcphdr th;
   1397 	void (*notify)(struct in6pcb *, int) = tcp6_notify;
   1398 	int nmatch;
   1399 	struct ip6_hdr *ip6;
   1400 	const struct sockaddr_in6 *sa6_src = NULL;
   1401 	struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
   1402 	struct mbuf *m;
   1403 	int off;
   1404 
   1405 	if (sa->sa_family != AF_INET6 ||
   1406 	    sa->sa_len != sizeof(struct sockaddr_in6))
   1407 		return;
   1408 	if ((unsigned)cmd >= PRC_NCMDS)
   1409 		return;
   1410 	else if (cmd == PRC_QUENCH) {
   1411 		/*
   1412 		 * Don't honor ICMP Source Quench messages meant for
   1413 		 * TCP connections.
   1414 		 */
   1415 		return;
   1416 	} else if (PRC_IS_REDIRECT(cmd))
   1417 		notify = in6_rtchange, d = NULL;
   1418 	else if (cmd == PRC_MSGSIZE)
   1419 		; /* special code is present, see below */
   1420 	else if (cmd == PRC_HOSTDEAD)
   1421 		d = NULL;
   1422 	else if (inet6ctlerrmap[cmd] == 0)
   1423 		return;
   1424 
   1425 	/* if the parameter is from icmp6, decode it. */
   1426 	if (d != NULL) {
   1427 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
   1428 		m = ip6cp->ip6c_m;
   1429 		ip6 = ip6cp->ip6c_ip6;
   1430 		off = ip6cp->ip6c_off;
   1431 		sa6_src = ip6cp->ip6c_src;
   1432 	} else {
   1433 		m = NULL;
   1434 		ip6 = NULL;
   1435 		sa6_src = &sa6_any;
   1436 		off = 0;
   1437 	}
   1438 
   1439 	if (ip6) {
   1440 		/*
   1441 		 * XXX: We assume that when ip6 is non NULL,
   1442 		 * M and OFF are valid.
   1443 		 */
   1444 
   1445 		/* check if we can safely examine src and dst ports */
   1446 		if (m->m_pkthdr.len < off + sizeof(th)) {
   1447 			if (cmd == PRC_MSGSIZE)
   1448 				icmp6_mtudisc_update((struct ip6ctlparam *)d, 0);
   1449 			return;
   1450 		}
   1451 
   1452 		bzero(&th, sizeof(th));
   1453 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
   1454 
   1455 		if (cmd == PRC_MSGSIZE) {
   1456 			int valid = 0;
   1457 
   1458 			/*
   1459 			 * Check to see if we have a valid TCP connection
   1460 			 * corresponding to the address in the ICMPv6 message
   1461 			 * payload.
   1462 			 */
   1463 			if (in6_pcblookup_connect(&tcbtable, &sa6->sin6_addr,
   1464 			    th.th_dport, (const struct in6_addr *)&sa6_src->sin6_addr,
   1465 			    th.th_sport, 0))
   1466 				valid++;
   1467 
   1468 			/*
   1469 			 * Depending on the value of "valid" and routing table
   1470 			 * size (mtudisc_{hi,lo}wat), we will:
   1471 			 * - recalcurate the new MTU and create the
   1472 			 *   corresponding routing entry, or
   1473 			 * - ignore the MTU change notification.
   1474 			 */
   1475 			icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
   1476 
   1477 			/*
   1478 			 * no need to call in6_pcbnotify, it should have been
   1479 			 * called via callback if necessary
   1480 			 */
   1481 			return;
   1482 		}
   1483 
   1484 		nmatch = in6_pcbnotify(&tcbtable, sa, th.th_dport,
   1485 		    (const struct sockaddr *)sa6_src, th.th_sport, cmd, NULL, notify);
   1486 		if (nmatch == 0 && syn_cache_count &&
   1487 		    (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
   1488 		     inet6ctlerrmap[cmd] == ENETUNREACH ||
   1489 		     inet6ctlerrmap[cmd] == EHOSTDOWN))
   1490 			syn_cache_unreach((const struct sockaddr *)sa6_src,
   1491 					  sa, &th);
   1492 	} else {
   1493 		(void) in6_pcbnotify(&tcbtable, sa, 0,
   1494 		    (const struct sockaddr *)sa6_src, 0, cmd, NULL, notify);
   1495 	}
   1496 }
   1497 #endif
   1498 
   1499 #ifdef INET
   1500 /* assumes that ip header and tcp header are contiguous on mbuf */
   1501 void *
   1502 tcp_ctlinput(int cmd, struct sockaddr *sa, void *v)
   1503 {
   1504 	struct ip *ip = v;
   1505 	struct tcphdr *th;
   1506 	struct icmp *icp;
   1507 	extern const int inetctlerrmap[];
   1508 	void (*notify)(struct inpcb *, int) = tcp_notify;
   1509 	int errno;
   1510 	int nmatch;
   1511 	struct tcpcb *tp;
   1512 	u_int mtu;
   1513 	tcp_seq seq;
   1514 	struct inpcb *inp;
   1515 #ifdef INET6
   1516 	struct in6pcb *in6p;
   1517 	struct in6_addr src6, dst6;
   1518 #endif
   1519 
   1520 	if (sa->sa_family != AF_INET ||
   1521 	    sa->sa_len != sizeof(struct sockaddr_in))
   1522 		return NULL;
   1523 	if ((unsigned)cmd >= PRC_NCMDS)
   1524 		return NULL;
   1525 	errno = inetctlerrmap[cmd];
   1526 	if (cmd == PRC_QUENCH)
   1527 		/*
   1528 		 * Don't honor ICMP Source Quench messages meant for
   1529 		 * TCP connections.
   1530 		 */
   1531 		return NULL;
   1532 	else if (PRC_IS_REDIRECT(cmd))
   1533 		notify = in_rtchange, ip = 0;
   1534 	else if (cmd == PRC_MSGSIZE && ip && ip->ip_v == 4) {
   1535 		/*
   1536 		 * Check to see if we have a valid TCP connection
   1537 		 * corresponding to the address in the ICMP message
   1538 		 * payload.
   1539 		 *
   1540 		 * Boundary check is made in icmp_input(), with ICMP_ADVLENMIN.
   1541 		 */
   1542 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
   1543 #ifdef INET6
   1544 		memset(&src6, 0, sizeof(src6));
   1545 		memset(&dst6, 0, sizeof(dst6));
   1546 		src6.s6_addr16[5] = dst6.s6_addr16[5] = 0xffff;
   1547 		memcpy(&src6.s6_addr32[3], &ip->ip_src, sizeof(struct in_addr));
   1548 		memcpy(&dst6.s6_addr32[3], &ip->ip_dst, sizeof(struct in_addr));
   1549 #endif
   1550 		if ((inp = in_pcblookup_connect(&tcbtable, ip->ip_dst,
   1551 		    th->th_dport, ip->ip_src, th->th_sport)) != NULL)
   1552 #ifdef INET6
   1553 			in6p = NULL;
   1554 #else
   1555 			;
   1556 #endif
   1557 #ifdef INET6
   1558 		else if ((in6p = in6_pcblookup_connect(&tcbtable, &dst6,
   1559 		    th->th_dport, &src6, th->th_sport, 0)) != NULL)
   1560 			;
   1561 #endif
   1562 		else
   1563 			return NULL;
   1564 
   1565 		/*
   1566 		 * Now that we've validated that we are actually communicating
   1567 		 * with the host indicated in the ICMP message, locate the
   1568 		 * ICMP header, recalculate the new MTU, and create the
   1569 		 * corresponding routing entry.
   1570 		 */
   1571 		icp = (struct icmp *)((caddr_t)ip -
   1572 		    offsetof(struct icmp, icmp_ip));
   1573 		if (inp) {
   1574 			if ((tp = intotcpcb(inp)) == NULL)
   1575 				return NULL;
   1576 		}
   1577 #ifdef INET6
   1578 		else if (in6p) {
   1579 			if ((tp = in6totcpcb(in6p)) == NULL)
   1580 				return NULL;
   1581 		}
   1582 #endif
   1583 		else
   1584 			return NULL;
   1585 		seq = ntohl(th->th_seq);
   1586 		if (SEQ_LT(seq, tp->snd_una) || SEQ_GT(seq, tp->snd_max))
   1587 			return NULL;
   1588 		/*
   1589 		 * If the ICMP message advertises a Next-Hop MTU
   1590 		 * equal or larger than the maximum packet size we have
   1591 		 * ever sent, drop the message.
   1592 		 */
   1593 		mtu = (u_int)ntohs(icp->icmp_nextmtu);
   1594 		if (mtu >= tp->t_pmtud_mtu_sent)
   1595 			return NULL;
   1596 		if (mtu >= tcp_hdrsz(tp) + tp->t_pmtud_mss_acked) {
   1597 			/*
   1598 			 * Calculate new MTU, and create corresponding
   1599 			 * route (traditional PMTUD).
   1600 			 */
   1601 			tp->t_flags &= ~TF_PMTUD_PEND;
   1602 			icmp_mtudisc(icp, ip->ip_dst);
   1603 		} else {
   1604 			/*
   1605 			 * Record the information got in the ICMP
   1606 			 * message; act on it later.
   1607 			 * If we had already recorded an ICMP message,
   1608 			 * replace the old one only if the new message
   1609 			 * refers to an older TCP segment
   1610 			 */
   1611 			if (tp->t_flags & TF_PMTUD_PEND) {
   1612 				if (SEQ_LT(tp->t_pmtud_th_seq, seq))
   1613 					return NULL;
   1614 			} else
   1615 				tp->t_flags |= TF_PMTUD_PEND;
   1616 			tp->t_pmtud_th_seq = seq;
   1617 			tp->t_pmtud_nextmtu = icp->icmp_nextmtu;
   1618 			tp->t_pmtud_ip_len = icp->icmp_ip.ip_len;
   1619 			tp->t_pmtud_ip_hl = icp->icmp_ip.ip_hl;
   1620 		}
   1621 		return NULL;
   1622 	} else if (cmd == PRC_HOSTDEAD)
   1623 		ip = 0;
   1624 	else if (errno == 0)
   1625 		return NULL;
   1626 	if (ip && ip->ip_v == 4 && sa->sa_family == AF_INET) {
   1627 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
   1628 		nmatch = in_pcbnotify(&tcbtable, satosin(sa)->sin_addr,
   1629 		    th->th_dport, ip->ip_src, th->th_sport, errno, notify);
   1630 		if (nmatch == 0 && syn_cache_count &&
   1631 		    (inetctlerrmap[cmd] == EHOSTUNREACH ||
   1632 		    inetctlerrmap[cmd] == ENETUNREACH ||
   1633 		    inetctlerrmap[cmd] == EHOSTDOWN)) {
   1634 			struct sockaddr_in sin;
   1635 			bzero(&sin, sizeof(sin));
   1636 			sin.sin_len = sizeof(sin);
   1637 			sin.sin_family = AF_INET;
   1638 			sin.sin_port = th->th_sport;
   1639 			sin.sin_addr = ip->ip_src;
   1640 			syn_cache_unreach((struct sockaddr *)&sin, sa, th);
   1641 		}
   1642 
   1643 		/* XXX mapped address case */
   1644 	} else
   1645 		in_pcbnotifyall(&tcbtable, satosin(sa)->sin_addr, errno,
   1646 		    notify);
   1647 	return NULL;
   1648 }
   1649 
   1650 /*
   1651  * When a source quench is received, we are being notified of congestion.
   1652  * Close the congestion window down to the Loss Window (one segment).
   1653  * We will gradually open it again as we proceed.
   1654  */
   1655 void
   1656 tcp_quench(struct inpcb *inp, int errno)
   1657 {
   1658 	struct tcpcb *tp = intotcpcb(inp);
   1659 
   1660 	if (tp) {
   1661 		tp->snd_cwnd = tp->t_segsz;
   1662 		tp->t_bytes_acked = 0;
   1663 	}
   1664 }
   1665 #endif
   1666 
   1667 #ifdef INET6
   1668 void
   1669 tcp6_quench(struct in6pcb *in6p, int errno)
   1670 {
   1671 	struct tcpcb *tp = in6totcpcb(in6p);
   1672 
   1673 	if (tp) {
   1674 		tp->snd_cwnd = tp->t_segsz;
   1675 		tp->t_bytes_acked = 0;
   1676 	}
   1677 }
   1678 #endif
   1679 
   1680 #ifdef INET
   1681 /*
   1682  * Path MTU Discovery handlers.
   1683  */
   1684 void
   1685 tcp_mtudisc_callback(struct in_addr faddr)
   1686 {
   1687 #ifdef INET6
   1688 	struct in6_addr in6;
   1689 #endif
   1690 
   1691 	in_pcbnotifyall(&tcbtable, faddr, EMSGSIZE, tcp_mtudisc);
   1692 #ifdef INET6
   1693 	memset(&in6, 0, sizeof(in6));
   1694 	in6.s6_addr16[5] = 0xffff;
   1695 	memcpy(&in6.s6_addr32[3], &faddr, sizeof(struct in_addr));
   1696 	tcp6_mtudisc_callback(&in6);
   1697 #endif
   1698 }
   1699 
   1700 /*
   1701  * On receipt of path MTU corrections, flush old route and replace it
   1702  * with the new one.  Retransmit all unacknowledged packets, to ensure
   1703  * that all packets will be received.
   1704  */
   1705 void
   1706 tcp_mtudisc(struct inpcb *inp, int errno)
   1707 {
   1708 	struct tcpcb *tp = intotcpcb(inp);
   1709 	struct rtentry *rt = in_pcbrtentry(inp);
   1710 
   1711 	if (tp != 0) {
   1712 		if (rt != 0) {
   1713 			/*
   1714 			 * If this was not a host route, remove and realloc.
   1715 			 */
   1716 			if ((rt->rt_flags & RTF_HOST) == 0) {
   1717 				in_rtchange(inp, errno);
   1718 				if ((rt = in_pcbrtentry(inp)) == 0)
   1719 					return;
   1720 			}
   1721 
   1722 			/*
   1723 			 * Slow start out of the error condition.  We
   1724 			 * use the MTU because we know it's smaller
   1725 			 * than the previously transmitted segment.
   1726 			 *
   1727 			 * Note: This is more conservative than the
   1728 			 * suggestion in draft-floyd-incr-init-win-03.
   1729 			 */
   1730 			if (rt->rt_rmx.rmx_mtu != 0)
   1731 				tp->snd_cwnd =
   1732 				    TCP_INITIAL_WINDOW(tcp_init_win,
   1733 				    rt->rt_rmx.rmx_mtu);
   1734 		}
   1735 
   1736 		/*
   1737 		 * Resend unacknowledged packets.
   1738 		 */
   1739 		tp->snd_nxt = tp->snd_una;
   1740 		tcp_output(tp);
   1741 	}
   1742 }
   1743 #endif
   1744 
   1745 #ifdef INET6
   1746 /*
   1747  * Path MTU Discovery handlers.
   1748  */
   1749 void
   1750 tcp6_mtudisc_callback(struct in6_addr *faddr)
   1751 {
   1752 	struct sockaddr_in6 sin6;
   1753 
   1754 	bzero(&sin6, sizeof(sin6));
   1755 	sin6.sin6_family = AF_INET6;
   1756 	sin6.sin6_len = sizeof(struct sockaddr_in6);
   1757 	sin6.sin6_addr = *faddr;
   1758 	(void) in6_pcbnotify(&tcbtable, (struct sockaddr *)&sin6, 0,
   1759 	    (const struct sockaddr *)&sa6_any, 0, PRC_MSGSIZE, NULL, tcp6_mtudisc);
   1760 }
   1761 
   1762 void
   1763 tcp6_mtudisc(struct in6pcb *in6p, int errno)
   1764 {
   1765 	struct tcpcb *tp = in6totcpcb(in6p);
   1766 	struct rtentry *rt = in6_pcbrtentry(in6p);
   1767 
   1768 	if (tp != 0) {
   1769 		if (rt != 0) {
   1770 			/*
   1771 			 * If this was not a host route, remove and realloc.
   1772 			 */
   1773 			if ((rt->rt_flags & RTF_HOST) == 0) {
   1774 				in6_rtchange(in6p, errno);
   1775 				if ((rt = in6_pcbrtentry(in6p)) == 0)
   1776 					return;
   1777 			}
   1778 
   1779 			/*
   1780 			 * Slow start out of the error condition.  We
   1781 			 * use the MTU because we know it's smaller
   1782 			 * than the previously transmitted segment.
   1783 			 *
   1784 			 * Note: This is more conservative than the
   1785 			 * suggestion in draft-floyd-incr-init-win-03.
   1786 			 */
   1787 			if (rt->rt_rmx.rmx_mtu != 0)
   1788 				tp->snd_cwnd =
   1789 				    TCP_INITIAL_WINDOW(tcp_init_win,
   1790 				    rt->rt_rmx.rmx_mtu);
   1791 		}
   1792 
   1793 		/*
   1794 		 * Resend unacknowledged packets.
   1795 		 */
   1796 		tp->snd_nxt = tp->snd_una;
   1797 		tcp_output(tp);
   1798 	}
   1799 }
   1800 #endif /* INET6 */
   1801 
   1802 /*
   1803  * Compute the MSS to advertise to the peer.  Called only during
   1804  * the 3-way handshake.  If we are the server (peer initiated
   1805  * connection), we are called with a pointer to the interface
   1806  * on which the SYN packet arrived.  If we are the client (we
   1807  * initiated connection), we are called with a pointer to the
   1808  * interface out which this connection should go.
   1809  *
   1810  * NOTE: Do not subtract IP option/extension header size nor IPsec
   1811  * header size from MSS advertisement.  MSS option must hold the maximum
   1812  * segment size we can accept, so it must always be:
   1813  *	 max(if mtu) - ip header - tcp header
   1814  */
   1815 u_long
   1816 tcp_mss_to_advertise(const struct ifnet *ifp, int af)
   1817 {
   1818 	extern u_long in_maxmtu;
   1819 	u_long mss = 0;
   1820 	u_long hdrsiz;
   1821 
   1822 	/*
   1823 	 * In order to avoid defeating path MTU discovery on the peer,
   1824 	 * we advertise the max MTU of all attached networks as our MSS,
   1825 	 * per RFC 1191, section 3.1.
   1826 	 *
   1827 	 * We provide the option to advertise just the MTU of
   1828 	 * the interface on which we hope this connection will
   1829 	 * be receiving.  If we are responding to a SYN, we
   1830 	 * will have a pretty good idea about this, but when
   1831 	 * initiating a connection there is a bit more doubt.
   1832 	 *
   1833 	 * We also need to ensure that loopback has a large enough
   1834 	 * MSS, as the loopback MTU is never included in in_maxmtu.
   1835 	 */
   1836 
   1837 	if (ifp != NULL)
   1838 		switch (af) {
   1839 		case AF_INET:
   1840 			mss = ifp->if_mtu;
   1841 			break;
   1842 #ifdef INET6
   1843 		case AF_INET6:
   1844 			mss = IN6_LINKMTU(ifp);
   1845 			break;
   1846 #endif
   1847 		}
   1848 
   1849 	if (tcp_mss_ifmtu == 0)
   1850 		switch (af) {
   1851 		case AF_INET:
   1852 			mss = max(in_maxmtu, mss);
   1853 			break;
   1854 #ifdef INET6
   1855 		case AF_INET6:
   1856 			mss = max(in6_maxmtu, mss);
   1857 			break;
   1858 #endif
   1859 		}
   1860 
   1861 	switch (af) {
   1862 	case AF_INET:
   1863 		hdrsiz = sizeof(struct ip);
   1864 		break;
   1865 #ifdef INET6
   1866 	case AF_INET6:
   1867 		hdrsiz = sizeof(struct ip6_hdr);
   1868 		break;
   1869 #endif
   1870 	default:
   1871 		hdrsiz = 0;
   1872 		break;
   1873 	}
   1874 	hdrsiz += sizeof(struct tcphdr);
   1875 	if (mss > hdrsiz)
   1876 		mss -= hdrsiz;
   1877 
   1878 	mss = max(tcp_mssdflt, mss);
   1879 	return (mss);
   1880 }
   1881 
   1882 /*
   1883  * Set connection variables based on the peer's advertised MSS.
   1884  * We are passed the TCPCB for the actual connection.  If we
   1885  * are the server, we are called by the compressed state engine
   1886  * when the 3-way handshake is complete.  If we are the client,
   1887  * we are called when we receive the SYN,ACK from the server.
   1888  *
   1889  * NOTE: Our advertised MSS value must be initialized in the TCPCB
   1890  * before this routine is called!
   1891  */
   1892 void
   1893 tcp_mss_from_peer(struct tcpcb *tp, int offer)
   1894 {
   1895 	struct socket *so;
   1896 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   1897 	struct rtentry *rt;
   1898 #endif
   1899 	u_long bufsize;
   1900 	int mss;
   1901 
   1902 #ifdef DIAGNOSTIC
   1903 	if (tp->t_inpcb && tp->t_in6pcb)
   1904 		panic("tcp_mss_from_peer: both t_inpcb and t_in6pcb are set");
   1905 #endif
   1906 	so = NULL;
   1907 	rt = NULL;
   1908 #ifdef INET
   1909 	if (tp->t_inpcb) {
   1910 		so = tp->t_inpcb->inp_socket;
   1911 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   1912 		rt = in_pcbrtentry(tp->t_inpcb);
   1913 #endif
   1914 	}
   1915 #endif
   1916 #ifdef INET6
   1917 	if (tp->t_in6pcb) {
   1918 		so = tp->t_in6pcb->in6p_socket;
   1919 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   1920 		rt = in6_pcbrtentry(tp->t_in6pcb);
   1921 #endif
   1922 	}
   1923 #endif
   1924 
   1925 	/*
   1926 	 * As per RFC1122, use the default MSS value, unless they
   1927 	 * sent us an offer.  Do not accept offers less than 256 bytes.
   1928 	 */
   1929 	mss = tcp_mssdflt;
   1930 	if (offer)
   1931 		mss = offer;
   1932 	mss = max(mss, 256);		/* sanity */
   1933 	tp->t_peermss = mss;
   1934 	mss -= tcp_optlen(tp);
   1935 #ifdef INET
   1936 	if (tp->t_inpcb)
   1937 		mss -= ip_optlen(tp->t_inpcb);
   1938 #endif
   1939 #ifdef INET6
   1940 	if (tp->t_in6pcb)
   1941 		mss -= ip6_optlen(tp->t_in6pcb);
   1942 #endif
   1943 
   1944 	/*
   1945 	 * If there's a pipesize, change the socket buffer to that size.
   1946 	 * Make the socket buffer an integral number of MSS units.  If
   1947 	 * the MSS is larger than the socket buffer, artificially decrease
   1948 	 * the MSS.
   1949 	 */
   1950 #ifdef RTV_SPIPE
   1951 	if (rt != NULL && rt->rt_rmx.rmx_sendpipe != 0)
   1952 		bufsize = rt->rt_rmx.rmx_sendpipe;
   1953 	else
   1954 #endif
   1955 	{
   1956 		KASSERT(so != NULL);
   1957 		bufsize = so->so_snd.sb_hiwat;
   1958 	}
   1959 	if (bufsize < mss)
   1960 		mss = bufsize;
   1961 	else {
   1962 		bufsize = roundup(bufsize, mss);
   1963 		if (bufsize > sb_max)
   1964 			bufsize = sb_max;
   1965 		(void) sbreserve(&so->so_snd, bufsize, so);
   1966 	}
   1967 	tp->t_segsz = mss;
   1968 
   1969 #ifdef RTV_SSTHRESH
   1970 	if (rt != NULL && rt->rt_rmx.rmx_ssthresh) {
   1971 		/*
   1972 		 * There's some sort of gateway or interface buffer
   1973 		 * limit on the path.  Use this to set the slow
   1974 		 * start threshold, but set the threshold to no less
   1975 		 * than 2 * MSS.
   1976 		 */
   1977 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
   1978 	}
   1979 #endif
   1980 }
   1981 
   1982 /*
   1983  * Processing necessary when a TCP connection is established.
   1984  */
   1985 void
   1986 tcp_established(struct tcpcb *tp)
   1987 {
   1988 	struct socket *so;
   1989 #ifdef RTV_RPIPE
   1990 	struct rtentry *rt;
   1991 #endif
   1992 	u_long bufsize;
   1993 
   1994 #ifdef DIAGNOSTIC
   1995 	if (tp->t_inpcb && tp->t_in6pcb)
   1996 		panic("tcp_established: both t_inpcb and t_in6pcb are set");
   1997 #endif
   1998 	so = NULL;
   1999 	rt = NULL;
   2000 #ifdef INET
   2001 	if (tp->t_inpcb) {
   2002 		so = tp->t_inpcb->inp_socket;
   2003 #if defined(RTV_RPIPE)
   2004 		rt = in_pcbrtentry(tp->t_inpcb);
   2005 #endif
   2006 	}
   2007 #endif
   2008 #ifdef INET6
   2009 	if (tp->t_in6pcb) {
   2010 		so = tp->t_in6pcb->in6p_socket;
   2011 #if defined(RTV_RPIPE)
   2012 		rt = in6_pcbrtentry(tp->t_in6pcb);
   2013 #endif
   2014 	}
   2015 #endif
   2016 
   2017 	tp->t_state = TCPS_ESTABLISHED;
   2018 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
   2019 
   2020 #ifdef RTV_RPIPE
   2021 	if (rt != NULL && rt->rt_rmx.rmx_recvpipe != 0)
   2022 		bufsize = rt->rt_rmx.rmx_recvpipe;
   2023 	else
   2024 #endif
   2025 	{
   2026 		KASSERT(so != NULL);
   2027 		bufsize = so->so_rcv.sb_hiwat;
   2028 	}
   2029 	if (bufsize > tp->t_ourmss) {
   2030 		bufsize = roundup(bufsize, tp->t_ourmss);
   2031 		if (bufsize > sb_max)
   2032 			bufsize = sb_max;
   2033 		(void) sbreserve(&so->so_rcv, bufsize, so);
   2034 	}
   2035 }
   2036 
   2037 /*
   2038  * Check if there's an initial rtt or rttvar.  Convert from the
   2039  * route-table units to scaled multiples of the slow timeout timer.
   2040  * Called only during the 3-way handshake.
   2041  */
   2042 void
   2043 tcp_rmx_rtt(struct tcpcb *tp)
   2044 {
   2045 #ifdef RTV_RTT
   2046 	struct rtentry *rt = NULL;
   2047 	int rtt;
   2048 
   2049 #ifdef DIAGNOSTIC
   2050 	if (tp->t_inpcb && tp->t_in6pcb)
   2051 		panic("tcp_rmx_rtt: both t_inpcb and t_in6pcb are set");
   2052 #endif
   2053 #ifdef INET
   2054 	if (tp->t_inpcb)
   2055 		rt = in_pcbrtentry(tp->t_inpcb);
   2056 #endif
   2057 #ifdef INET6
   2058 	if (tp->t_in6pcb)
   2059 		rt = in6_pcbrtentry(tp->t_in6pcb);
   2060 #endif
   2061 	if (rt == NULL)
   2062 		return;
   2063 
   2064 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
   2065 		/*
   2066 		 * XXX The lock bit for MTU indicates that the value
   2067 		 * is also a minimum value; this is subject to time.
   2068 		 */
   2069 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
   2070 			TCPT_RANGESET(tp->t_rttmin,
   2071 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
   2072 			    TCPTV_MIN, TCPTV_REXMTMAX);
   2073 		tp->t_srtt = rtt /
   2074 		    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
   2075 		if (rt->rt_rmx.rmx_rttvar) {
   2076 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
   2077 			    ((RTM_RTTUNIT / PR_SLOWHZ) >>
   2078 				(TCP_RTTVAR_SHIFT + 2));
   2079 		} else {
   2080 			/* Default variation is +- 1 rtt */
   2081 			tp->t_rttvar =
   2082 			    tp->t_srtt >> (TCP_RTT_SHIFT - TCP_RTTVAR_SHIFT);
   2083 		}
   2084 		TCPT_RANGESET(tp->t_rxtcur,
   2085 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2),
   2086 		    tp->t_rttmin, TCPTV_REXMTMAX);
   2087 	}
   2088 #endif
   2089 }
   2090 
   2091 tcp_seq	 tcp_iss_seq = 0;	/* tcp initial seq # */
   2092 #if NRND > 0
   2093 u_int8_t tcp_iss_secret[16];	/* 128 bits; should be plenty */
   2094 #endif
   2095 
   2096 /*
   2097  * Get a new sequence value given a tcp control block
   2098  */
   2099 tcp_seq
   2100 tcp_new_iss(struct tcpcb *tp, tcp_seq addin)
   2101 {
   2102 
   2103 #ifdef INET
   2104 	if (tp->t_inpcb != NULL) {
   2105 		return (tcp_new_iss1(&tp->t_inpcb->inp_laddr,
   2106 		    &tp->t_inpcb->inp_faddr, tp->t_inpcb->inp_lport,
   2107 		    tp->t_inpcb->inp_fport, sizeof(tp->t_inpcb->inp_laddr),
   2108 		    addin));
   2109 	}
   2110 #endif
   2111 #ifdef INET6
   2112 	if (tp->t_in6pcb != NULL) {
   2113 		return (tcp_new_iss1(&tp->t_in6pcb->in6p_laddr,
   2114 		    &tp->t_in6pcb->in6p_faddr, tp->t_in6pcb->in6p_lport,
   2115 		    tp->t_in6pcb->in6p_fport, sizeof(tp->t_in6pcb->in6p_laddr),
   2116 		    addin));
   2117 	}
   2118 #endif
   2119 	/* Not possible. */
   2120 	panic("tcp_new_iss");
   2121 }
   2122 
   2123 /*
   2124  * This routine actually generates a new TCP initial sequence number.
   2125  */
   2126 tcp_seq
   2127 tcp_new_iss1(void *laddr, void *faddr, u_int16_t lport, u_int16_t fport,
   2128     size_t addrsz, tcp_seq addin)
   2129 {
   2130 	tcp_seq tcp_iss;
   2131 
   2132 #if NRND > 0
   2133 	static int beenhere;
   2134 
   2135 	/*
   2136 	 * If we haven't been here before, initialize our cryptographic
   2137 	 * hash secret.
   2138 	 */
   2139 	if (beenhere == 0) {
   2140 		rnd_extract_data(tcp_iss_secret, sizeof(tcp_iss_secret),
   2141 		    RND_EXTRACT_ANY);
   2142 		beenhere = 1;
   2143 	}
   2144 
   2145 	if (tcp_do_rfc1948) {
   2146 		MD5_CTX ctx;
   2147 		u_int8_t hash[16];	/* XXX MD5 knowledge */
   2148 
   2149 		/*
   2150 		 * Compute the base value of the ISS.  It is a hash
   2151 		 * of (saddr, sport, daddr, dport, secret).
   2152 		 */
   2153 		MD5Init(&ctx);
   2154 
   2155 		MD5Update(&ctx, (u_char *) laddr, addrsz);
   2156 		MD5Update(&ctx, (u_char *) &lport, sizeof(lport));
   2157 
   2158 		MD5Update(&ctx, (u_char *) faddr, addrsz);
   2159 		MD5Update(&ctx, (u_char *) &fport, sizeof(fport));
   2160 
   2161 		MD5Update(&ctx, tcp_iss_secret, sizeof(tcp_iss_secret));
   2162 
   2163 		MD5Final(hash, &ctx);
   2164 
   2165 		memcpy(&tcp_iss, hash, sizeof(tcp_iss));
   2166 
   2167 		/*
   2168 		 * Now increment our "timer", and add it in to
   2169 		 * the computed value.
   2170 		 *
   2171 		 * XXX Use `addin'?
   2172 		 * XXX TCP_ISSINCR too large to use?
   2173 		 */
   2174 		tcp_iss_seq += TCP_ISSINCR;
   2175 #ifdef TCPISS_DEBUG
   2176 		printf("ISS hash 0x%08x, ", tcp_iss);
   2177 #endif
   2178 		tcp_iss += tcp_iss_seq + addin;
   2179 #ifdef TCPISS_DEBUG
   2180 		printf("new ISS 0x%08x\n", tcp_iss);
   2181 #endif
   2182 	} else
   2183 #endif /* NRND > 0 */
   2184 	{
   2185 		/*
   2186 		 * Randomize.
   2187 		 */
   2188 #if NRND > 0
   2189 		rnd_extract_data(&tcp_iss, sizeof(tcp_iss), RND_EXTRACT_ANY);
   2190 #else
   2191 		tcp_iss = arc4random();
   2192 #endif
   2193 
   2194 		/*
   2195 		 * If we were asked to add some amount to a known value,
   2196 		 * we will take a random value obtained above, mask off
   2197 		 * the upper bits, and add in the known value.  We also
   2198 		 * add in a constant to ensure that we are at least a
   2199 		 * certain distance from the original value.
   2200 		 *
   2201 		 * This is used when an old connection is in timed wait
   2202 		 * and we have a new one coming in, for instance.
   2203 		 */
   2204 		if (addin != 0) {
   2205 #ifdef TCPISS_DEBUG
   2206 			printf("Random %08x, ", tcp_iss);
   2207 #endif
   2208 			tcp_iss &= TCP_ISS_RANDOM_MASK;
   2209 			tcp_iss += addin + TCP_ISSINCR;
   2210 #ifdef TCPISS_DEBUG
   2211 			printf("Old ISS %08x, ISS %08x\n", addin, tcp_iss);
   2212 #endif
   2213 		} else {
   2214 			tcp_iss &= TCP_ISS_RANDOM_MASK;
   2215 			tcp_iss += tcp_iss_seq;
   2216 			tcp_iss_seq += TCP_ISSINCR;
   2217 #ifdef TCPISS_DEBUG
   2218 			printf("ISS %08x\n", tcp_iss);
   2219 #endif
   2220 		}
   2221 	}
   2222 
   2223 	if (tcp_compat_42) {
   2224 		/*
   2225 		 * Limit it to the positive range for really old TCP
   2226 		 * implementations.
   2227 		 * Just AND off the top bit instead of checking if
   2228 		 * is set first - saves a branch 50% of the time.
   2229 		 */
   2230 		tcp_iss &= 0x7fffffff;		/* XXX */
   2231 	}
   2232 
   2233 	return (tcp_iss);
   2234 }
   2235 
   2236 #if defined(IPSEC) || defined(FAST_IPSEC)
   2237 /* compute ESP/AH header size for TCP, including outer IP header. */
   2238 size_t
   2239 ipsec4_hdrsiz_tcp(struct tcpcb *tp)
   2240 {
   2241 	struct inpcb *inp;
   2242 	size_t hdrsiz;
   2243 
   2244 	/* XXX mapped addr case (tp->t_in6pcb) */
   2245 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
   2246 		return 0;
   2247 	switch (tp->t_family) {
   2248 	case AF_INET:
   2249 		/* XXX: should use currect direction. */
   2250 		hdrsiz = ipsec4_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, inp);
   2251 		break;
   2252 	default:
   2253 		hdrsiz = 0;
   2254 		break;
   2255 	}
   2256 
   2257 	return hdrsiz;
   2258 }
   2259 
   2260 #ifdef INET6
   2261 size_t
   2262 ipsec6_hdrsiz_tcp(struct tcpcb *tp)
   2263 {
   2264 	struct in6pcb *in6p;
   2265 	size_t hdrsiz;
   2266 
   2267 	if (!tp || !tp->t_template || !(in6p = tp->t_in6pcb))
   2268 		return 0;
   2269 	switch (tp->t_family) {
   2270 	case AF_INET6:
   2271 		/* XXX: should use currect direction. */
   2272 		hdrsiz = ipsec6_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, in6p);
   2273 		break;
   2274 	case AF_INET:
   2275 		/* mapped address case - tricky */
   2276 	default:
   2277 		hdrsiz = 0;
   2278 		break;
   2279 	}
   2280 
   2281 	return hdrsiz;
   2282 }
   2283 #endif
   2284 #endif /*IPSEC*/
   2285 
   2286 /*
   2287  * Determine the length of the TCP options for this connection.
   2288  *
   2289  * XXX:  What do we do for SACK, when we add that?  Just reserve
   2290  *       all of the space?  Otherwise we can't exactly be incrementing
   2291  *       cwnd by an amount that varies depending on the amount we last
   2292  *       had to SACK!
   2293  */
   2294 
   2295 u_int
   2296 tcp_optlen(struct tcpcb *tp)
   2297 {
   2298 	u_int optlen;
   2299 
   2300 	optlen = 0;
   2301 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
   2302 	    (TF_REQ_TSTMP | TF_RCVD_TSTMP))
   2303 		optlen += TCPOLEN_TSTAMP_APPA;
   2304 
   2305 #ifdef TCP_SIGNATURE
   2306 #if defined(INET6) && defined(FAST_IPSEC)
   2307 	if (tp->t_family == AF_INET)
   2308 #endif
   2309 	if (tp->t_flags & TF_SIGNATURE)
   2310 		optlen += TCPOLEN_SIGNATURE + 2;
   2311 #endif /* TCP_SIGNATURE */
   2312 
   2313 	return optlen;
   2314 }
   2315 
   2316 u_int
   2317 tcp_hdrsz(struct tcpcb *tp)
   2318 {
   2319 	u_int hlen;
   2320 
   2321 	switch (tp->t_family) {
   2322 #ifdef INET6
   2323 	case AF_INET6:
   2324 		hlen = sizeof(struct ip6_hdr);
   2325 		break;
   2326 #endif
   2327 	case AF_INET:
   2328 		hlen = sizeof(struct ip);
   2329 		break;
   2330 	default:
   2331 		hlen = 0;
   2332 		break;
   2333 	}
   2334 	hlen += sizeof(struct tcphdr);
   2335 
   2336 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
   2337 	    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
   2338 		hlen += TCPOLEN_TSTAMP_APPA;
   2339 #ifdef TCP_SIGNATURE
   2340 	if (tp->t_flags & TF_SIGNATURE)
   2341 		hlen += TCPOLEN_SIGLEN;
   2342 #endif
   2343 	return hlen;
   2344 }
   2345