model-net-mpi-wrklds.c 43.5 KB
Newer Older
1 2 3 4 5 6
/*
 * Copyright (C) 2014 University of Chicago.
 * See COPYRIGHT notice in top-level directory.
 *
 */
#include <ross.h>
7
#include <inttypes.h>
8

9
#include "codes/codes-workload.h"
10 11 12 13 14
#include "codes/codes.h"
#include "codes/configuration.h"
#include "codes/codes_mapping.h"
#include "codes/model-net.h"

15
#define TRACE -1
16 17 18 19 20 21 22 23 24

char workload_type[128];
char workload_file[8192];
char offset_file[8192];
static int wrkld_id;
static int num_net_traces = 0;

typedef struct nw_state nw_state;
typedef struct nw_message nw_message;
25
typedef int16_t dumpi_req_id;
26 27 28 29 30 31

static int net_id = 0;
static float noise = 5.0;
static int num_net_lps, num_nw_lps;
long long num_bytes_sent=0;
long long num_bytes_recvd=0;
32 33
double max_time = 0,  max_comm_time = 0, max_wait_time = 0, max_send_time = 0, max_recv_time = 0;
double avg_time = 0, avg_comm_time = 0, avg_wait_time = 0, avg_send_time = 0, avg_recv_time = 0;
34 35 36 37 38

/* global variables for codes mapping */
static char lp_group_name[MAX_NAME_LENGTH], lp_type_name[MAX_NAME_LENGTH], annotation[MAX_NAME_LENGTH];
static int mapping_grp_id, mapping_type_id, mapping_rep_id, mapping_offset;

39 40 41
/* MPI_OP_GET_NEXT is for getting next MPI operation when the previous operation completes.
* MPI_SEND_ARRIVED is issued when a MPI message arrives at its destination (the message is transported by model-net and an event is invoked when it arrives. 
* MPI_SEND_POSTED is issued when a MPI message has left the source LP (message is transported via model-net). */
42 43 44 45 46 47 48
enum MPI_NW_EVENTS
{
	MPI_OP_GET_NEXT=1,
	MPI_SEND_ARRIVED,
	MPI_SEND_POSTED,
};

49
/* stores pointers of pending MPI operations to be matched with their respective sends/receives. */
50 51
struct mpi_msgs_queue
{
52
	struct codes_workload_op* mpi_op;
53 54 55
	struct mpi_msgs_queue* next;
};

56
/* stores request IDs of completed MPI operations (Isends or Irecvs) */
57 58 59 60 61 62
struct completed_requests
{
	dumpi_req_id req_id;
	struct completed_requests* next;
};

63
/* for wait operations, store the pending operation and number of completed waits so far. */
64 65
struct pending_waits
{
66
	struct codes_workload_op* mpi_op;
67 68 69 70
	int num_completed;
	tw_stime start_time;
};

71
/* maintains the head and tail of the queue, as well as the number of elements currently in queue. Queues are pending_recvs queue (holds unmatched MPI recv operations) and arrival_queue (holds unmatched MPI send messages). */
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
struct mpi_queue_ptrs
{
	int num_elems;
	struct mpi_msgs_queue* queue_head;
	struct mpi_msgs_queue* queue_tail;
};

/* state of the network LP. It contains the pointers to send/receive lists */
struct nw_state
{
	long num_events_per_lp;
	tw_lpid nw_id;
	short wrkld_end;

	/* count of sends, receives, collectives and delays */
	unsigned long num_sends;
	unsigned long num_recvs;
	unsigned long num_cols;
	unsigned long num_delays;
91 92 93
	unsigned long num_wait;
	unsigned long num_waitall;
	unsigned long num_waitsome;
94 95

	/* time spent by the LP in executing the app trace*/
96 97
	double elapsed_time;

98
	/* time spent in compute operations */
99 100 101 102 103 104 105 106 107 108 109 110 111
	double compute_time;

	/* search time */
	double search_overhead;

	/* time spent in message send/isend */
	double send_time;

	/* time spent in message receive */
	double recv_time;
	
	/* time spent in wait operation */
	double wait_time;
112 113 114

	/* FIFO for isend messages arrived on destination */
	struct mpi_queue_ptrs* arrival_queue;
115

116 117
	/* FIFO for irecv messages posted but not yet matched with send operations */
	struct mpi_queue_ptrs* pending_recvs_queue;
118

119
	/* list of pending waits (and saved pending wait for reverse computation) */
120 121 122 123
	struct pending_waits* pending_waits;

	/* List of completed send/receive requests */
	struct completed_requests* completed_reqs;
124 125
};

126 127 128 129
/* data for handling reverse computation.
* saved_matched_req holds the request ID of matched receives/sends for wait operations.
* ptr_match_op holds the matched MPI operation which are removed from the queues when a send is matched with the receive in forward event handler. 
* network event being sent. op is the MPI operation issued by the network workloads API. rv_data holds the data for reverse computation (TODO: Fill this data structure only when the simulation runs in optimistic mode). */
130 131
struct nw_message
{
132 133 134
   int msg_type;
   /* for reverse computation */
   struct codes_workload_op * op;
135

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
   struct
   {
     /* forward event handler */
     struct
     {
        int op_type;
        tw_lpid src_rank;
        tw_lpid dest_rank;
        int num_bytes;
        int data_type;
        double sim_start_time;
        int16_t req_id;   
        int tag;
     } msg_info;

