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