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