/* -*-	Mode:C++; c-basic-offset:8; tab-width:8; indent-tabs-mode:t -*- */
/*
 * Copyright (c) 1994 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 Computer Systems
 *	Engineering Group at Lawrence Berkeley Laboratory.
 * 4. Neither the name of the University nor of the Laboratory 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.
 */

#ifndef lint
static const char rcsid[] =
    "@(#) $Header: /usr/local/cvsroot/ns2/queue/drop-tail.cc,v 1.3 2003/12/28 13:18:13 rkx Exp $ (LBL)";
#endif

#include "delay.h"
#include "flags.h"
#include "drop-tail.h"

static class DropTailClass : public TclClass {
 public:
	DropTailClass() : TclClass("Queue/DropTail") {}
	TclObject* create(int, const char*const*) {
		return (new DropTail);
	}
} class_drop_tail;

static class CWDropTailClass : public TclClass {
 public:
	CWDropTailClass() : TclClass("Queue/CWDT") {}
	TclObject* create(int, const char*const*) {
		return (new CWDropTail);
	}
} class_cw_drop_tail;


void DropTail::reset()
{
	ave_ = 0.0;
	curq_ = 0;
	dropped_ = 0;
	arrived_ = 0;
        if(link_)
		ptc_ = link_->bandwidth() / (8. * mean_pktsize_);
	idle_ = 1;
	if (&Scheduler::instance() != NULL)
		idletime_ = Scheduler::instance().clock();
	else
		idletime_ = 0.0; /* sched not instantiated yet */
	
	Queue::reset();
}

int 
DropTail::command(int argc, const char*const* argv) {

	Tcl& tcl = Tcl::instance();
	if (argc==2) {
		if (strcmp(argv[1], "printstats") == 0) {
			print_summarystats();
			return (TCL_OK);
		}
	}
	if (argc == 3) {
		if (!strcmp(argv[1], "packetqueue-attach")) {
			delete q_;
			if (!(q_ = (PacketQueue*) TclObject::lookup(argv[2])))
				return (TCL_ERROR);
			else {
				pq_ = q_;
				return (TCL_OK);
			}
		}
		// attach a file for variable tracing
                if (strcmp(argv[1], "attach") == 0) {
                        int mode;
                        const char* id = argv[2];
                        tchan_ = Tcl_GetChannel(tcl.interp(), (char*)id, &mode);
                        if (tchan_ == 0) {
                                tcl.resultf("DropTail: trace: can't attach %s for writing", id);
                                return (TCL_ERROR);
                        }
                        return (TCL_OK);
                }
		/* rkx */
		if(strcmp(argv[1], "q-weight") == 0) {
			double tmp = atof(argv[2]);
			if(tmp < 0.0 || tmp > 1.0) {
				tcl.resultf("DropTail: q-weight %g out of range", tmp);
				return TCL_ERROR;
			}
			q_w_ = tmp;
			return TCL_OK;
		}
		if(strcmp(argv[1], "mean-pktsize") == 0) {
			int tmp = atoi(argv[2]);
			if(tmp <= 0.0) {
				tcl.resultf("DropTail: mean-pktsize %d out of range", tmp);
				return TCL_ERROR;
			}
			mean_pktsize_ = tmp;
			return TCL_OK;
		}
		if(strcmp(argv[1], "idle-pktsize") == 0) {
			int tmp = atoi(argv[2]);
			if(tmp <= 0.0) {
				tcl.resultf("DropTail: idle-pktsize %d out of range", tmp);
				return TCL_ERROR;
			}
			idle_pktsize_ = tmp;
			return TCL_OK;
		}
		if (strcmp(argv[1], "link") == 0) {
			LinkDelay* del = (LinkDelay*)TclObject::lookup(argv[2]);
			if (del == 0) {
				tcl.resultf("DropTail: no LinkDelay object %s",
					argv[2]);
				return(TCL_ERROR);
			}
			// set ptc now
			link_ = del;
			ptc_ = link_->bandwidth() / (8. * mean_pktsize_);
			return (TCL_OK);
		}

	}
	return Queue::command(argc, argv);
}

/*
 * drop-tail
 */
void DropTail::enque(Packet* p)
{
	arrived_++;

	int qlen = qib_? q_->byteLength() : q_->length();

	if (summarystats) {
                Queue::updateStats(qlen);
	}
	curq_ = qlen;   // trace current Q length upon arrival
	/* rkx */
	int m = 0;
	if (idle_) {
		double now = Scheduler::instance().clock();
		/* To account for the period when the queue was empty. */
		idle_ = 0;
		double ptc = ptc_ * mean_pktsize_ / idle_pktsize_;
                m = int(ptc * (now - idletime_));
	}
	
	ave_  = estimator(qlen, m+1);   // trace average Q length upon arrival
	int qlimBytes = qlim_ * mean_pktsize_;
	if ((!qib_ && (q_->length() + 1) >= qlim_) ||
  	(qib_ && (q_->byteLength() + hdr_cmn::access(p)->size()) >= qlimBytes)){
		// if the queue would overflow if we added this packet...
		if (drop_front_) { /* remove from head of queue */
			q_->enque(p);
			Packet *pp = q_->deque();
			drop(pp);
		} else {
			drop(p);
		}
		dropped_++;
	} else {
		q_->enque(p);
	}
}

