Home | History | Annotate | Line # | Download | only in netinet
tcp_input.c revision 1.190
      1 /*	$NetBSD: tcp_input.c,v 1.190 2004/03/10 18:50:45 drochner 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.190 2004/03/10 18:50:45 drochner 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 				case AF_INET:
   1360 					if (ipsec4_in_reject_so(m, so)) {
   1361 						ipsecstat.in_polvio++;
   1362 						tp = NULL;
   1363 						goto dropwithreset;
   1364 					}
   1365 					break;
   1366 #ifdef INET6
   1367 				case AF_INET6:
   1368 					if (ipsec6_in_reject_so(m, so)) {
   1369 						ipsec6stat.in_polvio++;
   1370 						tp = NULL;
   1371 						goto dropwithreset;
   1372 					}
   1373 					break;
   1374 #endif
   1375 				}
   1376 #endif
   1377 
   1378 				/*
   1379 				 * LISTEN socket received a SYN
   1380 				 * from itself?  This can't possibly
   1381 				 * be valid; drop the packet.
   1382 				 */
   1383 				if (th->th_sport == th->th_dport) {
   1384 					int i;
   1385 
   1386 					switch (af) {
   1387 #ifdef INET
   1388 					case AF_INET:
   1389 						i = in_hosteq(ip->ip_src, ip->ip_dst);
   1390 						break;
   1391 #endif
   1392 #ifdef INET6
   1393 					case AF_INET6:
   1394 						i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst);
   1395 						break;
   1396 #endif
   1397 					default:
   1398 						i = 1;
   1399 					}
   1400 					if (i) {
   1401 						tcpstat.tcps_badsyn++;
   1402 						goto drop;
   1403 					}
   1404 				}
   1405 
   1406 				/*
   1407 				 * SYN looks ok; create compressed TCP
   1408 				 * state for it.
   1409 				 */
   1410 				if (so->so_qlen <= so->so_qlimit &&
   1411 				    syn_cache_add(&src.sa, &dst.sa, th, tlen,
   1412 						so, m, optp, optlen, &opti))
   1413 					m = NULL;
   1414 			}
   1415 			goto drop;
   1416 		}
   1417 	}
   1418 
   1419 after_listen:
   1420 #ifdef DIAGNOSTIC
   1421 	/*
   1422 	 * Should not happen now that all embryonic connections
   1423 	 * are handled with compressed state.
   1424 	 */
   1425 	if (tp->t_state == TCPS_LISTEN)
   1426 		panic("tcp_input: TCPS_LISTEN");
   1427 #endif
   1428 
   1429 	/*
   1430 	 * Segment received on connection.
   1431 	 * Reset idle time and keep-alive timer.
   1432 	 */
   1433 	tp->t_rcvtime = tcp_now;
   1434 	if (TCPS_HAVEESTABLISHED(tp->t_state))
   1435 		TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
   1436 
   1437 	/*
   1438 	 * Process options.
   1439 	 */
   1440 	if (optp)
   1441 		tcp_dooptions(tp, optp, optlen, th, &opti);
   1442 
   1443 	/*
   1444 	 * Header prediction: check for the two common cases
   1445 	 * of a uni-directional data xfer.  If the packet has
   1446 	 * no control flags, is in-sequence, the window didn't
   1447 	 * change and we're not retransmitting, it's a
   1448 	 * candidate.  If the length is zero and the ack moved
   1449 	 * forward, we're the sender side of the xfer.  Just
   1450 	 * free the data acked & wake any higher level process
   1451 	 * that was blocked waiting for space.  If the length
   1452 	 * is non-zero and the ack didn't move, we're the
   1453 	 * receiver side.  If we're getting packets in-order
   1454 	 * (the reassembly queue is empty), add the data to
   1455 	 * the socket buffer and note that we need a delayed ack.
   1456 	 */
   1457 	if (tp->t_state == TCPS_ESTABLISHED &&
   1458 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
   1459 	    (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
   1460 	    th->th_seq == tp->rcv_nxt &&
   1461 	    tiwin && tiwin == tp->snd_wnd &&
   1462 	    tp->snd_nxt == tp->snd_max) {
   1463 
   1464 		/*
   1465 		 * If last ACK falls within this segment's sequence numbers,
   1466 		 *  record the timestamp.
   1467 		 */
   1468 		if (opti.ts_present &&
   1469 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
   1470 		    SEQ_LT(tp->last_ack_sent, th->th_seq + tlen)) {
   1471 			tp->ts_recent_age = TCP_TIMESTAMP(tp);
   1472 			tp->ts_recent = opti.ts_val;
   1473 		}
   1474 
   1475 		if (tlen == 0) {
   1476 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
   1477 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
   1478 			    tp->snd_cwnd >= tp->snd_wnd &&
   1479 			    tp->t_dupacks < tcprexmtthresh) {
   1480 				/*
   1481 				 * this is a pure ack for outstanding data.
   1482 				 */
   1483 				++tcpstat.tcps_predack;
   1484 				if (opti.ts_present && opti.ts_ecr)
   1485 					tcp_xmit_timer(tp,
   1486 					  TCP_TIMESTAMP(tp) - opti.ts_ecr + 1);
   1487 				else if (tp->t_rtttime &&
   1488 				    SEQ_GT(th->th_ack, tp->t_rtseq))
   1489 					tcp_xmit_timer(tp,
   1490 					tcp_now - tp->t_rtttime);
   1491 				acked = th->th_ack - tp->snd_una;
   1492 				tcpstat.tcps_rcvackpack++;
   1493 				tcpstat.tcps_rcvackbyte += acked;
   1494 				ND6_HINT(tp);
   1495 
   1496 				if (acked > (tp->t_lastoff - tp->t_inoff))
   1497 					tp->t_lastm = NULL;
   1498 				sbdrop(&so->so_snd, acked);
   1499 				tp->t_lastoff -= acked;
   1500 
   1501 				/*
   1502 				 * We want snd_recover to track snd_una to
   1503 				 * avoid sequence wraparound problems for
   1504 				 * very large transfers.
   1505 				 */
   1506 				tp->snd_una = tp->snd_recover = th->th_ack;
   1507 				m_freem(m);
   1508 
   1509 				/*
   1510 				 * If all outstanding data are acked, stop
   1511 				 * retransmit timer, otherwise restart timer
   1512 				 * using current (possibly backed-off) value.
   1513 				 * If process is waiting for space,
   1514 				 * wakeup/selwakeup/signal.  If data
   1515 				 * are ready to send, let tcp_output
   1516 				 * decide between more output or persist.
   1517 				 */
   1518 				if (tp->snd_una == tp->snd_max)
   1519 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
   1520 				else if (TCP_TIMER_ISARMED(tp,
   1521 				    TCPT_PERSIST) == 0)
   1522 					TCP_TIMER_ARM(tp, TCPT_REXMT,
   1523 					    tp->t_rxtcur);
   1524 
   1525 				sowwakeup(so);
   1526 				if (so->so_snd.sb_cc)
   1527 					(void) tcp_output(tp);
   1528 				if (tcp_saveti)
   1529 					m_freem(tcp_saveti);
   1530 				return;
   1531 			}
   1532 		} else if (th->th_ack == tp->snd_una &&
   1533 		    TAILQ_FIRST(&tp->segq) == NULL &&
   1534 		    tlen <= sbspace(&so->so_rcv)) {
   1535 			/*
   1536 			 * this is a pure, in-sequence data packet
   1537 			 * with nothing on the reassembly queue and
   1538 			 * we have enough buffer space to take it.
   1539 			 */
   1540 			++tcpstat.tcps_preddat;
   1541 			tp->rcv_nxt += tlen;
   1542 			tcpstat.tcps_rcvpack++;
   1543 			tcpstat.tcps_rcvbyte += tlen;
   1544 			ND6_HINT(tp);
   1545 			/*
   1546 			 * Drop TCP, IP headers and TCP options then add data
   1547 			 * to socket buffer.
   1548 			 */
   1549 			if (so->so_state & SS_CANTRCVMORE)
   1550 				m_freem(m);
   1551 			else {
   1552 				m_adj(m, toff + off);
   1553 				sbappendstream(&so->so_rcv, m);
   1554 			}
   1555 			sorwakeup(so);
   1556 			TCP_SETUP_ACK(tp, th);
   1557 			if (tp->t_flags & TF_ACKNOW)
   1558 				(void) tcp_output(tp);
   1559 			if (tcp_saveti)
   1560 				m_freem(tcp_saveti);
   1561 			return;
   1562 		}
   1563 	}
   1564 
   1565 	/*
   1566 	 * Compute mbuf offset to TCP data segment.
   1567 	 */
   1568 	hdroptlen = toff + off;
   1569 
   1570 	/*
   1571 	 * Calculate amount of space in receive window,
   1572 	 * and then do TCP input processing.
   1573 	 * Receive window is amount of space in rcv queue,
   1574 	 * but not less than advertised window.
   1575 	 */
   1576 	{ int win;
   1577 
   1578 	win = sbspace(&so->so_rcv);
   1579 	if (win < 0)
   1580 		win = 0;
   1581 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
   1582 	}
   1583 
   1584 	switch (tp->t_state) {
   1585 	case TCPS_LISTEN:
   1586 		/*
   1587 		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
   1588 		 */
   1589 		if (m->m_flags & (M_BCAST|M_MCAST))
   1590 			goto drop;
   1591 		switch (af) {
   1592 #ifdef INET6
   1593 		case AF_INET6:
   1594 			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
   1595 				goto drop;
   1596 			break;
   1597 #endif /* INET6 */
   1598 		case AF_INET:
   1599 			if (IN_MULTICAST(ip->ip_dst.s_addr) ||
   1600 			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
   1601 				goto drop;
   1602 			break;
   1603 		}
   1604 		break;
   1605 
   1606 	/*
   1607 	 * If the state is SYN_SENT:
   1608 	 *	if seg contains an ACK, but not for our SYN, drop the input.
   1609 	 *	if seg contains a RST, then drop the connection.
   1610 	 *	if seg does not contain SYN, then drop it.
   1611 	 * Otherwise this is an acceptable SYN segment
   1612 	 *	initialize tp->rcv_nxt and tp->irs
   1613 	 *	if seg contains ack then advance tp->snd_una
   1614 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
   1615 	 *	arrange for segment to be acked (eventually)
   1616 	 *	continue processing rest of data/controls, beginning with URG
   1617 	 */
   1618 	case TCPS_SYN_SENT:
   1619 		if ((tiflags & TH_ACK) &&
   1620 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
   1621 		     SEQ_GT(th->th_ack, tp->snd_max)))
   1622 			goto dropwithreset;
   1623 		if (tiflags & TH_RST) {
   1624 			if (tiflags & TH_ACK)
   1625 				tp = tcp_drop(tp, ECONNREFUSED);
   1626 			goto drop;
   1627 		}
   1628 		if ((tiflags & TH_SYN) == 0)
   1629 			goto drop;
   1630 		if (tiflags & TH_ACK) {
   1631 			tp->snd_una = tp->snd_recover = th->th_ack;
   1632 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
   1633 				tp->snd_nxt = tp->snd_una;
   1634 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
   1635 		}
   1636 		tp->irs = th->th_seq;
   1637 		tcp_rcvseqinit(tp);
   1638 		tp->t_flags |= TF_ACKNOW;
   1639 		tcp_mss_from_peer(tp, opti.maxseg);
   1640 
   1641 		/*
   1642 		 * Initialize the initial congestion window.  If we
   1643 		 * had to retransmit the SYN, we must initialize cwnd
   1644 		 * to 1 segment (i.e. the Loss Window).
   1645 		 */
   1646 		if (tp->t_flags & TF_SYN_REXMT)
   1647 			tp->snd_cwnd = tp->t_peermss;
   1648 		else {
   1649 			int ss = tcp_init_win;
   1650 #ifdef INET
   1651 			if (inp != NULL && in_localaddr(inp->inp_faddr))
   1652 				ss = tcp_init_win_local;
   1653 #endif
   1654 #ifdef INET6
   1655 			if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
   1656 				ss = tcp_init_win_local;
   1657 #endif
   1658 			tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
   1659 		}
   1660 
   1661 		tcp_rmx_rtt(tp);
   1662 		if (tiflags & TH_ACK) {
   1663 			tcpstat.tcps_connects++;
   1664 			soisconnected(so);
   1665 			tcp_established(tp);
   1666 			/* Do window scaling on this connection? */
   1667 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   1668 			    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   1669 				tp->snd_scale = tp->requested_s_scale;
   1670 				tp->rcv_scale = tp->request_r_scale;
   1671 			}
   1672 			TCP_REASS_LOCK(tp);
   1673 			(void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
   1674 			TCP_REASS_UNLOCK(tp);
   1675 			/*
   1676 			 * if we didn't have to retransmit the SYN,
   1677 			 * use its rtt as our initial srtt & rtt var.
   1678 			 */
   1679 			if (tp->t_rtttime)
   1680 				tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
   1681 		} else
   1682 			tp->t_state = TCPS_SYN_RECEIVED;
   1683 
   1684 		/*
   1685 		 * Advance th->th_seq to correspond to first data byte.
   1686 		 * If data, trim to stay within window,
   1687 		 * dropping FIN if necessary.
   1688 		 */
   1689 		th->th_seq++;
   1690 		if (tlen > tp->rcv_wnd) {
   1691 			todrop = tlen - tp->rcv_wnd;
   1692 			m_adj(m, -todrop);
   1693 			tlen = tp->rcv_wnd;
   1694 			tiflags &= ~TH_FIN;
   1695 			tcpstat.tcps_rcvpackafterwin++;
   1696 			tcpstat.tcps_rcvbyteafterwin += todrop;
   1697 		}
   1698 		tp->snd_wl1 = th->th_seq - 1;
   1699 		tp->rcv_up = th->th_seq;
   1700 		goto step6;
   1701 
   1702 	/*
   1703 	 * If the state is SYN_RECEIVED:
   1704 	 *	If seg contains an ACK, but not for our SYN, drop the input
   1705 	 *	and generate an RST.  See page 36, rfc793
   1706 	 */
   1707 	case TCPS_SYN_RECEIVED:
   1708 		if ((tiflags & TH_ACK) &&
   1709 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
   1710 		     SEQ_GT(th->th_ack, tp->snd_max)))
   1711 			goto dropwithreset;
   1712 		break;
   1713 	}
   1714 
   1715 	/*
   1716 	 * States other than LISTEN or SYN_SENT.
   1717 	 * First check timestamp, if present.
   1718 	 * Then check that at least some bytes of segment are within
   1719 	 * receive window.  If segment begins before rcv_nxt,
   1720 	 * drop leading data (and SYN); if nothing left, just ack.
   1721 	 *
   1722 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
   1723 	 * and it's less than ts_recent, drop it.
   1724 	 */
   1725 	if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
   1726 	    TSTMP_LT(opti.ts_val, tp->ts_recent)) {
   1727 
   1728 		/* Check to see if ts_recent is over 24 days old.  */
   1729 		if ((int)(TCP_TIMESTAMP(tp) - tp->ts_recent_age) >
   1730 		    TCP_PAWS_IDLE) {
   1731 			/*
   1732 			 * Invalidate ts_recent.  If this segment updates
   1733 			 * ts_recent, the age will be reset later and ts_recent
   1734 			 * will get a valid value.  If it does not, setting
   1735 			 * ts_recent to zero will at least satisfy the
   1736 			 * requirement that zero be placed in the timestamp
   1737 			 * echo reply when ts_recent isn't valid.  The
   1738 			 * age isn't reset until we get a valid ts_recent
   1739 			 * because we don't want out-of-order segments to be
   1740 			 * dropped when ts_recent is old.
   1741 			 */
   1742 			tp->ts_recent = 0;
   1743 		} else {
   1744 			tcpstat.tcps_rcvduppack++;
   1745 			tcpstat.tcps_rcvdupbyte += tlen;
   1746 			tcpstat.tcps_pawsdrop++;
   1747 			goto dropafterack;
   1748 		}
   1749 	}
   1750 
   1751 	todrop = tp->rcv_nxt - th->th_seq;
   1752 	if (todrop > 0) {
   1753 		if (tiflags & TH_SYN) {
   1754 			tiflags &= ~TH_SYN;
   1755 			th->th_seq++;
   1756 			if (th->th_urp > 1)
   1757 				th->th_urp--;
   1758 			else {
   1759 				tiflags &= ~TH_URG;
   1760 				th->th_urp = 0;
   1761 			}
   1762 			todrop--;
   1763 		}
   1764 		if (todrop > tlen ||
   1765 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
   1766 			/*
   1767 			 * Any valid FIN must be to the left of the window.
   1768 			 * At this point the FIN must be a duplicate or
   1769 			 * out of sequence; drop it.
   1770 			 */
   1771 			tiflags &= ~TH_FIN;
   1772 			/*
   1773 			 * Send an ACK to resynchronize and drop any data.
   1774 			 * But keep on processing for RST or ACK.
   1775 			 */
   1776 			tp->t_flags |= TF_ACKNOW;
   1777 			todrop = tlen;
   1778 			tcpstat.tcps_rcvdupbyte += todrop;
   1779 			tcpstat.tcps_rcvduppack++;
   1780 		} else {
   1781 			tcpstat.tcps_rcvpartduppack++;
   1782 			tcpstat.tcps_rcvpartdupbyte += todrop;
   1783 		}
   1784 		hdroptlen += todrop;	/*drop from head afterwards*/
   1785 		th->th_seq += todrop;
   1786 		tlen -= todrop;
   1787 		if (th->th_urp > todrop)
   1788 			th->th_urp -= todrop;
   1789 		else {
   1790 			tiflags &= ~TH_URG;
   1791 			th->th_urp = 0;
   1792 		}
   1793 	}
   1794 
   1795 	/*
   1796 	 * If new data are received on a connection after the
   1797 	 * user processes are gone, then RST the other end.
   1798 	 */
   1799 	if ((so->so_state & SS_NOFDREF) &&
   1800 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
   1801 		tp = tcp_close(tp);
   1802 		tcpstat.tcps_rcvafterclose++;
   1803 		goto dropwithreset;
   1804 	}
   1805 
   1806 	/*
   1807 	 * If segment ends after window, drop trailing data
   1808 	 * (and PUSH and FIN); if nothing left, just ACK.
   1809 	 */
   1810 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
   1811 	if (todrop > 0) {
   1812 		tcpstat.tcps_rcvpackafterwin++;
   1813 		if (todrop >= tlen) {
   1814 			tcpstat.tcps_rcvbyteafterwin += tlen;
   1815 			/*
   1816 			 * If a new connection request is received
   1817 			 * while in TIME_WAIT, drop the old connection
   1818 			 * and start over if the sequence numbers
   1819 			 * are above the previous ones.
   1820 			 *
   1821 			 * NOTE: We will checksum the packet again, and
   1822 			 * so we need to put the header fields back into
   1823 			 * network order!
   1824 			 * XXX This kind of sucks, but we don't expect
   1825 			 * XXX this to happen very often, so maybe it
   1826 			 * XXX doesn't matter so much.
   1827 			 */
   1828 			if (tiflags & TH_SYN &&
   1829 			    tp->t_state == TCPS_TIME_WAIT &&
   1830 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
   1831 				iss = tcp_new_iss(tp, tp->snd_nxt);
   1832 				tp = tcp_close(tp);
   1833 				TCP_FIELDS_TO_NET(th);
   1834 				goto findpcb;
   1835 			}
   1836 			/*
   1837 			 * If window is closed can only take segments at
   1838 			 * window edge, and have to drop data and PUSH from
   1839 			 * incoming segments.  Continue processing, but
   1840 			 * remember to ack.  Otherwise, drop segment
   1841 			 * and ack.
   1842 			 */
   1843 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
   1844 				tp->t_flags |= TF_ACKNOW;
   1845 				tcpstat.tcps_rcvwinprobe++;
   1846 			} else
   1847 				goto dropafterack;
   1848 		} else
   1849 			tcpstat.tcps_rcvbyteafterwin += todrop;
   1850 		m_adj(m, -todrop);
   1851 		tlen -= todrop;
   1852 		tiflags &= ~(TH_PUSH|TH_FIN);
   1853 	}
   1854 
   1855 	/*
   1856 	 * If last ACK falls within this segment's sequence numbers,
   1857 	 * and the timestamp is newer, record it.
   1858 	 */
   1859 	if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
   1860 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
   1861 	    SEQ_LT(tp->last_ack_sent, th->th_seq + tlen +
   1862 		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
   1863 		tp->ts_recent_age = TCP_TIMESTAMP(tp);
   1864 		tp->ts_recent = opti.ts_val;
   1865 	}
   1866 
   1867 	/*
   1868 	 * If the RST bit is set examine the state:
   1869 	 *    SYN_RECEIVED STATE:
   1870 	 *	If passive open, return to LISTEN state.
   1871 	 *	If active open, inform user that connection was refused.
   1872 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
   1873 	 *	Inform user that connection was reset, and close tcb.
   1874 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
   1875 	 *	Close the tcb.
   1876 	 */
   1877 	if (tiflags&TH_RST) switch (tp->t_state) {
   1878 
   1879 	case TCPS_SYN_RECEIVED:
   1880 		so->so_error = ECONNREFUSED;
   1881 		goto close;
   1882 
   1883 	case TCPS_ESTABLISHED:
   1884 	case TCPS_FIN_WAIT_1:
   1885 	case TCPS_FIN_WAIT_2:
   1886 	case TCPS_CLOSE_WAIT:
   1887 		so->so_error = ECONNRESET;
   1888 	close:
   1889 		tp->t_state = TCPS_CLOSED;
   1890 		tcpstat.tcps_drops++;
   1891 		tp = tcp_close(tp);
   1892 		goto drop;
   1893 
   1894 	case TCPS_CLOSING:
   1895 	case TCPS_LAST_ACK:
   1896 	case TCPS_TIME_WAIT:
   1897 		tp = tcp_close(tp);
   1898 		goto drop;
   1899 	}
   1900 
   1901 	/*
   1902 	 * If a SYN is in the window, then this is an
   1903 	 * error and we send an RST and drop the connection.
   1904 	 */
   1905 	if (tiflags & TH_SYN) {
   1906 		tp = tcp_drop(tp, ECONNRESET);
   1907 		goto dropwithreset;
   1908 	}
   1909 
   1910 	/*
   1911 	 * If the ACK bit is off we drop the segment and return.
   1912 	 */
   1913 	if ((tiflags & TH_ACK) == 0) {
   1914 		if (tp->t_flags & TF_ACKNOW)
   1915 			goto dropafterack;
   1916 		else
   1917 			goto drop;
   1918 	}
   1919 
   1920 	/*
   1921 	 * Ack processing.
   1922 	 */
   1923 	switch (tp->t_state) {
   1924 
   1925 	/*
   1926 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
   1927 	 * ESTABLISHED state and continue processing, otherwise
   1928 	 * send an RST.
   1929 	 */
   1930 	case TCPS_SYN_RECEIVED:
   1931 		if (SEQ_GT(tp->snd_una, th->th_ack) ||
   1932 		    SEQ_GT(th->th_ack, tp->snd_max))
   1933 			goto dropwithreset;
   1934 		tcpstat.tcps_connects++;
   1935 		soisconnected(so);
   1936 		tcp_established(tp);
   1937 		/* Do window scaling? */
   1938 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   1939 		    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   1940 			tp->snd_scale = tp->requested_s_scale;
   1941 			tp->rcv_scale = tp->request_r_scale;
   1942 		}
   1943 		TCP_REASS_LOCK(tp);
   1944 		(void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
   1945 		TCP_REASS_UNLOCK(tp);
   1946 		tp->snd_wl1 = th->th_seq - 1;
   1947 		/* fall into ... */
   1948 
   1949 	/*
   1950 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
   1951 	 * ACKs.  If the ack is in the range
   1952 	 *	tp->snd_una < th->th_ack <= tp->snd_max
   1953 	 * then advance tp->snd_una to th->th_ack and drop
   1954 	 * data from the retransmission queue.  If this ACK reflects
   1955 	 * more up to date window information we update our window information.
   1956 	 */
   1957 	case TCPS_ESTABLISHED:
   1958 	case TCPS_FIN_WAIT_1:
   1959 	case TCPS_FIN_WAIT_2:
   1960 	case TCPS_CLOSE_WAIT:
   1961 	case TCPS_CLOSING:
   1962 	case TCPS_LAST_ACK:
   1963 	case TCPS_TIME_WAIT:
   1964 
   1965 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
   1966 			if (tlen == 0 && tiwin == tp->snd_wnd) {
   1967 				tcpstat.tcps_rcvdupack++;
   1968 				/*
   1969 				 * If we have outstanding data (other than
   1970 				 * a window probe), this is a completely
   1971 				 * duplicate ack (ie, window info didn't
   1972 				 * change), the ack is the biggest we've
   1973 				 * seen and we've seen exactly our rexmt
   1974 				 * threshhold of them, assume a packet
   1975 				 * has been dropped and retransmit it.
   1976 				 * Kludge snd_nxt & the congestion
   1977 				 * window so we send only this one
   1978 				 * packet.
   1979 				 *
   1980 				 * We know we're losing at the current
   1981 				 * window size so do congestion avoidance
   1982 				 * (set ssthresh to half the current window
   1983 				 * and pull our congestion window back to
   1984 				 * the new ssthresh).
   1985 				 *
   1986 				 * Dup acks mean that packets have left the
   1987 				 * network (they're now cached at the receiver)
   1988 				 * so bump cwnd by the amount in the receiver
   1989 				 * to keep a constant cwnd packets in the
   1990 				 * network.
   1991 				 */
   1992 				if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
   1993 				    th->th_ack != tp->snd_una)
   1994 					tp->t_dupacks = 0;
   1995 				else if (++tp->t_dupacks == tcprexmtthresh) {
   1996 					tcp_seq onxt = tp->snd_nxt;
   1997 					u_int win =
   1998 					    min(tp->snd_wnd, tp->snd_cwnd) /
   1999 					    2 /	tp->t_segsz;
   2000 					if (tcp_do_newreno && SEQ_LT(th->th_ack,
   2001 					    tp->snd_recover)) {
   2002 						/*
   2003 						 * False fast retransmit after
   2004 						 * timeout.  Do not cut window.
   2005 						 */
   2006 						tp->snd_cwnd += tp->t_segsz;
   2007 						tp->t_dupacks = 0;
   2008 						(void) tcp_output(tp);
   2009 						goto drop;
   2010 					}
   2011 
   2012 					if (win < 2)
   2013 						win = 2;
   2014 					tp->snd_ssthresh = win * tp->t_segsz;
   2015 					tp->snd_recover = tp->snd_max;
   2016 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
   2017 					tp->t_rtttime = 0;
   2018 					tp->snd_nxt = th->th_ack;
   2019 					tp->snd_cwnd = tp->t_segsz;
   2020 					(void) tcp_output(tp);
   2021 					tp->snd_cwnd = tp->snd_ssthresh +
   2022 					       tp->t_segsz * tp->t_dupacks;
   2023 					if (SEQ_GT(onxt, tp->snd_nxt))
   2024 						tp->snd_nxt = onxt;
   2025 					goto drop;
   2026 				} else if (tp->t_dupacks > tcprexmtthresh) {
   2027 					tp->snd_cwnd += tp->t_segsz;
   2028 					(void) tcp_output(tp);
   2029 					goto drop;
   2030 				}
   2031 			} else
   2032 				tp->t_dupacks = 0;
   2033 			break;
   2034 		}
   2035 		/*
   2036 		 * If the congestion window was inflated to account
   2037 		 * for the other side's cached packets, retract it.
   2038 		 */
   2039 		if (tcp_do_newreno == 0) {
   2040 			if (tp->t_dupacks >= tcprexmtthresh &&
   2041 			    tp->snd_cwnd > tp->snd_ssthresh)
   2042 				tp->snd_cwnd = tp->snd_ssthresh;
   2043 			tp->t_dupacks = 0;
   2044 		} else if (tp->t_dupacks >= tcprexmtthresh &&
   2045 			   tcp_newreno(tp, th) == 0) {
   2046 			tp->snd_cwnd = tp->snd_ssthresh;
   2047 			/*
   2048 			 * Window inflation should have left us with approx.
   2049 			 * snd_ssthresh outstanding data.  But in case we
   2050 			 * would be inclined to send a burst, better to do
   2051 			 * it via the slow start mechanism.
   2052 			 */
   2053 			if (SEQ_SUB(tp->snd_max, th->th_ack) < tp->snd_ssthresh)
   2054 				tp->snd_cwnd = SEQ_SUB(tp->snd_max, th->th_ack)
   2055 				    + tp->t_segsz;
   2056 			tp->t_dupacks = 0;
   2057 		}
   2058 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
   2059 			tcpstat.tcps_rcvacktoomuch++;
   2060 			goto dropafterack;
   2061 		}
   2062 		acked = th->th_ack - tp->snd_una;
   2063 		tcpstat.tcps_rcvackpack++;
   2064 		tcpstat.tcps_rcvackbyte += acked;
   2065 
   2066 		/*
   2067 		 * If we have a timestamp reply, update smoothed
   2068 		 * round trip time.  If no timestamp is present but
   2069 		 * transmit timer is running and timed sequence
   2070 		 * number was acked, update smoothed round trip time.
   2071 		 * Since we now have an rtt measurement, cancel the
   2072 		 * timer backoff (cf., Phil Karn's retransmit alg.).
   2073 		 * Recompute the initial retransmit timer.
   2074 		 */
   2075 		if (opti.ts_present && opti.ts_ecr)
   2076 			tcp_xmit_timer(tp, TCP_TIMESTAMP(tp) - opti.ts_ecr + 1);
   2077 		else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
   2078 			tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
   2079 
   2080 		/*
   2081 		 * If all outstanding data is acked, stop retransmit
   2082 		 * timer and remember to restart (more output or persist).
   2083 		 * If there is more data to be acked, restart retransmit
   2084 		 * timer, using current (possibly backed-off) value.
   2085 		 */
   2086 		if (th->th_ack == tp->snd_max) {
   2087 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
   2088 			needoutput = 1;
   2089 		} else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
   2090 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   2091 		/*
   2092 		 * When new data is acked, open the congestion window.
   2093 		 * If the window gives us less than ssthresh packets
   2094 		 * in flight, open exponentially (segsz per packet).
   2095 		 * Otherwise open linearly: segsz per window
   2096 		 * (segsz^2 / cwnd per packet), plus a constant
   2097 		 * fraction of a packet (segsz/8) to help larger windows
   2098 		 * open quickly enough.
   2099 		 */
   2100 		{
   2101 		u_int cw = tp->snd_cwnd;
   2102 		u_int incr = tp->t_segsz;
   2103 
   2104 		if (cw > tp->snd_ssthresh)
   2105 			incr = incr * incr / cw;
   2106 		if (tcp_do_newreno == 0 || SEQ_GEQ(th->th_ack, tp->snd_recover))
   2107 			tp->snd_cwnd = min(cw + incr,
   2108 			    TCP_MAXWIN << tp->snd_scale);
   2109 		}
   2110 		ND6_HINT(tp);
   2111 		if (acked > so->so_snd.sb_cc) {
   2112 			tp->snd_wnd -= so->so_snd.sb_cc;
   2113 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
   2114 			ourfinisacked = 1;
   2115 		} else {
   2116 			if (acked > (tp->t_lastoff - tp->t_inoff))
   2117 				tp->t_lastm = NULL;
   2118 			sbdrop(&so->so_snd, acked);
   2119 			tp->t_lastoff -= acked;
   2120 			ourfinisacked = 0;
   2121 		}
   2122 		sowwakeup(so);
   2123 		/*
   2124 		 * We want snd_recover to track snd_una to
   2125 		 * avoid sequence wraparound problems for
   2126 		 * very large transfers.
   2127 		 */
   2128 		tp->snd_una = tp->snd_recover = th->th_ack;
   2129 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
   2130 			tp->snd_nxt = tp->snd_una;
   2131 
   2132 		switch (tp->t_state) {
   2133 
   2134 		/*
   2135 		 * In FIN_WAIT_1 STATE in addition to the processing
   2136 		 * for the ESTABLISHED state if our FIN is now acknowledged
   2137 		 * then enter FIN_WAIT_2.
   2138 		 */
   2139 		case TCPS_FIN_WAIT_1:
   2140 			if (ourfinisacked) {
   2141 				/*
   2142 				 * If we can't receive any more
   2143 				 * data, then closing user can proceed.
   2144 				 * Starting the timer is contrary to the
   2145 				 * specification, but if we don't get a FIN
   2146 				 * we'll hang forever.
   2147 				 */
   2148 				if (so->so_state & SS_CANTRCVMORE) {
   2149 					soisdisconnected(so);
   2150 					if (tcp_maxidle > 0)
   2151 						TCP_TIMER_ARM(tp, TCPT_2MSL,
   2152 						    tcp_maxidle);
   2153 				}
   2154 				tp->t_state = TCPS_FIN_WAIT_2;
   2155 			}
   2156 			break;
   2157 
   2158 	 	/*
   2159 		 * In CLOSING STATE in addition to the processing for
   2160 		 * the ESTABLISHED state if the ACK acknowledges our FIN
   2161 		 * then enter the TIME-WAIT state, otherwise ignore
   2162 		 * the segment.
   2163 		 */
   2164 		case TCPS_CLOSING:
   2165 			if (ourfinisacked) {
   2166 				tp->t_state = TCPS_TIME_WAIT;
   2167 				tcp_canceltimers(tp);
   2168 				TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   2169 				soisdisconnected(so);
   2170 			}
   2171 			break;
   2172 
   2173 		/*
   2174 		 * In LAST_ACK, we may still be waiting for data to drain
   2175 		 * and/or to be acked, as well as for the ack of our FIN.
   2176 		 * If our FIN is now acknowledged, delete the TCB,
   2177 		 * enter the closed state and return.
   2178 		 */
   2179 		case TCPS_LAST_ACK:
   2180 			if (ourfinisacked) {
   2181 				tp = tcp_close(tp);
   2182 				goto drop;
   2183 			}
   2184 			break;
   2185 
   2186 		/*
   2187 		 * In TIME_WAIT state the only thing that should arrive
   2188 		 * is a retransmission of the remote FIN.  Acknowledge
   2189 		 * it and restart the finack timer.
   2190 		 */
   2191 		case TCPS_TIME_WAIT:
   2192 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   2193 			goto dropafterack;
   2194 		}
   2195 	}
   2196 
   2197 step6:
   2198 	/*
   2199 	 * Update window information.
   2200 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
   2201 	 */
   2202 	if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
   2203 	    (tp->snd_wl1 == th->th_seq && SEQ_LT(tp->snd_wl2, th->th_ack)) ||
   2204 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))) {
   2205 		/* keep track of pure window updates */
   2206 		if (tlen == 0 &&
   2207 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
   2208 			tcpstat.tcps_rcvwinupd++;
   2209 		tp->snd_wnd = tiwin;
   2210 		tp->snd_wl1 = th->th_seq;
   2211 		tp->snd_wl2 = th->th_ack;
   2212 		if (tp->snd_wnd > tp->max_sndwnd)
   2213 			tp->max_sndwnd = tp->snd_wnd;
   2214 		needoutput = 1;
   2215 	}
   2216 
   2217 	/*
   2218 	 * Process segments with URG.
   2219 	 */
   2220 	if ((tiflags & TH_URG) && th->th_urp &&
   2221 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   2222 		/*
   2223 		 * This is a kludge, but if we receive and accept
   2224 		 * random urgent pointers, we'll crash in
   2225 		 * soreceive.  It's hard to imagine someone
   2226 		 * actually wanting to send this much urgent data.
   2227 		 */
   2228 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
   2229 			th->th_urp = 0;			/* XXX */
   2230 			tiflags &= ~TH_URG;		/* XXX */
   2231 			goto dodata;			/* XXX */
   2232 		}
   2233 		/*
   2234 		 * If this segment advances the known urgent pointer,
   2235 		 * then mark the data stream.  This should not happen
   2236 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
   2237 		 * a FIN has been received from the remote side.
   2238 		 * In these states we ignore the URG.
   2239 		 *
   2240 		 * According to RFC961 (Assigned Protocols),
   2241 		 * the urgent pointer points to the last octet
   2242 		 * of urgent data.  We continue, however,
   2243 		 * to consider it to indicate the first octet
   2244 		 * of data past the urgent section as the original
   2245 		 * spec states (in one of two places).
   2246 		 */
   2247 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
   2248 			tp->rcv_up = th->th_seq + th->th_urp;
   2249 			so->so_oobmark = so->so_rcv.sb_cc +
   2250 			    (tp->rcv_up - tp->rcv_nxt) - 1;
   2251 			if (so->so_oobmark == 0)
   2252 				so->so_state |= SS_RCVATMARK;
   2253 			sohasoutofband(so);
   2254 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
   2255 		}
   2256 		/*
   2257 		 * Remove out of band data so doesn't get presented to user.
   2258 		 * This can happen independent of advancing the URG pointer,
   2259 		 * but if two URG's are pending at once, some out-of-band
   2260 		 * data may creep in... ick.
   2261 		 */
   2262 		if (th->th_urp <= (u_int16_t) tlen
   2263 #ifdef SO_OOBINLINE
   2264 		     && (so->so_options & SO_OOBINLINE) == 0
   2265 #endif
   2266 		     )
   2267 			tcp_pulloutofband(so, th, m, hdroptlen);
   2268 	} else
   2269 		/*
   2270 		 * If no out of band data is expected,
   2271 		 * pull receive urgent pointer along
   2272 		 * with the receive window.
   2273 		 */
   2274 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
   2275 			tp->rcv_up = tp->rcv_nxt;
   2276 dodata:							/* XXX */
   2277 
   2278 	/*
   2279 	 * Process the segment text, merging it into the TCP sequencing queue,
   2280 	 * and arranging for acknowledgement of receipt if necessary.
   2281 	 * This process logically involves adjusting tp->rcv_wnd as data
   2282 	 * is presented to the user (this happens in tcp_usrreq.c,
   2283 	 * case PRU_RCVD).  If a FIN has already been received on this
   2284 	 * connection then we just ignore the text.
   2285 	 */
   2286 	if ((tlen || (tiflags & TH_FIN)) &&
   2287 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   2288 		/*
   2289 		 * Insert segment ti into reassembly queue of tcp with
   2290 		 * control block tp.  Return TH_FIN if reassembly now includes
   2291 		 * a segment with FIN.  The macro form does the common case
   2292 		 * inline (segment is the next to be received on an
   2293 		 * established connection, and the queue is empty),
   2294 		 * avoiding linkage into and removal from the queue and
   2295 		 * repetition of various conversions.
   2296 		 * Set DELACK for segments received in order, but ack
   2297 		 * immediately when segments are out of order
   2298 		 * (so fast retransmit can work).
   2299 		 */
   2300 		/* NOTE: this was TCP_REASS() macro, but used only once */
   2301 		TCP_REASS_LOCK(tp);
   2302 		if (th->th_seq == tp->rcv_nxt &&
   2303 		    TAILQ_FIRST(&tp->segq) == NULL &&
   2304 		    tp->t_state == TCPS_ESTABLISHED) {
   2305 			TCP_SETUP_ACK(tp, th);
   2306 			tp->rcv_nxt += tlen;
   2307 			tiflags = th->th_flags & TH_FIN;
   2308 			tcpstat.tcps_rcvpack++;
   2309 			tcpstat.tcps_rcvbyte += tlen;
   2310 			ND6_HINT(tp);
   2311 			if (so->so_state & SS_CANTRCVMORE)
   2312 				m_freem(m);
   2313 			else {
   2314 				m_adj(m, hdroptlen);
   2315 				sbappendstream(&(so)->so_rcv, m);
   2316 			}
   2317 			sorwakeup(so);
   2318 		} else {
   2319 			m_adj(m, hdroptlen);
   2320 			tiflags = tcp_reass(tp, th, m, &tlen);
   2321 			tp->t_flags |= TF_ACKNOW;
   2322 		}
   2323 		TCP_REASS_UNLOCK(tp);
   2324 
   2325 		/*
   2326 		 * Note the amount of data that peer has sent into
   2327 		 * our window, in order to estimate the sender's
   2328 		 * buffer size.
   2329 		 */
   2330 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
   2331 	} else {
   2332 		m_freem(m);
   2333 		m = NULL;
   2334 		tiflags &= ~TH_FIN;
   2335 	}
   2336 
   2337 	/*
   2338 	 * If FIN is received ACK the FIN and let the user know
   2339 	 * that the connection is closing.  Ignore a FIN received before
   2340 	 * the connection is fully established.
   2341 	 */
   2342 	if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
   2343 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   2344 			socantrcvmore(so);
   2345 			tp->t_flags |= TF_ACKNOW;
   2346 			tp->rcv_nxt++;
   2347 		}
   2348 		switch (tp->t_state) {
   2349 
   2350 	 	/*
   2351 		 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
   2352 		 */
   2353 		case TCPS_ESTABLISHED:
   2354 			tp->t_state = TCPS_CLOSE_WAIT;
   2355 			break;
   2356 
   2357 	 	/*
   2358 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
   2359 		 * enter the CLOSING state.
   2360 		 */
   2361 		case TCPS_FIN_WAIT_1:
   2362 			tp->t_state = TCPS_CLOSING;
   2363 			break;
   2364 
   2365 	 	/*
   2366 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
   2367 		 * starting the time-wait timer, turning off the other
   2368 		 * standard timers.
   2369 		 */
   2370 		case TCPS_FIN_WAIT_2:
   2371 			tp->t_state = TCPS_TIME_WAIT;
   2372 			tcp_canceltimers(tp);
   2373 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   2374 			soisdisconnected(so);
   2375 			break;
   2376 
   2377 		/*
   2378 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
   2379 		 */
   2380 		case TCPS_TIME_WAIT:
   2381 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   2382 			break;
   2383 		}
   2384 	}
   2385 #ifdef TCP_DEBUG
   2386 	if (so->so_options & SO_DEBUG)
   2387 		tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
   2388 #endif
   2389 
   2390 	/*
   2391 	 * Return any desired output.
   2392 	 */
   2393 	if (needoutput || (tp->t_flags & TF_ACKNOW))
   2394 		(void) tcp_output(tp);
   2395 	if (tcp_saveti)
   2396 		m_freem(tcp_saveti);
   2397 	return;
   2398 
   2399 badsyn:
   2400 	/*
   2401 	 * Received a bad SYN.  Increment counters and dropwithreset.
   2402 	 */
   2403 	tcpstat.tcps_badsyn++;
   2404 	tp = NULL;
   2405 	goto dropwithreset;
   2406 
   2407 dropafterack:
   2408 	/*
   2409 	 * Generate an ACK dropping incoming segment if it occupies
   2410 	 * sequence space, where the ACK reflects our state.
   2411 	 */
   2412 	if (tiflags & TH_RST)
   2413 		goto drop;
   2414 	m_freem(m);
   2415 	tp->t_flags |= TF_ACKNOW;
   2416 	(void) tcp_output(tp);
   2417 	if (tcp_saveti)
   2418 		m_freem(tcp_saveti);
   2419 	return;
   2420 
   2421 dropwithreset_ratelim:
   2422 	/*
   2423 	 * We may want to rate-limit RSTs in certain situations,
   2424 	 * particularly if we are sending an RST in response to
   2425 	 * an attempt to connect to or otherwise communicate with
   2426 	 * a port for which we have no socket.
   2427 	 */
   2428 	if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
   2429 	    tcp_rst_ppslim) == 0) {
   2430 		/* XXX stat */
   2431 		goto drop;
   2432 	}
   2433 	/* ...fall into dropwithreset... */
   2434 
   2435 dropwithreset:
   2436 	/*
   2437 	 * Generate a RST, dropping incoming segment.
   2438 	 * Make ACK acceptable to originator of segment.
   2439 	 */
   2440 	if (tiflags & TH_RST)
   2441 		goto drop;
   2442 
   2443 	switch (af) {
   2444 #ifdef INET6
   2445 	case AF_INET6:
   2446 		/* For following calls to tcp_respond */
   2447 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
   2448 			goto drop;
   2449 		break;
   2450 #endif /* INET6 */
   2451 	case AF_INET:
   2452 		if (IN_MULTICAST(ip->ip_dst.s_addr) ||
   2453 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
   2454 			goto drop;
   2455 	}
   2456 
   2457 	if (tiflags & TH_ACK)
   2458 		(void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
   2459 	else {
   2460 		if (tiflags & TH_SYN)
   2461 			tlen++;
   2462 		(void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
   2463 		    TH_RST|TH_ACK);
   2464 	}
   2465 	if (tcp_saveti)
   2466 		m_freem(tcp_saveti);
   2467 	return;
   2468 
   2469 badcsum:
   2470 	tcpstat.tcps_rcvbadsum++;
   2471 drop:
   2472 	/*
   2473 	 * Drop space held by incoming segment and return.
   2474 	 */
   2475 	if (tp) {
   2476 		if (tp->t_inpcb)
   2477 			so = tp->t_inpcb->inp_socket;
   2478 #ifdef INET6
   2479 		else if (tp->t_in6pcb)
   2480 			so = tp->t_in6pcb->in6p_socket;
   2481 #endif
   2482 		else
   2483 			so = NULL;
   2484 #ifdef TCP_DEBUG
   2485 		if (so && (so->so_options & SO_DEBUG) != 0)
   2486 			tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
   2487 #endif
   2488 	}
   2489 	if (tcp_saveti)
   2490 		m_freem(tcp_saveti);
   2491 	m_freem(m);
   2492 	return;
   2493 }
   2494 
   2495 void
   2496 tcp_dooptions(tp, cp, cnt, th, oi)
   2497 	struct tcpcb *tp;
   2498 	u_char *cp;
   2499 	int cnt;
   2500 	struct tcphdr *th;
   2501 	struct tcp_opt_info *oi;
   2502 {
   2503 	u_int16_t mss;
   2504 	int opt, optlen;
   2505 
   2506 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   2507 		opt = cp[0];
   2508 		if (opt == TCPOPT_EOL)
   2509 			break;
   2510 		if (opt == TCPOPT_NOP)
   2511 			optlen = 1;
   2512 		else {
   2513 			if (cnt < 2)
   2514 				break;
   2515 			optlen = cp[1];
   2516 			if (optlen < 2 || optlen > cnt)
   2517 				break;
   2518 		}
   2519 		switch (opt) {
   2520 
   2521 		default:
   2522 			continue;
   2523 
   2524 		case TCPOPT_MAXSEG:
   2525 			if (optlen != TCPOLEN_MAXSEG)
   2526 				continue;
   2527 			if (!(th->th_flags & TH_SYN))
   2528 				continue;
   2529 			bcopy(cp + 2, &mss, sizeof(mss));
   2530 			oi->maxseg = ntohs(mss);
   2531 			break;
   2532 
   2533 		case TCPOPT_WINDOW:
   2534 			if (optlen != TCPOLEN_WINDOW)
   2535 				continue;
   2536 			if (!(th->th_flags & TH_SYN))
   2537 				continue;
   2538 			tp->t_flags |= TF_RCVD_SCALE;
   2539 			tp->requested_s_scale = cp[2];
   2540 			if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
   2541 #if 0	/*XXX*/
   2542 				char *p;
   2543 
   2544 				if (ip)
   2545 					p = ntohl(ip->ip_src);
   2546 #ifdef INET6
   2547 				else if (ip6)
   2548 					p = ip6_sprintf(&ip6->ip6_src);
   2549 #endif
   2550 				else
   2551 					p = "(unknown)";
   2552 				log(LOG_ERR, "TCP: invalid wscale %d from %s, "
   2553 				    "assuming %d\n",
   2554 				    tp->requested_s_scale, p,
   2555 				    TCP_MAX_WINSHIFT);
   2556 #else
   2557 				log(LOG_ERR, "TCP: invalid wscale %d, "
   2558 				    "assuming %d\n",
   2559 				    tp->requested_s_scale,
   2560 				    TCP_MAX_WINSHIFT);
   2561 #endif
   2562 				tp->requested_s_scale = TCP_MAX_WINSHIFT;
   2563 			}
   2564 			break;
   2565 
   2566 		case TCPOPT_TIMESTAMP:
   2567 			if (optlen != TCPOLEN_TIMESTAMP)
   2568 				continue;
   2569 			oi->ts_present = 1;
   2570 			bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
   2571 			NTOHL(oi->ts_val);
   2572 			bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
   2573 			NTOHL(oi->ts_ecr);
   2574 
   2575 			/*
   2576 			 * A timestamp received in a SYN makes
   2577 			 * it ok to send timestamp requests and replies.
   2578 			 */
   2579 			if (th->th_flags & TH_SYN) {
   2580 				tp->t_flags |= TF_RCVD_TSTMP;
   2581 				tp->ts_recent = oi->ts_val;
   2582 				tp->ts_recent_age = TCP_TIMESTAMP(tp);
   2583 			}
   2584 			break;
   2585 		case TCPOPT_SACK_PERMITTED:
   2586 			if (optlen != TCPOLEN_SACK_PERMITTED)
   2587 				continue;
   2588 			if (!(th->th_flags & TH_SYN))
   2589 				continue;
   2590 			tp->t_flags &= ~TF_CANT_TXSACK;
   2591 			break;
   2592 
   2593 		case TCPOPT_SACK:
   2594 			if (tp->t_flags & TF_IGNR_RXSACK)
   2595 				continue;
   2596 			if (optlen % 8 != 2 || optlen < 10)
   2597 				continue;
   2598 			cp += 2;
   2599 			optlen -= 2;
   2600 			for (; optlen > 0; cp -= 8, optlen -= 8) {
   2601 				tcp_seq lwe, rwe;
   2602 				bcopy((char *)cp, (char *) &lwe, sizeof(lwe));
   2603 				NTOHL(lwe);
   2604 				bcopy((char *)cp, (char *) &rwe, sizeof(rwe));
   2605 				NTOHL(rwe);
   2606 				/* tcp_mark_sacked(tp, lwe, rwe); */
   2607 			}
   2608 			break;
   2609 		}
   2610 	}
   2611 }
   2612 
   2613 /*
   2614  * Pull out of band byte out of a segment so
   2615  * it doesn't appear in the user's data queue.
   2616  * It is still reflected in the segment length for
   2617  * sequencing purposes.
   2618  */
   2619 void
   2620 tcp_pulloutofband(so, th, m, off)
   2621 	struct socket *so;
   2622 	struct tcphdr *th;
   2623 	struct mbuf *m;
   2624 	int off;
   2625 {
   2626 	int cnt = off + th->th_urp - 1;
   2627 
   2628 	while (cnt >= 0) {
   2629 		if (m->m_len > cnt) {
   2630 			char *cp = mtod(m, caddr_t) + cnt;
   2631 			struct tcpcb *tp = sototcpcb(so);
   2632 
   2633 			tp->t_iobc = *cp;
   2634 			tp->t_oobflags |= TCPOOB_HAVEDATA;
   2635 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
   2636 			m->m_len--;
   2637 			return;
   2638 		}
   2639 		cnt -= m->m_len;
   2640 		m = m->m_next;
   2641 		if (m == 0)
   2642 			break;
   2643 	}
   2644 	panic("tcp_pulloutofband");
   2645 }
   2646 
   2647 /*
   2648  * Collect new round-trip time estimate
   2649  * and update averages and current timeout.
   2650  */
   2651 void
   2652 tcp_xmit_timer(tp, rtt)
   2653 	struct tcpcb *tp;
   2654 	uint32_t rtt;
   2655 {
   2656 	int32_t delta;
   2657 
   2658 	tcpstat.tcps_rttupdated++;
   2659 	if (tp->t_srtt != 0) {
   2660 		/*
   2661 		 * srtt is stored as fixed point with 3 bits after the
   2662 		 * binary point (i.e., scaled by 8).  The following magic
   2663 		 * is equivalent to the smoothing algorithm in rfc793 with
   2664 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
   2665 		 * point).  Adjust rtt to origin 0.
   2666 		 */
   2667 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
   2668 		if ((tp->t_srtt += delta) <= 0)
   2669 			tp->t_srtt = 1 << 2;
   2670 		/*
   2671 		 * We accumulate a smoothed rtt variance (actually, a
   2672 		 * smoothed mean difference), then set the retransmit
   2673 		 * timer to smoothed rtt + 4 times the smoothed variance.
   2674 		 * rttvar is stored as fixed point with 2 bits after the
   2675 		 * binary point (scaled by 4).  The following is
   2676 		 * equivalent to rfc793 smoothing with an alpha of .75
   2677 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
   2678 		 * rfc793's wired-in beta.
   2679 		 */
   2680 		if (delta < 0)
   2681 			delta = -delta;
   2682 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
   2683 		if ((tp->t_rttvar += delta) <= 0)
   2684 			tp->t_rttvar = 1 << 2;
   2685 	} else {
   2686 		/*
   2687 		 * No rtt measurement yet - use the unsmoothed rtt.
   2688 		 * Set the variance to half the rtt (so our first
   2689 		 * retransmit happens at 3*rtt).
   2690 		 */
   2691 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
   2692 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
   2693 	}
   2694 	tp->t_rtttime = 0;
   2695 	tp->t_rxtshift = 0;
   2696 
   2697 	/*
   2698 	 * the retransmit should happen at rtt + 4 * rttvar.
   2699 	 * Because of the way we do the smoothing, srtt and rttvar
   2700 	 * will each average +1/2 tick of bias.  When we compute
   2701 	 * the retransmit timer, we want 1/2 tick of rounding and
   2702 	 * 1 extra tick because of +-1/2 tick uncertainty in the
   2703 	 * firing of the timer.  The bias will give us exactly the
   2704 	 * 1.5 tick we need.  But, because the bias is
   2705 	 * statistical, we have to test that we don't drop below
   2706 	 * the minimum feasible timer (which is 2 ticks).
   2707 	 */
   2708 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
   2709 	    max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
   2710 
   2711 	/*
   2712 	 * We received an ack for a packet that wasn't retransmitted;
   2713 	 * it is probably safe to discard any error indications we've
   2714 	 * received recently.  This isn't quite right, but close enough
   2715 	 * for now (a route might have failed after we sent a segment,
   2716 	 * and the return path might not be symmetrical).
   2717 	 */
   2718 	tp->t_softerror = 0;
   2719 }
   2720 
   2721 /*
   2722  * Checks for partial ack.  If partial ack arrives, force the retransmission
   2723  * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
   2724  * 1.  By setting snd_nxt to th_ack, this forces retransmission timer to
   2725  * be started again.  If the ack advances at least to tp->snd_recover, return 0.
   2726  */
   2727 int
   2728 tcp_newreno(tp, th)
   2729 	struct tcpcb *tp;
   2730 	struct tcphdr *th;
   2731 {
   2732 	tcp_seq onxt = tp->snd_nxt;
   2733 	u_long ocwnd = tp->snd_cwnd;
   2734 
   2735 	if (SEQ_LT(th->th_ack, tp->snd_recover)) {
   2736 		/*
   2737 		 * snd_una has not yet been updated and the socket's send
   2738 		 * buffer has not yet drained off the ACK'd data, so we
   2739 		 * have to leave snd_una as it was to get the correct data
   2740 		 * offset in tcp_output().
   2741 		 */
   2742 		TCP_TIMER_DISARM(tp, TCPT_REXMT);
   2743 		tp->t_rtttime = 0;
   2744 		tp->snd_nxt = th->th_ack;
   2745 		/*
   2746 		 * Set snd_cwnd to one segment beyond ACK'd offset.  snd_una
   2747 		 * is not yet updated when we're called.
   2748 		 */
   2749 		tp->snd_cwnd = tp->t_segsz + (th->th_ack - tp->snd_una);
   2750 		(void) tcp_output(tp);
   2751 		tp->snd_cwnd = ocwnd;
   2752 		if (SEQ_GT(onxt, tp->snd_nxt))
   2753 			tp->snd_nxt = onxt;
   2754 		/*
   2755 		 * Partial window deflation.  Relies on fact that tp->snd_una
   2756 		 * not updated yet.
   2757 		 */
   2758 		tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_segsz);
   2759 		return 1;
   2760 	}
   2761 	return 0;
   2762 }
   2763 
   2764 
   2765 /*
   2766  * TCP compressed state engine.  Currently used to hold compressed
   2767  * state for SYN_RECEIVED.
   2768  */
   2769 
   2770 u_long	syn_cache_count;
   2771 u_int32_t syn_hash1, syn_hash2;
   2772 
   2773 #define SYN_HASH(sa, sp, dp) \
   2774 	((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
   2775 				     ((u_int32_t)(sp)))^syn_hash2)))
   2776 #ifndef INET6
   2777 #define	SYN_HASHALL(hash, src, dst) \
   2778 do {									\
   2779 	hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr,	\
   2780 		((struct sockaddr_in *)(src))->sin_port,		\
   2781 		((struct sockaddr_in *)(dst))->sin_port);		\
   2782 } while (/*CONSTCOND*/ 0)
   2783 #else
   2784 #define SYN_HASH6(sa, sp, dp) \
   2785 	((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
   2786 	  (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
   2787 	 & 0x7fffffff)
   2788 
   2789 #define SYN_HASHALL(hash, src, dst) \
   2790 do {									\
   2791 	switch ((src)->sa_family) {					\
   2792 	case AF_INET:							\
   2793 		hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr, \
   2794 			((struct sockaddr_in *)(src))->sin_port,	\
   2795 			((struct sockaddr_in *)(dst))->sin_port);	\
   2796 		break;							\
   2797 	case AF_INET6:							\
   2798 		hash = SYN_HASH6(&((struct sockaddr_in6 *)(src))->sin6_addr, \
   2799 			((struct sockaddr_in6 *)(src))->sin6_port,	\
   2800 			((struct sockaddr_in6 *)(dst))->sin6_port);	\
   2801 		break;							\
   2802 	default:							\
   2803 		hash = 0;						\
   2804 	}								\
   2805 } while (/*CONSTCOND*/0)
   2806 #endif /* INET6 */
   2807 
   2808 #define	SYN_CACHE_RM(sc)						\
   2809 do {									\
   2810 	TAILQ_REMOVE(&tcp_syn_cache[(sc)->sc_bucketidx].sch_bucket,	\
   2811 	    (sc), sc_bucketq);						\
   2812 	(sc)->sc_tp = NULL;						\
   2813 	LIST_REMOVE((sc), sc_tpq);					\
   2814 	tcp_syn_cache[(sc)->sc_bucketidx].sch_length--;			\
   2815 	callout_stop(&(sc)->sc_timer);					\
   2816 	syn_cache_count--;						\
   2817 } while (/*CONSTCOND*/0)
   2818 
   2819 #define	SYN_CACHE_PUT(sc)						\
   2820 do {									\
   2821 	if ((sc)->sc_ipopts)						\
   2822 		(void) m_free((sc)->sc_ipopts);				\
   2823 	if ((sc)->sc_route4.ro_rt != NULL)				\
   2824 		RTFREE((sc)->sc_route4.ro_rt);				\
   2825 	if (callout_invoking(&(sc)->sc_timer))				\
   2826 		(sc)->sc_flags |= SCF_DEAD;				\
   2827 	else								\
   2828 		pool_put(&syn_cache_pool, (sc));			\
   2829 } while (/*CONSTCOND*/0)
   2830 
   2831 struct pool syn_cache_pool;
   2832 
   2833 /*
   2834  * We don't estimate RTT with SYNs, so each packet starts with the default
   2835  * RTT and each timer step has a fixed timeout value.
   2836  */
   2837 #define	SYN_CACHE_TIMER_ARM(sc)						\
   2838 do {									\
   2839 	TCPT_RANGESET((sc)->sc_rxtcur,					\
   2840 	    TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN,	\
   2841 	    TCPTV_REXMTMAX);						\
   2842 	callout_reset(&(sc)->sc_timer,					\
   2843 	    (sc)->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, (sc));	\
   2844 } while (/*CONSTCOND*/0)
   2845 
   2846 #define	SYN_CACHE_TIMESTAMP(sc)	(tcp_now - (sc)->sc_timebase)
   2847 
   2848 void
   2849 syn_cache_init()
   2850 {
   2851 	int i;
   2852 
   2853 	/* Initialize the hash buckets. */
   2854 	for (i = 0; i < tcp_syn_cache_size; i++)
   2855 		TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
   2856 
   2857 	/* Initialize the syn cache pool. */
   2858 	pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
   2859 	    "synpl", NULL);
   2860 }
   2861 
   2862 void
   2863 syn_cache_insert(sc, tp)
   2864 	struct syn_cache *sc;
   2865 	struct tcpcb *tp;
   2866 {
   2867 	struct syn_cache_head *scp;
   2868 	struct syn_cache *sc2;
   2869 	int s;
   2870 
   2871 	/*
   2872 	 * If there are no entries in the hash table, reinitialize
   2873 	 * the hash secrets.
   2874 	 */
   2875 	if (syn_cache_count == 0) {
   2876 		syn_hash1 = arc4random();
   2877 		syn_hash2 = arc4random();
   2878 	}
   2879 
   2880 	SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
   2881 	sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
   2882 	scp = &tcp_syn_cache[sc->sc_bucketidx];
   2883 
   2884 	/*
   2885 	 * Make sure that we don't overflow the per-bucket
   2886 	 * limit or the total cache size limit.
   2887 	 */
   2888 	s = splsoftnet();
   2889 	if (scp->sch_length >= tcp_syn_bucket_limit) {
   2890 		tcpstat.tcps_sc_bucketoverflow++;
   2891 		/*
   2892 		 * The bucket is full.  Toss the oldest element in the
   2893 		 * bucket.  This will be the first entry in the bucket.
   2894 		 */
   2895 		sc2 = TAILQ_FIRST(&scp->sch_bucket);
   2896 #ifdef DIAGNOSTIC
   2897 		/*
   2898 		 * This should never happen; we should always find an
   2899 		 * entry in our bucket.
   2900 		 */
   2901 		if (sc2 == NULL)
   2902 			panic("syn_cache_insert: bucketoverflow: impossible");
   2903 #endif
   2904 		SYN_CACHE_RM(sc2);
   2905 		SYN_CACHE_PUT(sc2);
   2906 	} else if (syn_cache_count >= tcp_syn_cache_limit) {
   2907 		struct syn_cache_head *scp2, *sce;
   2908 
   2909 		tcpstat.tcps_sc_overflowed++;
   2910 		/*
   2911 		 * The cache is full.  Toss the oldest entry in the
   2912 		 * first non-empty bucket we can find.
   2913 		 *
   2914 		 * XXX We would really like to toss the oldest
   2915 		 * entry in the cache, but we hope that this
   2916 		 * condition doesn't happen very often.
   2917 		 */
   2918 		scp2 = scp;
   2919 		if (TAILQ_EMPTY(&scp2->sch_bucket)) {
   2920 			sce = &tcp_syn_cache[tcp_syn_cache_size];
   2921 			for (++scp2; scp2 != scp; scp2++) {
   2922 				if (scp2 >= sce)
   2923 					scp2 = &tcp_syn_cache[0];
   2924 				if (! TAILQ_EMPTY(&scp2->sch_bucket))
   2925 					break;
   2926 			}
   2927 #ifdef DIAGNOSTIC
   2928 			/*
   2929 			 * This should never happen; we should always find a
   2930 			 * non-empty bucket.
   2931 			 */
   2932 			if (scp2 == scp)
   2933 				panic("syn_cache_insert: cacheoverflow: "
   2934 				    "impossible");
   2935 #endif
   2936 		}
   2937 		sc2 = TAILQ_FIRST(&scp2->sch_bucket);
   2938 		SYN_CACHE_RM(sc2);
   2939 		SYN_CACHE_PUT(sc2);
   2940 	}
   2941 
   2942 	/*
   2943 	 * Initialize the entry's timer.
   2944 	 */
   2945 	sc->sc_rxttot = 0;
   2946 	sc->sc_rxtshift = 0;
   2947 	SYN_CACHE_TIMER_ARM(sc);
   2948 
   2949 	/* Link it from tcpcb entry */
   2950 	LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
   2951 
   2952 	/* Put it into the bucket. */
   2953 	TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
   2954 	scp->sch_length++;
   2955 	syn_cache_count++;
   2956 
   2957 	tcpstat.tcps_sc_added++;
   2958 	splx(s);
   2959 }
   2960 
   2961 /*
   2962  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
   2963  * If we have retransmitted an entry the maximum number of times, expire
   2964  * that entry.
   2965  */
   2966 void
   2967 syn_cache_timer(void *arg)
   2968 {
   2969 	struct syn_cache *sc = arg;
   2970 	int s;
   2971 
   2972 	s = splsoftnet();
   2973 	callout_ack(&sc->sc_timer);
   2974 
   2975 	if (__predict_false(sc->sc_flags & SCF_DEAD)) {
   2976 		tcpstat.tcps_sc_delayed_free++;
   2977 		pool_put(&syn_cache_pool, sc);
   2978 		splx(s);
   2979 		return;
   2980 	}
   2981 
   2982 	if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
   2983 		/* Drop it -- too many retransmissions. */
   2984 		goto dropit;
   2985 	}
   2986 
   2987 	/*
   2988 	 * Compute the total amount of time this entry has
   2989 	 * been on a queue.  If this entry has been on longer
   2990 	 * than the keep alive timer would allow, expire it.
   2991 	 */
   2992 	sc->sc_rxttot += sc->sc_rxtcur;
   2993 	if (sc->sc_rxttot >= TCPTV_KEEP_INIT)
   2994 		goto dropit;
   2995 
   2996 	tcpstat.tcps_sc_retransmitted++;
   2997 	(void) syn_cache_respond(sc, NULL);
   2998 
   2999 	/* Advance the timer back-off. */
   3000 	sc->sc_rxtshift++;
   3001 	SYN_CACHE_TIMER_ARM(sc);
   3002 
   3003 	splx(s);
   3004 	return;
   3005 
   3006  dropit:
   3007 	tcpstat.tcps_sc_timed_out++;
   3008 	SYN_CACHE_RM(sc);
   3009 	SYN_CACHE_PUT(sc);
   3010 	splx(s);
   3011 }
   3012 
   3013 /*
   3014  * Remove syn cache created by the specified tcb entry,
   3015  * because this does not make sense to keep them
   3016  * (if there's no tcb entry, syn cache entry will never be used)
   3017  */
   3018 void
   3019 syn_cache_cleanup(tp)
   3020 	struct tcpcb *tp;
   3021 {
   3022 	struct syn_cache *sc, *nsc;
   3023 	int s;
   3024 
   3025 	s = splsoftnet();
   3026 
   3027 	for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
   3028 		nsc = LIST_NEXT(sc, sc_tpq);
   3029 
   3030 #ifdef DIAGNOSTIC
   3031 		if (sc->sc_tp != tp)
   3032 			panic("invalid sc_tp in syn_cache_cleanup");
   3033 #endif
   3034 		SYN_CACHE_RM(sc);
   3035 		SYN_CACHE_PUT(sc);
   3036 	}
   3037 	/* just for safety */
   3038 	LIST_INIT(&tp->t_sc);
   3039 
   3040 	splx(s);
   3041 }
   3042 
   3043 /*
   3044  * Find an entry in the syn cache.
   3045  */
   3046 struct syn_cache *
   3047 syn_cache_lookup(src, dst, headp)
   3048 	struct sockaddr *src;
   3049 	struct sockaddr *dst;
   3050 	struct syn_cache_head **headp;
   3051 {
   3052 	struct syn_cache *sc;
   3053 	struct syn_cache_head *scp;
   3054 	u_int32_t hash;
   3055 	int s;
   3056 
   3057 	SYN_HASHALL(hash, src, dst);
   3058 
   3059 	scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
   3060 	*headp = scp;
   3061 	s = splsoftnet();
   3062 	for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
   3063 	     sc = TAILQ_NEXT(sc, sc_bucketq)) {
   3064 		if (sc->sc_hash != hash)
   3065 			continue;
   3066 		if (!bcmp(&sc->sc_src, src, src->sa_len) &&
   3067 		    !bcmp(&sc->sc_dst, dst, dst->sa_len)) {
   3068 			splx(s);
   3069 			return (sc);
   3070 		}
   3071 	}
   3072 	splx(s);
   3073 	return (NULL);
   3074 }
   3075 
   3076 /*
   3077  * This function gets called when we receive an ACK for a
   3078  * socket in the LISTEN state.  We look up the connection
   3079  * in the syn cache, and if its there, we pull it out of
   3080  * the cache and turn it into a full-blown connection in
   3081  * the SYN-RECEIVED state.
   3082  *
   3083  * The return values may not be immediately obvious, and their effects
   3084  * can be subtle, so here they are:
   3085  *
   3086  *	NULL	SYN was not found in cache; caller should drop the
   3087  *		packet and send an RST.
   3088  *
   3089  *	-1	We were unable to create the new connection, and are
   3090  *		aborting it.  An ACK,RST is being sent to the peer
   3091  *		(unless we got screwey sequence numbners; see below),
   3092  *		because the 3-way handshake has been completed.  Caller
   3093  *		should not free the mbuf, since we may be using it.  If
   3094  *		we are not, we will free it.
   3095  *
   3096  *	Otherwise, the return value is a pointer to the new socket
   3097  *	associated with the connection.
   3098  */
   3099 struct socket *
   3100 syn_cache_get(src, dst, th, hlen, tlen, so, m)
   3101 	struct sockaddr *src;
   3102 	struct sockaddr *dst;
   3103 	struct tcphdr *th;
   3104 	unsigned int hlen, tlen;
   3105 	struct socket *so;
   3106 	struct mbuf *m;
   3107 {
   3108 	struct syn_cache *sc;
   3109 	struct syn_cache_head *scp;
   3110 	struct inpcb *inp = NULL;
   3111 #ifdef INET6
   3112 	struct in6pcb *in6p = NULL;
   3113 #endif
   3114 	struct tcpcb *tp = 0;
   3115 	struct mbuf *am;
   3116 	int s;
   3117 	struct socket *oso;
   3118 
   3119 	s = splsoftnet();
   3120 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
   3121 		splx(s);
   3122 		return (NULL);
   3123 	}
   3124 
   3125 	/*
   3126 	 * Verify the sequence and ack numbers.  Try getting the correct
   3127 	 * response again.
   3128 	 */
   3129 	if ((th->th_ack != sc->sc_iss + 1) ||
   3130 	    SEQ_LEQ(th->th_seq, sc->sc_irs) ||
   3131 	    SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
   3132 		(void) syn_cache_respond(sc, m);
   3133 		splx(s);
   3134 		return ((struct socket *)(-1));
   3135 	}
   3136 
   3137 	/* Remove this cache entry */
   3138 	SYN_CACHE_RM(sc);
   3139 	splx(s);
   3140 
   3141 	/*
   3142 	 * Ok, create the full blown connection, and set things up
   3143 	 * as they would have been set up if we had created the
   3144 	 * connection when the SYN arrived.  If we can't create
   3145 	 * the connection, abort it.
   3146 	 */
   3147 	/*
   3148 	 * inp still has the OLD in_pcb stuff, set the
   3149 	 * v6-related flags on the new guy, too.   This is
   3150 	 * done particularly for the case where an AF_INET6
   3151 	 * socket is bound only to a port, and a v4 connection
   3152 	 * comes in on that port.
   3153 	 * we also copy the flowinfo from the original pcb
   3154 	 * to the new one.
   3155 	 */
   3156 	oso = so;
   3157 	so = sonewconn(so, SS_ISCONNECTED);
   3158 	if (so == NULL)
   3159 		goto resetandabort;
   3160 
   3161 	switch (so->so_proto->pr_domain->dom_family) {
   3162 #ifdef INET
   3163 	case AF_INET:
   3164 		inp = sotoinpcb(so);
   3165 		break;
   3166 #endif
   3167 #ifdef INET6
   3168 	case AF_INET6:
   3169 		in6p = sotoin6pcb(so);
   3170 		break;
   3171 #endif
   3172 	}
   3173 	switch (src->sa_family) {
   3174 #ifdef INET
   3175 	case AF_INET:
   3176 		if (inp) {
   3177 			inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
   3178 			inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
   3179 			inp->inp_options = ip_srcroute();
   3180 			in_pcbstate(inp, INP_BOUND);
   3181 			if (inp->inp_options == NULL) {
   3182 				inp->inp_options = sc->sc_ipopts;
   3183 				sc->sc_ipopts = NULL;
   3184 			}
   3185 		}
   3186 #ifdef INET6
   3187 		else if (in6p) {
   3188 			/* IPv4 packet to AF_INET6 socket */
   3189 			bzero(&in6p->in6p_laddr, sizeof(in6p->in6p_laddr));
   3190 			in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
   3191 			bcopy(&((struct sockaddr_in *)dst)->sin_addr,
   3192 				&in6p->in6p_laddr.s6_addr32[3],
   3193 				sizeof(((struct sockaddr_in *)dst)->sin_addr));
   3194 			in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
   3195 			in6totcpcb(in6p)->t_family = AF_INET;
   3196 			if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
   3197 				in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
   3198 			else
   3199 				in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
   3200 			in6_pcbstate(in6p, IN6P_BOUND);
   3201 		}
   3202 #endif
   3203 		break;
   3204 #endif
   3205 #ifdef INET6
   3206 	case AF_INET6:
   3207 		if (in6p) {
   3208 			in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
   3209 			in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
   3210 			in6_pcbstate(in6p, IN6P_BOUND);
   3211 		}
   3212 		break;
   3213 #endif
   3214 	}
   3215 #ifdef INET6
   3216 	if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
   3217 		struct in6pcb *oin6p = sotoin6pcb(oso);
   3218 		/* inherit socket options from the listening socket */
   3219 		in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
   3220 		if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
   3221 			m_freem(in6p->in6p_options);
   3222 			in6p->in6p_options = 0;
   3223 		}
   3224 		ip6_savecontrol(in6p, &in6p->in6p_options,
   3225 			mtod(m, struct ip6_hdr *), m);
   3226 	}
   3227 #endif
   3228 
   3229 #if defined(IPSEC) || defined(FAST_IPSEC)
   3230 	/*
   3231 	 * we make a copy of policy, instead of sharing the policy,
   3232 	 * for better behavior in terms of SA lookup and dead SA removal.
   3233 	 */
   3234 	if (inp) {
   3235 		/* copy old policy into new socket's */
   3236 		if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp, inp->inp_sp))
   3237 			printf("tcp_input: could not copy policy\n");
   3238 	}
   3239 #ifdef INET6
   3240 	else if (in6p) {
   3241 		/* copy old policy into new socket's */
   3242 		if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
   3243 		    in6p->in6p_sp))
   3244 			printf("tcp_input: could not copy policy\n");
   3245 	}
   3246 #endif
   3247 #endif
   3248 
   3249 	/*
   3250 	 * Give the new socket our cached route reference.
   3251 	 */
   3252 	if (inp)
   3253 		inp->inp_route = sc->sc_route4;		/* struct assignment */
   3254 #ifdef INET6
   3255 	else
   3256 		in6p->in6p_route = sc->sc_route6;
   3257 #endif
   3258 	sc->sc_route4.ro_rt = NULL;
   3259 
   3260 	am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
   3261 	if (am == NULL)
   3262 		goto resetandabort;
   3263 	MCLAIM(am, &tcp_mowner);
   3264 	am->m_len = src->sa_len;
   3265 	bcopy(src, mtod(am, caddr_t), src->sa_len);
   3266 	if (inp) {
   3267 		if (in_pcbconnect(inp, am)) {
   3268 			(void) m_free(am);
   3269 			goto resetandabort;
   3270 		}
   3271 	}
   3272 #ifdef INET6
   3273 	else if (in6p) {
   3274 		if (src->sa_family == AF_INET) {
   3275 			/* IPv4 packet to AF_INET6 socket */
   3276 			struct sockaddr_in6 *sin6;
   3277 			sin6 = mtod(am, struct sockaddr_in6 *);
   3278 			am->m_len = sizeof(*sin6);
   3279 			bzero(sin6, sizeof(*sin6));
   3280 			sin6->sin6_family = AF_INET6;
   3281 			sin6->sin6_len = sizeof(*sin6);
   3282 			sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
   3283 			sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
   3284 			bcopy(&((struct sockaddr_in *)src)->sin_addr,
   3285 				&sin6->sin6_addr.s6_addr32[3],
   3286 				sizeof(sin6->sin6_addr.s6_addr32[3]));
   3287 		}
   3288 		if (in6_pcbconnect(in6p, am)) {
   3289 			(void) m_free(am);
   3290 			goto resetandabort;
   3291 		}
   3292 	}
   3293 #endif
   3294 	else {
   3295 		(void) m_free(am);
   3296 		goto resetandabort;
   3297 	}
   3298 	(void) m_free(am);
   3299 
   3300 	if (inp)
   3301 		tp = intotcpcb(inp);
   3302 #ifdef INET6
   3303 	else if (in6p)
   3304 		tp = in6totcpcb(in6p);
   3305 #endif
   3306 	else
   3307 		tp = NULL;
   3308 	tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
   3309 	if (sc->sc_request_r_scale != 15) {
   3310 		tp->requested_s_scale = sc->sc_requested_s_scale;
   3311 		tp->request_r_scale = sc->sc_request_r_scale;
   3312 		tp->snd_scale = sc->sc_requested_s_scale;
   3313 		tp->rcv_scale = sc->sc_request_r_scale;
   3314 		tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
   3315 	}
   3316 	if (sc->sc_flags & SCF_TIMESTAMP)
   3317 		tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
   3318 	tp->ts_timebase = sc->sc_timebase;
   3319 
   3320 	tp->t_template = tcp_template(tp);
   3321 	if (tp->t_template == 0) {
   3322 		tp = tcp_drop(tp, ENOBUFS);	/* destroys socket */
   3323 		so = NULL;
   3324 		m_freem(m);
   3325 		goto abort;
   3326 	}
   3327 
   3328 	tp->iss = sc->sc_iss;
   3329 	tp->irs = sc->sc_irs;
   3330 	tcp_sendseqinit(tp);
   3331 	tcp_rcvseqinit(tp);
   3332 	tp->t_state = TCPS_SYN_RECEIVED;
   3333 	TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
   3334 	tcpstat.tcps_accepts++;
   3335 
   3336 	/* Initialize tp->t_ourmss before we deal with the peer's! */
   3337 	tp->t_ourmss = sc->sc_ourmaxseg;
   3338 	tcp_mss_from_peer(tp, sc->sc_peermaxseg);
   3339 
   3340 	/*
   3341 	 * Initialize the initial congestion window.  If we
   3342 	 * had to retransmit the SYN,ACK, we must initialize cwnd
   3343 	 * to 1 segment (i.e. the Loss Window).
   3344 	 */
   3345 	if (sc->sc_rxtshift)
   3346 		tp->snd_cwnd = tp->t_peermss;
   3347 	else {
   3348 		int ss = tcp_init_win;
   3349 #ifdef INET
   3350 		if (inp != NULL && in_localaddr(inp->inp_faddr))
   3351 			ss = tcp_init_win_local;
   3352 #endif
   3353 #ifdef INET6
   3354 		if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
   3355 			ss = tcp_init_win_local;
   3356 #endif
   3357 		tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
   3358 	}
   3359 
   3360 	tcp_rmx_rtt(tp);
   3361 	tp->snd_wl1 = sc->sc_irs;
   3362 	tp->rcv_up = sc->sc_irs + 1;
   3363 
   3364 	/*
   3365 	 * This is what whould have happened in tcp_output() when
   3366 	 * the SYN,ACK was sent.
   3367 	 */
   3368 	tp->snd_up = tp->snd_una;
   3369 	tp->snd_max = tp->snd_nxt = tp->iss+1;
   3370 	TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   3371 	if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
   3372 		tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
   3373 	tp->last_ack_sent = tp->rcv_nxt;
   3374 
   3375 	tcpstat.tcps_sc_completed++;
   3376 	SYN_CACHE_PUT(sc);
   3377 	return (so);
   3378 
   3379 resetandabort:
   3380 	(void) tcp_respond(NULL, m, m, th,
   3381 			   th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
   3382 abort:
   3383 	if (so != NULL)
   3384 		(void) soabort(so);
   3385 	SYN_CACHE_PUT(sc);
   3386 	tcpstat.tcps_sc_aborted++;
   3387 	return ((struct socket *)(-1));
   3388 }
   3389 
   3390 /*
   3391  * This function is called when we get a RST for a
   3392  * non-existent connection, so that we can see if the
   3393  * connection is in the syn cache.  If it is, zap it.
   3394  */
   3395 
   3396 void
   3397 syn_cache_reset(src, dst, th)
   3398 	struct sockaddr *src;
   3399 	struct sockaddr *dst;
   3400 	struct tcphdr *th;
   3401 {
   3402 	struct syn_cache *sc;
   3403 	struct syn_cache_head *scp;
   3404 	int s = splsoftnet();
   3405 
   3406 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
   3407 		splx(s);
   3408 		return;
   3409 	}
   3410 	if (SEQ_LT(th->th_seq, sc->sc_irs) ||
   3411 	    SEQ_GT(th->th_seq, sc->sc_irs+1)) {
   3412 		splx(s);
   3413 		return;
   3414 	}
   3415 	SYN_CACHE_RM(sc);
   3416 	splx(s);
   3417 	tcpstat.tcps_sc_reset++;
   3418 	SYN_CACHE_PUT(sc);
   3419 }
   3420 
   3421 void
   3422 syn_cache_unreach(src, dst, th)
   3423 	struct sockaddr *src;
   3424 	struct sockaddr *dst;
   3425 	struct tcphdr *th;
   3426 {
   3427 	struct syn_cache *sc;
   3428 	struct syn_cache_head *scp;
   3429 	int s;
   3430 
   3431 	s = splsoftnet();
   3432 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
   3433 		splx(s);
   3434 		return;
   3435 	}
   3436 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
   3437 	if (ntohl (th->th_seq) != sc->sc_iss) {
   3438 		splx(s);
   3439 		return;
   3440 	}
   3441 
   3442 	/*
   3443 	 * If we've retransmitted 3 times and this is our second error,
   3444 	 * we remove the entry.  Otherwise, we allow it to continue on.
   3445 	 * This prevents us from incorrectly nuking an entry during a
   3446 	 * spurious network outage.
   3447 	 *
   3448 	 * See tcp_notify().
   3449 	 */
   3450 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
   3451 		sc->sc_flags |= SCF_UNREACH;
   3452 		splx(s);
   3453 		return;
   3454 	}
   3455 
   3456 	SYN_CACHE_RM(sc);
   3457 	splx(s);
   3458 	tcpstat.tcps_sc_unreach++;
   3459 	SYN_CACHE_PUT(sc);
   3460 }
   3461 
   3462 /*
   3463  * Given a LISTEN socket and an inbound SYN request, add
   3464  * this to the syn cache, and send back a segment:
   3465  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
   3466  * to the source.
   3467  *
   3468  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
   3469  * Doing so would require that we hold onto the data and deliver it
   3470  * to the application.  However, if we are the target of a SYN-flood
   3471  * DoS attack, an attacker could send data which would eventually
   3472  * consume all available buffer space if it were ACKed.  By not ACKing
   3473  * the data, we avoid this DoS scenario.
   3474  */
   3475 
   3476 int
   3477 syn_cache_add(src, dst, th, hlen, so, m, optp, optlen, oi)
   3478 	struct sockaddr *src;
   3479 	struct sockaddr *dst;
   3480 	struct tcphdr *th;
   3481 	unsigned int hlen;
   3482 	struct socket *so;
   3483 	struct mbuf *m;
   3484 	u_char *optp;
   3485 	int optlen;
   3486 	struct tcp_opt_info *oi;
   3487 {
   3488 	struct tcpcb tb, *tp;
   3489 	long win;
   3490 	struct syn_cache *sc;
   3491 	struct syn_cache_head *scp;
   3492 	struct mbuf *ipopts;
   3493 
   3494 	tp = sototcpcb(so);
   3495 
   3496 	/*
   3497 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
   3498 	 *
   3499 	 * Note this check is performed in tcp_input() very early on.
   3500 	 */
   3501 
   3502 	/*
   3503 	 * Initialize some local state.
   3504 	 */
   3505 	win = sbspace(&so->so_rcv);
   3506 	if (win > TCP_MAXWIN)
   3507 		win = TCP_MAXWIN;
   3508 
   3509 	switch (src->sa_family) {
   3510 #ifdef INET
   3511 	case AF_INET:
   3512 		/*
   3513 		 * Remember the IP options, if any.
   3514 		 */
   3515 		ipopts = ip_srcroute();
   3516 		break;
   3517 #endif
   3518 	default:
   3519 		ipopts = NULL;
   3520 	}
   3521 
   3522 	if (optp) {
   3523 		tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
   3524 		tcp_dooptions(&tb, optp, optlen, th, oi);
   3525 	} else
   3526 		tb.t_flags = 0;
   3527 
   3528 	/*
   3529 	 * See if we already have an entry for this connection.
   3530 	 * If we do, resend the SYN,ACK.  We do not count this
   3531 	 * as a retransmission (XXX though maybe we should).
   3532 	 */
   3533 	if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
   3534 		tcpstat.tcps_sc_dupesyn++;
   3535 		if (ipopts) {
   3536 			/*
   3537 			 * If we were remembering a previous source route,
   3538 			 * forget it and use the new one we've been given.
   3539 			 */
   3540 			if (sc->sc_ipopts)
   3541 				(void) m_free(sc->sc_ipopts);
   3542 			sc->sc_ipopts = ipopts;
   3543 		}
   3544 		sc->sc_timestamp = tb.ts_recent;
   3545 		if (syn_cache_respond(sc, m) == 0) {
   3546 			tcpstat.tcps_sndacks++;
   3547 			tcpstat.tcps_sndtotal++;
   3548 		}
   3549 		return (1);
   3550 	}
   3551 
   3552 	sc = pool_get(&syn_cache_pool, PR_NOWAIT);
   3553 	if (sc == NULL) {
   3554 		if (ipopts)
   3555 			(void) m_free(ipopts);
   3556 		return (0);
   3557 	}
   3558 
   3559 	/*
   3560 	 * Fill in the cache, and put the necessary IP and TCP
   3561 	 * options into the reply.
   3562 	 */
   3563 	bzero(sc, sizeof(struct syn_cache));
   3564 	callout_init(&sc->sc_timer);
   3565 	bcopy(src, &sc->sc_src, src->sa_len);
   3566 	bcopy(dst, &sc->sc_dst, dst->sa_len);
   3567 	sc->sc_flags = 0;
   3568 	sc->sc_ipopts = ipopts;
   3569 	sc->sc_irs = th->th_seq;
   3570 	switch (src->sa_family) {
   3571 #ifdef INET
   3572 	case AF_INET:
   3573 	    {
   3574 		struct sockaddr_in *srcin = (void *) src;
   3575 		struct sockaddr_in *dstin = (void *) dst;
   3576 
   3577 		sc->sc_iss = tcp_new_iss1(&dstin->sin_addr,
   3578 		    &srcin->sin_addr, dstin->sin_port,
   3579 		    srcin->sin_port, sizeof(dstin->sin_addr), 0);
   3580 		break;
   3581 	    }
   3582 #endif /* INET */
   3583 #ifdef INET6
   3584 	case AF_INET6:
   3585 	    {
   3586 		struct sockaddr_in6 *srcin6 = (void *) src;
   3587 		struct sockaddr_in6 *dstin6 = (void *) dst;
   3588 
   3589 		sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr,
   3590 		    &srcin6->sin6_addr, dstin6->sin6_port,
   3591 		    srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0);
   3592 		break;
   3593 	    }
   3594 #endif /* INET6 */
   3595 	}
   3596 	sc->sc_peermaxseg = oi->maxseg;
   3597 	sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
   3598 						m->m_pkthdr.rcvif : NULL,
   3599 						sc->sc_src.sa.sa_family);
   3600 	sc->sc_win = win;
   3601 	sc->sc_timebase = tcp_now;	/* see tcp_newtcpcb() */
   3602 	sc->sc_timestamp = tb.ts_recent;
   3603 	if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) ==
   3604 	    (TF_REQ_TSTMP|TF_RCVD_TSTMP))
   3605 		sc->sc_flags |= SCF_TIMESTAMP;
   3606 	if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   3607 	    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   3608 		sc->sc_requested_s_scale = tb.requested_s_scale;
   3609 		sc->sc_request_r_scale = 0;
   3610 		while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
   3611 		    TCP_MAXWIN << sc->sc_request_r_scale <
   3612 		    so->so_rcv.sb_hiwat)
   3613 			sc->sc_request_r_scale++;
   3614 	} else {
   3615 		sc->sc_requested_s_scale = 15;
   3616 		sc->sc_request_r_scale = 15;
   3617 	}
   3618 	sc->sc_tp = tp;
   3619 	if (syn_cache_respond(sc, m) == 0) {
   3620 		syn_cache_insert(sc, tp);
   3621 		tcpstat.tcps_sndacks++;
   3622 		tcpstat.tcps_sndtotal++;
   3623 	} else {
   3624 		SYN_CACHE_PUT(sc);
   3625 		tcpstat.tcps_sc_dropped++;
   3626 	}
   3627 	return (1);
   3628 }
   3629 
   3630 int
   3631 syn_cache_respond(sc, m)
   3632 	struct syn_cache *sc;
   3633 	struct mbuf *m;
   3634 {
   3635 	struct route *ro;
   3636 	u_int8_t *optp;
   3637 	int optlen, error;
   3638 	u_int16_t tlen;
   3639 	struct ip *ip = NULL;
   3640 #ifdef INET6
   3641 	struct ip6_hdr *ip6 = NULL;
   3642 #endif
   3643 	struct tcpcb *tp;
   3644 	struct tcphdr *th;
   3645 	u_int hlen;
   3646 	struct socket *so;
   3647 
   3648 	switch (sc->sc_src.sa.sa_family) {
   3649 	case AF_INET:
   3650 		hlen = sizeof(struct ip);
   3651 		ro = &sc->sc_route4;
   3652 		break;
   3653 #ifdef INET6
   3654 	case AF_INET6:
   3655 		hlen = sizeof(struct ip6_hdr);
   3656 		ro = (struct route *)&sc->sc_route6;
   3657 		break;
   3658 #endif
   3659 	default:
   3660 		if (m)
   3661 			m_freem(m);
   3662 		return (EAFNOSUPPORT);
   3663 	}
   3664 
   3665 	/* Compute the size of the TCP options. */
   3666 	optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
   3667 	    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
   3668 
   3669 	tlen = hlen + sizeof(struct tcphdr) + optlen;
   3670 
   3671 	/*
   3672 	 * Create the IP+TCP header from scratch.
   3673 	 */
   3674 	if (m)
   3675 		m_freem(m);
   3676 #ifdef DIAGNOSTIC
   3677 	if (max_linkhdr + tlen > MCLBYTES)
   3678 		return (ENOBUFS);
   3679 #endif
   3680 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   3681 	if (m && tlen > MHLEN) {
   3682 		MCLGET(m, M_DONTWAIT);
   3683 		if ((m->m_flags & M_EXT) == 0) {
   3684 			m_freem(m);
   3685 			m = NULL;
   3686 		}
   3687 	}
   3688 	if (m == NULL)
   3689 		return (ENOBUFS);
   3690 	MCLAIM(m, &tcp_tx_mowner);
   3691 
   3692 	/* Fixup the mbuf. */
   3693 	m->m_data += max_linkhdr;
   3694 	m->m_len = m->m_pkthdr.len = tlen;
   3695 	if (sc->sc_tp) {
   3696 		tp = sc->sc_tp;
   3697 		if (tp->t_inpcb)
   3698 			so = tp->t_inpcb->inp_socket;
   3699 #ifdef INET6
   3700 		else if (tp->t_in6pcb)
   3701 			so = tp->t_in6pcb->in6p_socket;
   3702 #endif
   3703 		else
   3704 			so = NULL;
   3705 	} else
   3706 		so = NULL;
   3707 	m->m_pkthdr.rcvif = NULL;
   3708 	memset(mtod(m, u_char *), 0, tlen);
   3709 
   3710 	switch (sc->sc_src.sa.sa_family) {
   3711 	case AF_INET:
   3712 		ip = mtod(m, struct ip *);
   3713 		ip->ip_dst = sc->sc_src.sin.sin_addr;
   3714 		ip->ip_src = sc->sc_dst.sin.sin_addr;
   3715 		ip->ip_p = IPPROTO_TCP;
   3716 		th = (struct tcphdr *)(ip + 1);
   3717 		th->th_dport = sc->sc_src.sin.sin_port;
   3718 		th->th_sport = sc->sc_dst.sin.sin_port;
   3719 		break;
   3720 #ifdef INET6
   3721 	case AF_INET6:
   3722 		ip6 = mtod(m, struct ip6_hdr *);
   3723 		ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
   3724 		ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
   3725 		ip6->ip6_nxt = IPPROTO_TCP;
   3726 		/* ip6_plen will be updated in ip6_output() */
   3727 		th = (struct tcphdr *)(ip6 + 1);
   3728 		th->th_dport = sc->sc_src.sin6.sin6_port;
   3729 		th->th_sport = sc->sc_dst.sin6.sin6_port;
   3730 		break;
   3731 #endif
   3732 	default:
   3733 		th = NULL;
   3734 	}
   3735 
   3736 	th->th_seq = htonl(sc->sc_iss);
   3737 	th->th_ack = htonl(sc->sc_irs + 1);
   3738 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
   3739 	th->th_flags = TH_SYN|TH_ACK;
   3740 	th->th_win = htons(sc->sc_win);
   3741 	/* th_sum already 0 */
   3742 	/* th_urp already 0 */
   3743 
   3744 	/* Tack on the TCP options. */
   3745 	optp = (u_int8_t *)(th + 1);
   3746 	*optp++ = TCPOPT_MAXSEG;
   3747 	*optp++ = 4;
   3748 	*optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
   3749 	*optp++ = sc->sc_ourmaxseg & 0xff;
   3750 
   3751 	if (sc->sc_request_r_scale != 15) {
   3752 		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
   3753 		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
   3754 		    sc->sc_request_r_scale);
   3755 		optp += 4;
   3756 	}
   3757 
   3758 	if (sc->sc_flags & SCF_TIMESTAMP) {
   3759 		u_int32_t *lp = (u_int32_t *)(optp);
   3760 		/* Form timestamp option as shown in appendix A of RFC 1323. */
   3761 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
   3762 		*lp++ = htonl(SYN_CACHE_TIMESTAMP(sc));
   3763 		*lp   = htonl(sc->sc_timestamp);
   3764 		optp += TCPOLEN_TSTAMP_APPA;
   3765 	}
   3766 
   3767 	/* Compute the packet's checksum. */
   3768 	switch (sc->sc_src.sa.sa_family) {
   3769 	case AF_INET:
   3770 		ip->ip_len = htons(tlen - hlen);
   3771 		th->th_sum = 0;
   3772 		th->th_sum = in_cksum(m, tlen);
   3773 		break;
   3774 #ifdef INET6
   3775 	case AF_INET6:
   3776 		ip6->ip6_plen = htons(tlen - hlen);
   3777 		th->th_sum = 0;
   3778 		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
   3779 		break;
   3780 #endif
   3781 	}
   3782 
   3783 	/*
   3784 	 * Fill in some straggling IP bits.  Note the stack expects
   3785 	 * ip_len to be in host order, for convenience.
   3786 	 */
   3787 	switch (sc->sc_src.sa.sa_family) {
   3788 #ifdef INET
   3789 	case AF_INET:
   3790 		ip->ip_len = htons(tlen);
   3791 		ip->ip_ttl = ip_defttl;
   3792 		/* XXX tos? */
   3793 		break;
   3794 #endif
   3795 #ifdef INET6
   3796 	case AF_INET6:
   3797 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
   3798 		ip6->ip6_vfc |= IPV6_VERSION;
   3799 		ip6->ip6_plen = htons(tlen - hlen);
   3800 		/* ip6_hlim will be initialized afterwards */
   3801 		/* XXX flowlabel? */
   3802 		break;
   3803 #endif
   3804 	}
   3805 
   3806 	/* XXX use IPsec policy on listening socket, on SYN ACK */
   3807 	tp = sc->sc_tp;
   3808 
   3809 	switch (sc->sc_src.sa.sa_family) {
   3810 #ifdef INET
   3811 	case AF_INET:
   3812 		error = ip_output(m, sc->sc_ipopts, ro,
   3813 		    (ip_mtudisc ? IP_MTUDISC : 0),
   3814 		    (struct ip_moptions *)NULL, so);
   3815 		break;
   3816 #endif
   3817 #ifdef INET6
   3818 	case AF_INET6:
   3819 		ip6->ip6_hlim = in6_selecthlim(NULL,
   3820 				ro->ro_rt ? ro->ro_rt->rt_ifp : NULL);
   3821 
   3822 		error = ip6_output(m, NULL /*XXX*/, (struct route_in6 *)ro, 0,
   3823 			(struct ip6_moptions *)0, so, NULL);
   3824 		break;
   3825 #endif
   3826 	default:
   3827 		error = EAFNOSUPPORT;
   3828 		break;
   3829 	}
   3830 	return (error);
   3831 }
   3832