     /* required for reverse computation*/
     struct 
      {
154 155 156
	int found_match;
	short matched_op;
	dumpi_req_id saved_matched_req;
157
	struct codes_workload_op* ptr_match_op;
158 159 160 161 162
	struct pending_waits* saved_pending_wait;

	double saved_send_time;
	double saved_recv_time;
	double saved_wait_time;
163 164
      } rc;
  } u;
165 166
};

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
/* executes MPI wait operation */
static void codes_exec_mpi_wait(nw_state* s, tw_bf* bf, nw_message* m, tw_lp* lp);

/* reverse of mpi wait function. */
static void codes_exec_mpi_wait_rc(nw_state* s, tw_bf* bf, nw_message* m, tw_lp* lp);

/* executes MPI isend and send operations */
static void codes_exec_mpi_send(nw_state* s, nw_message* m, tw_lp* lp);

/* execute MPI irecv operation */
static void codes_exec_mpi_recv(nw_state* s, nw_message* m, tw_lp* lp);

/* reverse of mpi recv function. */
static void codes_exec_mpi_recv_rc(nw_state* s, nw_message* m, tw_lp* lp);

/* execute the computational delay */
static void codes_exec_comp_delay(nw_state* s, nw_message* m, tw_lp* lp);

/* execute collective operation, currently only skips these operations. */
static void codes_exec_mpi_col(nw_state* s, nw_message* m, tw_lp* lp);

/* gets the next MPI operation from the network-workloads API. */
189 190
static void get_next_mpi_operation(nw_state* s, tw_bf * bf, nw_message * m, tw_lp * lp);

191 192 193 194 195 196 197
/* reverse handler of get next mpi operation. */
static void get_next_mpi_operation_rc(nw_state* s, tw_bf * bf, nw_message * m, tw_lp * lp);

/* Makes a call to get_next_mpi_operation. */
static void codes_issue_next_event(tw_lp* lp);

///////////////////// HELPER FUNCTIONS FOR MPI MESSAGE QUEUE HANDLING ///////////////
198 199 200 201 202 203 204 205 206 207 208 209
/* upon arrival of local completion message, inserts operation in completed send queue */
static void update_send_completion_queue(nw_state*s, tw_bf* bf, nw_message* m, tw_lp * lp);

/* reverse of the above function */
static void update_send_completion_queue_rc(nw_state*s, tw_bf* bf, nw_message* m, tw_lp * lp);

/* upon arrival of an isend operation, updates the arrival queue of the network */
static void update_arrival_queue(nw_state*s, tw_bf* bf, nw_message* m, tw_lp * lp);

/* reverse of the above function */
static void update_arrival_queue_rc(nw_state*s, tw_bf* bf, nw_message* m, tw_lp * lp);

210
/* insert MPI operation in the waiting queue*/
211
static void mpi_pending_queue_insert_op(struct mpi_queue_ptrs* mpi_queue, struct codes_workload_op* mpi_op);
212

213
/* remove completed request IDs from the queue for reuse. Reverse of above function. */
214
static void remove_req_id(struct completed_requests** requests, int16_t req_id);
215

216
/* remove MPI operation from the waiting queue.*/
217
static int mpi_queue_remove_matching_op(nw_state* s, tw_lp* lp, struct mpi_queue_ptrs* mpi_queue, nw_message * m);
218

219
/* remove the tail of the MPI operation from waiting queue */
220
static int mpi_queue_remove_tail(tw_lpid lpid, struct mpi_queue_ptrs* mpi_queue);
221

222
/* insert completed MPI requests in the queue. */
223
static void mpi_completed_queue_insert_op(struct completed_requests** mpi_completed_queue, dumpi_req_id req_id);
224

225 226
/* notifies the wait operations (if any) about the completed receives and sends requests. */
static int notify_waits(nw_state* s, tw_bf* bf, tw_lp* lp, nw_message* m, dumpi_req_id req_id);
227

228 229
/* reverse of notify waits function. */
static void notify_waits_rc(nw_state* s, tw_bf* bf, tw_lp* lp, nw_message* m, dumpi_req_id completed_req);
230

231 232
/* conversion from seconds to eanaoseconds */
static tw_stime s_to_ns(tw_stime ns);
233

234

235 236 237 238 239 240 241 242 243 244 245 246
/* initializes the queue and allocates memory */
static struct mpi_queue_ptrs* queue_init()
{
	struct mpi_queue_ptrs* mpi_queue = malloc(sizeof(struct mpi_queue_ptrs));

	mpi_queue->num_elems = 0;
	mpi_queue->queue_head = NULL;
	mpi_queue->queue_tail = NULL;
	
	return mpi_queue;
}

247
/* helper function: counts number of elements in the queue */
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
static int numQueue(struct mpi_queue_ptrs* mpi_queue)
{
	struct mpi_msgs_queue* tmp = malloc(sizeof(struct mpi_msgs_queue)); 
	assert(tmp);

	tmp = mpi_queue->queue_head;
	int count = 0;

	while(tmp)
	{
		++count;
		tmp = tmp->next;
	}
	return count;
	free(tmp);
}

