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