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