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