/*
 * btcp_input.c
 *
 * Derived from:
 *
 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)tcp_input.c	8.5 (Berkeley) 4/10/94
 *
 * 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:34:24 $
 */

#ifndef TUBA_INCLUDE
#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"
#include "btcp.h"

#define CANTRCVMORE(so) (sototcpst(so)->closed & 2)
#undef IN_MULTICAST
#define IN_MULTICAST(i)	(((i).a & 0xf0) == 0xe0)

extern int      Btcp_rcv_size;
extern int	PrintBadChksum;

static int	tcpcksum = 1;
static int	tcprexmtthresh = 3;
static struct	tcpiphdr tcp_saveti;

/* struct	inpcb *tcp_last_inpcb = &tcb; */

/* extern u_long sb_max; */

#endif /* TUBA_INCLUDE */
#define TCP_PAWS_IDLE	(24 * 24 * 60 * 60 * PR_SLOWHZ)

/* for modulo comparisons of timestamps */
#define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
#define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)

#ifdef __STDC__

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

#else

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

#endif

#ifdef XMEMTRACK

extern int BtcpTrackId;

extern char *xMallocTrack(unsigned, int);
extern char *xMallocZeroTrack(unsigned, int);
extern void xFreeTrack(char *, unsigned, int);

#define xMalloc(s)     xMallocTrack(s, BtcpTrackId)
#define xMallocZero(s) xMallocZeroTrack(s, BtcpTrackId)

#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
 */
#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; \
}
#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; \
	} \
}


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

#ifndef TUBA_INCLUDE


/*
 * TCP input routine, follows pages 65-76 of the
 * protocol specification dated September, 1981 very closely.
 */
XkReturn
btcp_input(self, transport_s, m)
  	Protl self;
	Sessn transport_s;
  	Msg *m;
{
/* 	register struct tcpiphdr *ti; */
	register struct inpcb *inp;
	int  option_buf[8];
	char *options = NULL;
	int option_len = 0;
	int len, tlen, off;
	register struct tcpcb *tp = 0;
	register int tiflags;
/* 	struct socket *so; */
	Sessn so = 0;
	Protl hlp = 0, hlpType = 0;
	struct tcpstate *tcpst;
	int todrop, acked, ourfinisacked, needoutput = 0;
	short ostate;
/* 	struct in_addr laddr; */
	int dropsocket = 0;
	int iss = 0;
	int dummy1, dummy2;
 	u_long tiwin, ts_val, ts_ecr; 
        int  iv;
 	int ts_present = 0; 
	Msg demuxmsg;
	struct tcphdr 	tHdr;
	IPpseudoHdr 	*pHdr;
	bool invoke_cantrcvmore = FALSE;
	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);
	/*
	 * 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
	 */

	/* ACB: Added cast to pHdr, to eliminate warning */
        check_sum = inCkSum(m, (u_short *) pHdr, sizeof(IPpseudoHdr));
        buffer = msgPop(m, sizeof(tHdr));
        if (! buffer) {
		xTrace0(tcpp, 3, 
			"btcp_input: msgPop of header failed -- dropping");
		return XK_FAILURE;
	}
        tcpHdrLoad(&tHdr, buffer, sizeof(tHdr), m);
	msgSetAttr(m, 0, 0, 0);

	xTrace4(tcpp, 3, "btcp_input seq %d, dlen %d, f( %s ) to port (%d)",
	       tHdr.th_seq, msgLength(m), tcpFlagStr(tHdr.th_flags),
	       tHdr.th_dport);
	DO_TRACE(ps, TCP_EVENT_IN, tcpGetTime(), msgLength(m), 
		 GET_TIDHR(tHdr));
	DO_TRACE(ps, TCP_EVENT_DATA, tHdr.th_seq, tHdr.th_win>>4,
		 GET_TIDHR(tHdr));
	DO_TRACE(ps, TCP_EVENT_DATA, tHdr.th_ack, tHdr.th_flags,
		 GET_TIDHR(tHdr));
 	msgConstructEmpty(&demuxmsg); 

	/*
	 * Check the checksum value (calculated in tcpHdrLoad)
	 */
	if (tcpcksum) {
	  	if (check_sum) {
			xTrace1(tcpp, TR_ERRORS,
				"btcp_input: bad checksum (%x)", tHdr.th_sum);
			if (PrintBadChksum) printf("Bad checksum\n");
			ps->tcpstat.tcps_rcvbadsum++;
			DO_TRACE(ps, TCP_EVENT_BADSUM, 0, 0, GET_TIDHR(tHdr));
			goto drop;
		}
	}

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

