Home | History | Annotate | Line # | Download | only in netinet
tcp_input.c revision 1.78
      1 /*	$NetBSD: tcp_input.c,v 1.78 1999/04/09 22:01:07 kml Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
      9  * Facility, NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
     42  *	The Regents of the University of California.  All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  * 1. Redistributions of source code must retain the above copyright
     48  *    notice, this list of conditions and the following disclaimer.
     49  * 2. Redistributions in binary form must reproduce the above copyright
     50  *    notice, this list of conditions and the following disclaimer in the
     51  *    documentation and/or other materials provided with the distribution.
     52  * 3. All advertising materials mentioning features or use of this software
     53  *    must display the following acknowledgement:
     54  *	This product includes software developed by the University of
     55  *	California, Berkeley and its contributors.
     56  * 4. Neither the name of the University nor the names of its contributors
     57  *    may be used to endorse or promote products derived from this software
     58  *    without specific prior written permission.
     59  *
     60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     61  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     62  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     63  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     64  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     65  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     66  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     68  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     69  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     70  * SUCH DAMAGE.
     71  *
     72  *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
     73  */
     74 
     75 /*
     76  *	TODO list for SYN cache stuff:
     77  *
     78  *	Find room for a "state" field, which is needed to keep a
     79  *	compressed state for TIME_WAIT TCBs.  It's been noted already
     80  *	that this is fairly important for very high-volume web and
     81  *	mail servers, which use a large number of short-lived
     82  *	connections.
     83  */
     84 
     85 #include <sys/param.h>
     86 #include <sys/systm.h>
     87 #include <sys/malloc.h>
     88 #include <sys/mbuf.h>
     89 #include <sys/protosw.h>
     90 #include <sys/socket.h>
     91 #include <sys/socketvar.h>
     92 #include <sys/errno.h>
     93 #include <sys/syslog.h>
     94 #include <sys/pool.h>
     95 
     96 #include <net/if.h>
     97 #include <net/route.h>
     98 
     99 #include <netinet/in.h>
    100 #include <netinet/in_systm.h>
    101 #include <netinet/ip.h>
    102 #include <netinet/in_pcb.h>
    103 #include <netinet/ip_var.h>
    104 #include <netinet/tcp.h>
    105 #include <netinet/tcp_fsm.h>
    106 #include <netinet/tcp_seq.h>
    107 #include <netinet/tcp_timer.h>
    108 #include <netinet/tcp_var.h>
    109 #include <netinet/tcpip.h>
    110 #include <netinet/tcp_debug.h>
    111 
    112 #include <machine/stdarg.h>
    113 
    114 int	tcprexmtthresh = 3;
    115 struct	tcpiphdr tcp_saveti;
    116 
    117 extern u_long sb_max;
    118 
    119 #define TCP_PAWS_IDLE	(24 * 24 * 60 * 60 * PR_SLOWHZ)
    120 
    121 /* for modulo comparisons of timestamps */
    122 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
    123 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
    124 
    125 /*
    126  * Macro to compute ACK transmission behavior.  Delay the ACK unless
    127  * we have already delayed an ACK (must send an ACK every two segments).
    128  * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
    129  * option is enabled.
    130  */
    131 #define	TCP_SETUP_ACK(tp, ti) \
    132 do { \
    133 	if ((tp)->t_flags & TF_DELACK || \
    134 	    (tcp_ack_on_push && (ti)->ti_flags & TH_PUSH)) \
    135 		tp->t_flags |= TF_ACKNOW; \
    136 	else \
    137 		TCP_SET_DELACK(tp); \
    138 } while (0)
    139 
    140 /*
    141  * Insert segment ti into reassembly queue of tcp with
    142  * control block tp.  Return TH_FIN if reassembly now includes
    143  * a segment with FIN.  The macro form does the common case inline
    144  * (segment is the next to be received on an established connection,
    145  * and the queue is empty), avoiding linkage into and removal
    146  * from the queue and repetition of various conversions.
    147  * Set DELACK for segments received in order, but ack immediately
    148  * when segments are out of order (so fast retransmit can work).
    149  */
    150 #define	TCP_REASS(tp, ti, m, so, flags) { \
    151 	TCP_REASS_LOCK((tp)); \
    152 	if ((ti)->ti_seq == (tp)->rcv_nxt && \
    153 	    (tp)->segq.lh_first == NULL && \
    154 	    (tp)->t_state == TCPS_ESTABLISHED) { \
    155 		TCP_SETUP_ACK(tp, ti); \
    156 		(tp)->rcv_nxt += (ti)->ti_len; \
    157 		flags = (ti)->ti_flags & TH_FIN; \
    158 		tcpstat.tcps_rcvpack++;\
    159 		tcpstat.tcps_rcvbyte += (ti)->ti_len;\
    160 		sbappend(&(so)->so_rcv, (m)); \
    161 		sorwakeup(so); \
    162 	} else { \
    163 		(flags) = tcp_reass((tp), (ti), (m)); \
    164 		tp->t_flags |= TF_ACKNOW; \
    165 	} \
    166 	TCP_REASS_UNLOCK((tp)); \
    167 }
    168 
    169 int
    170 tcp_reass(tp, ti, m)
    171 	register struct tcpcb *tp;
    172 	register struct tcpiphdr *ti;
    173 	struct mbuf *m;
    174 {
    175 	register struct ipqent *p, *q, *nq, *tiqe = NULL;
    176 	struct socket *so = tp->t_inpcb->inp_socket;
    177 	int pkt_flags;
    178 	tcp_seq pkt_seq;
    179 	unsigned pkt_len;
    180 	u_long rcvpartdupbyte = 0;
    181 	u_long rcvoobyte;
    182 
    183 	TCP_REASS_LOCK_CHECK(tp);
    184 
    185 	/*
    186 	 * Call with ti==0 after become established to
    187 	 * force pre-ESTABLISHED data up to user socket.
    188 	 */
    189 	if (ti == 0)
    190 		goto present;
    191 
    192 	rcvoobyte = ti->ti_len;
    193 	/*
    194 	 * Copy these to local variables because the tcpiphdr
    195 	 * gets munged while we are collapsing mbufs.
    196 	 */
    197 	pkt_seq = ti->ti_seq;
    198 	pkt_len = ti->ti_len;
    199 	pkt_flags = ti->ti_flags;
    200 	/*
    201 	 * Find a segment which begins after this one does.
    202 	 */
    203 	for (p = NULL, q = tp->segq.lh_first; q != NULL; q = nq) {
    204 		nq = q->ipqe_q.le_next;
    205 		/*
    206 		 * If the received segment is just right after this
    207 		 * fragment, merge the two together and then check
    208 		 * for further overlaps.
    209 		 */
    210 		if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
    211 #ifdef TCPREASS_DEBUG
    212 			printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
    213 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
    214 			       q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
    215 #endif
    216 			pkt_len += q->ipqe_len;
    217 			pkt_flags |= q->ipqe_flags;
    218 			pkt_seq = q->ipqe_seq;
    219 			m_cat(q->ipqe_m, m);
    220 			m = q->ipqe_m;
    221 			goto free_ipqe;
    222 		}
    223 		/*
    224 		 * If the received segment is completely past this
    225 		 * fragment, we need to go the next fragment.
    226 		 */
    227 		if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
    228 			p = q;
    229 			continue;
    230 		}
    231 		/*
    232 		 * If the fragment is past the received segment,
    233 		 * it (or any following) can't be concatenated.
    234 		 */
    235 		if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len))
    236 			break;
    237 		/*
    238 		 * We've received all the data in this segment before.
    239 		 * mark it as a duplicate and return.
    240 		 */
    241 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
    242 		    SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
    243 			tcpstat.tcps_rcvduppack++;
    244 			tcpstat.tcps_rcvdupbyte += pkt_len;
    245 			m_freem(m);
    246 			if (tiqe != NULL)
    247 				pool_put(&ipqent_pool, tiqe);
    248 			return (0);
    249 		}
    250 		/*
    251 		 * Received segment completely overlaps this fragment
    252 		 * so we drop the fragment (this keeps the temporal
    253 		 * ordering of segments correct).
    254 		 */
    255 		if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
    256 		    SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
    257 			rcvpartdupbyte += q->ipqe_len;
    258 			m_freem(q->ipqe_m);
    259 			goto free_ipqe;
    260 		}
    261 		/*
    262 		 * RX'ed segment extends past the end of the
    263 		 * fragment.  Drop the overlapping bytes.  Then
    264 		 * merge the fragment and segment then treat as
    265 		 * a longer received packet.
    266 		 */
    267 		if (SEQ_LT(q->ipqe_seq, pkt_seq)
    268 		    && SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq))  {
    269 			int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
    270 #ifdef TCPREASS_DEBUG
    271 			printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
    272 			       tp, overlap,
    273 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
    274 #endif
    275 			m_adj(m, overlap);
    276 			rcvpartdupbyte += overlap;
    277 			m_cat(q->ipqe_m, m);
    278 			m = q->ipqe_m;
    279 			pkt_seq = q->ipqe_seq;
    280 			pkt_len += q->ipqe_len - overlap;
    281 			rcvoobyte -= overlap;
    282 			goto free_ipqe;
    283 		}
    284 		/*
    285 		 * RX'ed segment extends past the front of the
    286 		 * fragment.  Drop the overlapping bytes on the
    287 		 * received packet.  The packet will then be
    288 		 * contatentated with this fragment a bit later.
    289 		 */
    290 		if (SEQ_GT(q->ipqe_seq, pkt_seq)
    291 		    && SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len))  {
    292 			int overlap = pkt_seq + pkt_len - q->ipqe_seq;
    293 #ifdef TCPREASS_DEBUG
    294 			printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
    295 			       tp, overlap,
    296 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
    297 #endif
    298 			m_adj(m, -overlap);
    299 			pkt_len -= overlap;
    300 			rcvpartdupbyte += overlap;
    301 			rcvoobyte -= overlap;
    302 		}
    303 		/*
    304 		 * If the received segment immediates precedes this
    305 		 * fragment then tack the fragment onto this segment
    306 		 * and reinsert the data.
    307 		 */
    308 		if (q->ipqe_seq == pkt_seq + pkt_len) {
    309 #ifdef TCPREASS_DEBUG
    310 			printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
    311 			       tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
    312 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
    313 #endif
    314 			pkt_len += q->ipqe_len;
    315 			pkt_flags |= q->ipqe_flags;
    316 			m_cat(m, q->ipqe_m);
    317 			LIST_REMOVE(q, ipqe_q);
    318 			LIST_REMOVE(q, ipqe_timeq);
    319 			if (tiqe == NULL) {
    320 			    tiqe = q;
    321 			} else {
    322 			    pool_put(&ipqent_pool, q);
    323 			}
    324 			break;
    325 		}
    326 		/*
    327 		 * If the fragment is before the segment, remember it.
    328 		 * When this loop is terminated, p will contain the
    329 		 * pointer to fragment that is right before the received
    330 		 * segment.
    331 		 */
    332 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
    333 			p = q;
    334 
    335 		continue;
    336 
    337 		/*
    338 		 * This is a common operation.  It also will allow
    339 		 * to save doing a malloc/free in most instances.
    340 		 */
    341 	  free_ipqe:
    342 		LIST_REMOVE(q, ipqe_q);
    343 		LIST_REMOVE(q, ipqe_timeq);
    344 		if (tiqe == NULL) {
    345 		    tiqe = q;
    346 		} else {
    347 		    pool_put(&ipqent_pool, q);
    348 		}
    349 	}
    350 
    351 	/*
    352 	 * Allocate a new queue entry since the received segment did not
    353 	 * collapse onto any other out-of-order block; thus we are allocating
    354 	 * a new block.  If it had collapsed, tiqe would not be NULL and
    355 	 * we would be reusing it.
    356 	 * XXX If we can't, just drop the packet.  XXX
    357 	 */
    358 	if (tiqe == NULL) {
    359 		tiqe = pool_get(&ipqent_pool, PR_NOWAIT);
    360 		if (tiqe == NULL) {
    361 			tcpstat.tcps_rcvmemdrop++;
    362 			m_freem(m);
    363 			return (0);
    364 		}
    365 	}
    366 
    367 	/*
    368 	 * Update the counters.
    369 	 */
    370 	tcpstat.tcps_rcvoopack++;
    371 	tcpstat.tcps_rcvoobyte += rcvoobyte;
    372 	if (rcvpartdupbyte) {
    373 	    tcpstat.tcps_rcvpartduppack++;
    374 	    tcpstat.tcps_rcvpartdupbyte += rcvpartdupbyte;
    375 	}
    376 
    377 	/*
    378 	 * Insert the new fragment queue entry into both queues.
    379 	 */
    380 	tiqe->ipqe_m = m;
    381 	tiqe->ipqe_seq = pkt_seq;
    382 	tiqe->ipqe_len = pkt_len;
    383 	tiqe->ipqe_flags = pkt_flags;
    384 	if (p == NULL) {
    385 		LIST_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
    386 #ifdef TCPREASS_DEBUG
    387 		if (tiqe->ipqe_seq != tp->rcv_nxt)
    388 			printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
    389 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
    390 #endif
    391 	} else {
    392 		LIST_INSERT_AFTER(p, tiqe, ipqe_q);
    393 #ifdef TCPREASS_DEBUG
    394 		printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
    395 		       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
    396 		       p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
    397 #endif
    398 	}
    399 
    400 	LIST_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
    401 
    402 present:
    403 	/*
    404 	 * Present data to user, advancing rcv_nxt through
    405 	 * completed sequence space.
    406 	 */
    407 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
    408 		return (0);
    409 	q = tp->segq.lh_first;
    410 	if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
    411 		return (0);
    412 	if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
    413 		return (0);
    414 
    415 	tp->rcv_nxt += q->ipqe_len;
    416 	pkt_flags = q->ipqe_flags & TH_FIN;
    417 
    418 	LIST_REMOVE(q, ipqe_q);
    419 	LIST_REMOVE(q, ipqe_timeq);
    420 	if (so->so_state & SS_CANTRCVMORE)
    421 		m_freem(q->ipqe_m);
    422 	else
    423 		sbappend(&so->so_rcv, q->ipqe_m);
    424 	pool_put(&ipqent_pool, q);
    425 	sorwakeup(so);
    426 	return (pkt_flags);
    427 }
    428 
    429 /*
    430  * TCP input routine, follows pages 65-76 of the
    431  * protocol specification dated September, 1981 very closely.
    432  */
    433 void
    434 #if __STDC__
    435 tcp_input(struct mbuf *m, ...)
    436 #else
    437 tcp_input(m, va_alist)
    438 	register struct mbuf *m;
    439 #endif
    440 {
    441 	register struct tcpiphdr *ti;
    442 	register struct inpcb *inp;
    443 	caddr_t optp = NULL;
    444 	int optlen = 0;
    445 	int len, tlen, off, hdroptlen;
    446 	register struct tcpcb *tp = 0;
    447 	register int tiflags;
    448 	struct socket *so = NULL;
    449 	int todrop, acked, ourfinisacked, needoutput = 0;
    450 	short ostate = 0;
    451 	int iss = 0;
    452 	u_long tiwin;
    453 	struct tcp_opt_info opti;
    454 	int iphlen;
    455 	va_list ap;
    456 
    457 	va_start(ap, m);
    458 	iphlen = va_arg(ap, int);
    459 	va_end(ap);
    460 
    461 	tcpstat.tcps_rcvtotal++;
    462 
    463 	opti.ts_present = 0;
    464 	opti.maxseg = 0;
    465 
    466 	/*
    467 	 * Get IP and TCP header together in first mbuf.
    468 	 * Note: IP leaves IP header in first mbuf.
    469 	 */
    470 	ti = mtod(m, struct tcpiphdr *);
    471 	if (iphlen > sizeof (struct ip))
    472 		ip_stripoptions(m, (struct mbuf *)0);
    473 	if (m->m_len < sizeof (struct tcpiphdr)) {
    474 		if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
    475 			tcpstat.tcps_rcvshort++;
    476 			return;
    477 		}
    478 		ti = mtod(m, struct tcpiphdr *);
    479 	}
    480 
    481 	/*
    482 	 * Checksum extended TCP header and data.
    483 	 */
    484 	len = ((struct ip *)ti)->ip_len;
    485 	tlen = len - sizeof (struct ip);
    486 	bzero(ti->ti_x1, sizeof ti->ti_x1);
    487 	ti->ti_len = (u_int16_t)tlen;
    488 	HTONS(ti->ti_len);
    489 	if (in_cksum(m, len) != 0) {
    490 		tcpstat.tcps_rcvbadsum++;
    491 		goto drop;
    492 	}
    493 
    494 	/*
    495 	 * Check that TCP offset makes sense,
    496 	 * pull out TCP options and adjust length.		XXX
    497 	 */
    498 	off = ti->ti_off << 2;
    499 	if (off < sizeof (struct tcphdr) || off > tlen) {
    500 		tcpstat.tcps_rcvbadoff++;
    501 		goto drop;
    502 	}
    503 	tlen -= off;
    504 	ti->ti_len = tlen;
    505 	if (off > sizeof (struct tcphdr)) {
    506 		if (m->m_len < sizeof(struct ip) + off) {
    507 			if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
    508 				tcpstat.tcps_rcvshort++;
    509 				return;
    510 			}
    511 			ti = mtod(m, struct tcpiphdr *);
    512 		}
    513 		optlen = off - sizeof (struct tcphdr);
    514 		optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
    515 		/*
    516 		 * Do quick retrieval of timestamp options ("options
    517 		 * prediction?").  If timestamp is the only option and it's
    518 		 * formatted as recommended in RFC 1323 appendix A, we
    519 		 * quickly get the values now and not bother calling
    520 		 * tcp_dooptions(), etc.
    521 		 */
    522 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
    523 		     (optlen > TCPOLEN_TSTAMP_APPA &&
    524 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
    525 		     *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
    526 		     (ti->ti_flags & TH_SYN) == 0) {
    527 			opti.ts_present = 1;
    528 			opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
    529 			opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
    530 			optp = NULL;	/* we've parsed the options */
    531 		}
    532 	}
    533 	tiflags = ti->ti_flags;
    534 
    535 	/*
    536 	 * Convert TCP protocol specific fields to host format.
    537 	 */
    538 	NTOHL(ti->ti_seq);
    539 	NTOHL(ti->ti_ack);
    540 	NTOHS(ti->ti_win);
    541 	NTOHS(ti->ti_urp);
    542 
    543 	/*
    544 	 * Locate pcb for segment.
    545 	 */
    546 findpcb:
    547 	inp = in_pcblookup_connect(&tcbtable, ti->ti_src, ti->ti_sport,
    548 	    ti->ti_dst, ti->ti_dport);
    549 	if (inp == 0) {
    550 		++tcpstat.tcps_pcbhashmiss;
    551 		inp = in_pcblookup_bind(&tcbtable, ti->ti_dst, ti->ti_dport);
    552 		if (inp == 0) {
    553 			++tcpstat.tcps_noport;
    554 			goto dropwithreset;
    555 		}
    556 	}
    557 
    558 	/*
    559 	 * If the state is CLOSED (i.e., TCB does not exist) then
    560 	 * all data in the incoming segment is discarded.
    561 	 * If the TCB exists but is in CLOSED state, it is embryonic,
    562 	 * but should either do a listen or a connect soon.
    563 	 */
    564 	tp = intotcpcb(inp);
    565 	if (tp == 0)
    566 		goto dropwithreset;
    567 	if (tp->t_state == TCPS_CLOSED)
    568 		goto drop;
    569 
    570 	/* Unscale the window into a 32-bit value. */
    571 	if ((tiflags & TH_SYN) == 0)
    572 		tiwin = ti->ti_win << tp->snd_scale;
    573 	else
    574 		tiwin = ti->ti_win;
    575 
    576 	so = inp->inp_socket;
    577 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
    578 		if (so->so_options & SO_DEBUG) {
    579 			ostate = tp->t_state;
    580 			tcp_saveti = *ti;
    581 		}
    582 		if (so->so_options & SO_ACCEPTCONN) {
    583   			if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
    584 				if (tiflags & TH_RST) {
    585 					syn_cache_reset(ti);
    586 				} else if ((tiflags & (TH_ACK|TH_SYN)) ==
    587 				    (TH_ACK|TH_SYN)) {
    588 					/*
    589 					 * Received a SYN,ACK.  This should
    590 					 * never happen while we are in
    591 					 * LISTEN.  Send an RST.
    592 					 */
    593 					goto badsyn;
    594 				} else if (tiflags & TH_ACK) {
    595 					so = syn_cache_get(so, m);
    596 					if (so == NULL) {
    597 						/*
    598 						 * We don't have a SYN for
    599 						 * this ACK; send an RST.
    600 						 */
    601 						goto badsyn;
    602 					} else if (so ==
    603 					    (struct socket *)(-1)) {
    604 						/*
    605 						 * We were unable to create
    606 						 * the connection.  If the
    607 						 * 3-way handshake was
    608 						 * completed, and RST has
    609 						 * been sent to the peer.
    610 						 * Since the mbuf might be
    611 						 * in use for the reply,
    612 						 * do not free it.
    613 						 */
    614 						m = NULL;
    615 					} else {
    616 						/*
    617 						 * We have created a
    618 						 * full-blown connection.
    619 						 */
    620 						inp = sotoinpcb(so);
    621 						tp = intotcpcb(inp);
    622 						tiwin <<= tp->snd_scale;
    623 						goto after_listen;
    624 					}
    625   				} else {
    626 					/*
    627 					 * None of RST, SYN or ACK was set.
    628 					 * This is an invalid packet for a
    629 					 * TCB in LISTEN state.  Send a RST.
    630 					 */
    631 					goto badsyn;
    632 				}
    633   			} else {
    634 				/*
    635 				 * Received a SYN.
    636 				 */
    637 				if (in_hosteq(ti->ti_src, ti->ti_dst) &&
    638 				    ti->ti_sport == ti->ti_dport) {
    639 					/*
    640 					 * LISTEN socket received a SYN
    641 					 * from itself?  This can't possibly
    642 					 * be valid; drop the packet.
    643 					 */
    644 					tcpstat.tcps_badsyn++;
    645 					goto drop;
    646 				}
    647 				/*
    648 				 * SYN looks ok; create compressed TCP
    649 				 * state for it.
    650 				 */
    651 				if (so->so_qlen <= so->so_qlimit &&
    652 				    syn_cache_add(so, m, optp, optlen, &opti))
    653 					m = NULL;
    654 			}
    655 			goto drop;
    656 		}
    657 	}
    658 
    659 after_listen:
    660 #ifdef DIAGNOSTIC
    661 	/*
    662 	 * Should not happen now that all embryonic connections
    663 	 * are handled with compressed state.
    664 	 */
    665 	if (tp->t_state == TCPS_LISTEN)
    666 		panic("tcp_input: TCPS_LISTEN");
    667 #endif
    668 
    669 	/*
    670 	 * Segment received on connection.
    671 	 * Reset idle time and keep-alive timer.
    672 	 */
    673 	tp->t_idle = 0;
    674 	if (TCPS_HAVEESTABLISHED(tp->t_state))
    675 		TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
    676 
    677 	/*
    678 	 * Process options.
    679 	 */
    680 	if (optp)
    681 		tcp_dooptions(tp, optp, optlen, ti, &opti);
    682 
    683 	/*
    684 	 * Header prediction: check for the two common cases
    685 	 * of a uni-directional data xfer.  If the packet has
    686 	 * no control flags, is in-sequence, the window didn't
    687 	 * change and we're not retransmitting, it's a
    688 	 * candidate.  If the length is zero and the ack moved
    689 	 * forward, we're the sender side of the xfer.  Just
    690 	 * free the data acked & wake any higher level process
    691 	 * that was blocked waiting for space.  If the length
    692 	 * is non-zero and the ack didn't move, we're the
    693 	 * receiver side.  If we're getting packets in-order
    694 	 * (the reassembly queue is empty), add the data to
    695 	 * the socket buffer and note that we need a delayed ack.
    696 	 */
    697 	if (tp->t_state == TCPS_ESTABLISHED &&
    698 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
    699 	    (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
    700 	    ti->ti_seq == tp->rcv_nxt &&
    701 	    tiwin && tiwin == tp->snd_wnd &&
    702 	    tp->snd_nxt == tp->snd_max) {
    703 
    704 		/*
    705 		 * If last ACK falls within this segment's sequence numbers,
    706 		 *  record the timestamp.
    707 		 */
    708 		if (opti.ts_present &&
    709 		    SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
    710 		    SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len)) {
    711 			tp->ts_recent_age = tcp_now;
    712 			tp->ts_recent = opti.ts_val;
    713 		}
    714 
    715 		if (ti->ti_len == 0) {
    716 			if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
    717 			    SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
    718 			    tp->snd_cwnd >= tp->snd_wnd &&
    719 			    tp->t_dupacks < tcprexmtthresh) {
    720 				/*
    721 				 * this is a pure ack for outstanding data.
    722 				 */
    723 				++tcpstat.tcps_predack;
    724 				if (opti.ts_present)
    725 					tcp_xmit_timer(tp,
    726 					    tcp_now-opti.ts_ecr+1);
    727 				else if (tp->t_rtt &&
    728 				    SEQ_GT(ti->ti_ack, tp->t_rtseq))
    729 					tcp_xmit_timer(tp, tp->t_rtt);
    730 				acked = ti->ti_ack - tp->snd_una;
    731 				tcpstat.tcps_rcvackpack++;
    732 				tcpstat.tcps_rcvackbyte += acked;
    733 				sbdrop(&so->so_snd, acked);
    734 				tp->snd_una = ti->ti_ack;
    735 				m_freem(m);
    736 
    737 				/*
    738 				 * If all outstanding data are acked, stop
    739 				 * retransmit timer, otherwise restart timer
    740 				 * using current (possibly backed-off) value.
    741 				 * If process is waiting for space,
    742 				 * wakeup/selwakeup/signal.  If data
    743 				 * are ready to send, let tcp_output
    744 				 * decide between more output or persist.
    745 				 */
    746 				if (tp->snd_una == tp->snd_max)
    747 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
    748 				else if (TCP_TIMER_ISARMED(tp,
    749 				    TCPT_PERSIST) == 0)
    750 					TCP_TIMER_ARM(tp, TCPT_REXMT,
    751 					    tp->t_rxtcur);
    752 
    753 				sowwakeup(so);
    754 				if (so->so_snd.sb_cc)
    755 					(void) tcp_output(tp);
    756 				return;
    757 			}
    758 		} else if (ti->ti_ack == tp->snd_una &&
    759 		    tp->segq.lh_first == NULL &&
    760 		    ti->ti_len <= sbspace(&so->so_rcv)) {
    761 			/*
    762 			 * this is a pure, in-sequence data packet
    763 			 * with nothing on the reassembly queue and
    764 			 * we have enough buffer space to take it.
    765 			 */
    766 			++tcpstat.tcps_preddat;
    767 			tp->rcv_nxt += ti->ti_len;
    768 			tcpstat.tcps_rcvpack++;
    769 			tcpstat.tcps_rcvbyte += ti->ti_len;
    770 			/*
    771 			 * Drop TCP, IP headers and TCP options then add data
    772 			 * to socket buffer.
    773 			 */
    774 			m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
    775 			m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
    776 			sbappend(&so->so_rcv, m);
    777 			sorwakeup(so);
    778 			TCP_SETUP_ACK(tp, ti);
    779 			if (tp->t_flags & TF_ACKNOW)
    780 				(void) tcp_output(tp);
    781 			return;
    782 		}
    783 	}
    784 
    785 	/*
    786 	 * Drop TCP, IP headers and TCP options.
    787 	 */
    788 	hdroptlen  = sizeof(struct tcpiphdr) + off - sizeof(struct tcphdr);
    789 	m->m_data += hdroptlen;
    790 	m->m_len  -= hdroptlen;
    791 
    792 	/*
    793 	 * Calculate amount of space in receive window,
    794 	 * and then do TCP input processing.
    795 	 * Receive window is amount of space in rcv queue,
    796 	 * but not less than advertised window.
    797 	 */
    798 	{ int win;
    799 
    800 	win = sbspace(&so->so_rcv);
    801 	if (win < 0)
    802 		win = 0;
    803 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
    804 	}
    805 
    806 	switch (tp->t_state) {
    807 
    808 	/*
    809 	 * If the state is SYN_SENT:
    810 	 *	if seg contains an ACK, but not for our SYN, drop the input.
    811 	 *	if seg contains a RST, then drop the connection.
    812 	 *	if seg does not contain SYN, then drop it.
    813 	 * Otherwise this is an acceptable SYN segment
    814 	 *	initialize tp->rcv_nxt and tp->irs
    815 	 *	if seg contains ack then advance tp->snd_una
    816 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
    817 	 *	arrange for segment to be acked (eventually)
    818 	 *	continue processing rest of data/controls, beginning with URG
    819 	 */
    820 	case TCPS_SYN_SENT:
    821 		if ((tiflags & TH_ACK) &&
    822 		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
    823 		     SEQ_GT(ti->ti_ack, tp->snd_max)))
    824 			goto dropwithreset;
    825 		if (tiflags & TH_RST) {
    826 			if (tiflags & TH_ACK)
    827 				tp = tcp_drop(tp, ECONNREFUSED);
    828 			goto drop;
    829 		}
    830 		if ((tiflags & TH_SYN) == 0)
    831 			goto drop;
    832 		if (tiflags & TH_ACK) {
    833 			tp->snd_una = ti->ti_ack;
    834 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
    835 				tp->snd_nxt = tp->snd_una;
    836 		}
    837 		TCP_TIMER_DISARM(tp, TCPT_REXMT);
    838 		tp->irs = ti->ti_seq;
    839 		tcp_rcvseqinit(tp);
    840 		tp->t_flags |= TF_ACKNOW;
    841 		tcp_mss_from_peer(tp, opti.maxseg);
    842 
    843 		/*
    844 		 * Initialize the initial congestion window.  If we
    845 		 * had to retransmit the SYN, we must initialize cwnd
    846 		 * to 1 segment (i.e. the Loss Window).
    847 		 */
    848 		if (tp->t_flags & TF_SYN_REXMT)
    849 			tp->snd_cwnd = tp->t_peermss;
    850 		else
    851 			tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win,
    852 			    tp->t_peermss);
    853 
    854 		tcp_rmx_rtt(tp);
    855 		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
    856 			tcpstat.tcps_connects++;
    857 			soisconnected(so);
    858 			tcp_established(tp);
    859 			/* Do window scaling on this connection? */
    860 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
    861 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
    862 				tp->snd_scale = tp->requested_s_scale;
    863 				tp->rcv_scale = tp->request_r_scale;
    864 			}
    865 			TCP_REASS_LOCK(tp);
    866 			(void) tcp_reass(tp, (struct tcpiphdr *)0,
    867 				(struct mbuf *)0);
    868 			TCP_REASS_UNLOCK(tp);
    869 			/*
    870 			 * if we didn't have to retransmit the SYN,
    871 			 * use its rtt as our initial srtt & rtt var.
    872 			 */
    873 			if (tp->t_rtt)
    874 				tcp_xmit_timer(tp, tp->t_rtt);
    875 		} else
    876 			tp->t_state = TCPS_SYN_RECEIVED;
    877 
    878 		/*
    879 		 * Advance ti->ti_seq to correspond to first data byte.
    880 		 * If data, trim to stay within window,
    881 		 * dropping FIN if necessary.
    882 		 */
    883 		ti->ti_seq++;
    884 		if (ti->ti_len > tp->rcv_wnd) {
    885 			todrop = ti->ti_len - tp->rcv_wnd;
    886 			m_adj(m, -todrop);
    887 			ti->ti_len = tp->rcv_wnd;
    888 			tiflags &= ~TH_FIN;
    889 			tcpstat.tcps_rcvpackafterwin++;
    890 			tcpstat.tcps_rcvbyteafterwin += todrop;
    891 		}
    892 		tp->snd_wl1 = ti->ti_seq - 1;
    893 		tp->rcv_up = ti->ti_seq;
    894 		goto step6;
    895 
    896 	/*
    897 	 * If the state is SYN_RECEIVED:
    898 	 *	If seg contains an ACK, but not for our SYN, drop the input
    899 	 *	and generate an RST.  See page 36, rfc793
    900 	 */
    901 	case TCPS_SYN_RECEIVED:
    902 		if ((tiflags & TH_ACK) &&
    903 		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
    904 		     SEQ_GT(ti->ti_ack, tp->snd_max)))
    905 			goto dropwithreset;
    906 		break;
    907 	}
    908 
    909 	/*
    910 	 * States other than LISTEN or SYN_SENT.
    911 	 * First check timestamp, if present.
    912 	 * Then check that at least some bytes of segment are within
    913 	 * receive window.  If segment begins before rcv_nxt,
    914 	 * drop leading data (and SYN); if nothing left, just ack.
    915 	 *
    916 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
    917 	 * and it's less than ts_recent, drop it.
    918 	 */
    919 	if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
    920 	    TSTMP_LT(opti.ts_val, tp->ts_recent)) {
    921 
    922 		/* Check to see if ts_recent is over 24 days old.  */
    923 		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
    924 			/*
    925 			 * Invalidate ts_recent.  If this segment updates
    926 			 * ts_recent, the age will be reset later and ts_recent
    927 			 * will get a valid value.  If it does not, setting
    928 			 * ts_recent to zero will at least satisfy the
    929 			 * requirement that zero be placed in the timestamp
    930 			 * echo reply when ts_recent isn't valid.  The
    931 			 * age isn't reset until we get a valid ts_recent
    932 			 * because we don't want out-of-order segments to be
    933 			 * dropped when ts_recent is old.
    934 			 */
    935 			tp->ts_recent = 0;
    936 		} else {
    937 			tcpstat.tcps_rcvduppack++;
    938 			tcpstat.tcps_rcvdupbyte += ti->ti_len;
    939 			tcpstat.tcps_pawsdrop++;
    940 			goto dropafterack;
    941 		}
    942 	}
    943 
    944 	todrop = tp->rcv_nxt - ti->ti_seq;
    945 	if (todrop > 0) {
    946 		if (tiflags & TH_SYN) {
    947 			tiflags &= ~TH_SYN;
    948 			ti->ti_seq++;
    949 			if (ti->ti_urp > 1)
    950 				ti->ti_urp--;
    951 			else {
    952 				tiflags &= ~TH_URG;
    953 				ti->ti_urp = 0;
    954 			}
    955 			todrop--;
    956 		}
    957 		if (todrop > ti->ti_len ||
    958 		    (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
    959 			/*
    960 			 * Any valid FIN must be to the left of the window.
    961 			 * At this point the FIN must be a duplicate or
    962 			 * out of sequence; drop it.
    963 			 */
    964 			tiflags &= ~TH_FIN;
    965 			/*
    966 			 * Send an ACK to resynchronize and drop any data.
    967 			 * But keep on processing for RST or ACK.
    968 			 */
    969 			tp->t_flags |= TF_ACKNOW;
    970 			todrop = ti->ti_len;
    971 			tcpstat.tcps_rcvdupbyte += todrop;
    972 			tcpstat.tcps_rcvduppack++;
    973 		} else {
    974 			tcpstat.tcps_rcvpartduppack++;
    975 			tcpstat.tcps_rcvpartdupbyte += todrop;
    976 		}
    977 		m_adj(m, todrop);
    978 		ti->ti_seq += todrop;
    979 		ti->ti_len -= todrop;
    980 		if (ti->ti_urp > todrop)
    981 			ti->ti_urp -= todrop;
    982 		else {
    983 			tiflags &= ~TH_URG;
    984 			ti->ti_urp = 0;
    985 		}
    986 	}
    987 
    988 	/*
    989 	 * If new data are received on a connection after the
    990 	 * user processes are gone, then RST the other end.
    991 	 */
    992 	if ((so->so_state & SS_NOFDREF) &&
    993 	    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
    994 		tp = tcp_close(tp);
    995 		tcpstat.tcps_rcvafterclose++;
    996 		goto dropwithreset;
    997 	}
    998 
    999 	/*
   1000 	 * If segment ends after window, drop trailing data
   1001 	 * (and PUSH and FIN); if nothing left, just ACK.
   1002 	 */
   1003 	todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
   1004 	if (todrop > 0) {
   1005 		tcpstat.tcps_rcvpackafterwin++;
   1006 		if (todrop >= ti->ti_len) {
   1007 			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
   1008 			/*
   1009 			 * If a new connection request is received
   1010 			 * while in TIME_WAIT, drop the old connection
   1011 			 * and start over if the sequence numbers
   1012 			 * are above the previous ones.
   1013 			 */
   1014 			if (tiflags & TH_SYN &&
   1015 			    tp->t_state == TCPS_TIME_WAIT &&
   1016 			    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
   1017 				iss = tcp_new_iss(tp, sizeof(struct tcpcb),
   1018 						  tp->snd_nxt);
   1019 				tp = tcp_close(tp);
   1020 				/*
   1021 				 * We have already advanced the mbuf
   1022 				 * pointers past the IP+TCP headers and
   1023 				 * options.  Restore those pointers before
   1024 				 * attempting to use the TCP header again.
   1025 				 */
   1026 				m->m_data -= hdroptlen;
   1027 				m->m_len  += hdroptlen;
   1028 				goto findpcb;
   1029 			}
   1030 			/*
   1031 			 * If window is closed can only take segments at
   1032 			 * window edge, and have to drop data and PUSH from
   1033 			 * incoming segments.  Continue processing, but
   1034 			 * remember to ack.  Otherwise, drop segment
   1035 			 * and ack.
   1036 			 */
   1037 			if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
   1038 				tp->t_flags |= TF_ACKNOW;
   1039 				tcpstat.tcps_rcvwinprobe++;
   1040 			} else
   1041 				goto dropafterack;
   1042 		} else
   1043 			tcpstat.tcps_rcvbyteafterwin += todrop;
   1044 		m_adj(m, -todrop);
   1045 		ti->ti_len -= todrop;
   1046 		tiflags &= ~(TH_PUSH|TH_FIN);
   1047 	}
   1048 
   1049 	/*
   1050 	 * If last ACK falls within this segment's sequence numbers,
   1051 	 * and the timestamp is newer, record it.
   1052 	 */
   1053 	if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
   1054 	    SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
   1055 	    SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len +
   1056 		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
   1057 		tp->ts_recent_age = tcp_now;
   1058 		tp->ts_recent = opti.ts_val;
   1059 	}
   1060 
   1061 	/*
   1062 	 * If the RST bit is set examine the state:
   1063 	 *    SYN_RECEIVED STATE:
   1064 	 *	If passive open, return to LISTEN state.
   1065 	 *	If active open, inform user that connection was refused.
   1066 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
   1067 	 *	Inform user that connection was reset, and close tcb.
   1068 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
   1069 	 *	Close the tcb.
   1070 	 */
   1071 	if (tiflags&TH_RST) switch (tp->t_state) {
   1072 
   1073 	case TCPS_SYN_RECEIVED:
   1074 		so->so_error = ECONNREFUSED;
   1075 		goto close;
   1076 
   1077 	case TCPS_ESTABLISHED:
   1078 	case TCPS_FIN_WAIT_1:
   1079 	case TCPS_FIN_WAIT_2:
   1080 	case TCPS_CLOSE_WAIT:
   1081 		so->so_error = ECONNRESET;
   1082 	close:
   1083 		tp->t_state = TCPS_CLOSED;
   1084 		tcpstat.tcps_drops++;
   1085 		tp = tcp_close(tp);
   1086 		goto drop;
   1087 
   1088 	case TCPS_CLOSING:
   1089 	case TCPS_LAST_ACK:
   1090 	case TCPS_TIME_WAIT:
   1091 		tp = tcp_close(tp);
   1092 		goto drop;
   1093 	}
   1094 
   1095 	/*
   1096 	 * If a SYN is in the window, then this is an
   1097 	 * error and we send an RST and drop the connection.
   1098 	 */
   1099 	if (tiflags & TH_SYN) {
   1100 		tp = tcp_drop(tp, ECONNRESET);
   1101 		goto dropwithreset;
   1102 	}
   1103 
   1104 	/*
   1105 	 * If the ACK bit is off we drop the segment and return.
   1106 	 */
   1107 	if ((tiflags & TH_ACK) == 0) {
   1108 		if (tp->t_flags & TF_ACKNOW)
   1109 			goto dropafterack;
   1110 		else
   1111 			goto drop;
   1112 	}
   1113 
   1114 	/*
   1115 	 * Ack processing.
   1116 	 */
   1117 	switch (tp->t_state) {
   1118 
   1119 	/*
   1120 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
   1121 	 * ESTABLISHED state and continue processing, otherwise
   1122 	 * send an RST.
   1123 	 */
   1124 	case TCPS_SYN_RECEIVED:
   1125 		if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
   1126 		    SEQ_GT(ti->ti_ack, tp->snd_max))
   1127 			goto dropwithreset;
   1128 		tcpstat.tcps_connects++;
   1129 		soisconnected(so);
   1130 		tcp_established(tp);
   1131 		/* Do window scaling? */
   1132 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   1133 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
   1134 			tp->snd_scale = tp->requested_s_scale;
   1135 			tp->rcv_scale = tp->request_r_scale;
   1136 		}
   1137 		TCP_REASS_LOCK(tp);
   1138 		(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
   1139 		TCP_REASS_UNLOCK(tp);
   1140 		tp->snd_wl1 = ti->ti_seq - 1;
   1141 		/* fall into ... */
   1142 
   1143 	/*
   1144 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
   1145 	 * ACKs.  If the ack is in the range
   1146 	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
   1147 	 * then advance tp->snd_una to ti->ti_ack and drop
   1148 	 * data from the retransmission queue.  If this ACK reflects
   1149 	 * more up to date window information we update our window information.
   1150 	 */
   1151 	case TCPS_ESTABLISHED:
   1152 	case TCPS_FIN_WAIT_1:
   1153 	case TCPS_FIN_WAIT_2:
   1154 	case TCPS_CLOSE_WAIT:
   1155 	case TCPS_CLOSING:
   1156 	case TCPS_LAST_ACK:
   1157 	case TCPS_TIME_WAIT:
   1158 
   1159 		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
   1160 			if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
   1161 				tcpstat.tcps_rcvdupack++;
   1162 				/*
   1163 				 * If we have outstanding data (other than
   1164 				 * a window probe), this is a completely
   1165 				 * duplicate ack (ie, window info didn't
   1166 				 * change), the ack is the biggest we've
   1167 				 * seen and we've seen exactly our rexmt
   1168 				 * threshhold of them, assume a packet
   1169 				 * has been dropped and retransmit it.
   1170 				 * Kludge snd_nxt & the congestion
   1171 				 * window so we send only this one
   1172 				 * packet.
   1173 				 *
   1174 				 * We know we're losing at the current
   1175 				 * window size so do congestion avoidance
   1176 				 * (set ssthresh to half the current window
   1177 				 * and pull our congestion window back to
   1178 				 * the new ssthresh).
   1179 				 *
   1180 				 * Dup acks mean that packets have left the
   1181 				 * network (they're now cached at the receiver)
   1182 				 * so bump cwnd by the amount in the receiver
   1183 				 * to keep a constant cwnd packets in the
   1184 				 * network.
   1185 				 */
   1186 				if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
   1187 				    ti->ti_ack != tp->snd_una)
   1188 					tp->t_dupacks = 0;
   1189 				else if (++tp->t_dupacks == tcprexmtthresh) {
   1190 					tcp_seq onxt = tp->snd_nxt;
   1191 					u_int win =
   1192 					    min(tp->snd_wnd, tp->snd_cwnd) /
   1193 					    2 /	tp->t_segsz;
   1194 					if (SEQ_LT(ti->ti_ack, tp->snd_recover)) {
   1195 						/*
   1196 						 * False fast retransmit after
   1197 						 * timeout.  Do not cut window.
   1198 						 */
   1199 						tp->snd_cwnd += tp->t_segsz;
   1200 						tp->t_dupacks = 0;
   1201 						(void) tcp_output(tp);
   1202 						goto drop;
   1203 					}
   1204 
   1205 					if (win < 2)
   1206 						win = 2;
   1207 					tp->snd_ssthresh = win * tp->t_segsz;
   1208 					tp->snd_recover = tp->snd_max;
   1209 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
   1210 					tp->t_rtt = 0;
   1211 					tp->snd_nxt = ti->ti_ack;
   1212 					tp->snd_cwnd = tp->t_segsz;
   1213 					(void) tcp_output(tp);
   1214 					tp->snd_cwnd = tp->snd_ssthresh +
   1215 					       tp->t_segsz * tp->t_dupacks;
   1216 					if (SEQ_GT(onxt, tp->snd_nxt))
   1217 						tp->snd_nxt = onxt;
   1218 					goto drop;
   1219 				} else if (tp->t_dupacks > tcprexmtthresh) {
   1220 					tp->snd_cwnd += tp->t_segsz;
   1221 					(void) tcp_output(tp);
   1222 					goto drop;
   1223 				}
   1224 			} else
   1225 				tp->t_dupacks = 0;
   1226 			break;
   1227 		}
   1228 		/*
   1229 		 * If the congestion window was inflated to account
   1230 		 * for the other side's cached packets, retract it.
   1231 		 */
   1232 		if (!tcp_do_newreno) {
   1233 			if (tp->t_dupacks >= tcprexmtthresh &&
   1234 			    tp->snd_cwnd > tp->snd_ssthresh)
   1235 				tp->snd_cwnd = tp->snd_ssthresh;
   1236 			tp->t_dupacks = 0;
   1237 		} else if (tp->t_dupacks >= tcprexmtthresh
   1238 		    && !tcp_newreno(tp, ti)) {
   1239 			tp->snd_cwnd = tp->snd_ssthresh;
   1240 			/*
   1241 			 * Window inflation should have left us with approx.
   1242 			 * snd_ssthresh outstanding data.  But in case we
   1243 			 * would be inclined to send a burst, better to do
   1244 			 * it via the slow start mechanism.
   1245 			 */
   1246 			if (SEQ_SUB(tp->snd_max, ti->ti_ack) < tp->snd_ssthresh)
   1247 				tp->snd_cwnd = SEQ_SUB(tp->snd_max, ti->ti_ack)
   1248 				     + tp->t_segsz;
   1249 			tp->t_dupacks = 0;
   1250 		}
   1251 		if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
   1252 			tcpstat.tcps_rcvacktoomuch++;
   1253 			goto dropafterack;
   1254 		}
   1255 		acked = ti->ti_ack - tp->snd_una;
   1256 		tcpstat.tcps_rcvackpack++;
   1257 		tcpstat.tcps_rcvackbyte += acked;
   1258 
   1259 		/*
   1260 		 * If we have a timestamp reply, update smoothed
   1261 		 * round trip time.  If no timestamp is present but
   1262 		 * transmit timer is running and timed sequence
   1263 		 * number was acked, update smoothed round trip time.
   1264 		 * Since we now have an rtt measurement, cancel the
   1265 		 * timer backoff (cf., Phil Karn's retransmit alg.).
   1266 		 * Recompute the initial retransmit timer.
   1267 		 */
   1268 		if (opti.ts_present)
   1269 			tcp_xmit_timer(tp, tcp_now - opti.ts_ecr + 1);
   1270 		else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
   1271 			tcp_xmit_timer(tp,tp->t_rtt);
   1272 
   1273 		/*
   1274 		 * If all outstanding data is acked, stop retransmit
   1275 		 * timer and remember to restart (more output or persist).
   1276 		 * If there is more data to be acked, restart retransmit
   1277 		 * timer, using current (possibly backed-off) value.
   1278 		 */
   1279 		if (ti->ti_ack == tp->snd_max) {
   1280 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
   1281 			needoutput = 1;
   1282 		} else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
   1283 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   1284 		/*
   1285 		 * When new data is acked, open the congestion window.
   1286 		 * If the window gives us less than ssthresh packets
   1287 		 * in flight, open exponentially (segsz per packet).
   1288 		 * Otherwise open linearly: segsz per window
   1289 		 * (segsz^2 / cwnd per packet), plus a constant
   1290 		 * fraction of a packet (segsz/8) to help larger windows
   1291 		 * open quickly enough.
   1292 		 */
   1293 		{
   1294 		register u_int cw = tp->snd_cwnd;
   1295 		register u_int incr = tp->t_segsz;
   1296 
   1297 		if (cw > tp->snd_ssthresh)
   1298 			incr = incr * incr / cw;
   1299 		if (!tcp_do_newreno || SEQ_GEQ(ti->ti_ack, tp->snd_recover))
   1300 			tp->snd_cwnd = min(cw + incr,TCP_MAXWIN<<tp->snd_scale);
   1301 		}
   1302 		if (acked > so->so_snd.sb_cc) {
   1303 			tp->snd_wnd -= so->so_snd.sb_cc;
   1304 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
   1305 			ourfinisacked = 1;
   1306 		} else {
   1307 			sbdrop(&so->so_snd, acked);
   1308 			tp->snd_wnd -= acked;
   1309 			ourfinisacked = 0;
   1310 		}
   1311 		sowwakeup(so);
   1312 		tp->snd_una = ti->ti_ack;
   1313 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
   1314 			tp->snd_nxt = tp->snd_una;
   1315 
   1316 		switch (tp->t_state) {
   1317 
   1318 		/*
   1319 		 * In FIN_WAIT_1 STATE in addition to the processing
   1320 		 * for the ESTABLISHED state if our FIN is now acknowledged
   1321 		 * then enter FIN_WAIT_2.
   1322 		 */
   1323 		case TCPS_FIN_WAIT_1:
   1324 			if (ourfinisacked) {
   1325 				/*
   1326 				 * If we can't receive any more
   1327 				 * data, then closing user can proceed.
   1328 				 * Starting the timer is contrary to the
   1329 				 * specification, but if we don't get a FIN
   1330 				 * we'll hang forever.
   1331 				 */
   1332 				if (so->so_state & SS_CANTRCVMORE) {
   1333 					soisdisconnected(so);
   1334 					if (tcp_maxidle > 0)
   1335 						TCP_TIMER_ARM(tp, TCPT_2MSL,
   1336 						    tcp_maxidle);
   1337 				}
   1338 				tp->t_state = TCPS_FIN_WAIT_2;
   1339 			}
   1340 			break;
   1341 
   1342 	 	/*
   1343 		 * In CLOSING STATE in addition to the processing for
   1344 		 * the ESTABLISHED state if the ACK acknowledges our FIN
   1345 		 * then enter the TIME-WAIT state, otherwise ignore
   1346 		 * the segment.
   1347 		 */
   1348 		case TCPS_CLOSING:
   1349 			if (ourfinisacked) {
   1350 				tp->t_state = TCPS_TIME_WAIT;
   1351 				tcp_canceltimers(tp);
   1352 				TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   1353 				soisdisconnected(so);
   1354 			}
   1355 			break;
   1356 
   1357 		/*
   1358 		 * In LAST_ACK, we may still be waiting for data to drain
   1359 		 * and/or to be acked, as well as for the ack of our FIN.
   1360 		 * If our FIN is now acknowledged, delete the TCB,
   1361 		 * enter the closed state and return.
   1362 		 */
   1363 		case TCPS_LAST_ACK:
   1364 			if (ourfinisacked) {
   1365 				tp = tcp_close(tp);
   1366 				goto drop;
   1367 			}
   1368 			break;
   1369 
   1370 		/*
   1371 		 * In TIME_WAIT state the only thing that should arrive
   1372 		 * is a retransmission of the remote FIN.  Acknowledge
   1373 		 * it and restart the finack timer.
   1374 		 */
   1375 		case TCPS_TIME_WAIT:
   1376 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   1377 			goto dropafterack;
   1378 		}
   1379 	}
   1380 
   1381 step6:
   1382 	/*
   1383 	 * Update window information.
   1384 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
   1385 	 */
   1386 	if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
   1387 	    (tp->snd_wl1 == ti->ti_seq && SEQ_LT(tp->snd_wl2, ti->ti_ack)) ||
   1388 	    (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))) {
   1389 		/* keep track of pure window updates */
   1390 		if (ti->ti_len == 0 &&
   1391 		    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
   1392 			tcpstat.tcps_rcvwinupd++;
   1393 		tp->snd_wnd = tiwin;
   1394 		tp->snd_wl1 = ti->ti_seq;
   1395 		tp->snd_wl2 = ti->ti_ack;
   1396 		if (tp->snd_wnd > tp->max_sndwnd)
   1397 			tp->max_sndwnd = tp->snd_wnd;
   1398 		needoutput = 1;
   1399 	}
   1400 
   1401 	/*
   1402 	 * Process segments with URG.
   1403 	 */
   1404 	if ((tiflags & TH_URG) && ti->ti_urp &&
   1405 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   1406 		/*
   1407 		 * This is a kludge, but if we receive and accept
   1408 		 * random urgent pointers, we'll crash in
   1409 		 * soreceive.  It's hard to imagine someone
   1410 		 * actually wanting to send this much urgent data.
   1411 		 */
   1412 		if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
   1413 			ti->ti_urp = 0;			/* XXX */
   1414 			tiflags &= ~TH_URG;		/* XXX */
   1415 			goto dodata;			/* XXX */
   1416 		}
   1417 		/*
   1418 		 * If this segment advances the known urgent pointer,
   1419 		 * then mark the data stream.  This should not happen
   1420 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
   1421 		 * a FIN has been received from the remote side.
   1422 		 * In these states we ignore the URG.
   1423 		 *
   1424 		 * According to RFC961 (Assigned Protocols),
   1425 		 * the urgent pointer points to the last octet
   1426 		 * of urgent data.  We continue, however,
   1427 		 * to consider it to indicate the first octet
   1428 		 * of data past the urgent section as the original
   1429 		 * spec states (in one of two places).
   1430 		 */
   1431 		if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
   1432 			tp->rcv_up = ti->ti_seq + ti->ti_urp;
   1433 			so->so_oobmark = so->so_rcv.sb_cc +
   1434 			    (tp->rcv_up - tp->rcv_nxt) - 1;
   1435 			if (so->so_oobmark == 0)
   1436 				so->so_state |= SS_RCVATMARK;
   1437 			sohasoutofband(so);
   1438 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
   1439 		}
   1440 		/*
   1441 		 * Remove out of band data so doesn't get presented to user.
   1442 		 * This can happen independent of advancing the URG pointer,
   1443 		 * but if two URG's are pending at once, some out-of-band
   1444 		 * data may creep in... ick.
   1445 		 */
   1446 		if (ti->ti_urp <= (u_int16_t) ti->ti_len
   1447 #ifdef SO_OOBINLINE
   1448 		     && (so->so_options & SO_OOBINLINE) == 0
   1449 #endif
   1450 		     )
   1451 			tcp_pulloutofband(so, ti, m);
   1452 	} else
   1453 		/*
   1454 		 * If no out of band data is expected,
   1455 		 * pull receive urgent pointer along
   1456 		 * with the receive window.
   1457 		 */
   1458 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
   1459 			tp->rcv_up = tp->rcv_nxt;
   1460 dodata:							/* XXX */
   1461 
   1462 	/*
   1463 	 * Process the segment text, merging it into the TCP sequencing queue,
   1464 	 * and arranging for acknowledgment of receipt if necessary.
   1465 	 * This process logically involves adjusting tp->rcv_wnd as data
   1466 	 * is presented to the user (this happens in tcp_usrreq.c,
   1467 	 * case PRU_RCVD).  If a FIN has already been received on this
   1468 	 * connection then we just ignore the text.
   1469 	 */
   1470 	if ((ti->ti_len || (tiflags & TH_FIN)) &&
   1471 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   1472 		TCP_REASS(tp, ti, m, so, tiflags);
   1473 		/*
   1474 		 * Note the amount of data that peer has sent into
   1475 		 * our window, in order to estimate the sender's
   1476 		 * buffer size.
   1477 		 */
   1478 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
   1479 	} else {
   1480 		m_freem(m);
   1481 		tiflags &= ~TH_FIN;
   1482 	}
   1483 
   1484 	/*
   1485 	 * If FIN is received ACK the FIN and let the user know
   1486 	 * that the connection is closing.  Ignore a FIN received before
   1487 	 * the connection is fully established.
   1488 	 */
   1489 	if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
   1490 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   1491 			socantrcvmore(so);
   1492 			tp->t_flags |= TF_ACKNOW;
   1493 			tp->rcv_nxt++;
   1494 		}
   1495 		switch (tp->t_state) {
   1496 
   1497 	 	/*
   1498 		 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
   1499 		 */
   1500 		case TCPS_ESTABLISHED:
   1501 			tp->t_state = TCPS_CLOSE_WAIT;
   1502 			break;
   1503 
   1504 	 	/*
   1505 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
   1506 		 * enter the CLOSING state.
   1507 		 */
   1508 		case TCPS_FIN_WAIT_1:
   1509 			tp->t_state = TCPS_CLOSING;
   1510 			break;
   1511 
   1512 	 	/*
   1513 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
   1514 		 * starting the time-wait timer, turning off the other
   1515 		 * standard timers.
   1516 		 */
   1517 		case TCPS_FIN_WAIT_2:
   1518 			tp->t_state = TCPS_TIME_WAIT;
   1519 			tcp_canceltimers(tp);
   1520 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   1521 			soisdisconnected(so);
   1522 			break;
   1523 
   1524 		/*
   1525 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
   1526 		 */
   1527 		case TCPS_TIME_WAIT:
   1528 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   1529 			break;
   1530 		}
   1531 	}
   1532 	if (so->so_options & SO_DEBUG)
   1533 		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
   1534 
   1535 	/*
   1536 	 * Return any desired output.
   1537 	 */
   1538 	if (needoutput || (tp->t_flags & TF_ACKNOW))
   1539 		(void) tcp_output(tp);
   1540 	return;
   1541 
   1542 badsyn:
   1543 	/*
   1544 	 * Received a bad SYN.  Increment counters and dropwithreset.
   1545 	 */
   1546 	tcpstat.tcps_badsyn++;
   1547 	tp = NULL;
   1548 	goto dropwithreset;
   1549 
   1550 dropafterack:
   1551 	/*
   1552 	 * Generate an ACK dropping incoming segment if it occupies
   1553 	 * sequence space, where the ACK reflects our state.
   1554 	 */
   1555 	if (tiflags & TH_RST)
   1556 		goto drop;
   1557 	m_freem(m);
   1558 	tp->t_flags |= TF_ACKNOW;
   1559 	(void) tcp_output(tp);
   1560 	return;
   1561 
   1562 dropwithreset:
   1563 	/*
   1564 	 * Generate a RST, dropping incoming segment.
   1565 	 * Make ACK acceptable to originator of segment.
   1566 	 * Don't bother to respond if destination was broadcast/multicast.
   1567 	 */
   1568 	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
   1569 	    IN_MULTICAST(ti->ti_dst.s_addr))
   1570 		goto drop;
   1571 	if (tiflags & TH_ACK)
   1572 		(void)tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
   1573 	else {
   1574 		if (tiflags & TH_SYN)
   1575 			ti->ti_len++;
   1576 		(void)tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
   1577 		    TH_RST|TH_ACK);
   1578 	}
   1579 	return;
   1580 
   1581 drop:
   1582 	/*
   1583 	 * Drop space held by incoming segment and return.
   1584 	 */
   1585 	if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
   1586 		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
   1587 	m_freem(m);
   1588 	return;
   1589 }
   1590 
   1591 void
   1592 tcp_dooptions(tp, cp, cnt, ti, oi)
   1593 	struct tcpcb *tp;
   1594 	u_char *cp;
   1595 	int cnt;
   1596 	struct tcpiphdr *ti;
   1597 	struct tcp_opt_info *oi;
   1598 {
   1599 	u_int16_t mss;
   1600 	int opt, optlen;
   1601 
   1602 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1603 		opt = cp[0];
   1604 		if (opt == TCPOPT_EOL)
   1605 			break;
   1606 		if (opt == TCPOPT_NOP)
   1607 			optlen = 1;
   1608 		else {
   1609 			optlen = cp[1];
   1610 			if (optlen <= 0)
   1611 				break;
   1612 		}
   1613 		switch (opt) {
   1614 
   1615 		default:
   1616 			continue;
   1617 
   1618 		case TCPOPT_MAXSEG:
   1619 			if (optlen != TCPOLEN_MAXSEG)
   1620 				continue;
   1621 			if (!(ti->ti_flags & TH_SYN))
   1622 				continue;
   1623 			bcopy(cp + 2, &mss, sizeof(mss));
   1624 			oi->maxseg = ntohs(mss);
   1625 			break;
   1626 
   1627 		case TCPOPT_WINDOW:
   1628 			if (optlen != TCPOLEN_WINDOW)
   1629 				continue;
   1630 			if (!(ti->ti_flags & TH_SYN))
   1631 				continue;
   1632 			tp->t_flags |= TF_RCVD_SCALE;
   1633 			tp->requested_s_scale = cp[2];
   1634 			if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
   1635 				log(LOG_ERR, "TCP: invalid wscale %d from "
   1636 				    "0x%08x, assuming %d\n",
   1637 				    tp->requested_s_scale,
   1638 				    ntohl(ti->ti_src.s_addr),
   1639 				    TCP_MAX_WINSHIFT);
   1640 				tp->requested_s_scale = TCP_MAX_WINSHIFT;
   1641 			}
   1642 			break;
   1643 
   1644 		case TCPOPT_TIMESTAMP:
   1645 			if (optlen != TCPOLEN_TIMESTAMP)
   1646 				continue;
   1647 			oi->ts_present = 1;
   1648 			bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
   1649 			NTOHL(oi->ts_val);
   1650 			bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
   1651 			NTOHL(oi->ts_ecr);
   1652 
   1653 			/*
   1654 			 * A timestamp received in a SYN makes
   1655 			 * it ok to send timestamp requests and replies.
   1656 			 */
   1657 			if (ti->ti_flags & TH_SYN) {
   1658 				tp->t_flags |= TF_RCVD_TSTMP;
   1659 				tp->ts_recent = oi->ts_val;
   1660 				tp->ts_recent_age = tcp_now;
   1661 			}
   1662 			break;
   1663 		case TCPOPT_SACK_PERMITTED:
   1664 			if (optlen != TCPOLEN_SACK_PERMITTED)
   1665 				continue;
   1666 			if (!(ti->ti_flags & TH_SYN))
   1667 				continue;
   1668 			tp->t_flags &= ~TF_CANT_TXSACK;
   1669 			break;
   1670 
   1671 		case TCPOPT_SACK:
   1672 			if (tp->t_flags & TF_IGNR_RXSACK)
   1673 				continue;
   1674 			if (optlen % 8 != 2 || optlen < 10)
   1675 				continue;
   1676 			cp += 2;
   1677 			optlen -= 2;
   1678 			for (; optlen > 0; cp -= 8, optlen -= 8) {
   1679 				tcp_seq lwe, rwe;
   1680 				bcopy((char *)cp, (char *) &lwe, sizeof(lwe));
   1681 				NTOHL(lwe);
   1682 				bcopy((char *)cp, (char *) &rwe, sizeof(rwe));
   1683 				NTOHL(rwe);
   1684 				/* tcp_mark_sacked(tp, lwe, rwe); */
   1685 			}
   1686 			break;
   1687 		}
   1688 	}
   1689 }
   1690 
   1691 /*
   1692  * Pull out of band byte out of a segment so
   1693  * it doesn't appear in the user's data queue.
   1694  * It is still reflected in the segment length for
   1695  * sequencing purposes.
   1696  */
   1697 void
   1698 tcp_pulloutofband(so, ti, m)
   1699 	struct socket *so;
   1700 	struct tcpiphdr *ti;
   1701 	register struct mbuf *m;
   1702 {
   1703 	int cnt = ti->ti_urp - 1;
   1704 
   1705 	while (cnt >= 0) {
   1706 		if (m->m_len > cnt) {
   1707 			char *cp = mtod(m, caddr_t) + cnt;
   1708 			struct tcpcb *tp = sototcpcb(so);
   1709 
   1710 			tp->t_iobc = *cp;
   1711 			tp->t_oobflags |= TCPOOB_HAVEDATA;
   1712 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
   1713 			m->m_len--;
   1714 			return;
   1715 		}
   1716 		cnt -= m->m_len;
   1717 		m = m->m_next;
   1718 		if (m == 0)
   1719 			break;
   1720 	}
   1721 	panic("tcp_pulloutofband");
   1722 }
   1723 
   1724 /*
   1725  * Collect new round-trip time estimate
   1726  * and update averages and current timeout.
   1727  */
   1728 void
   1729 tcp_xmit_timer(tp, rtt)
   1730 	register struct tcpcb *tp;
   1731 	short rtt;
   1732 {
   1733 	register short delta;
   1734 	short rttmin;
   1735 
   1736 	tcpstat.tcps_rttupdated++;
   1737 	--rtt;
   1738 	if (tp->t_srtt != 0) {
   1739 		/*
   1740 		 * srtt is stored as fixed point with 3 bits after the
   1741 		 * binary point (i.e., scaled by 8).  The following magic
   1742 		 * is equivalent to the smoothing algorithm in rfc793 with
   1743 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
   1744 		 * point).  Adjust rtt to origin 0.
   1745 		 */
   1746 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
   1747 		if ((tp->t_srtt += delta) <= 0)
   1748 			tp->t_srtt = 1 << 2;
   1749 		/*
   1750 		 * We accumulate a smoothed rtt variance (actually, a
   1751 		 * smoothed mean difference), then set the retransmit
   1752 		 * timer to smoothed rtt + 4 times the smoothed variance.
   1753 		 * rttvar is stored as fixed point with 2 bits after the
   1754 		 * binary point (scaled by 4).  The following is
   1755 		 * equivalent to rfc793 smoothing with an alpha of .75
   1756 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
   1757 		 * rfc793's wired-in beta.
   1758 		 */
   1759 		if (delta < 0)
   1760 			delta = -delta;
   1761 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
   1762 		if ((tp->t_rttvar += delta) <= 0)
   1763 			tp->t_rttvar = 1 << 2;
   1764 	} else {
   1765 		/*
   1766 		 * No rtt measurement yet - use the unsmoothed rtt.
   1767 		 * Set the variance to half the rtt (so our first
   1768 		 * retransmit happens at 3*rtt).
   1769 		 */
   1770 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
   1771 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
   1772 	}
   1773 	tp->t_rtt = 0;
   1774 	tp->t_rxtshift = 0;
   1775 
   1776 	/*
   1777 	 * the retransmit should happen at rtt + 4 * rttvar.
   1778 	 * Because of the way we do the smoothing, srtt and rttvar
   1779 	 * will each average +1/2 tick of bias.  When we compute
   1780 	 * the retransmit timer, we want 1/2 tick of rounding and
   1781 	 * 1 extra tick because of +-1/2 tick uncertainty in the
   1782 	 * firing of the timer.  The bias will give us exactly the
   1783 	 * 1.5 tick we need.  But, because the bias is
   1784 	 * statistical, we have to test that we don't drop below
   1785 	 * the minimum feasible timer (which is 2 ticks).
   1786 	 */
   1787 	if (tp->t_rttmin > rtt + 2)
   1788 		rttmin = tp->t_rttmin;
   1789 	else
   1790 		rttmin = rtt + 2;
   1791 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX);
   1792 
   1793 	/*
   1794 	 * We received an ack for a packet that wasn't retransmitted;
   1795 	 * it is probably safe to discard any error indications we've
   1796 	 * received recently.  This isn't quite right, but close enough
   1797 	 * for now (a route might have failed after we sent a segment,
   1798 	 * and the return path might not be symmetrical).
   1799 	 */
   1800 	tp->t_softerror = 0;
   1801 }
   1802 
   1803 /*
   1804  * Checks for partial ack.  If partial ack arrives, force the retransmission
   1805  * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
   1806  * 1.  By setting snd_nxt to ti_ack, this forces retransmission timer to
   1807  * be started again.  If the ack advances at least to tp->snd_recover, return 0.
   1808  */
   1809 int
   1810 tcp_newreno(tp, ti)
   1811 	struct tcpcb *tp;
   1812 	struct tcpiphdr *ti;
   1813 {
   1814 	if (SEQ_LT(ti->ti_ack, tp->snd_recover)) {
   1815 	        tcp_seq onxt = tp->snd_nxt;
   1816 	        tcp_seq ouna = tp->snd_una;  /* Haven't updated snd_una yet*/
   1817 	        u_long  ocwnd = tp->snd_cwnd;
   1818 		TCP_TIMER_DISARM(tp, TCPT_REXMT);
   1819 	        tp->t_rtt = 0;
   1820 	        tp->snd_nxt = ti->ti_ack;
   1821 	        tp->snd_cwnd = tp->t_segsz;
   1822 	        tp->snd_una = ti->ti_ack;
   1823 	        (void) tcp_output(tp);
   1824 	        tp->snd_cwnd = ocwnd;
   1825 	        tp->snd_una = ouna;
   1826 	        if (SEQ_GT(onxt, tp->snd_nxt))
   1827 	                tp->snd_nxt = onxt;
   1828 	        /*
   1829 	         * Partial window deflation.  Relies on fact that tp->snd_una
   1830 	         * not updated yet.
   1831 	         */
   1832 	        tp->snd_cwnd -= (ti->ti_ack - tp->snd_una - tp->t_segsz);
   1833 	        return 1;
   1834 	}
   1835 	return 0;
   1836 }
   1837 
   1838 
   1839 /*
   1840  * TCP compressed state engine.  Currently used to hold compressed
   1841  * state for SYN_RECEIVED.
   1842  */
   1843 
   1844 u_long	syn_cache_count;
   1845 u_int32_t syn_hash1, syn_hash2;
   1846 
   1847 #define SYN_HASH(sa, sp, dp) \
   1848 	((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
   1849 				     ((u_int32_t)(sp)))^syn_hash2)))
   1850 
   1851 LIST_HEAD(, syn_cache_head) tcp_syn_cache_queue;
   1852 
   1853 #define	SYN_CACHE_RM(sc, scp)						\
   1854 do {									\
   1855 	TAILQ_REMOVE(&(scp)->sch_queue, (sc), sc_queue);		\
   1856 	if (--(scp)->sch_length	== 0)					\
   1857 		LIST_REMOVE((scp), sch_headq);				\
   1858 	syn_cache_count--;						\
   1859 } while (0)
   1860 
   1861 #define	SYN_CACHE_PUT(sc)						\
   1862 do {									\
   1863 	if ((sc)->sc_ipopts)						\
   1864 		(void) m_free((sc)->sc_ipopts);				\
   1865 	if ((sc)->sc_route.ro_rt != NULL)				\
   1866 		RTFREE((sc)->sc_route.ro_rt);				\
   1867 	pool_put(&syn_cache_pool, (sc));				\
   1868 } while (0)
   1869 
   1870 struct pool syn_cache_pool;
   1871 
   1872 void
   1873 syn_cache_init()
   1874 {
   1875 	int i;
   1876 
   1877 	/* Initialize the hash bucket queues. */
   1878 	for (i = 0; i < tcp_syn_cache_size; i++)
   1879 		TAILQ_INIT(&tcp_syn_cache[i].sch_queue);
   1880 
   1881 	/* Initialize the active hash bucket cache. */
   1882 	LIST_INIT(&tcp_syn_cache_queue);
   1883 
   1884 	/* Initialize the syn cache pool. */
   1885 	pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
   1886 	    "synpl", 0, NULL, NULL, M_PCB);
   1887 }
   1888 
   1889 void
   1890 syn_cache_insert(sc)
   1891 	struct syn_cache *sc;
   1892 {
   1893 	struct syn_cache_head *scp, *scp2, *sce;
   1894 	struct syn_cache *sc2;
   1895 	int s;
   1896 
   1897 	/*
   1898 	 * If there are no entries in the hash table, reinitialize
   1899 	 * the hash secrets.
   1900 	 */
   1901 	if (syn_cache_count == 0) {
   1902 		struct timeval tv;
   1903 		microtime(&tv);
   1904 		syn_hash1 = random() ^ (u_long)&sc;
   1905 		syn_hash2 = random() ^ tv.tv_usec;
   1906 	}
   1907 
   1908 	sc->sc_hash = SYN_HASH(&sc->sc_src, sc->sc_sport, sc->sc_dport);
   1909 	scp = &tcp_syn_cache[sc->sc_hash % tcp_syn_cache_size];
   1910 
   1911 	/*
   1912 	 * Make sure that we don't overflow the per-bucket
   1913 	 * limit or the total cache size limit.
   1914 	 */
   1915 	s = splsoftnet();
   1916 	if (scp->sch_length >= tcp_syn_bucket_limit) {
   1917 		tcpstat.tcps_sc_bucketoverflow++;
   1918 		/*
   1919 		 * The bucket is full.  Toss the first (i.e. oldest)
   1920 		 * element in this bucket.
   1921 		 */
   1922 		sc2 = TAILQ_FIRST(&scp->sch_queue);
   1923 		SYN_CACHE_RM(sc2, scp);
   1924 		SYN_CACHE_PUT(sc2);
   1925 	} else if (syn_cache_count >= tcp_syn_cache_limit) {
   1926 		tcpstat.tcps_sc_overflowed++;
   1927 		/*
   1928 		 * The cache is full.  Toss the first (i.e. oldest)
   1929 		 * element in the first non-empty bucket we can find.
   1930 		 */
   1931 		scp2 = scp;
   1932 		if (TAILQ_FIRST(&scp2->sch_queue) == NULL) {
   1933 			sce = &tcp_syn_cache[tcp_syn_cache_size];
   1934 			for (++scp2; scp2 != scp; scp2++) {
   1935 				if (scp2 >= sce)
   1936 					scp2 = &tcp_syn_cache[0];
   1937 				if (TAILQ_FIRST(&scp2->sch_queue) != NULL)
   1938 					break;
   1939 			}
   1940 		}
   1941 		sc2 = TAILQ_FIRST(&scp2->sch_queue);
   1942 		if (sc2 == NULL) {
   1943 			SYN_CACHE_PUT(sc);
   1944 			return;
   1945 		}
   1946 		SYN_CACHE_RM(sc2, scp2);
   1947 		SYN_CACHE_PUT(sc2);
   1948 	}
   1949 
   1950 	/* Set entry's timer. */
   1951 	PRT_SLOW_ARM(sc->sc_timer, tcp_syn_cache_timeo);
   1952 
   1953 	/* Put it into the bucket. */
   1954 	TAILQ_INSERT_TAIL(&scp->sch_queue, sc, sc_queue);
   1955 	if (++scp->sch_length == 1)
   1956 		LIST_INSERT_HEAD(&tcp_syn_cache_queue, scp, sch_headq);
   1957 	syn_cache_count++;
   1958 
   1959 	tcpstat.tcps_sc_added++;
   1960 	splx(s);
   1961 }
   1962 
   1963 /*
   1964  * Walk down the cache list, looking for expired entries in each bucket.
   1965  */
   1966 void
   1967 syn_cache_timer()
   1968 {
   1969 	struct syn_cache_head *scp, *nscp;
   1970 	struct syn_cache *sc, *nsc;
   1971 	int s;
   1972 
   1973 	s = splsoftnet();
   1974 	for (scp = LIST_FIRST(&tcp_syn_cache_queue); scp != NULL; scp = nscp) {
   1975 #ifdef DIAGNOSTIC
   1976 		if (TAILQ_FIRST(&scp->sch_queue) == NULL)
   1977 			panic("syn_cache_timer: queue inconsistency");
   1978 #endif
   1979 		nscp = LIST_NEXT(scp, sch_headq);
   1980 		for (sc = TAILQ_FIRST(&scp->sch_queue);
   1981 		     sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_timer);
   1982 		     sc = nsc) {
   1983 			nsc = TAILQ_NEXT(sc, sc_queue);
   1984 			tcpstat.tcps_sc_timed_out++;
   1985 			SYN_CACHE_RM(sc, scp);
   1986 			SYN_CACHE_PUT(sc);
   1987 		}
   1988 	}
   1989 	splx(s);
   1990 }
   1991 
   1992 /*
   1993  * Find an entry in the syn cache.
   1994  */
   1995 struct syn_cache *
   1996 syn_cache_lookup(ti, headp)
   1997 	struct tcpiphdr *ti;
   1998 	struct syn_cache_head **headp;
   1999 {
   2000 	struct syn_cache *sc;
   2001 	struct syn_cache_head *scp;
   2002 	u_int32_t hash;
   2003 	int s;
   2004 
   2005 	hash = SYN_HASH(&ti->ti_src, ti->ti_sport, ti->ti_dport);
   2006 
   2007 	scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
   2008 	*headp = scp;
   2009 	s = splsoftnet();
   2010 	for (sc = TAILQ_FIRST(&scp->sch_queue); sc != NULL;
   2011 	     sc = TAILQ_NEXT(sc, sc_queue)) {
   2012 		if (sc->sc_hash != hash)
   2013 			continue;
   2014 		if (sc->sc_src.s_addr == ti->ti_src.s_addr &&
   2015 		    sc->sc_sport == ti->ti_sport &&
   2016 		    sc->sc_dport == ti->ti_dport &&
   2017 		    sc->sc_dst.s_addr == ti->ti_dst.s_addr) {
   2018 			splx(s);
   2019 			return (sc);
   2020 		}
   2021 	}
   2022 	splx(s);
   2023 	return (NULL);
   2024 }
   2025 
   2026 /*
   2027  * This function gets called when we receive an ACK for a
   2028  * socket in the LISTEN state.  We look up the connection
   2029  * in the syn cache, and if its there, we pull it out of
   2030  * the cache and turn it into a full-blown connection in
   2031  * the SYN-RECEIVED state.
   2032  *
   2033  * The return values may not be immediately obvious, and their effects
   2034  * can be subtle, so here they are:
   2035  *
   2036  *	NULL	SYN was not found in cache; caller should drop the
   2037  *		packet and send an RST.
   2038  *
   2039  *	-1	We were unable to create the new connection, and are
   2040  *		aborting it.  An ACK,RST is being sent to the peer
   2041  *		(unless we got screwey sequence numbners; see below),
   2042  *		because the 3-way handshake has been completed.  Caller
   2043  *		should not free the mbuf, since we may be using it.  If
   2044  *		we are not, we will free it.
   2045  *
   2046  *	Otherwise, the return value is a pointer to the new socket
   2047  *	associated with the connection.
   2048  */
   2049 struct socket *
   2050 syn_cache_get(so, m)
   2051 	struct socket *so;
   2052 	struct mbuf *m;
   2053 {
   2054 	struct syn_cache *sc;
   2055 	struct syn_cache_head *scp;
   2056 	register struct inpcb *inp;
   2057 	register struct tcpcb *tp = 0;
   2058 	register struct tcpiphdr *ti;
   2059 	struct sockaddr_in *sin;
   2060 	struct mbuf *am;
   2061 	long win;
   2062 	int s;
   2063 
   2064 	ti = mtod(m, struct tcpiphdr *);
   2065 	s = splsoftnet();
   2066 	if ((sc = syn_cache_lookup(ti, &scp)) == NULL) {
   2067 		splx(s);
   2068 		return (NULL);
   2069 	}
   2070 
   2071 	win = sbspace(&so->so_rcv);
   2072 	if (win > TCP_MAXWIN)
   2073 		win = TCP_MAXWIN;
   2074 
   2075 	/*
   2076 	 * Verify the sequence and ack numbers.  Try getting the correct
   2077 	 * response again.
   2078 	 */
   2079 	if ((ti->ti_ack != sc->sc_iss + 1) ||
   2080 	    SEQ_LEQ(ti->ti_seq, sc->sc_irs) ||
   2081 	    SEQ_GT(ti->ti_seq, sc->sc_irs + 1 + win)) {
   2082 		(void) syn_cache_respond(sc, m, win, 0);
   2083 		splx(s);
   2084 		return ((struct socket *)(-1));
   2085 	}
   2086 
   2087 	/* Remove this cache entry */
   2088 	SYN_CACHE_RM(sc, scp);
   2089 	splx(s);
   2090 
   2091 	/*
   2092 	 * Ok, create the full blown connection, and set things up
   2093 	 * as they would have been set up if we had created the
   2094 	 * connection when the SYN arrived.  If we can't create
   2095 	 * the connection, abort it.
   2096 	 */
   2097 	so = sonewconn(so, SS_ISCONNECTED);
   2098 	if (so == NULL)
   2099 		goto resetandabort;
   2100 
   2101 	inp = sotoinpcb(so);
   2102 	inp->inp_laddr = sc->sc_dst;
   2103 	inp->inp_lport = sc->sc_dport;
   2104 	in_pcbstate(inp, INP_BOUND);
   2105 	inp->inp_options = ip_srcroute();
   2106 	if (inp->inp_options == NULL) {
   2107 		inp->inp_options = sc->sc_ipopts;
   2108 		sc->sc_ipopts = NULL;
   2109 	}
   2110 
   2111 	/*
   2112 	 * Give the new socket our cached route reference.
   2113 	 */
   2114 	inp->inp_route = sc->sc_route;		/* struct assignment */
   2115 	sc->sc_route.ro_rt = NULL;
   2116 
   2117 	am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
   2118 	if (am == NULL)
   2119 		goto resetandabort;
   2120 	am->m_len = sizeof(struct sockaddr_in);
   2121 	sin = mtod(am, struct sockaddr_in *);
   2122 	sin->sin_family = AF_INET;
   2123 	sin->sin_len = sizeof(*sin);
   2124 	sin->sin_addr = sc->sc_src;
   2125 	sin->sin_port = sc->sc_sport;
   2126 	bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
   2127 	if (in_pcbconnect(inp, am)) {
   2128 		(void) m_free(am);
   2129 		goto resetandabort;
   2130 	}
   2131 	(void) m_free(am);
   2132 
   2133 	tp = intotcpcb(inp);
   2134 	if (sc->sc_request_r_scale != 15) {
   2135 		tp->requested_s_scale = sc->sc_requested_s_scale;
   2136 		tp->request_r_scale = sc->sc_request_r_scale;
   2137 		tp->snd_scale = sc->sc_requested_s_scale;
   2138 		tp->rcv_scale = sc->sc_request_r_scale;
   2139 		tp->t_flags |= TF_RCVD_SCALE;
   2140 	}
   2141 	if (sc->sc_flags & SCF_TIMESTAMP)
   2142 		tp->t_flags |= TF_RCVD_TSTMP;
   2143 
   2144 	tp->t_template = tcp_template(tp);
   2145 	if (tp->t_template == 0) {
   2146 		tp = tcp_drop(tp, ENOBUFS);	/* destroys socket */
   2147 		so = NULL;
   2148 		m_freem(m);
   2149 		goto abort;
   2150 	}
   2151 
   2152 	tp->iss = sc->sc_iss;
   2153 	tp->irs = sc->sc_irs;
   2154 	tcp_sendseqinit(tp);
   2155 	tcp_rcvseqinit(tp);
   2156 	tp->t_state = TCPS_SYN_RECEIVED;
   2157 	TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
   2158 	tcpstat.tcps_accepts++;
   2159 
   2160 	/* Initialize tp->t_ourmss before we deal with the peer's! */
   2161 	tp->t_ourmss = sc->sc_ourmaxseg;
   2162 	tcp_mss_from_peer(tp, sc->sc_peermaxseg);
   2163 
   2164 	/*
   2165 	 * Initialize the initial congestion window.  If we
   2166 	 * had to retransmit the SYN,ACK, we must initialize cwnd
   2167 	 * to 1 segment (i.e. the Loss Window).
   2168 	 */
   2169 	if (sc->sc_rexmt_count)
   2170 		tp->snd_cwnd = tp->t_peermss;
   2171 	else
   2172 		tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win, tp->t_peermss);
   2173 
   2174 	tcp_rmx_rtt(tp);
   2175 	tp->snd_wl1 = sc->sc_irs;
   2176 	tp->rcv_up = sc->sc_irs + 1;
   2177 
   2178 	/*
   2179 	 * This is what whould have happened in tcp_ouput() when
   2180 	 * the SYN,ACK was sent.
   2181 	 */
   2182 	tp->snd_up = tp->snd_una;
   2183 	tp->snd_max = tp->snd_nxt = tp->iss+1;
   2184 	TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   2185 	if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
   2186 		tp->rcv_adv = tp->rcv_nxt + win;
   2187 	tp->last_ack_sent = tp->rcv_nxt;
   2188 
   2189 	tcpstat.tcps_sc_completed++;
   2190 	SYN_CACHE_PUT(sc);
   2191 	return (so);
   2192 
   2193 resetandabort:
   2194 	(void) tcp_respond(NULL, ti, m, ti->ti_seq+ti->ti_len,
   2195 	    (tcp_seq)0, TH_RST|TH_ACK);
   2196 abort:
   2197 	if (so != NULL)
   2198 		(void) soabort(so);
   2199 	SYN_CACHE_PUT(sc);
   2200 	tcpstat.tcps_sc_aborted++;
   2201 	return ((struct socket *)(-1));
   2202 }
   2203 
   2204 /*
   2205  * This function is called when we get a RST for a
   2206  * non-existant connection, so that we can see if the
   2207  * connection is in the syn cache.  If it is, zap it.
   2208  */
   2209 
   2210 void
   2211 syn_cache_reset(ti)
   2212 	register struct tcpiphdr *ti;
   2213 {
   2214 	struct syn_cache *sc;
   2215 	struct syn_cache_head *scp;
   2216 	int s = splsoftnet();
   2217 
   2218 	if ((sc = syn_cache_lookup(ti, &scp)) == NULL) {
   2219 		splx(s);
   2220 		return;
   2221 	}
   2222 	if (SEQ_LT(ti->ti_seq,sc->sc_irs) ||
   2223 	    SEQ_GT(ti->ti_seq, sc->sc_irs+1)) {
   2224 		splx(s);
   2225 		return;
   2226 	}
   2227 	SYN_CACHE_RM(sc, scp);
   2228 	splx(s);
   2229 	tcpstat.tcps_sc_reset++;
   2230 	SYN_CACHE_PUT(sc);
   2231 }
   2232 
   2233 void
   2234 syn_cache_unreach(ip, th)
   2235 	struct ip *ip;
   2236 	struct tcphdr *th;
   2237 {
   2238 	struct syn_cache *sc;
   2239 	struct syn_cache_head *scp;
   2240 	struct tcpiphdr ti2;
   2241 	int s;
   2242 
   2243 	ti2.ti_src.s_addr = ip->ip_dst.s_addr;
   2244 	ti2.ti_dst.s_addr = ip->ip_src.s_addr;
   2245 	ti2.ti_sport = th->th_dport;
   2246 	ti2.ti_dport = th->th_sport;
   2247 
   2248 	s = splsoftnet();
   2249 	if ((sc = syn_cache_lookup(&ti2, &scp)) == NULL) {
   2250 		splx(s);
   2251 		return;
   2252 	}
   2253 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
   2254 	if (ntohl (th->th_seq) != sc->sc_iss) {
   2255 		splx(s);
   2256 		return;
   2257 	}
   2258 
   2259 	/*
   2260 	 * If we've rertransmitted 3 times and this is our second error,
   2261 	 * we remove the entry.  Otherwise, we allow it to continue on.
   2262 	 * This prevents us from incorrectly nuking an entry during a
   2263 	 * spurious network outage.
   2264 	 *
   2265 	 * See tcp_notify().
   2266 	 */
   2267 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rexmt_count < 3) {
   2268 		sc->sc_flags |= SCF_UNREACH;
   2269 		splx(s);
   2270 		return;
   2271 	}
   2272 
   2273 	SYN_CACHE_RM(sc, scp);
   2274 	splx(s);
   2275 	tcpstat.tcps_sc_unreach++;
   2276 	SYN_CACHE_PUT(sc);
   2277 }
   2278 
   2279 /*
   2280  * Given a LISTEN socket and an inbound SYN request, add
   2281  * this to the syn cache, and send back a segment:
   2282  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
   2283  * to the source.
   2284  *
   2285  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
   2286  * Doing so would require that we hold onto the data and deliver it
   2287  * to the application.  However, if we are the target of a SYN-flood
   2288  * DoS attack, an attacker could send data which would eventually
   2289  * consume all available buffer space if it were ACKed.  By not ACKing
   2290  * the data, we avoid this DoS scenario.
   2291  */
   2292 
   2293 int
   2294 syn_cache_add(so, m, optp, optlen, oi)
   2295 	struct socket *so;
   2296 	struct mbuf *m;
   2297 	u_char *optp;
   2298 	int optlen;
   2299 	struct tcp_opt_info *oi;
   2300 {
   2301 	register struct tcpiphdr *ti;
   2302 	struct tcpcb tb, *tp;
   2303 	long win;
   2304 	struct syn_cache *sc;
   2305 	struct syn_cache_head *scp;
   2306 	struct mbuf *ipopts;
   2307 
   2308 	tp = sototcpcb(so);
   2309 	ti = mtod(m, struct tcpiphdr *);
   2310 
   2311 	/*
   2312 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
   2313 	 * in_broadcast() should never return true on a received
   2314 	 * packet with M_BCAST not set.
   2315 	 */
   2316 	if (m->m_flags & (M_BCAST|M_MCAST) ||
   2317 	    IN_MULTICAST(ti->ti_src.s_addr) ||
   2318 	    IN_MULTICAST(ti->ti_dst.s_addr))
   2319 		return (0);
   2320 
   2321 	/*
   2322 	 * Initialize some local state.
   2323 	 */
   2324 	win = sbspace(&so->so_rcv);
   2325 	if (win > TCP_MAXWIN)
   2326 		win = TCP_MAXWIN;
   2327 
   2328 	/*
   2329 	 * Remember the IP options, if any.
   2330 	 */
   2331 	ipopts = ip_srcroute();
   2332 
   2333 	if (optp) {
   2334 		tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
   2335 		tcp_dooptions(&tb, optp, optlen, ti, oi);
   2336 	} else
   2337 		tb.t_flags = 0;
   2338 
   2339 	/*
   2340 	 * See if we already have an entry for this connection.
   2341 	 * If we do, resend the SYN,ACK, and remember since the
   2342 	 * initial congestion window must be initialized to 1
   2343 	 * segment when the connection completes.
   2344 	 */
   2345 	if ((sc = syn_cache_lookup(ti, &scp)) != NULL) {
   2346 		tcpstat.tcps_sc_dupesyn++;
   2347 		sc->sc_rexmt_count++;
   2348 		if (sc->sc_rexmt_count == 0) {
   2349 			/*
   2350 			 * Eeek!  We rolled the counter.  Just set it
   2351 			 * to the max value.  This shouldn't ever happen,
   2352 			 * but there's no real reason to panic here, since
   2353 			 * the count doesn't have to be very precise.
   2354 			 */
   2355 			sc->sc_rexmt_count = USHRT_MAX;
   2356 		}
   2357 
   2358 		if (ipopts) {
   2359 			/*
   2360 			 * If we were remembering a previous source route,
   2361 			 * forget it and use the new one we've been given.
   2362 			 */
   2363 			if (sc->sc_ipopts)
   2364 				(void) m_free(sc->sc_ipopts);
   2365 			sc->sc_ipopts = ipopts;
   2366 		}
   2367 
   2368 		if (syn_cache_respond(sc, m, win, tb.ts_recent) == 0) {
   2369 			tcpstat.tcps_sndacks++;
   2370 			tcpstat.tcps_sndtotal++;
   2371 		}
   2372 		return (1);
   2373 	}
   2374 
   2375 	sc = pool_get(&syn_cache_pool, PR_NOWAIT);
   2376 	if (sc == NULL) {
   2377 		if (ipopts)
   2378 			(void) m_free(ipopts);
   2379 		return (0);
   2380 	}
   2381 
   2382 	/*
   2383 	 * Fill in the cache, and put the necessary IP and TCP
   2384 	 * options into the reply.
   2385 	 */
   2386 	memset(&sc->sc_route, 0, sizeof(sc->sc_route));
   2387 	sc->sc_src.s_addr = ti->ti_src.s_addr;
   2388 	sc->sc_dst.s_addr = ti->ti_dst.s_addr;
   2389 	sc->sc_sport = ti->ti_sport;
   2390 	sc->sc_dport = ti->ti_dport;
   2391 	sc->sc_flags = 0;
   2392 	sc->sc_ipopts = ipopts;
   2393 	sc->sc_irs = ti->ti_seq;
   2394 	sc->sc_iss = tcp_new_iss(sc, sizeof(struct syn_cache), 0);
   2395 	sc->sc_peermaxseg = oi->maxseg;
   2396 	sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
   2397 						m->m_pkthdr.rcvif : NULL);
   2398 	if (tcp_do_rfc1323 && (tb.t_flags & TF_RCVD_TSTMP))
   2399 		sc->sc_flags |= SCF_TIMESTAMP;
   2400 	if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   2401 	    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   2402 		sc->sc_requested_s_scale = tb.requested_s_scale;
   2403 		sc->sc_request_r_scale = 0;
   2404 		while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
   2405 		    TCP_MAXWIN << sc->sc_request_r_scale <
   2406 		    so->so_rcv.sb_hiwat)
   2407 			sc->sc_request_r_scale++;
   2408 	} else {
   2409 		sc->sc_requested_s_scale = 15;
   2410 		sc->sc_request_r_scale = 15;
   2411 	}
   2412 	if (syn_cache_respond(sc, m, win, tb.ts_recent) == 0) {
   2413 		syn_cache_insert(sc);
   2414 		tcpstat.tcps_sndacks++;
   2415 		tcpstat.tcps_sndtotal++;
   2416 	} else {
   2417 		SYN_CACHE_PUT(sc);
   2418 		tcpstat.tcps_sc_dropped++;
   2419 	}
   2420 	return (1);
   2421 }
   2422 
   2423 int
   2424 syn_cache_respond(sc, m, win, ts)
   2425 	struct syn_cache *sc;
   2426 	struct mbuf *m;
   2427 	long win;
   2428 	u_long ts;
   2429 {
   2430 	struct route *ro = &sc->sc_route;
   2431 	struct rtentry *rt;
   2432 	struct sockaddr_in *dst;
   2433 	struct tcpiphdr *ti;
   2434 	u_int8_t *optp;
   2435 	int optlen, error;
   2436 	u_int16_t tlen;
   2437 
   2438 	/* Compute the size of the TCP options. */
   2439 	optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
   2440 	    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
   2441 
   2442 	tlen = sizeof(struct tcpiphdr) + optlen;
   2443 
   2444 	/*
   2445 	 * Create the IP+TCP header from scratch.  Reuse the received mbuf
   2446 	 * if possible.
   2447 	 */
   2448 	if (m != NULL) {
   2449 		m_freem(m->m_next);
   2450 		m->m_next = NULL;
   2451 		MRESETDATA(m);
   2452 	} else {
   2453 		MGETHDR(m, M_DONTWAIT, MT_DATA);
   2454 		if (m == NULL)
   2455 			return (ENOBUFS);
   2456 	}
   2457 
   2458 	/* Fixup the mbuf. */
   2459 	m->m_data += max_linkhdr;
   2460 	m->m_len = m->m_pkthdr.len = tlen;
   2461 	m->m_pkthdr.rcvif = NULL;
   2462 
   2463 	ti = mtod(m, struct tcpiphdr *);
   2464 	memset(ti, 0, tlen);
   2465 
   2466 	ti->ti_dst = sc->sc_src;
   2467 	ti->ti_src = sc->sc_dst;
   2468 	ti->ti_sport = sc->sc_dport;
   2469 	ti->ti_dport = sc->sc_sport;
   2470 	ti->ti_pr = IPPROTO_TCP;
   2471 	ti->ti_len = htons(tlen - sizeof(struct ip));
   2472 	/* ti_x1 already 0'd */
   2473 	ti->ti_seq = htonl(sc->sc_iss);
   2474 	ti->ti_ack = htonl(sc->sc_irs + 1);
   2475 	/* ti_x2 already 0 */
   2476 	ti->ti_off = (sizeof(struct tcphdr) + optlen) >> 2;
   2477 	ti->ti_flags = TH_SYN|TH_ACK;
   2478 	ti->ti_win = htons(win);
   2479 	/* ti_sum already 0 */
   2480 	/* ti_urp already 0 */
   2481 
   2482 	/* Tack on the TCP options. */
   2483 	optp = (u_int8_t *)(ti + 1);
   2484 	*optp++ = TCPOPT_MAXSEG;
   2485 	*optp++ = 4;
   2486 	*optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
   2487 	*optp++ = sc->sc_ourmaxseg & 0xff;
   2488 
   2489 	if (sc->sc_request_r_scale != 15) {
   2490 		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
   2491 		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
   2492 		    sc->sc_request_r_scale);
   2493 		optp += 4;
   2494 	}
   2495 
   2496 	if (sc->sc_flags & SCF_TIMESTAMP) {
   2497 		u_int32_t *lp = (u_int32_t *)(optp);
   2498 		/* Form timestamp option as shown in appendix A of RFC 1323. */
   2499 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
   2500 		*lp++ = htonl(tcp_now);
   2501 		*lp   = htonl(ts);
   2502 		optp += TCPOLEN_TSTAMP_APPA;
   2503 	}
   2504 
   2505 	/* Compute the packet's checksum. */
   2506 	ti->ti_sum = in_cksum(m, tlen);
   2507 
   2508 	/*
   2509 	 * Fill in some straggling IP bits.  Note the stack expects
   2510 	 * ip_len to be in host order, for convenience.
   2511 	 */
   2512 	((struct ip *)ti)->ip_len = tlen;
   2513 	((struct ip *)ti)->ip_ttl = ip_defttl;
   2514 	/* XXX tos? */
   2515 
   2516 	/*
   2517 	 * If we're doing Path MTU discovery, we need to set DF unless
   2518 	 * the route's MTU is locked.  If we don't yet know the route,
   2519 	 * look it up now.  We will copy this reference to the inpcb
   2520 	 * when we finish creating the connection.
   2521 	 */
   2522 	if ((rt = ro->ro_rt) == NULL || (rt->rt_flags & RTF_UP) == 0) {
   2523 		if (ro->ro_rt != NULL) {
   2524 			RTFREE(ro->ro_rt);
   2525 			ro->ro_rt = NULL;
   2526 		}
   2527 		dst = satosin(&ro->ro_dst);
   2528 		dst->sin_family = AF_INET;
   2529 		dst->sin_len = sizeof(*dst);
   2530 		dst->sin_addr = ti->ti_dst;
   2531 		rtalloc(ro);
   2532 		if ((rt = ro->ro_rt) == NULL) {
   2533 			m_freem(m);
   2534 			ipstat.ips_noroute++;
   2535 			return (EHOSTUNREACH);
   2536 		}
   2537 	}
   2538 	if (ip_mtudisc != 0 && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
   2539 		((struct ip *)ti)->ip_off |= IP_DF;
   2540 
   2541 	/* ...and send it off! */
   2542 	error = ip_output(m, sc->sc_ipopts, ro, 0, NULL);
   2543 
   2544 	return (error);
   2545 }
   2546