/* prints elements in a send/recv queue */
static void printQueue(tw_lpid lpid, struct mpi_queue_ptrs* mpi_queue, char* msg)
{
	printf("\n ************ Printing the queue %s *************** ", msg);
	struct mpi_msgs_queue* tmp = malloc(sizeof(struct mpi_msgs_queue));
	assert(tmp);

	tmp = mpi_queue->queue_head;
	
	while(tmp)
	{
276
		if(tmp->mpi_op->op_type == CODES_WK_SEND || tmp->mpi_op->op_type == CODES_WK_ISEND)
277 278 279
			printf("\n lpid %ld send operation data type %d count %d tag %d source %d", 
				    lpid, tmp->mpi_op->u.send.data_type, tmp->mpi_op->u.send.count, 
				     tmp->mpi_op->u.send.tag, tmp->mpi_op->u.send.source_rank);
280
		else if(tmp->mpi_op->op_type == CODES_WK_IRECV || tmp->mpi_op->op_type == CODES_WK_RECV)
281 282 283 284 285 286 287 288 289 290 291
			printf("\n lpid %ld recv operation data type %d count %d tag %d source %d", 
				   lpid, tmp->mpi_op->u.recv.data_type, tmp->mpi_op->u.recv.count, 
				    tmp->mpi_op->u.recv.tag, tmp->mpi_op->u.recv.source_rank );
		else
			printf("\n Invalid data type in the queue %d ", tmp->mpi_op->op_type);
		tmp = tmp->next;
	}
	free(tmp);
}

/* re-insert element in the queue at the index --- maintained for reverse computation */
292
static void mpi_queue_update(struct mpi_queue_ptrs* mpi_queue, struct codes_workload_op* mpi_op, int pos)
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
{
	struct mpi_msgs_queue* elem = malloc(sizeof(struct mpi_msgs_queue));
	assert(elem);
	elem->mpi_op = mpi_op;
	
	/* inserting at the head */
	if(pos == 0)
	{
	   if(!mpi_queue->queue_tail)
		mpi_queue->queue_tail = elem;
	   elem->next = mpi_queue->queue_head;
	   mpi_queue->queue_head = elem;
	   mpi_queue->num_elems++;
	   return;
	}

	int index = 0;
	struct mpi_msgs_queue* tmp = mpi_queue->queue_head;
	while(index < pos - 1)
	{
		tmp = tmp->next;
		++index;
	}

	if(!tmp)
		printf("\n Invalid index! %d pos %d size %d ", index, pos, numQueue(mpi_queue));
	if(tmp == mpi_queue->queue_tail)
	    mpi_queue->queue_tail = elem;

	elem->next = tmp->next;
	tmp->next = elem;
	mpi_queue->num_elems++;

	return;
}

329
/* prints the elements of a queue (for debugging purposes). */
330 331 332 333
static void printCompletedQueue(nw_state* s, tw_lp* lp)
{
	   if(TRACE == lp->gid)
	   {
334
	   	printf("\n %lf contents of completed operations queue ", tw_now(lp));
335 336 337 338 339 340 341 342 343
	   	struct completed_requests* current = s->completed_reqs;
	   	while(current)
	    	{
			printf(" %d ",current->req_id);
			current = current->next;
	   	}
	   }
}

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
/* reverse handler of notify_waits function. */
static void notify_waits_rc(nw_state* s, tw_bf* bf, tw_lp* lp, nw_message* m, dumpi_req_id completed_req)
{
   int i;

   /*if(bf->c1)
    {*/
	/* if pending wait is still present and is of type MPI_WAIT then do nothing*/
/*	s->wait_time = s->saved_wait_time; 	
	mpi_completed_queue_insert_op(&s->completed_reqs, completed_req);	
	s->pending_waits = wait_elem;
	s->saved_pending_wait = NULL;
    }
*/
  if(lp->gid == TRACE)
	  printf("\n %lf reverse -- notify waits req id %d ", tw_now(lp), completed_req);
  printCompletedQueue(s, lp);
361
  if(m->u.rc.matched_op == 1)
362 363
	s->pending_waits->num_completed--;
   /* if a wait-elem exists, it means the request ID has been matched*/
364
   if(m->u.rc.matched_op == 2) 
365 366 367 368 369 370
    {
	if(lp->gid == TRACE)
	{
		printf("\n %lf matched req id %d ", tw_now(lp), completed_req);
		printCompletedQueue(s, lp);
	}
371 372
        struct pending_waits* wait_elem = m->u.rc.saved_pending_wait;
	s->wait_time = m->u.rc.saved_wait_time;
373 374 375 376 377 378 379 380 381 382 383 384 385 386
	int count = wait_elem->mpi_op->u.waits.count; 

	for( i = 0; i < count; i++ )
		mpi_completed_queue_insert_op(&s->completed_reqs, wait_elem->mpi_op->u.waits.req_ids[i]);

	wait_elem->num_completed--;	
	s->pending_waits = wait_elem;
	tw_rand_reverse_unif(lp->rng);

   }
}

