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