#endif /* TUBA_INCLUDE */

	/*
	 * 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++;
		goto drop;
	}
	tiflags = tHdr.th_flags;

	tlen -= off;
	if ((option_len = off - sizeof (struct tcphdr)) > 0) {
	  xTrace1(tcpp, 3, "btcp_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,
				"btcp_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, GET_TIDHR(tHdr));
                if (option_len > 32)
		  options = xMalloc(option_len);
                else
		  options = (char *)option_buf;
                 
                buffer = msgPop(m, option_len);
                xAssert(buffer);
                tcpOptionsLoad(options, buffer, option_len, 0);

		/* 
		 * Do quick retrieval of timestamp options ("options
		 * prediction?").  If timestamp is the only option and it's
		 * formatted as recommended in RFC 1323 appendix A, we
		 * quickly get the values now and not bother calling
		 * tcp_dooptions(), etc.
		 */
                bcopy(options, (char *)&iv, sizeof(int));
		if ((option_len == TCPOLEN_TSTAMP_APPA ||
		     (option_len > TCPOLEN_TSTAMP_APPA &&
			options[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
		     iv == htonl(TCPOPT_TSTAMP_HDR) &&
		     (tiflags & TH_SYN) == 0) {
			ts_present = 1;
			ts_val = ntohl(*(u_long *)(options + 4));
			ts_ecr = ntohl(*(u_long *)(options + 8));
		  	DO_TRACE(ps, TCP_EVENT_OTHER9, ts_ecr, 1,
				 GET_TIDHR(tHdr));
			/* ACB: Added cast to option_buf */
			if (options != (char *)option_buf)
#ifdef XMEMTRACK
			  xFreeTrack(options,(unsigned)option_len, BtcpTrackId);
#else
			  xFree(options);
#endif
			options = NULL;	/* we've parsed the options */
		}
	}

	/*
	 * 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");
	    hlp = 0;
	    so = 0;
	    inp = 0;
	    tp = 0;
	  } else {
	    hlp = e->hlp;
	    hlpType = e->hlpType;
            Btcp_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, "btcp_input:  no so");
		goto dropwithreset;
	}
	if (xIsProtl(hlp)) {
		so = btcp_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;
/* #if BSD>=43 */
/* 		inp->inp_options = ip_srcroute(); */
/* #endif */
		/* 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;
	}
	tcpst = sototcpst(so);
	if (inp == 0) {
		xTrace0(tcpp, 2, "btcp_input:  no inp");
		goto dropwithreset;
	}
	if (tp == 0) {
		xTrace0(tcpp, 2, "btcp_input:  no tp");
		goto dropwithreset;
	}
	if (tp->t_state == TCPS_CLOSED) {
		xTrace0(tcpp, 2, "btcp_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] = tcp_keepidle; */
	tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;

	/*
	 * 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,
			&ts_present, &ts_val, &ts_ecr);
	  /* ACB: Added cast to option_buf */
          if (options != (char *)option_buf)
#ifdef XMEMTRACK
            xFreeTrack(options, (unsigned)option_len, BtcpTrackId);
#else
	    xFree(options);
#endif
        }
	/* LSB should we set options=0 as in previous implementations? */

	DO_TRACE(ps, TCP_EVENT_IN0, tp->rcv_nxt, tp->t_state, tcpst->tid);
	/* 
	 * Header prediction: check for the two common cases
	 * of a uni-directional data xfer.  If the packet has
	 * no control flags, is in-sequence, the window didn't
	 * change and we're not retransmitting, it's a
	 * candidate.  If the length is zero and the ack moved
	 * forward, we're the sender side of the xfer.  Just
	 * free the data acked & wake any higher level process
	 * that was blocked waiting for space.  If the length
	 * is non-zero and the ack didn't move, we're the
	 * receiver side.  If we're getting packets in-order
	 * (the reassembly queue is empty), add the data to
	 * the socket buffer and note that we need a delayed ack.
	 */
	if (tp->t_state == TCPS_ESTABLISHED &&
	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
	    (!ts_present || TSTMP_GEQ(ts_val, tp->ts_recent)) &&
	    tHdr.th_seq == tp->rcv_nxt &&
	    tiwin && tiwin == tp->snd_wnd &&
	    tp->snd_nxt == tp->snd_max) {

		/* 
		 * If last ACK falls within this segment's sequence numbers,
		 *  record the timestamp.
		 */
		if (ts_present && SEQ_LEQ(tHdr.th_seq, tp->last_ack_sent) &&
		   SEQ_LT(tp->last_ack_sent, tHdr.th_seq + tlen)) {
			tp->ts_recent_age = ps->tcp_now;
			tp->ts_recent = ts_val;
		}

		if (tlen == 0) {
			if (SEQ_GT(tHdr.th_ack, tp->snd_una) &&
			    SEQ_LEQ(tHdr.th_ack, tp->snd_max) &&
			    tp->snd_cwnd >= tp->snd_wnd 
#ifdef FIX_1
			    && tp->t_dupacks < tcprexmtthresh
#endif
                            )
 			    { 
				/*
				 * this is a pure ack for outstanding data.
				 */
			  	DO_TRACE(ps, TCP_EVENT_OTHER9, 1, 5,
					 tcpst->tid);
				++ps->tcpstat.tcps_predack;
				if (ts_present)
					tcp_xmit_timer(tp, ps->tcp_now-ts_ecr+1, ps);
				else if (tp->t_rtt &&
					    SEQ_GT(tHdr.th_ack, tp->t_rtseq))
					tcp_xmit_timer(tp, tp->t_rtt, ps);
				acked = tHdr.th_ack - tp->snd_una;
				ps->tcpstat.tcps_rcvackpack++;
				ps->tcpstat.tcps_rcvackbyte += acked;
				sbdrop(tcpst->snd, acked, &dummy1, &dummy2);
				tp->snd_una = tHdr.th_ack;
/* 				m_freem(m); */

				/*
				 * If all outstanding data are acked, stop
				 * retransmit timer, otherwise restart timer
				 * using current (possibly backed-off) value.
				 * If process is waiting for space,
				 * wakeup/selwakeup/signal.  If data
				 * are ready to send, let tcp_output
				 * decide between more output or persist.
				 */
				if (tp->snd_una == tp->snd_max)
					tp->t_timer[TCPT_REXMT] = 0;
				else if (tp->t_timer[TCPT_PERSIST] == 0)
					tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;

				if (tcpst->waiting.waitCount) {
				  tcpSemVAll(&tcpst->waiting);
				}
                                if (sblength(tcpst->snd) > 0)
                                        (void) btcp_output(tp);
				
				return XK_SUCCESS;
			}
		} else if (tHdr.th_ack == tp->snd_una &&
		    tp->seg_next == (struct reass *)tp &&
		    tlen <= tcpst->rcv_space) {
			/*
			 * this is a pure, in-sequence data packet
			 * with nothing on the reassembly queue and
			 * we have enough buffer space to take it.
			 */
			++ps->tcpstat.tcps_preddat;
			DO_TRACE(ps, TCP_EVENT_OTHER9, 2, 5, tcpst->tid);
			tp->rcv_nxt += tlen;
			ps->tcpstat.tcps_rcvpack++;
			ps->tcpstat.tcps_rcvbyte += tlen;
			/*
			 * Drop TCP, IP headers and TCP options then add data
			 * to socket buffer.
			 */
/* 			sbappend(&so->so_rcv, m); */
/* 			sorwakeup(so); */
			if (tp->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;
			*/
			tcpst->rcv_space -= tlen;
			xPop(so, transport_s, m, 0);
			return XK_SUCCESS;
		}
	}

	/*
	 * 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, "btcp_input: tcpcb %lx switch %s", (u_long)tp,
		tcpstates[tp->t_state]);

	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;
		/*
		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
		 * in_broadcast() should never return true on a received
		 * packet with M_BCAST not set.
		 */
/* 		if (m->m_flags & (M_BCAST|M_MCAST) || 
   LSB flags set by ether input (see if_ethersubr.c) */

		if (in_broadcast(*(struct in_addr *)&pHdr->dst))
/*	          IN_MULTICAST(*(struct in_addr *)&pHdr->dst)) LSB should I?*/
			goto drop;

		xTrace0(tcpp, 3, "btcp_input: LISTEN");
		tp->t_template = btcp_template(tp);
		if (tp->t_template == 0) {
			tp = btcp_drop(tp, ENOBUFS);
			dropsocket = 0;		/* socket is already gone */
			goto drop;
		}
		if (options) {
			tcp_dooptions(ps, tp, options, option_len, &tHdr,
				&ts_present, &ts_val, &ts_ecr);
			/* ACB: Added cast to option_buf */
        	  	if (options != (char *)option_buf)
#ifdef XMEMTRACK
          		  xFreeTrack(options,(unsigned)option_len, BtcpTrackId);
#else
			  xFree(options);
#endif
                }
		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);
		tcp_rcvseqinit(tp);
		tp->t_flags |= TF_ACKNOW;
		tp->t_state = TCPS_SYN_RECEIVED;
		tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
		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 = btcp_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;
		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
			ps->tcpstat.tcps_connects++;
			soisconnected(so);
			tp->t_state = TCPS_ESTABLISHED;
			/* Do window scaling on this connection? */
			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;
			}
			/* LSB bsd code doesn't have this */
			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)
				tcp_xmit_timer(tp, tp->t_rtt, ps);
		} 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;
			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 timestamp, if present.
	 * Then 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.
	 * 
	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
	 * and it's less than ts_recent, drop it.
	 */
	if (ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
	    TSTMP_LT(ts_val, tp->ts_recent)) {

		/* Check to see if ts_recent is over 24 days old.  */
		if ((int)(ps->tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
			/*
			 * Invalidate ts_recent.  If this segment updates
			 * ts_recent, the age will be reset later and ts_recent
			 * will get a valid value.  If it does not, setting
			 * ts_recent to zero will at least satisfy the
			 * requirement that zero be placed in the timestamp
			 * echo reply when ts_recent isn't valid.  The
			 * age isn't reset until we get a valid ts_recent
			 * because we don't want out-of-order segments to be
			 * dropped when ts_recent is old.
			 */
			tp->ts_recent = 0;
		} else {
			ps->tcpstat.tcps_rcvduppack++;
			ps->tcpstat.tcps_rcvdupbyte += tlen;
			ps->tcpstat.tcps_pawsdrop++;
			goto dropafterack;
		}
	}

	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--;
		}
		/* LSB next test changes from previous versions! */
		if (todrop >= tlen) {
			ps->tcpstat.tcps_rcvduppack++;
			ps->tcpstat.tcps_rcvdupbyte += tlen;
			/*
			 * If segment is just one to the left of the window,
			 * check two special cases:
			 * 1. Don't toss RST in response to 4.2-style keepalive.
			 * 2. If the only thing to drop is a FIN, we can drop
			 *    it, but check the ACK or we will get into FIN
			 *    wars if our FINs crossed (both CLOSING).
			 * In either case, send ACK to resynchronize,
			 * but keep on processing for RST or ACK.
			 */
			if ((tiflags & TH_FIN && todrop == tlen + 1)
#ifdef TCP_COMPAT_42
			  || (tiflags & TH_RST && tHdr.th_seq == tp->rcv_nxt - 1)
#endif
			   ) {
				todrop = tlen;
				tiflags &= ~TH_FIN;
				tp->t_flags |= TF_ACKNOW;
			} else {
				/*
				 * Handle the case when a bound socket connects
				 * to itself. Allow packets with a SYN and
				 * an ACK to continue with the processing.
				 */
				if (todrop != 0 || (tiflags & TH_ACK) == 0)
					goto dropafterack;
			}
		} 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 are 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 = btcp_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;
				tp = btcp_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);
	}

	/*
	 * If last ACK falls within this segment's sequence numbers,
	 * record its timestamp.
	 */
	if (ts_present && SEQ_LEQ(tHdr.th_seq, tp->last_ack_sent) &&
	    SEQ_LT(tp->last_ack_sent, tHdr.th_seq + tlen +
		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
		tp->ts_recent_age = ps->tcp_now;
		tp->ts_recent = ts_val;
	}

	/*
	 * 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 = btcp_drop(tp, ECONNREFUSED);
		goto drop;

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

	case TCPS_CLOSING:
	case TCPS_LAST_ACK:
	case TCPS_TIME_WAIT:
		tp = btcp_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 = btcp_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;
		}
		/* LSB should I add: tp->t_maxseg = MIN(... */
		(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 (other than
				 * 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 if (++tp->t_dupacks == tcprexmtthresh) {
					tcp_seq onxt = tp->snd_nxt;
					u_int win =
					    MIN(tp->snd_wnd, tp->snd_cwnd) / 2/
						tp->t_maxseg;

					if (win < 2)
						win = 2;
					tp->snd_ssthresh = win * tp->t_maxseg;
					tp->t_timer[TCPT_REXMT] = 0;
					tp->t_rtt = 0;
					tp->snd_nxt = tHdr.th_ack;
					tp->snd_cwnd = tp->t_maxseg;
					(void) btcp_output(tp);
					tp->snd_cwnd = tp->snd_ssthresh +
					       tp->t_maxseg * tp->t_dupacks;
					if (SEQ_GT(onxt, tp->snd_nxt))
						tp->snd_nxt = onxt;
					goto drop;
				} else if (tp->t_dupacks > tcprexmtthresh) {
				  	tp->snd_cwnd += tp->t_maxseg;
					(void) btcp_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.
		 */
#ifdef FIX_0
		if (tp->t_dupacks >= tcprexmtthresh &&
#else
		if (tp->t_dupacks > tcprexmtthresh &&
#endif
		    tp->snd_cwnd > tp->snd_ssthresh)
			tp->snd_cwnd = tp->snd_ssthresh;
		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 we have a timestamp reply, update smoothed
		 * round trip time.  If no timestamp is present but
		 * 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 (ts_present)
			tcp_xmit_timer(tp, ps->tcp_now-ts_ecr+1, ps);
		else if (tp->t_rtt && SEQ_GT(tHdr.th_ack, tp->t_rtseq))
			tcp_xmit_timer(tp,tp->t_rtt, ps);

		/*
		 * 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;
		/*
		 * 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
		 * (maxseg^2 / cwnd per packet), plus a constant
		 * fraction of a packet (maxseg/8) to help larger windows
		 * open quickly enough.
		 */
		/* LSB: may need to get rid of maxseg/8 part! */
		{
		u_int cw = tp->snd_cwnd;
		u_int incr = tp->t_maxseg;

/* #define FIX_8 */
#define FIX_9
		if (cw > tp->snd_ssthresh)
#ifdef FIX_8
                        incr = incr / (cw / incr)
#else
			incr = incr * incr / cw 
#endif
#ifndef FIX_4
			       + incr / 8
#endif
		        ;
#ifdef FIX_9
		else if ( (!tp->delack)&&(cw > tp->t_maxseg) )
		  /*
		   * If using immediate acks, try increasing the slow start
		   * window as if used delayed acks, that is, only every
		   * other acknowlegment.
		   */
		    incr = (incr+1)/2;
#endif
                xTrace4(tcpp, TR_EVENTS,
		      "btcp_input: congestion window=%x (MIN(%x+%x,65535<<%d))",
                        cw + incr, cw, incr, tp->snd_scale);
		tp->snd_cwnd = MIN(cw + incr, TCP_MAXWIN<<tp->snd_scale);
		/*
		if ( strcmp(self->instName,"client")==0) printf(
		    "btcp_input: congestion window=%d (MIN(%d+%d,%d<<%d))\n",
                        tp->snd_cwnd, cw, incr, TCP_MAXWIN, tp->snd_scale);
		*/
		}
		if (acked > sblength(tcpst->snd)) {
			tp->snd_wnd -= sblength(tcpst->snd);
			sbdrop(tcpst->snd, sblength(tcpst->snd), &dummy1, 
			       &dummy2);
			ourfinisacked = 1;
		} else {
			sbdrop(tcpst->snd, acked, &dummy1, &dummy2);
			tp->snd_wnd -= acked;
			ourfinisacked = 0;
		}
		if (tcpst->waiting.waitCount) {
		  tcpSemVAll(&tcpst->waiting);
		}
#if 0
		if (so->so_snd.sb_flags & SB_NOTIFY)
			sowwakeup(so);
#endif
		tp->snd_una = tHdr.th_ack;
		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
			tp->snd_nxt = tp->snd_una;


		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]=ps->tcp_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;
				btcp_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 = btcp_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, "btcp_input:  step6 on %lx", (u_long)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;
	}

#ifdef FIX_6
	if (acked >= 3*tp->t_maxseg  &&  
	    (tp->snd_cwnd - (tp->snd_nxt - tp->snd_una)) > 3*tp->t_maxseg) {
	  if (tp->snd_cwnd > tp->snd_ssthresh)
	    tp->snd_ssthresh = tp->snd_cwnd;
	  tp->snd_cwnd = (tp->snd_nxt - tp->snd_una) + 3*tp->t_maxseg;
	}
#endif

	/*
	 * 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 (in one of two places).
		 */
		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
/* #ifdef SO_OOBINLINE <LSB> */
		    && (tcpst->flags & TCPST_OOBINLINE) == 0 
/* #endif */
		     )
			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, "btcp_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 (tp->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) {
                        if ( ! (tcpst->flags & TCPST_RCV_ACK_ALWAYS) ) {
                            tcpst->rcv_space -= mlen;
                        }
                        xPop(so, transport_s, &demuxmsg, 0);
                    } /* if */
                    msgDestroy(&demuxmsg);
                }       
                        
		/*
		 * 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);
	} 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, "btcp_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;
			btcp_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) btcp_output(tp);

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


dropafterack:
	xTrace1(tcpp, 4, "btcp_input:  drop after ack %lx", (u_long)tp);
	DO_TRACE(ps, TCP_EVENT_DROPAA, tiflags, 0, tcpst->tid);
	/*
	 * 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) btcp_output(tp);
	return XK_SUCCESS;

dropwithreset:
	xTrace1(tcpp, 4, "btcp_input:  drop with reset on %lx", (u_long)tp);
	DO_TRACE(ps, TCP_EVENT_DROPWR, tiflags, 0, tcpst->tid);
	/* ACB: Added cast to option_buf */
	if (options != (char *)option_buf) {
#ifdef XMEMTRACK
	  (void) xFreeTrack(options, (unsigned)option_len, BtcpTrackId);
#else
	  (void)xFree(options);
#endif
	  options = 0;
	}
	/*
	 * Generate a RST, dropping incoming segment.
	 * Make ACK acceptable to originator of segment.
	 * Don't bother to respond if destination was broadcast/multicast.
	 */
	if ((tiflags & TH_RST) || in_broadcast(*(struct in_addr *)&pHdr->dst)
/* 	    m->m_flags & (M_BCAST|M_MCAST) || */
	    || IN_MULTICAST(pHdr->src))
		goto drop;
        {     
                IPpseudoHdr     tmpPhdr;

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

drop:
	xTrace1(tcpp, 4, "btcp_input:  drop on %lx", (u_long)tp);
	DO_TRACE(ps, TCP_EVENT_DROP, tiflags, 0, tcpst->tid);
	/* ACB: Added cast to option_buf */
	if (options != (char *)option_buf) {
#ifdef XMEMTRACK
		xFreeTrack(options, (unsigned)option_len, BtcpTrackId);
#else
		xFree(options);
#endif
		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)
		(void) soabort(so);
	msgDestroy(&demuxmsg);
	return XK_SUCCESS;
#ifndef TUBA_INCLUDE
}

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

	tcpst = tcpcbtoso(tp)->state;
	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 != TCPOLEN_MAXSEG)
				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,
				 tcpst->tid);
                        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, tcpst->tid);
			break;

		case TCPOPT_TIMESTAMP:
			if (optlen != TCPOLEN_TIMESTAMP)
				continue;
			*ts_present = 1;
			bcopy((char *)cp + 2, (char *) ts_val, sizeof(*ts_val));
			ntohl(*ts_val);
			bcopy((char *)cp + 6, (char *) ts_ecr, sizeof(*ts_ecr));
			DO_TRACE(ps, TCP_EVENT_OTHER9, *ts_ecr, 1, tcpst->tid);
			ntohl(*ts_ecr);

			/* 
			 * A timestamp received in a SYN makes
			 * it ok to send timestamp requests and replies.
			 */
			if (tHdr->th_flags & TH_SYN) {
				tp->t_flags |= TF_RCVD_TSTMP;
				tp->ts_recent = *ts_val;
				tp->ts_recent_age = ps->tcp_now;
				DO_TRACE(ps, TCP_EVENT_OTHER9, 
					 3333, 1, tcpst->tid);

			}
			break;
		}
	}
}