/* notify the completed send/receive request to the wait operation. */
static int notify_waits(nw_state* s, tw_bf* bf, tw_lp* lp, nw_message* m, dumpi_req_id completed_req)
387 388 389 390 391 392 393
{
	int i;
	/* traverse the pending waits list and look what type of wait operations are 
	there. If its just a single wait and the request ID has just been completed, 
	then the network node LP can go on with fetching the next operation from the log.
	If its waitall then wait for all pending requests to complete and then proceed. */
	struct pending_waits* wait_elem = s->pending_waits;
394
	m->u.rc.matched_op = 0;
395 396 397
	
	if(lp->gid == TRACE)
		printf("\n %lf notify waits req id %d ", tw_now(lp), completed_req);
398 399 400

	if(!wait_elem)
		return 0;
401

402 403
	int op_type = wait_elem->mpi_op->op_type;

404
	if(op_type == CODES_WK_WAIT)
405 406 407
	{
		if(wait_elem->mpi_op->u.wait.req_id == completed_req)	
		  {
408
			m->u.rc.saved_wait_time = s->wait_time;
409
			s->wait_time += (tw_now(lp) - wait_elem->start_time);
410
                        remove_req_id(&s->completed_reqs, completed_req);
411
	
412
			m->u.rc.saved_pending_wait = wait_elem;			
413 414 415 416 417 418
			s->pending_waits = NULL;
			codes_issue_next_event(lp);	
			return 0;
		 }
	}
	else
419
	if(op_type == CODES_WK_WAITALL)
420
	{
421 422
	   int required_count = wait_elem->mpi_op->u.waits.count;
	  for(i = 0; i < required_count; i++)
423 424
	   {
	    if(wait_elem->mpi_op->u.waits.req_ids[i] == completed_req)
425 426 427
		{
			if(lp->gid == TRACE)
				printCompletedQueue(s, lp);
428
			m->u.rc.matched_op = 1;
429
			wait_elem->num_completed++;	
430
		}
431 432
	   }
	   
433
	    if(wait_elem->num_completed == required_count)
434
	     {
435 436 437 438 439
		if(lp->gid == TRACE)
		{
			printf("\n %lf req %d completed %d", tw_now(lp), completed_req, wait_elem->num_completed);
			printCompletedQueue(s, lp);
		}
440 441
		m->u.rc.matched_op = 2;
		m->u.rc.saved_wait_time = s->wait_time;
442
		s->wait_time += (tw_now(lp) - wait_elem->start_time);
443
		m->u.rc.saved_pending_wait = wait_elem;
444
		s->pending_waits = NULL; 
445
		for(i = 0; i < required_count; i++)
446 447 448
			remove_req_id(&s->completed_reqs, wait_elem->mpi_op->u.waits.req_ids[i]);	
		codes_issue_next_event(lp); //wait completed
	    }
449
       }
450 451 452
	return 0;
}

453 454 455 456 457 458 459 460 461 462
/* reverse handler of MPI wait operation */
static void codes_exec_mpi_wait_rc(nw_state* s, tw_bf* bf, nw_message* m, tw_lp* lp)
{
    if(s->pending_waits)
     {
    	s->pending_waits = NULL;
	return;
     }
   else
    {
463 464
	s->wait_time = m->u.rc.saved_wait_time;
 	mpi_completed_queue_insert_op(&s->completed_reqs, m->op->u.wait.req_id);	
465 466 467
	tw_rand_reverse_unif(lp->rng);		
    }
}
468 469

/* execute MPI wait operation */
470
static void codes_exec_mpi_wait(nw_state* s, tw_bf* bf, nw_message* m, tw_lp* lp)
471 472 473
{
/* check in the completed receives queue if the request ID has already been completed.*/

474
   assert(!s->pending_waits);
475
   dumpi_req_id req_id = m->op->u.wait.req_id;
476 477 478 479 480

   unsigned long search_start_time, search_end_time;
   struct completed_requests* current = s->completed_reqs; 
   search_start_time = tw_now(lp);
   while(current)
481
    {
482 483 484
	if(current->req_id == req_id)
	   {
		remove_req_id(&s->completed_reqs, req_id);
485
		m->u.rc.saved_wait_time = s->wait_time;
486 487 488 489 490
		s->wait_time += tw_now(lp) - search_start_time;
		codes_issue_next_event(lp);
		return;	
	   }
	current = current->next;		
491 492 493 494 495 496 497 498 499 500
    }
   search_end_time = tw_now(lp);
   s->search_overhead += (search_end_time - search_start_time);

   /* If not, add the wait operation in the pending 'waits' list. */
    struct pending_waits* wait_op = malloc(sizeof(struct pending_waits));
    wait_op->mpi_op = m->op;  
    wait_op->num_completed = 0; 
    wait_op->start_time = search_start_time;
    s->pending_waits = wait_op;
501 502
}

