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