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