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