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