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