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