/*
 * vtcp_input.c
 *
 * Derived from:
 *
 * Copyright (c) 1982, 1986 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that this notice is preserved and that due credit is given
 * to the University of California at Berkeley. The name of the University
 * may not be used to endorse or promote products derived from this
 * software without specific prior written permission. This software
 * is provided ``as is'' without express or implied warranty.
 *
 *    @(#)tcp_input.c 7.13+ (Berkeley) 11/13/87
 *
 * Modified for x-kernel v3.3	12/10/90
 * Modifications Copyright (C) 1996,1990  Larry L. Peterson and Norman C. Hutchinson
 *
 * $Revision: 1.8 $
 * $Date: 1998/05/13 02:37:08 $
 */

#include "xkernel.h"
#include "ip.h"
#include "tcp_internal.h"
#include "tcp_fsm.h"
#include "tcp_seq.h"
#include "tcp_timer.h"
#include "tcp_var.h"
#include "tcpip.h"
#include "tcp_debug.h"

#define CANTRCVMORE(so) (sototcpst(so)->closed & 2)

extern int 	Vtcp_rcv_size;

/* int	tcpprintfs = 0; */
static int	tcpcksum = 1;
static struct	tcpiphdr tcp_saveti;

#ifdef __STDC__

static void	tcp_dooptions(PSTATE *, struct tcpcb *, char *, int,
			      struct tcphdr *);
static void 	tcp_pulloutofband(Sessn, struct tcphdr *, Msg *);

#else

static void	tcp_dooptions();
static void 	tcp_pulloutofband();

#endif

/*
 * Insert segment ti into reassembly queue of tcp with
 * control block tp.  Return TH_FIN if reassembly now includes
 * a segment with FIN.  The macro form does the common case inline
 * (segment is the next to be received on an established connection,
 * and the queue is empty), avoiding linkage into and removal
 * from the queue and repetition of various conversions.
 * Set DELACK for segments received in order, but ack immediately
 * when segments are out of order (so fast retransmit can work).
 *
 * Reassembled message, if one exists, is placed in demuxmsg
 * Vegas ACKS on every packet!
 * ---------------------------
 */
#define	TCP_REASS_DELACK(tp, th, so, m, dMsg, flags) { \
	if ((th)->th_seq == (tp)->rcv_nxt && \
	    (tp)->seg_next == (struct reass *)(tp) && \
	    (tp)->t_state == TCPS_ESTABLISHED) { \
		(tp)->t_flags |= TF_DELACK; \
		(tp)->rcv_nxt += msgLength(m); \
		flags = (th)->th_flags & TH_FIN; \
		ps->tcpstat.tcps_rcvpack++;\
		ps->tcpstat.tcps_rcvbyte += msgLength(m);\
		msgAssign((dMsg), (m)); \
	} else { \
		(flags) = tcp_reass((tp), (th), (so), (m), (dMsg)); \
		(tp)->t_flags |= TF_ACKNOW; \
	} \
}
#define TCP_REASS_ACKNOW(tp, th, so, m, dMsg, flags) { \
        if ((th)->th_seq == (tp)->rcv_nxt && \
            (tp)->seg_next == (struct reass *)(tp) && \
            (tp)->t_state == TCPS_ESTABLISHED) { \
/*              (tp)->t_flags |= TF_DELACK; */\
                (tp)->rcv_nxt += msgLength(m); \
                flags = (th)->th_flags & TH_FIN; \
                ps->tcpstat.tcps_rcvpack++;\
                ps->tcpstat.tcps_rcvbyte += msgLength(m);\
                msgAssign((dMsg), (m)); \
        } else \
                (flags) = tcp_reass((tp), (th), (so), (m), (dMsg)); \
        (tp)->t_flags |= TF_ACKNOW; \
}


int
tcp_reass(tp, th, so, m, demuxmsg)
	register struct tcpcb *tp;
	register struct tcphdr *th;
     	Sessn so;
	Msg *m, *demuxmsg;
{
	register struct reass *q, *next;
	int flags;
	PSTATE *ps=(PSTATE *)so->myprotl->state;

	xTrace0(tcpp, TR_FUNCTIONAL_TRACE, "tcp_reass function entered");
	/*
	 * Call with th==0 after become established to
	 * force pre-ESTABLISHED data up to user socket.
	 */
	if (th == 0)
		goto present;

	/*
	 * Find a segment which begins after this one does.
	 */
	for (q = tp->seg_next; q != (struct reass *)tp;
	    q = (struct reass *)q->next)
		if (SEQ_GT(q->th.th_seq, th->th_seq))
			break;

	/*
	 * If there is a preceding segment, it may provide some of
	 * our data already.  If so, drop the data from the incoming
	 * segment.  If it provides all of our data, drop us.
	 */
	if (q->prev != (struct reass *)tp) {
		register int i;
		q = q->prev;
		/* conversion to int (in i) handles seq wraparound */
		i = q->th.th_seq + msgLength(&q->m) - th->th_seq;
		if (i > 0) {
			if (i >= msgLength(m)) {
				ps->tcpstat.tcps_rcvduppack++;
				ps->tcpstat.tcps_rcvdupbyte += msgLength(m);
				return(0);
			}
			msgDiscard(m, i);
			th->th_seq += i;
		}
		q = q->next;
	}
	ps->tcpstat.tcps_rcvoopack++;
	ps->tcpstat.tcps_rcvoobyte += msgLength(m);

	/*
	 * While we overlap succeeding segments trim them or,
	 * if they are completely covered, dequeue them.
	 */
	while (q != (struct reass *)tp) {
		register int i = (th->th_seq + msgLength(m)) - q->th.th_seq;
		if (i <= 0)
			break;
		if (i < msgLength(&q->m)) {
			q->th.th_seq += i;
			msgDiscard(&q->m, i);
			break;
		}
		next = q->next;
		remque(q);
		msgDestroy(&q->m);
		xFree((char *) q);
		q = next;
	}

	/*
	 * Stick new segment in its place.
	 */
	{
		struct reass *new;
		new = (struct reass *)xMalloc(sizeof *new);
		new->th = *th;
		msgConstructCopy(&new->m, m);
		insque(new, q);
/*		print_reass(tp, "Inserted segment"); */
	}
present:
	/*
	 * Present data to user, advancing rcv_nxt through
	 * completed sequence space.
	 */
	if (TCPS_HAVERCVDSYN(tp->t_state) == 0)
		return (0);
	q = tp->seg_next;
	th = &q->th;
	if (q == (struct reass *)tp || th->th_seq != tp->rcv_nxt)
		return (0);
	if (tp->t_state == TCPS_SYN_RECEIVED && msgLength(&q->m))
		return (0);
	do {
		tp->rcv_nxt += msgLength(&q->m);
		flags = th->th_flags & TH_FIN;
		next = q->next;
		remque(q);
		if (! CANTRCVMORE(so)) {
			msgJoin(demuxmsg, demuxmsg, &q->m);
		}
		msgDestroy(&q->m);
		xFree((char *)q);
		q = next;
		th = &q->th;
	} while (q != (struct reass *)tp && th->th_seq == tp->rcv_nxt);
	return (flags);
}


XkReturn
vtcpPop(self, lls, m, hdr)
    Sessn self;
    Sessn lls;
    Msg *m;
    void *hdr;
{
    return xDemux(xGetUp(self), self, m);
}


/*
 * TCP input routine, follows pages 65-76 of the
 * protocol specification dated September, 1981 very closely.
 */
