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