503
static void codes_exec_mpi_wait_all_rc(nw_state* s, tw_bf* bf, nw_message* m, tw_lp* lp)
504
{
505 506
   if(lp->gid == TRACE)
  {
507
   printf("\n %lf codes exec mpi waitall reverse %d ", tw_now(lp), m->u.rc.found_match);
508 509
   printCompletedQueue(s, lp); 
  } 
510
  if(m->u.rc.found_match)
511 512
    {
   	int i;
513 514
	s->wait_time = m->u.rc.saved_wait_time;
	int count = m->op->u.waits.count;
515 516 517 518
	dumpi_req_id req_id[count];

	for( i = 0; i < count; i++)
	{
519
		req_id[i] = m->op->u.waits.req_ids[i];
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
		mpi_completed_queue_insert_op(&s->completed_reqs, req_id[i]);
	}
	tw_rand_reverse_unif(lp->rng);
    }
    else
    {
	struct pending_waits* wait_op = s->pending_waits;
	free(wait_op);
	s->pending_waits = NULL;
	assert(!s->pending_waits);
	if(lp->gid == TRACE)
		printf("\n %lf Nullifying codes waitall ", tw_now(lp));
    }
}
static void codes_exec_mpi_wait_all(nw_state* s, tw_bf* bf, nw_message* m, tw_lp* lp)
{
  //assert(!s->pending_waits);
537
  int count = m->op->u.waits.count;
538 539 540 541 542 543 544 545 546 547
  int i, num_completed = 0;
  dumpi_req_id req_id[count];
  struct completed_requests* current = s->completed_reqs;

  /* check number of completed irecvs in the completion queue */ 
  unsigned long start_time, search_end_time;
  start_time = tw_now(lp);

  if(lp->gid == TRACE)
    {
548
  	printf(" \n (%lf) MPI waitall posted %d count", tw_now(lp), m->op->u.waits.count);
549
	for(i = 0; i < count; i++)
550
		printf(" %d ", (int)m->op->u.waits.req_ids[i]);
551 552 553 554 555 556
   	printCompletedQueue(s, lp);	 
   }
  while(current) 
   {
	  for(i = 0; i < count; i++)
	   {
557
	     req_id[i] = m->op->u.waits.req_ids[i];
558 559 560 561 562 563 564 565 566
	     if(req_id[i] == current->req_id)
 		 num_completed++;
   	  }
	 current = current->next;
   }

  search_end_time = tw_now(lp);

  if(TRACE== lp->gid)
567
	  printf("\n %lf Num completed %d count %d ", tw_now(lp), num_completed, count);
568 569

  s->search_overhead += (search_end_time - start_time);
570

571
  m->u.rc.found_match = 0;
572
  if(count == num_completed)
573
  {
574
	m->u.rc.found_match = 1;
575
	for( i = 0; i < count; i++)	
576
		remove_req_id(&s->completed_reqs, req_id[i]);
577

578
	m->u.rc.saved_wait_time = s->wait_time;	
579 580 581 582 583 584 585
	s->wait_time += tw_now(lp) - start_time;
	codes_issue_next_event(lp);
  }
  else
  {
 	/* If not, add the wait operation in the pending 'waits' list. */
	  struct pending_waits* wait_op = malloc(sizeof(struct pending_waits));
586
	  wait_op->mpi_op = m->op;  
587 588 589 590 591 592 593 594 595 596 597 598
	  wait_op->num_completed = num_completed;
	  wait_op->start_time = start_time;
	  s->pending_waits = wait_op;
  }
}

/* request ID is being reused so delete it from the list once the matching is done */
static void remove_req_id(struct completed_requests** mpi_completed_queue, dumpi_req_id req_id)
{
	struct completed_requests* current = *mpi_completed_queue;

	if(!current)
599 600 601
		tw_error(TW_LOC, "\n REQ ID DOES NOT EXIST");
	
       if(current->req_id == req_id)
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
	{
		*mpi_completed_queue = current->next;
		free(current);
		return;
	}
	
	struct completed_requests* elem;
	while(current->next)
	{
	   elem = current->next;
	   if(elem->req_id == req_id)	
	     {
		current->next = elem->next;
		free(elem);
		return;
	     }
	   current = current->next;	
	}
	return;
}

/* inserts mpi operation in the completed requests queue */
624
static void mpi_completed_queue_insert_op(struct completed_requests** mpi_completed_queue, dumpi_req_id req_id)
625 626 627 628 629 630 631 632
{
	struct completed_requests* reqs = malloc(sizeof(struct completed_requests));
	assert(reqs);

	reqs->req_id = req_id;

	if(!(*mpi_completed_queue))	
	{
633
			reqs->next = NULL;
634
			*mpi_completed_queue = reqs;
635
			return;
636 637 638
	}
	reqs->next = *mpi_completed_queue;
	*mpi_completed_queue = reqs;
639
	return;
640 641
}

642
/* insert MPI send or receive operation in the queues starting from tail. Unmatched sends go to arrival queue and unmatched receives go to pending receives queues. */
643
static void mpi_pending_queue_insert_op(struct mpi_queue_ptrs* mpi_queue, struct codes_workload_op* mpi_op)
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
{
	/* insert mpi operation */
	struct mpi_msgs_queue* elem = malloc(sizeof(struct mpi_msgs_queue));
	assert(elem);

	elem->mpi_op = mpi_op;
     	elem->next = NULL;

	if(!mpi_queue->queue_head)
	  mpi_queue->queue_head = elem;

	if(mpi_queue->queue_tail)
	    mpi_queue->queue_tail->next = elem;
	
        mpi_queue->queue_tail = elem;
	mpi_queue->num_elems++;

	return;
}

/* match the send/recv operations */
665
static int match_receive(nw_state* s, tw_lp* lp, tw_lpid lpid, struct codes_workload_op* op1, struct codes_workload_op* op2)
666
{
667 668 669 670 671 672 673 674 675 676 677 678 679 680
        assert(op1->op_type == CODES_WK_IRECV || op1->op_type == CODES_WK_RECV);
        assert(op2->op_type == CODES_WK_SEND || op2->op_type == CODES_WK_ISEND);

        if((op1->u.recv.num_bytes >= op2->u.send.num_bytes) &&
                   ((op1->u.recv.tag == op2->u.send.tag) || op1->u.recv.tag == -1) &&
                   ((op1->u.recv.source_rank == op2->u.send.source_rank) || op1->u.recv.source_rank == -1))
                   {
                        if(lp->gid == TRACE)
                           printf("\n op1 rank %d bytes %d ", op1->u.recv.source_rank, op1->u.recv.num_bytes);
                        s->recv_time += tw_now(lp) - op2->sim_start_time;
                        mpi_completed_queue_insert_op(&s->completed_reqs, op1->u.recv.req_id);
                        return 1;
                   }
        return -1;
681 682 683
}

