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