nse.patch 117 KB
Newer Older
1
--- dist-ns-allinone-2.26/ns-2.26/trace/cmu-trace.cc	Wed Feb 26 15:11:29 2003
2
+++ ns-allinone-2.26/ns-2.26/trace/cmu-trace.cc	Fri Nov 28 16:55:25 2003
3 4 5 6 7 8 9 10 11 12
@@ -941,6 +941,8 @@
 		case PT_GAF:
 		case PT_PING:
 			break;
+		case PT_LIVE:
+			break;
 		default:
 			fprintf(stderr, "%s - invalid packet type (%s).\n",
 				__PRETTY_FUNCTION__, packet_info.name(ch->ptype()));
--- dist-ns-allinone-2.26/ns-2.26/tools/random.cc	Wed Feb 26 15:11:28 2003
13
+++ ns-allinone-2.26/ns-2.26/tools/random.cc	Fri Nov 28 16:55:25 2003
14 15 16
@@ -47,11 +47,13 @@
 #define GCC_THROW
 #endif
17
 
18 19 20 21 22 23 24 25
+#if 0
 RANDOM_RETURN_TYPE
 random() GCC_THROW
 {
 	printf("random() called in ns.\nRandom is not portable, please use Random::uniform() instead.\n");
 	abort();
 }
+#endif
26
 
27 28
 #endif /* !WIN32 */
--- dist-ns-allinone-2.26/ns-2.26/tcp/tcp-full.cc	Wed Feb 26 15:11:24 2003
29
+++ ns-allinone-2.26/ns-2.26/tcp/tcp-full.cc	Fri Nov 28 16:55:25 2003
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
@@ -76,7 +76,7 @@
  *
  * Some warnings and comments:
  *	this version of TCP will not work correctly if the sequence number
- *	goes above 2147483648 due to sequence number wrap
+ *	goes above 1073741824 due to sequence number wrap
  *
  *	this version of TCP by default sends data at the beginning of a
  *	connection in the "typical" way... That is,
@@ -360,16 +360,16 @@
 	case TCPS_CLOSED:
 	case TCPS_LISTEN:
                 reset();
-                curseq_ = iss_ + nb;
+                INCR_SEQ( curseq_, SEQ_ADD(iss_, nb));
                 connect();              // initiate new connection
 		break;
 
 	case TCPS_ESTABLISHED:
 	case TCPS_SYN_SENT:
 	case TCPS_SYN_RECEIVED:
-                if (curseq_ < iss_) 
+	        if (SEQ_LT(curseq_, iss_) ) 
                         curseq_ = iss_; 
-                curseq_ += nb;
+                INCR_SEQ(curseq_, nb);
 		break;
 
 	default:
@@ -454,7 +454,7 @@
 void
 FullTcpAgent::usrclosed()
 {
-	curseq_ = maxseq_ - 1;	// now, no more data
+	curseq_ = SEQ_SUB(maxseq_, 1);	// now, no more data
 	infinite_send_ = FALSE;	// stop infinite send
 
 	switch (state_) {
@@ -736,7 +736,7 @@
 int
 FullTcpAgent::rcvseqinit(int seq, int dlen)
 {
-	return (seq + dlen + 1);
+	return (SEQ_ADD(seq, dlen + 1));
 }
 
 /*
@@ -764,8 +764,8 @@
 FullTcpAgent::pack(Packet *pkt)
 {
 	hdr_tcp *tcph = hdr_tcp::access(pkt);
-	return (tcph->ackno() >= highest_ack_ &&
-		tcph->ackno() < recover_);
+	return (SEQ_GE(tcph->ackno(), highest_ack_) &&
+		SEQ_LT(tcph->ackno(), recover_));
 }
 
 /*
@@ -822,6 +822,9 @@
         tcph->hlen() = tcpip_base_hdr_size_;
 	tcph->hlen() += build_options(tcph);
 
+	/* Fill in maxseg_ for MSS negotiation in TCPTap (NSE) */
+	tcph->maxseg() = maxseg_;
+	
 	/*
 	 * Explicit Congestion Notification (ECN) related:
 	 * Bits in header:
@@ -930,24 +933,24 @@
 	else
 		size_ =  maxseg_ + headersize();
 
-	int is_retransmit = (seqno < maxseq_);
+	int is_retransmit = SEQ_LT(seqno, maxseq_);
 	int quiet = (highest_ack_ == maxseq_);
 	int pflags = outflags();
 	int syn = (seqno == iss_);
 	int emptying_buffer = FALSE;
 	int buffered_bytes = (infinite_send_) ? TCP_MAXSEQ :
-				curseq_ - highest_ack_ + 1;
+				SEQ_ADD( SEQ_SUB(curseq_, highest_ack_), 1);
 
 	int win = window() * maxseg_;	// window (in bytes)
-	int off = seqno - highest_ack_;	// offset of seg in window
+	int off = SEQ_SUB(seqno, highest_ack_);	// offset of seg in window
 	int datalen;
 	//int amtsent = 0;
 
 	// be careful if we have not received any ACK yet
 	if (highest_ack_ < 0) {
 		if (!infinite_send_)
-			buffered_bytes = curseq_ - iss_;;
-		off = seqno - iss_;
+			buffered_bytes = SEQ_SUB(curseq_, iss_);
+		off = SEQ_SUB(seqno, iss_);
 	}
 
 	if (syn && !data_on_syn_)
@@ -989,7 +992,7 @@
 	// a dataless SYN packet counts also
 	//
 
-	if (!infinite_send_ && ((seqno + datalen) > curseq_ || 
+	if (!infinite_send_ && (SEQ_GT( SEQ_ADD(seqno, datalen), curseq_) || 
 	    (syn && datalen == 0))) {
 		emptying_buffer = TRUE;
 		//
@@ -1106,15 +1109,15 @@
 	 * around until we actually send a segment
 	 */
 
-	int reliable = datalen + syn + fin; // seq #'s reliably sent
+	int reliable = SEQ_ADD(datalen, syn + fin); // seq #'s reliably sent
 	if (cong_action_ && reliable > 0)
 		cong_action_ = FALSE;
 
 	// highest: greatest sequence number sent + 1
 	//	and adjusted for SYNs and FINs which use up one number
 
-	int highest = seqno + reliable;
-	if (highest > maxseq_) {
+	int highest = SEQ_ADD(seqno, reliable);
+	if (SEQ_GT(highest, maxseq_)) {
 		maxseq_ = highest;
 		//
 		// if we are using conventional RTT estimation,
@@ -1207,10 +1210,11 @@
         int win = window() * maxseg_;
         int topwin = curseq_; // 1 seq number past the last byte we can send
 
-        if ((topwin > highest_ack_ + win) || infinite_send_)
-                topwin = highest_ack_ + win; 
+	int hiack_plus_win = SEQ_ADD(highest_ack_, win);
+        if (SEQ_GT(topwin, hiack_plus_win) || infinite_send_)
+                INCR_SEQ( topwin, hiack_plus_win); 
 
-	return (seq < topwin);
+	return (SEQ_LT(seq, topwin));
 }
 /*
  * Process an ACK
@@ -1231,7 +1235,7 @@
 	hdr_tcp *tcph = hdr_tcp::access(pkt);
173
 
174 175 176
 	register int ackno = tcph->ackno();
-	int progress = (ackno > highest_ack_);
+	int progress = SEQ_GT(ackno, highest_ack_);
177
 
178 179 180 181 182
 	if (ackno == maxseq_) {
 		cancel_rtx_timer();	// all data ACKd
@@ -1250,7 +1254,7 @@
 	// update t_seqno_ here, otherwise we would be doing
 	// go-back-n.
183
 
184 185 186
-	if (t_seqno_ < highest_ack_)
+	if (SEQ_LT(t_seqno_, highest_ack_))
 		t_seqno_ = highest_ack_; // seq# to send next
187
 
188 189 190 191 192 193 194 195 196 197 198 199 200
         /*
@@ -1266,7 +1270,7 @@
 			recent_age_ = now();
 			recent_ = tcph->ts();
 			rtt_update(now() - tcph->ts_echo());
-		} else if (rtt_active_ && ackno > rtt_seq_) {
+		} else if (rtt_active_ && SEQ_GT(ackno,rtt_seq_)) {
 			// got an RTT sample, record it
 			// "t_backoff_ = 1;" deleted by T. Kelly.
 			rtt_active_ = FALSE;
@@ -1368,10 +1372,10 @@
 	if (flags_ & TF_ACKNOW)
 		return TRUE;
201
 
202 203 204 205 206 207 208
-	int spa = (spa_thresh_ > 0 && ((rcv_nxt_ - irs_)  < spa_thresh_)) ?
+	int spa = (spa_thresh_ > 0 && (SEQ_SUB(rcv_nxt_,irs_)  < spa_thresh_)) ?
 		1 : segs_per_ack_;
 		
-	return ((rcv_nxt_ - last_ack_sent_) >= (spa * maxseg_));
+	return (SEQ_SUB(rcv_nxt_, last_ack_sent_) >= (spa * maxseg_));
 }
209
 
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
 /*
@@ -1510,7 +1514,7 @@
 		 * See RFC1323 (now RFC1323 bis)
                  */
                 if (ts_option_ && !fh->no_ts_ &&
-		    tcph->seqno() <= last_ack_sent_) {
+		    SEQ_LE(tcph->seqno(), last_ack_sent_)) {
 			/*
 			 * this is the case where the ts value is newer than
 			 * the last one we've seen, and the seq # is the one
@@ -1548,7 +1552,7 @@
 			// If we are in fast
 			// recovery, go below so we can remember to deflate
 			// the window if we need to
-			if (ackno > highest_ack_ && ackno < maxseq_ &&
+			if (SEQ_GT(ackno, highest_ack_) && SEQ_LT(ackno, maxseq_) &&
 			    cwnd_ >= wnd_ && !fastrecov_) {
 				newack(pkt);	// update timers,  highest_ack_
 				send_much(0, REASON_NORMAL, maxburst_);
@@ -1566,7 +1570,7 @@
 			//	this routine scans all tcpcb's looking for
 			//	DELACK segments and when it finds them
 			//	changes DELACK to ACKNOW and calls tcp_output()
-			rcv_nxt_ += datalen;
+			INCR_SEQ(rcv_nxt_, datalen);
 			flags_ |= TF_DELACK;
 			recvBytes(datalen); // notify application of "delivery"
 			//
@@ -1667,7 +1671,7 @@
239
 
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
 		/* drop if it's a SYN+ACK and the ack field is bad */
 		if ((tiflags & TH_ACK) &&
-			((ackno <= iss_) || (ackno > maxseq_))) {
+			(SEQ_LE(ackno, iss_) || SEQ_GT(ackno, maxseq_))) {
 			// not an ACK for our SYN, discard
 			fprintf(stderr,
 			    "%f: FullTcpAgent::recv(%s): bad ACK for our SYN: ",
@@ -1761,14 +1765,14 @@
 			 * SYN+ACK, so t_seqno_ will have been
 			 * advanced to 2... reduce this
 			 */
-			t_seqno_--;	// CHECKME
+			DECR_SEQ(t_seqno_, 1);	// CHECKME
 		}
 
 trimthenstep6:
 		/*
 		 * advance the seq# to correspond to first data byte
 		 */
-		tcph->seqno()++;
+		INCR_SEQ(tcph->seqno(), 1);
 
 		if (tiflags & TH_ACK)
 			goto process_ACK;
@@ -1838,13 +1842,13 @@
 	// do anything with it.  In particular, would like to
 	// avoid ACKing an incoming FIN+ACK while in CLOSING
 	//
-	todrop = rcv_nxt_ - tcph->seqno();  // how much overlap?
+	todrop = SEQ_SUB(rcv_nxt_, tcph->seqno());  // how much overlap?
 
 	if (todrop > 0 && ((tiflags & (TH_SYN)) || datalen > 0)) {
 //printf("%f(%s): trim 1..todrop:%d, dlen:%d\n",now(), name(), todrop, datalen);
 		if (tiflags & TH_SYN) {
 			tiflags &= ~TH_SYN;
-			tcph->seqno()++;
+			INCR_SEQ(tcph->seqno(), 1);
 			th->size()--;	// XXX Must decrease packet size too!!
 					// Q: Why?.. this is only a SYN
 			todrop--;
@@ -1881,7 +1885,7 @@
 		 * Trim duplicate data from the front of the packet
 		 */
 
-		tcph->seqno() += todrop;
+		INCR_SEQ(tcph->seqno(), todrop);
 		th->size() -= todrop;	// XXX Must decrease size too!!
 					// why? [kf]..prob when put in RQ
 		datalen -= todrop;
@@ -1894,7 +1898,7 @@
 	 * record the timestamp.
 	 * See RFC1323 (now RFC1323 bis)
 	 */
-	if (ts_option_ && !fh->no_ts_ && tcph->seqno() <= last_ack_sent_) {
+	if (ts_option_ && !fh->no_ts_ && SEQ_LE(tcph->seqno(), last_ack_sent_)) {
 		/*
 		 * this is the case where the ts value is newer than
 		 * the last one we've seen, and the seq # is the one we expect
@@ -1925,7 +1929,7 @@
 
 	switch (state_) {
 	case TCPS_SYN_RECEIVED:	/* want ACK for our SYN+ACK */
-		if (ackno < highest_ack_ || ackno > maxseq_) {
+		if (SEQ_LT(ackno, highest_ack_) || SEQ_GT(ackno, maxseq_)) {
 			// not in useful range
 		    	fprintf(stderr,
 		    		"%f: FullTcpAgent(%s): ack(%d) not in range while in SYN_RECEIVED: ",
@@ -1999,13 +2003,13 @@
 		//	try not to be fooled by data
 		//
 
-		if (fastrecov_ && (datalen == 0 || ackno > highest_ack_))
+		if (fastrecov_ && (datalen == 0 || SEQ_GT(ackno, highest_ack_)))
 			pipe_ -= maxseg_;
 
 		// look for dup ACKs (dup ack numbers, no data)
 		//
 		// do fast retransmit/recovery if at/past thresh
-		if (ackno <= highest_ack_) {
+		if (SEQ_LE(ackno, highest_ack_)) {
 			// a pure ACK which doesn't advance highest_ack_
 			if (datalen == 0 && (!dupseg_fix_ || !dupseg)) {
 
@@ -2029,7 +2033,7 @@
                                  */
 
 				if ((rtx_timer_.status() != TIMER_PENDING) ||
-				    ackno < highest_ack_) {
+				    SEQ_LT(ackno, highest_ack_)) {
 					// Q: significance of timer not pending?
 					// ACK below highest_ack_
 					oldack();
@@ -2069,7 +2073,7 @@
 
 process_ACK:
 
-		if (ackno > maxseq_) {
+		if (SEQ_GT(ackno, maxseq_)) {
 			// ack more than we sent(!?)
 			fprintf(stderr,
 			    "%f: FullTcpAgent::recv(%s) too-big ACK (maxseq:%d): ",
@@ -2130,7 +2134,7 @@
 		 * If no data (only SYN) was ACK'd,
 		 *    skip rest of ACK processing.
 		 */
-		if (ackno == (highest_ack_ + 1))
+		if (ackno == SEQ_ADD(highest_ack_, 1))
 			goto step6;
 
 		// if we are delaying initial cwnd growth (probably due to
@@ -2244,7 +2248,7 @@
 			// accept the data here as-is (i.e. don't
 			// require being in ESTABLISHED state)
 			flags_ |= TF_DELACK;
-			rcv_nxt_ += datalen;
+			INCR_SEQ(rcv_nxt_, datalen);
 			tiflags = tcph->flags() & TH_FIN;
 
 			// give to "application" here
@@ -2262,11 +2266,11 @@
 			// Note that we may have just a FIN here (datalen = 0)
 			int rcv_nxt_old_ = rcv_nxt_; // notify app. if changes
 			tiflags = reass(pkt);
-			if (rcv_nxt_ > rcv_nxt_old_) {
+			if (SEQ_GT(rcv_nxt_, rcv_nxt_old_)) {
 				// if rcv_nxt_ has advanced, must have
 				// been a hole fill.  In this case, there
 				// is something to give to application
-				recvBytes(rcv_nxt_ - rcv_nxt_old_);
+				recvBytes(SEQ_SUB(rcv_nxt_, rcv_nxt_old_));
 			}
 			flags_ |= TF_ACKNOW;
372
 
373 374 375 376 377 378 379 380 381 382
@@ -2295,7 +2299,7 @@
 	if (tiflags & TH_FIN) {
 		if (TCPS_HAVERCVDFIN(state_) == 0) {
 			flags_ |= TF_ACKNOW;
- 			rcv_nxt_++;
+ 			INCR_SEQ(rcv_nxt_, 1);
 		}
 		switch (state_) {
                 /*
@@ -2332,7 +2336,7 @@
383
 
384 385 386 387 388 389
 	if (needoutput || (flags_ & TF_ACKNOW))
 		send_much(1, REASON_NORMAL, maxburst_);
-	else if (curseq_ >= highest_ack_ || infinite_send_)
+	else if (SEQ_GE(curseq_, highest_ack_) || infinite_send_)
 		send_much(0, REASON_NORMAL, maxburst_);
 	// K: which state to return to when nothing left?
390
 
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
@@ -2363,9 +2367,9 @@
 	if (tiflags & TH_ACK) {
 		sendpacket(ackno, 0, 0x0, 0, REASON_NORMAL);
 	} else {
-		int ack = tcph->seqno() + datalen;
+		int ack = SEQ_ADD(tcph->seqno(), datalen);
 		if (tiflags & TH_SYN)
-			ack--;
+			DECR_SEQ(ack, 1);
 		sendpacket(0, ack, TH_ACK, 0, REASON_NORMAL);
 	}
 drop:
@@ -2393,7 +2397,7 @@
 FullTcpAgent::dupack_action()
 {   
406
 
407 408
-        int recovered = (highest_ack_ > recover_);
+        int recovered = SEQ_GT(highest_ack_, recover_);
409
 
410 411 412 413 414 415 416 417
 	fastrecov_ = TRUE;
 	rtxbytes_ = 0;
@@ -2579,7 +2583,7 @@
 void
 TahoeFullTcpAgent::dupack_action()
 {  
-        int recovered = (highest_ack_ > recover_);
+        int recovered = SEQ_GT(highest_ack_, recover_);
418
 
419 420 421 422 423
 	fastrecov_ = TRUE;
 	rtxbytes_ = 0;
@@ -2696,11 +2700,11 @@
 SackFullTcpAgent::dupack_action()
 {
424
 
425 426
-        int recovered = (highest_ack_ > recover_);
+        int recovered = SEQ_GT(highest_ack_, recover_);
427
 
428 429 430 431
 	fastrecov_ = TRUE;
 	rtxbytes_ = 0;
-	pipe_ = maxseq_ - highest_ack_ - sq_.total();
+	pipe_ = SEQ_SUB( SEQ_SUB(maxseq_, highest_ack_), sq_.total());
432
 
433 434 435 436
 //printf("%f: SACK DUPACK-ACTION:pipe_:%d, sq-total:%d, bugfix:%d, cwnd:%d, highest_ack:%d, recover_:%d\n",
 //now(), pipe_, sq_.total(), bug_fix_, int(cwnd_), int(highest_ack_), recover_);
@@ -2740,7 +2744,7 @@
 	recover_ = maxseq_;	// where I am when recovery starts
437
 
438 439 440
 	int amt = fast_retransmit(highest_ack_);
-	h_seqno_ = highest_ack_ + amt;
+	h_seqno_ = SEQ_ADD(highest_ack_, amt);
441
 
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
 //printf("%f: FAST-RTX seq:%d, h_seqno_ is now:%d, pipe:%d, cwnd:%d, recover:%d\n",
 //now(), int(highest_ack_), h_seqno_, pipe_, int(cwnd_), recover_);
@@ -2753,12 +2757,12 @@
 void
 SackFullTcpAgent::pack_action(Packet* p)
 {
-	if (!sq_.empty() && sack_min_ < highest_ack_) {
+	if (!sq_.empty() && SEQ_LT(sack_min_, highest_ack_)) {
 		sack_min_ = highest_ack_;
 		sq_.cleartonxt();
 	}
 	pipe_ -= maxseg_;	// see comment in tcp-sack1.cc
-	if (h_seqno_ < highest_ack_)
+	if (SEQ_LT(h_seqno_, highest_ack_))
 		h_seqno_ = highest_ack_;
 }
458
 
459 460 461 462 463 464 465 466 467 468 469
@@ -2768,7 +2772,7 @@
 //printf("%f: EXITING fast recovery, recover:%d\n",
 //now(), recover_);
 	fastrecov_ = pipectrl_ = FALSE;
-        if (!sq_.empty() && sack_min_ < highest_ack_) {
+        if (!sq_.empty() && SEQ_LT(sack_min_, highest_ack_)) {
                 sack_min_ = highest_ack_;
                 sq_.cleartonxt();
         }
@@ -2854,8 +2858,8 @@
 		return (FullTcpAgent::send_allowed(seq));
470
 
471 472 473 474 475 476 477 478 479 480 481
 	// don't overshoot receiver's advertised window
-	int topawin = highest_ack_ + int(wnd_) * maxseg_;
-	if (seq >= topawin) {
+	int topawin = SEQ_ADD(highest_ack_, int(wnd_) * maxseg_);
+	if (SEQ_GE(seq, topawin)) {
 //printf("%f: SEND(%d) NOT ALLOWED DUE TO AWIN:%d, pipe:%d, cwnd:%d\n",
 //now(), seq, topawin, pipe_, int(cwnd_));
 		return FALSE;
@@ -2877,7 +2881,7 @@
 SackFullTcpAgent::nxt_tseq()
 {
482
 
483 484 485
-	int in_recovery = (highest_ack_ < recover_);
+	int in_recovery = SEQ_LT(highest_ack_, recover_);
 	int seq = h_seqno_;
486
 
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
 	if (!in_recovery) {
@@ -2916,13 +2920,13 @@
 			// adjust h_seqno, as we may have
 			// been "jumped ahead" by learning
 			// about a filled hole
-			if (seq > h_seqno_)
+			if (SEQ_GT(seq, h_seqno_))
 				h_seqno_ = seq;
 			return (seq);
 		} else if (fcnt <= 0)
 			break;
 		else {
-			seq += maxseg_;
+			INCR_SEQ(seq, maxseg_);
 		}
 	}
 //if (int(t_seqno_) > 1)
--- dist-ns-allinone-2.26/ns-2.26/tcp/tcp-full.h	Wed Feb 26 15:11:24 2003
505
+++ ns-allinone-2.26/ns-2.26/tcp/tcp-full.h	Fri Nov 28 16:55:25 2003
506 507 508
@@ -104,6 +104,20 @@
 #define PF_TIMEOUT 0x04	    /* protocol defined */
 #define	TCP_PAWS_IDLE	(24 * 24 * 60 * 60)	/* 24 days in secs */
509
 
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
+#define SEQ_LT(a,b)  (((a)<(b) && (b)-(a) < TCP_MAXSEQ/2) || ((a)>(b) && (a)-(b) >= TCP_MAXSEQ/2))
+#define SEQ_LE(a,b)  (((a)<=(b) && (b)-(a) < TCP_MAXSEQ/2) || ((a)>(b) && (a)-(b) >= TCP_MAXSEQ/2))
+#define SEQ_GT(a,b)  (((a)>(b) && (a)-(b) < TCP_MAXSEQ/2) || ((a)<(b) && (b)-(a) >= TCP_MAXSEQ/2))
+#define SEQ_GE(a,b)  (((a)>=(b) && (a)-(b) < TCP_MAXSEQ/2) || ((a)<(b) && (b)-(a) >= TCP_MAXSEQ/2))
+#define INCR_SEQ(num, val) (num) = ((num) + (val)) % TCP_MAXSEQ
+#define SEQ_ADD(num, val) (((num) + (val)) % TCP_MAXSEQ)
+inline int SEQ_SUB(int num, int val) {
+  int ret = num - val;
+    return( abs(ret) < TCP_MAXSEQ/2 ? ret : ((int)(((long long)(num) - (val) + TCP_MAXSEQ) % TCP_MAXSEQ)) );
+}
+#define DECR_SEQ(num, val) (num) = SEQ_SUB((num), (val))
+#define SEQ_MIN(x,y) (SEQ_LT((x),(y))?(x):(y))
+#define SEQ_MAX(x,y) (SEQ_GT((x),(y))?(x):(y))
+
 class FullTcpAgent;
 class DelAckTimer : public TimerHandler {
 public:
@@ -190,9 +204,9 @@
 	}
 	virtual void sent(int seq, int amt) {
 		if (seq == t_seqno_)
-			t_seqno_ += amt;
+			INCR_SEQ(t_seqno_, amt);
 		pipe_ += amt;
-		if (seq < int(maxseq_))
+		if (SEQ_LT(seq, int(maxseq_)))
 			rtxbytes_ += amt;
 	}
 	virtual void oldack() {			// what to do on old ack
--- dist-ns-allinone-2.26/ns-2.26/tcp/tcp.h	Wed Feb 26 15:11:25 2003
540
+++ ns-allinone-2.26/ns-2.26/tcp/tcp.h	Fri Nov 28 16:55:25 2003
541 542 543 544 545 546
@@ -56,6 +56,8 @@
 	int tcp_flags_;         /* TCP flags for FullTcp */
 	int last_rtt_;		/* more recent RTT measurement in ms, */
 				/*   for statistics only */
+        int maxseg_;            /* MSS for TCPTap to negotiate in the SYN segment
+				   needed in NSE */
547
 
548 549 550 551 552 553 554 555
 	static int offset_;	// offset for this header
 	inline static int& offset() { return offset_; }
@@ -75,6 +77,7 @@
 	int& ackno() { return (ackno_); }  
 	int& flags() { return (tcp_flags_); }
 	int& last_rtt() { return (last_rtt_); }
+	int& maxseg() { return (maxseg_); }
 };
556
 
557 558
 /* these are used to mark packets as to why we xmitted them */
--- dist-ns-allinone-2.26/ns-2.26/tcl/lib/ns-address.tcl	Wed Feb 26 15:09:37 2003
559
+++ ns-allinone-2.26/ns-2.26/tcl/lib/ns-address.tcl	Fri Nov 28 16:55:25 2003
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
@@ -162,7 +162,7 @@
 	Simulator set AddressFormat_ HIER
 	Node enable-module "Hier"
 	if [$self multicast?] {
-		$a set-mcastbits 1
+		$a set-mcastbits 3
 	}
 	eval $a set-idbits $hlevel $args
 }
@@ -184,7 +184,7 @@
 	# One bit is set aside for mcast as default :: this waste of 1 bit 
 	# may be avoided, if mcast option is enabled before the initialization
 	# of Simulator.
-	$a set-mcastbits 1
+	$a set-mcastbits 3
 	set lastbit [expr $node - [$a set mcastsize_]]
 	$a set-idbits 1 $lastbit
 }
@@ -269,9 +269,9 @@
 
 AllocAddrBits instproc set-mcastbits {bit_num} {
 	$self instvar size_ mcastsize_
-	if {$bit_num != 1} {
-		error "setmcast : mcastbit > 1"
-	}
+	#if {$bit_num != 1} {
+		#error "setmcast : mcastbit > 1"
+	#}
 	set mcastsize_ $bit_num
 
 	#chk to ensure there;s no change in size
--- dist-ns-allinone-2.26/ns-2.26/tcl/lib/ns-default.tcl	Wed Feb 26 15:09:37 2003
592
+++ ns-allinone-2.26/ns-2.26/tcl/lib/ns-default.tcl	Fri Nov 28 16:55:25 2003
593 594 595 596 597 598 599 600 601 602
@@ -347,6 +347,8 @@
 Classifier set offset_ 0
 Classifier set shift_ 0
 Classifier set mask_ 0xffffffff
+# default IP mask is 255.255.255.0
+Classifier set ipmask_ 0xffffff00
 Classifier set debug_ false
 
 Classifier/Hash set default_ -1; # none
--- dist-ns-allinone-2.26/ns-2.26/tcl/lib/ns-lib.tcl	Wed Feb 26 15:09:37 2003
603
+++ ns-allinone-2.26/ns-2.26/tcl/lib/ns-lib.tcl	Mon Jan 12 00:36:16 2004
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
@@ -1,6 +1,6 @@
 # -*-	Mode:tcl; tcl-indent-level:8; tab-width:8; indent-tabs-mode:t -*-
 #
-# Copyright (c) 1996 Regents of the University of California.
+# Copyright (c) 1996, 2003 Regents of the University of California.
 # All rights reserved.
 # 
 # Redistribution and use in source and binary forms, with or without
@@ -882,6 +882,9 @@
 	# Do all nam-related initialization here
 	$self init-nam
 
+	# XXX netbed specific 
+	#$self add-routes-to-neighbour-ips
+
 	# NIXVECTOR xxx?
 	# global simstart
 	# set simstart [clock seconds]
@@ -1372,8 +1375,8 @@
 	$link_([$n1 id]:[$n2 id]) cost $c
 }
625
 
626 627 628 629 630 631
-Simulator instproc attach-agent { node agent } {
-	$node attach $agent
+Simulator instproc attach-agent { node agent {port ""} } {
+	$node attach $agent $port
 	# $agent set nodeid_ [$node id]
 }
632
 
633
@@ -2045,3 +2048,167 @@
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
 	}
 }
     
+# XXX netbed changes
+Simulator instproc inet-aton ipaddr {
+    set c [regsub -all \\. $ipaddr " " addrlist]
+    if { $c == 0} { 
+        return [expr $ipaddr]
+    }
+    if { [llength $addrlist] != 4} {
+        error "Ill-formatted ip address $ipaddr, addrlistlth = [llength $addrlist]"
+    }
+    if { $c == 3 } {
+        set r 0
+        foreach a $addrlist {
+            if { $a < 0 || $a > 255 } {
+                error "Ill-formatted ip address $ipaddr, a = $a"
+            }
+            set r [expr ($r << 8) + $a]     
+        }
+        return $r
+    } else {
+        error "Ill-formatted ip address $ipaddr, c = $c"
+    }
+}
659
+
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
+# XXX netbed changes
+Simulator instproc inet-ntoa ipaddr {
+    set p1 [expr ($ipaddr >> 24) & 0xff]
+    set p2 [expr ($ipaddr >> 16) & 0xff]
+    set p3 [expr ($ipaddr >>  8) & 0xff]
+    set p4 [expr ($ipaddr >>  0) & 0xff]
+    return [format "%d\.%d\.%d\.%d" $p1 $p2 $p3 $p4]
+}
+
+# XXX netbed changes
+Simulator instproc add-ip { node ip } {
+
+    $self instvar iptonode_
+    $self instvar ipsubnetlist_
+
+    set iptonode_($ip) $node
+    $self cmd add-ip $node $ip
+    
+    set ip_masked [expr [$self inet-aton $ip] & [$self inet-aton "255.255.255.0"]]
+    lappend ipsubnetlist_($ip_masked) $ip
+}
+
+Simulator instproc add-ip-mask-target { ip mask target } {
+    $self instvar iptotarget_
+
+    set ipaton [$self inet-aton $ip]
+    set maskaton [$self inet-aton $mask]
+    set ipmask [$self inet-ntoa [expr $ipaton & $maskaton]]
+    
+    set iptotarget_($ipmask) $target
+}
+
+# XXX netbed changes
+Simulator instproc ip-to-node {ip} {
+    $self instvar iptonode_
+
+    if { [info exists iptonode_($ip)] } {
+	return $iptonode_($ip)
+    } else {
+	    return {}
+    }
+}
+
+# XXX netbed changes
+Simulator instproc ip-to-target {ip} {
+    $self instvar iptotarget_
+
+    if { [info exists iptotarget_($ip)] } {
+	return $iptotarget_($ip)
+    } else {
+	    return {}
+    }
+}
+
+## Should be called only after routing is computed
+## A good place is the run method
+## XXX netbed specific
+Simulator instproc add-routes-to-neighbour-ips {} {
+    $self instvar ipsubnetlist_
+    $self instvar iptotarget_
+    $self instvar link_
+
+    set rtlogic [$self get-routelogic]
+
+    foreach subnet [array names ipsubnetlist_] {
+	set subnet_aton [$self inet-aton $subnet]
+	foreach ip1 $ipsubnetlist_($subnet) {
+	    foreach ip2 $ipsubnetlist_($subnet) {
+		if( $ip1 == $ip2 ) {
+		    continue
+		}
+		set node1 $iptotarget_($ip1)
+		set node2 $iptotarget_($ip2)
+		set rt1id [$rtlogic lookup [$node1 id] [$node2 id]]
+		set rt2id [$rtlogic lookup [$node2 id] [$node1 id]]
+		$node1 add-route $subnet-aton $link_([$node1 id]:$rt1id)
+		$node2 add-route $subnet-aton $link_([$node2 id]:$rt2id)
+	    }
+	}
+    }
+}
+
+# XXX netbed changes
+Simulator instproc rlink { n1 n2ip {bw ""} {delay ""} {qtype ""} args } {
+    $self instvar rlink_ queueMap_ 
+
+    set sid [$n1 id]
+    set did [$self inet-aton $n2ip]
+
+    # If any of the bw/delay/qtype are not passed, it means
+    # that we have a link from a sim node to a real node.
+    # Any shaping will happen via a dummynet node
+    if { $bw == {} || $delay == {} || $qtype == {} } {	    
+	set rlink_($sid:$did) [new Rlink $n1 $n2ip]
+	$self add-ip-mask-target $n2ip 255.255.255.255 [$rlink_($sid:$did) head]
+	return $rlink_($sid:$did)
+    }
+    
+	
+    if { [info exists queueMap_($qtype)] } {
+	set qtype $queueMap_($qtype)
+    }
+    # construct the queue
+    set qtypeOrig $qtype
+    switch -exact $qtype {
+	ErrorModule {
+	    if { [llength $args] > 0 } {
+		set q [eval new $qtype $args]
+	    } else {
+		set q [new $qtype Fid]
+	    }
+	}
+	intserv {
+	    set qtype [lindex $args 0]
+	    set q [new Queue/$qtype]
+	}
+	default {
+	    if { [llength $args] == 0} {
+		set q [new Queue/$qtype]
+	    } else {
+		set q [new Queue/$qtype $args]
+	    }
+	}
+    }	
+    set rlink_($sid:$did) [new Rlink $n1 $n2ip $bw $delay $q]
+    $self add-ip-mask-target $n2ip 255.255.255.255 [$rlink_($sid:$did) head]
+    return $rlink_($sid:$did)
+}
+
+Simulator instproc ip-connect { agent ip port } {
790 791 792 793 794 795 796 797 798 799
+    set ipaton [$self inet-aton $ip]
+    $agent set dst_addr_ $ipaton
+    $agent set dst_port_ $port
+
+    $agent instvar node_
+    $node_ instvar nodeiplist_
+    # We just use one of the IP addresses of src node
+    # as the agent's src address
+    set srcipaton [$self inet-aton [lindex $nodeiplist_ 0]]
+    $agent set agent_addr_ $srcipaton
800 801
+}
--- dist-ns-allinone-2.26/ns-2.26/tcl/lib/ns-link.tcl	Wed Feb 26 15:09:37 2003
802
+++ ns-allinone-2.26/ns-2.26/tcl/lib/ns-link.tcl	Tue Dec  2 00:57:03 2003
803 804 805 806 807 808 809 810 811 812
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1996 Regents of the University of California.
+# Copyright (c) 1996, 2003 Regents of the University of California.
 # All rights reserved.
 # 
 # Redistribution and use in source and binary forms, with or without
@@ -63,6 +63,14 @@
 	return $head_
 }
813
 
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
+# XXX netbed specific
+# Want to have the same method for both
+# node and link
+Link instproc entry {} {
+    $self instvar head_
+    return $head_
+}
+
 Link instproc add-to-head { connector } {
 	$self instvar head_
 	$connector target [$head_ target]
@@ -164,6 +172,123 @@
 	$self instvar link_
 	$em target [$link_ target]
 	$link_ target $em
+}
+
+# XXX netbed specific
+Link instproc set-ip {ip} {
+    $self instvar srcipaddr_ fromNode_
+
+    set srcipaddr_ $ip
+    $fromNode_ add-ip $ip
+
+    # Besides that, adding a route for
+    # the subnet with this link as the target
+    # will ensure that packets destined to the 
+    # neighbors will be routed to us
+    set ns_ [Simulator instance]
+    
+    set ipmasked [expr [$ns_ inet-aton $ip] & [$ns_ inet-aton 255.255.255.0]]
+    $fromNode_ add-route $ipmasked [$self head]
+
+    # Need to add mapping from subnet mask to link so that new routes being
+    # added can use this
+    $ns_ add-ip-mask-target $ip 255.255.255.0 [$self head]
+}
+
+# XXX netbed specific
+Class Rlink -superclass Link
+
+Rlink instproc init { src dstip {bw ""} {delay ""} {q ""} {lltype "DelayLink"} } {
+        $self next $src $dstip
+	$self instvar link_ queue_ head_ toNode_ ttl_
+	$self instvar drophead_ dstipaddr_ srcipaddr_ target_
+
+        set dstipaddr_ $dstip
+	set ns [Simulator instance]
+	set drophead_ [new Connector]
+	$drophead_ target [$ns set nullAgent_]
+
+	set head_ [new Connector]
+	$head_ set link_ $self
+
+        # If any of the bw/delay/qtype are not passed, it means
+	# that we have a link from a sim node to a real node.
+	# Any shaping will happen via a dummynet node
+        if { $bw == {} || $delay == {} || $q == {} } {
+	    set target_ [new Agent/IPTap]
+	    $ns attach-agent $src $target_
+	    $head_ target $target_
+	    return $self
+	}
+
+	#set head_ $queue_ -> replace by the following
+	# xxx this is hacky
+	if { [[$q info class] info heritage ErrModule] == "ErrorModule" } {
+		$head_ target [$q classifier]
+        } else {
+                $head_ target $q
+
+        }
+
+	set queue_ $q
+	set link_ [new $lltype]
+	$link_ set bandwidth_ $bw
+	$link_ set delay_ $delay
+
+	$queue_ target $link_
+	set target_ [new Agent/IPTap]
+
+	# put the ttl checker after the delay
+	# so we don't have to worry about accounting
+	# for ttl-drops within the trace and/or monitor
+	# fabric
+	#
+	set ttl_ [new TTLChecker]
+	$ttl_ target $target_
+	$self ttl-drop-trace
+	$link_ target $ttl_
+
+	$ns attach-agent $src $target_
+	$queue_ drop-target $drophead_
+
+	return $self
+	# Finally, if running a multicast simulation,
+	# put the iif for the neighbor node...
+#	if { [$ns multicast?] } {
+#		$self enable-mcast $src $dst
+#	}
+#        $ns instvar srcRt_
+#	if [info exists srcRt_] {
+#        	if { $srcRt_ == 1 } {
+#            	$self enable-src-rt $src $dst $head_
+#        	}
+#	}    
+}
+
+Rlink instproc ttl-drop-trace args {
+	$self instvar ttl_
+	if ![info exists ttl_] return
+	if {[llength $args] != 0} {
+		$ttl_ drop-target [lindex $args 0]
+	} else {
+		$self instvar drophead_
+		$ttl_ drop-target $drophead_
+	}
+}
+
+Rlink instproc srcipaddr {} {
+    $self instvar srcipaddr_
+    return $srcipaddr_
+}
+
+Rlink instproc dstipaddr {} {
+    $self instvar dstipaddr_
+    return $dstipaddr_
+}
+
+Rlink instproc target {} {
+    $self instvar target_
+    return $target_
 }
947
 
948 949
 Class SimpleLink -superclass Link
--- dist-ns-allinone-2.26/ns-2.26/tcl/lib/ns-node.tcl	Wed Feb 26 15:09:37 2003
950
+++ ns-allinone-2.26/ns-2.26/tcl/lib/ns-node.tcl	Sun Jan  4 18:27:34 2004
951
@@ -492,6 +492,15 @@
952 953 954 955 956 957
 		# at the port demuxer (if there is one)
 		$self add-route $address_ $dmux_
 	}
+	# XXX netbed specific
+	$self instvar nodeiplist_
+	set ns_ [Simulator instance]
958 959 960 961 962
+	if { [info exists nodeiplist_] } {
+	    foreach ip $nodeiplist_ { 
+	    	set ipaton [$ns_ inet-aton $ip]
+	    	$self add-route $ipaton $dmux_
+	    }
963 964 965 966
+	}
 	if { $port == "" } {
 		set port [$dmux_ alloc-port [[Simulator instance] nullagent]]
 	}
967
@@ -569,3 +578,49 @@
968 969 970
 	$self instvar neighbor_
 	return [expr [lsearch $neighbor_ $node] != -1]
 }
971
+
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
+# XXX netbed specific
+Node instproc add-ip { ip } {
+    set ns_ [Simulator instance]
+    $ns_ instvar iplist_
+    lappend iplist_ $ip
+
+    $self instvar nodeiplist_ dmux_
+    lappend nodeiplist_ $ip
+
+    set ip_aton [$ns_ inet-aton $ip]
+
+    if { $dmux_ != "" } {
+	# By adding the IP of this link to the node, we
+	# make sure that packets with the dstaddr == ip
+	# will be given to the port classifier
+	$self add-route $ip_aton $dmux_
+    }
+    $ns_ add-ip $self $ip
+}
+
+# XXX netbed specific
+Node instproc add-route-to-ip { ip nhopip {mask 255.255.255.255} } {
+    set ns_ [Simulator instance]
+
+    set ip_aton [$ns_ inet-aton $ip]
+    set mask_aton [$ns_ inet-aton $mask]
+    set ip_masked [expr $ip_aton & $mask_aton]
+    set node [$ns_ ip-to-node $nhopip]
+    if { $node != {} } {
+        $self add-route $ip_masked [[$ns_ link $self $node] head]
+	return
+    }
+
+    set target [$ns_ ip-to-target $nhopip]
+    if { $target == {} } {
+	set nhop_aton [$ns_ inet-aton $nhopip]
+	set target [$ns_ ip-to-target [$ns_ inet-ntoa \
+	    [expr $nhop_aton & [$ns_ inet-aton 255.255.255.0]]]]
+    }
+
+    if { $target != {} } {
+	$self add-route $ip_masked $target
+    }
+}
+
--- dist-ns-allinone-2.26/ns-2.26/tcl/lib/ns-rtmodule.tcl	Fri Feb 28 10:50:56 2003
1018
+++ ns-allinone-2.26/ns-2.26/tcl/lib/ns-rtmodule.tcl	Fri Nov 28 16:55:25 2003
1019 1020 1021 1022 1023
@@ -125,6 +125,7 @@
 	$classifier_ set mask_ [AddrParams NodeMask 1]
 	$classifier_ set shift_ [AddrParams NodeShift 1]
 	# XXX Base should ALWAYS be the first module to be installed.
+        $classifier_ set ipmask_ [[Simulator instance] inet-aton 255.255.255.0]
1024
 
1025 1026
 	$node install-entry $self $classifier_
 }
1027
--- dist-ns-allinone-2.26/ns-2.26/apps/telnet.cc	Wed Feb 26 15:07:16 2003
1028
+++ ns-allinone-2.26/ns-2.26/apps/telnet.cc	Fri Nov 28 16:55:25 2003
1029 1030 1031 1032 1033 1034 1035 1036 1037
@@ -77,7 +77,7 @@
 {
         if (running_) {
 	        /* call the TCP advance method */
-		agent_->sendmsg(agent_->size());
+		agent_->sendmsg(1); // send 1 byte packets instead of 1460
 		/* reschedule the timer */
 		double t = next();
 		timer_.resched(t);
1038
--- dist-ns-allinone-2.26/ns-2.26/classifier/classifier-hash.h	Wed Feb 26 15:07:30 2003
1039
+++ ns-allinone-2.26/ns-2.26/classifier/classifier-hash.h	Fri Nov 28 16:55:25 2003
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
@@ -177,5 +177,17 @@
 	const char* hashkey(nsaddr_t, nsaddr_t dst, int) {
 		return (const char*) mshift(dst);
 	}
+	/* Since our address classifier (in flat 32 bit addressing) is
+	   a dest hash classifier, we do a naive longer prefix matching
+	   of the full IP address and then use ipmask_ to do a shorter
+	   prefix matching */
+	virtual int lookup(Packet* p) {
+		hdr_ip* h = hdr_ip::access(p);
+		int sl = get_hash(h->saddr(), h->daddr(), h->flowid());
+		if (sl >= 0 && sl <=maxslot_)
+		  return (sl);
+		return get_hash(h->saddr(), h->daddr() & ipmask_,
+				h->flowid());
+	}
 };
 
--- dist-ns-allinone-2.26/ns-2.26/classifier/classifier.cc	Wed Feb 26 15:07:34 2003
1059
+++ ns-allinone-2.26/ns-2.26/classifier/classifier.cc	Fri Nov 28 16:55:25 2003
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
@@ -52,13 +52,14 @@
 
 
 Classifier::Classifier() : 
-	slot_(0), nslot_(0), maxslot_(-1), shift_(0), mask_(0xffffffff), nsize_(0)
+	slot_(0), nslot_(0), maxslot_(-1), shift_(0), mask_(0xffffffff), nsize_(0), ipmask_(0xffffff00)
 {
 	default_target_ = 0;
 
 	bind("offset_", &offset_);
 	bind("shift_", &shift_);
 	bind("mask_", &mask_);
+	bind("ipmask_", &ipmask_);
 }
 
 int Classifier::classify(Packet *p)
--- dist-ns-allinone-2.26/ns-2.26/classifier/classifier.h	Wed Feb 26 15:07:34 2003
1077
+++ ns-allinone-2.26/ns-2.26/classifier/classifier.h	Fri Nov 28 16:55:25 2003
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
@@ -82,10 +82,11 @@
 	int nslot_;
 	int maxslot_;
 	int offset_;		// offset for Packet::access()
-	int shift_;
-	int mask_;
+	u_int32_t shift_;
+	u_int32_t mask_;
 	NsObject *default_target_;
 	int nsize_;       //what size of nslot_ should be
+	u_int32_t ipmask_;
 };
 
 #endif
1092
--- dist-ns-allinone-2.26/ns-2.26/classifier/classifier-port.h	Wed Feb 26 15:07:33 2003
1093 1094 1095
+++ ns-allinone-2.26/ns-2.26/classifier/classifier-port.h	Fri Mar 19 17:27:13 2004
@@ -28,13 +28,29 @@
 #include "ip.h"
1096 1097
 #include "classifier.h"
 
1098 1099 1100 1101 1102 1103
+#ifdef STORE_PKTS
+#ifndef NUM_PKTS
+#define NUM_PKTS 100000
+#endif
+#endif
+
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
 class PortClassifier : public Classifier {
+#ifdef STORE_PKTS    
+public:
+    	PortClassifier();
+#endif
 protected:
 	int classify(Packet *p);
 // 	void clear(int slot);
 // 	int getnxt(NsObject *);
 //	int command(int argc, const char*const* argv);
 // 	int reserved_;
+#ifdef STORE_PKTS
+	Tcl_HashTable pktsonport;
+	int command(int argc, const char*const* argv);
+	void print_pkts();
1119
+	void alloc_store_pkts(u_int32_t port, u_int32_t max_size=NUM_PKTS);
1120 1121 1122 1123
+#endif
 };
 
 class ReservePortClassifier : public PortClassifier {
1124
--- dist-ns-allinone-2.26/ns-2.26/classifier/classifier-port.cc	Wed Feb 26 15:07:33 2003
1125 1126
+++ ns-allinone-2.26/ns-2.26/classifier/classifier-port.cc	Wed Apr 14 03:58:33 2004
@@ -26,6 +26,31 @@
1127 1128 1129 1130 1131
 #endif
 
 #include "classifier-port.h"
+#include "packet.h"
+
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
+#ifdef STORE_PKTS
+
+struct pkt_data {
+    double ts;
+    unsigned int size;
+    double clock;
+};
+
+struct pkt_dump {
+    pkt_dump() : num_pkts(0) {}
1142 1143 1144 1145 1146 1147
+    ns_addr_t src;
+    ns_addr_t dst;
+    u_int32_t num_pkts;
+    u_int32_t max_pkts;
+    // variable sized array
+    pkt_data pkts[0];
1148 1149 1150 1151 1152 1153
+};
+
+PortClassifier::PortClassifier()
+{
+    	Tcl_InitHashTable( &pktsonport, TCL_ONE_WORD_KEYS );
+}
1154 1155 1156 1157
+#endif
 
 int PortClassifier::classify(Packet *p) 
 {
1158
@@ -33,8 +58,99 @@
1159 1160
 	// or masking is required since in the 32-bit addressing,
 	// ports are stored in a seperate variable.
1161 1162
 	hdr_ip* iph = hdr_ip::access(p);
+#ifdef STORE_PKTS
1163 1164
+	Tcl_HashEntry *he = Tcl_FindHashEntry( &pktsonport,
+					       (char *)(iph->dport()) );
1165 1166
+
+	pkt_dump *dump = 0;
1167
+	if( he != 0 ) {
1168
+	    dump = (pkt_dump *)Tcl_GetHashValue(he);
1169 1170 1171 1172 1173 1174 1175
+	    if ( dump->num_pkts < dump->max_pkts ) {
+		if( dump->num_pkts == 0 ) {
+		    dump->src = iph->src_;
+		    dump->dst = iph->dst_;
+		}
+		hdr_cmn *hc = HDR_CMN(p);
+		dump->pkts[dump->num_pkts].size = hc->size();
1176
+		dump->pkts[dump->num_pkts].ts = p->time_; 
1177 1178 1179 1180
+		dump->pkts[dump->num_pkts].clock = Scheduler::instance().clock(); 
+		dump->num_pkts += 1;
+	    }
+	} 
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
+#endif
 	return iph->dport();
 };
+
+#ifdef STORE_PKTS
+
+int PortClassifier::command(int argc, const char*const* argv)
+{
+        if (argc == 2 && strcmp(argv[1],"print-pkts") == 0) {
+	    	print_pkts();
+                return(TCL_OK);
1192 1193 1194 1195 1196 1197 1198 1199 1200
+        } 
+#ifdef STORE_PKTS
+	else if (argc >= 3 && strcmp(argv[1],"store-pkts") == 0) {
+	        u_int32_t port = atoi(argv[2]);
+		if ( argc == 4 )
+		    alloc_store_pkts(port, atoi(argv[3]));
+		else
+		    alloc_store_pkts(port);
+                return(TCL_OK);
1201
+        }
1202
+#endif
1203 1204 1205
+        return (Classifier::command(argc, argv));
+}
+
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
+#ifdef STORE_PKTS
+void PortClassifier::alloc_store_pkts(u_int32_t port, u_int32_t max_size) {
+
+	int newentry = 0;
+	pkt_dump *dump = 0;
+	Tcl_HashEntry *he = Tcl_CreateHashEntry( &pktsonport,
+						 (char *)port,
+						 &newentry );
+	if( newentry == 0 ) {
+	    dump = (pkt_dump *)Tcl_GetHashValue(he);
+	    free(dump);
+	    dump = 0;
+	} 
+	dump = (pkt_dump *)calloc(1, sizeof(pkt_dump) + 
+		    		  max_size * sizeof(pkt_data) );
+	dump->max_pkts = max_size;
+	Tcl_SetHashValue( he, (char *)dump );
+}
+#endif
+
1226 1227 1228 1229
+void PortClassifier::print_pkts()
+{
+    	Tcl_HashSearch search;
+	Tcl_HashEntry *he = 0;
1230 1231
+	Tcl &tcl = Tcl::instance();
+	char srcip[20], dstip[20];
1232 1233 1234 1235 1236 1237 1238
+
+	for( he = Tcl_FirstHashEntry(&pktsonport, &search) ; he != 0 ;
+	     he = Tcl_NextHashEntry(&search) ) {
+	    pkt_dump *dump = (pkt_dump *)Tcl_GetHashValue( he );
+	    if( dump->num_pkts == 0 ) 
+		continue;
+
1239 1240 1241 1242 1243 1244
+	    tcl.evalf("[Simulator instance] inet-ntoa %d", dump->src.addr_ );
+	    strncpy( srcip, tcl.result(), sizeof(srcip) );
+	    tcl.evalf("[Simulator instance] inet-ntoa %d", dump->dst.addr_ );
+	    strncpy( dstip, tcl.result(), sizeof(dstip) );
+	    printf("***************src-%s:%d dst-%s:%d***************\n", 
+		    srcip, dump->src.port_, dstip, dump->dst.port_ );
1245
+	    for( unsigned int i=0 ; i<dump->num_pkts ; i++ ) {
1246
+		printf("%f %d %f\n", dump->pkts[i].ts, dump->pkts[i].size,
1247 1248 1249
+		       dump->pkts[i].clock );
+	    }
+	    printf("---------------------------------------\n");
1250
+	    fflush(stdout);
1251 1252 1253 1254 1255 1256 1257
+	}
+}
+
+#endif 
 
 static class PortClassifierClass : public TclClass {
 public:
1258
--- dist-ns-allinone-2.26/ns-2.26/common/ip.h	Wed Feb 26 15:07:39 2003
1259
+++ ns-allinone-2.26/ns-2.26/common/ip.h	Fri Nov 28 16:55:25 2003
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
@@ -76,11 +76,11 @@
 	/* per-field member acces functions */
 	ns_addr_t& src() { return (src_); }
 	nsaddr_t& saddr() { return (src_.addr_); }
-        int32_t& sport() { return src_.port_;}
+        u_int32_t& sport() { return src_.port_;}
 
 	ns_addr_t& dst() { return (dst_); }
 	nsaddr_t& daddr() { return (dst_.addr_); }
-        int32_t& dport() { return dst_.port_;}
+        u_int32_t& dport() { return dst_.port_;}
 	int& ttl() { return (ttl_); }
 	/* ipv6 fields */
 	int& flowid() { return (fid_); }
--- dist-ns-allinone-2.26/ns-2.26/common/packet.h	Wed Feb 26 15:07:40 2003
1275
+++ ns-allinone-2.26/ns-2.26/common/packet.h	Fri Jan 16 16:09:19 2004
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
@@ -325,6 +325,10 @@
 	inline int& ref_count() { return (ref_count_); }
 	static inline Packet* alloc();
 	static inline Packet* alloc(int);
+        static inline int compress(unsigned long* pTarget, 
+				   unsigned long* pSource, int Count);
+	static inline int uncompress(unsigned long* pTarget, 
+				     unsigned long* pSource, int Count);
 	inline void allocdata(int);
 	// dirty hack for diffusion data
 	inline void initdata() { data_  = 0;}
@@ -519,8 +523,8 @@
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
 			abort();
 	}
 	init(p); // Initialize bits_[]
-	(HDR_CMN(p))->next_hop_ = -2; // -1 reserved for IP_BROADCAST
-	(HDR_CMN(p))->last_hop_ = -2; // -1 reserved for IP_BROADCAST
+	(HDR_CMN(p))->next_hop_ = (nsaddr_t)-2; // -1 reserved for IP_BROADCAST
+	(HDR_CMN(p))->last_hop_ = (nsaddr_t)-2; // -1 reserved for IP_BROADCAST
 	p->fflag_ = TRUE;
 	(HDR_CMN(p))->direction() = hdr_cmn::DOWN;
 	/* setting all direction of pkts to be downward as default; 
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
@@ -607,6 +611,88 @@
                         p->bits_[offset + i + 12], p->bits_[offset + i + 13],
                         p->bits_[offset + i + 14], p->bits_[offset + i + 15]);
         }
+}
+
+inline int Packet::compress(unsigned long* pTarget, unsigned long* pSource, int Count)
+{ // Returns total size of target buffer
+  // This code works only on buffers <= 0x10000 words long (about 250k bytes)
+  // Target buffer must be 1 word longer than source, to allow for the
+  // case where no zeros at all occur.
+ int offset = 0;
+ int skipping = 1;
+ int targoffset = 0;
+ int lth;
+
+ unsigned long* pCW = pTarget; // Control word pointer
+ // Format of control word is 16 bits of length, 16 bits of starting offset
+ *pCW = 0;  // All zero CW means done
+ while(offset < Count)
+   {
+     if (skipping)
+       {
+         if (pSource[offset] |= 0)
+           { // Time to stop skipping
+             skipping = 0;
+             pCW = &pTarget[targoffset];
+             *pCW = offset; // Set source offset, leave lth zero for now
+             targoffset++;  // Leave room for CW
+             lth = 0;       // Counts how many non-zero
+           }
+         else
+           { // Still zero, just skip it
+             offset++;
+           }
+       }
+     if (!skipping)
+       {
+         // First see if we found a zero
+         if (pSource[offset] == 0)
+           { // Found a zero, but just use it unless two in a row
+             if ((offset+1) < Count)
+               {
+                 if (pSource[offset+1] == 0)
+                   {
+                     skipping = 1; // Found two in a row, resume skipping
+                     *pCW |= (lth << 16);
+                     //*pCW |= (0x1L << 31); // just for debugging, mark cw
+                     offset++; // And skip this one
+                   }
+               }
+           }
+       }
+     if (!skipping)
+       {
+         pTarget[targoffset++] = pSource[offset++];
+         lth++;
+       }
+   }
+ if (!skipping)
+   { // Need to update last CW
+     *pCW |= (lth << 16);
+     //*pCW |= (0x1L << 31); // just for debugging, mark cw
+   }
+ return(targoffset);
+}
+
+inline int Packet::uncompress(unsigned long* pTarget, unsigned long* pSource, int Count)
+{ // Reverse above compression
+  // Target buffer MUST BE ZERO on entry!
+int offset = 0;
+int targoffset = 0;
+int lth;
+
+  while(offset < Count)
+    {
+      // Get next control word
+      targoffset = pSource[offset] & 0xffff;
+      lth = pSource[offset] >> 16;
+      offset++;
+      for (int i = 0; i < lth; i++)
+        { // Copy to target
+          pTarget[targoffset++] = pSource[offset++];
+        }
+    }
+  return(targoffset); // Last non-zero entry
 }
 
 #endif
1387
--- dist-ns-allinone-2.26/ns-2.26/common/scheduler.cc	Wed Feb 26 15:07:41 2003
1388 1389
+++ ns-allinone-2.26/ns-2.26/common/scheduler.cc	Tue Mar 30 17:46:34 2004
@@ -46,12 +46,50 @@
1390 1391 1392 1393 1394
 #include "config.h"
 #include "scheduler.h"
 #include "packet.h"
+#ifdef USEEVENTS
+#include "tbevent.h"
1395 1396 1397 1398 1399 1400 1401 1402
+#endif
+
+#ifdef HAVE_POLLER
+
+#include "Poller_kqueue.h"
+
+Poller_kqueue *poller;
+
1403 1404
+#endif
 
1405
 
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
 #ifdef MEMDEBUG_SIMULATIONS
 #include "mem-trace.h"
 #endif
 
+#ifdef MEASURE_EVENT_RATE
+
+unsigned long long event_dispatch_counter;
+unsigned int events_per_sec_arr[70];
+
+#endif
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
+
+#ifdef GETTIME_TSC
+
+#define read_tsc()      \
+    ({ \
+        unsigned long low, high; \
+        asm volatile( \
+        ".byte 0x0f; .byte 0x31" \
+        : "=d" (high), "=a" (low)); \
+        ((unsigned long long)high << 32) | low; \
+    })
+
+#define TSC_FREQ     851.94
+#define TSC_COUNT_PERSEC (TSC_FREQ * 1000000)
+
+#endif
+
+#ifdef SCHED_DEBUG
+static Tcl_HashTable newevents;
+#endif
1436 1437 1438
+
 Scheduler* Scheduler::instance_;
 scheduler_uid_t Scheduler::uid_ = 1;
1439
 
1440
@@ -62,6 +100,9 @@
1441 1442 1443 1444 1445 1446 1447 1448 1449
 
 Scheduler::Scheduler() : clock_(SCHED_START), halted_(0)
 {
+#ifdef SCHED_DEBUG
+	  Tcl_InitHashTable( &newevents, TCL_ONE_WORD_KEYS );
+#endif
 }
 
 Scheduler::~Scheduler(){
1450
@@ -112,6 +153,17 @@
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
 
 	e->time_ = t;
 	insert(e);
+#ifdef SCHED_DEBUG
+	int newentry = 0 ;
+	Tcl_HashEntry *he = Tcl_CreateHashEntry( &newevents,
+						 (char *)((unsigned int)e->uid_),
+						 &newentry );
+	if( newentry == 0 ) {
+	  fprintf(stderr, "e->uid_ = %d already present. error\n", (unsigned int)e->uid_);
+	} else {
+	  Tcl_SetHashValue( he, (char *)h );
+	}
+#endif
 }
 
 void
1468
@@ -579,7 +631,7 @@
1469 1470 1471
 	}
 } class_calendar_sched;
 
1472
-CalendarScheduler::CalendarScheduler() : cal_clock_(clock_) {
1473
+CalendarScheduler::CalendarScheduler() : cal_clock_(clock_), cached_head_(0) {
1474
 	reinit(4, 1.0, cal_clock_);
1475
 }
1476
 
1477
@@ -598,6 +650,7 @@
1478 1479 1480
 		// may happen in RT scheduler
 		cal_clock_ = e->time_;
 		i = lastbucket_ = CALENDAR_HASH(cal_clock_);
1481
+		cached_head_ = e;
1482 1483
 	} else
 		i = CALENDAR_HASH(e->time_);
1484
 
1485
@@ -703,6 +756,10 @@
1486 1487
 	if (qsize_ == 0)
 		return NULL;
1488
 
1489 1490 1491
+	if (cached_head_) {
+	  return cached_head_;	  
+	}
1492
+
1493 1494 1495
 	int l, i = lastbucket_;
 	int lastbucket_dec = (lastbucket_) ? lastbucket_ - 1 : nbuckets_ - 1;
 	double diff;
1496
@@ -755,7 +812,7 @@
1497 1498 1499 1500 1501 1502
 	 */
 	lastbucket_ = l;
  	cal_clock_  = e->time_;
-	
+	cached_head_ = e;
 	return e;
1503 1504
 }
 
1505
@@ -797,6 +854,8 @@
1506
 		resize(nbuckets_ >> 1, cal_clock_);
1507
 	}
1508
 
1509 1510 1511
+	cached_head_ = 0;
+
 	return e;
1512
 }
1513
 
1514
@@ -926,6 +985,9 @@
1515 1516
 
 	--qsize_;
1517
 
1518 1519 1520
+	if ( e == cached_head_ )
+	  cached_head_ = 0;
+
1521
 	return;
1522 1523
 }
 
1524
@@ -946,23 +1008,6 @@
1525 1526
 	return NULL;
 }
1527
 
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
-#ifndef WIN32
-#include <sys/time.h>
-#endif
-
-class RealTimeScheduler : public CalendarScheduler {
-public:
-	RealTimeScheduler();
-	virtual void run();
-	double start() const { return start_; }
-	virtual void reset();
-protected:
-	void sync() { clock_ = tod(); }
-	double tod();
-	double slop_;	// allowed drift between real-time and virt time
-	double start_;	// starting time
-};
-
1545
 static class RealTimeSchedulerClass : public TclClass {
1546 1547
 public:
 	RealTimeSchedulerClass() : TclClass("Scheduler/RealTime") {}
1548
@@ -971,72 +1016,245 @@
1549 1550 1551 1552 1553 1554
 	}
 } class_realtime_sched;
 
-RealTimeScheduler::RealTimeScheduler() : start_(0.0)
+RealTimeScheduler::RealTimeScheduler() : start_(0.0), num_violation_(0),
+                                         clock_first_violation_(0.0)
1555 1556
 {
 	bind("maxslop_", &slop_);
1557 1558 1559
+#ifdef USEEVENTS
+        evsink_ = 0 ;
+#endif
1560 1561 1562
+#ifdef GETTIME_TSC
+        basetsc_ = 0 ;
+	oneontscfreq_ = 1.0 / (double)TSC_COUNT_PERSEC;
1563
+	tscfreq_ = TSC_COUNT_PERSEC;
1564
+#endif
1565 1566 1567 1568
+#ifdef HAVE_POLLER
+	poller = new Poller_kqueue;
+	poller->init();
+#endif
1569 1570
+}
+
1571 1572
+#ifdef USEEVENTS
+  
1573
+int RealTimeScheduler::command(int argc, const char*const* argv)
1574 1575 1576 1577 1578 1579 1580 1581 1582
+{
+  if (instance_ == 0)
+    instance_ = this;
+  
+  
+  if( argc == 3 ) {
+    if(strcmp(argv[1], "tbevent-sink") == 0) {
+      evsink_ = (TbEventSink *)TclObject::lookup(argv[2]);
+      return(TCL_OK);
1583 1584 1585 1586 1587 1588 1589
+    } else if (strcmp(argv[1], "cpuspeed") == 0) {
+      double ret;
+      if( (ret = atof(argv[2])) != 0 ) {
+	tscfreq_ = ret;
+	oneontscfreq_ = 1.0 / tscfreq_;
+      }
+      return(TCL_OK);
1590 1591 1592 1593 1594 1595 1596 1597
+    }
+  }
+
+  return(Scheduler::command(argc, argv));
+}  
+
+#endif
+
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
+/*
+ * dispatch a single simulator event by setting the system
+ * virtul clock to the event's timestamp and calling its handler.
+ * Note that the event may have side effects of placing other items
+ * in the scheduling queue
+ */
+
+void
+RealTimeScheduler::dispatch(Event* p, double t)
+{
+
+#ifdef SCHED_DEBUG
+	Tcl_HashEntry *he = Tcl_FindHashEntry(&newevents, (char *)((unsigned int)p->uid_));
+	if( he ) {
+	  Tcl_DeleteHashEntry(he);
+	} else {
+	  fprintf(stderr, "error. couldnt find event with uid = %d\n", (unsigned int)p->uid_);
+	}
+#endif
+	clock_ = t;
+	p->uid_ = -p->uid_;	// being dispatched
+	p->handler_->handle(p);	// dispatch
+#ifdef MEASURE_EVENT_RATE
+	event_dispatch_counter++;
+#endif
 }
 
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
 double
 RealTimeScheduler::tod()
 {
+#ifdef GETTIME_TSC
+                 
+        unsigned long long curtsc = read_tsc();
+        return (((double)(curtsc - basetsc_)) * oneontscfreq_);
+#else
 	timeval tv;
 	gettimeofday(&tv, 0);
 	double s = tv.tv_sec;
 	s += (1e-6 * tv.tv_usec);
 	return (s - start_);
+#endif
 }
 
 void
1642
 RealTimeScheduler::reset()
1643 1644 1645
 {
 	clock_ = SCHED_START;
+#ifdef GETTIME_TSC   
1646 1647
+	timeval tv;
+	gettimeofday(&tv, 0);
1648
+        basetsc_ = read_tsc();
1649
+	start_ = tv.tv_sec + (1e-6 * tv.tv_usec);
1650 1651
+#else
 	start_ = tod();
1652 1653 1654 1655 1656 1657
+#endif
 }
 
+#ifdef SCHED_DEBUG
+int done = 0;
+#endif
1658
+
1659 1660
 void 
 RealTimeScheduler::run()
1661
 { 
1662
+#ifdef SELECT_TIMEOUT
1663
 	static const double RTSCHEDULER_MINWAIT = 1.0e-3; // don't wait for less
1664
+	static const double delta = 1.0e-4; // should be smaller than above
1665
+#endif
1666 1667
+	static const int VIOLATION_THRESHOLD = 5;
+	static const double VIOLATION_TIME_THRESHOLD = 1.0;
1668
 	const Event *p;
1669
+	bool gethead = true;
1670 1671 1672 1673 1674 1675 1676
+
+#ifdef USEEVENTS
+
+	if( evsink_ ) {
+	  evsink_->init();
+	  evsink_->subscribe();
+	}
1677
+
1678
+#endif
1679
 
1680 1681 1682 1683
 	/*XXX*/
 	instance_ = this;
 
 	while (!halted_) {
1684
+		if( gethead ) {
1685 1686
+		  p = head();
+		  gethead = false;
1687
+		}
1688 1689 1690 1691
 		clock_ = tod();
-		p = head();
+
 		if (p && (clock_ - p->time_) > slop_) {
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
-			fprintf(stderr,
-				"RealTimeScheduler: warning: slop "
-				"%f exceeded limit %f [clock_:%f, p->time_:%f]\n",
-				clock_ - p->time_, slop_, clock_, p->time_);
+		    num_violation_++;
+		    if (num_violation_ == 1 ) {
+			clock_first_violation_ = clock_;
+		    } else if(num_violation_ == VIOLATION_THRESHOLD) {
+			double diff = clock_ - clock_first_violation_;
+			if (diff < VIOLATION_TIME_THRESHOLD) {
1702
+#ifdef USEEVENTS
1703
+			    if (evsink_) {
1704
+#ifdef RESWAP
1705
+				evsink_->send_nseswap();
1706
+#endif
1707
+			    }
1708
+#endif
1709 1710 1711 1712 1713
+			} else {
+			    clock_first_violation_ = clock_;
+			    num_violation_ = 1;
+			}
+		    }
1714
+#ifdef PRINT_SLOP
1715 1716 1717 1718
+		    fprintf(stderr,
+			    "RealTimeScheduler: warning: slop "
+			    "%f exceeded limit %f [clock_:%f, p->time_:%f]\n",
+			    clock_ - p->time_, slop_, clock_, p->time_);
1719
+#endif
1720 1721
+		    clock_ = tod();
 		}
1722 1723 1724
 		// handle "old events"
 		while (p && p->time_ <= clock_) {
 
1725
+#ifdef DISPATCH_IN_RT
1726
 			dispatch(deque(), clock_);
1727 1728 1729
+#else
+			dispatch(deque(), p->time_);
+#endif
1730 1731 1732 1733
 			if (halted_)
 				return;
 			p = head();
 			clock_ = tod();
1734
 		}
1735
-		
1736
+
1737
+#ifdef USEEVENTS
1738
+		if( evsink_ && evsink_->poll() == 1 ) {
1739
+		  gethead = true;
1740
+		  continue;
1741 1742
+		}
+#endif
1743
+
1744 1745 1746 1747 1748
+#ifdef SCHED_DEBUG
+		if( clock_ >= 240.0 && done == 0 ) {
+		  fprintf( stderr, "After 60 secs. Hash Stats for newevents = %s\n",
+			   Tcl_HashStats(&newevents) );
+		  done = 1;
1749 1750
+		}
+#endif
1751
+
1752
+#if !defined(HAVE_POLLER) && defined(SELECT_TIMEOUT)
1753 1754
 		if (!p) {
 			// blocking wait for TCL events
1755 1756 1757 1758 1759
-			Tcl_WaitForEvent(0); // no sim events, wait forever
+			// Tcl_WaitForEvent(0); // no sim events, wait forever
+			// XXX: But we can't afford to wait forever coz testbed
+			// events are not being polled here and we might miss them
 			clock_ = tod();
1760
+			Tcl_WaitForEvent(0); // no sim events, wait forever
1761 1762
 		} else {
 			double diff = p->time_ - clock_;
1763
 			// blocking wait only if there is enough time
1764 1765 1766 1767
 			if (diff > RTSCHEDULER_MINWAIT) {
 				Tcl_Time to;
 				to.sec = long(diff);
-				to.usec = long(1e6*(diff - to.sec));
1768
+				to.usec = long(1e6*((diff - delta) - to.sec)); // wait for delta less
1769 1770 1771 1772 1773
 				Tcl_WaitForEvent(&to);    // block
 				clock_ = tod();
 			}
 		}
-		Tcl_DoOneEvent(TCL_DONT_WAIT);
1774 1775 1776
+#else
+		clock_ = tod();
+#endif
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
+#ifdef HAVE_POLLER
+		struct Poller::PollEvent pe;
+
+		if(poller->waitForEvents(0) == 0) {
+		    while(poller->getNextEvent(&pe) == 0) {
+			Poller::Client *client = pe.client;
+			if (client) {
+			    client->notifyPollEvent(&pe);
+			    gethead = true;
+			}
+		    }
+		}
+#else
1790
+		if( Tcl_DoOneEvent(TCL_DONT_WAIT) == 1 ) {
1791 1792 1793 1794 1795 1796 1797
+		  /* If we have more than 1 I/O channel (bpf device typically)
+		   * that we can get packets from, we better service all that
+		   * are ready in one go or some packets will be quite late. The 
+		   * while loop below runs as many times as there are I/O channels
+		   * ready
+		   */
+		  while( Tcl_ServiceEvent(0) == 1 );
1798 1799
+		  gethead = true;
+		}
1800
+#endif
1801
 	}
1802
 	// we reach here only if halted
1803
 }
1804
--- dist-ns-allinone-2.26/ns-2.26/common/scheduler.h	Wed Feb 26 15:07:41 2003
1805
+++ ns-allinone-2.26/ns-2.26/common/scheduler.h	Thu Mar 11 19:01:17 2004
1806
@@ -98,7 +98,7 @@
1807 1808 1809 1810 1811 1812 1813 1814
 protected:
 	void dumpq();	// for debug: remove + print remaining events
 	void dispatch(Event*);	// execute an event
-	void dispatch(Event*, double);	// exec event, set clock_
+	virtual void dispatch(Event*, double);	// exec event, set clock_
 	Scheduler();
 	virtual ~Scheduler();
 	int command(int argc, const char*const* argv);
1815
@@ -176,6 +176,7 @@
1816 1817
 private:
 	virtual void insert2(Event*);
1818
 	double cal_clock_;  // same as clock in sims, may be different in RT-scheduling.
1819
+	const Event *cached_head_;
1820 1821 1822
 
 };
 
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
@@ -206,5 +207,43 @@
 	int validate(Event *);
 };
 
+#ifndef WIN32
+#include <sys/time.h>
+#endif
+
+#ifdef USEEVENTS
+class TbEventSink;
+#endif
+
+class RealTimeScheduler : public CalendarScheduler {
+public:
+	RealTimeScheduler();
+	virtual void run();
+	virtual double start() const { return start_; }
+	virtual void reset();
+#ifdef USEEVENTS
+	int command(int argc, const char*const* argv);
+#endif
+protected:
+	void sync() { clock_ = tod(); }
+	virtual void dispatch(Event*, double);	// exec event, set clock_
+	double tod();
+	double slop_;	// allowed drift between real-time and virt time
+	double start_;	// starting time
+	int    num_violation_; /* Number of times the clock has drifted by
+	                        * slop between real-time and virtual time
+			        */
+	double clock_first_violation_; /* Value of clock when the first
+				        * violation is detected
+				        */
+#ifdef USEEVENTS
+        TbEventSink *evsink_;
+#endif
+#ifdef GETTIME_TSC
+        unsigned long long basetsc_ ;
+        double  oneontscfreq_;
+        double  tscfreq_;
+#endif
+};
 
 #endif
1867
--- dist-ns-allinone-2.26/ns-2.26/common/simulator.cc	Wed Feb 26 15:07:41 2003
1868
+++ ns-allinone-2.26/ns-2.26/common/simulator.cc	Fri Nov 28 16:55:25 2003
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
@@ -23,6 +23,7 @@
 #include "object.h"
 
 //class ParentNode;
+Simulator* Simulator::instance_;
 
 static class SimulatorClass : public TclClass {
 public:
@@ -92,6 +93,25 @@
 			int id = atoi(argv[3]);
 			add_node(node, id);
 			return TCL_OK;
+		} else if (strcmp(argv[1], "add-ip") == 0) {
+			Node *node = (Node *)(TclObject::lookup(argv[2]));
+			if (node == NULL) {
+				tcl.add_errorf("Wrong object name %s",argv[2]);
+				return TCL_ERROR;
+			}
+			in_addr_t ip = inet_addr(argv[3]);
+			int newentry = 0;
+			Tcl_HashEntry *he = Tcl_CreateHashEntry( &iptonode,
+								 (char *)(ip),
+								 &newentry );
+			if ( newentry == 0 ) {
+				Node *n = (Node *)Tcl_GetHashValue( he );
+				tcl.add_errorf("IP address %s already belongs to node %s\n",
+					       argv[3], n->name() );
+				return TCL_ERROR;
+			}
+			Tcl_SetHashValue( he, (char *)node);	
+			return TCL_OK;
 		} 
 	}
 	return (TclObject::command(argc, argv));
@@ -250,3 +270,11 @@
 	return l_head;
 }
 
+Node * Simulator::ip_to_node(in_addr_t ip) {
+
+	Tcl_HashEntry *he = Tcl_FindHashEntry( &iptonode, (char *)ip );
+	if( he == 0 ) 
+		return 0;
+	else
+		return (Node *)Tcl_GetHashValue(he);
+}
--- dist-ns-allinone-2.26/ns-2.26/common/simulator.h	Wed Feb 26 15:07:42 2003
1916
+++ ns-allinone-2.26/ns-2.26/common/simulator.h	Fri Nov 28 16:55:25 2003
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
@@ -25,17 +25,21 @@
 
 #include <tclcl.h>
 #include "object.h"
+#include <sys/types.h>
 
 class ParentNode;
 class RouteLogic;
+class Node;
 
 class Simulator : public TclObject {
 public:
       Simulator() : nodelist_(NULL), rtobject_(NULL), nn_(0), \
-	size_(0) {}
+	size_(0) { Tcl_InitHashTable( &iptonode, TCL_ONE_WORD_KEYS ); instance_ = this; }
       ~Simulator() {
-	    delete []nodelist_; 
+	    delete []nodelist_;
+	    instance_ = 0;
       }
+      static Simulator &instance() { return (*instance_); }
 	int command(int argc, const char*const* argv);
 	void populate_flat_classifiers();
 	void populate_hier_classifiers();
@@ -45,12 +49,15 @@
 	char *append_addr(int level, int *addr);
 	void alloc(int n);
 	void check(int n);
+	Node *ip_to_node(in_addr_t);
 	
 private:
         ParentNode **nodelist_;
 	RouteLogic *rtobject_;
 	int nn_;
 	int size_;
+	Tcl_HashTable iptonode;
+	static Simulator *instance_;
 };
 
 #endif /* ns_simulator_h */
1957
--- dist-ns-allinone-2.26/ns-2.26/common/tclAppInit.cc	Wed Feb 26 15:07:42 2003
1958
+++ ns-allinone-2.26/ns-2.26/common/tclAppInit.cc	Fri Nov 28 16:55:25 2003
1959 1960
@@ -186,6 +186,7 @@
 	return TCL_OK;
1961 1962
 }
 
1963 1964
+#if 0
 #ifndef WIN32
1965
 void
1966 1967 1968 1969
 abort()
@@ -200,6 +201,7 @@
 #endif /*abort*/
 	/*NOTREACHED*/
1970
 }
1971 1972
+#endif
 #endif
1973 1974
 
 }
1975
--- dist-ns-allinone-2.26/ns-2.26/common/timer-handler.cc	Wed Feb 26 15:07:42 2003
1976
+++ ns-allinone-2.26/ns-2.26/common/timer-handler.cc	Fri Nov 28 16:55:25 2003
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
@@ -76,3 +76,40 @@
 	if (status_ == TIMER_HANDLING)
 		status_ = TIMER_IDLE;
 }
+
+#ifdef MEASURE_EVENT_RATE
+
+extern unsigned long long event_dispatch_counter;
+
+unsigned int idx;
+
+#define MAX_EVENT_ARR 70
+
+// circular buffer for the data
+extern unsigned int events_per_sec_arr[MAX_EVENT_ARR];
+
+
+void EventRateTimer::expire(Event *e) {
+
+  if ( idx % MAX_EVENT_ARR == MAX_EVENT_ARR-1 ) {
+
+    events_per_sec_arr[idx % MAX_EVENT_ARR] = event_dispatch_counter;
+    event_dispatch_counter = 0;
+    idx++;
+    
+    int i = 0 ;
+    for( ; i < MAX_EVENT_ARR-1 ; i++ ) {
+      fprintf(stderr, "%u, ", events_per_sec_arr[i] );
+    }
+    fprintf(stderr, "%u\n", events_per_sec_arr[MAX_EVENT_ARR-1] );    
+  } else {
+  
+    events_per_sec_arr[idx % MAX_EVENT_ARR] = event_dispatch_counter;
+    event_dispatch_counter = 0;
+    idx++;
+  }
+  resched(1.0);    
+    
+}
+
+#endif
2018
--- dist-ns-allinone-2.26/ns-2.26/common/timer-handler.h	Wed Feb 26 15:07:42 2003
2019
+++ ns-allinone-2.26/ns-2.26/common/timer-handler.h	Fri Nov 28 16:55:25 2003
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
@@ -88,4 +88,15 @@
 // mode:c++
 // End:
 
+#ifdef MEASURE_EVENT_RATE
+
+class EventRateTimer : public TimerHandler {
+
+public:
+  virtual void expire(Event *e) ;
+
+};
+
+#endif
+
 #endif /* timer_handler_h */
2036
--- dist-ns-allinone-2.26/ns-2.26/routing/address.cc	Wed Feb 26 15:09:15 2003
2037
+++ ns-allinone-2.26/ns-2.26/routing/address.cc	Fri Nov 28 16:55:25 2003
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
@@ -120,7 +120,7 @@
 			}
 			else 
 				levels_ = temp;
-			NodeShift_ = new int[levels_ + 1];
+			NodeShift_ = new u_int32_t[levels_ + 1];
 			for (i = 3, c = 1; c <= levels_; c++, i+=2)
 				NodeShift_[c] = atoi(argv[i]);
 			return (TCL_OK); 
@@ -136,7 +136,7 @@
 			}
 			else 
 				levels_ = temp;
