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