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