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