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