XkReturn
vtcp_input(self, transport_s, m)
	Protl self;
	Sessn transport_s;
	Msg *m;
{
	struct inpcb *inp;
	char *options = 0;
	int option_len = 0;
	int len, tlen, off;
	struct tcpcb *tp = 0;
	register int tiflags;
	Sessn so = 0;
	Protl hlp = 0, hlpType = 0;
	struct tcpstate *tcpst;
	int todrop, acked, ourfinisacked, needoutput = 0;
	short ostate;
	int dropsocket = 0;
	int iss = 0;
        u_long tiwin;
	Msg demuxmsg;
        int demuxmsgDestroyed=0;
	struct tcphdr 	tHdr;
	IPpseudoHdr 	*pHdr;
	bool invoke_cantrcvmore = FALSE;
        int sendTime;
        int transmits;
        int currentTime;
	PSTATE		*ps=(PSTATE *)self->state;
        void *buffer;
        u_short check_sum;

	ps->tcpstat.tcps_rcvtotal++;

	tlen = msgLength(m);
	pHdr = (IPpseudoHdr *)msgGetAttr(m, 0);
	xAssert(pHdr);					/* LSB 8/9/94 */
	/*
	 * Get IP and TCP header together in stack part of message.
	 * UNIX Note: IP leaves IP header in first mbuf.
	 * x-kernel Note:  IP attaches IP pseudoheader (in network byte
	 * order) as the attribute of the message
	 */
        check_sum = inCkSum(m, (u_short *)pHdr, sizeof(IPpseudoHdr));
        buffer = msgPop(m, sizeof(tHdr));
        if (! buffer) {
		xTrace0(tcpp, 3,
			"vtcp_input: msgPop of header failed -- dropping");
		return XK_FAILURE;
	}
        tcpHdrLoad(&tHdr, buffer, sizeof(tHdr), m);

	msgSetAttr(m, 0, 0, 0);

	xTrace4(tcpp, 3, "vtcp_input seq %d, dlen %d, f( %s ) to port (%d)",
	       tHdr.th_seq, msgLength(m), tcpFlagStr(tHdr.th_flags),
	       tHdr.th_dport);

	/* millisecond clock assumption */
        currentTime = tcpGetTime();
	DO_TRACE(ps, TCP_EVENT_IN, currentTime, msgLength(m),
		 GET_TID(tHdr.th_sport,tHdr.th_dport));
	DO_TRACE(ps, TCP_EVENT_DATA, tHdr.th_seq, tHdr.th_win>>4, 0);
	DO_TRACE(ps, TCP_EVENT_DATA, tHdr.th_ack, tHdr.th_flags, 0);
	msgConstructEmpty(&demuxmsg);

	/*
	 * Check the checksum value (calculated in tcpHdrLoad)
	 */
	if (tcpcksum) {
                if (check_sum) {
			xTrace1(tcpp, TR_ERRORS,
				"vtcp_input: bad checksum (%x)", check_sum);
			ps->tcpstat.tcps_rcvbadsum++;
#if BSD<=43
			ps->tcpstat.tcps_badsum++;
#endif
			DO_TRACE(ps, TCP_EVENT_BADSUM, 0, 0, 0);
			goto drop;
		}
	}

	xTrace1(tcpp, 4, "Received msg with sequence number %d",
		tHdr.th_seq);

	/*
	 * Check that TCP offset makes sense,
	 * pull out TCP options and adjust length.
	 */
	off = tHdr.th_off << 2;
	if (off < sizeof (struct tcphdr) || off > tlen) {
		xTrace2(tcpp, 1, "bad tcp off: src %x off %d", pHdr->src, off);
		ps->tcpstat.tcps_rcvbadoff++;
#if BSD<=43
		ps->tcpstat.tcps_badoff++;
#endif
		goto drop;
	}
	tlen -= off;
	if ((option_len = off - sizeof (struct tcphdr)) > 0) {
		xTrace1(tcpp, 3, "vtcp_input: %d bytes of options", option_len);
		/*
		 * Re-check the length, cause option_len increases the size
		 * of the tcp header
		 */
		if (tlen < 0) {
			xTrace2(tcpp, 2,
				"vtcp_input: rcvd short optlen = %d, len = %d",
				option_len, tlen);
			ps->tcpstat.tcps_rcvshort++;
			msgDestroy(&demuxmsg);
			return XK_FAILURE;
		}
		/*
		 * Put the options somewhere reasonable
		 */
		DO_TRACE(ps, TCP_EVENT_ROPT, option_len, 0, 0);
		options = xMalloc(option_len);

                buffer = msgPop(m, option_len);
                xAssert(buffer);
                tcpOptionsLoad(options, buffer, option_len, 0);
	}
	tiflags = tHdr.th_flags;

	/*
	 * Locate pcb for segment.
	 */
findpcb:
	{
		ActiveId	activeId;
		PassiveId 	passiveId;
		PSTATE		*pstate;

		pstate = (PSTATE *)self->state;
		bzero((char *)&activeId, sizeof(activeId));
		activeId.localport = tHdr.th_dport;
		activeId.remoteport = tHdr.th_sport;
		activeId.remoteaddr = pHdr->src;
		xTrace3(tcpp, 4, "Looking for %d->%s.%d",
			activeId.localport, ipHostStr(&activeId.remoteaddr),
			activeId.remoteport);
		/* look in the active map */
		if (mapResolve(pstate->activeMap, &activeId, (void **)&so) ==
		    XK_FAILURE) {
			/*
			 * Look in the passive map
			 */
			Enable	*e;

			passiveId = activeId.localport;
			xTrace1(tcpp, 4, "Looking for passive open on %d",
				passiveId);
			/* look in the map */
			if (mapResolve(pstate->passiveMap, &passiveId,
				       (void **)&e) == XK_FAILURE) {
				xTrace0(tcpp, 4,
					"No passive open object exists");
				so = 0;
				hlp = 0;
				inp = 0;
				tp = 0;
			} else {
				hlp = e->hlp;
				hlpType = e->hlpType;
				Vtcp_rcv_size = (int)e->info;
				xTrace1(tcpp, 4,
					"Found openenable object: %lx",
					(u_long)so);
				inp = 0;
				tp =  0;
			}
		} else {
			inp = sototcpst(so)->inpcb;
			tp =  sototcpst(so)->tcpcb;
		}
	}

	/*
	 * If the state is CLOSED (i.e., TCB does not exist) then
	 * all data in the incoming segment is discarded.
	 * If the TCB exists but is in CLOSED state, it is embryonic,
	 * but should either do a listen or a connect soon.
	 */
	if (!so && !hlp) {
		xTrace0(tcpp, 2, "vtcp_input:  no so");
		goto dropwithreset;
	}
	if (xIsProtl(hlp)) {
		so = vtcp_sonewconn(self, hlp, hlpType, &pHdr->src, &pHdr->dst,
			       tHdr.th_sport, tHdr.th_dport);
		if (so == 0)
			goto drop;
		/*
		 * This is ugly, but ....
		 *
		 * Mark socket as temporary until we're
		 * committed to keeping it.  The code at
		 * ``drop'' and ``dropwithreset'' check the
		 * flag dropsocket to see if the temporary
		 * socket created here should be discarded.
		 * We mark the socket as discardable until
		 * we're committed to it below in TCPS_LISTEN.
		 */
		dropsocket++;
		inp = sotoinpcb(so);
		bcopy((char *)&pHdr->dst, (char *)&inp->inp_laddr,
		      sizeof(pHdr->dst));
		inp->inp_lport = tHdr.th_dport;
		tp = intotcpcb(inp);
		tp->t_state = TCPS_LISTEN;
                /* Compute proper scaling value from buffer space
                 */
                while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
                       TCP_MAXWIN << tp->request_r_scale <
                       sototcpst(so)->rcv_hiwat)
                  tp->request_r_scale++;
	}
	xIfTrace(tcpp, 1) {
		ostate = tp->t_state;
#if 0
		tcp_saveti = *ti;
#endif
	}
	tcpst = sototcpst(so);
	if (inp == 0) {
		xTrace0(tcpp, 2, "vtcp_input:  no inp");
		goto dropwithreset;
	}
	if (tp == 0) {
		xTrace0(tcpp, 2, "vtcp_input:  no tp");
		goto dropwithreset;
	}
	if (tp->t_state == TCPS_CLOSED) {
		xTrace0(tcpp, 2, "vtcp_input:  TCPS_CLOSED");
		goto drop;
	}
        /* Unscale the window into a 32-bit value. */
        if ((tiflags & TH_SYN) == 0)
                tiwin = tHdr.th_win << tp->snd_scale;
        else
                tiwin = tHdr.th_win;