-			NodeMask_ = new int[levels_ + 1];
+			NodeMask_ = new u_int32_t[levels_ + 1];
 			for (i = 3, c = 1; c <= levels_; c++, i+=2) 
 				NodeMask_[c] = atoi(argv[i]);
 			return (TCL_OK);
--- dist-ns-allinone-2.26/ns-2.26/routing/address.h	Wed Feb 26 15:09:15 2003
2057
+++ ns-allinone-2.26/ns-2.26/routing/address.h	Fri Nov 28 16:55:25 2003
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
@@ -61,10 +61,10 @@
 	// e.g 32 for level=1, 10/11/11 for level=3.
 	// used to check validity of address-str.
 	int *bpl_;
-	int *NodeShift_;
-	int *NodeMask_;
-	int McastShift_;
-	int McastMask_;
+	u_int32_t *NodeShift_;
+	u_int32_t *NodeMask_;
+	u_int32_t McastShift_;
+	u_int32_t McastMask_;
 	int levels_;
  protected:
 	int command(int argc, const char*const* argv);
2073
--- dist-ns-allinone-2.26/ns-2.26/emulate/iptap.cc	Wed Feb 26 15:08:40 2003
2074
+++ ns-allinone-2.26/ns-2.26/emulate/iptap.cc	Fri Apr 16 06:07:15 2004
2075 2076 2077 2078 2079 2080 2081
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 1998 The Regents of the University of California.
+ * Copyright (c) 1997, 1998, 2003 The Regents of the University of California.
  * All rights reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
