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