Packet* DropTail::deque()
{
	Packet* p;
        if (summarystats && &Scheduler::instance() != NULL) {
                Queue::updateStats(qib_?q_->byteLength():q_->length());
        }
	p = q_->deque();
	if (p != 0) {
		idle_ = 0;
	} else {
		idle_ = 1;
		// deque() may invoked by Queue::reset at init
		// time (before the scheduler is instantiated).
		// deal with this case
		if (&Scheduler::instance() != NULL)
			idletime_ = Scheduler::instance().clock();
		else
			idletime_ = 0.0;
	}
	return p;
}

void DropTail::print_summarystats()
{
	//double now = Scheduler::instance().clock();
        printf("True average queue: %5.3f", true_ave_);
        if (qib_)
                printf(" (in bytes)");
        printf(" time: %5.3f\n", total_time_);
}

void
DropTail::trace(TracedVar* v)
{
        char wrk[500], *p;

        if ((p = strstr(v->name(), "curq")) == NULL && 
	    (p = strstr(v->name(), "ave")) == NULL ) {
                fprintf(stderr, "DropTail:unknown trace var %s\n",
                        v->name());
                return;
        }

        if (tchan_) {
                int n;
                double t = Scheduler::instance().clock();
                // XXX: be compatible with nsv1 RED trace entries
                if (strstr(v->name(), "curq") != NULL) {
                        sprintf(wrk, "Q %g %d", t, int(*((TracedInt*) v)));
                } else {
                        sprintf(wrk, "%c %g %g", *p, t,
                                double(*((TracedDouble*) v)));
                }
                n = strlen(wrk);
                wrk[n] = '\n';
                wrk[n+1] = 0;
                (void)Tcl_Write(tchan_, wrk, n+1);
        }
        return;
}

double
DropTail::estimator(int nqueued, int m)
{
	double old_ave, new_ave;

	old_ave = ave_;
	while(--m >= 1)
		old_ave *= 1.0 - q_w_;
	old_ave *= 1.0 - q_w_;
	new_ave = old_ave + q_w_ * nqueued;
	return new_ave;
}

CWDropTail::CWDropTail() : thresh_(0), cwmark_(1), marked_(0)
{
	bind_bool("cwmark_", &cwmark_);
	bind("thresh_", &thresh_);
	bind("dropped_", &dropped_);
	bind("marked_", &marked_);
	bind("arrived_", &arrived_);
	bind("passed_", &passed_);
}


void
CWDropTail::enque(Packet* p)
{
	int qlen = qib_? q_->byteLength() : q_->length();

	hdr_flags* hf = hdr_flags::access(p);

	int cw_drop = 0;

	if(thresh_ == 0) {
		thresh_ = (qib_ ? qlim_ * mean_pktsize_ : qlim_) / 2;
		if(thresh_ == 0)
			thresh_ = 1;
	}

	if (summarystats) {
                Queue::updateStats(qlen);
	}
	curq_ = qlen;   // trace current Q length upon arrival
	++arrived_;

	/* rkx */
	int m = 0;
	if (idle_) {
		double now = Scheduler::instance().clock();
		/* To account for the period when the queue was empty. */
		idle_ = 0;
		double ptc = ptc_ * mean_pktsize_ / idle_pktsize_;
                m = int(ptc * (now - idletime_));
	}
	
	ave_  = estimator(qlen, m+1);   // trace average Q length upon arrival
	
	if(int(ave_) >= thresh_) {	// average queue length crossed the CW threshold
		if(!cwmark_ || !hf->ect()) {
			cw_drop = 1;
		} else {
			hf->ce() = 1;
			marked_++;
			cw_drop = 0;
		}
	}

	int qlimBytes = qlim_ * mean_pktsize_;
	if (cw_drop || (!qib_ && (q_->length() + 1) >= qlim_) ||
  	(qib_ && (q_->byteLength() + hdr_cmn::access(p)->size()) >= qlimBytes)){
		// if the queue would overflow if we added this packet...
		if (drop_front_) { /* remove from head of queue */
			q_->enque(p);
			Packet *pp = q_->deque();
			drop(pp);
		} else {
			drop(p);
		}
		dropped_++;
	} else {
		q_->enque(p);
		++passed_;
	}
}

