xref: /original-bsd/sys/netinet/tcp_input.c (revision 9a35f7df)
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  *
7  *	@(#)tcp_input.c	8.12 (Berkeley) 05/24/95
8  */
9 
10 #ifndef TUBA_INCLUDE
11 #include <sys/param.h>
12 #include <sys/systm.h>
13 #include <sys/malloc.h>
14 #include <sys/mbuf.h>
15 #include <sys/protosw.h>
16 #include <sys/socket.h>
17 #include <sys/socketvar.h>
18 #include <sys/errno.h>
19 
20 #include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
21 
22 #include <net/if.h>
23 #include <net/route.h>
24 
25 #include <netinet/in.h>
26 #include <netinet/in_systm.h>
27 #include <netinet/ip.h>
28 #include <netinet/in_pcb.h>
29 #include <netinet/ip_var.h>
30 #include <netinet/tcp.h>
31 #include <netinet/tcp_fsm.h>
32 #include <netinet/tcp_seq.h>
33 #include <netinet/tcp_timer.h>
34 #include <netinet/tcp_var.h>
35 #include <netinet/tcpip.h>
36 #include <netinet/tcp_debug.h>
37 
38 int	tcprexmtthresh = 3;
39 struct	tcpiphdr tcp_saveti;
40 struct	inpcb *tcp_last_inpcb = &tcb;
41 
42 extern u_long sb_max;
43 
44 #endif /* TUBA_INCLUDE */
45 #define TCP_PAWS_IDLE	(24 * 24 * 60 * 60 * PR_SLOWHZ)
46 
47 /* for modulo comparisons of timestamps */
48 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
49 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
50 
51 
52 /*
53  * Insert segment ti into reassembly queue of tcp with
54  * control block tp.  Return TH_FIN if reassembly now includes
55  * a segment with FIN.  The macro form does the common case inline
56  * (segment is the next to be received on an established connection,
57  * and the queue is empty), avoiding linkage into and removal
58  * from the queue and repetition of various conversions.
59  * Set DELACK for segments received in order, but ack immediately
60  * when segments are out of order (so fast retransmit can work).
61  */
62 #define	TCP_REASS(tp, ti, m, so, flags) { \
63 	if ((ti)->ti_seq == (tp)->rcv_nxt && \
64 	    (tp)->seg_next == (struct tcpiphdr *)(tp) && \
65 	    (tp)->t_state == TCPS_ESTABLISHED) { \
66 		tp->t_flags |= TF_DELACK; \
67 		(tp)->rcv_nxt += (ti)->ti_len; \
68 		flags = (ti)->ti_flags & TH_FIN; \
69 		tcpstat.tcps_rcvpack++;\
70 		tcpstat.tcps_rcvbyte += (ti)->ti_len;\
71 		sbappend(&(so)->so_rcv, (m)); \
72 		sorwakeup(so); \
73 	} else { \
74 		(flags) = tcp_reass((tp), (ti), (m)); \
75 		tp->t_flags |= TF_ACKNOW; \
76 	} \
77 }
78 #ifndef TUBA_INCLUDE
79 
80 int
81 tcp_reass(tp, ti, m)
82 	register struct tcpcb *tp;
83 	register struct tcpiphdr *ti;
84 	struct mbuf *m;
85 {
86 	register struct tcpiphdr *q;
87 	struct socket *so = tp->t_inpcb->inp_socket;
88 	int flags;
89 
90 	/*
91 	 * Call with ti==0 after become established to
92 	 * force pre-ESTABLISHED data up to user socket.
93 	 */
94 	if (ti == 0)
95 		goto present;
96 
97 	/*
98 	 * Find a segment which begins after this one does.
99 	 */
100 	for (q = tp->seg_next; q != (struct tcpiphdr *)tp;
101 	    q = (struct tcpiphdr *)q->ti_next)
102 		if (SEQ_GT(q->ti_seq, ti->ti_seq))
103 			break;
104 
105 	/*
106 	 * If there is a preceding segment, it may provide some of
107 	 * our data already.  If so, drop the data from the incoming
108 	 * segment.  If it provides all of our data, drop us.
109 	 */
110 	if ((struct tcpiphdr *)q->ti_prev != (struct tcpiphdr *)tp) {
111 		register int i;
112 		q = (struct tcpiphdr *)q->ti_prev;
113 		/* conversion to int (in i) handles seq wraparound */
114 		i = q->ti_seq + q->ti_len - ti->ti_seq;
115 		if (i > 0) {
116 			if (i >= ti->ti_len) {
117 				tcpstat.tcps_rcvduppack++;
118 				tcpstat.tcps_rcvdupbyte += ti->ti_len;
119 				m_freem(m);
120 				return (0);
121 			}
122 			m_adj(m, i);
123 			ti->ti_len -= i;
124 			ti->ti_seq += i;
125 		}
126 		q = (struct tcpiphdr *)(q->ti_next);
127 	}
128 	tcpstat.tcps_rcvoopack++;
129 	tcpstat.tcps_rcvoobyte += ti->ti_len;
130 	REASS_MBUF(ti) = m;		/* XXX */
131 
132 	/*
133 	 * While we overlap succeeding segments trim them or,
134 	 * if they are completely covered, dequeue them.
135 	 */
136 	while (q != (struct tcpiphdr *)tp) {
137 		register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
138 		if (i <= 0)
139 			break;
140 		if (i < q->ti_len) {
141 			q->ti_seq += i;
142 			q->ti_len -= i;
143 			m_adj(REASS_MBUF(q), i);
144 			break;
145 		}
146 		q = (struct tcpiphdr *)q->ti_next;
147 		m = REASS_MBUF((struct tcpiphdr *)q->ti_prev);
148 		remque(q->ti_prev);
149 		m_freem(m);
150 	}
151 
152 	/*
153 	 * Stick new segment in its place.
154 	 */
155 	insque(ti, q->ti_prev);
156 
157 present:
158 	/*
159 	 * Present data to user, advancing rcv_nxt through
160 	 * completed sequence space.
161 	 */
162 	if (TCPS_HAVERCVDSYN(tp->t_state) == 0)
163 		return (0);
164 	ti = tp->seg_next;
165 	if (ti == (struct tcpiphdr *)tp || ti->ti_seq != tp->rcv_nxt)
166 		return (0);
167 	if (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)
168 		return (0);
169 	do {
170 		tp->rcv_nxt += ti->ti_len;
171 		flags = ti->ti_flags & TH_FIN;
172 		remque(ti);
173 		m = REASS_MBUF(ti);
174 		ti = (struct tcpiphdr *)ti->ti_next;
175 		if (so->so_state & SS_CANTRCVMORE)
176 			m_freem(m);
177 		else
178 			sbappend(&so->so_rcv, m);
179 	} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
180 	sorwakeup(so);
181 	return (flags);
182 }
183 
184 /*
185  * TCP input routine, follows pages 65-76 of the
186  * protocol specification dated September, 1981 very closely.
187  */
188 void
189 tcp_input(m, iphlen)
190 	register struct mbuf *m;
191 	int iphlen;
192 {
193 	register struct tcpiphdr *ti;
194 	register struct inpcb *inp;
195 	u_char *optp = NULL;
196 	int optlen;
197 	int len, tlen, off;
198 	register struct tcpcb *tp = 0;
199 	register int tiflags;
200 	struct socket *so;
201 	int todrop, acked, ourfinisacked, needoutput = 0;
202 	short ostate;
203 	struct in_addr laddr;
204 	int dropsocket = 0;
205 	int iss = 0;
206 	u_long tiwin, ts_val, ts_ecr;
207 	int ts_present = 0;
208 
209 	tcpstat.tcps_rcvtotal++;
210 	/*
211 	 * Get IP and TCP header together in first mbuf.
212 	 * Note: IP leaves IP header in first mbuf.
213 	 */
214 	ti = mtod(m, struct tcpiphdr *);
215 	if (iphlen > sizeof (struct ip))
216 		ip_stripoptions(m, (struct mbuf *)0);
217 	if (m->m_len < sizeof (struct tcpiphdr)) {
218 		if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
219 			tcpstat.tcps_rcvshort++;
220 			return;
221 		}
222 		ti = mtod(m, struct tcpiphdr *);
223 	}
224 
225 	/*
226 	 * Checksum extended TCP header and data.
227 	 */
228 	tlen = ((struct ip *)ti)->ip_len;
229 	len = sizeof (struct ip) + tlen;
230 	ti->ti_next = ti->ti_prev = 0;
231 	ti->ti_x1 = 0;
232 	ti->ti_len = (u_short)tlen;
233 	HTONS(ti->ti_len);
234 	if (ti->ti_sum = in_cksum(m, len)) {
235 		tcpstat.tcps_rcvbadsum++;
236 		goto drop;
237 	}
238 #endif /* TUBA_INCLUDE */
239 
240 	/*
241 	 * Check that TCP offset makes sense,
242 	 * pull out TCP options and adjust length.		XXX
243 	 */
244 	off = ti->ti_off << 2;
245 	if (off < sizeof (struct tcphdr) || off > tlen) {
246 		tcpstat.tcps_rcvbadoff++;
247 		goto drop;
248 	}
249 	tlen -= off;
250 	ti->ti_len = tlen;
251 	if (off > sizeof (struct tcphdr)) {
252 		if (m->m_len < sizeof(struct ip) + off) {
253 			if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
254 				tcpstat.tcps_rcvshort++;
255 				return;
256 			}
257 			ti = mtod(m, struct tcpiphdr *);
258 		}
259 		optlen = off - sizeof (struct tcphdr);
260 		optp = mtod(m, u_char *) + sizeof (struct tcpiphdr);
261 		/*
262 		 * Do quick retrieval of timestamp options ("options
263 		 * prediction?").  If timestamp is the only option and it's
264 		 * formatted as recommended in RFC 1323 appendix A, we
265 		 * quickly get the values now and not bother calling
266 		 * tcp_dooptions(), etc.
267 		 */
268 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
269 		     (optlen > TCPOLEN_TSTAMP_APPA &&
270 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
271 		     *(u_long *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
272 		     (ti->ti_flags & TH_SYN) == 0) {
273 			ts_present = 1;
274 			ts_val = ntohl(*(u_long *)(optp + 4));
275 			ts_ecr = ntohl(*(u_long *)(optp + 8));
276 			optp = NULL;	/* we've parsed the options */
277 		}
278 	}
279 	tiflags = ti->ti_flags;
280 
281 	/*
282 	 * Convert TCP protocol specific fields to host format.
283 	 */
284 	NTOHL(ti->ti_seq);
285 	NTOHL(ti->ti_ack);
286 	NTOHS(ti->ti_win);
287 	NTOHS(ti->ti_urp);
288 
289 	/*
290 	 * Locate pcb for segment.
291 	 */
292 findpcb:
293 	inp = tcp_last_inpcb;
294 	if (inp->inp_lport != ti->ti_dport ||
295 	    inp->inp_fport != ti->ti_sport ||
296 	    inp->inp_faddr.s_addr != ti->ti_src.s_addr ||
297 	    inp->inp_laddr.s_addr != ti->ti_dst.s_addr) {
298 		inp = in_pcblookup(&tcb, ti->ti_src, ti->ti_sport,
299 		    ti->ti_dst, ti->ti_dport, INPLOOKUP_WILDCARD);
300 		if (inp)
301 			tcp_last_inpcb = inp;
302 		++tcpstat.tcps_pcbcachemiss;
303 	}
304 
305 	/*
306 	 * If the state is CLOSED (i.e., TCB does not exist) then
307 	 * all data in the incoming segment is discarded.
308 	 * If the TCB exists but is in CLOSED state, it is embryonic,
309 	 * but should either do a listen or a connect soon.
310 	 */
311 	if (inp == 0)
312 		goto dropwithreset;
313 	tp = intotcpcb(inp);
314 	if (tp == 0)
315 		goto dropwithreset;
316 	if (tp->t_state == TCPS_CLOSED)
317 		goto drop;
318 
319 	/* Unscale the window into a 32-bit value. */
320 	if ((tiflags & TH_SYN) == 0)
321 		tiwin = ti->ti_win << tp->snd_scale;
322 	else
323 		tiwin = ti->ti_win;
324 
325 	so = inp->inp_socket;
326 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
327 		if (so->so_options & SO_DEBUG) {
328 			ostate = tp->t_state;
329 			tcp_saveti = *ti;
330 		}
331 		if (so->so_options & SO_ACCEPTCONN) {
332 			if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
333 				/*
334 				 * Note: dropwithreset makes sure we don't
335 				 * send a reset in response to a RST.
336 				 */
337 				if (tiflags & TH_ACK) {
338 					tcpstat.tcps_badsyn++;
339 					goto dropwithreset;
340 				}
341 				goto drop;
342 			}
343 			so = sonewconn(so, 0);
344 			if (so == 0)
345 				goto drop;
346 			/*
347 			 * This is ugly, but ....
348 			 *
349 			 * Mark socket as temporary until we're
350 			 * committed to keeping it.  The code at
351 			 * ``drop'' and ``dropwithreset'' check the
352 			 * flag dropsocket to see if the temporary
353 			 * socket created here should be discarded.
354 			 * We mark the socket as discardable until
355 			 * we're committed to it below in TCPS_LISTEN.
356 			 */
357 			dropsocket++;
358 			inp = (struct inpcb *)so->so_pcb;
359 			inp->inp_laddr = ti->ti_dst;
360 			inp->inp_lport = ti->ti_dport;
361 #if BSD>=43
362 			inp->inp_options = ip_srcroute();
363 #endif
364 			tp = intotcpcb(inp);
365 			tp->t_state = TCPS_LISTEN;
366 
367 			/* Compute proper scaling value from buffer space
368 			 */
369 			while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
370 			   TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
371 				tp->request_r_scale++;
372 		}
373 	}
374 
375 	/*
376 	 * Segment received on connection.
377 	 * Reset idle time and keep-alive timer.
378 	 */
379 	tp->t_idle = 0;
380 	tp->t_timer[TCPT_KEEP] = tcp_keepidle;
381 
382 	/*
383 	 * Process options if not in LISTEN state,
384 	 * else do it below (after getting remote address).
385 	 */
386 	if (optp && tp->t_state != TCPS_LISTEN)
387 		tcp_dooptions(tp, optp, optlen, ti,
388 			&ts_present, &ts_val, &ts_ecr);
389 
390 	/*
391 	 * Header prediction: check for the two common cases
392 	 * of a uni-directional data xfer.  If the packet has
393 	 * no control flags, is in-sequence, the window didn't
394 	 * change and we're not retransmitting, it's a
395 	 * candidate.  If the length is zero and the ack moved
396 	 * forward, we're the sender side of the xfer.  Just
397 	 * free the data acked & wake any higher level process
398 	 * that was blocked waiting for space.  If the length
399 	 * is non-zero and the ack didn't move, we're the
400 	 * receiver side.  If we're getting packets in-order
401 	 * (the reassembly queue is empty), add the data to
402 	 * the socket buffer and note that we need a delayed ack.
403 	 */
404 	if (tp->t_state == TCPS_ESTABLISHED &&
405 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
406 	    (!ts_present || TSTMP_GEQ(ts_val, tp->ts_recent)) &&
407 	    ti->ti_seq == tp->rcv_nxt &&
408 	    tiwin && tiwin == tp->snd_wnd &&
409 	    tp->snd_nxt == tp->snd_max) {
410 
411 		/*
412 		 * If last ACK falls within this segment's sequence numbers,
413 		 *  record the timestamp.
414 		 */
415 		if (ts_present && SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
416 		   SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len)) {
417 			tp->ts_recent_age = tcp_now;
418 			tp->ts_recent = ts_val;
419 		}
420 
421 		if (ti->ti_len == 0) {
422 			if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
423 			    SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
424 			    tp->snd_cwnd >= tp->snd_wnd) {
425 				/*
426 				 * this is a pure ack for outstanding data.
427 				 */
428 				++tcpstat.tcps_predack;
429 				if (ts_present)
430 					tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
431 				else if (tp->t_rtt &&
432 					    SEQ_GT(ti->ti_ack, tp->t_rtseq))
433 					tcp_xmit_timer(tp, tp->t_rtt);
434 				acked = ti->ti_ack - tp->snd_una;
435 				tcpstat.tcps_rcvackpack++;
436 				tcpstat.tcps_rcvackbyte += acked;
437 				sbdrop(&so->so_snd, acked);
438 				tp->snd_una = ti->ti_ack;
439 				m_freem(m);
440 
441 				/*
442 				 * If all outstanding data are acked, stop
443 				 * retransmit timer, otherwise restart timer
444 				 * using current (possibly backed-off) value.
445 				 * If process is waiting for space,
446 				 * wakeup/selwakeup/signal.  If data
447 				 * are ready to send, let tcp_output
448 				 * decide between more output or persist.
449 				 */
450 				if (tp->snd_una == tp->snd_max)
451 					tp->t_timer[TCPT_REXMT] = 0;
452 				else if (tp->t_timer[TCPT_PERSIST] == 0)
453 					tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
454 
455 				if (so->so_snd.sb_flags & SB_NOTIFY)
456 					sowwakeup(so);
457 				if (so->so_snd.sb_cc)
458 					(void) tcp_output(tp);
459 				return;
460 			}
461 		} else if (ti->ti_ack == tp->snd_una &&
462 		    tp->seg_next == (struct tcpiphdr *)tp &&
463 		    ti->ti_len <= sbspace(&so->so_rcv)) {
464 			/*
465 			 * this is a pure, in-sequence data packet
466 			 * with nothing on the reassembly queue and
467 			 * we have enough buffer space to take it.
468 			 */
469 			++tcpstat.tcps_preddat;
470 			tp->rcv_nxt += ti->ti_len;
471 			tcpstat.tcps_rcvpack++;
472 			tcpstat.tcps_rcvbyte += ti->ti_len;
473 			/*
474 			 * Drop TCP, IP headers and TCP options then add data
475 			 * to socket buffer.
476 			 */
477 			m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
478 			m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
479 			sbappend(&so->so_rcv, m);
480 			sorwakeup(so);
481 			tp->t_flags |= TF_DELACK;
482 			return;
483 		}
484 	}
485 
486 	/*
487 	 * Drop TCP, IP headers and TCP options.
488 	 */
489 	m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
490 	m->m_len  -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
491 
492 	/*
493 	 * Calculate amount of space in receive window,
494 	 * and then do TCP input processing.
495 	 * Receive window is amount of space in rcv queue,
496 	 * but not less than advertised window.
497 	 */
498 	{ int win;
499 
500 	win = sbspace(&so->so_rcv);
501 	if (win < 0)
502 		win = 0;
503 	tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));
504 	}
505 
506 	switch (tp->t_state) {
507 
508 	/*
509 	 * If the state is LISTEN then ignore segment if it contains an RST.
510 	 * If the segment contains an ACK then it is bad and send a RST.
511 	 * If it does not contain a SYN then it is not interesting; drop it.
512 	 * Don't bother responding if the destination was a broadcast.
513 	 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
514 	 * tp->iss, and send a segment:
515 	 *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
516 	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
517 	 * Fill in remote peer address fields if not previously specified.
518 	 * Enter SYN_RECEIVED state, and process any other fields of this
519 	 * segment in this state.
520 	 */
521 	case TCPS_LISTEN: {
522 		struct mbuf *am;
523 		register struct sockaddr_in *sin;
524 
525 #ifdef already_done
526 		if (tiflags & TH_RST)
527 			goto drop;
528 		if (tiflags & TH_ACK)
529 			goto dropwithreset;
530 		if ((tiflags & TH_SYN) == 0)
531 			goto drop;
532 #endif
533 		/*
534 		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
535 		 * in_broadcast() should never return true on a received
536 		 * packet with M_BCAST not set.
537 		 */
538 		if (m->m_flags & (M_BCAST|M_MCAST) ||
539 		    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
540 			goto drop;
541 		am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
542 		if (am == NULL)
543 			goto drop;
544 		am->m_len = sizeof (struct sockaddr_in);
545 		sin = mtod(am, struct sockaddr_in *);
546 		sin->sin_family = AF_INET;
547 		sin->sin_len = sizeof(*sin);
548 		sin->sin_addr = ti->ti_src;
549 		sin->sin_port = ti->ti_sport;
550 		bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
551 		laddr = inp->inp_laddr;
552 		if (inp->inp_laddr.s_addr == INADDR_ANY)
553 			inp->inp_laddr = ti->ti_dst;
554 		if (in_pcbconnect(inp, am)) {
555 			inp->inp_laddr = laddr;
556 			(void) m_free(am);
557 			goto drop;
558 		}
559 		(void) m_free(am);
560 		tp->t_template = tcp_template(tp);
561 		if (tp->t_template == 0) {
562 			tp = tcp_drop(tp, ENOBUFS);
563 			dropsocket = 0;		/* socket is already gone */
564 			goto drop;
565 		}
566 		if (optp)
567 			tcp_dooptions(tp, optp, optlen, ti,
568 				&ts_present, &ts_val, &ts_ecr);
569 		if (iss)
570 			tp->iss = iss;
571 		else
572 			tp->iss = tcp_iss;
573 		tcp_iss += TCP_ISSINCR/4;
574 		tp->irs = ti->ti_seq;
575 		tcp_sendseqinit(tp);
576 		tcp_rcvseqinit(tp);
577 		tp->t_flags |= TF_ACKNOW;
578 		tp->t_state = TCPS_SYN_RECEIVED;
579 		tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
580 		dropsocket = 0;		/* committed to socket */
581 		tcpstat.tcps_accepts++;
582 		goto trimthenstep6;
583 		}
584 
585 	/*
586 	 * If the state is SYN_SENT:
587 	 *	if seg contains an ACK, but not for our SYN, drop the input.
588 	 *	if seg contains a RST, then drop the connection.
589 	 *	if seg does not contain SYN, then drop it.
590 	 * Otherwise this is an acceptable SYN segment
591 	 *	initialize tp->rcv_nxt and tp->irs
592 	 *	if seg contains ack then advance tp->snd_una
593 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
594 	 *	arrange for segment to be acked (eventually)
595 	 *	continue processing rest of data/controls, beginning with URG
596 	 */
597 	case TCPS_SYN_SENT:
598 		if ((tiflags & TH_ACK) &&
599 		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
600 		     SEQ_GT(ti->ti_ack, tp->snd_max)))
601 			goto dropwithreset;
602 		if (tiflags & TH_RST) {
603 			if (tiflags & TH_ACK)
604 				tp = tcp_drop(tp, ECONNREFUSED);
605 			goto drop;
606 		}
607 		if ((tiflags & TH_SYN) == 0)
608 			goto drop;
609 		if (tiflags & TH_ACK) {
610 			tp->snd_una = ti->ti_ack;
611 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
612 				tp->snd_nxt = tp->snd_una;
613 		}
614 		tp->t_timer[TCPT_REXMT] = 0;
615 		tp->irs = ti->ti_seq;
616 		tcp_rcvseqinit(tp);
617 		tp->t_flags |= TF_ACKNOW;
618 		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
619 			tcpstat.tcps_connects++;
620 			soisconnected(so);
621 			tp->t_state = TCPS_ESTABLISHED;
622 			/* Do window scaling on this connection? */
623 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
624 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
625 				tp->snd_scale = tp->requested_s_scale;
626 				tp->rcv_scale = tp->request_r_scale;
627 			}
628 			(void) tcp_reass(tp, (struct tcpiphdr *)0,
629 				(struct mbuf *)0);
630 			/*
631 			 * if we didn't have to retransmit the SYN,
632 			 * use its rtt as our initial srtt & rtt var.
633 			 */
634 			if (tp->t_rtt)
635 				tcp_xmit_timer(tp, tp->t_rtt);
636 		} else
637 			tp->t_state = TCPS_SYN_RECEIVED;
638 
639 trimthenstep6:
640 		/*
641 		 * Advance ti->ti_seq to correspond to first data byte.
642 		 * If data, trim to stay within window,
643 		 * dropping FIN if necessary.
644 		 */
645 		ti->ti_seq++;
646 		if (ti->ti_len > tp->rcv_wnd) {
647 			todrop = ti->ti_len - tp->rcv_wnd;
648 			m_adj(m, -todrop);
649 			ti->ti_len = tp->rcv_wnd;
650 			tiflags &= ~TH_FIN;
651 			tcpstat.tcps_rcvpackafterwin++;
652 			tcpstat.tcps_rcvbyteafterwin += todrop;
653 		}
654 		tp->snd_wl1 = ti->ti_seq - 1;
655 		tp->rcv_up = ti->ti_seq;
656 		goto step6;
657 	}
658 
659 	/*
660 	 * States other than LISTEN or SYN_SENT.
661 	 * First check timestamp, if present.
662 	 * Then check that at least some bytes of segment are within
663 	 * receive window.  If segment begins before rcv_nxt,
664 	 * drop leading data (and SYN); if nothing left, just ack.
665 	 *
666 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
667 	 * and it's less than ts_recent, drop it.
668 	 */
669 	if (ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
670 	    TSTMP_LT(ts_val, tp->ts_recent)) {
671 
672 		/* Check to see if ts_recent is over 24 days old.  */
673 		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
674 			/*
675 			 * Invalidate ts_recent.  If this segment updates
676 			 * ts_recent, the age will be reset later and ts_recent
677 			 * will get a valid value.  If it does not, setting
678 			 * ts_recent to zero will at least satisfy the
679 			 * requirement that zero be placed in the timestamp
680 			 * echo reply when ts_recent isn't valid.  The
681 			 * age isn't reset until we get a valid ts_recent
682 			 * because we don't want out-of-order segments to be
683 			 * dropped when ts_recent is old.
684 			 */
685 			tp->ts_recent = 0;
686 		} else {
687 			tcpstat.tcps_rcvduppack++;
688 			tcpstat.tcps_rcvdupbyte += ti->ti_len;
689 			tcpstat.tcps_pawsdrop++;
690 			goto dropafterack;
691 		}
692 	}
693 
694 	todrop = tp->rcv_nxt - ti->ti_seq;
695 	if (todrop > 0) {
696 		if (tiflags & TH_SYN) {
697 			tiflags &= ~TH_SYN;
698 			ti->ti_seq++;
699 			if (ti->ti_urp > 1)
700 				ti->ti_urp--;
701 			else
702 				tiflags &= ~TH_URG;
703 			todrop--;
704 		}
705 		if (todrop >= ti->ti_len) {
706 			tcpstat.tcps_rcvduppack++;
707 			tcpstat.tcps_rcvdupbyte += ti->ti_len;
708 			/*
709 			 * If segment is just one to the left of the window,
710 			 * check two special cases:
711 			 * 1. Don't toss RST in response to 4.2-style keepalive.
712 			 * 2. If the only thing to drop is a FIN, we can drop
713 			 *    it, but check the ACK or we will get into FIN
714 			 *    wars if our FINs crossed (both CLOSING).
715 			 * In either case, send ACK to resynchronize,
716 			 * but keep on processing for RST or ACK.
717 			 */
718 			if ((tiflags & TH_FIN && todrop == ti->ti_len + 1)
719 #ifdef TCP_COMPAT_42
720 			  || (tiflags & TH_RST && ti->ti_seq == tp->rcv_nxt - 1)
721 #endif
722 			   ) {
723 				todrop = ti->ti_len;
724 				tiflags &= ~TH_FIN;
725 			} else {
726 				/*
727 				 * Handle the case when a bound socket connects
728 				 * to itself. Allow packets with a SYN and
729 				 * an ACK to continue with the processing.
730 				 */
731 				if (todrop != 0 || (tiflags & TH_ACK) == 0)
732 					goto dropafterack;
733 			}
734 			tp->t_flags |= TF_ACKNOW;
735 		} else {
736 			tcpstat.tcps_rcvpartduppack++;
737 			tcpstat.tcps_rcvpartdupbyte += todrop;
738 		}
739 		m_adj(m, todrop);
740 		ti->ti_seq += todrop;
741 		ti->ti_len -= todrop;
742 		if (ti->ti_urp > todrop)
743 			ti->ti_urp -= todrop;
744 		else {
745 			tiflags &= ~TH_URG;
746 			ti->ti_urp = 0;
747 		}
748 	}
749 
750 	/*
751 	 * If new data are received on a connection after the
752 	 * user processes are gone, then RST the other end.
753 	 */
754 	if ((so->so_state & SS_NOFDREF) &&
755 	    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
756 		tp = tcp_close(tp);
757 		tcpstat.tcps_rcvafterclose++;
758 		goto dropwithreset;
759 	}
760 
761 	/*
762 	 * If segment ends after window, drop trailing data
763 	 * (and PUSH and FIN); if nothing left, just ACK.
764 	 */
765 	todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
766 	if (todrop > 0) {
767 		tcpstat.tcps_rcvpackafterwin++;
768 		if (todrop >= ti->ti_len) {
769 			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
770 			/*
771 			 * If a new connection request is received
772 			 * while in TIME_WAIT, drop the old connection
773 			 * and start over if the sequence numbers
774 			 * are above the previous ones.
775 			 */
776 			if (tiflags & TH_SYN &&
777 			    tp->t_state == TCPS_TIME_WAIT &&
778 			    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
779 				iss = tp->snd_nxt + TCP_ISSINCR;
780 				tp = tcp_close(tp);
781 				goto findpcb;
782 			}
783 			/*
784 			 * If window is closed can only take segments at
785 			 * window edge, and have to drop data and PUSH from
786 			 * incoming segments.  Continue processing, but
787 			 * remember to ack.  Otherwise, drop segment
788 			 * and ack.
789 			 */
790 			if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
791 				tp->t_flags |= TF_ACKNOW;
792 				tcpstat.tcps_rcvwinprobe++;
793 			} else
794 				goto dropafterack;
795 		} else
796 			tcpstat.tcps_rcvbyteafterwin += todrop;
797 		m_adj(m, -todrop);
798 		ti->ti_len -= todrop;
799 		tiflags &= ~(TH_PUSH|TH_FIN);
800 	}
801 
802 	/*
803 	 * If last ACK falls within this segment's sequence numbers,
804 	 * record its timestamp.
805 	 */
806 	if (ts_present && SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
807 	    SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len +
808 		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
809 		tp->ts_recent_age = tcp_now;
810 		tp->ts_recent = ts_val;
811 	}
812 
813 	/*
814 	 * If the RST bit is set examine the state:
815 	 *    SYN_RECEIVED STATE:
816 	 *	If passive open, return to LISTEN state.
817 	 *	If active open, inform user that connection was refused.
818 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
819 	 *	Inform user that connection was reset, and close tcb.
820 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
821 	 *	Close the tcb.
822 	 */
823 	if (tiflags&TH_RST) switch (tp->t_state) {
824 
825 	case TCPS_SYN_RECEIVED:
826 		so->so_error = ECONNREFUSED;
827 		goto close;
828 
829 	case TCPS_ESTABLISHED:
830 	case TCPS_FIN_WAIT_1:
831 	case TCPS_FIN_WAIT_2:
832 	case TCPS_CLOSE_WAIT:
833 		so->so_error = ECONNRESET;
834 	close:
835 		tp->t_state = TCPS_CLOSED;
836 		tcpstat.tcps_drops++;
837 		tp = tcp_close(tp);
838 		goto drop;
839 
840 	case TCPS_CLOSING:
841 	case TCPS_LAST_ACK:
842 	case TCPS_TIME_WAIT:
843 		tp = tcp_close(tp);
844 		goto drop;
845 	}
846 
847 	/*
848 	 * If a SYN is in the window, then this is an
849 	 * error and we send an RST and drop the connection.
850 	 */
851 	if (tiflags & TH_SYN) {
852 		tp = tcp_drop(tp, ECONNRESET);
853 		goto dropwithreset;
854 	}
855 
856 	/*
857 	 * If the ACK bit is off we drop the segment and return.
858 	 */
859 	if ((tiflags & TH_ACK) == 0)
860 		goto drop;
861 
862 	/*
863 	 * Ack processing.
864 	 */
865 	switch (tp->t_state) {
866 
867 	/*
868 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
869 	 * ESTABLISHED state and continue processing, otherwise
870 	 * send an RST.
871 	 */
872 	case TCPS_SYN_RECEIVED:
873 		if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
874 		    SEQ_GT(ti->ti_ack, tp->snd_max))
875 			goto dropwithreset;
876 		tcpstat.tcps_connects++;
877 		soisconnected(so);
878 		tp->t_state = TCPS_ESTABLISHED;
879 		/* Do window scaling? */
880 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
881 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
882 			tp->snd_scale = tp->requested_s_scale;
883 			tp->rcv_scale = tp->request_r_scale;
884 		}
885 		(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
886 		tp->snd_wl1 = ti->ti_seq - 1;
887 		/* fall into ... */
888 
889 	/*
890 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
891 	 * ACKs.  If the ack is in the range
892 	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
893 	 * then advance tp->snd_una to ti->ti_ack and drop
894 	 * data from the retransmission queue.  If this ACK reflects
895 	 * more up to date window information we update our window information.
896 	 */
897 	case TCPS_ESTABLISHED:
898 	case TCPS_FIN_WAIT_1:
899 	case TCPS_FIN_WAIT_2:
900 	case TCPS_CLOSE_WAIT:
901 	case TCPS_CLOSING:
902 	case TCPS_LAST_ACK:
903 	case TCPS_TIME_WAIT:
904 
905 		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
906 			if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
907 				tcpstat.tcps_rcvdupack++;
908 				/*
909 				 * If we have outstanding data (other than
910 				 * a window probe), this is a completely
911 				 * duplicate ack (ie, window info didn't
912 				 * change), the ack is the biggest we've
913 				 * seen and we've seen exactly our rexmt
914 				 * threshhold of them, assume a packet
915 				 * has been dropped and retransmit it.
916 				 * Kludge snd_nxt & the congestion
917 				 * window so we send only this one
918 				 * packet.
919 				 *
920 				 * We know we're losing at the current
921 				 * window size so do congestion avoidance
922 				 * (set ssthresh to half the current window
923 				 * and pull our congestion window back to
924 				 * the new ssthresh).
925 				 *
926 				 * Dup acks mean that packets have left the
927 				 * network (they're now cached at the receiver)
928 				 * so bump cwnd by the amount in the receiver
929 				 * to keep a constant cwnd packets in the
930 				 * network.
931 				 */
932 				if (tp->t_timer[TCPT_REXMT] == 0 ||
933 				    ti->ti_ack != tp->snd_una)
934 					tp->t_dupacks = 0;
935 				else if (++tp->t_dupacks == tcprexmtthresh) {
936 					tcp_seq onxt = tp->snd_nxt;
937 					u_int win =
938 					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
939 						tp->t_maxseg;
940 
941 					if (win < 2)
942 						win = 2;
943 					tp->snd_ssthresh = win * tp->t_maxseg;
944 					tp->t_timer[TCPT_REXMT] = 0;
945 					tp->t_rtt = 0;
946 					tp->snd_nxt = ti->ti_ack;
947 					tp->snd_cwnd = tp->t_maxseg;
948 					(void) tcp_output(tp);
949 					tp->snd_cwnd = tp->snd_ssthresh +
950 					       tp->t_maxseg * tp->t_dupacks;
951 					if (SEQ_GT(onxt, tp->snd_nxt))
952 						tp->snd_nxt = onxt;
953 					goto drop;
954 				} else if (tp->t_dupacks > tcprexmtthresh) {
955 					tp->snd_cwnd += tp->t_maxseg;
956 					(void) tcp_output(tp);
957 					goto drop;
958 				}
959 			} else
960 				tp->t_dupacks = 0;
961 			break;
962 		}
963 		/*
964 		 * If the congestion window was inflated to account
965 		 * for the other side's cached packets, retract it.
966 		 */
967 		if (tp->t_dupacks > tcprexmtthresh &&
968 		    tp->snd_cwnd > tp->snd_ssthresh)
969 			tp->snd_cwnd = tp->snd_ssthresh;
970 		tp->t_dupacks = 0;
971 		if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
972 			tcpstat.tcps_rcvacktoomuch++;
973 			goto dropafterack;
974 		}
975 		acked = ti->ti_ack - tp->snd_una;
976 		tcpstat.tcps_rcvackpack++;
977 		tcpstat.tcps_rcvackbyte += acked;
978 
979 		/*
980 		 * If we have a timestamp reply, update smoothed
981 		 * round trip time.  If no timestamp is present but
982 		 * transmit timer is running and timed sequence
983 		 * number was acked, update smoothed round trip time.
984 		 * Since we now have an rtt measurement, cancel the
985 		 * timer backoff (cf., Phil Karn's retransmit alg.).
986 		 * Recompute the initial retransmit timer.
987 		 */
988 		if (ts_present)
989 			tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
990 		else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
991 			tcp_xmit_timer(tp,tp->t_rtt);
992 
993 		/*
994 		 * If all outstanding data is acked, stop retransmit
995 		 * timer and remember to restart (more output or persist).
996 		 * If there is more data to be acked, restart retransmit
997 		 * timer, using current (possibly backed-off) value.
998 		 */
999 		if (ti->ti_ack == tp->snd_max) {
1000 			tp->t_timer[TCPT_REXMT] = 0;
1001 			needoutput = 1;
1002 		} else if (tp->t_timer[TCPT_PERSIST] == 0)
1003 			tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1004 		/*
1005 		 * When new data is acked, open the congestion window.
1006 		 * If the window gives us less than ssthresh packets
1007 		 * in flight, open exponentially (maxseg per packet).
1008 		 * Otherwise open linearly: maxseg per window
1009 		 * (maxseg * (maxseg / cwnd) per packet).
1010 		 */
1011 		{
1012 		register u_int cw = tp->snd_cwnd;
1013 		register u_int incr = tp->t_maxseg;
1014 
1015 		if (cw > tp->snd_ssthresh)
1016 			incr = incr * incr / cw;
1017 		tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1018 		}
1019 		if (acked > so->so_snd.sb_cc) {
1020 			tp->snd_wnd -= so->so_snd.sb_cc;
1021 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1022 			ourfinisacked = 1;
1023 		} else {
1024 			sbdrop(&so->so_snd, acked);
1025 			tp->snd_wnd -= acked;
1026 			ourfinisacked = 0;
1027 		}
1028 		if (so->so_snd.sb_flags & SB_NOTIFY)
1029 			sowwakeup(so);
1030 		tp->snd_una = ti->ti_ack;
1031 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1032 			tp->snd_nxt = tp->snd_una;
1033 
1034 		switch (tp->t_state) {
1035 
1036 		/*
1037 		 * In FIN_WAIT_1 STATE in addition to the processing
1038 		 * for the ESTABLISHED state if our FIN is now acknowledged
1039 		 * then enter FIN_WAIT_2.
1040 		 */
1041 		case TCPS_FIN_WAIT_1:
1042 			if (ourfinisacked) {
1043 				/*
1044 				 * If we can't receive any more
1045 				 * data, then closing user can proceed.
1046 				 * Starting the timer is contrary to the
1047 				 * specification, but if we don't get a FIN
1048 				 * we'll hang forever.
1049 				 */
1050 				if (so->so_state & SS_CANTRCVMORE) {
1051 					soisdisconnected(so);
1052 					tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1053 				}
1054 				tp->t_state = TCPS_FIN_WAIT_2;
1055 			}
1056 			break;
1057 
1058 	 	/*
1059 		 * In CLOSING STATE in addition to the processing for
1060 		 * the ESTABLISHED state if the ACK acknowledges our FIN
1061 		 * then enter the TIME-WAIT state, otherwise ignore
1062 		 * the segment.
1063 		 */
1064 		case TCPS_CLOSING:
1065 			if (ourfinisacked) {
1066 				tp->t_state = TCPS_TIME_WAIT;
1067 				tcp_canceltimers(tp);
1068 				tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1069 				soisdisconnected(so);
1070 			}
1071 			break;
1072 
1073 		/*
1074 		 * In LAST_ACK, we may still be waiting for data to drain
1075 		 * and/or to be acked, as well as for the ack of our FIN.
1076 		 * If our FIN is now acknowledged, delete the TCB,
1077 		 * enter the closed state and return.
1078 		 */
1079 		case TCPS_LAST_ACK:
1080 			if (ourfinisacked) {
1081 				tp = tcp_close(tp);
1082 				goto drop;
1083 			}
1084 			break;
1085 
1086 		/*
1087 		 * In TIME_WAIT state the only thing that should arrive
1088 		 * is a retransmission of the remote FIN.  Acknowledge
1089 		 * it and restart the finack timer.
1090 		 */
1091 		case TCPS_TIME_WAIT:
1092 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1093 			goto dropafterack;
1094 		}
1095 	}
1096 
1097 step6:
1098 	/*
1099 	 * Update window information.
1100 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1101 	 */
1102 	if ((tiflags & TH_ACK) &&
1103 	    (SEQ_LT(tp->snd_wl1, ti->ti_seq) || tp->snd_wl1 == ti->ti_seq &&
1104 	    (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1105 	     tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))) {
1106 		/* keep track of pure window updates */
1107 		if (ti->ti_len == 0 &&
1108 		    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1109 			tcpstat.tcps_rcvwinupd++;
1110 		tp->snd_wnd = tiwin;
1111 		tp->snd_wl1 = ti->ti_seq;
1112 		tp->snd_wl2 = ti->ti_ack;
1113 		if (tp->snd_wnd > tp->max_sndwnd)
1114 			tp->max_sndwnd = tp->snd_wnd;
1115 		needoutput = 1;
1116 	}
1117 
1118 	/*
1119 	 * Process segments with URG.
1120 	 */
1121 	if ((tiflags & TH_URG) && ti->ti_urp &&
1122 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1123 		/*
1124 		 * This is a kludge, but if we receive and accept
1125 		 * random urgent pointers, we'll crash in
1126 		 * soreceive.  It's hard to imagine someone
1127 		 * actually wanting to send this much urgent data.
1128 		 */
1129 		if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1130 			ti->ti_urp = 0;			/* XXX */
1131 			tiflags &= ~TH_URG;		/* XXX */
1132 			goto dodata;			/* XXX */
1133 		}
1134 		/*
1135 		 * If this segment advances the known urgent pointer,
1136 		 * then mark the data stream.  This should not happen
1137 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1138 		 * a FIN has been received from the remote side.
1139 		 * In these states we ignore the URG.
1140 		 *
1141 		 * According to RFC961 (Assigned Protocols),
1142 		 * the urgent pointer points to the last octet
1143 		 * of urgent data.  We continue, however,
1144 		 * to consider it to indicate the first octet
1145 		 * of data past the urgent section as the original
1146 		 * spec states (in one of two places).
1147 		 */
1148 		if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1149 			tp->rcv_up = ti->ti_seq + ti->ti_urp;
1150 			so->so_oobmark = so->so_rcv.sb_cc +
1151 			    (tp->rcv_up - tp->rcv_nxt) - 1;
1152 			if (so->so_oobmark == 0)
1153 				so->so_state |= SS_RCVATMARK;
1154 			sohasoutofband(so);
1155 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1156 		}
1157 		/*
1158 		 * Remove out of band data so doesn't get presented to user.
1159 		 * This can happen independent of advancing the URG pointer,
1160 		 * but if two URG's are pending at once, some out-of-band
1161 		 * data may creep in... ick.
1162 		 */
1163 		if (ti->ti_urp <= ti->ti_len
1164 #ifdef SO_OOBINLINE
1165 		     && (so->so_options & SO_OOBINLINE) == 0
1166 #endif
1167 		     )
1168 			tcp_pulloutofband(so, ti, m);
1169 	} else
1170 		/*
1171 		 * If no out of band data is expected,
1172 		 * pull receive urgent pointer along
1173 		 * with the receive window.
1174 		 */
1175 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1176 			tp->rcv_up = tp->rcv_nxt;
1177 dodata:							/* XXX */
1178 
1179 	/*
1180 	 * Process the segment text, merging it into the TCP sequencing queue,
1181 	 * and arranging for acknowledgment of receipt if necessary.
1182 	 * This process logically involves adjusting tp->rcv_wnd as data
1183 	 * is presented to the user (this happens in tcp_usrreq.c,
1184 	 * case PRU_RCVD).  If a FIN has already been received on this
1185 	 * connection then we just ignore the text.
1186 	 */
1187 	if ((ti->ti_len || (tiflags&TH_FIN)) &&
1188 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1189 		TCP_REASS(tp, ti, m, so, tiflags);
1190 		/*
1191 		 * Note the amount of data that peer has sent into
1192 		 * our window, in order to estimate the sender's
1193 		 * buffer size.
1194 		 */
1195 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1196 	} else {
1197 		m_freem(m);
1198 		tiflags &= ~TH_FIN;
1199 	}
1200 
1201 	/*
1202 	 * If FIN is received ACK the FIN and let the user know
1203 	 * that the connection is closing.
1204 	 */
1205 	if (tiflags & TH_FIN) {
1206 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1207 			socantrcvmore(so);
1208 			tp->t_flags |= TF_ACKNOW;
1209 			tp->rcv_nxt++;
1210 		}
1211 		switch (tp->t_state) {
1212 
1213 	 	/*
1214 		 * In SYN_RECEIVED and ESTABLISHED STATES
1215 		 * enter the CLOSE_WAIT state.
1216 		 */
1217 		case TCPS_SYN_RECEIVED:
1218 		case TCPS_ESTABLISHED:
1219 			tp->t_state = TCPS_CLOSE_WAIT;
1220 			break;
1221 
1222 	 	/*
1223 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1224 		 * enter the CLOSING state.
1225 		 */
1226 		case TCPS_FIN_WAIT_1:
1227 			tp->t_state = TCPS_CLOSING;
1228 			break;
1229 
1230 	 	/*
1231 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1232 		 * starting the time-wait timer, turning off the other
1233 		 * standard timers.
1234 		 */
1235 		case TCPS_FIN_WAIT_2:
1236 			tp->t_state = TCPS_TIME_WAIT;
1237 			tcp_canceltimers(tp);
1238 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1239 			soisdisconnected(so);
1240 			break;
1241 
1242 		/*
1243 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1244 		 */
1245 		case TCPS_TIME_WAIT:
1246 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1247 			break;
1248 		}
1249 	}
1250 	if (so->so_options & SO_DEBUG)
1251 		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1252 
1253 	/*
1254 	 * Return any desired output.
1255 	 */
1256 	if (needoutput || (tp->t_flags & TF_ACKNOW))
1257 		(void) tcp_output(tp);
1258 	return;
1259 
1260 dropafterack:
1261 	/*
1262 	 * Generate an ACK dropping incoming segment if it occupies
1263 	 * sequence space, where the ACK reflects our state.
1264 	 */
1265 	if (tiflags & TH_RST)
1266 		goto drop;
1267 	m_freem(m);
1268 	tp->t_flags |= TF_ACKNOW;
1269 	(void) tcp_output(tp);
1270 	return;
1271 
1272 dropwithreset:
1273 	/*
1274 	 * Generate a RST, dropping incoming segment.
1275 	 * Make ACK acceptable to originator of segment.
1276 	 * Don't bother to respond if destination was broadcast/multicast.
1277 	 */
1278 	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1279 	    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
1280 		goto drop;
1281 	if (tiflags & TH_ACK)
1282 		tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1283 	else {
1284 		if (tiflags & TH_SYN)
1285 			ti->ti_len++;
1286 		tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1287 		    TH_RST|TH_ACK);
1288 	}
1289 	/* destroy temporarily created socket */
1290 	if (dropsocket)
1291 		(void) soabort(so);
1292 	return;
1293 
1294 drop:
1295 	/*
1296 	 * Drop space held by incoming segment and return.
1297 	 */
1298 	if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1299 		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1300 	m_freem(m);
1301 	/* destroy temporarily created socket */
1302 	if (dropsocket)
1303 		(void) soabort(so);
1304 	return;
1305 #ifndef TUBA_INCLUDE
1306 }
1307 
1308 void
1309 tcp_dooptions(tp, cp, cnt, ti, ts_present, ts_val, ts_ecr)
1310 	struct tcpcb *tp;
1311 	u_char *cp;
1312 	int cnt;
1313 	struct tcpiphdr *ti;
1314 	int *ts_present;
1315 	u_long *ts_val, *ts_ecr;
1316 {
1317 	u_short mss;
1318 	int opt, optlen;
1319 
1320 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1321 		opt = cp[0];
1322 		if (opt == TCPOPT_EOL)
1323 			break;
1324 		if (opt == TCPOPT_NOP)
1325 			optlen = 1;
1326 		else {
1327 			optlen = cp[1];
1328 			if (optlen <= 0)
1329 				break;
1330 		}
1331 		switch (opt) {
1332 
1333 		default:
1334 			continue;
1335 
1336 		case TCPOPT_MAXSEG:
1337 			if (optlen != TCPOLEN_MAXSEG)
1338 				continue;
1339 			if (!(ti->ti_flags & TH_SYN))
1340 				continue;
1341 			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1342 			NTOHS(mss);
1343 			(void) tcp_mss(tp, mss);	/* sets t_maxseg */
1344 			break;
1345 
1346 		case TCPOPT_WINDOW:
1347 			if (optlen != TCPOLEN_WINDOW)
1348 				continue;
1349 			if (!(ti->ti_flags & TH_SYN))
1350 				continue;
1351 			tp->t_flags |= TF_RCVD_SCALE;
1352 			tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1353 			break;
1354 
1355 		case TCPOPT_TIMESTAMP:
1356 			if (optlen != TCPOLEN_TIMESTAMP)
1357 				continue;
1358 			*ts_present = 1;
1359 			bcopy((char *)cp + 2, (char *) ts_val, sizeof(*ts_val));
1360 			NTOHL(*ts_val);
1361 			bcopy((char *)cp + 6, (char *) ts_ecr, sizeof(*ts_ecr));
1362 			NTOHL(*ts_ecr);
1363 
1364 			/*
1365 			 * A timestamp received in a SYN makes
1366 			 * it ok to send timestamp requests and replies.
1367 			 */
1368 			if (ti->ti_flags & TH_SYN) {
1369 				tp->t_flags |= TF_RCVD_TSTMP;
1370 				tp->ts_recent = *ts_val;
1371 				tp->ts_recent_age = tcp_now;
1372 			}
1373 			break;
1374 		}
1375 	}
1376 }
1377 
1378 /*
1379  * Pull out of band byte out of a segment so
1380  * it doesn't appear in the user's data queue.
1381  * It is still reflected in the segment length for
1382  * sequencing purposes.
1383  */
1384 void
1385 tcp_pulloutofband(so, ti, m)
1386 	struct socket *so;
1387 	struct tcpiphdr *ti;
1388 	register struct mbuf *m;
1389 {
1390 	int cnt = ti->ti_urp - 1;
1391 
1392 	while (cnt >= 0) {
1393 		if (m->m_len > cnt) {
1394 			char *cp = mtod(m, caddr_t) + cnt;
1395 			struct tcpcb *tp = sototcpcb(so);
1396 
1397 			tp->t_iobc = *cp;
1398 			tp->t_oobflags |= TCPOOB_HAVEDATA;
1399 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1400 			m->m_len--;
1401 			return;
1402 		}
1403 		cnt -= m->m_len;
1404 		m = m->m_next;
1405 		if (m == 0)
1406 			break;
1407 	}
1408 	panic("tcp_pulloutofband");
1409 }
1410 
1411 /*
1412  * Collect new round-trip time estimate
1413  * and update averages and current timeout.
1414  */
1415 void
1416 tcp_xmit_timer(tp, rtt)
1417 	register struct tcpcb *tp;
1418 	short rtt;
1419 {
1420 	register short delta;
1421 
1422 	tcpstat.tcps_rttupdated++;
1423 	if (tp->t_srtt != 0) {
1424 		/*
1425 		 * srtt is stored as fixed point with 3 bits after the
1426 		 * binary point (i.e., scaled by 8).  The following magic
1427 		 * is equivalent to the smoothing algorithm in rfc793 with
1428 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1429 		 * point).  Adjust rtt to origin 0.
1430 		 */
1431 		delta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);
1432 		if ((tp->t_srtt += delta) <= 0)
1433 			tp->t_srtt = 1;
1434 		/*
1435 		 * We accumulate a smoothed rtt variance (actually, a
1436 		 * smoothed mean difference), then set the retransmit
1437 		 * timer to smoothed rtt + 4 times the smoothed variance.
1438 		 * rttvar is stored as fixed point with 2 bits after the
1439 		 * binary point (scaled by 4).  The following is
1440 		 * equivalent to rfc793 smoothing with an alpha of .75
1441 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
1442 		 * rfc793's wired-in beta.
1443 		 */
1444 		if (delta < 0)
1445 			delta = -delta;
1446 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1447 		if ((tp->t_rttvar += delta) <= 0)
1448 			tp->t_rttvar = 1;
1449 	} else {
1450 		/*
1451 		 * No rtt measurement yet - use the unsmoothed rtt.
1452 		 * Set the variance to half the rtt (so our first
1453 		 * retransmit happens at 3*rtt).
1454 		 */
1455 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
1456 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
1457 	}
1458 	tp->t_rtt = 0;
1459 	tp->t_rxtshift = 0;
1460 
1461 	/*
1462 	 * the retransmit should happen at rtt + 4 * rttvar.
1463 	 * Because of the way we do the smoothing, srtt and rttvar
1464 	 * will each average +1/2 tick of bias.  When we compute
1465 	 * the retransmit timer, we want 1/2 tick of rounding and
1466 	 * 1 extra tick because of +-1/2 tick uncertainty in the
1467 	 * firing of the timer.  The bias will give us exactly the
1468 	 * 1.5 tick we need.  But, because the bias is
1469 	 * statistical, we have to test that we don't drop below
1470 	 * the minimum feasible timer (which is 2 ticks).
1471 	 */
1472 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1473 	    tp->t_rttmin, TCPTV_REXMTMAX);
1474 
1475 	/*
1476 	 * We received an ack for a packet that wasn't retransmitted;
1477 	 * it is probably safe to discard any error indications we've
1478 	 * received recently.  This isn't quite right, but close enough
1479 	 * for now (a route might have failed after we sent a segment,
1480 	 * and the return path might not be symmetrical).
1481 	 */
1482 	tp->t_softerror = 0;
1483 }
1484 
1485 /*
1486  * Determine a reasonable value for maxseg size.
1487  * If the route is known, check route for mtu.
1488  * If none, use an mss that can be handled on the outgoing
1489  * interface without forcing IP to fragment; if bigger than
1490  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1491  * to utilize large mbufs.  If no route is found, route has no mtu,
1492  * or the destination isn't local, use a default, hopefully conservative
1493  * size (usually 512 or the default IP max size, but no more than the mtu
1494  * of the interface), as we can't discover anything about intervening
1495  * gateways or networks.  We also initialize the congestion/slow start
1496  * window to be a single segment if the destination isn't local.
1497  * While looking at the routing entry, we also initialize other path-dependent
1498  * parameters from pre-set or cached values in the routing entry.
1499  */
1500 int
1501 tcp_mss(tp, offer)
1502 	register struct tcpcb *tp;
1503 	u_int offer;
1504 {
1505 	struct route *ro;
1506 	register struct rtentry *rt;
1507 	struct ifnet *ifp;
1508 	register int rtt, mss;
1509 	u_long bufsize;
1510 	struct inpcb *inp;
1511 	struct socket *so;
1512 	extern int tcp_mssdflt;
1513 
1514 	inp = tp->t_inpcb;
1515 	ro = &inp->inp_route;
1516 
1517 	if ((rt = ro->ro_rt) == (struct rtentry *)0) {
1518 		/* No route yet, so try to acquire one */
1519 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1520 			ro->ro_dst.sa_family = AF_INET;
1521 			ro->ro_dst.sa_len = sizeof(ro->ro_dst);
1522 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
1523 				inp->inp_faddr;
1524 			rtalloc(ro);
1525 		}
1526 		if ((rt = ro->ro_rt) == (struct rtentry *)0)
1527 			return (tcp_mssdflt);
1528 	}
1529 	ifp = rt->rt_ifp;
1530 	so = inp->inp_socket;
1531 
1532 #ifdef RTV_MTU	/* if route characteristics exist ... */
1533 	/*
1534 	 * While we're here, check if there's an initial rtt
1535 	 * or rttvar.  Convert from the route-table units
1536 	 * to scaled multiples of the slow timeout timer.
1537 	 */
1538 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
1539 		/*
1540 		 * XXX the lock bit for MTU indicates that the value
1541 		 * is also a minimum value; this is subject to time.
1542 		 */
1543 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
1544 			tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
1545 		tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
1546 		if (rt->rt_rmx.rmx_rttvar)
1547 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
1548 			    (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
1549 		else
1550 			/* default variation is +- 1 rtt */
1551 			tp->t_rttvar =
1552 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
1553 		TCPT_RANGESET(tp->t_rxtcur,
1554 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
1555 		    tp->t_rttmin, TCPTV_REXMTMAX);
1556 	}
1557 	/*
1558 	 * if there's an mtu associated with the route, use it
1559 	 */
1560 	if (rt->rt_rmx.rmx_mtu)
1561 		mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
1562 	else
1563 #endif /* RTV_MTU */
1564 	{
1565 		mss = ifp->if_mtu - sizeof(struct tcpiphdr);
1566 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
1567 		if (mss > MCLBYTES)
1568 			mss &= ~(MCLBYTES-1);
1569 #else
1570 		if (mss > MCLBYTES)
1571 			mss = mss / MCLBYTES * MCLBYTES;
1572 #endif
1573 		if (!in_localaddr(inp->inp_faddr))
1574 			mss = min(mss, tcp_mssdflt);
1575 	}
1576 	/*
1577 	 * The current mss, t_maxseg, is initialized to the default value.
1578 	 * If we compute a smaller value, reduce the current mss.
1579 	 * If we compute a larger value, return it for use in sending
1580 	 * a max seg size option, but don't store it for use
1581 	 * unless we received an offer at least that large from peer.
1582 	 * However, do not accept offers under 32 bytes.
1583 	 */
1584 	if (offer)
1585 		mss = min(mss, offer);
1586 	mss = max(mss, 32);		/* sanity */
1587 	if (mss < tp->t_maxseg || offer != 0) {
1588 		/*
1589 		 * If there's a pipesize, change the socket buffer
1590 		 * to that size.  Make the socket buffers an integral
1591 		 * number of mss units; if the mss is larger than
1592 		 * the socket buffer, decrease the mss.
1593 		 */
1594 #ifdef RTV_SPIPE
1595 		if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
1596 #endif
1597 			bufsize = so->so_snd.sb_hiwat;
1598 		if (bufsize < mss)
1599 			mss = bufsize;
1600 		else {
1601 			bufsize = roundup(bufsize, mss);
1602 			if (bufsize > sb_max)
1603 				bufsize = sb_max;
1604 			(void)sbreserve(&so->so_snd, bufsize);
1605 		}
1606 		tp->t_maxseg = mss;
1607 
1608 #ifdef RTV_RPIPE
1609 		if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
1610 #endif
1611 			bufsize = so->so_rcv.sb_hiwat;
1612 		if (bufsize > mss) {
1613 			bufsize = roundup(bufsize, mss);
1614 			if (bufsize > sb_max)
1615 				bufsize = sb_max;
1616 			(void)sbreserve(&so->so_rcv, bufsize);
1617 		}
1618 	}
1619 	tp->snd_cwnd = mss;
1620 
1621 #ifdef RTV_SSTHRESH
1622 	if (rt->rt_rmx.rmx_ssthresh) {
1623 		/*
1624 		 * There's some sort of gateway or interface
1625 		 * buffer limit on the path.  Use this to set
1626 		 * the slow start threshhold, but set the
1627 		 * threshold to no less than 2*mss.
1628 		 */
1629 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
1630 	}
1631 #endif /* RTV_MTU */
1632 	return (mss);
1633 }
1634 #endif /* TUBA_INCLUDE */
1635