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