/* used for reverse computation. removes the tail of the queue */
684
static int mpi_queue_remove_tail(tw_lpid lpid, struct mpi_queue_ptrs* mpi_queue)
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
{
	assert(mpi_queue->queue_tail);
	if(mpi_queue->queue_tail == NULL)
	{
		printf("\n Error! tail not updated ");	
		return 0;
	}
	struct mpi_msgs_queue* tmp = mpi_queue->queue_head;

	if(mpi_queue->queue_head == mpi_queue->queue_tail)
	{
		mpi_queue->queue_head = NULL;
		mpi_queue->queue_tail = NULL;
		free(tmp);
		mpi_queue->num_elems--;
		 return 1;
	}

	struct mpi_msgs_queue* elem = mpi_queue->queue_tail;

	while(tmp->next != mpi_queue->queue_tail)
		tmp = tmp->next;

	mpi_queue->queue_tail = tmp;
	mpi_queue->queue_tail->next = NULL;
	mpi_queue->num_elems--;

	free(elem);
	return 1;
}

/* search for a matching mpi operation and remove it from the list. 
 * Record the index in the list from where the element got deleted. 
 * Index is used for inserting the element once again in the queue for reverse computation. */
719
static int mpi_queue_remove_matching_op(nw_state* s, tw_lp* lp, struct mpi_queue_ptrs* mpi_queue, nw_message * m)
720
{
721 722
       struct codes_workload_op * mpi_op = m->op;
 
723 724 725 726 727 728 729 730
	if(mpi_queue->queue_head == NULL)
		return -1;

	/* remove mpi operation */
	struct mpi_msgs_queue* tmp = mpi_queue->queue_head;
	int indx = 0;

	/* if head of the list has the required mpi op to be deleted */
731
	int rcv_val = 0;
732
	if(mpi_op->op_type == CODES_WK_SEND || mpi_op->op_type == CODES_WK_ISEND)
733
	  {
734
		rcv_val = match_receive(s, lp, lp->gid, tmp->mpi_op, mpi_op);
735
		m->u.rc.saved_matched_req = tmp->mpi_op->u.recv.req_id;  
736
	 }
737
	else if(mpi_op->op_type == CODES_WK_RECV || mpi_op->op_type == CODES_WK_IRECV)
738
	  {
739
		rcv_val = match_receive(s, lp, lp->gid, mpi_op, tmp->mpi_op);
740
	  	m->u.rc.saved_matched_req = mpi_op->u.recv.req_id;
741 742
	  }
	if(rcv_val >= 0)
743
	{
744
		memcpy(&m->u.rc.ptr_match_op, &tmp->mpi_op, sizeof(struct codes_workload_op));
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
		if(mpi_queue->queue_head == mpi_queue->queue_tail)
		   {
			mpi_queue->queue_tail = NULL;
			mpi_queue->queue_head = NULL;
			 free(tmp);
		   }
		 else
		   {
			mpi_queue->queue_head = tmp->next;
			free(tmp);	
		   }
		mpi_queue->num_elems--;
		return indx;
	}

	/* record the index where matching operation has been found */
	struct mpi_msgs_queue* elem;

	while(tmp->next)	
	{
	   indx++;
	   elem = tmp->next;
767
	   
768
	    if(mpi_op->op_type == CODES_WK_SEND || mpi_op->op_type == CODES_WK_ISEND)
769
	     {
770
		rcv_val = match_receive(s, lp, lp->gid, elem->mpi_op, mpi_op);
771
	     	m->u.rc.saved_matched_req = elem->mpi_op->u.recv.req_id; 
772
	     }
773
	    else if(mpi_op->op_type == CODES_WK_RECV || mpi_op->op_type == CODES_WK_IRECV)
774
	     {
775
		rcv_val = match_receive(s, lp, lp->gid, mpi_op, elem->mpi_op);
776
		m->u.rc.saved_matched_req = mpi_op->u.recv.req_id;
777 778
	     }
   	     if(rcv_val >= 0)
779
		{
780
		    memcpy(&m->u.rc.ptr_match_op, &elem->mpi_op, sizeof(struct codes_workload_op));
781 782
		    if(elem == mpi_queue->queue_tail)
			mpi_queue->queue_tail = tmp;
783
		    
784 785 786 787
		    tmp->next = elem->next;

		    free(elem);
		    mpi_queue->num_elems--;
788
		
789 790 791
		    return indx;
		}
	   tmp = tmp->next;
792
        }
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
	return -1;
}
/* Trigger getting next event at LP */
static void codes_issue_next_event(tw_lp* lp)
{
   tw_event *e;
   nw_message* msg;

   tw_stime ts;

   ts = g_tw_lookahead + 0.1 + tw_rand_exponential(lp->rng, noise);
   e = tw_event_new( lp->gid, ts, lp );
   msg = tw_event_data(e);

   msg->msg_type = MPI_OP_GET_NEXT;
   tw_event_send(e);
}

