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