2082
@@ -37,28 +37,80 @@
2083 2084 2085
 #endif
 
 #include "iptap.h"
2086 2087
+#include "node.h"
+#include "simulator.h"
2088
+#include <sys/time.h>
2089 2090
+#include <netinet/in.h>
+
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
+#include "tbnexthop.h"
+
+#ifdef MEASURE_EVENT_RATE
+#include "timer-handler.h"
+
+EventRateTimer ert;
+unsigned int firstpacket;
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#include        "tbdefs.h"
+#include        "log.h"
2105
+
2106 2107 2108 2109
+#ifdef __cplusplus
+}
+#endif
 
2110
 
2111 2112 2113 2114 2115 2116
 static class IPTapAgentClass : public TclClass {
  public:
-	IPTapAgentClass() : TclClass("Agent/IPTap") {}
+	IPTapAgentClass() : TclClass("Agent/IPTap") {
+	}
 	TclObject* create(int, const char*const*) {
2117 2118 2119 2120 2121 2122 2123
+#ifdef MEASURE_EVENT_RATE
+	  // schedule the event rate 
+	  if ( firstpacket == 0 ) {
+	    ert.sched(1.0);
+	    firstpacket++;
+	  }
+#endif
2124
 		return (new IPTapAgent());
2125
 	}
2126 2127 2128
 } class_iptap_agent;
 
 
