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