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