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