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