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