2129
 IPTapAgent::IPTapAgent() 
2130 2131 2132 2133 2134
+#ifdef MEASURE_DELAYS  
+                        :  firstpkt_in_burst(false),
+			   max_delay(0.0), bpf_ts_to_iptap_max_delay(0.0),
+			   bpf_ts_to_iptap_min_delay(100.0), data_idx(0)
+#endif
2135 2136 2137
 {
   int i = 0;
   index = 0;
2138 2139
+#ifdef MEASURE_DELAYS
+  memset( bpf_ts_to_iptap, 0, sizeof(bpf_ts_to_iptap));
2140 2141 2142 2143
+#endif
   for (; i < MAX_PACKETS ; i++) {
     ident[i] = -1;
     offset[i] = -1;
2144 2145 2146 2147 2148 2149 2150 2151 2152
   }
 
+  sbuflen = rbuflen = ROUNDUP(sizeof(struct ip) + Packet::hdrlen_, sizeof(unsigned long) )
+                      + sizeof(unsigned long);
+  sendbuf = new unsigned char[sbuflen];
+  recvbuf = new unsigned char[rbuflen];
+  mtu = 1500; /* just assume default */
+  icmpagent = 0;
+  memset( &srcnodeipaddr, 0, sizeof(srcnodeipaddr) );
2153
+  send_count = recv_count = 0;
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163
 }
 
