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