/*
 * Proposed tcp_demux / tcp_pop split
 */

	/*
	 * Segment received on connection.
	 * Reset idle time and keep-alive timer.
	 */
	tp->t_idle = 0;
	tp->t_timer[TCPT_KEEP] = TCPTV_KEEP;

	/*
	 * Process options if not in LISTEN state,
	 * else do it below (after getting remote address).
	 */
	if (options && tp->t_state != TCPS_LISTEN) {
		tcp_dooptions(ps, tp, options, option_len, &tHdr);
		options = 0;
	}

	/*
	 * Calculate amount of space in receive window,
	 * and then do TCP input processing.
	 * Receive window is amount of space in rcv queue,
	 * but not less than advertised window.
	 */
	{
		int win;
		win = tcpst->rcv_space;
		if (win < 0)
		  win = 0;
		tp->rcv_wnd = MAX(win, (int)(tp->rcv_adv - tp->rcv_nxt));
		xTrace4(tcpp, 5,
			"New win (%x) = max(std (%x), adv (%x) - nxt (%x))",
			tp->rcv_wnd, win, tp->rcv_adv, tp->rcv_nxt);
	}

	xTrace2(tcpp, 4, "vtcp_input: tcpcb %lx switch %s", (u_long)tp,
		tcpstates[tp->t_state]);

	DO_TRACE(ps, TCP_EVENT_IN0, tp->rcv_nxt, tp->t_state, tcpst->tid);
	switch (tp->t_state) {

	/*
	 * If the state is LISTEN then ignore segment if it contains an RST.
	 * If the segment contains an ACK then it is bad and send a RST.
	 * If it does not contain a SYN then it is not interesting; drop it.
	 * Don't bother responding if the destination was a broadcast.
	 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
	 * tp->iss, and send a segment:
	 *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
	 * Fill in remote peer address fields if not previously specified.
	 * Enter SYN_RECEIVED state, and process any other fields of this
	 * segment in this state.
	 */
	case TCPS_LISTEN: {
		if (tiflags & TH_RST)
			goto drop;
		if (tiflags & TH_ACK)
			goto dropwithreset;
		if ((tiflags & TH_SYN) == 0)
			goto drop;
		if (in_broadcast(*(struct in_addr *)&pHdr->dst))
			goto drop;
		xTrace0(tcpp, 3, "vtcp_input: LISTEN");
		tp->t_template = tcp_template(tp);
		if (tp->t_template == 0) {
			tp = tcp_drop(tp, ENOBUFS);
			dropsocket = 0;		/* socket is already gone */
			goto drop;
		}
		if (options) {
			tcp_dooptions(ps, tp, options, option_len, &tHdr);
		}
		if (iss)
			tp->iss = iss;
		else
			tp->iss = ps->tcp_iss;
		ps->tcp_iss += TCP_ISSINCR/2;
		tp->irs = tHdr.th_seq;
		tcp_sendseqinit(tp);
		tp->v_cong_detect_begseq = tp->snd_nxt; /* Vegas var */
		tcp_rcvseqinit(tp);
		tp->t_flags |= TF_ACKNOW;
		tp->t_state = TCPS_SYN_RECEIVED;
		tp->t_timer[TCPT_KEEP] = TCPTV_KEEP;
		dropsocket = 0;		/* committed to socket */
		ps->tcpstat.tcps_accepts++;
		goto trimthenstep6;
	}

	/*
	 * If the state is SYN_SENT:
	 *	if seg contains an ACK, but not for our SYN, drop the input.
	 *	if seg contains a RST, then drop the connection.
	 *	if seg does not contain SYN, then drop it.
	 * Otherwise this is an acceptable SYN segment
	 *	initialize tp->rcv_nxt and tp->irs
	 *	if seg contains ack then advance tp->snd_una
	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
	 *	arrange for segment to be acked (eventually)
	 *	continue processing rest of data/controls, beginning with URG
	 */
	case TCPS_SYN_SENT:
		if ((tiflags & TH_ACK) &&
		    (SEQ_LEQ(tHdr.th_ack, tp->iss) ||
		     SEQ_GT(tHdr.th_ack, tp->snd_max))) {
			xTrace0(tcpp, 4,
				"input state SYN_SENT -- dropping with reset");
			xTrace3(tcpp, 4, "   (ack==%d, iss==%d, snd_max==%d)",
				tHdr.th_ack, tp->iss, tp->snd_max);
			goto dropwithreset;
		}
		if (tiflags & TH_RST) {
			if (tiflags & TH_ACK)
				tp = tcp_drop(tp, ECONNREFUSED);
			goto drop;
		}
		if ((tiflags & TH_SYN) == 0)
			goto drop;
		if (tiflags & TH_ACK) {
			tp->snd_una = tHdr.th_ack;
			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
				tp->snd_nxt = tp->snd_una;
		}
		tp->t_timer[TCPT_REXMT] = 0;
		tp->irs = tHdr.th_seq;
		tcp_rcvseqinit(tp);
	        tp->t_flags |= TF_ACKNOW;
	        tp->v_cong_detect_begtime = currentTime; /* Vegas var */
		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
			ps->tcpstat.tcps_connects++;
			soisconnected(so);
			tp->t_state = TCPS_ESTABLISHED;
                        if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
                                (TF_RCVD_SCALE|TF_REQ_SCALE)) {
                                tp->snd_scale = tp->requested_s_scale;
                                tp->rcv_scale = tp->request_r_scale;
                        }
			tp->t_maxseg = MIN(tp->t_maxseg, tcp_mss(tp));
			(void) tcp_reass(tp, NULL, so, NULL, &demuxmsg);
			/*
			 * if we didn't have to retransmit the SYN,
			 * use its rtt as our initial srtt & rtt var.
			 */
			if (tp->t_rtt) {
			        /* Initialize Vegas RTT variables
				 */
			        if (tp->v_timeout == 1000 &&
				    tp->v_synsent != 0) {
                                  tp->v_rtt = currentTime - tp->v_synsent + 1;
                                  tp->v_sa = tp->v_rtt << 3;
                                  tp->v_sd = tp->v_rtt;
                                  tp->v_timeout = ((tp->v_sa >> 2) +
                                                   tp->v_sd) >> 1;
                                  DO_TRACE(ps, TCP_EVENT_SET_TO, tp->v_timeout,
                                           tp->v_rtt, tHdr.th_dport);
                                }
				tp->t_srtt = tp->t_rtt << 3;
				tp->t_rttvar = tp->t_rtt << 1;
				TCPT_RANGESET(tp->t_rxtcur,
				    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
				    TCPTV_MIN, TCPTV_REXMTMAX);
				DO_TRACE(ps, TCP_EVENT_OTHER9,
					 tp->t_rxtcur, 4, 0);
				tp->t_rtt = 0;
			}
		} else
			tp->t_state = TCPS_SYN_RECEIVED;

trimthenstep6:
		/*
		 * Advance ti->ti_seq to correspond to first data byte.
		 * If data, trim to stay within window,
		 * dropping FIN if necessary.
		 */
	  	tHdr.th_seq++;
		if (tlen > tp->rcv_wnd) {
			todrop = tlen - tp->rcv_wnd;
			xTrace2(tcpp, 5,
				"tlen (%d) > rcv_wnd (%d) ... truncating",
				tlen, tp->rcv_wnd);
			msgTruncate(m, todrop);
			tlen = tp->rcv_wnd;
			tiflags &= ~TH_FIN;
			ps->tcpstat.tcps_rcvpackafterwin++;
			ps->tcpstat.tcps_rcvbyteafterwin += todrop;
		}
		tp->snd_wl1 = tHdr.th_seq - 1;
		tp->rcv_up = tHdr.th_seq;
		goto step6;
	}

	/*
	 * States other than LISTEN or SYN_SENT.
	 * First check that at least some bytes of segment are within
	 * receive window.  If segment begins before rcv_nxt,
	 * drop leading data (and SYN); if nothing left, just ack.
	 */
	todrop = tp->rcv_nxt - tHdr.th_seq;
	if (todrop > 0) {
		if (tiflags & TH_SYN) {
			tiflags &= ~TH_SYN;
			tHdr.th_seq++;
			if (tHdr.th_urp > 1)
				tHdr.th_urp--;
			else
				tiflags &= ~TH_URG;
			todrop--;
		}
		if (todrop > tlen ||
		    todrop == tlen && (tiflags & TH_FIN) == 0) {
#ifdef TCP_COMPAT_42
			/*
			 * Don't toss RST in response to 4.2-style keepalive.
			 */
			if (tHdr.th_seq == tp->rcv_nxt - 1 && tiflags & TH_RST)
				goto do_rst;
#endif
			ps->tcpstat.tcps_rcvduppack++;
			ps->tcpstat.tcps_rcvdupbyte += tlen;
			todrop = tlen;
			tiflags &= ~TH_FIN;
			tp->t_flags |= TF_ACKNOW;
		} else {
			ps->tcpstat.tcps_rcvpartduppack++;
			ps->tcpstat.tcps_rcvpartdupbyte += todrop;
		}
		xTrace1(tcpp, 5, "Discarding %d bytes from front of msg",
			todrop);
		msgDiscard(m, todrop);
		tHdr.th_seq += todrop;
		tlen -= todrop;
		if (tHdr.th_urp > todrop)
			tHdr.th_urp -= todrop;
		else {
			tiflags &= ~TH_URG;
			tHdr.th_urp = 0;
		}
	}

	/*
	 * If new data is received on a connection after the
	 * user processes are gone, then RST the other end.
	 */
