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