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