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