/*
 * 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);
}


/*
 * Collect new round-trip time estimate
 * and update averages and current timeout.
 */
static void
tcp_xmit_timer(tp, rtt, ps)
	register struct tcpcb *tp;
	short rtt;
  	PSTATE *ps;
{
	register short delta;

	ps->tcpstat.tcps_rttupdated++;
	if (tp->t_srtt != 0) {
		/*
		 * 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 rtt to origin 0.
		 */
#ifdef FIX_2
                delta = ( (rtt-1) << 2 ) - ( tp->t_srtt >> 3 );
#else
 	        delta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);   
#endif
		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 + 4 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;
#ifdef FIX_2
                delta -= (tp->t_rttvar >> 2);
#else
   		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);   
#endif
  		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 3*rtt).
		 */
		tp->t_srtt = rtt << TCP_RTT_SHIFT;
		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
	}
	tp->t_rtt = 0;
	tp->t_rxtshift = 0;

	/*
	 * the retransmit should happen at rtt + 4 * rttvar.
	 * Because of the way we do the smoothing, srtt and rttvar
	 * will each average +1/2 tick of bias.  When we compute
	 * the retransmit timer, we want 1/2 tick of rounding and
	 * 1 extra tick because of +-1/2 tick uncertainty in the
	 * firing of the timer.  The bias will give us exactly the
	 * 1.5 tick we need.  But, because the bias is
	 * statistical, we have to test that we don't drop below
	 * the minimum feasible timer (which is 2 ticks).
	 */
