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