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