#ifdef FIX_2
        TCPT_RANGESET(tp->t_rxtcur,
                      ( ((tp)->t_srtt >> 3) + (tp)->t_rttvar ) >> 2,
                      rtt+1, TCPTV_REXMTMAX);
#else
  	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),  
 		      tp->t_rttmin, TCPTV_REXMTMAX);  
#endif
	DO_TRACE(ps, TCP_EVENT_OTHER9, 
		 tp->t_rxtcur | (rtt << 8) | (tp->t_srtt << 16) |
		 (tp->t_rttvar << 24), 
		 4, ((struct tcpstate *)tcpcbtoso(tp)->state)->tid);
	
	/*
	 * We received an ack for a packet that wasn't retransmitted;
	 * it is probably safe to discard any error indications we've
	 * received recently.  This isn't quite right, but close enough
	 * for now (a route might have failed after we sent a segment,
	 * and the return path might not be symmetrical).
	 */
	tp->t_softerror = 0;
}

#ifndef XNETSIM

/*
 * Determine a reasonable value for maxseg size.
 * If the route is known, check route for mtu.
 * If none, use an mss that can be handled on the outgoing
 * interface without forcing IP to fragment; if bigger than
 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
 * to utilize large mbufs.  If no route is found, route has no mtu,
 * or the destination isn't local, use a default, hopefully conservative
 * size (usually 512 or the default IP max size, but no more than the mtu
 * of the interface), 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.
 * While looking at the routing entry, we also initialize other path-dependent
 * parameters from pre-set or cached values in the routing entry.
 */

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

int
tcp_mss(tp, /* offer */)
	register struct tcpcb *tp;
/* 	u_int offer; */
{
  /* LSB: major mods to BSD code! */
        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);
}       


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, "rtcp_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);
#ifdef XMEMTRACK
		xFreeTrack((char *) q, sizeof(struct reass), BtcpTrackId);
#else
		xFree((char *)q);
#endif
		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);
#ifdef XMEMTRACK
		xFreeTrack((char *)q, sizeof(struct reass), BtcpTrackId);
#else
		xFree((char *)q);
#endif
		q = next;
		th = &q->th;
	} while (q != (struct reass *)tp && th->th_seq == tp->rcv_nxt);
	return (flags);
}


#endif /* TUBA_INCLUDE */
#endif /* XNETSIM */