#define ISNOTREFERENCED(X) 0
	if (ISNOTREFERENCED(so) &&
	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
		tp = tcp_destroy(tp);
		ps->tcpstat.tcps_rcvafterclose++;
		goto dropwithreset;
	}

	/*
	 * If segment ends after window, drop trailing data
	 * (and PUSH and FIN); if nothing left, just ACK.
	 */
	todrop = (tHdr.th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
	if (todrop > 0) {
		ps->tcpstat.tcps_rcvpackafterwin++;
		if (todrop >= tlen) {
			ps->tcpstat.tcps_rcvbyteafterwin += tlen;
			/*
			 * If a new connection request is received
			 * while in TIME_WAIT, drop the old connection
			 * and start over if the sequence numbers
			 * are above the previous ones.
			 */
			if (tiflags & TH_SYN &&
			    tp->t_state == TCPS_TIME_WAIT &&
			    SEQ_GT(tHdr.th_seq, tp->rcv_nxt)) {
				iss = tp->rcv_nxt + TCP_ISSINCR;
				(void) tcp_destroy(tp);
				goto findpcb;
			}
			/*
			 * If window is closed can only take segments at
			 * window edge, and have to drop data and PUSH from
			 * incoming segments.  Continue processing, but
			 * remember to ack.  Otherwise, drop segment
			 * and ack.
			 */
			if (tp->rcv_wnd == 0 && tHdr.th_seq == tp->rcv_nxt) {
				tp->t_flags |= TF_ACKNOW;
				ps->tcpstat.tcps_rcvwinprobe++;
			} else
				goto dropafterack;
		} else
			ps->tcpstat.tcps_rcvbyteafterwin += todrop;
		xTrace1(tcpp, 5,
			"segment ends after window -- truncating to %d",
			todrop);
		msgTruncate(m, todrop);
		tlen -= todrop;
		tiflags &= ~(TH_PUSH|TH_FIN);
	}

#ifdef TCP_COMPAT_42
do_rst:
#endif
	/*
	 * If the RST bit is set examine the state:
	 *    SYN_RECEIVED STATE:
	 *	If passive open, return to LISTEN state.
	 *	If active open, inform user that connection was refused.
	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
	 *	Inform user that connection was reset, and close tcb.
	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
	 *	Close the tcb.
	 */
	if (tiflags & TH_RST) switch (tp->t_state) {

	case TCPS_SYN_RECEIVED:
		tp = tcp_drop(tp, ECONNREFUSED);
		goto drop;

	case TCPS_ESTABLISHED:
	case TCPS_FIN_WAIT_1:
	case TCPS_FIN_WAIT_2:
	case TCPS_CLOSE_WAIT:
		tp = tcp_drop(tp, ECONNRESET);
		goto drop;

	case TCPS_CLOSING:
	case TCPS_LAST_ACK:
	case TCPS_TIME_WAIT:
		tp = tcp_destroy(tp);
		goto drop;
	}

	/*
	 * If a SYN is in the window, then this is an
	 * error and we send an RST and drop the connection.
	 */
	if (tiflags & TH_SYN) {
		tp = tcp_drop(tp, ECONNRESET);
		goto dropwithreset;
	}

	/*
	 * If the ACK bit is off we drop the segment and return.
	 */
	if ((tiflags & TH_ACK) == 0)
		goto drop;

	/*
	 * Ack processing.
	 */
	switch (tp->t_state) {

	/*
	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
	 * ESTABLISHED state and continue processing, otherwise
	 * send an RST.
	 */
	case TCPS_SYN_RECEIVED:
		if (SEQ_GT(tp->snd_una, tHdr.th_ack) ||
		    SEQ_GT(tHdr.th_ack, tp->snd_max))
			goto dropwithreset;
		ps->tcpstat.tcps_connects++;
		soisconnected(so);
		tp->t_state = TCPS_ESTABLISHED;
                /* Do window scaling? */
                if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
                        (TF_RCVD_SCALE|TF_REQ_SCALE)) {
                        tp->snd_scale = tp->requested_s_scale;
                        tp->rcv_scale = tp->request_r_scale;
                }
		tp->t_maxseg = MIN(tp->t_maxseg, tcp_mss(tp));
		(void) tcp_reass(tp, NULL, so, NULL, &demuxmsg);
		tp->snd_wl1 = tHdr.th_seq - 1;
		/* fall into ... */

	/*
	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
	 * ACKs.  If the ack is in the range
	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
	 * then advance tp->snd_una to ti->ti_ack and drop
	 * data from the retransmission queue.  If this ACK reflects
	 * more up to date window information we update our window information.
	 */
	case TCPS_ESTABLISHED:
	case TCPS_FIN_WAIT_1:
	case TCPS_FIN_WAIT_2:
	case TCPS_CLOSE_WAIT:
	case TCPS_CLOSING:
	case TCPS_LAST_ACK:
	case TCPS_TIME_WAIT:

		if (SEQ_LEQ(tHdr.th_ack, tp->snd_una)) {
			if (tlen == 0 && tiwin == tp->snd_wnd) {
			  ps->tcpstat.tcps_rcvdupack++;
				/*
				 * If we have outstanding data (not a
				 * window probe), this is a completely
				 * duplicate ack (ie, window info didn't
				 * change), the ack is the biggest we've
				 * seen and we've seen exactly our rexmt
				 * threshhold of them, assume a packet
				 * has been dropped and retransmit it.
                                 * Kludge snd_nxt & the congestion
                                 * window so we send only this one
                                 * packet.
                                 *
                                 * We know we're losing at the current
                                 * window size so do congestion avoidance
                                 * (set ssthresh to half the current window
                                 * and pull our congestion window back to
                                 * the new ssthresh).
                                 *
                                 * Dup acks mean that packets have left the
                                 * network (they're now cached at the receiver)
                                 * so bump cwnd by the amount in the receiver
                                 * to keep a constant cwnd packets in the
                                 * network.
				 */
                         if (tp->t_timer[TCPT_REXMT] == 0 ||
                              tHdr.th_ack != tp->snd_una)
                            tp->t_dupacks = 0;

			 else { /* we have a duplicate ACK */
			    /* Vegas retransmit mods:
	  		     * Find out if any segments timed out. Sbexpire
			     * sets transmits and sendTime and returns
			     * the number of bytes contained in all segments
			     * which have timed out. Transmits is
			     * the number of times the first segment that
			     * needs to be retransmitted has been transmitted
			     * already. SendTime is the time when the first
			     * segment was last transmitted.
			     */
                            len = sbexpire(tcpst->snd,
                                           currentTime-tp->v_timeout,
                                           tp->t_maxseg, &transmits,
                                           &sendTime);

/*                        if ((tp->snd_nxt-tp->snd_una >= 2*tp->t_maxseg &&  */
			    if (( len >= tp->t_maxseg) ||
				++tp->t_dupacks == tp->t_rexmtthresh) {
                              tcp_seq onxt=tp->snd_nxt;
                              u_long win = MIN(tp->snd_wnd, tp->snd_cwnd);
                              u_long old_cwnd=tp->snd_cwnd;

			      /* we will check for timed out segments when
			       * we receive the next two non-duplicate ACKS
			       * (or less depending on how much is in transit).
			       */
			      tp->v_worried = MIN(2, (tp->snd_nxt-tp->snd_una)/
						     tp->t_maxseg - 1);
                              tp->snd_nxt = tHdr.th_ack;
                              tp->snd_cwnd = tp->t_maxseg;
			      if (tp->t_dupacks != tp->t_rexmtthresh) {
				ps->tcpstat.tcps_dupftimeo++;
				DO_TRACE(ps, TCP_EVENT_WSND,
					 len,
					 tp->v_worried,
					 tHdr.th_dport);
			      }

			      /* Do exponential backoff if segment has
			       * been sent more than once
			       */
                              if (transmits > 1) {
				DO_TRACE(ps, TCP_EVENT_RTO, tp->v_timeout<<1,
					 tp->v_timeout, tHdr.th_dport);
				tp->v_timeout <<= 1;
/* 				if (tp->t_dupacks != tp->t_rexmtthresh)  */
/* 				  break; */
                              }
			      else
				tp->v_timeout += (tp->v_timeout >> 3);

			      /* If cwnd hasn't changed since the segment
			       * was sent, then we need to decrease it
			       */
			      if (tp->v_time_cwin_chg < sendTime) {
                                win /= tp->t_maxseg;
				if (win <= 3)
				  win = 2;
 				else if (transmits > 1)
 				  win /= 2;
				else
				  win -= (win >> 2);
				tp->v_newcwnd = win * tp->t_maxseg;
                                tp->t_timer[TCPT_REXMT] = 0;
                                tp->t_rtt = 0;
                                (void) vtcp_output(tp);
                                tp->v_time_cwin_chg = tcpGetTime();
				tp->snd_cwnd = tp->v_newcwnd +
                                  tp->t_maxseg * tp->t_dupacks;
				if (len > 0) {
				  DO_TRACE(ps, TCP_EVENT_RCWND,
					   tp->snd_cwnd,
					   TCP_NOTE_WORRIED,
					   tHdr.th_dport);
				}
				else {
				  DO_TRACE(ps, TCP_EVENT_RCWND,
					   tp->snd_cwnd,
					   TCP_NOTE_DUPACK,
					   tHdr.th_dport);
				}
                              }
                              else { /* no need to change cwnd */
                                (void) vtcp_output(tp);
                                tp->snd_cwnd = old_cwnd;
                              }
			      if (transmits == 1)
				tp->t_dupacks = tp->t_rexmtthresh;
                              if (SEQ_GT(onxt, tp->snd_nxt))
                                tp->snd_nxt = onxt;
                              goto drop;

                            } else if (tp->t_dupacks > tp->t_rexmtthresh) {
                              if (tp->snd_cwnd < (65535 - tp->t_maxseg))
                                tp->snd_cwnd += tp->t_maxseg;

			      /* Toggle for exponential decrease of
			       * sending rate after losses, instead of
			       * waiting half a RTT before starting sending
			       * again. Currently not used.
			       */
/*			      if ((tp->v_send_toggle = !tp->v_send_toggle))
                                tp->v_use_sndwnd = 1;
*/
                              (void) vtcp_output(tp);
                              goto drop;
                            }
                          }
			} else
			  tp->t_dupacks = 0;
			break;
		}

                /*
                 * If the congestion window was inflated to account
                 * for the other side's cached packets, retract it.
                 */
                if (tp->t_dupacks > tp->t_rexmtthresh &&
                    tp->snd_cwnd > tp->v_newcwnd) {
                        tp->snd_cwnd = tp->v_newcwnd;
			/* In Vegas ssthresh is only used during slow-start */
			tp->snd_ssthresh = 2*tp->t_maxseg;
		    }
		tp->t_dupacks = 0;
		if (SEQ_GT(tHdr.th_ack, tp->snd_max)) {
			ps->tcpstat.tcps_rcvacktoomuch++;
			goto dropafterack;
		}
		acked = tHdr.th_ack - tp->snd_una;
		ps->tcpstat.tcps_rcvackpack++;
		ps->tcpstat.tcps_rcvackbyte += acked;

		xTrace2(tcpp, 4,
			"Received ACK for byte %d (%d new bytes ACKED)",
			tHdr.th_ack, acked);
		DO_TRACE(ps, TCP_EVENT_IN1, tHdr.th_ack, acked, tcpst->tid);

		/*
		 * If transmit timer is running and timed sequence
		 * number was acked, update smoothed round trip time.
		 * Since we now have an rtt measurement, cancel the
		 * timer backoff (cf., Phil Karn's retransmit alg.).
		 * Recompute the initial retransmit timer.
		 */
		if (tp->t_rtt && SEQ_GT(tHdr.th_ack, tp->t_rtseq)) {
			ps->tcpstat.tcps_rttupdated++;
			if (tp->t_srtt != 0) {
				register short delta;

				/*
				 * srtt is stored as fixed point with 3 bits
				 * after the binary point (i.e., scaled by 8).
				 * The following magic is equivalent
				 * to the smoothing algorithm in rfc793
				 * with an alpha of .875
				 * (srtt = rtt/8 + srtt*7/8 in fixed point).
				 * Adjust t_rtt to origin 0.
				 */
				tp->t_rtt--;
				delta = tp->t_rtt - (tp->t_srtt >> 3);
				if ((tp->t_srtt += delta) <= 0)
					tp->t_srtt = 1;
				/*
				 * We accumulate a smoothed rtt variance
				 * (actually, a smoothed mean difference),
				 * then set the retransmit timer to smoothed
				 * rtt + 2 times the smoothed variance.
				 * rttvar is stored as fixed point
				 * with 2 bits after the binary point
				 * (scaled by 4).  The following is equivalent
				 * to rfc793 smoothing with an alpha of .75
				 * (rttvar = rttvar*3/4 + |delta| / 4).
				 * This replaces rfc793's wired-in beta.
				 */
				if (delta < 0)
					delta = -delta;
				delta -= (tp->t_rttvar >> 2);
				if ((tp->t_rttvar += delta) <= 0)
					tp->t_rttvar = 1;
			} else {
				/*
				 * No rtt measurement yet - use the
				 * unsmoothed rtt.  Set the variance
				 * to half the rtt (so our first
				 * retransmit happens at 2*rtt)
				 */
				tp->t_srtt = tp->t_rtt << 3;
				tp->t_rttvar = tp->t_rtt << 1;
			}
			tp->t_rtt = 0;
			tp->t_rxtshift = 0;
			TCPT_RANGESET(tp->t_rxtcur,
			    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
			    TCPTV_MIN, TCPTV_REXMTMAX);
			DO_TRACE(ps, TCP_EVENT_OTHER9, tp->t_rxtcur, 4, 0);
		}

		/*
		 * If all outstanding data is acked, stop retransmit
		 * timer and remember to restart (more output or persist).
		 * If there is more data to be acked, restart retransmit
		 * timer, using current (possibly backed-off) value.
		 */
		if (tHdr.th_ack == tp->snd_max) {
			tp->t_timer[TCPT_REXMT] = 0;
			needoutput = 1;
		} else if (tp->t_timer[TCPT_PERSIST] == 0)
			tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;


		/* Reno did this:
		 * When new data is acked, open the congestion window.
		 * If the window gives us less than ssthresh packets
		 * in flight, open exponentially (maxseg per packet).
		 * Otherwise open linearly (maxseg per window,
		 * or maxseg^2 / cwnd per packet).
		 *
		 * Vegas modifies it by adding congestion detection/avoidance.
		 * So we may not only not increase the congestion window,
		 * we may even decrease it before losses occur.
		 *
		 * Once per RTT we need to do the congestion avoidance
		 * stuff, and the modified slow-start (only increasing
		 * every other RTT). We need to add a fast path so as not
		 * to do this is only one or two segments in transit
		 * (LAN case)?
		 */
		if (tHdr.th_ack > tp->v_cong_detect_begseq) {
		  int rtt, rttLen, sndEpoch, actual_rate, pred_rate, win;

		  if (tp->v_cong_detect_cntRTT > 0)
		    rtt = tp->v_cong_detect_sumRTT/tp->v_cong_detect_cntRTT;
		  else
		     rtt = currentTime - tp->v_cong_detect_begtime + 1;
		  tp->v_cong_detect_sumRTT = tp->v_cong_detect_cntRTT = 0;
		  rttLen = tp->snd_nxt - tp->v_cong_detect_begseq;

		  /* If there was only one packet in transit, then
		   * update baseRTT.
		   */
		  if (rttLen <= tp->t_maxseg  &&  rtt > 0) {
		    tp->v_cong_detect_baseRtt = rtt;
		    DO_TRACE(ps, TCP_EVENT_OTHER9, rtt, rttLen, tHdr.th_dport);
		  }


		  if (rtt > 0) {

		    /* The following rates are in 100s bytes/sec. This assumes
		     * that the time is given in milliseconds.
		     */
		    actual_rate = rttLen*10/rtt;
		    pred_rate = (tp->snd_nxt - tp->snd_una +
				 MIN(tp->t_maxseg - acked, 0))*10 /
				 tp->v_cong_detect_baseRtt;
		    DO_TRACE(ps, TCP_EVENT_OTHER6, actual_rate/10,
			     pred_rate/10, tHdr.th_dport);

		    /* If we are currently doing slow-start
		     */
		    if (tp->snd_cwnd < tp->snd_ssthresh) {

		      /* Check if we are sending faster than available
			 bandwidth
		       */
		      if ((pred_rate - actual_rate)*tp->v_cong_detect_baseRtt >
			  10*tp->v_exp_inc_nseg*tp->t_maxseg)
			tp->v_exp_inc_isless = 1;
		      else
			tp->v_exp_inc_isless = 0;

		      /* sndEpoch is the interval of time during which
		       * we sent data. During slow-start, we usually
		       * don't send during the whole RTT, only during
		       * part of the beginning.
		       */
		      sndEpoch = tp->v_cong_detect_last_sendtime -
			tp->v_cong_detect_begtime;
		      win = tp->snd_cwnd - tp->t_maxseg;
		      DO_TRACE(ps, TCP_EVENT_OTHER8, sndEpoch, rtt,
			       tHdr.th_dport);

		      /* The following is executed if we are trying to
		       * predict the available bandwidth during slow-start
		       */
		      if (tp->v_cong_detect_predict_do  &&  sndEpoch > 0) {
			if (tp->v_exp_inc_do) {
			  if (tp->v_exp_inc_flag) {
			    if (tp->snd_cwnd >= 8*tp->t_maxseg) {
			      tp->snd_ssthresh = (win*rtt)/(2*sndEpoch);
			      tp->v_cong_detect_predict_do = 0;
			    }
			  }
			  else {
			    if (tp->snd_cwnd >= 4*tp->t_maxseg) {
			      tp->snd_ssthresh = (win*rtt)/(sndEpoch);
			      tp->v_cong_detect_predict_do = 0;
			    }
			  }
			}
			else if (tp->snd_cwnd >= 8*tp->t_maxseg) {
			  tp->snd_ssthresh = (win*rtt)/(2*sndEpoch);
			  tp->v_cong_detect_predict_do = 0;
			}
			if (tp->snd_ssthresh <= tp->snd_cwnd)
			  tp->snd_ssthresh = 2*tp->t_maxseg;
		      }
		      tp->v_exp_inc_flag = !tp->v_exp_inc_flag;
		      DO_TRACE(ps, TCP_EVENT_OTHER5, tp->v_exp_inc_isless,
			       tp->v_exp_inc_flag, tHdr.th_dport);
		    }

		    /* Check if we are sending too slowly (using less than
		     * top_nseg buffers
		     */
		    if ((pred_rate - actual_rate)*tp->v_cong_detect_baseRtt >
			10*tp->v_cong_detect_top_nseg*tp->t_maxseg)
		      tp->v_cong_detect_top_isless = 1;
		    else
		      tp->v_cong_detect_top_isless = 0;

		    /* Check if we are sending to fast (using more than
		     * bot_nseg worth of buffers
		     */
		    if ((pred_rate - actual_rate)*tp->v_cong_detect_baseRtt >
			10*tp->v_cong_detect_bot_nseg*tp->t_maxseg)
		      tp->v_cong_detect_bot_isless = 1;
		    else
		      tp->v_cong_detect_bot_isless = 0;

		  } /* rtt > 0 */

		  tp->v_cong_detect_begseq = tp->snd_nxt;
		  tp->v_cong_detect_begtime = currentTime;
		  DO_TRACE(ps, TCP_EVENT_OTHER5, tp->v_cong_detect_bot_isless,
			   tp->v_cong_detect_top_isless, tHdr.th_dport);


		  /* This next section decides by how much to increase
		   * or decrease the congestion window when each ACK is
		   * received. In Reno, it is increased by maxseg during
		   * slow-start and by maxseg*(maxseg/cwnd) otherwise.
		   *
		   * In Vegas, the congestion avoidance mechanism (when
		   * active) decides by how much. If it is active during
		   * slow-start, then the increases only happen during
		   * every other RTT, and then the increase is maxseg,
		   * as long as we have not overran the available bw
		   * (exp_inc_isless == 0).
		   * If we are not doing slow-start right now,
		   * then if we need to send faster (top_isless == 0)
		   * we increase it by maxseg*(maxseg/cwnd), if we
		   * need to send slower, then we decrease cwnd by
		   * maxseg immediately and we don't change the cwnd
		   * during the next RTT.
		   */

		  if (tp->snd_cwnd < tp->snd_ssthresh) {
		    /* Doing slow-start right now */
		    if (tp->v_exp_inc_do) {
		    /* Doing congestion avoidance during slow-start */
		      if (!tp->v_exp_inc_flag)
			/* Not increasing during this RTT */
			tp->v_incr = 0;
		      else if (tp->v_exp_inc_isless) {
			/* Going faster than available bw, so slow down */
			tp->snd_ssthresh = 2*tp->t_maxseg;
			tp->snd_cwnd -= (tp->snd_cwnd >> 3);
			tp->v_incr = 0;
		      }
		      else
			/* Increase by one maxseg with each ACK */
			tp->v_incr = tp->t_maxseg;
		    }
		    else {
		      /* Not doing congestion avoidance during slow-start */
		      tp->v_incr = tp->t_maxseg;
		    }
		  } /* end of doing slow-start right now */

		  else {
		    /* not doing slow-start right now */
		    if (tp->v_cong_detect_do) {
		      /* Doing congestion detection/avoidance */
		      if (tp->v_cong_detect_bot_isless) {
			/* Going too fast, so slow down */
			tp->snd_cwnd -= tp->t_maxseg;
			if (tp->snd_cwnd < 2*tp->t_maxseg)
			  tp->snd_cwnd = 2*tp->t_maxseg;
			tp->v_incr = 0;
		      }
		      else if (tp->v_cong_detect_top_isless)
			/* The current rate is fine */
			tp->v_incr = 0;
		      else
			/* We can go faster */
			tp->v_incr = MAX(((int)tp->t_maxseg)*tp->t_maxseg /
					   tp->snd_cwnd, 1);
		    }
		    else
		      /* Not doing congestion detection/avoidance */
		      tp->v_incr = MAX(((int)tp->t_maxseg)*tp->t_maxseg /
					 tp->snd_cwnd, 1);
		  } /* end of not doing slow-start right now */

		} /* End of code done once per RTT */


		/* Since we set how much to increase only once per RTT,
		 * we need to check during slow-start if we have
		 * surpassed sstthresh before the RTT period is over.
		 */
		if (tp->v_incr == tp->t_maxseg &&
		    tp->snd_cwnd >= tp->snd_ssthresh)
		  tp->v_incr = 0;

		xTrace4(tcpp, TR_MAJOR_EVENTS,
		      "vtcp_input: congestion window=%d (MIN(%d+%d,65535<<%d))",
			tp->snd_cwnd + tp->v_incr, tp->snd_cwnd,
			tp->v_incr, tp->snd_scale);

		/* Increase congestion window unless we haven't been able
		 * to keep up with the congestion window.
		 */
		if (tp->v_incr > 0 &&
		    (tp->snd_cwnd - (tp->snd_nxt - tp->snd_una)) <=
		    2*tp->t_maxseg)
		  tp->snd_cwnd = MIN(tp->snd_cwnd + tp->v_incr,
				     TCP_MAXWIN<<tp->snd_scale);

		/* sbdrop will drop all acked bytes from the send buffer.
		 * sendTime is set to the time the last acked segment
		 * was sent, transmits to the largest number of times
		 * an acked segment was sent.
		 */
		if (acked > sblength(tcpst->snd)) {
			tp->snd_wnd -= sblength(tcpst->snd);
                        sbdrop(tcpst->snd, sblength(tcpst->snd), &sendTime,
                               &transmits);
			ourfinisacked = 1;
		} else {
                        sbdrop(tcpst->snd, acked, &sendTime, &transmits);
			tp->snd_wnd -= acked;
			ourfinisacked = 0;
		}

		/* Do Vegas' RTT stuff. Note that Vegas ACKs every packet.
		 * If running against a TCP which doesn't ACK every packet,
		 * it may be a good idea to change sbdrop so sendTime
		 * returns the time of the earliest segment sent. I'm not
		 * sure if it is really needed, as Vegas only checks for
		 * timeouts when ACKs are received (usually duplicate ACKs).
		 */
                if (( sendTime != 0) && (transmits == 1)) {
		  int rtt, n;

		  rtt = currentTime - sendTime + 1;
		  tp->v_cong_detect_sumRTT += rtt;
		  tp->v_cong_detect_cntRTT++;
		  if (rtt > 0) {
		    tp->v_rtt = rtt;

		    /* The following is used fpr spike prevention */
		    tp->v_spike_timeInc = rtt*tp->t_maxseg/(tp->snd_cwnd+1);

		    if (tp->v_rtt < tp->v_cong_detect_baseRtt)
		      tp->v_cong_detect_baseRtt = tp->v_rtt;

		    n = tp->v_rtt - (tp->v_sa >> 3);
		    tp->v_sa += n;
		    if (n <0) n = -n;
		    n -= (tp->v_sd >> 2);
		    tp->v_sd += n;

		    tp->v_timeout = (((tp->v_sa >> 2) + tp->v_sd) >> 1);
		    /* Since we use more accurate time, we need to make
		       it a little bigger */
		    tp->v_timeout += (tp->v_timeout >> 4);

		    DO_TRACE(ps, TCP_EVENT_SET_TO, tp->v_timeout,
			   tp->v_rtt, tHdr.th_dport);
		  }
		} /* End of Vegas' RTT stuff */

		if (tcpst->waiting.waitCount) {
		  tcpSemVAll(&tcpst->waiting);
		}

#if 0
		if ((so->so_snd.sb_flags & SB_WAIT) || so->so_snd.sb_sel)
			sowwakeup(so);
#endif
		tp->snd_una = tHdr.th_ack;
		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
			tp->snd_nxt = tp->snd_una;

		/* If this is the first or second ACK after a retransmit,
		 * check for timed out segments (Vegas).
		 */
                if (tp->v_worried > 0) {
                        tp->v_worried--;

			/* Check if any segments have expired. If so, we
			 * will retransmit one segment but there is no need
			 * to change the congestion window since we already
			 * did it.
			 */
                        len = sbexpire(tcpst->snd, currentTime-tp->v_timeout,
                                       tp->t_maxseg, &transmits, &sendTime);
                        if (len) {
			  tcp_seq old_next=tp->snd_nxt;
			  u_long  old_cwnd=tp->snd_cwnd;

			  ps->tcpstat.tcps_worryftimeo++;
			  DO_TRACE(ps, TCP_EVENT_WSND, len, tp->v_worried,
				   tHdr.th_dport);
			  tp->t_dupacks = tp->t_rexmtthresh;
			  tp->snd_nxt = tHdr.th_ack;
			  tp->snd_cwnd = tp->t_maxseg;
			  (void) vtcp_output(tp);
			  if (SEQ_GT(old_next, tp->snd_nxt))
			    tp->snd_nxt = old_next;
			  tp->snd_cwnd = old_cwnd;
                        }
                        else
			  tp->v_worried = 0;
                }

		switch (tp->t_state) {

		/*
		 * In FIN_WAIT_1 STATE in addition to the processing
		 * for the ESTABLISHED state if our FIN is now acknowledged
		 * then enter FIN_WAIT_2.
		 */
		case TCPS_FIN_WAIT_1:
			if (ourfinisacked) {
				/*
				 * If we can't receive any more
				 * data, then closing user can proceed.
				 * Starting the timer is contrary to the
				 * specification, but if we don't get a FIN
				 * we'll hang forever.
				 */
				if (CANTRCVMORE(so)) {
					soisdisconnected(so);
					tp->t_timer[TCPT_2MSL] = TCPTV_MAXIDLE;
				}
				tp->t_state = TCPS_FIN_WAIT_2;
			}
			break;

	 	/*
		 * In CLOSING STATE in addition to the processing for
		 * the ESTABLISHED state if the ACK acknowledges our FIN
		 * then enter the TIME-WAIT state, otherwise ignore
		 * the segment.
		 */
		case TCPS_CLOSING:
			if (ourfinisacked) {
				tp->t_state = TCPS_TIME_WAIT;
				vtcp_canceltimers(tp);
				tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
				soisdisconnected(so);
			}
			break;

		/*
		 * In LAST_ACK, we may still be waiting for data to drain
		 * and/or to be acked, as well as for the ack of our FIN.
		 * If our FIN is now acknowledged, delete the TCB,
		 * enter the closed state and return.
		 */
		case TCPS_LAST_ACK:
			if (ourfinisacked) {
				tp = tcp_destroy(tp);
				goto drop;
			}
			break;

		/*
		 * In TIME_WAIT state the only thing that should arrive
		 * is a retransmission of the remote FIN.  Acknowledge
		 * it and restart the finack timer.
		 */
		case TCPS_TIME_WAIT:
			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
			goto dropafterack;
		}
	}

