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