+IPTapAgent::~IPTapAgent()
+{
+  delete[] sendbuf;
+  delete[] recvbuf;
+}
 
 /*
  * Checking for duplicate packets.  Need to do this, if running
2164 2165 2166 2167 2168 2169 2170
@@ -127,21 +179,77 @@
   inst->processpkt(p, ts);
 }
 
+bool PacketDecapsulateIfNeeded(Packet *p);
+
 void
2171 2172 2173 2174 2175
 IPTapAgent::processpkt(Packet *p, const struct timeval &ts)
 {
   struct ip *ipheader;
-  struct tcphdr *tcpheader;
-  unsigned char *buf;
2176
   
2177 2178 2179 2180
   /* Ip header information from the grabbed packet. */
-  int iphlen;  
   unsigned short datagramlen;
   unsigned char ttl;
2181 2182
+
+  recv_count++;
2183
+
2184
+#ifdef MEASURE_DELAYS
2185
+
2186
+  double delay ;
2187 2188 2189 2190
+  // This code keeps some delay data and drops the packet 
+  if( firstpkt_in_burst ) {
+    ts_firstpkt_in_burst = ts.tv_sec + ts.tv_usec * 1e-6 ;
+    firstpkt_in_burst = false;
2191 2192 2193 2194 2195 2196 2197
+    delay = 0.0;
+  } else {
+    delay = double(ts.tv_sec + ts.tv_usec * 1e-6) - ts_firstpkt_in_burst;
+    timeval tv;
+    gettimeofday(&tv, 0);
+    double nowts = tv.tv_sec + (1e-6 * tv.tv_usec);
+    max_delay = MAX(nowts - ts_firstpkt_in_burst, max_delay);
2198 2199 2200
+  }
+
+
2201 2202
+#endif
+
2203 2204 2205
   
