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