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