step6:
	xTrace1(tcpp, 4, "vtcp_input:  step6 on %lx", tp);
	/*
	 * Update window information.
	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
	 */
	if ((tiflags & TH_ACK) &&
	    (SEQ_LT(tp->snd_wl1, tHdr.th_seq) || tp->snd_wl1 == tHdr.th_seq &&
	    (SEQ_LT(tp->snd_wl2, tHdr.th_ack) ||
	     tp->snd_wl2 == tHdr.th_ack && tiwin > tp->snd_wnd))) {
		/* keep track of pure window updates */
		if (tlen == 0 &&
		    tp->snd_wl2 == tHdr.th_ack && tiwin > tp->snd_wnd)
			ps->tcpstat.tcps_rcvwinupd++;
		tp->snd_wnd = tiwin;
		tp->snd_wl1 = tHdr.th_seq;
		tp->snd_wl2 = tHdr.th_ack;
		if (tp->snd_wnd > tp->max_sndwnd)
			tp->max_sndwnd = tp->snd_wnd;
		needoutput = 1;
	}

	/*
	 * Process segments with URG.
	 */
	if ((tiflags & TH_URG) && tHdr.th_urp &&
	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
		/*
		 * This is a kludge, but if we receive and accept
		 * random urgent pointers, we'll crash in
		 * soreceive.  It's hard to imagine someone
		 * actually wanting to send this much urgent data.
		 */
		if (tHdr.th_urp > SB_MAX) {
			tHdr.th_urp = 0;			/* XXX */
			tiflags &= ~TH_URG;		/* XXX */
			goto dodata;			/* XXX */
		}
		/*
		 * If this segment advances the known urgent pointer,
		 * then mark the data stream.  This should not happen
		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
		 * a FIN has been received from the remote side.
		 * In these states we ignore the URG.
		 *
		 * According to RFC961 (Assigned Protocols),
		 * the urgent pointer points to the last octet
		 * of urgent data.  We continue, however,
		 * to consider it to indicate the first octet
		 * of data past the urgent section
		 * as the original spec states.
		 */
		if (SEQ_GT(tHdr.th_seq+tHdr.th_urp, tp->rcv_up)) {
		    tp->rcv_up = tHdr.th_seq + tHdr.th_urp;
		    sohasoutofband(so,
				   (tcpst->rcv_hiwat - tcpst->rcv_space) +
				   (tp->rcv_up - tp->rcv_nxt) - 1);
			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
		}
		/*
		 * Remove out of band data so doesn't get presented to user.
		 * This can happen independent of advancing the URG pointer,
		 * but if two URG's are pending at once, some out-of-band
		 * data may creep in... ick.
		 */
		if (tHdr.th_urp <= tlen &&
		    (tcpst->flags & TCPST_OOBINLINE) == 0)
		  tcp_pulloutofband(so, &tHdr, m);
	} else
		/*
		 * If no out of band data is expected,
		 * pull receive urgent pointer along
		 * with the receive window.
		 */
		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
			tp->rcv_up = tp->rcv_nxt;
