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