Home | History | Annotate | Line # | Download | only in netinet
tcp_input.c revision 1.328
      1 /*	$NetBSD: tcp_input.c,v 1.328 2013/08/29 17:49:20 rmind 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   1.1 (NRL) 17 January 1995
     34  *
     35  * NRL grants permission for redistribution and use in source and binary
     36  * forms, with or without modification, of the software and documentation
     37  * created at NRL provided that the following conditions are met:
     38  *
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. All advertising materials mentioning features or use of this software
     45  *    must display the following acknowledgements:
     46  *      This product includes software developed by the University of
     47  *      California, Berkeley and its contributors.
     48  *      This product includes software developed at the Information
     49  *      Technology Division, US Naval Research Laboratory.
     50  * 4. Neither the name of the NRL nor the names of its contributors
     51  *    may be used to endorse or promote products derived from this software
     52  *    without specific prior written permission.
     53  *
     54  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
     55  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     56  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
     57  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
     58  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     59  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     60  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     61  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     62  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     63  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     64  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     65  *
     66  * The views and conclusions contained in the software and documentation
     67  * are those of the authors and should not be interpreted as representing
     68  * official policies, either expressed or implied, of the US Naval
     69  * Research Laboratory (NRL).
     70  */
     71 
     72 /*-
     73  * Copyright (c) 1997, 1998, 1999, 2001, 2005, 2006,
     74  * 2011 The NetBSD Foundation, Inc.
     75  * All rights reserved.
     76  *
     77  * This code is derived from software contributed to The NetBSD Foundation
     78  * by Coyote Point Systems, Inc.
     79  * This code is derived from software contributed to The NetBSD Foundation
     80  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
     81  * Facility, NASA Ames Research Center.
     82  * This code is derived from software contributed to The NetBSD Foundation
     83  * by Charles M. Hannum.
     84  * This code is derived from software contributed to The NetBSD Foundation
     85  * by Rui Paulo.
     86  *
     87  * Redistribution and use in source and binary forms, with or without
     88  * modification, are permitted provided that the following conditions
     89  * are met:
     90  * 1. Redistributions of source code must retain the above copyright
     91  *    notice, this list of conditions and the following disclaimer.
     92  * 2. Redistributions in binary form must reproduce the above copyright
     93  *    notice, this list of conditions and the following disclaimer in the
     94  *    documentation and/or other materials provided with the distribution.
     95  *
     96  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     97  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     98  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     99  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
    100  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    101  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    102  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    103  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    104  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    105  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    106  * POSSIBILITY OF SUCH DAMAGE.
    107  */
    108 
    109 /*
    110  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
    111  *	The Regents of the University of California.  All rights reserved.
    112  *
    113  * Redistribution and use in source and binary forms, with or without
    114  * modification, are permitted provided that the following conditions
    115  * are met:
    116  * 1. Redistributions of source code must retain the above copyright
    117  *    notice, this list of conditions and the following disclaimer.
    118  * 2. Redistributions in binary form must reproduce the above copyright
    119  *    notice, this list of conditions and the following disclaimer in the
    120  *    documentation and/or other materials provided with the distribution.
    121  * 3. Neither the name of the University nor the names of its contributors
    122  *    may be used to endorse or promote products derived from this software
    123  *    without specific prior written permission.
    124  *
    125  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
    126  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    127  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    128  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
    129  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    130  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    131  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    132  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    133  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    134  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    135  * SUCH DAMAGE.
    136  *
    137  *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
    138  */
    139 
    140 /*
    141  *	TODO list for SYN cache stuff:
    142  *
    143  *	Find room for a "state" field, which is needed to keep a
    144  *	compressed state for TIME_WAIT TCBs.  It's been noted already
    145  *	that this is fairly important for very high-volume web and
    146  *	mail servers, which use a large number of short-lived
    147  *	connections.
    148  */
    149 
    150 #include <sys/cdefs.h>
    151 __KERNEL_RCSID(0, "$NetBSD: tcp_input.c,v 1.328 2013/08/29 17:49:20 rmind Exp $");
    152 
    153 #include "opt_inet.h"
    154 #include "opt_ipsec.h"
    155 #include "opt_inet_csum.h"
    156 #include "opt_tcp_debug.h"
    157 
    158 #include <sys/param.h>
    159 #include <sys/systm.h>
    160 #include <sys/malloc.h>
    161 #include <sys/mbuf.h>
    162 #include <sys/protosw.h>
    163 #include <sys/socket.h>
    164 #include <sys/socketvar.h>
    165 #include <sys/errno.h>
    166 #include <sys/syslog.h>
    167 #include <sys/pool.h>
    168 #include <sys/domain.h>
    169 #include <sys/kernel.h>
    170 #ifdef TCP_SIGNATURE
    171 #include <sys/md5.h>
    172 #endif
    173 #include <sys/lwp.h> /* for lwp0 */
    174 #include <sys/cprng.h>
    175 
    176 #include <net/if.h>
    177 #include <net/route.h>
    178 #include <net/if_types.h>
    179 
    180 #include <netinet/in.h>
    181 #include <netinet/in_systm.h>
    182 #include <netinet/ip.h>
    183 #include <netinet/in_pcb.h>
    184 #include <netinet/in_var.h>
    185 #include <netinet/ip_var.h>
    186 #include <netinet/in_offload.h>
    187 
    188 #ifdef INET6
    189 #ifndef INET
    190 #include <netinet/in.h>
    191 #endif
    192 #include <netinet/ip6.h>
    193 #include <netinet6/ip6_var.h>
    194 #include <netinet6/in6_pcb.h>
    195 #include <netinet6/ip6_var.h>
    196 #include <netinet6/in6_var.h>
    197 #include <netinet/icmp6.h>
    198 #include <netinet6/nd6.h>
    199 #ifdef TCP_SIGNATURE
    200 #include <netinet6/scope6_var.h>
    201 #endif
    202 #endif
    203 
    204 #ifndef INET6
    205 /* always need ip6.h for IP6_EXTHDR_GET */
    206 #include <netinet/ip6.h>
    207 #endif
    208 
    209 #include <netinet/tcp.h>
    210 #include <netinet/tcp_fsm.h>
    211 #include <netinet/tcp_seq.h>
    212 #include <netinet/tcp_timer.h>
    213 #include <netinet/tcp_var.h>
    214 #include <netinet/tcp_private.h>
    215 #include <netinet/tcpip.h>
    216 #include <netinet/tcp_congctl.h>
    217 #include <netinet/tcp_debug.h>
    218 
    219 #ifdef INET6
    220 #include "faith.h"
    221 #if defined(NFAITH) && NFAITH > 0
    222 #include <net/if_faith.h>
    223 #endif
    224 #endif	/* INET6 */
    225 
    226 #ifdef IPSEC
    227 #include <netipsec/ipsec.h>
    228 #include <netipsec/ipsec_var.h>
    229 #include <netipsec/ipsec_private.h>
    230 #include <netipsec/key.h>
    231 #ifdef INET6
    232 #include <netipsec/ipsec6.h>
    233 #endif
    234 #endif	/* IPSEC*/
    235 
    236 #include <netinet/tcp_vtw.h>
    237 
    238 int	tcprexmtthresh = 3;
    239 int	tcp_log_refused;
    240 
    241 int	tcp_do_autorcvbuf = 1;
    242 int	tcp_autorcvbuf_inc = 16 * 1024;
    243 int	tcp_autorcvbuf_max = 256 * 1024;
    244 int	tcp_msl = (TCPTV_MSL / PR_SLOWHZ);
    245 
    246 static int tcp_rst_ppslim_count = 0;
    247 static struct timeval tcp_rst_ppslim_last;
    248 static int tcp_ackdrop_ppslim_count = 0;
    249 static struct timeval tcp_ackdrop_ppslim_last;
    250 
    251 #define TCP_PAWS_IDLE	(24U * 24 * 60 * 60 * PR_SLOWHZ)
    252 
    253 /* for modulo comparisons of timestamps */
    254 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
    255 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
    256 
    257 /*
    258  * Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint.
    259  */
    260 #ifdef INET6
    261 static inline void
    262 nd6_hint(struct tcpcb *tp)
    263 {
    264 	struct rtentry *rt;
    265 
    266 	if (tp != NULL && tp->t_in6pcb != NULL && tp->t_family == AF_INET6 &&
    267 	    (rt = rtcache_validate(&tp->t_in6pcb->in6p_route)) != NULL)
    268 		nd6_nud_hint(rt, NULL, 0);
    269 }
    270 #else
    271 static inline void
    272 nd6_hint(struct tcpcb *tp)
    273 {
    274 }
    275 #endif
    276 
    277 /*
    278  * Compute ACK transmission behavior.  Delay the ACK unless
    279  * we have already delayed an ACK (must send an ACK every two segments).
    280  * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
    281  * option is enabled.
    282  */
    283 static void
    284 tcp_setup_ack(struct tcpcb *tp, const struct tcphdr *th)
    285 {
    286 
    287 	if (tp->t_flags & TF_DELACK ||
    288 	    (tcp_ack_on_push && th->th_flags & TH_PUSH))
    289 		tp->t_flags |= TF_ACKNOW;
    290 	else
    291 		TCP_SET_DELACK(tp);
    292 }
    293 
    294 static void
    295 icmp_check(struct tcpcb *tp, const struct tcphdr *th, int acked)
    296 {
    297 
    298 	/*
    299 	 * If we had a pending ICMP message that refers to data that have
    300 	 * just been acknowledged, disregard the recorded ICMP message.
    301 	 */
    302 	if ((tp->t_flags & TF_PMTUD_PEND) &&
    303 	    SEQ_GT(th->th_ack, tp->t_pmtud_th_seq))
    304 		tp->t_flags &= ~TF_PMTUD_PEND;
    305 
    306 	/*
    307 	 * Keep track of the largest chunk of data
    308 	 * acknowledged since last PMTU update
    309 	 */
    310 	if (tp->t_pmtud_mss_acked < acked)
    311 		tp->t_pmtud_mss_acked = acked;
    312 }
    313 
    314 /*
    315  * Convert TCP protocol fields to host order for easier processing.
    316  */
    317 static void
    318 tcp_fields_to_host(struct tcphdr *th)
    319 {
    320 
    321 	NTOHL(th->th_seq);
    322 	NTOHL(th->th_ack);
    323 	NTOHS(th->th_win);
    324 	NTOHS(th->th_urp);
    325 }
    326 
    327 /*
    328  * ... and reverse the above.
    329  */
    330 static void
    331 tcp_fields_to_net(struct tcphdr *th)
    332 {
    333 
    334 	HTONL(th->th_seq);
    335 	HTONL(th->th_ack);
    336 	HTONS(th->th_win);
    337 	HTONS(th->th_urp);
    338 }
    339 
    340 #ifdef TCP_CSUM_COUNTERS
    341 #include <sys/device.h>
    342 
    343 #if defined(INET)
    344 extern struct evcnt tcp_hwcsum_ok;
    345 extern struct evcnt tcp_hwcsum_bad;
    346 extern struct evcnt tcp_hwcsum_data;
    347 extern struct evcnt tcp_swcsum;
    348 #endif /* defined(INET) */
    349 #if defined(INET6)
    350 extern struct evcnt tcp6_hwcsum_ok;
    351 extern struct evcnt tcp6_hwcsum_bad;
    352 extern struct evcnt tcp6_hwcsum_data;
    353 extern struct evcnt tcp6_swcsum;
    354 #endif /* defined(INET6) */
    355 
    356 #define	TCP_CSUM_COUNTER_INCR(ev)	(ev)->ev_count++
    357 
    358 #else
    359 
    360 #define	TCP_CSUM_COUNTER_INCR(ev)	/* nothing */
    361 
    362 #endif /* TCP_CSUM_COUNTERS */
    363 
    364 #ifdef TCP_REASS_COUNTERS
    365 #include <sys/device.h>
    366 
    367 extern struct evcnt tcp_reass_;
    368 extern struct evcnt tcp_reass_empty;
    369 extern struct evcnt tcp_reass_iteration[8];
    370 extern struct evcnt tcp_reass_prependfirst;
    371 extern struct evcnt tcp_reass_prepend;
    372 extern struct evcnt tcp_reass_insert;
    373 extern struct evcnt tcp_reass_inserttail;
    374 extern struct evcnt tcp_reass_append;
    375 extern struct evcnt tcp_reass_appendtail;
    376 extern struct evcnt tcp_reass_overlaptail;
    377 extern struct evcnt tcp_reass_overlapfront;
    378 extern struct evcnt tcp_reass_segdup;
    379 extern struct evcnt tcp_reass_fragdup;
    380 
    381 #define	TCP_REASS_COUNTER_INCR(ev)	(ev)->ev_count++
    382 
    383 #else
    384 
    385 #define	TCP_REASS_COUNTER_INCR(ev)	/* nothing */
    386 
    387 #endif /* TCP_REASS_COUNTERS */
    388 
    389 static int tcp_reass(struct tcpcb *, const struct tcphdr *, struct mbuf *,
    390     int *);
    391 static int tcp_dooptions(struct tcpcb *, const u_char *, int,
    392     struct tcphdr *, struct mbuf *, int, struct tcp_opt_info *);
    393 
    394 #ifdef INET
    395 static void tcp4_log_refused(const struct ip *, const struct tcphdr *);
    396 #endif
    397 #ifdef INET6
    398 static void tcp6_log_refused(const struct ip6_hdr *, const struct tcphdr *);
    399 #endif
    400 
    401 #define	TRAVERSE(x) while ((x)->m_next) (x) = (x)->m_next
    402 
    403 #if defined(MBUFTRACE)
    404 struct mowner tcp_reass_mowner = MOWNER_INIT("tcp", "reass");
    405 #endif /* defined(MBUFTRACE) */
    406 
    407 static struct pool tcpipqent_pool;
    408 
    409 void
    410 tcpipqent_init(void)
    411 {
    412 
    413 	pool_init(&tcpipqent_pool, sizeof(struct ipqent), 0, 0, 0, "tcpipqepl",
    414 	    NULL, IPL_VM);
    415 }
    416 
    417 struct ipqent *
    418 tcpipqent_alloc(void)
    419 {
    420 	struct ipqent *ipqe;
    421 	int s;
    422 
    423 	s = splvm();
    424 	ipqe = pool_get(&tcpipqent_pool, PR_NOWAIT);
    425 	splx(s);
    426 
    427 	return ipqe;
    428 }
    429 
    430 void
    431 tcpipqent_free(struct ipqent *ipqe)
    432 {
    433 	int s;
    434 
    435 	s = splvm();
    436 	pool_put(&tcpipqent_pool, ipqe);
    437 	splx(s);
    438 }
    439 
    440 static int
    441 tcp_reass(struct tcpcb *tp, const struct tcphdr *th, struct mbuf *m, int *tlen)
    442 {
    443 	struct ipqent *p, *q, *nq, *tiqe = NULL;
    444 	struct socket *so = NULL;
    445 	int pkt_flags;
    446 	tcp_seq pkt_seq;
    447 	unsigned pkt_len;
    448 	u_long rcvpartdupbyte = 0;
    449 	u_long rcvoobyte;
    450 #ifdef TCP_REASS_COUNTERS
    451 	u_int count = 0;
    452 #endif
    453 	uint64_t *tcps;
    454 
    455 	if (tp->t_inpcb)
    456 		so = tp->t_inpcb->inp_socket;
    457 #ifdef INET6
    458 	else if (tp->t_in6pcb)
    459 		so = tp->t_in6pcb->in6p_socket;
    460 #endif
    461 
    462 	TCP_REASS_LOCK_CHECK(tp);
    463 
    464 	/*
    465 	 * Call with th==0 after become established to
    466 	 * force pre-ESTABLISHED data up to user socket.
    467 	 */
    468 	if (th == 0)
    469 		goto present;
    470 
    471 	m_claimm(m, &tcp_reass_mowner);
    472 
    473 	rcvoobyte = *tlen;
    474 	/*
    475 	 * Copy these to local variables because the tcpiphdr
    476 	 * gets munged while we are collapsing mbufs.
    477 	 */
    478 	pkt_seq = th->th_seq;
    479 	pkt_len = *tlen;
    480 	pkt_flags = th->th_flags;
    481 
    482 	TCP_REASS_COUNTER_INCR(&tcp_reass_);
    483 
    484 	if ((p = TAILQ_LAST(&tp->segq, ipqehead)) != NULL) {
    485 		/*
    486 		 * When we miss a packet, the vast majority of time we get
    487 		 * packets that follow it in order.  So optimize for that.
    488 		 */
    489 		if (pkt_seq == p->ipqe_seq + p->ipqe_len) {
    490 			p->ipqe_len += pkt_len;
    491 			p->ipqe_flags |= pkt_flags;
    492 			m_cat(p->ipre_mlast, m);
    493 			TRAVERSE(p->ipre_mlast);
    494 			m = NULL;
    495 			tiqe = p;
    496 			TAILQ_REMOVE(&tp->timeq, p, ipqe_timeq);
    497 			TCP_REASS_COUNTER_INCR(&tcp_reass_appendtail);
    498 			goto skip_replacement;
    499 		}
    500 		/*
    501 		 * While we're here, if the pkt is completely beyond
    502 		 * anything we have, just insert it at the tail.
    503 		 */
    504 		if (SEQ_GT(pkt_seq, p->ipqe_seq + p->ipqe_len)) {
    505 			TCP_REASS_COUNTER_INCR(&tcp_reass_inserttail);
    506 			goto insert_it;
    507 		}
    508 	}
    509 
    510 	q = TAILQ_FIRST(&tp->segq);
    511 
    512 	if (q != NULL) {
    513 		/*
    514 		 * If this segment immediately precedes the first out-of-order
    515 		 * block, simply slap the segment in front of it and (mostly)
    516 		 * skip the complicated logic.
    517 		 */
    518 		if (pkt_seq + pkt_len == q->ipqe_seq) {
    519 			q->ipqe_seq = pkt_seq;
    520 			q->ipqe_len += pkt_len;
    521 			q->ipqe_flags |= pkt_flags;
    522 			m_cat(m, q->ipqe_m);
    523 			q->ipqe_m = m;
    524 			q->ipre_mlast = m; /* last mbuf may have changed */
    525 			TRAVERSE(q->ipre_mlast);
    526 			tiqe = q;
    527 			TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
    528 			TCP_REASS_COUNTER_INCR(&tcp_reass_prependfirst);
    529 			goto skip_replacement;
    530 		}
    531 	} else {
    532 		TCP_REASS_COUNTER_INCR(&tcp_reass_empty);
    533 	}
    534 
    535 	/*
    536 	 * Find a segment which begins after this one does.
    537 	 */
    538 	for (p = NULL; q != NULL; q = nq) {
    539 		nq = TAILQ_NEXT(q, ipqe_q);
    540 #ifdef TCP_REASS_COUNTERS
    541 		count++;
    542 #endif
    543 		/*
    544 		 * If the received segment is just right after this
    545 		 * fragment, merge the two together and then check
    546 		 * for further overlaps.
    547 		 */
    548 		if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
    549 #ifdef TCPREASS_DEBUG
    550 			printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
    551 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
    552 			       q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
    553 #endif
    554 			pkt_len += q->ipqe_len;
    555 			pkt_flags |= q->ipqe_flags;
    556 			pkt_seq = q->ipqe_seq;
    557 			m_cat(q->ipre_mlast, m);
    558 			TRAVERSE(q->ipre_mlast);
    559 			m = q->ipqe_m;
    560 			TCP_REASS_COUNTER_INCR(&tcp_reass_append);
    561 			goto free_ipqe;
    562 		}
    563 		/*
    564 		 * If the received segment is completely past this
    565 		 * fragment, we need to go the next fragment.
    566 		 */
    567 		if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
    568 			p = q;
    569 			continue;
    570 		}
    571 		/*
    572 		 * If the fragment is past the received segment,
    573 		 * it (or any following) can't be concatenated.
    574 		 */
    575 		if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len)) {
    576 			TCP_REASS_COUNTER_INCR(&tcp_reass_insert);
    577 			break;
    578 		}
    579 
    580 		/*
    581 		 * We've received all the data in this segment before.
    582 		 * mark it as a duplicate and return.
    583 		 */
    584 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
    585 		    SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
    586 			tcps = TCP_STAT_GETREF();
    587 			tcps[TCP_STAT_RCVDUPPACK]++;
    588 			tcps[TCP_STAT_RCVDUPBYTE] += pkt_len;
    589 			TCP_STAT_PUTREF();
    590 			tcp_new_dsack(tp, pkt_seq, pkt_len);
    591 			m_freem(m);
    592 			if (tiqe != NULL) {
    593 				tcpipqent_free(tiqe);
    594 			}
    595 			TCP_REASS_COUNTER_INCR(&tcp_reass_segdup);
    596 			goto out;
    597 		}
    598 		/*
    599 		 * Received segment completely overlaps this fragment
    600 		 * so we drop the fragment (this keeps the temporal
    601 		 * ordering of segments correct).
    602 		 */
    603 		if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
    604 		    SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
    605 			rcvpartdupbyte += q->ipqe_len;
    606 			m_freem(q->ipqe_m);
    607 			TCP_REASS_COUNTER_INCR(&tcp_reass_fragdup);
    608 			goto free_ipqe;
    609 		}
    610 		/*
    611 		 * RX'ed segment extends past the end of the
    612 		 * fragment.  Drop the overlapping bytes.  Then
    613 		 * merge the fragment and segment then treat as
    614 		 * a longer received packet.
    615 		 */
    616 		if (SEQ_LT(q->ipqe_seq, pkt_seq) &&
    617 		    SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq))  {
    618 			int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
    619 #ifdef TCPREASS_DEBUG
    620 			printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
    621 			       tp, overlap,
    622 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
    623 #endif
    624 			m_adj(m, overlap);
    625 			rcvpartdupbyte += overlap;
    626 			m_cat(q->ipre_mlast, m);
    627 			TRAVERSE(q->ipre_mlast);
    628 			m = q->ipqe_m;
    629 			pkt_seq = q->ipqe_seq;
    630 			pkt_len += q->ipqe_len - overlap;
    631 			rcvoobyte -= overlap;
    632 			TCP_REASS_COUNTER_INCR(&tcp_reass_overlaptail);
    633 			goto free_ipqe;
    634 		}
    635 		/*
    636 		 * RX'ed segment extends past the front of the
    637 		 * fragment.  Drop the overlapping bytes on the
    638 		 * received packet.  The packet will then be
    639 		 * contatentated with this fragment a bit later.
    640 		 */
    641 		if (SEQ_GT(q->ipqe_seq, pkt_seq) &&
    642 		    SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len))  {
    643 			int overlap = pkt_seq + pkt_len - q->ipqe_seq;
    644 #ifdef TCPREASS_DEBUG
    645 			printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
    646 			       tp, overlap,
    647 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
    648 #endif
    649 			m_adj(m, -overlap);
    650 			pkt_len -= overlap;
    651 			rcvpartdupbyte += overlap;
    652 			TCP_REASS_COUNTER_INCR(&tcp_reass_overlapfront);
    653 			rcvoobyte -= overlap;
    654 		}
    655 		/*
    656 		 * If the received segment immediates precedes this
    657 		 * fragment then tack the fragment onto this segment
    658 		 * and reinsert the data.
    659 		 */
    660 		if (q->ipqe_seq == pkt_seq + pkt_len) {
    661 #ifdef TCPREASS_DEBUG
    662 			printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
    663 			       tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
    664 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
    665 #endif
    666 			pkt_len += q->ipqe_len;
    667 			pkt_flags |= q->ipqe_flags;
    668 			m_cat(m, q->ipqe_m);
    669 			TAILQ_REMOVE(&tp->segq, q, ipqe_q);
    670 			TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
    671 			tp->t_segqlen--;
    672 			KASSERT(tp->t_segqlen >= 0);
    673 			KASSERT(tp->t_segqlen != 0 ||
    674 			    (TAILQ_EMPTY(&tp->segq) &&
    675 			    TAILQ_EMPTY(&tp->timeq)));
    676 			if (tiqe == NULL) {
    677 				tiqe = q;
    678 			} else {
    679 				tcpipqent_free(q);
    680 			}
    681 			TCP_REASS_COUNTER_INCR(&tcp_reass_prepend);
    682 			break;
    683 		}
    684 		/*
    685 		 * If the fragment is before the segment, remember it.
    686 		 * When this loop is terminated, p will contain the
    687 		 * pointer to fragment that is right before the received
    688 		 * segment.
    689 		 */
    690 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
    691 			p = q;
    692 
    693 		continue;
    694 
    695 		/*
    696 		 * This is a common operation.  It also will allow
    697 		 * to save doing a malloc/free in most instances.
    698 		 */
    699 	  free_ipqe:
    700 		TAILQ_REMOVE(&tp->segq, q, ipqe_q);
    701 		TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
    702 		tp->t_segqlen--;
    703 		KASSERT(tp->t_segqlen >= 0);
    704 		KASSERT(tp->t_segqlen != 0 ||
    705 		    (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq)));
    706 		if (tiqe == NULL) {
    707 			tiqe = q;
    708 		} else {
    709 			tcpipqent_free(q);
    710 		}
    711 	}
    712 
    713 #ifdef TCP_REASS_COUNTERS
    714 	if (count > 7)
    715 		TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[0]);
    716 	else if (count > 0)
    717 		TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[count]);
    718 #endif
    719 
    720     insert_it:
    721 
    722 	/*
    723 	 * Allocate a new queue entry since the received segment did not
    724 	 * collapse onto any other out-of-order block; thus we are allocating
    725 	 * a new block.  If it had collapsed, tiqe would not be NULL and
    726 	 * we would be reusing it.
    727 	 * XXX If we can't, just drop the packet.  XXX
    728 	 */
    729 	if (tiqe == NULL) {
    730 		tiqe = tcpipqent_alloc();
    731 		if (tiqe == NULL) {
    732 			TCP_STATINC(TCP_STAT_RCVMEMDROP);
    733 			m_freem(m);
    734 			goto out;
    735 		}
    736 	}
    737 
    738 	/*
    739 	 * Update the counters.
    740 	 */
    741 	tcps = TCP_STAT_GETREF();
    742 	tcps[TCP_STAT_RCVOOPACK]++;
    743 	tcps[TCP_STAT_RCVOOBYTE] += rcvoobyte;
    744 	if (rcvpartdupbyte) {
    745 	    tcps[TCP_STAT_RCVPARTDUPPACK]++;
    746 	    tcps[TCP_STAT_RCVPARTDUPBYTE] += rcvpartdupbyte;
    747 	}
    748 	TCP_STAT_PUTREF();
    749 
    750 	/*
    751 	 * Insert the new fragment queue entry into both queues.
    752 	 */
    753 	tiqe->ipqe_m = m;
    754 	tiqe->ipre_mlast = m;
    755 	tiqe->ipqe_seq = pkt_seq;
    756 	tiqe->ipqe_len = pkt_len;
    757 	tiqe->ipqe_flags = pkt_flags;
    758 	if (p == NULL) {
    759 		TAILQ_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
    760 #ifdef TCPREASS_DEBUG
    761 		if (tiqe->ipqe_seq != tp->rcv_nxt)
    762 			printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
    763 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
    764 #endif
    765 	} else {
    766 		TAILQ_INSERT_AFTER(&tp->segq, p, tiqe, ipqe_q);
    767 #ifdef TCPREASS_DEBUG
    768 		printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
    769 		       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
    770 		       p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
    771 #endif
    772 	}
    773 	tp->t_segqlen++;
    774 
    775 skip_replacement:
    776 
    777 	TAILQ_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
    778 
    779 present:
    780 	/*
    781 	 * Present data to user, advancing rcv_nxt through
    782 	 * completed sequence space.
    783 	 */
    784 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
    785 		goto out;
    786 	q = TAILQ_FIRST(&tp->segq);
    787 	if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
    788 		goto out;
    789 	if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
    790 		goto out;
    791 
    792 	tp->rcv_nxt += q->ipqe_len;
    793 	pkt_flags = q->ipqe_flags & TH_FIN;
    794 	nd6_hint(tp);
    795 
    796 	TAILQ_REMOVE(&tp->segq, q, ipqe_q);
    797 	TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
    798 	tp->t_segqlen--;
    799 	KASSERT(tp->t_segqlen >= 0);
    800 	KASSERT(tp->t_segqlen != 0 ||
    801 	    (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq)));
    802 	if (so->so_state & SS_CANTRCVMORE)
    803 		m_freem(q->ipqe_m);
    804 	else
    805 		sbappendstream(&so->so_rcv, q->ipqe_m);
    806 	tcpipqent_free(q);
    807 	TCP_REASS_UNLOCK(tp);
    808 	sorwakeup(so);
    809 	return (pkt_flags);
    810 out:
    811 	TCP_REASS_UNLOCK(tp);
    812 	return (0);
    813 }
    814 
    815 #ifdef INET6
    816 int
    817 tcp6_input(struct mbuf **mp, int *offp, int proto)
    818 {
    819 	struct mbuf *m = *mp;
    820 
    821 	/*
    822 	 * draft-itojun-ipv6-tcp-to-anycast
    823 	 * better place to put this in?
    824 	 */
    825 	if (m->m_flags & M_ANYCAST6) {
    826 		struct ip6_hdr *ip6;
    827 		if (m->m_len < sizeof(struct ip6_hdr)) {
    828 			if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
    829 				TCP_STATINC(TCP_STAT_RCVSHORT);
    830 				return IPPROTO_DONE;
    831 			}
    832 		}
    833 		ip6 = mtod(m, struct ip6_hdr *);
    834 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
    835 		    (char *)&ip6->ip6_dst - (char *)ip6);
    836 		return IPPROTO_DONE;
    837 	}
    838 
    839 	tcp_input(m, *offp, proto);
    840 	return IPPROTO_DONE;
    841 }
    842 #endif
    843 
    844 #ifdef INET
    845 static void
    846 tcp4_log_refused(const struct ip *ip, const struct tcphdr *th)
    847 {
    848 	char src[4*sizeof "123"];
    849 	char dst[4*sizeof "123"];
    850 
    851 	if (ip) {
    852 		strlcpy(src, inet_ntoa(ip->ip_src), sizeof(src));
    853 		strlcpy(dst, inet_ntoa(ip->ip_dst), sizeof(dst));
    854 	}
    855 	else {
    856 		strlcpy(src, "(unknown)", sizeof(src));
    857 		strlcpy(dst, "(unknown)", sizeof(dst));
    858 	}
    859 	log(LOG_INFO,
    860 	    "Connection attempt to TCP %s:%d from %s:%d\n",
    861 	    dst, ntohs(th->th_dport),
    862 	    src, ntohs(th->th_sport));
    863 }
    864 #endif
    865 
    866 #ifdef INET6
    867 static void
    868 tcp6_log_refused(const struct ip6_hdr *ip6, const struct tcphdr *th)
    869 {
    870 	char src[INET6_ADDRSTRLEN];
    871 	char dst[INET6_ADDRSTRLEN];
    872 
    873 	if (ip6) {
    874 		strlcpy(src, ip6_sprintf(&ip6->ip6_src), sizeof(src));
    875 		strlcpy(dst, ip6_sprintf(&ip6->ip6_dst), sizeof(dst));
    876 	}
    877 	else {
    878 		strlcpy(src, "(unknown v6)", sizeof(src));
    879 		strlcpy(dst, "(unknown v6)", sizeof(dst));
    880 	}
    881 	log(LOG_INFO,
    882 	    "Connection attempt to TCP [%s]:%d from [%s]:%d\n",
    883 	    dst, ntohs(th->th_dport),
    884 	    src, ntohs(th->th_sport));
    885 }
    886 #endif
    887 
    888 /*
    889  * Checksum extended TCP header and data.
    890  */
    891 int
    892 tcp_input_checksum(int af, struct mbuf *m, const struct tcphdr *th,
    893     int toff, int off, int tlen)
    894 {
    895 
    896 	/*
    897 	 * XXX it's better to record and check if this mbuf is
    898 	 * already checked.
    899 	 */
    900 
    901 	switch (af) {
    902 #ifdef INET
    903 	case AF_INET:
    904 		switch (m->m_pkthdr.csum_flags &
    905 			((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv4) |
    906 			 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
    907 		case M_CSUM_TCPv4|M_CSUM_TCP_UDP_BAD:
    908 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_bad);
    909 			goto badcsum;
    910 
    911 		case M_CSUM_TCPv4|M_CSUM_DATA: {
    912 			u_int32_t hw_csum = m->m_pkthdr.csum_data;
    913 
    914 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_data);
    915 			if (m->m_pkthdr.csum_flags & M_CSUM_NO_PSEUDOHDR) {
    916 				const struct ip *ip =
    917 				    mtod(m, const struct ip *);
    918 
    919 				hw_csum = in_cksum_phdr(ip->ip_src.s_addr,
    920 				    ip->ip_dst.s_addr,
    921 				    htons(hw_csum + tlen + off + IPPROTO_TCP));
    922 			}
    923 			if ((hw_csum ^ 0xffff) != 0)
    924 				goto badcsum;
    925 			break;
    926 		}
    927 
    928 		case M_CSUM_TCPv4:
    929 			/* Checksum was okay. */
    930 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_ok);
    931 			break;
    932 
    933 		default:
    934 			/*
    935 			 * Must compute it ourselves.  Maybe skip checksum
    936 			 * on loopback interfaces.
    937 			 */
    938 			if (__predict_true(!(m->m_pkthdr.rcvif->if_flags &
    939 					     IFF_LOOPBACK) ||
    940 					   tcp_do_loopback_cksum)) {
    941 				TCP_CSUM_COUNTER_INCR(&tcp_swcsum);
    942 				if (in4_cksum(m, IPPROTO_TCP, toff,
    943 					      tlen + off) != 0)
    944 					goto badcsum;
    945 			}
    946 			break;
    947 		}
    948 		break;
    949 #endif /* INET4 */
    950 
    951 #ifdef INET6
    952 	case AF_INET6:
    953 		switch (m->m_pkthdr.csum_flags &
    954 			((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv6) |
    955 			 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
    956 		case M_CSUM_TCPv6|M_CSUM_TCP_UDP_BAD:
    957 			TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_bad);
    958 			goto badcsum;
    959 
    960 #if 0 /* notyet */
    961 		case M_CSUM_TCPv6|M_CSUM_DATA:
    962 #endif
    963 
    964 		case M_CSUM_TCPv6:
    965 			/* Checksum was okay. */
    966 			TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_ok);
    967 			break;
    968 
    969 		default:
    970 			/*
    971 			 * Must compute it ourselves.  Maybe skip checksum
    972 			 * on loopback interfaces.
    973 			 */
    974 			if (__predict_true((m->m_flags & M_LOOP) == 0 ||
    975 			    tcp_do_loopback_cksum)) {
    976 				TCP_CSUM_COUNTER_INCR(&tcp6_swcsum);
    977 				if (in6_cksum(m, IPPROTO_TCP, toff,
    978 				    tlen + off) != 0)
    979 					goto badcsum;
    980 			}
    981 		}
    982 		break;
    983 #endif /* INET6 */
    984 	}
    985 
    986 	return 0;
    987 
    988 badcsum:
    989 	TCP_STATINC(TCP_STAT_RCVBADSUM);
    990 	return -1;
    991 }
    992 
    993 /* When a packet arrives addressed to a vestigial tcpbp, we
    994  * nevertheless have to respond to it per the spec.
    995  */
    996 static void tcp_vtw_input(struct tcphdr *th, vestigial_inpcb_t *vp,
    997 			  struct mbuf *m, int tlen, int multicast)
    998 {
    999 	int		tiflags;
   1000 	int		todrop, dupseg;
   1001 	uint32_t	t_flags = 0;
   1002 	uint64_t	*tcps;
   1003 
   1004 	tiflags = th->th_flags;
   1005 	todrop  = vp->rcv_nxt - th->th_seq;
   1006 	dupseg  = false;
   1007 
   1008 	if (todrop > 0) {
   1009 		if (tiflags & TH_SYN) {
   1010 			tiflags &= ~TH_SYN;
   1011 			++th->th_seq;
   1012 			if (th->th_urp > 1)
   1013 				--th->th_urp;
   1014 			else {
   1015 				tiflags &= ~TH_URG;
   1016 				th->th_urp = 0;
   1017 			}
   1018 			--todrop;
   1019 		}
   1020 		if (todrop > tlen ||
   1021 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
   1022 			/*
   1023 			 * Any valid FIN or RST must be to the left of the
   1024 			 * window.  At this point the FIN or RST must be a
   1025 			 * duplicate or out of sequence; drop it.
   1026 			 */
   1027 			if (tiflags & TH_RST)
   1028 				goto drop;
   1029 			tiflags &= ~(TH_FIN|TH_RST);
   1030 			/*
   1031 			 * Send an ACK to resynchronize and drop any data.
   1032 			 * But keep on processing for RST or ACK.
   1033 			 */
   1034 			t_flags |= TF_ACKNOW;
   1035 			todrop = tlen;
   1036 			dupseg = true;
   1037 			tcps = TCP_STAT_GETREF();
   1038 			tcps[TCP_STAT_RCVDUPPACK] += 1;
   1039 			tcps[TCP_STAT_RCVDUPBYTE] += todrop;
   1040 			TCP_STAT_PUTREF();
   1041 		} else if ((tiflags & TH_RST)
   1042 			   && th->th_seq != vp->rcv_nxt) {
   1043 			/*
   1044 			 * Test for reset before adjusting the sequence
   1045 			 * number for overlapping data.
   1046 			 */
   1047 			goto dropafterack_ratelim;
   1048 		} else {
   1049 			tcps = TCP_STAT_GETREF();
   1050 			tcps[TCP_STAT_RCVPARTDUPPACK] += 1;
   1051 			tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
   1052 			TCP_STAT_PUTREF();
   1053 		}
   1054 
   1055 //		tcp_new_dsack(tp, th->th_seq, todrop);
   1056 //		hdroptlen += todrop;	/*drop from head afterwards*/
   1057 
   1058 		th->th_seq += todrop;
   1059 		tlen -= todrop;
   1060 
   1061 		if (th->th_urp > todrop)
   1062 			th->th_urp -= todrop;
   1063 		else {
   1064 			tiflags &= ~TH_URG;
   1065 			th->th_urp = 0;
   1066 		}
   1067 	}
   1068 
   1069 	/*
   1070 	 * If new data are received on a connection after the
   1071 	 * user processes are gone, then RST the other end.
   1072 	 */
   1073 	if (tlen) {
   1074 		TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
   1075 		goto dropwithreset;
   1076 	}
   1077 
   1078 	/*
   1079 	 * If segment ends after window, drop trailing data
   1080 	 * (and PUSH and FIN); if nothing left, just ACK.
   1081 	 */
   1082 	todrop = (th->th_seq + tlen) - (vp->rcv_nxt+vp->rcv_wnd);
   1083 
   1084 	if (todrop > 0) {
   1085 		TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
   1086 		if (todrop >= tlen) {
   1087 			/*
   1088 			 * The segment actually starts after the window.
   1089 			 * th->th_seq + tlen - vp->rcv_nxt - vp->rcv_wnd >= tlen
   1090 			 * th->th_seq - vp->rcv_nxt - vp->rcv_wnd >= 0
   1091 			 * th->th_seq >= vp->rcv_nxt + vp->rcv_wnd
   1092 			 */
   1093 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
   1094 			/*
   1095 			 * If a new connection request is received
   1096 			 * while in TIME_WAIT, drop the old connection
   1097 			 * and start over if the sequence numbers
   1098 			 * are above the previous ones.
   1099 			 */
   1100 			if ((tiflags & TH_SYN)
   1101 			    && SEQ_GT(th->th_seq, vp->rcv_nxt)) {
   1102 				/* We only support this in the !NOFDREF case, which
   1103 				 * is to say: not here.
   1104 				 */
   1105 				goto dropwithreset;;
   1106 			}
   1107 			/*
   1108 			 * If window is closed can only take segments at
   1109 			 * window edge, and have to drop data and PUSH from
   1110 			 * incoming segments.  Continue processing, but
   1111 			 * remember to ack.  Otherwise, drop segment
   1112 			 * and (if not RST) ack.
   1113 			 */
   1114 			if (vp->rcv_wnd == 0 && th->th_seq == vp->rcv_nxt) {
   1115 				t_flags |= TF_ACKNOW;
   1116 				TCP_STATINC(TCP_STAT_RCVWINPROBE);
   1117 			} else
   1118 				goto dropafterack;
   1119 		} else
   1120 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
   1121 		m_adj(m, -todrop);
   1122 		tlen -= todrop;
   1123 		tiflags &= ~(TH_PUSH|TH_FIN);
   1124 	}
   1125 
   1126 	if (tiflags & TH_RST) {
   1127 		if (th->th_seq != vp->rcv_nxt)
   1128 			goto dropafterack_ratelim;
   1129 
   1130 		vtw_del(vp->ctl, vp->vtw);
   1131 		goto drop;
   1132 	}
   1133 
   1134 	/*
   1135 	 * If the ACK bit is off we drop the segment and return.
   1136 	 */
   1137 	if ((tiflags & TH_ACK) == 0) {
   1138 		if (t_flags & TF_ACKNOW)
   1139 			goto dropafterack;
   1140 		else
   1141 			goto drop;
   1142 	}
   1143 
   1144 	/*
   1145 	 * In TIME_WAIT state the only thing that should arrive
   1146 	 * is a retransmission of the remote FIN.  Acknowledge
   1147 	 * it and restart the finack timer.
   1148 	 */
   1149 	vtw_restart(vp);
   1150 	goto dropafterack;
   1151 
   1152 dropafterack:
   1153 	/*
   1154 	 * Generate an ACK dropping incoming segment if it occupies
   1155 	 * sequence space, where the ACK reflects our state.
   1156 	 */
   1157 	if (tiflags & TH_RST)
   1158 		goto drop;
   1159 	goto dropafterack2;
   1160 
   1161 dropafterack_ratelim:
   1162 	/*
   1163 	 * We may want to rate-limit ACKs against SYN/RST attack.
   1164 	 */
   1165 	if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
   1166 			 tcp_ackdrop_ppslim) == 0) {
   1167 		/* XXX stat */
   1168 		goto drop;
   1169 	}
   1170 	/* ...fall into dropafterack2... */
   1171 
   1172 dropafterack2:
   1173 	(void)tcp_respond(0, m, m, th, th->th_seq + tlen, th->th_ack,
   1174 			  TH_ACK);
   1175 	return;
   1176 
   1177 dropwithreset:
   1178 	/*
   1179 	 * Generate a RST, dropping incoming segment.
   1180 	 * Make ACK acceptable to originator of segment.
   1181 	 */
   1182 	if (tiflags & TH_RST)
   1183 		goto drop;
   1184 
   1185 	if (tiflags & TH_ACK)
   1186 		tcp_respond(0, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
   1187 	else {
   1188 		if (tiflags & TH_SYN)
   1189 			++tlen;
   1190 		(void)tcp_respond(0, m, m, th, th->th_seq + tlen, (tcp_seq)0,
   1191 				  TH_RST|TH_ACK);
   1192 	}
   1193 	return;
   1194 drop:
   1195 	m_freem(m);
   1196 }
   1197 
   1198 /*
   1199  * TCP input routine, follows pages 65-76 of RFC 793 very closely.
   1200  */
   1201 void
   1202 tcp_input(struct mbuf *m, ...)
   1203 {
   1204 	struct tcphdr *th;
   1205 	struct ip *ip;
   1206 	struct inpcb *inp;
   1207 #ifdef INET6
   1208 	struct ip6_hdr *ip6;
   1209 	struct in6pcb *in6p;
   1210 #endif
   1211 	u_int8_t *optp = NULL;
   1212 	int optlen = 0;
   1213 	int len, tlen, toff, hdroptlen = 0;
   1214 	struct tcpcb *tp = 0;
   1215 	int tiflags;
   1216 	struct socket *so = NULL;
   1217 	int todrop, acked, ourfinisacked, needoutput = 0;
   1218 	bool dupseg;
   1219 #ifdef TCP_DEBUG
   1220 	short ostate = 0;
   1221 #endif
   1222 	u_long tiwin;
   1223 	struct tcp_opt_info opti;
   1224 	int off, iphlen;
   1225 	va_list ap;
   1226 	int af;		/* af on the wire */
   1227 	struct mbuf *tcp_saveti = NULL;
   1228 	uint32_t ts_rtt;
   1229 	uint8_t iptos;
   1230 	uint64_t *tcps;
   1231 	vestigial_inpcb_t vestige;
   1232 
   1233 	vestige.valid = 0;
   1234 
   1235 	MCLAIM(m, &tcp_rx_mowner);
   1236 	va_start(ap, m);
   1237 	toff = va_arg(ap, int);
   1238 	(void)va_arg(ap, int);		/* ignore value, advance ap */
   1239 	va_end(ap);
   1240 
   1241 	TCP_STATINC(TCP_STAT_RCVTOTAL);
   1242 
   1243 	memset(&opti, 0, sizeof(opti));
   1244 	opti.ts_present = 0;
   1245 	opti.maxseg = 0;
   1246 
   1247 	/*
   1248 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN.
   1249 	 *
   1250 	 * TCP is, by definition, unicast, so we reject all
   1251 	 * multicast outright.
   1252 	 *
   1253 	 * Note, there are additional src/dst address checks in
   1254 	 * the AF-specific code below.
   1255 	 */
   1256 	if (m->m_flags & (M_BCAST|M_MCAST)) {
   1257 		/* XXX stat */
   1258 		goto drop;
   1259 	}
   1260 #ifdef INET6
   1261 	if (m->m_flags & M_ANYCAST6) {
   1262 		/* XXX stat */
   1263 		goto drop;
   1264 	}
   1265 #endif
   1266 
   1267 	/*
   1268 	 * Get IP and TCP header.
   1269 	 * Note: IP leaves IP header in first mbuf.
   1270 	 */
   1271 	ip = mtod(m, struct ip *);
   1272 	switch (ip->ip_v) {
   1273 #ifdef INET
   1274 	case 4:
   1275 #ifdef INET6
   1276 		ip6 = NULL;
   1277 #endif
   1278 		af = AF_INET;
   1279 		iphlen = sizeof(struct ip);
   1280 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
   1281 			sizeof(struct tcphdr));
   1282 		if (th == NULL) {
   1283 			TCP_STATINC(TCP_STAT_RCVSHORT);
   1284 			return;
   1285 		}
   1286 		/* We do the checksum after PCB lookup... */
   1287 		len = ntohs(ip->ip_len);
   1288 		tlen = len - toff;
   1289 		iptos = ip->ip_tos;
   1290 		break;
   1291 #endif
   1292 #ifdef INET6
   1293 	case 6:
   1294 		ip = NULL;
   1295 		iphlen = sizeof(struct ip6_hdr);
   1296 		af = AF_INET6;
   1297 		ip6 = mtod(m, struct ip6_hdr *);
   1298 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
   1299 			sizeof(struct tcphdr));
   1300 		if (th == NULL) {
   1301 			TCP_STATINC(TCP_STAT_RCVSHORT);
   1302 			return;
   1303 		}
   1304 
   1305 		/* Be proactive about malicious use of IPv4 mapped address */
   1306 		if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
   1307 		    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
   1308 			/* XXX stat */
   1309 			goto drop;
   1310 		}
   1311 
   1312 		/*
   1313 		 * Be proactive about unspecified IPv6 address in source.
   1314 		 * As we use all-zero to indicate unbounded/unconnected pcb,
   1315 		 * unspecified IPv6 address can be used to confuse us.
   1316 		 *
   1317 		 * Note that packets with unspecified IPv6 destination is
   1318 		 * already dropped in ip6_input.
   1319 		 */
   1320 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
   1321 			/* XXX stat */
   1322 			goto drop;
   1323 		}
   1324 
   1325 		/*
   1326 		 * Make sure destination address is not multicast.
   1327 		 * Source address checked in ip6_input().
   1328 		 */
   1329 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
   1330 			/* XXX stat */
   1331 			goto drop;
   1332 		}
   1333 
   1334 		/* We do the checksum after PCB lookup... */
   1335 		len = m->m_pkthdr.len;
   1336 		tlen = len - toff;
   1337 		iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
   1338 		break;
   1339 #endif
   1340 	default:
   1341 		m_freem(m);
   1342 		return;
   1343 	}
   1344 
   1345 	KASSERT(TCP_HDR_ALIGNED_P(th));
   1346 
   1347 	/*
   1348 	 * Check that TCP offset makes sense,
   1349 	 * pull out TCP options and adjust length.		XXX
   1350 	 */
   1351 	off = th->th_off << 2;
   1352 	if (off < sizeof (struct tcphdr) || off > tlen) {
   1353 		TCP_STATINC(TCP_STAT_RCVBADOFF);
   1354 		goto drop;
   1355 	}
   1356 	tlen -= off;
   1357 
   1358 	/*
   1359 	 * tcp_input() has been modified to use tlen to mean the TCP data
   1360 	 * length throughout the function.  Other functions can use
   1361 	 * m->m_pkthdr.len as the basis for calculating the TCP data length.
   1362 	 * rja
   1363 	 */
   1364 
   1365 	if (off > sizeof (struct tcphdr)) {
   1366 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, off);
   1367 		if (th == NULL) {
   1368 			TCP_STATINC(TCP_STAT_RCVSHORT);
   1369 			return;
   1370 		}
   1371 		/*
   1372 		 * NOTE: ip/ip6 will not be affected by m_pulldown()
   1373 		 * (as they're before toff) and we don't need to update those.
   1374 		 */
   1375 		KASSERT(TCP_HDR_ALIGNED_P(th));
   1376 		optlen = off - sizeof (struct tcphdr);
   1377 		optp = ((u_int8_t *)th) + sizeof(struct tcphdr);
   1378 		/*
   1379 		 * Do quick retrieval of timestamp options ("options
   1380 		 * prediction?").  If timestamp is the only option and it's
   1381 		 * formatted as recommended in RFC 1323 appendix A, we
   1382 		 * quickly get the values now and not bother calling
   1383 		 * tcp_dooptions(), etc.
   1384 		 */
   1385 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
   1386 		     (optlen > TCPOLEN_TSTAMP_APPA &&
   1387 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
   1388 		     *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
   1389 		     (th->th_flags & TH_SYN) == 0) {
   1390 			opti.ts_present = 1;
   1391 			opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
   1392 			opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
   1393 			optp = NULL;	/* we've parsed the options */
   1394 		}
   1395 	}
   1396 	tiflags = th->th_flags;
   1397 
   1398 	/*
   1399 	 * Locate pcb for segment.
   1400 	 */
   1401 findpcb:
   1402 	inp = NULL;
   1403 #ifdef INET6
   1404 	in6p = NULL;
   1405 #endif
   1406 	switch (af) {
   1407 #ifdef INET
   1408 	case AF_INET:
   1409 		inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
   1410 					   ip->ip_dst, th->th_dport,
   1411 					   &vestige);
   1412 		if (inp == 0 && !vestige.valid) {
   1413 			TCP_STATINC(TCP_STAT_PCBHASHMISS);
   1414 			inp = in_pcblookup_bind(&tcbtable, ip->ip_dst, th->th_dport);
   1415 		}
   1416 #ifdef INET6
   1417 		if (inp == 0 && !vestige.valid) {
   1418 			struct in6_addr s, d;
   1419 
   1420 			/* mapped addr case */
   1421 			memset(&s, 0, sizeof(s));
   1422 			s.s6_addr16[5] = htons(0xffff);
   1423 			bcopy(&ip->ip_src, &s.s6_addr32[3], sizeof(ip->ip_src));
   1424 			memset(&d, 0, sizeof(d));
   1425 			d.s6_addr16[5] = htons(0xffff);
   1426 			bcopy(&ip->ip_dst, &d.s6_addr32[3], sizeof(ip->ip_dst));
   1427 			in6p = in6_pcblookup_connect(&tcbtable, &s,
   1428 						     th->th_sport, &d, th->th_dport,
   1429 						     0, &vestige);
   1430 			if (in6p == 0 && !vestige.valid) {
   1431 				TCP_STATINC(TCP_STAT_PCBHASHMISS);
   1432 				in6p = in6_pcblookup_bind(&tcbtable, &d,
   1433 				    th->th_dport, 0);
   1434 			}
   1435 		}
   1436 #endif
   1437 #ifndef INET6
   1438 		if (inp == 0 && !vestige.valid)
   1439 #else
   1440 		if (inp == 0 && in6p == 0 && !vestige.valid)
   1441 #endif
   1442 		{
   1443 			TCP_STATINC(TCP_STAT_NOPORT);
   1444 			if (tcp_log_refused &&
   1445 			    (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
   1446 				tcp4_log_refused(ip, th);
   1447 			}
   1448 			tcp_fields_to_host(th);
   1449 			goto dropwithreset_ratelim;
   1450 		}
   1451 #if defined(IPSEC)
   1452 		if (inp && (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0 &&
   1453 		    ipsec4_in_reject(m, inp)) {
   1454 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1455 			goto drop;
   1456 		}
   1457 #ifdef INET6
   1458 		else if (in6p &&
   1459 		    (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 &&
   1460 		    ipsec6_in_reject_so(m, in6p->in6p_socket)) {
   1461 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1462 			goto drop;
   1463 		}
   1464 #endif
   1465 #endif /*IPSEC*/
   1466 		break;
   1467 #endif /*INET*/
   1468 #ifdef INET6
   1469 	case AF_INET6:
   1470 	    {
   1471 		int faith;
   1472 
   1473 #if defined(NFAITH) && NFAITH > 0
   1474 		faith = faithprefix(&ip6->ip6_dst);
   1475 #else
   1476 		faith = 0;
   1477 #endif
   1478 		in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src,
   1479 					     th->th_sport, &ip6->ip6_dst, th->th_dport, faith, &vestige);
   1480 		if (!in6p && !vestige.valid) {
   1481 			TCP_STATINC(TCP_STAT_PCBHASHMISS);
   1482 			in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst,
   1483 				th->th_dport, faith);
   1484 		}
   1485 		if (!in6p && !vestige.valid) {
   1486 			TCP_STATINC(TCP_STAT_NOPORT);
   1487 			if (tcp_log_refused &&
   1488 			    (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
   1489 				tcp6_log_refused(ip6, th);
   1490 			}
   1491 			tcp_fields_to_host(th);
   1492 			goto dropwithreset_ratelim;
   1493 		}
   1494 #if defined(IPSEC)
   1495 		if (in6p
   1496 		    && (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0
   1497 		    && ipsec6_in_reject(m, in6p)) {
   1498 			IPSEC6_STATINC(IPSEC_STAT_IN_POLVIO);
   1499 			goto drop;
   1500 		}
   1501 #endif /*IPSEC*/
   1502 		break;
   1503 	    }
   1504 #endif
   1505 	}
   1506 
   1507 	/*
   1508 	 * If the state is CLOSED (i.e., TCB does not exist) then
   1509 	 * all data in the incoming segment is discarded.
   1510 	 * If the TCB exists but is in CLOSED state, it is embryonic,
   1511 	 * but should either do a listen or a connect soon.
   1512 	 */
   1513 	tp = NULL;
   1514 	so = NULL;
   1515 	if (inp) {
   1516 		/* Check the minimum TTL for socket. */
   1517 		if (ip->ip_ttl < inp->inp_ip_minttl)
   1518 			goto drop;
   1519 
   1520 		tp = intotcpcb(inp);
   1521 		so = inp->inp_socket;
   1522 	}
   1523 #ifdef INET6
   1524 	else if (in6p) {
   1525 		tp = in6totcpcb(in6p);
   1526 		so = in6p->in6p_socket;
   1527 	}
   1528 #endif
   1529 	else if (vestige.valid) {
   1530 		int mc = 0;
   1531 
   1532 		/* We do not support the resurrection of vtw tcpcps.
   1533 		 */
   1534 		if (tcp_input_checksum(af, m, th, toff, off, tlen))
   1535 			goto badcsum;
   1536 
   1537 		switch (af) {
   1538 #ifdef INET6
   1539 		case AF_INET6:
   1540 			mc = IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst);
   1541 			break;
   1542 #endif
   1543 
   1544 		case AF_INET:
   1545 			mc = (IN_MULTICAST(ip->ip_dst.s_addr)
   1546 			      || in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif));
   1547 			break;
   1548 		}
   1549 
   1550 		tcp_fields_to_host(th);
   1551 		tcp_vtw_input(th, &vestige, m, tlen, mc);
   1552 		m = 0;
   1553 		goto drop;
   1554 	}
   1555 
   1556 	if (tp == 0) {
   1557 		tcp_fields_to_host(th);
   1558 		goto dropwithreset_ratelim;
   1559 	}
   1560 	if (tp->t_state == TCPS_CLOSED)
   1561 		goto drop;
   1562 
   1563 	KASSERT(so->so_lock == softnet_lock);
   1564 	KASSERT(solocked(so));
   1565 
   1566 	/*
   1567 	 * Checksum extended TCP header and data.
   1568 	 */
   1569 	if (tcp_input_checksum(af, m, th, toff, off, tlen))
   1570 		goto badcsum;
   1571 
   1572 	tcp_fields_to_host(th);
   1573 
   1574 	/* Unscale the window into a 32-bit value. */
   1575 	if ((tiflags & TH_SYN) == 0)
   1576 		tiwin = th->th_win << tp->snd_scale;
   1577 	else
   1578 		tiwin = th->th_win;
   1579 
   1580 #ifdef INET6
   1581 	/* save packet options if user wanted */
   1582 	if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
   1583 		if (in6p->in6p_options) {
   1584 			m_freem(in6p->in6p_options);
   1585 			in6p->in6p_options = 0;
   1586 		}
   1587 		KASSERT(ip6 != NULL);
   1588 		ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
   1589 	}
   1590 #endif
   1591 
   1592 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
   1593 		union syn_cache_sa src;
   1594 		union syn_cache_sa dst;
   1595 
   1596 		memset(&src, 0, sizeof(src));
   1597 		memset(&dst, 0, sizeof(dst));
   1598 		switch (af) {
   1599 #ifdef INET
   1600 		case AF_INET:
   1601 			src.sin.sin_len = sizeof(struct sockaddr_in);
   1602 			src.sin.sin_family = AF_INET;
   1603 			src.sin.sin_addr = ip->ip_src;
   1604 			src.sin.sin_port = th->th_sport;
   1605 
   1606 			dst.sin.sin_len = sizeof(struct sockaddr_in);
   1607 			dst.sin.sin_family = AF_INET;
   1608 			dst.sin.sin_addr = ip->ip_dst;
   1609 			dst.sin.sin_port = th->th_dport;
   1610 			break;
   1611 #endif
   1612 #ifdef INET6
   1613 		case AF_INET6:
   1614 			src.sin6.sin6_len = sizeof(struct sockaddr_in6);
   1615 			src.sin6.sin6_family = AF_INET6;
   1616 			src.sin6.sin6_addr = ip6->ip6_src;
   1617 			src.sin6.sin6_port = th->th_sport;
   1618 
   1619 			dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
   1620 			dst.sin6.sin6_family = AF_INET6;
   1621 			dst.sin6.sin6_addr = ip6->ip6_dst;
   1622 			dst.sin6.sin6_port = th->th_dport;
   1623 			break;
   1624 #endif /* INET6 */
   1625 		default:
   1626 			goto badsyn;	/*sanity*/
   1627 		}
   1628 
   1629 		if (so->so_options & SO_DEBUG) {
   1630 #ifdef TCP_DEBUG
   1631 			ostate = tp->t_state;
   1632 #endif
   1633 
   1634 			tcp_saveti = NULL;
   1635 			if (iphlen + sizeof(struct tcphdr) > MHLEN)
   1636 				goto nosave;
   1637 
   1638 			if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) {
   1639 				tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
   1640 				if (!tcp_saveti)
   1641 					goto nosave;
   1642 			} else {
   1643 				MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER);
   1644 				if (!tcp_saveti)
   1645 					goto nosave;
   1646 				MCLAIM(m, &tcp_mowner);
   1647 				tcp_saveti->m_len = iphlen;
   1648 				m_copydata(m, 0, iphlen,
   1649 				    mtod(tcp_saveti, void *));
   1650 			}
   1651 
   1652 			if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
   1653 				m_freem(tcp_saveti);
   1654 				tcp_saveti = NULL;
   1655 			} else {
   1656 				tcp_saveti->m_len += sizeof(struct tcphdr);
   1657 				memcpy(mtod(tcp_saveti, char *) + iphlen, th,
   1658 				    sizeof(struct tcphdr));
   1659 			}
   1660 	nosave:;
   1661 		}
   1662 		if (so->so_options & SO_ACCEPTCONN) {
   1663 			if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
   1664 				if (tiflags & TH_RST) {
   1665 					syn_cache_reset(&src.sa, &dst.sa, th);
   1666 				} else if ((tiflags & (TH_ACK|TH_SYN)) ==
   1667 				    (TH_ACK|TH_SYN)) {
   1668 					/*
   1669 					 * Received a SYN,ACK.  This should
   1670 					 * never happen while we are in
   1671 					 * LISTEN.  Send an RST.
   1672 					 */
   1673 					goto badsyn;
   1674 				} else if (tiflags & TH_ACK) {
   1675 					so = syn_cache_get(&src.sa, &dst.sa,
   1676 						th, toff, tlen, so, m);
   1677 					if (so == NULL) {
   1678 						/*
   1679 						 * We don't have a SYN for
   1680 						 * this ACK; send an RST.
   1681 						 */
   1682 						goto badsyn;
   1683 					} else if (so ==
   1684 					    (struct socket *)(-1)) {
   1685 						/*
   1686 						 * We were unable to create
   1687 						 * the connection.  If the
   1688 						 * 3-way handshake was
   1689 						 * completed, and RST has
   1690 						 * been sent to the peer.
   1691 						 * Since the mbuf might be
   1692 						 * in use for the reply,
   1693 						 * do not free it.
   1694 						 */
   1695 						m = NULL;
   1696 					} else {
   1697 						/*
   1698 						 * We have created a
   1699 						 * full-blown connection.
   1700 						 */
   1701 						tp = NULL;
   1702 						inp = NULL;
   1703 #ifdef INET6
   1704 						in6p = NULL;
   1705 #endif
   1706 						switch (so->so_proto->pr_domain->dom_family) {
   1707 #ifdef INET
   1708 						case AF_INET:
   1709 							inp = sotoinpcb(so);
   1710 							tp = intotcpcb(inp);
   1711 							break;
   1712 #endif
   1713 #ifdef INET6
   1714 						case AF_INET6:
   1715 							in6p = sotoin6pcb(so);
   1716 							tp = in6totcpcb(in6p);
   1717 							break;
   1718 #endif
   1719 						}
   1720 						if (tp == NULL)
   1721 							goto badsyn;	/*XXX*/
   1722 						tiwin <<= tp->snd_scale;
   1723 						goto after_listen;
   1724 					}
   1725 				} else {
   1726 					/*
   1727 					 * None of RST, SYN or ACK was set.
   1728 					 * This is an invalid packet for a
   1729 					 * TCB in LISTEN state.  Send a RST.
   1730 					 */
   1731 					goto badsyn;
   1732 				}
   1733 			} else {
   1734 				/*
   1735 				 * Received a SYN.
   1736 				 *
   1737 				 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
   1738 				 */
   1739 				if (m->m_flags & (M_BCAST|M_MCAST))
   1740 					goto drop;
   1741 
   1742 				switch (af) {
   1743 #ifdef INET6
   1744 				case AF_INET6:
   1745 					if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
   1746 						goto drop;
   1747 					break;
   1748 #endif /* INET6 */
   1749 				case AF_INET:
   1750 					if (IN_MULTICAST(ip->ip_dst.s_addr) ||
   1751 					    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
   1752 						goto drop;
   1753 				break;
   1754 				}
   1755 
   1756 #ifdef INET6
   1757 				/*
   1758 				 * If deprecated address is forbidden, we do
   1759 				 * not accept SYN to deprecated interface
   1760 				 * address to prevent any new inbound
   1761 				 * connection from getting established.
   1762 				 * When we do not accept SYN, we send a TCP
   1763 				 * RST, with deprecated source address (instead
   1764 				 * of dropping it).  We compromise it as it is
   1765 				 * much better for peer to send a RST, and
   1766 				 * RST will be the final packet for the
   1767 				 * exchange.
   1768 				 *
   1769 				 * If we do not forbid deprecated addresses, we
   1770 				 * accept the SYN packet.  RFC2462 does not
   1771 				 * suggest dropping SYN in this case.
   1772 				 * If we decipher RFC2462 5.5.4, it says like
   1773 				 * this:
   1774 				 * 1. use of deprecated addr with existing
   1775 				 *    communication is okay - "SHOULD continue
   1776 				 *    to be used"
   1777 				 * 2. use of it with new communication:
   1778 				 *   (2a) "SHOULD NOT be used if alternate
   1779 				 *        address with sufficient scope is
   1780 				 *        available"
   1781 				 *   (2b) nothing mentioned otherwise.
   1782 				 * Here we fall into (2b) case as we have no
   1783 				 * choice in our source address selection - we
   1784 				 * must obey the peer.
   1785 				 *
   1786 				 * The wording in RFC2462 is confusing, and
   1787 				 * there are multiple description text for
   1788 				 * deprecated address handling - worse, they
   1789 				 * are not exactly the same.  I believe 5.5.4
   1790 				 * is the best one, so we follow 5.5.4.
   1791 				 */
   1792 				if (af == AF_INET6 && !ip6_use_deprecated) {
   1793 					struct in6_ifaddr *ia6;
   1794 					if ((ia6 = in6ifa_ifpwithaddr(m->m_pkthdr.rcvif,
   1795 					    &ip6->ip6_dst)) &&
   1796 					    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
   1797 						tp = NULL;
   1798 						goto dropwithreset;
   1799 					}
   1800 				}
   1801 #endif
   1802 
   1803 #if defined(IPSEC)
   1804 				switch (af) {
   1805 #ifdef INET
   1806 				case AF_INET:
   1807 					if (ipsec4_in_reject_so(m, so)) {
   1808 						IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
   1809 						tp = NULL;
   1810 						goto dropwithreset;
   1811 					}
   1812 					break;
   1813 #endif
   1814 #ifdef INET6
   1815 				case AF_INET6:
   1816 					if (ipsec6_in_reject_so(m, so)) {
   1817 						IPSEC6_STATINC(IPSEC_STAT_IN_POLVIO);
   1818 						tp = NULL;
   1819 						goto dropwithreset;
   1820 					}
   1821 					break;
   1822 #endif /*INET6*/
   1823 				}
   1824 #endif /*IPSEC*/
   1825 
   1826 				/*
   1827 				 * LISTEN socket received a SYN
   1828 				 * from itself?  This can't possibly
   1829 				 * be valid; drop the packet.
   1830 				 */
   1831 				if (th->th_sport == th->th_dport) {
   1832 					int i;
   1833 
   1834 					switch (af) {
   1835 #ifdef INET
   1836 					case AF_INET:
   1837 						i = in_hosteq(ip->ip_src, ip->ip_dst);
   1838 						break;
   1839 #endif
   1840 #ifdef INET6
   1841 					case AF_INET6:
   1842 						i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst);
   1843 						break;
   1844 #endif
   1845 					default:
   1846 						i = 1;
   1847 					}
   1848 					if (i) {
   1849 						TCP_STATINC(TCP_STAT_BADSYN);
   1850 						goto drop;
   1851 					}
   1852 				}
   1853 
   1854 				/*
   1855 				 * SYN looks ok; create compressed TCP
   1856 				 * state for it.
   1857 				 */
   1858 				if (so->so_qlen <= so->so_qlimit &&
   1859 				    syn_cache_add(&src.sa, &dst.sa, th, tlen,
   1860 						so, m, optp, optlen, &opti))
   1861 					m = NULL;
   1862 			}
   1863 			goto drop;
   1864 		}
   1865 	}
   1866 
   1867 after_listen:
   1868 #ifdef DIAGNOSTIC
   1869 	/*
   1870 	 * Should not happen now that all embryonic connections
   1871 	 * are handled with compressed state.
   1872 	 */
   1873 	if (tp->t_state == TCPS_LISTEN)
   1874 		panic("tcp_input: TCPS_LISTEN");
   1875 #endif
   1876 
   1877 	/*
   1878 	 * Segment received on connection.
   1879 	 * Reset idle time and keep-alive timer.
   1880 	 */
   1881 	tp->t_rcvtime = tcp_now;
   1882 	if (TCPS_HAVEESTABLISHED(tp->t_state))
   1883 		TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepidle);
   1884 
   1885 	/*
   1886 	 * Process options.
   1887 	 */
   1888 #ifdef TCP_SIGNATURE
   1889 	if (optp || (tp->t_flags & TF_SIGNATURE))
   1890 #else
   1891 	if (optp)
   1892 #endif
   1893 		if (tcp_dooptions(tp, optp, optlen, th, m, toff, &opti) < 0)
   1894 			goto drop;
   1895 
   1896 	if (TCP_SACK_ENABLED(tp)) {
   1897 		tcp_del_sackholes(tp, th);
   1898 	}
   1899 
   1900 	if (TCP_ECN_ALLOWED(tp)) {
   1901 		if (tiflags & TH_CWR) {
   1902 			tp->t_flags &= ~TF_ECN_SND_ECE;
   1903 		}
   1904 		switch (iptos & IPTOS_ECN_MASK) {
   1905 		case IPTOS_ECN_CE:
   1906 			tp->t_flags |= TF_ECN_SND_ECE;
   1907 			TCP_STATINC(TCP_STAT_ECN_CE);
   1908 			break;
   1909 		case IPTOS_ECN_ECT0:
   1910 			TCP_STATINC(TCP_STAT_ECN_ECT);
   1911 			break;
   1912 		case IPTOS_ECN_ECT1:
   1913 			/* XXX: ignore for now -- rpaulo */
   1914 			break;
   1915 		}
   1916 		/*
   1917 		 * Congestion experienced.
   1918 		 * Ignore if we are already trying to recover.
   1919 		 */
   1920 		if ((tiflags & TH_ECE) && SEQ_GEQ(tp->snd_una, tp->snd_recover))
   1921 			tp->t_congctl->cong_exp(tp);
   1922 	}
   1923 
   1924 	if (opti.ts_present && opti.ts_ecr) {
   1925 		/*
   1926 		 * Calculate the RTT from the returned time stamp and the
   1927 		 * connection's time base.  If the time stamp is later than
   1928 		 * the current time, or is extremely old, fall back to non-1323
   1929 		 * RTT calculation.  Since ts_rtt is unsigned, we can test both
   1930 		 * at the same time.
   1931 		 *
   1932 		 * Note that ts_rtt is in units of slow ticks (500
   1933 		 * ms).  Since most earthbound RTTs are < 500 ms,
   1934 		 * observed values will have large quantization noise.
   1935 		 * Our smoothed RTT is then the fraction of observed
   1936 		 * samples that are 1 tick instead of 0 (times 500
   1937 		 * ms).
   1938 		 *
   1939 		 * ts_rtt is increased by 1 to denote a valid sample,
   1940 		 * with 0 indicating an invalid measurement.  This
   1941 		 * extra 1 must be removed when ts_rtt is used, or
   1942 		 * else an an erroneous extra 500 ms will result.
   1943 		 */
   1944 		ts_rtt = TCP_TIMESTAMP(tp) - opti.ts_ecr + 1;
   1945 		if (ts_rtt > TCP_PAWS_IDLE)
   1946 			ts_rtt = 0;
   1947 	} else {
   1948 		ts_rtt = 0;
   1949 	}
   1950 
   1951 	/*
   1952 	 * Header prediction: check for the two common cases
   1953 	 * of a uni-directional data xfer.  If the packet has
   1954 	 * no control flags, is in-sequence, the window didn't
   1955 	 * change and we're not retransmitting, it's a
   1956 	 * candidate.  If the length is zero and the ack moved
   1957 	 * forward, we're the sender side of the xfer.  Just
   1958 	 * free the data acked & wake any higher level process
   1959 	 * that was blocked waiting for space.  If the length
   1960 	 * is non-zero and the ack didn't move, we're the
   1961 	 * receiver side.  If we're getting packets in-order
   1962 	 * (the reassembly queue is empty), add the data to
   1963 	 * the socket buffer and note that we need a delayed ack.
   1964 	 */
   1965 	if (tp->t_state == TCPS_ESTABLISHED &&
   1966 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ECE|TH_CWR|TH_ACK))
   1967 	        == TH_ACK &&
   1968 	    (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
   1969 	    th->th_seq == tp->rcv_nxt &&
   1970 	    tiwin && tiwin == tp->snd_wnd &&
   1971 	    tp->snd_nxt == tp->snd_max) {
   1972 
   1973 		/*
   1974 		 * If last ACK falls within this segment's sequence numbers,
   1975 		 * record the timestamp.
   1976 		 * NOTE that the test is modified according to the latest
   1977 		 * proposal of the tcplw (at) cray.com list (Braden 1993/04/26).
   1978 		 *
   1979 		 * note that we already know
   1980 		 *	TSTMP_GEQ(opti.ts_val, tp->ts_recent)
   1981 		 */
   1982 		if (opti.ts_present &&
   1983 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
   1984 			tp->ts_recent_age = tcp_now;
   1985 			tp->ts_recent = opti.ts_val;
   1986 		}
   1987 
   1988 		if (tlen == 0) {
   1989 			/* Ack prediction. */
   1990 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
   1991 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
   1992 			    tp->snd_cwnd >= tp->snd_wnd &&
   1993 			    tp->t_partialacks < 0) {
   1994 				/*
   1995 				 * this is a pure ack for outstanding data.
   1996 				 */
   1997 				if (ts_rtt)
   1998 					tcp_xmit_timer(tp, ts_rtt - 1);
   1999 				else if (tp->t_rtttime &&
   2000 				    SEQ_GT(th->th_ack, tp->t_rtseq))
   2001 					tcp_xmit_timer(tp,
   2002 					  tcp_now - tp->t_rtttime);
   2003 				acked = th->th_ack - tp->snd_una;
   2004 				tcps = TCP_STAT_GETREF();
   2005 				tcps[TCP_STAT_PREDACK]++;
   2006 				tcps[TCP_STAT_RCVACKPACK]++;
   2007 				tcps[TCP_STAT_RCVACKBYTE] += acked;
   2008 				TCP_STAT_PUTREF();
   2009 				nd6_hint(tp);
   2010 
   2011 				if (acked > (tp->t_lastoff - tp->t_inoff))
   2012 					tp->t_lastm = NULL;
   2013 				sbdrop(&so->so_snd, acked);
   2014 				tp->t_lastoff -= acked;
   2015 
   2016 				icmp_check(tp, th, acked);
   2017 
   2018 				tp->snd_una = th->th_ack;
   2019 				tp->snd_fack = tp->snd_una;
   2020 				if (SEQ_LT(tp->snd_high, tp->snd_una))
   2021 					tp->snd_high = tp->snd_una;
   2022 				m_freem(m);
   2023 
   2024 				/*
   2025 				 * If all outstanding data are acked, stop
   2026 				 * retransmit timer, otherwise restart timer
   2027 				 * using current (possibly backed-off) value.
   2028 				 * If process is waiting for space,
   2029 				 * wakeup/selnotify/signal.  If data
   2030 				 * are ready to send, let tcp_output
   2031 				 * decide between more output or persist.
   2032 				 */
   2033 				if (tp->snd_una == tp->snd_max)
   2034 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
   2035 				else if (TCP_TIMER_ISARMED(tp,
   2036 				    TCPT_PERSIST) == 0)
   2037 					TCP_TIMER_ARM(tp, TCPT_REXMT,
   2038 					    tp->t_rxtcur);
   2039 
   2040 				sowwakeup(so);
   2041 				if (so->so_snd.sb_cc) {
   2042 					KERNEL_LOCK(1, NULL);
   2043 					(void) tcp_output(tp);
   2044 					KERNEL_UNLOCK_ONE(NULL);
   2045 				}
   2046 				if (tcp_saveti)
   2047 					m_freem(tcp_saveti);
   2048 				return;
   2049 			}
   2050 		} else if (th->th_ack == tp->snd_una &&
   2051 		    TAILQ_FIRST(&tp->segq) == NULL &&
   2052 		    tlen <= sbspace(&so->so_rcv)) {
   2053 			int newsize = 0;	/* automatic sockbuf scaling */
   2054 
   2055 			/*
   2056 			 * this is a pure, in-sequence data packet
   2057 			 * with nothing on the reassembly queue and
   2058 			 * we have enough buffer space to take it.
   2059 			 */
   2060 			tp->rcv_nxt += tlen;
   2061 			tcps = TCP_STAT_GETREF();
   2062 			tcps[TCP_STAT_PREDDAT]++;
   2063 			tcps[TCP_STAT_RCVPACK]++;
   2064 			tcps[TCP_STAT_RCVBYTE] += tlen;
   2065 			TCP_STAT_PUTREF();
   2066 			nd6_hint(tp);
   2067 
   2068 		/*
   2069 		 * Automatic sizing enables the performance of large buffers
   2070 		 * and most of the efficiency of small ones by only allocating
   2071 		 * space when it is needed.
   2072 		 *
   2073 		 * On the receive side the socket buffer memory is only rarely
   2074 		 * used to any significant extent.  This allows us to be much
   2075 		 * more aggressive in scaling the receive socket buffer.  For
   2076 		 * the case that the buffer space is actually used to a large
   2077 		 * extent and we run out of kernel memory we can simply drop
   2078 		 * the new segments; TCP on the sender will just retransmit it
   2079 		 * later.  Setting the buffer size too big may only consume too
   2080 		 * much kernel memory if the application doesn't read() from
   2081 		 * the socket or packet loss or reordering makes use of the
   2082 		 * reassembly queue.
   2083 		 *
   2084 		 * The criteria to step up the receive buffer one notch are:
   2085 		 *  1. the number of bytes received during the time it takes
   2086 		 *     one timestamp to be reflected back to us (the RTT);
   2087 		 *  2. received bytes per RTT is within seven eighth of the
   2088 		 *     current socket buffer size;
   2089 		 *  3. receive buffer size has not hit maximal automatic size;
   2090 		 *
   2091 		 * This algorithm does one step per RTT at most and only if
   2092 		 * we receive a bulk stream w/o packet losses or reorderings.
   2093 		 * Shrinking the buffer during idle times is not necessary as
   2094 		 * it doesn't consume any memory when idle.
   2095 		 *
   2096 		 * TODO: Only step up if the application is actually serving
   2097 		 * the buffer to better manage the socket buffer resources.
   2098 		 */
   2099 			if (tcp_do_autorcvbuf &&
   2100 			    opti.ts_ecr &&
   2101 			    (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
   2102 				if (opti.ts_ecr > tp->rfbuf_ts &&
   2103 				    opti.ts_ecr - tp->rfbuf_ts < PR_SLOWHZ) {
   2104 					if (tp->rfbuf_cnt >
   2105 					    (so->so_rcv.sb_hiwat / 8 * 7) &&
   2106 					    so->so_rcv.sb_hiwat <
   2107 					    tcp_autorcvbuf_max) {
   2108 						newsize =
   2109 						    min(so->so_rcv.sb_hiwat +
   2110 						    tcp_autorcvbuf_inc,
   2111 						    tcp_autorcvbuf_max);
   2112 					}
   2113 					/* Start over with next RTT. */
   2114 					tp->rfbuf_ts = 0;
   2115 					tp->rfbuf_cnt = 0;
   2116 				} else
   2117 					tp->rfbuf_cnt += tlen;	/* add up */
   2118 			}
   2119 
   2120 			/*
   2121 			 * Drop TCP, IP headers and TCP options then add data
   2122 			 * to socket buffer.
   2123 			 */
   2124 			if (so->so_state & SS_CANTRCVMORE)
   2125 				m_freem(m);
   2126 			else {
   2127 				/*
   2128 				 * Set new socket buffer size.
   2129 				 * Give up when limit is reached.
   2130 				 */
   2131 				if (newsize)
   2132 					if (!sbreserve(&so->so_rcv,
   2133 					    newsize, so))
   2134 						so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
   2135 				m_adj(m, toff + off);
   2136 				sbappendstream(&so->so_rcv, m);
   2137 			}
   2138 			sorwakeup(so);
   2139 			tcp_setup_ack(tp, th);
   2140 			if (tp->t_flags & TF_ACKNOW) {
   2141 				KERNEL_LOCK(1, NULL);
   2142 				(void) tcp_output(tp);
   2143 				KERNEL_UNLOCK_ONE(NULL);
   2144 			}
   2145 			if (tcp_saveti)
   2146 				m_freem(tcp_saveti);
   2147 			return;
   2148 		}
   2149 	}
   2150 
   2151 	/*
   2152 	 * Compute mbuf offset to TCP data segment.
   2153 	 */
   2154 	hdroptlen = toff + off;
   2155 
   2156 	/*
   2157 	 * Calculate amount of space in receive window,
   2158 	 * and then do TCP input processing.
   2159 	 * Receive window is amount of space in rcv queue,
   2160 	 * but not less than advertised window.
   2161 	 */
   2162 	{ int win;
   2163 
   2164 	win = sbspace(&so->so_rcv);
   2165 	if (win < 0)
   2166 		win = 0;
   2167 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
   2168 	}
   2169 
   2170 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
   2171 	tp->rfbuf_ts = 0;
   2172 	tp->rfbuf_cnt = 0;
   2173 
   2174 	switch (tp->t_state) {
   2175 	/*
   2176 	 * If the state is SYN_SENT:
   2177 	 *	if seg contains an ACK, but not for our SYN, drop the input.
   2178 	 *	if seg contains a RST, then drop the connection.
   2179 	 *	if seg does not contain SYN, then drop it.
   2180 	 * Otherwise this is an acceptable SYN segment
   2181 	 *	initialize tp->rcv_nxt and tp->irs
   2182 	 *	if seg contains ack then advance tp->snd_una
   2183 	 *	if seg contains a ECE and ECN support is enabled, the stream
   2184 	 *	    is ECN capable.
   2185 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
   2186 	 *	arrange for segment to be acked (eventually)
   2187 	 *	continue processing rest of data/controls, beginning with URG
   2188 	 */
   2189 	case TCPS_SYN_SENT:
   2190 		if ((tiflags & TH_ACK) &&
   2191 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
   2192 		     SEQ_GT(th->th_ack, tp->snd_max)))
   2193 			goto dropwithreset;
   2194 		if (tiflags & TH_RST) {
   2195 			if (tiflags & TH_ACK)
   2196 				tp = tcp_drop(tp, ECONNREFUSED);
   2197 			goto drop;
   2198 		}
   2199 		if ((tiflags & TH_SYN) == 0)
   2200 			goto drop;
   2201 		if (tiflags & TH_ACK) {
   2202 			tp->snd_una = th->th_ack;
   2203 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
   2204 				tp->snd_nxt = tp->snd_una;
   2205 			if (SEQ_LT(tp->snd_high, tp->snd_una))
   2206 				tp->snd_high = tp->snd_una;
   2207 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
   2208 
   2209 			if ((tiflags & TH_ECE) && tcp_do_ecn) {
   2210 				tp->t_flags |= TF_ECN_PERMIT;
   2211 				TCP_STATINC(TCP_STAT_ECN_SHS);
   2212 			}
   2213 
   2214 		}
   2215 		tp->irs = th->th_seq;
   2216 		tcp_rcvseqinit(tp);
   2217 		tp->t_flags |= TF_ACKNOW;
   2218 		tcp_mss_from_peer(tp, opti.maxseg);
   2219 
   2220 		/*
   2221 		 * Initialize the initial congestion window.  If we
   2222 		 * had to retransmit the SYN, we must initialize cwnd
   2223 		 * to 1 segment (i.e. the Loss Window).
   2224 		 */
   2225 		if (tp->t_flags & TF_SYN_REXMT)
   2226 			tp->snd_cwnd = tp->t_peermss;
   2227 		else {
   2228 			int ss = tcp_init_win;
   2229 #ifdef INET
   2230 			if (inp != NULL && in_localaddr(inp->inp_faddr))
   2231 				ss = tcp_init_win_local;
   2232 #endif
   2233 #ifdef INET6
   2234 			if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
   2235 				ss = tcp_init_win_local;
   2236 #endif
   2237 			tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
   2238 		}
   2239 
   2240 		tcp_rmx_rtt(tp);
   2241 		if (tiflags & TH_ACK) {
   2242 			TCP_STATINC(TCP_STAT_CONNECTS);
   2243 			/*
   2244 			 * move tcp_established before soisconnected
   2245 			 * because upcall handler can drive tcp_output
   2246 			 * functionality.
   2247 			 * XXX we might call soisconnected at the end of
   2248 			 * all processing
   2249 			 */
   2250 			tcp_established(tp);
   2251 			soisconnected(so);
   2252 			/* Do window scaling on this connection? */
   2253 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   2254 			    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   2255 				tp->snd_scale = tp->requested_s_scale;
   2256 				tp->rcv_scale = tp->request_r_scale;
   2257 			}
   2258 			TCP_REASS_LOCK(tp);
   2259 			(void) tcp_reass(tp, NULL, NULL, &tlen);
   2260 			/*
   2261 			 * if we didn't have to retransmit the SYN,
   2262 			 * use its rtt as our initial srtt & rtt var.
   2263 			 */
   2264 			if (tp->t_rtttime)
   2265 				tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
   2266 		} else
   2267 			tp->t_state = TCPS_SYN_RECEIVED;
   2268 
   2269 		/*
   2270 		 * Advance th->th_seq to correspond to first data byte.
   2271 		 * If data, trim to stay within window,
   2272 		 * dropping FIN if necessary.
   2273 		 */
   2274 		th->th_seq++;
   2275 		if (tlen > tp->rcv_wnd) {
   2276 			todrop = tlen - tp->rcv_wnd;
   2277 			m_adj(m, -todrop);
   2278 			tlen = tp->rcv_wnd;
   2279 			tiflags &= ~TH_FIN;
   2280 			tcps = TCP_STAT_GETREF();
   2281 			tcps[TCP_STAT_RCVPACKAFTERWIN]++;
   2282 			tcps[TCP_STAT_RCVBYTEAFTERWIN] += todrop;
   2283 			TCP_STAT_PUTREF();
   2284 		}
   2285 		tp->snd_wl1 = th->th_seq - 1;
   2286 		tp->rcv_up = th->th_seq;
   2287 		goto step6;
   2288 
   2289 	/*
   2290 	 * If the state is SYN_RECEIVED:
   2291 	 *	If seg contains an ACK, but not for our SYN, drop the input
   2292 	 *	and generate an RST.  See page 36, rfc793
   2293 	 */
   2294 	case TCPS_SYN_RECEIVED:
   2295 		if ((tiflags & TH_ACK) &&
   2296 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
   2297 		     SEQ_GT(th->th_ack, tp->snd_max)))
   2298 			goto dropwithreset;
   2299 		break;
   2300 	}
   2301 
   2302 	/*
   2303 	 * States other than LISTEN or SYN_SENT.
   2304 	 * First check timestamp, if present.
   2305 	 * Then check that at least some bytes of segment are within
   2306 	 * receive window.  If segment begins before rcv_nxt,
   2307 	 * drop leading data (and SYN); if nothing left, just ack.
   2308 	 *
   2309 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
   2310 	 * and it's less than ts_recent, drop it.
   2311 	 */
   2312 	if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
   2313 	    TSTMP_LT(opti.ts_val, tp->ts_recent)) {
   2314 
   2315 		/* Check to see if ts_recent is over 24 days old.  */
   2316 		if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) {
   2317 			/*
   2318 			 * Invalidate ts_recent.  If this segment updates
   2319 			 * ts_recent, the age will be reset later and ts_recent
   2320 			 * will get a valid value.  If it does not, setting
   2321 			 * ts_recent to zero will at least satisfy the
   2322 			 * requirement that zero be placed in the timestamp
   2323 			 * echo reply when ts_recent isn't valid.  The
   2324 			 * age isn't reset until we get a valid ts_recent
   2325 			 * because we don't want out-of-order segments to be
   2326 			 * dropped when ts_recent is old.
   2327 			 */
   2328 			tp->ts_recent = 0;
   2329 		} else {
   2330 			tcps = TCP_STAT_GETREF();
   2331 			tcps[TCP_STAT_RCVDUPPACK]++;
   2332 			tcps[TCP_STAT_RCVDUPBYTE] += tlen;
   2333 			tcps[TCP_STAT_PAWSDROP]++;
   2334 			TCP_STAT_PUTREF();
   2335 			tcp_new_dsack(tp, th->th_seq, tlen);
   2336 			goto dropafterack;
   2337 		}
   2338 	}
   2339 
   2340 	todrop = tp->rcv_nxt - th->th_seq;
   2341 	dupseg = false;
   2342 	if (todrop > 0) {
   2343 		if (tiflags & TH_SYN) {
   2344 			tiflags &= ~TH_SYN;
   2345 			th->th_seq++;
   2346 			if (th->th_urp > 1)
   2347 				th->th_urp--;
   2348 			else {
   2349 				tiflags &= ~TH_URG;
   2350 				th->th_urp = 0;
   2351 			}
   2352 			todrop--;
   2353 		}
   2354 		if (todrop > tlen ||
   2355 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
   2356 			/*
   2357 			 * Any valid FIN or RST must be to the left of the
   2358 			 * window.  At this point the FIN or RST must be a
   2359 			 * duplicate or out of sequence; drop it.
   2360 			 */
   2361 			if (tiflags & TH_RST)
   2362 				goto drop;
   2363 			tiflags &= ~(TH_FIN|TH_RST);
   2364 			/*
   2365 			 * Send an ACK to resynchronize and drop any data.
   2366 			 * But keep on processing for RST or ACK.
   2367 			 */
   2368 			tp->t_flags |= TF_ACKNOW;
   2369 			todrop = tlen;
   2370 			dupseg = true;
   2371 			tcps = TCP_STAT_GETREF();
   2372 			tcps[TCP_STAT_RCVDUPPACK]++;
   2373 			tcps[TCP_STAT_RCVDUPBYTE] += todrop;
   2374 			TCP_STAT_PUTREF();
   2375 		} else if ((tiflags & TH_RST) &&
   2376 			   th->th_seq != tp->rcv_nxt) {
   2377 			/*
   2378 			 * Test for reset before adjusting the sequence
   2379 			 * number for overlapping data.
   2380 			 */
   2381 			goto dropafterack_ratelim;
   2382 		} else {
   2383 			tcps = TCP_STAT_GETREF();
   2384 			tcps[TCP_STAT_RCVPARTDUPPACK]++;
   2385 			tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
   2386 			TCP_STAT_PUTREF();
   2387 		}
   2388 		tcp_new_dsack(tp, th->th_seq, todrop);
   2389 		hdroptlen += todrop;	/*drop from head afterwards*/
   2390 		th->th_seq += todrop;
   2391 		tlen -= todrop;
   2392 		if (th->th_urp > todrop)
   2393 			th->th_urp -= todrop;
   2394 		else {
   2395 			tiflags &= ~TH_URG;
   2396 			th->th_urp = 0;
   2397 		}
   2398 	}
   2399 
   2400 	/*
   2401 	 * If new data are received on a connection after the
   2402 	 * user processes are gone, then RST the other end.
   2403 	 */
   2404 	if ((so->so_state & SS_NOFDREF) &&
   2405 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
   2406 		tp = tcp_close(tp);
   2407 		TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
   2408 		goto dropwithreset;
   2409 	}
   2410 
   2411 	/*
   2412 	 * If segment ends after window, drop trailing data
   2413 	 * (and PUSH and FIN); if nothing left, just ACK.
   2414 	 */
   2415 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
   2416 	if (todrop > 0) {
   2417 		TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
   2418 		if (todrop >= tlen) {
   2419 			/*
   2420 			 * The segment actually starts after the window.
   2421 			 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen
   2422 			 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0
   2423 			 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd
   2424 			 */
   2425 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
   2426 			/*
   2427 			 * If a new connection request is received
   2428 			 * while in TIME_WAIT, drop the old connection
   2429 			 * and start over if the sequence numbers
   2430 			 * are above the previous ones.
   2431 			 *
   2432 			 * NOTE: We will checksum the packet again, and
   2433 			 * so we need to put the header fields back into
   2434 			 * network order!
   2435 			 * XXX This kind of sucks, but we don't expect
   2436 			 * XXX this to happen very often, so maybe it
   2437 			 * XXX doesn't matter so much.
   2438 			 */
   2439 			if (tiflags & TH_SYN &&
   2440 			    tp->t_state == TCPS_TIME_WAIT &&
   2441 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
   2442 				tp = tcp_close(tp);
   2443 				tcp_fields_to_net(th);
   2444 				goto findpcb;
   2445 			}
   2446 			/*
   2447 			 * If window is closed can only take segments at
   2448 			 * window edge, and have to drop data and PUSH from
   2449 			 * incoming segments.  Continue processing, but
   2450 			 * remember to ack.  Otherwise, drop segment
   2451 			 * and (if not RST) ack.
   2452 			 */
   2453 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
   2454 				tp->t_flags |= TF_ACKNOW;
   2455 				TCP_STATINC(TCP_STAT_RCVWINPROBE);
   2456 			} else
   2457 				goto dropafterack;
   2458 		} else
   2459 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
   2460 		m_adj(m, -todrop);
   2461 		tlen -= todrop;
   2462 		tiflags &= ~(TH_PUSH|TH_FIN);
   2463 	}
   2464 
   2465 	/*
   2466 	 * If last ACK falls within this segment's sequence numbers,
   2467 	 *  record the timestamp.
   2468 	 * NOTE:
   2469 	 * 1) That the test incorporates suggestions from the latest
   2470 	 *    proposal of the tcplw (at) cray.com list (Braden 1993/04/26).
   2471 	 * 2) That updating only on newer timestamps interferes with
   2472 	 *    our earlier PAWS tests, so this check should be solely
   2473 	 *    predicated on the sequence space of this segment.
   2474 	 * 3) That we modify the segment boundary check to be
   2475 	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
   2476 	 *    instead of RFC1323's
   2477 	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
   2478 	 *    This modified check allows us to overcome RFC1323's
   2479 	 *    limitations as described in Stevens TCP/IP Illustrated
   2480 	 *    Vol. 2 p.869. In such cases, we can still calculate the
   2481 	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
   2482 	 */
   2483 	if (opti.ts_present &&
   2484 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
   2485 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
   2486 		    ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
   2487 		tp->ts_recent_age = tcp_now;
   2488 		tp->ts_recent = opti.ts_val;
   2489 	}
   2490 
   2491 	/*
   2492 	 * If the RST bit is set examine the state:
   2493 	 *    SYN_RECEIVED STATE:
   2494 	 *	If passive open, return to LISTEN state.
   2495 	 *	If active open, inform user that connection was refused.
   2496 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
   2497 	 *	Inform user that connection was reset, and close tcb.
   2498 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
   2499 	 *	Close the tcb.
   2500 	 */
   2501 	if (tiflags & TH_RST) {
   2502 		if (th->th_seq != tp->rcv_nxt)
   2503 			goto dropafterack_ratelim;
   2504 
   2505 		switch (tp->t_state) {
   2506 		case TCPS_SYN_RECEIVED:
   2507 			so->so_error = ECONNREFUSED;
   2508 			goto close;
   2509 
   2510 		case TCPS_ESTABLISHED:
   2511 		case TCPS_FIN_WAIT_1:
   2512 		case TCPS_FIN_WAIT_2:
   2513 		case TCPS_CLOSE_WAIT:
   2514 			so->so_error = ECONNRESET;
   2515 		close:
   2516 			tp->t_state = TCPS_CLOSED;
   2517 			TCP_STATINC(TCP_STAT_DROPS);
   2518 			tp = tcp_close(tp);
   2519 			goto drop;
   2520 
   2521 		case TCPS_CLOSING:
   2522 		case TCPS_LAST_ACK:
   2523 		case TCPS_TIME_WAIT:
   2524 			tp = tcp_close(tp);
   2525 			goto drop;
   2526 		}
   2527 	}
   2528 
   2529 	/*
   2530 	 * Since we've covered the SYN-SENT and SYN-RECEIVED states above
   2531 	 * we must be in a synchronized state.  RFC791 states (under RST
   2532 	 * generation) that any unacceptable segment (an out-of-order SYN
   2533 	 * qualifies) received in a synchronized state must elicit only an
   2534 	 * empty acknowledgment segment ... and the connection remains in
   2535 	 * the same state.
   2536 	 */
   2537 	if (tiflags & TH_SYN) {
   2538 		if (tp->rcv_nxt == th->th_seq) {
   2539 			tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1,
   2540 			    TH_ACK);
   2541 			if (tcp_saveti)
   2542 				m_freem(tcp_saveti);
   2543 			return;
   2544 		}
   2545 
   2546 		goto dropafterack_ratelim;
   2547 	}
   2548 
   2549 	/*
   2550 	 * If the ACK bit is off we drop the segment and return.
   2551 	 */
   2552 	if ((tiflags & TH_ACK) == 0) {
   2553 		if (tp->t_flags & TF_ACKNOW)
   2554 			goto dropafterack;
   2555 		else
   2556 			goto drop;
   2557 	}
   2558 
   2559 	/*
   2560 	 * Ack processing.
   2561 	 */
   2562 	switch (tp->t_state) {
   2563 
   2564 	/*
   2565 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
   2566 	 * ESTABLISHED state and continue processing, otherwise
   2567 	 * send an RST.
   2568 	 */
   2569 	case TCPS_SYN_RECEIVED:
   2570 		if (SEQ_GT(tp->snd_una, th->th_ack) ||
   2571 		    SEQ_GT(th->th_ack, tp->snd_max))
   2572 			goto dropwithreset;
   2573 		TCP_STATINC(TCP_STAT_CONNECTS);
   2574 		soisconnected(so);
   2575 		tcp_established(tp);
   2576 		/* Do window scaling? */
   2577 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   2578 		    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   2579 			tp->snd_scale = tp->requested_s_scale;
   2580 			tp->rcv_scale = tp->request_r_scale;
   2581 		}
   2582 		TCP_REASS_LOCK(tp);
   2583 		(void) tcp_reass(tp, NULL, NULL, &tlen);
   2584 		tp->snd_wl1 = th->th_seq - 1;
   2585 		/* fall into ... */
   2586 
   2587 	/*
   2588 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
   2589 	 * ACKs.  If the ack is in the range
   2590 	 *	tp->snd_una < th->th_ack <= tp->snd_max
   2591 	 * then advance tp->snd_una to th->th_ack and drop
   2592 	 * data from the retransmission queue.  If this ACK reflects
   2593 	 * more up to date window information we update our window information.
   2594 	 */
   2595 	case TCPS_ESTABLISHED:
   2596 	case TCPS_FIN_WAIT_1:
   2597 	case TCPS_FIN_WAIT_2:
   2598 	case TCPS_CLOSE_WAIT:
   2599 	case TCPS_CLOSING:
   2600 	case TCPS_LAST_ACK:
   2601 	case TCPS_TIME_WAIT:
   2602 
   2603 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
   2604 			if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) {
   2605 				TCP_STATINC(TCP_STAT_RCVDUPACK);
   2606 				/*
   2607 				 * If we have outstanding data (other than
   2608 				 * a window probe), this is a completely
   2609 				 * duplicate ack (ie, window info didn't
   2610 				 * change), the ack is the biggest we've
   2611 				 * seen and we've seen exactly our rexmt
   2612 				 * threshhold of them, assume a packet
   2613 				 * has been dropped and retransmit it.
   2614 				 * Kludge snd_nxt & the congestion
   2615 				 * window so we send only this one
   2616 				 * packet.
   2617 				 */
   2618 				if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
   2619 				    th->th_ack != tp->snd_una)
   2620 					tp->t_dupacks = 0;
   2621 				else if (tp->t_partialacks < 0 &&
   2622 					 (++tp->t_dupacks == tcprexmtthresh ||
   2623 					 TCP_FACK_FASTRECOV(tp))) {
   2624 					/*
   2625 					 * Do the fast retransmit, and adjust
   2626 					 * congestion control paramenters.
   2627 					 */
   2628 					if (tp->t_congctl->fast_retransmit(tp, th)) {
   2629 						/* False fast retransmit */
   2630 						break;
   2631 					} else
   2632 						goto drop;
   2633 				} else if (tp->t_dupacks > tcprexmtthresh) {
   2634 					tp->snd_cwnd += tp->t_segsz;
   2635 					KERNEL_LOCK(1, NULL);
   2636 					(void) tcp_output(tp);
   2637 					KERNEL_UNLOCK_ONE(NULL);
   2638 					goto drop;
   2639 				}
   2640 			} else {
   2641 				/*
   2642 				 * If the ack appears to be very old, only
   2643 				 * allow data that is in-sequence.  This
   2644 				 * makes it somewhat more difficult to insert
   2645 				 * forged data by guessing sequence numbers.
   2646 				 * Sent an ack to try to update the send
   2647 				 * sequence number on the other side.
   2648 				 */
   2649 				if (tlen && th->th_seq != tp->rcv_nxt &&
   2650 				    SEQ_LT(th->th_ack,
   2651 				    tp->snd_una - tp->max_sndwnd))
   2652 					goto dropafterack;
   2653 			}
   2654 			break;
   2655 		}
   2656 		/*
   2657 		 * If the congestion window was inflated to account
   2658 		 * for the other side's cached packets, retract it.
   2659 		 */
   2660 		/* XXX: make SACK have his own congestion control
   2661 		 * struct -- rpaulo */
   2662 		if (TCP_SACK_ENABLED(tp))
   2663 			tcp_sack_newack(tp, th);
   2664 		else
   2665 			tp->t_congctl->fast_retransmit_newack(tp, th);
   2666 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
   2667 			TCP_STATINC(TCP_STAT_RCVACKTOOMUCH);
   2668 			goto dropafterack;
   2669 		}
   2670 		acked = th->th_ack - tp->snd_una;
   2671 		tcps = TCP_STAT_GETREF();
   2672 		tcps[TCP_STAT_RCVACKPACK]++;
   2673 		tcps[TCP_STAT_RCVACKBYTE] += acked;
   2674 		TCP_STAT_PUTREF();
   2675 
   2676 		/*
   2677 		 * If we have a timestamp reply, update smoothed
   2678 		 * round trip time.  If no timestamp is present but
   2679 		 * transmit timer is running and timed sequence
   2680 		 * number was acked, update smoothed round trip time.
   2681 		 * Since we now have an rtt measurement, cancel the
   2682 		 * timer backoff (cf., Phil Karn's retransmit alg.).
   2683 		 * Recompute the initial retransmit timer.
   2684 		 */
   2685 		if (ts_rtt)
   2686 			tcp_xmit_timer(tp, ts_rtt - 1);
   2687 		else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
   2688 			tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
   2689 
   2690 		/*
   2691 		 * If all outstanding data is acked, stop retransmit
   2692 		 * timer and remember to restart (more output or persist).
   2693 		 * If there is more data to be acked, restart retransmit
   2694 		 * timer, using current (possibly backed-off) value.
   2695 		 */
   2696 		if (th->th_ack == tp->snd_max) {
   2697 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
   2698 			needoutput = 1;
   2699 		} else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
   2700 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   2701 
   2702 		/*
   2703 		 * New data has been acked, adjust the congestion window.
   2704 		 */
   2705 		tp->t_congctl->newack(tp, th);
   2706 
   2707 		nd6_hint(tp);
   2708 		if (acked > so->so_snd.sb_cc) {
   2709 			tp->snd_wnd -= so->so_snd.sb_cc;
   2710 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
   2711 			ourfinisacked = 1;
   2712 		} else {
   2713 			if (acked > (tp->t_lastoff - tp->t_inoff))
   2714 				tp->t_lastm = NULL;
   2715 			sbdrop(&so->so_snd, acked);
   2716 			tp->t_lastoff -= acked;
   2717 			tp->snd_wnd -= acked;
   2718 			ourfinisacked = 0;
   2719 		}
   2720 		sowwakeup(so);
   2721 
   2722 		icmp_check(tp, th, acked);
   2723 
   2724 		tp->snd_una = th->th_ack;
   2725 		if (SEQ_GT(tp->snd_una, tp->snd_fack))
   2726 			tp->snd_fack = tp->snd_una;
   2727 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
   2728 			tp->snd_nxt = tp->snd_una;
   2729 		if (SEQ_LT(tp->snd_high, tp->snd_una))
   2730 			tp->snd_high = tp->snd_una;
   2731 
   2732 		switch (tp->t_state) {
   2733 
   2734 		/*
   2735 		 * In FIN_WAIT_1 STATE in addition to the processing
   2736 		 * for the ESTABLISHED state if our FIN is now acknowledged
   2737 		 * then enter FIN_WAIT_2.
   2738 		 */
   2739 		case TCPS_FIN_WAIT_1:
   2740 			if (ourfinisacked) {
   2741 				/*
   2742 				 * If we can't receive any more
   2743 				 * data, then closing user can proceed.
   2744 				 * Starting the timer is contrary to the
   2745 				 * specification, but if we don't get a FIN
   2746 				 * we'll hang forever.
   2747 				 */
   2748 				if (so->so_state & SS_CANTRCVMORE) {
   2749 					soisdisconnected(so);
   2750 					if (tp->t_maxidle > 0)
   2751 						TCP_TIMER_ARM(tp, TCPT_2MSL,
   2752 						    tp->t_maxidle);
   2753 				}
   2754 				tp->t_state = TCPS_FIN_WAIT_2;
   2755 			}
   2756 			break;
   2757 
   2758 	 	/*
   2759 		 * In CLOSING STATE in addition to the processing for
   2760 		 * the ESTABLISHED state if the ACK acknowledges our FIN
   2761 		 * then enter the TIME-WAIT state, otherwise ignore
   2762 		 * the segment.
   2763 		 */
   2764 		case TCPS_CLOSING:
   2765 			if (ourfinisacked) {
   2766 				tp->t_state = TCPS_TIME_WAIT;
   2767 				tcp_canceltimers(tp);
   2768 				TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
   2769 				soisdisconnected(so);
   2770 			}
   2771 			break;
   2772 
   2773 		/*
   2774 		 * In LAST_ACK, we may still be waiting for data to drain
   2775 		 * and/or to be acked, as well as for the ack of our FIN.
   2776 		 * If our FIN is now acknowledged, delete the TCB,
   2777 		 * enter the closed state and return.
   2778 		 */
   2779 		case TCPS_LAST_ACK:
   2780 			if (ourfinisacked) {
   2781 				tp = tcp_close(tp);
   2782 				goto drop;
   2783 			}
   2784 			break;
   2785 
   2786 		/*
   2787 		 * In TIME_WAIT state the only thing that should arrive
   2788 		 * is a retransmission of the remote FIN.  Acknowledge
   2789 		 * it and restart the finack timer.
   2790 		 */
   2791 		case TCPS_TIME_WAIT:
   2792 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
   2793 			goto dropafterack;
   2794 		}
   2795 	}
   2796 
   2797 step6:
   2798 	/*
   2799 	 * Update window information.
   2800 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
   2801 	 */
   2802 	if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
   2803 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
   2804 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
   2805 		/* keep track of pure window updates */
   2806 		if (tlen == 0 &&
   2807 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
   2808 			TCP_STATINC(TCP_STAT_RCVWINUPD);
   2809 		tp->snd_wnd = tiwin;
   2810 		tp->snd_wl1 = th->th_seq;
   2811 		tp->snd_wl2 = th->th_ack;
   2812 		if (tp->snd_wnd > tp->max_sndwnd)
   2813 			tp->max_sndwnd = tp->snd_wnd;
   2814 		needoutput = 1;
   2815 	}
   2816 
   2817 	/*
   2818 	 * Process segments with URG.
   2819 	 */
   2820 	if ((tiflags & TH_URG) && th->th_urp &&
   2821 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   2822 		/*
   2823 		 * This is a kludge, but if we receive and accept
   2824 		 * random urgent pointers, we'll crash in
   2825 		 * soreceive.  It's hard to imagine someone
   2826 		 * actually wanting to send this much urgent data.
   2827 		 */
   2828 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
   2829 			th->th_urp = 0;			/* XXX */
   2830 			tiflags &= ~TH_URG;		/* XXX */
   2831 			goto dodata;			/* XXX */
   2832 		}
   2833 		/*
   2834 		 * If this segment advances the known urgent pointer,
   2835 		 * then mark the data stream.  This should not happen
   2836 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
   2837 		 * a FIN has been received from the remote side.
   2838 		 * In these states we ignore the URG.
   2839 		 *
   2840 		 * According to RFC961 (Assigned Protocols),
   2841 		 * the urgent pointer points to the last octet
   2842 		 * of urgent data.  We continue, however,
   2843 		 * to consider it to indicate the first octet
   2844 		 * of data past the urgent section as the original
   2845 		 * spec states (in one of two places).
   2846 		 */
   2847 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
   2848 			tp->rcv_up = th->th_seq + th->th_urp;
   2849 			so->so_oobmark = so->so_rcv.sb_cc +
   2850 			    (tp->rcv_up - tp->rcv_nxt) - 1;
   2851 			if (so->so_oobmark == 0)
   2852 				so->so_state |= SS_RCVATMARK;
   2853 			sohasoutofband(so);
   2854 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
   2855 		}
   2856 		/*
   2857 		 * Remove out of band data so doesn't get presented to user.
   2858 		 * This can happen independent of advancing the URG pointer,
   2859 		 * but if two URG's are pending at once, some out-of-band
   2860 		 * data may creep in... ick.
   2861 		 */
   2862 		if (th->th_urp <= (u_int16_t) tlen
   2863 #ifdef SO_OOBINLINE
   2864 		     && (so->so_options & SO_OOBINLINE) == 0
   2865 #endif
   2866 		     )
   2867 			tcp_pulloutofband(so, th, m, hdroptlen);
   2868 	} else
   2869 		/*
   2870 		 * If no out of band data is expected,
   2871 		 * pull receive urgent pointer along
   2872 		 * with the receive window.
   2873 		 */
   2874 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
   2875 			tp->rcv_up = tp->rcv_nxt;
   2876 dodata:							/* XXX */
   2877 
   2878 	/*
   2879 	 * Process the segment text, merging it into the TCP sequencing queue,
   2880 	 * and arranging for acknowledgement of receipt if necessary.
   2881 	 * This process logically involves adjusting tp->rcv_wnd as data
   2882 	 * is presented to the user (this happens in tcp_usrreq.c,
   2883 	 * case PRU_RCVD).  If a FIN has already been received on this
   2884 	 * connection then we just ignore the text.
   2885 	 */
   2886 	if ((tlen || (tiflags & TH_FIN)) &&
   2887 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   2888 		/*
   2889 		 * Insert segment ti into reassembly queue of tcp with
   2890 		 * control block tp.  Return TH_FIN if reassembly now includes
   2891 		 * a segment with FIN.  The macro form does the common case
   2892 		 * inline (segment is the next to be received on an
   2893 		 * established connection, and the queue is empty),
   2894 		 * avoiding linkage into and removal from the queue and
   2895 		 * repetition of various conversions.
   2896 		 * Set DELACK for segments received in order, but ack
   2897 		 * immediately when segments are out of order
   2898 		 * (so fast retransmit can work).
   2899 		 */
   2900 		/* NOTE: this was TCP_REASS() macro, but used only once */
   2901 		TCP_REASS_LOCK(tp);
   2902 		if (th->th_seq == tp->rcv_nxt &&
   2903 		    TAILQ_FIRST(&tp->segq) == NULL &&
   2904 		    tp->t_state == TCPS_ESTABLISHED) {
   2905 			tcp_setup_ack(tp, th);
   2906 			tp->rcv_nxt += tlen;
   2907 			tiflags = th->th_flags & TH_FIN;
   2908 			tcps = TCP_STAT_GETREF();
   2909 			tcps[TCP_STAT_RCVPACK]++;
   2910 			tcps[TCP_STAT_RCVBYTE] += tlen;
   2911 			TCP_STAT_PUTREF();
   2912 			nd6_hint(tp);
   2913 			if (so->so_state & SS_CANTRCVMORE)
   2914 				m_freem(m);
   2915 			else {
   2916 				m_adj(m, hdroptlen);
   2917 				sbappendstream(&(so)->so_rcv, m);
   2918 			}
   2919 			TCP_REASS_UNLOCK(tp);
   2920 			sorwakeup(so);
   2921 		} else {
   2922 			m_adj(m, hdroptlen);
   2923 			tiflags = tcp_reass(tp, th, m, &tlen);
   2924 			tp->t_flags |= TF_ACKNOW;
   2925 		}
   2926 
   2927 		/*
   2928 		 * Note the amount of data that peer has sent into
   2929 		 * our window, in order to estimate the sender's
   2930 		 * buffer size.
   2931 		 */
   2932 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
   2933 	} else {
   2934 		m_freem(m);
   2935 		m = NULL;
   2936 		tiflags &= ~TH_FIN;
   2937 	}
   2938 
   2939 	/*
   2940 	 * If FIN is received ACK the FIN and let the user know
   2941 	 * that the connection is closing.  Ignore a FIN received before
   2942 	 * the connection is fully established.
   2943 	 */
   2944 	if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
   2945 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   2946 			socantrcvmore(so);
   2947 			tp->t_flags |= TF_ACKNOW;
   2948 			tp->rcv_nxt++;
   2949 		}
   2950 		switch (tp->t_state) {
   2951 
   2952 	 	/*
   2953 		 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
   2954 		 */
   2955 		case TCPS_ESTABLISHED:
   2956 			tp->t_state = TCPS_CLOSE_WAIT;
   2957 			break;
   2958 
   2959 	 	/*
   2960 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
   2961 		 * enter the CLOSING state.
   2962 		 */
   2963 		case TCPS_FIN_WAIT_1:
   2964 			tp->t_state = TCPS_CLOSING;
   2965 			break;
   2966 
   2967 	 	/*
   2968 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
   2969 		 * starting the time-wait timer, turning off the other
   2970 		 * standard timers.
   2971 		 */
   2972 		case TCPS_FIN_WAIT_2:
   2973 			tp->t_state = TCPS_TIME_WAIT;
   2974 			tcp_canceltimers(tp);
   2975 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
   2976 			soisdisconnected(so);
   2977 			break;
   2978 
   2979 		/*
   2980 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
   2981 		 */
   2982 		case TCPS_TIME_WAIT:
   2983 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
   2984 			break;
   2985 		}
   2986 	}
   2987 #ifdef TCP_DEBUG
   2988 	if (so->so_options & SO_DEBUG)
   2989 		tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
   2990 #endif
   2991 
   2992 	/*
   2993 	 * Return any desired output.
   2994 	 */
   2995 	if (needoutput || (tp->t_flags & TF_ACKNOW)) {
   2996 		KERNEL_LOCK(1, NULL);
   2997 		(void) tcp_output(tp);
   2998 		KERNEL_UNLOCK_ONE(NULL);
   2999 	}
   3000 	if (tcp_saveti)
   3001 		m_freem(tcp_saveti);
   3002 
   3003 	if (tp->t_state == TCPS_TIME_WAIT
   3004 	    && (so->so_state & SS_NOFDREF)
   3005 	    && (tp->t_inpcb || af != AF_INET)
   3006 	    && (tp->t_in6pcb || af != AF_INET6)
   3007 	    && ((af == AF_INET ? tcp4_vtw_enable : tcp6_vtw_enable) & 1) != 0
   3008 	    && TAILQ_EMPTY(&tp->segq)
   3009 	    && vtw_add(af, tp)) {
   3010 		;
   3011 	}
   3012 	return;
   3013 
   3014 badsyn:
   3015 	/*
   3016 	 * Received a bad SYN.  Increment counters and dropwithreset.
   3017 	 */
   3018 	TCP_STATINC(TCP_STAT_BADSYN);
   3019 	tp = NULL;
   3020 	goto dropwithreset;
   3021 
   3022 dropafterack:
   3023 	/*
   3024 	 * Generate an ACK dropping incoming segment if it occupies
   3025 	 * sequence space, where the ACK reflects our state.
   3026 	 */
   3027 	if (tiflags & TH_RST)
   3028 		goto drop;
   3029 	goto dropafterack2;
   3030 
   3031 dropafterack_ratelim:
   3032 	/*
   3033 	 * We may want to rate-limit ACKs against SYN/RST attack.
   3034 	 */
   3035 	if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
   3036 	    tcp_ackdrop_ppslim) == 0) {
   3037 		/* XXX stat */
   3038 		goto drop;
   3039 	}
   3040 	/* ...fall into dropafterack2... */
   3041 
   3042 dropafterack2:
   3043 	m_freem(m);
   3044 	tp->t_flags |= TF_ACKNOW;
   3045 	KERNEL_LOCK(1, NULL);
   3046 	(void) tcp_output(tp);
   3047 	KERNEL_UNLOCK_ONE(NULL);
   3048 	if (tcp_saveti)
   3049 		m_freem(tcp_saveti);
   3050 	return;
   3051 
   3052 dropwithreset_ratelim:
   3053 	/*
   3054 	 * We may want to rate-limit RSTs in certain situations,
   3055 	 * particularly if we are sending an RST in response to
   3056 	 * an attempt to connect to or otherwise communicate with
   3057 	 * a port for which we have no socket.
   3058 	 */
   3059 	if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
   3060 	    tcp_rst_ppslim) == 0) {
   3061 		/* XXX stat */
   3062 		goto drop;
   3063 	}
   3064 	/* ...fall into dropwithreset... */
   3065 
   3066 dropwithreset:
   3067 	/*
   3068 	 * Generate a RST, dropping incoming segment.
   3069 	 * Make ACK acceptable to originator of segment.
   3070 	 */
   3071 	if (tiflags & TH_RST)
   3072 		goto drop;
   3073 
   3074 	switch (af) {
   3075 #ifdef INET6
   3076 	case AF_INET6:
   3077 		/* For following calls to tcp_respond */
   3078 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
   3079 			goto drop;
   3080 		break;
   3081 #endif /* INET6 */
   3082 	case AF_INET:
   3083 		if (IN_MULTICAST(ip->ip_dst.s_addr) ||
   3084 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
   3085 			goto drop;
   3086 	}
   3087 
   3088 	if (tiflags & TH_ACK)
   3089 		(void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
   3090 	else {
   3091 		if (tiflags & TH_SYN)
   3092 			tlen++;
   3093 		(void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
   3094 		    TH_RST|TH_ACK);
   3095 	}
   3096 	if (tcp_saveti)
   3097 		m_freem(tcp_saveti);
   3098 	return;
   3099 
   3100 badcsum:
   3101 drop:
   3102 	/*
   3103 	 * Drop space held by incoming segment and return.
   3104 	 */
   3105 	if (tp) {
   3106 		if (tp->t_inpcb)
   3107 			so = tp->t_inpcb->inp_socket;
   3108 #ifdef INET6
   3109 		else if (tp->t_in6pcb)
   3110 			so = tp->t_in6pcb->in6p_socket;
   3111 #endif
   3112 		else
   3113 			so = NULL;
   3114 #ifdef TCP_DEBUG
   3115 		if (so && (so->so_options & SO_DEBUG) != 0)
   3116 			tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
   3117 #endif
   3118 	}
   3119 	if (tcp_saveti)
   3120 		m_freem(tcp_saveti);
   3121 	m_freem(m);
   3122 	return;
   3123 }
   3124 
   3125 #ifdef TCP_SIGNATURE
   3126 int
   3127 tcp_signature_apply(void *fstate, void *data, u_int len)
   3128 {
   3129 
   3130 	MD5Update(fstate, (u_char *)data, len);
   3131 	return (0);
   3132 }
   3133 
   3134 struct secasvar *
   3135 tcp_signature_getsav(struct mbuf *m, struct tcphdr *th)
   3136 {
   3137 	struct secasvar *sav;
   3138 #ifdef IPSEC
   3139 	union sockaddr_union dst;
   3140 #endif
   3141 	struct ip *ip;
   3142 	struct ip6_hdr *ip6;
   3143 
   3144 	ip = mtod(m, struct ip *);
   3145 	switch (ip->ip_v) {
   3146 	case 4:
   3147 		ip = mtod(m, struct ip *);
   3148 		ip6 = NULL;
   3149 		break;
   3150 	case 6:
   3151 		ip = NULL;
   3152 		ip6 = mtod(m, struct ip6_hdr *);
   3153 		break;
   3154 	default:
   3155 		return (NULL);
   3156 	}
   3157 
   3158 #ifdef IPSEC
   3159 	/* Extract the destination from the IP header in the mbuf. */
   3160 	memset(&dst, 0, sizeof(union sockaddr_union));
   3161 	if (ip !=NULL) {
   3162 		dst.sa.sa_len = sizeof(struct sockaddr_in);
   3163 		dst.sa.sa_family = AF_INET;
   3164 		dst.sin.sin_addr = ip->ip_dst;
   3165 	} else {
   3166 		dst.sa.sa_len = sizeof(struct sockaddr_in6);
   3167 		dst.sa.sa_family = AF_INET6;
   3168 		dst.sin6.sin6_addr = ip6->ip6_dst;
   3169 	}
   3170 
   3171 	/*
   3172 	 * Look up an SADB entry which matches the address of the peer.
   3173 	 */
   3174 	sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI), 0, 0);
   3175 #else
   3176 	if (ip)
   3177 		sav = key_allocsa(AF_INET, (void *)&ip->ip_src,
   3178 		    (void *)&ip->ip_dst, IPPROTO_TCP,
   3179 		    htonl(TCP_SIG_SPI), 0, 0);
   3180 	else
   3181 		sav = key_allocsa(AF_INET6, (void *)&ip6->ip6_src,
   3182 		    (void *)&ip6->ip6_dst, IPPROTO_TCP,
   3183 		    htonl(TCP_SIG_SPI), 0, 0);
   3184 #endif
   3185 
   3186 	return (sav);	/* freesav must be performed by caller */
   3187 }
   3188 
   3189 int
   3190 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
   3191     struct secasvar *sav, char *sig)
   3192 {
   3193 	MD5_CTX ctx;
   3194 	struct ip *ip;
   3195 	struct ipovly *ipovly;
   3196 	struct ip6_hdr *ip6;
   3197 	struct ippseudo ippseudo;
   3198 	struct ip6_hdr_pseudo ip6pseudo;
   3199 	struct tcphdr th0;
   3200 	int l, tcphdrlen;
   3201 
   3202 	if (sav == NULL)
   3203 		return (-1);
   3204 
   3205 	tcphdrlen = th->th_off * 4;
   3206 
   3207 	switch (mtod(m, struct ip *)->ip_v) {
   3208 	case 4:
   3209 		ip = mtod(m, struct ip *);
   3210 		ip6 = NULL;
   3211 		break;
   3212 	case 6:
   3213 		ip = NULL;
   3214 		ip6 = mtod(m, struct ip6_hdr *);
   3215 		break;
   3216 	default:
   3217 		return (-1);
   3218 	}
   3219 
   3220 	MD5Init(&ctx);
   3221 
   3222 	if (ip) {
   3223 		memset(&ippseudo, 0, sizeof(ippseudo));
   3224 		ipovly = (struct ipovly *)ip;
   3225 		ippseudo.ippseudo_src = ipovly->ih_src;
   3226 		ippseudo.ippseudo_dst = ipovly->ih_dst;
   3227 		ippseudo.ippseudo_pad = 0;
   3228 		ippseudo.ippseudo_p = IPPROTO_TCP;
   3229 		ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
   3230 		MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
   3231 	} else {
   3232 		memset(&ip6pseudo, 0, sizeof(ip6pseudo));
   3233 		ip6pseudo.ip6ph_src = ip6->ip6_src;
   3234 		in6_clearscope(&ip6pseudo.ip6ph_src);
   3235 		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
   3236 		in6_clearscope(&ip6pseudo.ip6ph_dst);
   3237 		ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
   3238 		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
   3239 		MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
   3240 	}
   3241 
   3242 	th0 = *th;
   3243 	th0.th_sum = 0;
   3244 	MD5Update(&ctx, (char *)&th0, sizeof(th0));
   3245 
   3246 	l = m->m_pkthdr.len - thoff - tcphdrlen;
   3247 	if (l > 0)
   3248 		m_apply(m, thoff + tcphdrlen,
   3249 		    m->m_pkthdr.len - thoff - tcphdrlen,
   3250 		    tcp_signature_apply, &ctx);
   3251 
   3252 	MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
   3253 	MD5Final(sig, &ctx);
   3254 
   3255 	return (0);
   3256 }
   3257 #endif
   3258 
   3259 /*
   3260  * tcp_dooptions: parse and process tcp options.
   3261  *
   3262  * returns -1 if this segment should be dropped.  (eg. wrong signature)
   3263  * otherwise returns 0.
   3264  */
   3265 
   3266 static int
   3267 tcp_dooptions(struct tcpcb *tp, const u_char *cp, int cnt,
   3268     struct tcphdr *th,
   3269     struct mbuf *m, int toff, struct tcp_opt_info *oi)
   3270 {
   3271 	u_int16_t mss;
   3272 	int opt, optlen = 0;
   3273 #ifdef TCP_SIGNATURE
   3274 	void *sigp = NULL;
   3275 	char sigbuf[TCP_SIGLEN];
   3276 	struct secasvar *sav = NULL;
   3277 #endif
   3278 
   3279 	for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
   3280 		opt = cp[0];
   3281 		if (opt == TCPOPT_EOL)
   3282 			break;
   3283 		if (opt == TCPOPT_NOP)
   3284 			optlen = 1;
   3285 		else {
   3286 			if (cnt < 2)
   3287 				break;
   3288 			optlen = cp[1];
   3289 			if (optlen < 2 || optlen > cnt)
   3290 				break;
   3291 		}
   3292 		switch (opt) {
   3293 
   3294 		default:
   3295 			continue;
   3296 
   3297 		case TCPOPT_MAXSEG:
   3298 			if (optlen != TCPOLEN_MAXSEG)
   3299 				continue;
   3300 			if (!(th->th_flags & TH_SYN))
   3301 				continue;
   3302 			if (TCPS_HAVERCVDSYN(tp->t_state))
   3303 				continue;
   3304 			bcopy(cp + 2, &mss, sizeof(mss));
   3305 			oi->maxseg = ntohs(mss);
   3306 			break;
   3307 
   3308 		case TCPOPT_WINDOW:
   3309 			if (optlen != TCPOLEN_WINDOW)
   3310 				continue;
   3311 			if (!(th->th_flags & TH_SYN))
   3312 				continue;
   3313 			if (TCPS_HAVERCVDSYN(tp->t_state))
   3314 				continue;
   3315 			tp->t_flags |= TF_RCVD_SCALE;
   3316 			tp->requested_s_scale = cp[2];
   3317 			if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
   3318 #if 0	/*XXX*/
   3319 				char *p;
   3320 
   3321 				if (ip)
   3322 					p = ntohl(ip->ip_src);
   3323 #ifdef INET6
   3324 				else if (ip6)
   3325 					p = ip6_sprintf(&ip6->ip6_src);
   3326 #endif
   3327 				else
   3328 					p = "(unknown)";
   3329 				log(LOG_ERR, "TCP: invalid wscale %d from %s, "
   3330 				    "assuming %d\n",
   3331 				    tp->requested_s_scale, p,
   3332 				    TCP_MAX_WINSHIFT);
   3333 #else
   3334 				log(LOG_ERR, "TCP: invalid wscale %d, "
   3335 				    "assuming %d\n",
   3336 				    tp->requested_s_scale,
   3337 				    TCP_MAX_WINSHIFT);
   3338 #endif
   3339 				tp->requested_s_scale = TCP_MAX_WINSHIFT;
   3340 			}
   3341 			break;
   3342 
   3343 		case TCPOPT_TIMESTAMP:
   3344 			if (optlen != TCPOLEN_TIMESTAMP)
   3345 				continue;
   3346 			oi->ts_present = 1;
   3347 			bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
   3348 			NTOHL(oi->ts_val);
   3349 			bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
   3350 			NTOHL(oi->ts_ecr);
   3351 
   3352 			if (!(th->th_flags & TH_SYN))
   3353 				continue;
   3354 			if (TCPS_HAVERCVDSYN(tp->t_state))
   3355 				continue;
   3356 			/*
   3357 			 * A timestamp received in a SYN makes
   3358 			 * it ok to send timestamp requests and replies.
   3359 			 */
   3360 			tp->t_flags |= TF_RCVD_TSTMP;
   3361 			tp->ts_recent = oi->ts_val;
   3362 			tp->ts_recent_age = tcp_now;
   3363                         break;
   3364 
   3365 		case TCPOPT_SACK_PERMITTED:
   3366 			if (optlen != TCPOLEN_SACK_PERMITTED)
   3367 				continue;
   3368 			if (!(th->th_flags & TH_SYN))
   3369 				continue;
   3370 			if (TCPS_HAVERCVDSYN(tp->t_state))
   3371 				continue;
   3372 			if (tcp_do_sack) {
   3373 				tp->t_flags |= TF_SACK_PERMIT;
   3374 				tp->t_flags |= TF_WILL_SACK;
   3375 			}
   3376 			break;
   3377 
   3378 		case TCPOPT_SACK:
   3379 			tcp_sack_option(tp, th, cp, optlen);
   3380 			break;
   3381 #ifdef TCP_SIGNATURE
   3382 		case TCPOPT_SIGNATURE:
   3383 			if (optlen != TCPOLEN_SIGNATURE)
   3384 				continue;
   3385 			if (sigp && memcmp(sigp, cp + 2, TCP_SIGLEN))
   3386 				return (-1);
   3387 
   3388 			sigp = sigbuf;
   3389 			memcpy(sigbuf, cp + 2, TCP_SIGLEN);
   3390 			tp->t_flags |= TF_SIGNATURE;
   3391 			break;
   3392 #endif
   3393 		}
   3394 	}
   3395 
   3396 #ifndef TCP_SIGNATURE
   3397 	return 0;
   3398 #else
   3399 	if (tp->t_flags & TF_SIGNATURE) {
   3400 
   3401 		sav = tcp_signature_getsav(m, th);
   3402 
   3403 		if (sav == NULL && tp->t_state == TCPS_LISTEN)
   3404 			return (-1);
   3405 	}
   3406 
   3407 	if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE))
   3408 		goto out;
   3409 
   3410 	if (sigp) {
   3411 		char sig[TCP_SIGLEN];
   3412 
   3413 		tcp_fields_to_net(th);
   3414 		if (tcp_signature(m, th, toff, sav, sig) < 0) {
   3415 			tcp_fields_to_host(th);
   3416 			goto out;
   3417 		}
   3418 		tcp_fields_to_host(th);
   3419 
   3420 		if (memcmp(sig, sigp, TCP_SIGLEN)) {
   3421 			TCP_STATINC(TCP_STAT_BADSIG);
   3422 			goto out;
   3423 		} else
   3424 			TCP_STATINC(TCP_STAT_GOODSIG);
   3425 
   3426 		key_sa_recordxfer(sav, m);
   3427 		KEY_FREESAV(&sav);
   3428 	}
   3429 	return 0;
   3430 out:
   3431 	if (sav != NULL)
   3432 		KEY_FREESAV(&sav);
   3433 	return -1;
   3434 #endif
   3435 }
   3436 
   3437 /*
   3438  * Pull out of band byte out of a segment so
   3439  * it doesn't appear in the user's data queue.
   3440  * It is still reflected in the segment length for
   3441  * sequencing purposes.
   3442  */
   3443 void
   3444 tcp_pulloutofband(struct socket *so, struct tcphdr *th,
   3445     struct mbuf *m, int off)
   3446 {
   3447 	int cnt = off + th->th_urp - 1;
   3448 
   3449 	while (cnt >= 0) {
   3450 		if (m->m_len > cnt) {
   3451 			char *cp = mtod(m, char *) + cnt;
   3452 			struct tcpcb *tp = sototcpcb(so);
   3453 
   3454 			tp->t_iobc = *cp;
   3455 			tp->t_oobflags |= TCPOOB_HAVEDATA;
   3456 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
   3457 			m->m_len--;
   3458 			return;
   3459 		}
   3460 		cnt -= m->m_len;
   3461 		m = m->m_next;
   3462 		if (m == 0)
   3463 			break;
   3464 	}
   3465 	panic("tcp_pulloutofband");
   3466 }
   3467 
   3468 /*
   3469  * Collect new round-trip time estimate
   3470  * and update averages and current timeout.
   3471  *
   3472  * rtt is in units of slow ticks (typically 500 ms) -- essentially the
   3473  * difference of two timestamps.
   3474  */
   3475 void
   3476 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt)
   3477 {
   3478 	int32_t delta;
   3479 
   3480 	TCP_STATINC(TCP_STAT_RTTUPDATED);
   3481 	if (tp->t_srtt != 0) {
   3482 		/*
   3483 		 * Compute the amount to add to srtt for smoothing,
   3484 		 * *alpha, or 2^(-TCP_RTT_SHIFT).  Because
   3485 		 * srtt is stored in 1/32 slow ticks, we conceptually
   3486 		 * shift left 5 bits, subtract srtt to get the
   3487 		 * diference, and then shift right by TCP_RTT_SHIFT
   3488 		 * (3) to obtain 1/8 of the difference.
   3489 		 */
   3490 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
   3491 		/*
   3492 		 * This can never happen, because delta's lowest
   3493 		 * possible value is 1/8 of t_srtt.  But if it does,
   3494 		 * set srtt to some reasonable value, here chosen
   3495 		 * as 1/8 tick.
   3496 		 */
   3497 		if ((tp->t_srtt += delta) <= 0)
   3498 			tp->t_srtt = 1 << 2;
   3499 		/*
   3500 		 * RFC2988 requires that rttvar be updated first.
   3501 		 * This code is compliant because "delta" is the old
   3502 		 * srtt minus the new observation (scaled).
   3503 		 *
   3504 		 * RFC2988 says:
   3505 		 *   rttvar = (1-beta) * rttvar + beta * |srtt-observed|
   3506 		 *
   3507 		 * delta is in units of 1/32 ticks, and has then been
   3508 		 * divided by 8.  This is equivalent to being in 1/16s
   3509 		 * units and divided by 4.  Subtract from it 1/4 of
   3510 		 * the existing rttvar to form the (signed) amount to
   3511 		 * adjust.
   3512 		 */
   3513 		if (delta < 0)
   3514 			delta = -delta;
   3515 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
   3516 		/*
   3517 		 * As with srtt, this should never happen.  There is
   3518 		 * no support in RFC2988 for this operation.  But 1/4s
   3519 		 * as rttvar when faced with something arguably wrong
   3520 		 * is ok.
   3521 		 */
   3522 		if ((tp->t_rttvar += delta) <= 0)
   3523 			tp->t_rttvar = 1 << 2;
   3524 
   3525 		/*
   3526 		 * If srtt exceeds .01 second, ensure we use the 'remote' MSL
   3527 		 * Problem is: it doesn't work.  Disabled by defaulting
   3528 		 * tcp_rttlocal to 0; see corresponding code in
   3529 		 * tcp_subr that selects local vs remote in a different way.
   3530 		 *
   3531 		 * The static branch prediction hint here should be removed
   3532 		 * when the rtt estimator is fixed and the rtt_enable code
   3533 		 * is turned back on.
   3534 		 */
   3535 		if (__predict_false(tcp_rttlocal) && tcp_msl_enable
   3536 		    && tp->t_srtt > tcp_msl_remote_threshold
   3537 		    && tp->t_msl  < tcp_msl_remote) {
   3538 			tp->t_msl = tcp_msl_remote;
   3539 		}
   3540 	} else {
   3541 		/*
   3542 		 * This is the first measurement.  Per RFC2988, 2.2,
   3543 		 * set rtt=R and srtt=R/2.
   3544 		 * For srtt, storage representation is 1/32 ticks,
   3545 		 * so shift left by 5.
   3546 		 * For rttvar, storage representation is 1/16 ticks,
   3547 		 * So shift left by 4, but then right by 1 to halve.
   3548 		 */
   3549 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
   3550 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
   3551 	}
   3552 	tp->t_rtttime = 0;
   3553 	tp->t_rxtshift = 0;
   3554 
   3555 	/*
   3556 	 * the retransmit should happen at rtt + 4 * rttvar.
   3557 	 * Because of the way we do the smoothing, srtt and rttvar
   3558 	 * will each average +1/2 tick of bias.  When we compute
   3559 	 * the retransmit timer, we want 1/2 tick of rounding and
   3560 	 * 1 extra tick because of +-1/2 tick uncertainty in the
   3561 	 * firing of the timer.  The bias will give us exactly the
   3562 	 * 1.5 tick we need.  But, because the bias is
   3563 	 * statistical, we have to test that we don't drop below
   3564 	 * the minimum feasible timer (which is 2 ticks).
   3565 	 */
   3566 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
   3567 	    max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
   3568 
   3569 	/*
   3570 	 * We received an ack for a packet that wasn't retransmitted;
   3571 	 * it is probably safe to discard any error indications we've
   3572 	 * received recently.  This isn't quite right, but close enough
   3573 	 * for now (a route might have failed after we sent a segment,
   3574 	 * and the return path might not be symmetrical).
   3575 	 */
   3576 	tp->t_softerror = 0;
   3577 }
   3578 
   3579 
   3580 /*
   3581  * TCP compressed state engine.  Currently used to hold compressed
   3582  * state for SYN_RECEIVED.
   3583  */
   3584 
   3585 u_long	syn_cache_count;
   3586 u_int32_t syn_hash1, syn_hash2;
   3587 
   3588 #define SYN_HASH(sa, sp, dp) \
   3589 	((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
   3590 				     ((u_int32_t)(sp)))^syn_hash2)))
   3591 #ifndef INET6
   3592 #define	SYN_HASHALL(hash, src, dst) \
   3593 do {									\
   3594 	hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr,	\
   3595 		((const struct sockaddr_in *)(src))->sin_port,		\
   3596 		((const struct sockaddr_in *)(dst))->sin_port);		\
   3597 } while (/*CONSTCOND*/ 0)
   3598 #else
   3599 #define SYN_HASH6(sa, sp, dp) \
   3600 	((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
   3601 	  (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
   3602 	 & 0x7fffffff)
   3603 
   3604 #define SYN_HASHALL(hash, src, dst) \
   3605 do {									\
   3606 	switch ((src)->sa_family) {					\
   3607 	case AF_INET:							\
   3608 		hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
   3609 			((const struct sockaddr_in *)(src))->sin_port,	\
   3610 			((const struct sockaddr_in *)(dst))->sin_port);	\
   3611 		break;							\
   3612 	case AF_INET6:							\
   3613 		hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \
   3614 			((const struct sockaddr_in6 *)(src))->sin6_port,	\
   3615 			((const struct sockaddr_in6 *)(dst))->sin6_port);	\
   3616 		break;							\
   3617 	default:							\
   3618 		hash = 0;						\
   3619 	}								\
   3620 } while (/*CONSTCOND*/0)
   3621 #endif /* INET6 */
   3622 
   3623 static struct pool syn_cache_pool;
   3624 
   3625 /*
   3626  * We don't estimate RTT with SYNs, so each packet starts with the default
   3627  * RTT and each timer step has a fixed timeout value.
   3628  */
   3629 #define	SYN_CACHE_TIMER_ARM(sc)						\
   3630 do {									\
   3631 	TCPT_RANGESET((sc)->sc_rxtcur,					\
   3632 	    TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN,	\
   3633 	    TCPTV_REXMTMAX);						\
   3634 	callout_reset(&(sc)->sc_timer,					\
   3635 	    (sc)->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, (sc));	\
   3636 } while (/*CONSTCOND*/0)
   3637 
   3638 #define	SYN_CACHE_TIMESTAMP(sc)	(tcp_now - (sc)->sc_timebase)
   3639 
   3640 static inline void
   3641 syn_cache_rm(struct syn_cache *sc)
   3642 {
   3643 	TAILQ_REMOVE(&tcp_syn_cache[sc->sc_bucketidx].sch_bucket,
   3644 	    sc, sc_bucketq);
   3645 	sc->sc_tp = NULL;
   3646 	LIST_REMOVE(sc, sc_tpq);
   3647 	tcp_syn_cache[sc->sc_bucketidx].sch_length--;
   3648 	callout_stop(&sc->sc_timer);
   3649 	syn_cache_count--;
   3650 }
   3651 
   3652 static inline void
   3653 syn_cache_put(struct syn_cache *sc)
   3654 {
   3655 	if (sc->sc_ipopts)
   3656 		(void) m_free(sc->sc_ipopts);
   3657 	rtcache_free(&sc->sc_route);
   3658 	sc->sc_flags |= SCF_DEAD;
   3659 	if (!callout_invoking(&sc->sc_timer))
   3660 		callout_schedule(&(sc)->sc_timer, 1);
   3661 }
   3662 
   3663 void
   3664 syn_cache_init(void)
   3665 {
   3666 	int i;
   3667 
   3668 	pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
   3669 	    "synpl", NULL, IPL_SOFTNET);
   3670 
   3671 	/* Initialize the hash buckets. */
   3672 	for (i = 0; i < tcp_syn_cache_size; i++)
   3673 		TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
   3674 }
   3675 
   3676 void
   3677 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp)
   3678 {
   3679 	struct syn_cache_head *scp;
   3680 	struct syn_cache *sc2;
   3681 	int s;
   3682 
   3683 	/*
   3684 	 * If there are no entries in the hash table, reinitialize
   3685 	 * the hash secrets.
   3686 	 */
   3687 	if (syn_cache_count == 0) {
   3688 		syn_hash1 = cprng_fast32();
   3689 		syn_hash2 = cprng_fast32();
   3690 	}
   3691 
   3692 	SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
   3693 	sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
   3694 	scp = &tcp_syn_cache[sc->sc_bucketidx];
   3695 
   3696 	/*
   3697 	 * Make sure that we don't overflow the per-bucket
   3698 	 * limit or the total cache size limit.
   3699 	 */
   3700 	s = splsoftnet();
   3701 	if (scp->sch_length >= tcp_syn_bucket_limit) {
   3702 		TCP_STATINC(TCP_STAT_SC_BUCKETOVERFLOW);
   3703 		/*
   3704 		 * The bucket is full.  Toss the oldest element in the
   3705 		 * bucket.  This will be the first entry in the bucket.
   3706 		 */
   3707 		sc2 = TAILQ_FIRST(&scp->sch_bucket);
   3708 #ifdef DIAGNOSTIC
   3709 		/*
   3710 		 * This should never happen; we should always find an
   3711 		 * entry in our bucket.
   3712 		 */
   3713 		if (sc2 == NULL)
   3714 			panic("syn_cache_insert: bucketoverflow: impossible");
   3715 #endif
   3716 		syn_cache_rm(sc2);
   3717 		syn_cache_put(sc2);	/* calls pool_put but see spl above */
   3718 	} else if (syn_cache_count >= tcp_syn_cache_limit) {
   3719 		struct syn_cache_head *scp2, *sce;
   3720 
   3721 		TCP_STATINC(TCP_STAT_SC_OVERFLOWED);
   3722 		/*
   3723 		 * The cache is full.  Toss the oldest entry in the
   3724 		 * first non-empty bucket we can find.
   3725 		 *
   3726 		 * XXX We would really like to toss the oldest
   3727 		 * entry in the cache, but we hope that this
   3728 		 * condition doesn't happen very often.
   3729 		 */
   3730 		scp2 = scp;
   3731 		if (TAILQ_EMPTY(&scp2->sch_bucket)) {
   3732 			sce = &tcp_syn_cache[tcp_syn_cache_size];
   3733 			for (++scp2; scp2 != scp; scp2++) {
   3734 				if (scp2 >= sce)
   3735 					scp2 = &tcp_syn_cache[0];
   3736 				if (! TAILQ_EMPTY(&scp2->sch_bucket))
   3737 					break;
   3738 			}
   3739 #ifdef DIAGNOSTIC
   3740 			/*
   3741 			 * This should never happen; we should always find a
   3742 			 * non-empty bucket.
   3743 			 */
   3744 			if (scp2 == scp)
   3745 				panic("syn_cache_insert: cacheoverflow: "
   3746 				    "impossible");
   3747 #endif
   3748 		}
   3749 		sc2 = TAILQ_FIRST(&scp2->sch_bucket);
   3750 		syn_cache_rm(sc2);
   3751 		syn_cache_put(sc2);	/* calls pool_put but see spl above */
   3752 	}
   3753 
   3754 	/*
   3755 	 * Initialize the entry's timer.
   3756 	 */
   3757 	sc->sc_rxttot = 0;
   3758 	sc->sc_rxtshift = 0;
   3759 	SYN_CACHE_TIMER_ARM(sc);
   3760 
   3761 	/* Link it from tcpcb entry */
   3762 	LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
   3763 
   3764 	/* Put it into the bucket. */
   3765 	TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
   3766 	scp->sch_length++;
   3767 	syn_cache_count++;
   3768 
   3769 	TCP_STATINC(TCP_STAT_SC_ADDED);
   3770 	splx(s);
   3771 }
   3772 
   3773 /*
   3774  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
   3775  * If we have retransmitted an entry the maximum number of times, expire
   3776  * that entry.
   3777  */
   3778 void
   3779 syn_cache_timer(void *arg)
   3780 {
   3781 	struct syn_cache *sc = arg;
   3782 
   3783 	mutex_enter(softnet_lock);
   3784 	KERNEL_LOCK(1, NULL);
   3785 	callout_ack(&sc->sc_timer);
   3786 
   3787 	if (__predict_false(sc->sc_flags & SCF_DEAD)) {
   3788 		TCP_STATINC(TCP_STAT_SC_DELAYED_FREE);
   3789 		callout_destroy(&sc->sc_timer);
   3790 		pool_put(&syn_cache_pool, sc);
   3791 		KERNEL_UNLOCK_ONE(NULL);
   3792 		mutex_exit(softnet_lock);
   3793 		return;
   3794 	}
   3795 
   3796 	if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
   3797 		/* Drop it -- too many retransmissions. */
   3798 		goto dropit;
   3799 	}
   3800 
   3801 	/*
   3802 	 * Compute the total amount of time this entry has
   3803 	 * been on a queue.  If this entry has been on longer
   3804 	 * than the keep alive timer would allow, expire it.
   3805 	 */
   3806 	sc->sc_rxttot += sc->sc_rxtcur;
   3807 	if (sc->sc_rxttot >= tcp_keepinit)
   3808 		goto dropit;
   3809 
   3810 	TCP_STATINC(TCP_STAT_SC_RETRANSMITTED);
   3811 	(void) syn_cache_respond(sc, NULL);
   3812 
   3813 	/* Advance the timer back-off. */
   3814 	sc->sc_rxtshift++;
   3815 	SYN_CACHE_TIMER_ARM(sc);
   3816 
   3817 	KERNEL_UNLOCK_ONE(NULL);
   3818 	mutex_exit(softnet_lock);
   3819 	return;
   3820 
   3821  dropit:
   3822 	TCP_STATINC(TCP_STAT_SC_TIMED_OUT);
   3823 	syn_cache_rm(sc);
   3824 	if (sc->sc_ipopts)
   3825 		(void) m_free(sc->sc_ipopts);
   3826 	rtcache_free(&sc->sc_route);
   3827 	callout_destroy(&sc->sc_timer);
   3828 	pool_put(&syn_cache_pool, sc);
   3829 	KERNEL_UNLOCK_ONE(NULL);
   3830 	mutex_exit(softnet_lock);
   3831 }
   3832 
   3833 /*
   3834  * Remove syn cache created by the specified tcb entry,
   3835  * because this does not make sense to keep them
   3836  * (if there's no tcb entry, syn cache entry will never be used)
   3837  */
   3838 void
   3839 syn_cache_cleanup(struct tcpcb *tp)
   3840 {
   3841 	struct syn_cache *sc, *nsc;
   3842 	int s;
   3843 
   3844 	s = splsoftnet();
   3845 
   3846 	for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
   3847 		nsc = LIST_NEXT(sc, sc_tpq);
   3848 
   3849 #ifdef DIAGNOSTIC
   3850 		if (sc->sc_tp != tp)
   3851 			panic("invalid sc_tp in syn_cache_cleanup");
   3852 #endif
   3853 		syn_cache_rm(sc);
   3854 		syn_cache_put(sc);	/* calls pool_put but see spl above */
   3855 	}
   3856 	/* just for safety */
   3857 	LIST_INIT(&tp->t_sc);
   3858 
   3859 	splx(s);
   3860 }
   3861 
   3862 /*
   3863  * Find an entry in the syn cache.
   3864  */
   3865 struct syn_cache *
   3866 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst,
   3867     struct syn_cache_head **headp)
   3868 {
   3869 	struct syn_cache *sc;
   3870 	struct syn_cache_head *scp;
   3871 	u_int32_t hash;
   3872 	int s;
   3873 
   3874 	SYN_HASHALL(hash, src, dst);
   3875 
   3876 	scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
   3877 	*headp = scp;
   3878 	s = splsoftnet();
   3879 	for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
   3880 	     sc = TAILQ_NEXT(sc, sc_bucketq)) {
   3881 		if (sc->sc_hash != hash)
   3882 			continue;
   3883 		if (!memcmp(&sc->sc_src, src, src->sa_len) &&
   3884 		    !memcmp(&sc->sc_dst, dst, dst->sa_len)) {
   3885 			splx(s);
   3886 			return (sc);
   3887 		}
   3888 	}
   3889 	splx(s);
   3890 	return (NULL);
   3891 }
   3892 
   3893 /*
   3894  * This function gets called when we receive an ACK for a
   3895  * socket in the LISTEN state.  We look up the connection
   3896  * in the syn cache, and if its there, we pull it out of
   3897  * the cache and turn it into a full-blown connection in
   3898  * the SYN-RECEIVED state.
   3899  *
   3900  * The return values may not be immediately obvious, and their effects
   3901  * can be subtle, so here they are:
   3902  *
   3903  *	NULL	SYN was not found in cache; caller should drop the
   3904  *		packet and send an RST.
   3905  *
   3906  *	-1	We were unable to create the new connection, and are
   3907  *		aborting it.  An ACK,RST is being sent to the peer
   3908  *		(unless we got screwey sequence numbners; see below),
   3909  *		because the 3-way handshake has been completed.  Caller
   3910  *		should not free the mbuf, since we may be using it.  If
   3911  *		we are not, we will free it.
   3912  *
   3913  *	Otherwise, the return value is a pointer to the new socket
   3914  *	associated with the connection.
   3915  */
   3916 struct socket *
   3917 syn_cache_get(struct sockaddr *src, struct sockaddr *dst,
   3918     struct tcphdr *th, unsigned int hlen, unsigned int tlen,
   3919     struct socket *so, struct mbuf *m)
   3920 {
   3921 	struct syn_cache *sc;
   3922 	struct syn_cache_head *scp;
   3923 	struct inpcb *inp = NULL;
   3924 #ifdef INET6
   3925 	struct in6pcb *in6p = NULL;
   3926 #endif
   3927 	struct tcpcb *tp = 0;
   3928 	struct mbuf *am;
   3929 	int s;
   3930 	struct socket *oso;
   3931 
   3932 	s = splsoftnet();
   3933 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
   3934 		splx(s);
   3935 		return (NULL);
   3936 	}
   3937 
   3938 	/*
   3939 	 * Verify the sequence and ack numbers.  Try getting the correct
   3940 	 * response again.
   3941 	 */
   3942 	if ((th->th_ack != sc->sc_iss + 1) ||
   3943 	    SEQ_LEQ(th->th_seq, sc->sc_irs) ||
   3944 	    SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
   3945 		(void) syn_cache_respond(sc, m);
   3946 		splx(s);
   3947 		return ((struct socket *)(-1));
   3948 	}
   3949 
   3950 	/* Remove this cache entry */
   3951 	syn_cache_rm(sc);
   3952 	splx(s);
   3953 
   3954 	/*
   3955 	 * Ok, create the full blown connection, and set things up
   3956 	 * as they would have been set up if we had created the
   3957 	 * connection when the SYN arrived.  If we can't create
   3958 	 * the connection, abort it.
   3959 	 */
   3960 	/*
   3961 	 * inp still has the OLD in_pcb stuff, set the
   3962 	 * v6-related flags on the new guy, too.   This is
   3963 	 * done particularly for the case where an AF_INET6
   3964 	 * socket is bound only to a port, and a v4 connection
   3965 	 * comes in on that port.
   3966 	 * we also copy the flowinfo from the original pcb
   3967 	 * to the new one.
   3968 	 */
   3969 	oso = so;
   3970 	so = sonewconn(so, true);
   3971 	if (so == NULL)
   3972 		goto resetandabort;
   3973 
   3974 	switch (so->so_proto->pr_domain->dom_family) {
   3975 #ifdef INET
   3976 	case AF_INET:
   3977 		inp = sotoinpcb(so);
   3978 		break;
   3979 #endif
   3980 #ifdef INET6
   3981 	case AF_INET6:
   3982 		in6p = sotoin6pcb(so);
   3983 		break;
   3984 #endif
   3985 	}
   3986 	switch (src->sa_family) {
   3987 #ifdef INET
   3988 	case AF_INET:
   3989 		if (inp) {
   3990 			inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
   3991 			inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
   3992 			inp->inp_options = ip_srcroute();
   3993 			in_pcbstate(inp, INP_BOUND);
   3994 			if (inp->inp_options == NULL) {
   3995 				inp->inp_options = sc->sc_ipopts;
   3996 				sc->sc_ipopts = NULL;
   3997 			}
   3998 		}
   3999 #ifdef INET6
   4000 		else if (in6p) {
   4001 			/* IPv4 packet to AF_INET6 socket */
   4002 			memset(&in6p->in6p_laddr, 0, sizeof(in6p->in6p_laddr));
   4003 			in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
   4004 			bcopy(&((struct sockaddr_in *)dst)->sin_addr,
   4005 				&in6p->in6p_laddr.s6_addr32[3],
   4006 				sizeof(((struct sockaddr_in *)dst)->sin_addr));
   4007 			in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
   4008 			in6totcpcb(in6p)->t_family = AF_INET;
   4009 			if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
   4010 				in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
   4011 			else
   4012 				in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
   4013 			in6_pcbstate(in6p, IN6P_BOUND);
   4014 		}
   4015 #endif
   4016 		break;
   4017 #endif
   4018 #ifdef INET6
   4019 	case AF_INET6:
   4020 		if (in6p) {
   4021 			in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
   4022 			in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
   4023 			in6_pcbstate(in6p, IN6P_BOUND);
   4024 		}
   4025 		break;
   4026 #endif
   4027 	}
   4028 #ifdef INET6
   4029 	if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
   4030 		struct in6pcb *oin6p = sotoin6pcb(oso);
   4031 		/* inherit socket options from the listening socket */
   4032 		in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
   4033 		if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
   4034 			m_freem(in6p->in6p_options);
   4035 			in6p->in6p_options = 0;
   4036 		}
   4037 		ip6_savecontrol(in6p, &in6p->in6p_options,
   4038 			mtod(m, struct ip6_hdr *), m);
   4039 	}
   4040 #endif
   4041 
   4042 #if defined(IPSEC)
   4043 	/*
   4044 	 * we make a copy of policy, instead of sharing the policy,
   4045 	 * for better behavior in terms of SA lookup and dead SA removal.
   4046 	 */
   4047 	if (inp) {
   4048 		/* copy old policy into new socket's */
   4049 		if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp, inp->inp_sp))
   4050 			printf("tcp_input: could not copy policy\n");
   4051 	}
   4052 #ifdef INET6
   4053 	else if (in6p) {
   4054 		/* copy old policy into new socket's */
   4055 		if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
   4056 		    in6p->in6p_sp))
   4057 			printf("tcp_input: could not copy policy\n");
   4058 	}
   4059 #endif
   4060 #endif
   4061 
   4062 	/*
   4063 	 * Give the new socket our cached route reference.
   4064 	 */
   4065 	if (inp) {
   4066 		rtcache_copy(&inp->inp_route, &sc->sc_route);
   4067 		rtcache_free(&sc->sc_route);
   4068 	}
   4069 #ifdef INET6
   4070 	else {
   4071 		rtcache_copy(&in6p->in6p_route, &sc->sc_route);
   4072 		rtcache_free(&sc->sc_route);
   4073 	}
   4074 #endif
   4075 
   4076 	am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
   4077 	if (am == NULL)
   4078 		goto resetandabort;
   4079 	MCLAIM(am, &tcp_mowner);
   4080 	am->m_len = src->sa_len;
   4081 	bcopy(src, mtod(am, void *), src->sa_len);
   4082 	if (inp) {
   4083 		if (in_pcbconnect(inp, am, &lwp0)) {
   4084 			(void) m_free(am);
   4085 			goto resetandabort;
   4086 		}
   4087 	}
   4088 #ifdef INET6
   4089 	else if (in6p) {
   4090 		if (src->sa_family == AF_INET) {
   4091 			/* IPv4 packet to AF_INET6 socket */
   4092 			struct sockaddr_in6 *sin6;
   4093 			sin6 = mtod(am, struct sockaddr_in6 *);
   4094 			am->m_len = sizeof(*sin6);
   4095 			memset(sin6, 0, sizeof(*sin6));
   4096 			sin6->sin6_family = AF_INET6;
   4097 			sin6->sin6_len = sizeof(*sin6);
   4098 			sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
   4099 			sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
   4100 			bcopy(&((struct sockaddr_in *)src)->sin_addr,
   4101 				&sin6->sin6_addr.s6_addr32[3],
   4102 				sizeof(sin6->sin6_addr.s6_addr32[3]));
   4103 		}
   4104 		if (in6_pcbconnect(in6p, am, NULL)) {
   4105 			(void) m_free(am);
   4106 			goto resetandabort;
   4107 		}
   4108 	}
   4109 #endif
   4110 	else {
   4111 		(void) m_free(am);
   4112 		goto resetandabort;
   4113 	}
   4114 	(void) m_free(am);
   4115 
   4116 	if (inp)
   4117 		tp = intotcpcb(inp);
   4118 #ifdef INET6
   4119 	else if (in6p)
   4120 		tp = in6totcpcb(in6p);
   4121 #endif
   4122 	else
   4123 		tp = NULL;
   4124 	tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
   4125 	if (sc->sc_request_r_scale != 15) {
   4126 		tp->requested_s_scale = sc->sc_requested_s_scale;
   4127 		tp->request_r_scale = sc->sc_request_r_scale;
   4128 		tp->snd_scale = sc->sc_requested_s_scale;
   4129 		tp->rcv_scale = sc->sc_request_r_scale;
   4130 		tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
   4131 	}
   4132 	if (sc->sc_flags & SCF_TIMESTAMP)
   4133 		tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
   4134 	tp->ts_timebase = sc->sc_timebase;
   4135 
   4136 	tp->t_template = tcp_template(tp);
   4137 	if (tp->t_template == 0) {
   4138 		tp = tcp_drop(tp, ENOBUFS);	/* destroys socket */
   4139 		so = NULL;
   4140 		m_freem(m);
   4141 		goto abort;
   4142 	}
   4143 
   4144 	tp->iss = sc->sc_iss;
   4145 	tp->irs = sc->sc_irs;
   4146 	tcp_sendseqinit(tp);
   4147 	tcp_rcvseqinit(tp);
   4148 	tp->t_state = TCPS_SYN_RECEIVED;
   4149 	TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepinit);
   4150 	TCP_STATINC(TCP_STAT_ACCEPTS);
   4151 
   4152 	if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack)
   4153 		tp->t_flags |= TF_WILL_SACK;
   4154 
   4155 	if ((sc->sc_flags & SCF_ECN_PERMIT) && tcp_do_ecn)
   4156 		tp->t_flags |= TF_ECN_PERMIT;
   4157 
   4158 #ifdef TCP_SIGNATURE
   4159 	if (sc->sc_flags & SCF_SIGNATURE)
   4160 		tp->t_flags |= TF_SIGNATURE;
   4161 #endif
   4162 
   4163 	/* Initialize tp->t_ourmss before we deal with the peer's! */
   4164 	tp->t_ourmss = sc->sc_ourmaxseg;
   4165 	tcp_mss_from_peer(tp, sc->sc_peermaxseg);
   4166 
   4167 	/*
   4168 	 * Initialize the initial congestion window.  If we
   4169 	 * had to retransmit the SYN,ACK, we must initialize cwnd
   4170 	 * to 1 segment (i.e. the Loss Window).
   4171 	 */
   4172 	if (sc->sc_rxtshift)
   4173 		tp->snd_cwnd = tp->t_peermss;
   4174 	else {
   4175 		int ss = tcp_init_win;
   4176 #ifdef INET
   4177 		if (inp != NULL && in_localaddr(inp->inp_faddr))
   4178 			ss = tcp_init_win_local;
   4179 #endif
   4180 #ifdef INET6
   4181 		if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
   4182 			ss = tcp_init_win_local;
   4183 #endif
   4184 		tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
   4185 	}
   4186 
   4187 	tcp_rmx_rtt(tp);
   4188 	tp->snd_wl1 = sc->sc_irs;
   4189 	tp->rcv_up = sc->sc_irs + 1;
   4190 
   4191 	/*
   4192 	 * This is what whould have happened in tcp_output() when
   4193 	 * the SYN,ACK was sent.
   4194 	 */
   4195 	tp->snd_up = tp->snd_una;
   4196 	tp->snd_max = tp->snd_nxt = tp->iss+1;
   4197 	TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   4198 	if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
   4199 		tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
   4200 	tp->last_ack_sent = tp->rcv_nxt;
   4201 	tp->t_partialacks = -1;
   4202 	tp->t_dupacks = 0;
   4203 
   4204 	TCP_STATINC(TCP_STAT_SC_COMPLETED);
   4205 	s = splsoftnet();
   4206 	syn_cache_put(sc);
   4207 	splx(s);
   4208 	return (so);
   4209 
   4210 resetandabort:
   4211 	(void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
   4212 abort:
   4213 	if (so != NULL) {
   4214 		(void) soqremque(so, 1);
   4215 		(void) soabort(so);
   4216 		mutex_enter(softnet_lock);
   4217 	}
   4218 	s = splsoftnet();
   4219 	syn_cache_put(sc);
   4220 	splx(s);
   4221 	TCP_STATINC(TCP_STAT_SC_ABORTED);
   4222 	return ((struct socket *)(-1));
   4223 }
   4224 
   4225 /*
   4226  * This function is called when we get a RST for a
   4227  * non-existent connection, so that we can see if the
   4228  * connection is in the syn cache.  If it is, zap it.
   4229  */
   4230 
   4231 void
   4232 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th)
   4233 {
   4234 	struct syn_cache *sc;
   4235 	struct syn_cache_head *scp;
   4236 	int s = splsoftnet();
   4237 
   4238 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
   4239 		splx(s);
   4240 		return;
   4241 	}
   4242 	if (SEQ_LT(th->th_seq, sc->sc_irs) ||
   4243 	    SEQ_GT(th->th_seq, sc->sc_irs+1)) {
   4244 		splx(s);
   4245 		return;
   4246 	}
   4247 	syn_cache_rm(sc);
   4248 	TCP_STATINC(TCP_STAT_SC_RESET);
   4249 	syn_cache_put(sc);	/* calls pool_put but see spl above */
   4250 	splx(s);
   4251 }
   4252 
   4253 void
   4254 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst,
   4255     struct tcphdr *th)
   4256 {
   4257 	struct syn_cache *sc;
   4258 	struct syn_cache_head *scp;
   4259 	int s;
   4260 
   4261 	s = splsoftnet();
   4262 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
   4263 		splx(s);
   4264 		return;
   4265 	}
   4266 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
   4267 	if (ntohl (th->th_seq) != sc->sc_iss) {
   4268 		splx(s);
   4269 		return;
   4270 	}
   4271 
   4272 	/*
   4273 	 * If we've retransmitted 3 times and this is our second error,
   4274 	 * we remove the entry.  Otherwise, we allow it to continue on.
   4275 	 * This prevents us from incorrectly nuking an entry during a
   4276 	 * spurious network outage.
   4277 	 *
   4278 	 * See tcp_notify().
   4279 	 */
   4280 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
   4281 		sc->sc_flags |= SCF_UNREACH;
   4282 		splx(s);
   4283 		return;
   4284 	}
   4285 
   4286 	syn_cache_rm(sc);
   4287 	TCP_STATINC(TCP_STAT_SC_UNREACH);
   4288 	syn_cache_put(sc);	/* calls pool_put but see spl above */
   4289 	splx(s);
   4290 }
   4291 
   4292 /*
   4293  * Given a LISTEN socket and an inbound SYN request, add
   4294  * this to the syn cache, and send back a segment:
   4295  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
   4296  * to the source.
   4297  *
   4298  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
   4299  * Doing so would require that we hold onto the data and deliver it
   4300  * to the application.  However, if we are the target of a SYN-flood
   4301  * DoS attack, an attacker could send data which would eventually
   4302  * consume all available buffer space if it were ACKed.  By not ACKing
   4303  * the data, we avoid this DoS scenario.
   4304  */
   4305 
   4306 int
   4307 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th,
   4308     unsigned int hlen, struct socket *so, struct mbuf *m, u_char *optp,
   4309     int optlen, struct tcp_opt_info *oi)
   4310 {
   4311 	struct tcpcb tb, *tp;
   4312 	long win;
   4313 	struct syn_cache *sc;
   4314 	struct syn_cache_head *scp;
   4315 	struct mbuf *ipopts;
   4316 	struct tcp_opt_info opti;
   4317 	int s;
   4318 
   4319 	tp = sototcpcb(so);
   4320 
   4321 	memset(&opti, 0, sizeof(opti));
   4322 
   4323 	/*
   4324 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
   4325 	 *
   4326 	 * Note this check is performed in tcp_input() very early on.
   4327 	 */
   4328 
   4329 	/*
   4330 	 * Initialize some local state.
   4331 	 */
   4332 	win = sbspace(&so->so_rcv);
   4333 	if (win > TCP_MAXWIN)
   4334 		win = TCP_MAXWIN;
   4335 
   4336 	switch (src->sa_family) {
   4337 #ifdef INET
   4338 	case AF_INET:
   4339 		/*
   4340 		 * Remember the IP options, if any.
   4341 		 */
   4342 		ipopts = ip_srcroute();
   4343 		break;
   4344 #endif
   4345 	default:
   4346 		ipopts = NULL;
   4347 	}
   4348 
   4349 #ifdef TCP_SIGNATURE
   4350 	if (optp || (tp->t_flags & TF_SIGNATURE))
   4351 #else
   4352 	if (optp)
   4353 #endif
   4354 	{
   4355 		tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
   4356 #ifdef TCP_SIGNATURE
   4357 		tb.t_flags |= (tp->t_flags & TF_SIGNATURE);
   4358 #endif
   4359 		tb.t_state = TCPS_LISTEN;
   4360 		if (tcp_dooptions(&tb, optp, optlen, th, m, m->m_pkthdr.len -
   4361 		    sizeof(struct tcphdr) - optlen - hlen, oi) < 0)
   4362 			return (0);
   4363 	} else
   4364 		tb.t_flags = 0;
   4365 
   4366 	/*
   4367 	 * See if we already have an entry for this connection.
   4368 	 * If we do, resend the SYN,ACK.  We do not count this
   4369 	 * as a retransmission (XXX though maybe we should).
   4370 	 */
   4371 	if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
   4372 		TCP_STATINC(TCP_STAT_SC_DUPESYN);
   4373 		if (ipopts) {
   4374 			/*
   4375 			 * If we were remembering a previous source route,
   4376 			 * forget it and use the new one we've been given.
   4377 			 */
   4378 			if (sc->sc_ipopts)
   4379 				(void) m_free(sc->sc_ipopts);
   4380 			sc->sc_ipopts = ipopts;
   4381 		}
   4382 		sc->sc_timestamp = tb.ts_recent;
   4383 		if (syn_cache_respond(sc, m) == 0) {
   4384 			uint64_t *tcps = TCP_STAT_GETREF();
   4385 			tcps[TCP_STAT_SNDACKS]++;
   4386 			tcps[TCP_STAT_SNDTOTAL]++;
   4387 			TCP_STAT_PUTREF();
   4388 		}
   4389 		return (1);
   4390 	}
   4391 
   4392 	s = splsoftnet();
   4393 	sc = pool_get(&syn_cache_pool, PR_NOWAIT);
   4394 	splx(s);
   4395 	if (sc == NULL) {
   4396 		if (ipopts)
   4397 			(void) m_free(ipopts);
   4398 		return (0);
   4399 	}
   4400 
   4401 	/*
   4402 	 * Fill in the cache, and put the necessary IP and TCP
   4403 	 * options into the reply.
   4404 	 */
   4405 	memset(sc, 0, sizeof(struct syn_cache));
   4406 	callout_init(&sc->sc_timer, CALLOUT_MPSAFE);
   4407 	bcopy(src, &sc->sc_src, src->sa_len);
   4408 	bcopy(dst, &sc->sc_dst, dst->sa_len);
   4409 	sc->sc_flags = 0;
   4410 	sc->sc_ipopts = ipopts;
   4411 	sc->sc_irs = th->th_seq;
   4412 	switch (src->sa_family) {
   4413 #ifdef INET
   4414 	case AF_INET:
   4415 	    {
   4416 		struct sockaddr_in *srcin = (void *) src;
   4417 		struct sockaddr_in *dstin = (void *) dst;
   4418 
   4419 		sc->sc_iss = tcp_new_iss1(&dstin->sin_addr,
   4420 		    &srcin->sin_addr, dstin->sin_port,
   4421 		    srcin->sin_port, sizeof(dstin->sin_addr), 0);
   4422 		break;
   4423 	    }
   4424 #endif /* INET */
   4425 #ifdef INET6
   4426 	case AF_INET6:
   4427 	    {
   4428 		struct sockaddr_in6 *srcin6 = (void *) src;
   4429 		struct sockaddr_in6 *dstin6 = (void *) dst;
   4430 
   4431 		sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr,
   4432 		    &srcin6->sin6_addr, dstin6->sin6_port,
   4433 		    srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0);
   4434 		break;
   4435 	    }
   4436 #endif /* INET6 */
   4437 	}
   4438 	sc->sc_peermaxseg = oi->maxseg;
   4439 	sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
   4440 						m->m_pkthdr.rcvif : NULL,
   4441 						sc->sc_src.sa.sa_family);
   4442 	sc->sc_win = win;
   4443 	sc->sc_timebase = tcp_now - 1;	/* see tcp_newtcpcb() */
   4444 	sc->sc_timestamp = tb.ts_recent;
   4445 	if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) ==
   4446 	    (TF_REQ_TSTMP|TF_RCVD_TSTMP))
   4447 		sc->sc_flags |= SCF_TIMESTAMP;
   4448 	if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   4449 	    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   4450 		sc->sc_requested_s_scale = tb.requested_s_scale;
   4451 		sc->sc_request_r_scale = 0;
   4452 		/*
   4453 		 * Pick the smallest possible scaling factor that
   4454 		 * will still allow us to scale up to sb_max.
   4455 		 *
   4456 		 * We do this because there are broken firewalls that
   4457 		 * will corrupt the window scale option, leading to
   4458 		 * the other endpoint believing that our advertised
   4459 		 * window is unscaled.  At scale factors larger than
   4460 		 * 5 the unscaled window will drop below 1500 bytes,
   4461 		 * leading to serious problems when traversing these
   4462 		 * broken firewalls.
   4463 		 *
   4464 		 * With the default sbmax of 256K, a scale factor
   4465 		 * of 3 will be chosen by this algorithm.  Those who
   4466 		 * choose a larger sbmax should watch out
   4467 		 * for the compatiblity problems mentioned above.
   4468 		 *
   4469 		 * RFC1323: The Window field in a SYN (i.e., a <SYN>
   4470 		 * or <SYN,ACK>) segment itself is never scaled.
   4471 		 */
   4472 		while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
   4473 		    (TCP_MAXWIN << sc->sc_request_r_scale) < sb_max)
   4474 			sc->sc_request_r_scale++;
   4475 	} else {
   4476 		sc->sc_requested_s_scale = 15;
   4477 		sc->sc_request_r_scale = 15;
   4478 	}
   4479 	if ((tb.t_flags & TF_SACK_PERMIT) && tcp_do_sack)
   4480 		sc->sc_flags |= SCF_SACK_PERMIT;
   4481 
   4482 	/*
   4483 	 * ECN setup packet recieved.
   4484 	 */
   4485 	if ((th->th_flags & (TH_ECE|TH_CWR)) && tcp_do_ecn)
   4486 		sc->sc_flags |= SCF_ECN_PERMIT;
   4487 
   4488 #ifdef TCP_SIGNATURE
   4489 	if (tb.t_flags & TF_SIGNATURE)
   4490 		sc->sc_flags |= SCF_SIGNATURE;
   4491 #endif
   4492 	sc->sc_tp = tp;
   4493 	if (syn_cache_respond(sc, m) == 0) {
   4494 		uint64_t *tcps = TCP_STAT_GETREF();
   4495 		tcps[TCP_STAT_SNDACKS]++;
   4496 		tcps[TCP_STAT_SNDTOTAL]++;
   4497 		TCP_STAT_PUTREF();
   4498 		syn_cache_insert(sc, tp);
   4499 	} else {
   4500 		s = splsoftnet();
   4501 		/*
   4502 		 * syn_cache_put() will try to schedule the timer, so
   4503 		 * we need to initialize it
   4504 		 */
   4505 		SYN_CACHE_TIMER_ARM(sc);
   4506 		syn_cache_put(sc);
   4507 		splx(s);
   4508 		TCP_STATINC(TCP_STAT_SC_DROPPED);
   4509 	}
   4510 	return (1);
   4511 }
   4512 
   4513 /*
   4514  * syn_cache_respond: (re)send SYN+ACK.
   4515  *
   4516  * returns 0 on success.  otherwise returns an errno, typically ENOBUFS.
   4517  */
   4518 
   4519 int
   4520 syn_cache_respond(struct syn_cache *sc, struct mbuf *m)
   4521 {
   4522 #ifdef INET6
   4523 	struct rtentry *rt;
   4524 #endif
   4525 	struct route *ro;
   4526 	u_int8_t *optp;
   4527 	int optlen, error;
   4528 	u_int16_t tlen;
   4529 	struct ip *ip = NULL;
   4530 #ifdef INET6
   4531 	struct ip6_hdr *ip6 = NULL;
   4532 #endif
   4533 	struct tcpcb *tp = NULL;
   4534 	struct tcphdr *th;
   4535 	u_int hlen;
   4536 	struct socket *so;
   4537 
   4538 	ro = &sc->sc_route;
   4539 	switch (sc->sc_src.sa.sa_family) {
   4540 	case AF_INET:
   4541 		hlen = sizeof(struct ip);
   4542 		break;
   4543 #ifdef INET6
   4544 	case AF_INET6:
   4545 		hlen = sizeof(struct ip6_hdr);
   4546 		break;
   4547 #endif
   4548 	default:
   4549 		if (m)
   4550 			m_freem(m);
   4551 		return (EAFNOSUPPORT);
   4552 	}
   4553 
   4554 	/* Compute the size of the TCP options. */
   4555 	optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
   4556 	    ((sc->sc_flags & SCF_SACK_PERMIT) ? (TCPOLEN_SACK_PERMITTED + 2) : 0) +
   4557 #ifdef TCP_SIGNATURE
   4558 	    ((sc->sc_flags & SCF_SIGNATURE) ? (TCPOLEN_SIGNATURE + 2) : 0) +
   4559 #endif
   4560 	    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
   4561 
   4562 	tlen = hlen + sizeof(struct tcphdr) + optlen;
   4563 
   4564 	/*
   4565 	 * Create the IP+TCP header from scratch.
   4566 	 */
   4567 	if (m)
   4568 		m_freem(m);
   4569 #ifdef DIAGNOSTIC
   4570 	if (max_linkhdr + tlen > MCLBYTES)
   4571 		return (ENOBUFS);
   4572 #endif
   4573 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   4574 	if (m && (max_linkhdr + tlen) > MHLEN) {
   4575 		MCLGET(m, M_DONTWAIT);
   4576 		if ((m->m_flags & M_EXT) == 0) {
   4577 			m_freem(m);
   4578 			m = NULL;
   4579 		}
   4580 	}
   4581 	if (m == NULL)
   4582 		return (ENOBUFS);
   4583 	MCLAIM(m, &tcp_tx_mowner);
   4584 
   4585 	/* Fixup the mbuf. */
   4586 	m->m_data += max_linkhdr;
   4587 	m->m_len = m->m_pkthdr.len = tlen;
   4588 	if (sc->sc_tp) {
   4589 		tp = sc->sc_tp;
   4590 		if (tp->t_inpcb)
   4591 			so = tp->t_inpcb->inp_socket;
   4592 #ifdef INET6
   4593 		else if (tp->t_in6pcb)
   4594 			so = tp->t_in6pcb->in6p_socket;
   4595 #endif
   4596 		else
   4597 			so = NULL;
   4598 	} else
   4599 		so = NULL;
   4600 	m->m_pkthdr.rcvif = NULL;
   4601 	memset(mtod(m, u_char *), 0, tlen);
   4602 
   4603 	switch (sc->sc_src.sa.sa_family) {
   4604 	case AF_INET:
   4605 		ip = mtod(m, struct ip *);
   4606 		ip->ip_v = 4;
   4607 		ip->ip_dst = sc->sc_src.sin.sin_addr;
   4608 		ip->ip_src = sc->sc_dst.sin.sin_addr;
   4609 		ip->ip_p = IPPROTO_TCP;
   4610 		th = (struct tcphdr *)(ip + 1);
   4611 		th->th_dport = sc->sc_src.sin.sin_port;
   4612 		th->th_sport = sc->sc_dst.sin.sin_port;
   4613 		break;
   4614 #ifdef INET6
   4615 	case AF_INET6:
   4616 		ip6 = mtod(m, struct ip6_hdr *);
   4617 		ip6->ip6_vfc = IPV6_VERSION;
   4618 		ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
   4619 		ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
   4620 		ip6->ip6_nxt = IPPROTO_TCP;
   4621 		/* ip6_plen will be updated in ip6_output() */
   4622 		th = (struct tcphdr *)(ip6 + 1);
   4623 		th->th_dport = sc->sc_src.sin6.sin6_port;
   4624 		th->th_sport = sc->sc_dst.sin6.sin6_port;
   4625 		break;
   4626 #endif
   4627 	default:
   4628 		th = NULL;
   4629 	}
   4630 
   4631 	th->th_seq = htonl(sc->sc_iss);
   4632 	th->th_ack = htonl(sc->sc_irs + 1);
   4633 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
   4634 	th->th_flags = TH_SYN|TH_ACK;
   4635 	th->th_win = htons(sc->sc_win);
   4636 	/* th_sum already 0 */
   4637 	/* th_urp already 0 */
   4638 
   4639 	/* Tack on the TCP options. */
   4640 	optp = (u_int8_t *)(th + 1);
   4641 	*optp++ = TCPOPT_MAXSEG;
   4642 	*optp++ = 4;
   4643 	*optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
   4644 	*optp++ = sc->sc_ourmaxseg & 0xff;
   4645 
   4646 	if (sc->sc_request_r_scale != 15) {
   4647 		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
   4648 		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
   4649 		    sc->sc_request_r_scale);
   4650 		optp += 4;
   4651 	}
   4652 
   4653 	if (sc->sc_flags & SCF_TIMESTAMP) {
   4654 		u_int32_t *lp = (u_int32_t *)(optp);
   4655 		/* Form timestamp option as shown in appendix A of RFC 1323. */
   4656 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
   4657 		*lp++ = htonl(SYN_CACHE_TIMESTAMP(sc));
   4658 		*lp   = htonl(sc->sc_timestamp);
   4659 		optp += TCPOLEN_TSTAMP_APPA;
   4660 	}
   4661 
   4662 	if (sc->sc_flags & SCF_SACK_PERMIT) {
   4663 		u_int8_t *p = optp;
   4664 
   4665 		/* Let the peer know that we will SACK. */
   4666 		p[0] = TCPOPT_SACK_PERMITTED;
   4667 		p[1] = 2;
   4668 		p[2] = TCPOPT_NOP;
   4669 		p[3] = TCPOPT_NOP;
   4670 		optp += 4;
   4671 	}
   4672 
   4673 	/*
   4674 	 * Send ECN SYN-ACK setup packet.
   4675 	 * Routes can be asymetric, so, even if we receive a packet
   4676 	 * with ECE and CWR set, we must not assume no one will block
   4677 	 * the ECE packet we are about to send.
   4678 	 */
   4679 	if ((sc->sc_flags & SCF_ECN_PERMIT) && tp &&
   4680 	    SEQ_GEQ(tp->snd_nxt, tp->snd_max)) {
   4681 		th->th_flags |= TH_ECE;
   4682 		TCP_STATINC(TCP_STAT_ECN_SHS);
   4683 
   4684 		/*
   4685 		 * draft-ietf-tcpm-ecnsyn-00.txt
   4686 		 *
   4687 		 * "[...] a TCP node MAY respond to an ECN-setup
   4688 		 * SYN packet by setting ECT in the responding
   4689 		 * ECN-setup SYN/ACK packet, indicating to routers
   4690 		 * that the SYN/ACK packet is ECN-Capable.
   4691 		 * This allows a congested router along the path
   4692 		 * to mark the packet instead of dropping the
   4693 		 * packet as an indication of congestion."
   4694 		 *
   4695 		 * "[...] There can be a great benefit in setting
   4696 		 * an ECN-capable codepoint in SYN/ACK packets [...]
   4697 		 * Congestion is  most likely to occur in
   4698 		 * the server-to-client direction.  As a result,
   4699 		 * setting an ECN-capable codepoint in SYN/ACK
   4700 		 * packets can reduce the occurence of three-second
   4701 		 * retransmit timeouts resulting from the drop
   4702 		 * of SYN/ACK packets."
   4703 		 *
   4704 		 * Page 4 and 6, January 2006.
   4705 		 */
   4706 
   4707 		switch (sc->sc_src.sa.sa_family) {
   4708 #ifdef INET
   4709 		case AF_INET:
   4710 			ip->ip_tos |= IPTOS_ECN_ECT0;
   4711 			break;
   4712 #endif
   4713 #ifdef INET6
   4714 		case AF_INET6:
   4715 			ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
   4716 			break;
   4717 #endif
   4718 		}
   4719 		TCP_STATINC(TCP_STAT_ECN_ECT);
   4720 	}
   4721 
   4722 #ifdef TCP_SIGNATURE
   4723 	if (sc->sc_flags & SCF_SIGNATURE) {
   4724 		struct secasvar *sav;
   4725 		u_int8_t *sigp;
   4726 
   4727 		sav = tcp_signature_getsav(m, th);
   4728 
   4729 		if (sav == NULL) {
   4730 			if (m)
   4731 				m_freem(m);
   4732 			return (EPERM);
   4733 		}
   4734 
   4735 		*optp++ = TCPOPT_SIGNATURE;
   4736 		*optp++ = TCPOLEN_SIGNATURE;
   4737 		sigp = optp;
   4738 		memset(optp, 0, TCP_SIGLEN);
   4739 		optp += TCP_SIGLEN;
   4740 		*optp++ = TCPOPT_NOP;
   4741 		*optp++ = TCPOPT_EOL;
   4742 
   4743 		(void)tcp_signature(m, th, hlen, sav, sigp);
   4744 
   4745 		key_sa_recordxfer(sav, m);
   4746 		KEY_FREESAV(&sav);
   4747 	}
   4748 #endif
   4749 
   4750 	/* Compute the packet's checksum. */
   4751 	switch (sc->sc_src.sa.sa_family) {
   4752 	case AF_INET:
   4753 		ip->ip_len = htons(tlen - hlen);
   4754 		th->th_sum = 0;
   4755 		th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
   4756 		break;
   4757 #ifdef INET6
   4758 	case AF_INET6:
   4759 		ip6->ip6_plen = htons(tlen - hlen);
   4760 		th->th_sum = 0;
   4761 		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
   4762 		break;
   4763 #endif
   4764 	}
   4765 
   4766 	/*
   4767 	 * Fill in some straggling IP bits.  Note the stack expects
   4768 	 * ip_len to be in host order, for convenience.
   4769 	 */
   4770 	switch (sc->sc_src.sa.sa_family) {
   4771 #ifdef INET
   4772 	case AF_INET:
   4773 		ip->ip_len = htons(tlen);
   4774 		ip->ip_ttl = ip_defttl;
   4775 		/* XXX tos? */
   4776 		break;
   4777 #endif
   4778 #ifdef INET6
   4779 	case AF_INET6:
   4780 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
   4781 		ip6->ip6_vfc |= IPV6_VERSION;
   4782 		ip6->ip6_plen = htons(tlen - hlen);
   4783 		/* ip6_hlim will be initialized afterwards */
   4784 		/* XXX flowlabel? */
   4785 		break;
   4786 #endif
   4787 	}
   4788 
   4789 	/* XXX use IPsec policy on listening socket, on SYN ACK */
   4790 	tp = sc->sc_tp;
   4791 
   4792 	switch (sc->sc_src.sa.sa_family) {
   4793 #ifdef INET
   4794 	case AF_INET:
   4795 		error = ip_output(m, sc->sc_ipopts, ro,
   4796 		    (ip_mtudisc ? IP_MTUDISC : 0),
   4797 		    NULL, so);
   4798 		break;
   4799 #endif
   4800 #ifdef INET6
   4801 	case AF_INET6:
   4802 		ip6->ip6_hlim = in6_selecthlim(NULL,
   4803 				(rt = rtcache_validate(ro)) != NULL ? rt->rt_ifp
   4804 				                                    : NULL);
   4805 
   4806 		error = ip6_output(m, NULL /*XXX*/, ro, 0, NULL, so, NULL);
   4807 		break;
   4808 #endif
   4809 	default:
   4810 		error = EAFNOSUPPORT;
   4811 		break;
   4812 	}
   4813 	return (error);
   4814 }
   4815