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