-  /* TCP header info from the grabbed packet. */
-  unsigned char tcphlen;
2206
+#if 0
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
+  timeval tv;
+  gettimeofday(&tv, 0);
+  double nowts = tv.tv_sec + (1e-6 * tv.tv_usec);
+  max_delay = MAX(nowts - ts_firstpkt_in_burst, max_delay);
+  bpf_ts_to_iptap[data_idx] = nowts - (ts.tv_sec + ts.tv_usec * 1e-6);
+  bpf_ts_to_iptap_max_delay = MAX(bpf_ts_to_iptap[data_idx],
+			      bpf_ts_to_iptap_max_delay);
+  bpf_ts_to_iptap_min_delay = MIN(bpf_ts_to_iptap[data_idx],
+			      bpf_ts_to_iptap_min_delay);
+  data_idx = (data_idx+1) %
+    (sizeof(bpf_ts_to_iptap)/sizeof(bpf_ts_to_iptap[0]));
2218
+
2219 2220
+  Packet::free(p);
+  return;
2221
   
2222
+#endif
2223 2224
+
+#if 0 //MEASURE_EVENT_RATE
2225 2226 2227 2228 2229 2230
+  // schedule the event rate 
+  if ( firstpacket == 0 ) {
+    ert.sched(1.0);
+    firstpacket++;
+  }
+#endif
2231 2232 2233 2234 2235 2236 2237 2238 2239
+  
+  // Pcap would have filled in a timestamp based on the bpf timestamp
+  double ptime = p->time_;
+  // We always need to decapsulate right here coz further simulation
+  // of the packet
+  if( PacketDecapsulateIfNeeded(p) ) {
+      p->time_ = ptime;
+      goto sendit;
+  }
2240 2241 2242 2243
+  /* PcapNetwork created this packet and does not know how
+     to initialize it. So, we need to do that here by calling
+     the base Agent class's initpkt method */
+  initpkt(p);
2244 2245
   /* 
      At this point, all I have to do is to grab the ttl value 
2246
      from the received packet and put it in p's ttl field after
2247
@@ -150,8 +258,6 @@
2248 2249 2250 2251 2252 2253 2254 2255
   */
 
   ipheader = (struct ip *) p->accessdata();
-  buf = p->accessdata();
-  iphlen = ipheader->ip_hl * 4;
   ttl = ipheader->ip_ttl;
   if (!(--ttl)) {
     fprintf(stderr,
2256 2257 2258 2259 2260 2261