dodata:							/* XXX */
	xTrace1(tcpp, 4, "vtcp_input:  do data on %lx", (u_long)tp);
	/*
	 * Process the segment text, merging it into the TCP sequencing queue,
	 * and arranging for acknowledgment of receipt if necessary.
	 * This process logically involves adjusting tp->rcv_wnd as data
	 * is presented to the user (this happens in tcp_usrreq.c,
	 * case PRU_RCVD).  If a FIN has already been received on this
	 * connection then we just ignore the text.
	 */
	if ((tlen || (tiflags&TH_FIN)) &&
	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
		xTrace1(tcpp, 5,
			"Calling macro reassemble with msg len %d",
			msgLength(m));
		if (ps->delack) {
		  TCP_REASS_DELACK(tp, &tHdr, so, m, &demuxmsg, tiflags);
		} else {
		  TCP_REASS_ACKNOW(tp, &tHdr, so, m, &demuxmsg, tiflags);
		}
		xTrace1(tcpp, 5,
			"after reassembly demux msg has length %d",
			msgLength(m));
		/*
		 * Pass received message to user:
		 */
		{
		    int mlen = msgLength(&demuxmsg);
		    if (mlen != 0) {
			tcpst->rcv_space -= mlen;
			xPop(so, transport_s, &demuxmsg, (void *)0);
		    } /* if */
		    msgDestroy(&demuxmsg);
		    demuxmsgDestroyed = 1;
		}
		if (ps->delack)
			tp->t_flags |= TF_DELACK;
		/*
		 * The following else causes every packet to be acked
		 * twice, once on receipt and again when the buffer is
		 * freed, causing a window update. DOGN.
		 */
		/*
		else
			tp->t_flags |= TF_ACKNOW;
		*/
		/*
		 * Note the amount of data that peer has sent into
		 * our window, in order to estimate the sender's
		 * buffer size.
		 */
		len = tcpst->rcv_hiwat - (tp->rcv_adv - tp->rcv_nxt);
		if (len > tp->max_rcvd)
			tp->max_rcvd = len;
	} else {
		tiflags &= ~TH_FIN;
	}

	/*
	 * If FIN is received ACK the FIN and let the user know
	 * that the connection is closing.
	 */
	if (tiflags & TH_FIN) {
		xTrace1(tcpp, 4, "vtcp_input:  got fin on %lx", (u_long)tp);

		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
		    invoke_cantrcvmore = TRUE;
		    tp->t_flags |= TF_ACKNOW;
		    tp->rcv_nxt++;
		}
		switch (tp->t_state) {

	 	/*
		 * In SYN_RECEIVED and ESTABLISHED STATES
		 * enter the CLOSE_WAIT state.
		 */
		case TCPS_SYN_RECEIVED:
		case TCPS_ESTABLISHED:
			tp->t_state = TCPS_CLOSE_WAIT;
			break;

	 	/*
		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
		 * enter the CLOSING state.
		 */
		case TCPS_FIN_WAIT_1:
			tp->t_state = TCPS_CLOSING;
			break;

	 	/*
		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
		 * starting the time-wait timer, turning off the other
		 * standard timers.
		 */
		case TCPS_FIN_WAIT_2:
			tp->t_state = TCPS_TIME_WAIT;
			vtcp_canceltimers(tp);
			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
			soisdisconnected(so);
			break;

		/*
		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
		 */
		case TCPS_TIME_WAIT:
			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
			break;
		}
	}
	xIfTrace(tcpp, 2)
		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);

	/*
	 * Return any desired output.
	 */
	if (needoutput || (tp->t_flags & TF_ACKNOW)) {
		(void) vtcp_output(tp);
	}

	if (invoke_cantrcvmore) {
	    socantrcvmore(so);
	} /* if */
        if (!demuxmsgDestroyed)
          msgDestroy(&demuxmsg);
	return XK_SUCCESS;

