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