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