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