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