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