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