/* Simulate delays between MPI operations */
static void codes_exec_comp_delay(nw_state* s, nw_message* m, tw_lp* lp)
{
814
	struct codes_workload_op* mpi_op = m->op;
815 816 817 818
	tw_event* e;
	tw_stime ts;
	nw_message* msg;

819 820
	s->compute_time += s_to_ns(mpi_op->u.delay.seconds);
	ts = s_to_ns(mpi_op->u.delay.seconds) + g_tw_lookahead + 0.1;
821 822 823 824 825 826 827 828 829 830
	ts += tw_rand_exponential(lp->rng, noise);
	
	e = tw_event_new( lp->gid, ts , lp );
	msg = tw_event_data(e);
	msg->msg_type = MPI_OP_GET_NEXT;

	tw_event_send(e); 
}

/* reverse computation operation for MPI irecv */
831
static void codes_exec_mpi_recv_rc(nw_state* s, nw_message* m, tw_lp* lp)
832
{
833 834 835
	num_bytes_recvd -= m->op->u.recv.num_bytes;
	s->recv_time = m->u.rc.saved_recv_time;
	if(m->u.rc.found_match >= 0)
836
	  {
837 838 839
		s->recv_time = m->u.rc.saved_recv_time;
		mpi_queue_update(s->arrival_queue, m->u.rc.ptr_match_op, m->u.rc.found_match);
		remove_req_id(&s->completed_reqs, m->op->u.recv.req_id);
840
		tw_rand_reverse_unif(lp->rng);
841
	  }
842
	else if(m->u.rc.found_match < 0)
843
	    {
844 845
		mpi_queue_remove_tail(lp->gid, s->pending_recvs_queue);
		if(m->op->op_type == CODES_WK_IRECV)
846
			tw_rand_reverse_unif(lp->rng);
847 848 849 850
	    }
}

/* Execute MPI Irecv operation (non-blocking receive) */ 
851
static void codes_exec_mpi_recv(nw_state* s, nw_message* m, tw_lp* lp)
852 853 854 855 856
{
/* Once an irecv is posted, list of completed sends is checked to find a matching isend.
   If no matching isend is found, the receive operation is queued in the pending queue of
   receive operations. */

857 858
	m->u.rc.saved_recv_time = s->recv_time;
	struct codes_workload_op* mpi_op = m->op;
859 860
	mpi_op->sim_start_time = tw_now(lp);
	unsigned long long start_searching, end_searching; 
861
	num_bytes_recvd += mpi_op->u.recv.num_bytes;
862 863

	if(lp->gid == TRACE)
864
		printf("\n %lf codes exec mpi recv req id %d", tw_now(lp), (int)mpi_op->u.recv.req_id);
865 866 867
	
	start_searching = tw_now(lp);  
	dumpi_req_id req_id;
868
	int found_matching_sends = mpi_queue_remove_matching_op(s, lp, s->arrival_queue, m);
869 870 871 872 873
	
	/* save the req id inserted in the completed queue for reverse computation. */
	//m->matched_recv = req_id;
	end_searching = tw_now(lp); 
	s->search_overhead += (end_searching - start_searching); 
874 875 876

	if(found_matching_sends < 0)
	  {
877
		m->u.rc.found_match = -1;
878 879 880
		mpi_pending_queue_insert_op(s->pending_recvs_queue, mpi_op);
	
	       /* for mpi irecvs, this is a non-blocking receive so just post it and move on with the trace read. */
881
		if(mpi_op->op_type == CODES_WK_IRECV)
882 883 884 885 886 887
		   {
			codes_issue_next_event(lp);	
			return;
		   }
		else
			printf("\n CODES MPI RECV OPERATION!!! ");
888
	  }
889
	else
890 891
	  {
		/*if(lp->gid == TRACE)
892 893 894 895
			printf("\n Matched after removing: arrival queue num_elems %d ", s->arrival_queue->num_elems);*/
		/* update completed requests list */
		//int count_after = numQueue(s->arrival_queue);
		//assert(count_before == (count_after+1));
896
	   	m->u.rc.found_match = found_matching_sends;
897
		codes_issue_next_event(lp); 
898 899 900 901
	 }
}

/* executes MPI send and isend operations */
902
static void codes_exec_mpi_send(nw_state* s, nw_message * m, tw_lp* lp)
903
{
904
        struct codes_workload_op * mpi_op = m->op; 
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
	/* model-net event */
	tw_lpid dest_rank;

	codes_mapping_get_lp_info(lp->gid, lp_group_name, &mapping_grp_id, 
	    lp_type_name, &mapping_type_id, annotation, &mapping_rep_id, &mapping_offset);

	if(net_id == DRAGONFLY) /* special handling for the dragonfly case */
	{
		int num_routers, lps_per_rep, factor;
		num_routers = codes_mapping_get_lp_count("MODELNET_GRP", 1,
                  "dragonfly_router", NULL, 1);
	 	lps_per_rep = (2 * num_nw_lps) + num_routers;	
		factor = mpi_op->u.send.dest_rank / num_nw_lps;
		dest_rank = (lps_per_rep * factor) + (mpi_op->u.send.dest_rank % num_nw_lps);	
	}
	else
	{
		/* other cases like torus/simplenet/loggp etc. */
		codes_mapping_get_lp_id(lp_group_name, lp_type_name, NULL, 1,  
	    	  mpi_op->u.send.dest_rank, mapping_offset, &dest_rank);
	}

	num_bytes_sent += mpi_op->u.send.num_bytes;

	nw_message* local_m = malloc(sizeof(nw_message));
	nw_message* remote_m = malloc(sizeof(nw_message));
	assert(local_m && remote_m);

933 934 935 936 937 938 939 940 941 942
        local_m->u.msg_info.sim_start_time = tw_now(lp);
        local_m->u.msg_info.dest_rank = mpi_op->u.send.dest_rank;
	local_m->u.msg_info.src_rank = mpi_op->u.send.source_rank;
        local_m->u.msg_info.op_type = mpi_op->op_type; 
        local_m->msg_type = MPI_SEND_POSTED;
        local_m->u.msg_info.tag = mpi_op->u.send.tag;
        local_m->u.msg_info.num_bytes = mpi_op->u.send.num_bytes;
        local_m->u.msg_info.req_id = mpi_op->u.send.req_id;

        memcpy(remote_m, local_m, sizeof(nw_message));
943
	remote_m->msg_type = MPI_SEND_ARRIVED;
944

945 946
	model_net_event(net_id, "test", dest_rank, mpi_op->u.send.num_bytes, 0.0, 
	    sizeof(nw_message), (const void*)remote_m, sizeof(nw_message), (const void*)local_m, lp);
947

948 949 950
	/*if(TRACE == lp->gid)	
		printf("\n !!! %lf send req id %d dest %d nw_message %d ", tw_now(lp), (int)mpi_op->u.send.req_id, (int)dest_rank, sizeof(nw_message));
	*/
951
	/* isend executed, now get next MPI operation from the queue */ 
952
	if(mpi_op->op_type == CODES_WK_ISEND)
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
	   codes_issue_next_event(lp);
}

