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