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