/* MPI collective operations */
static void codes_exec_mpi_col(nw_state* s, nw_message* m, tw_lp* lp)
{
	codes_issue_next_event(lp);
}

/* convert seconds to ns */
static tw_stime s_to_ns(tw_stime ns)
{
    return(ns * (1000.0 * 1000.0 * 1000.0));
}


static void update_send_completion_queue_rc(nw_state* s, tw_bf * bf, nw_message * m, tw_lp * lp)
{
	//mpi_queue_remove_matching_op(&s->completed_isend_queue_head, &s->completed_isend_queue_tail, &m->op, SEND);
972
	if(m->u.msg_info.op_type == CODES_WK_SEND)
973
		tw_rand_reverse_unif(lp->rng);	
974

975
	if(m->u.msg_info.op_type == CODES_WK_ISEND)
976
	  {
977 978
		notify_waits_rc(s, bf, lp, m, m->u.msg_info.req_id);
		remove_req_id(&s->completed_reqs, m->u.msg_info.req_id);
979
	 }
980 981 982 983 984
}

/* completed isends are added in the list */
static void update_send_completion_queue(nw_state* s, tw_bf * bf, nw_message * m, tw_lp * lp)
{
985
	if(TRACE == lp->gid)
986 987
		printf("\n %lf isend operation completed req id %d ", tw_now(lp), m->u.msg_info.req_id);
	if(m->u.msg_info.op_type == CODES_WK_ISEND)
988
	   {	
989 990
		mpi_completed_queue_insert_op(&s->completed_reqs, m->u.msg_info.req_id);
	   	notify_waits(s, bf, lp, m, m->u.msg_info.req_id);
991 992
	   }  
	
993
	/* blocking send operation */
994
	if(m->u.msg_info.op_type == CODES_WK_SEND)
995 996 997 998 999 1000 1001 1002
		codes_issue_next_event(lp);	

	 return;
}

/* reverse handler for updating arrival queue function */
static void update_arrival_queue_rc(nw_state* s, tw_bf * bf, nw_message * m, tw_lp * lp)
{
1003 1004
	s->send_time = m->u.rc.saved_send_time;
	s->recv_time = m->u.rc.saved_recv_time;
1005

1006
	if(m->u.rc.found_match >= 0)
1007
	{
1008 1009
		// TODO: Modify for recvs
		if(lp->gid == TRACE)
1010 1011 1012
			printf("\n %lf reverse-- update arrival queue req ID %d", tw_now(lp), (int) m->u.rc.saved_matched_req);
		dumpi_req_id req_id = m->u.rc.saved_matched_req;
		notify_waits_rc(s, bf, lp, m, m->u.rc.saved_matched_req);
1013
		//int count = numQueue(s->pending_recvs_queue);
1014 1015
		mpi_queue_update(s->pending_recvs_queue, m->u.rc.ptr_match_op, m->u.rc.found_match);
		remove_req_id(&s->completed_reqs, m->u.rc.saved_matched_req);
1016
	
1017 1018 1019
		/*if(lp->gid == TRACE)
			printf("\n Reverse: after adding pending recvs queue %d ", s->pending_recvs_queue->num_elems);*/
	}
1020
	else if(m->u.rc.found_match < 0)
1021
	{
1022
		mpi_queue_remove_tail(lp->gid, s->arrival_queue);	
1023 1024 1025 1026 1027 1028 1029 1030
		/*if(lp->gid == TRACE)
			printf("\n Reverse: after removing arrivals queue %d ", s->arrival_queue->num_elems);*/
	}
}

/* once an isend operation arrives, the pending receives queue is checked to find out if there is a irecv that has already been posted. If no isend has been posted, */
static void update_arrival_queue(nw_state* s, tw_bf * bf, nw_message * m, tw_lp * lp)
{
1031 1032 1033
	//int count_before = numQueue(s->pending_recvs_queue);
	int is_blocking = 0; /* checks if the recv operation was blocking or not */
	unsigned long long start_searching, end_searching;
1034

1035