dropafterack:
	xTrace1(tcpp, 4, "vtcp_input:  drop after ack %lx", (u_long)tp);
	DO_TRACE(ps, TCP_EVENT_DROPAA, tiflags, 0, 0);
	/*
	 * Generate an ACK dropping incoming segment if it occupies
	 * sequence space, where the ACK reflects our state.
	 */
	if (tiflags & TH_RST)
		goto drop;
	tp->t_flags |= TF_ACKNOW;
	(void) vtcp_output(tp);
	msgDestroy(&demuxmsg);
	return XK_SUCCESS;

dropwithreset:
	xTrace1(tcpp, 4, "vtcp_input:  drop with reset on %lx", (u_long)tp);
	DO_TRACE(ps, TCP_EVENT_DROPWR, tiflags, 0, 0);
	if (options) {
		(void) xFree(options);
		options = 0;
	}
	/*
	 * Generate a RST, dropping incoming segment.
	 * Make ACK acceptable to originator of segment.
	 * Don't bother to respond if destination was broadcast.
	 */
	if ((tiflags & TH_RST) || in_broadcast(*(struct in_addr *)&pHdr->dst))
		goto drop;
	{
		IPpseudoHdr	tmpPhdr;

		tmpPhdr.src = pHdr->dst;
		tmpPhdr.dst = pHdr->src;
		tmpPhdr.zero = 0;
		tmpPhdr.prot = pHdr->prot;
		if (tiflags & TH_ACK)
		  	tcp_respond(self, tp, &tHdr, &tmpPhdr, tHdr.th_ack,
				    (tcp_seq)0, TH_RST);
		else {
			if (tiflags & TH_SYN)
			  	tlen++;
			tcp_respond(self, tp, &tHdr, &tmpPhdr,
				    tHdr.th_seq + tlen,
				    (tcp_seq)0, TH_RST|TH_ACK);
		}
	}
	/* destroy temporarily created socket */
	if (dropsocket)
	  	soabort(so);
	msgDestroy(&demuxmsg);
	return XK_SUCCESS;

