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