drop:
	xTrace1(tcpp, 4, "vtcp_input:  drop on %lx", (u_long)tp);
	DO_TRACE(ps, TCP_EVENT_DROP, tiflags, 0, 0);
	if (options) {
		xFree(options);
		options = 0;
	}
	/*
	 * Drop space held by incoming segment and return.
	 */
	xIfTrace(tcpp, 2)
		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
	/* destroy temporarily created socket */
	if (dropsocket)
		soabort(so);
	msgDestroy(&demuxmsg);
	return XK_SUCCESS;
}


static void
tcp_dooptions(ps, tp, options, option_len, tHdr)
  	PSTATE *ps;
	struct tcpcb *tp;
	char         *options;
	int	      option_len;
	struct tcphdr *tHdr;
{
	register u_char *cp;
	int opt, optlen, cnt;

	cp = (u_char *)options;
	cnt = option_len;
	for (; cnt > 0; cnt -= optlen, cp += optlen) {
		opt = cp[0];
		if (opt == TCPOPT_EOL)
			break;
		if (opt == TCPOPT_NOP)
			optlen = 1;
		else {
			optlen = cp[1];
			if (optlen <= 0)
				break;
		}
		switch (opt) {

		default:
			continue;

		case TCPOPT_MAXSEG:
			if (optlen != 4)
				continue;
			if (!(tHdr->th_flags & TH_SYN))
				continue;
			tp->t_maxseg = *(u_short *)(cp + 2);
			tp->t_maxseg = ntohs((u_short)tp->t_maxseg);
			DO_TRACE(ps, TCP_EVENT_OTHER9, tp->t_maxseg, 0, 0);
			tp->t_maxseg = MIN(tp->t_maxseg, tcp_mss(tp));
			break;

		case TCPOPT_WINDOW:
                        if (optlen != TCPOLEN_WINDOW)
                                continue;
                        if (!(tHdr->th_flags & TH_SYN))
                                continue;
                        tp->t_flags |= TF_RCVD_SCALE;
                        tp->requested_s_scale = MIN(cp[2], TCP_MAX_WINSHIFT);
                        DO_TRACE(ps, TCP_EVENT_OTHER9,
                                 tp->requested_s_scale, 2, 0);
                        break;

		}
	}
	xFree(options);
}


/*
 * Pull out of band byte out of a segment so
 * it doesn't appear in the user's data queue.
 * It is still reflected in the segment length for
 * sequencing purposes.
 */
static void
tcp_pulloutofband(so, th, m)
	Sessn so;
	struct tcphdr *th;
	Msg *m;
{
	Msg firstPart;
	struct tcpcb *tp = sototcpcb(so);
	int cnt = th->th_urp - 1;
        int  dataLen;
        MsgWalk mi;
        u_char *data;

	tp->t_oobflags |= TCPOOB_HAVEDATA;

	msgConstructEmpty(&firstPart);
	msgBreak(m, &firstPart, cnt);

        msgWalkInit(&mi, m);
        if ((data = msgWalkNext(&mi, &dataLen)) != 0) {
          xAssert(dataLen >= 1);
          tp->t_iobc = *(char *)data;
        }
        msgWalkDone(&mi);

	msgDiscard(m, 1);
	msgJoin(m, &firstPart, m);
	msgDestroy(&firstPart);
}

/*
#ifdef XNETSIM
extern int TcpPacket;
#endif
*/

/*
 *  Determine a reasonable value for maxseg size.
 *  If the route is known, use one that can be handled
 *  on the given interface without forcing IP to fragment.
 *  If bigger than an mbuf cluster (MCLBYTES), round down to nearest size
 *  to utilize large mbufs.
 *  If interface pointer is unavailable, or the destination isn't local,
 *  use a conservative size (512 or the default IP max size, but no more
 *  than the mtu of the interface through which we route),
 *  as we can't discover anything about intervening gateways or networks.
 *  We also initialize the congestion/slow start window to be a single
 *  segment if the destination isn't local; this information should
 *  probably all be saved with the routing entry at the transport level.
 *
 *  This is ugly, and doesn't belong at this level, but has to happen somehow.
 */
int
tcp_mss(tp)
	register struct tcpcb *tp;
{
    	Sessn tcpSessn;
	int mss;

	tcpSessn = tcpcbtoso(tp);
	if (xControlSessn(xGetSessnDown(tcpSessn, 0), GETOPTPACKET,
		     (char *)&mss, sizeof(int)) < sizeof(int)) {
	    xTrace0(tcpp, 3, "tcp_mss: GETOPTPACKET control of lls failed");
	    mss = 512;
	}
/*
#ifdef XNETSIM
        if (TcpPacket > 0)
          mss = TcpPacket + sizeof(struct tcphdr);
#endif
*/
	xTrace1(tcpp, 3, "tcp_mss: GETOPTPACKET control of lls returned %d",
		mss);
	mss -= sizeof(struct tcphdr);
        tp->snd_cwnd = tp->t_slowstart * mss;
	return (mss);
}


void
print_reass(tp, m)
    struct tcpcb *tp;
    char *m;
{
	struct reass *s;
	printf("Printing reass\n");
	printf("%s %x:", m, tp->rcv_nxt);
	for (s = tp->seg_next; s != (struct reass *)tp; s = s->next) {
		printf("[%x-%x) ", s->th.th_seq, msgLength(&s->m));
	}
	printf("\n");
}
