model-net-mpi-wrklds.c 46 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
#include "codes/codes.h"
#include "codes/configuration.h"
#include "codes/codes_mapping.h"
#include "codes/model-net.h"
14
#include "codes/rc-stack.h"
15

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

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

24 25 26 27 28 29
/* Doing LP IO*/
static char lp_io_dir[256] = {'\0'};
static lp_io_handle io_handle;
static unsigned int lp_io_use_suffix = 0;
static int do_lp_io = 0;

30 31
typedef struct nw_state nw_state;
typedef struct nw_message nw_message;
32
typedef int16_t dumpi_req_id;
33 34 35 36 37 38

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;
39 40
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;
41 42 43 44 45

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

46 47 48
/* runtime option for disabling computation time simulation */
static int disable_delay = 0;

49 50 51
/* 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). */
52 53 54 55
enum MPI_NW_EVENTS
{
	MPI_OP_GET_NEXT=1,
	MPI_SEND_ARRIVED,
56
    MPI_SEND_ARRIVED_CB, // for tracking message times on sender
57 58 59
	MPI_SEND_POSTED,
};

60
/* stores pointers of pending MPI operations to be matched with their respective sends/receives. */
61 62
struct mpi_msgs_queue
{
63 64
	struct codes_workload_op * mpi_op;
	struct mpi_msgs_queue * next;
65 66
};

67
/* stores request IDs of completed MPI operations (Isends or Irecvs) */
68 69 70
struct completed_requests
{
	dumpi_req_id req_id;
71
	struct completed_requests * next;
72 73
};

74
/* for wait operations, store the pending operation and number of completed waits so far. */
75 76
struct pending_waits
{
77
	struct codes_workload_op * mpi_op;
78 79 80 81
	int num_completed;
	tw_stime start_time;
};

82
/* 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). */
83 84 85 86 87 88 89 90 91 92 93 94 95 96
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;

97
    struct rc_stack * st;
98 99 100 101 102
	/* count of sends, receives, collectives and delays */
	unsigned long num_sends;
	unsigned long num_recvs;
	unsigned long num_cols;
	unsigned long num_delays;
103 104 105
	unsigned long num_wait;
	unsigned long num_waitall;
	unsigned long num_waitsome;
106 107

	/* time spent by the LP in executing the app trace*/
108
	double start_time;
109
	double elapsed_time;
110
	/* time spent in compute operations */
111 112 113 114 115 116 117
	double compute_time;
	/* 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;
118
	/* FIFO for isend messages arrived on destination */
119
	struct mpi_queue_ptrs * arrival_queue;
120
	/* FIFO for irecv messages posted but not yet matched with send operations */
121
	struct mpi_queue_ptrs * pending_recvs_queue;
122
	/* list of pending waits (and saved pending wait for reverse computation) */
123
	struct pending_waits * pending_waits;
124
	/* List of completed send/receive requests */
125
	struct completed_requests * completed_reqs;
126 127
};

128 129 130 131
/* 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). */
132 133
struct nw_message
{
134
   int msg_type;
135

136 137 138 139 140 141 142 143 144 145 146
   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;
147 148
        // for callbacks - time message was received
        double msg_send_time;
149 150 151 152 153 154 155
        int16_t req_id;   
        int tag;
     } msg_info;

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

        double saved_send_time;
        double saved_recv_time;
        double saved_wait_time;
166 167
      } rc;
  } u;
168 169
};

170
/* executes MPI wait operation */
171 172
static void codes_exec_mpi_wait(
        nw_state* s, tw_lp* lp, nw_message * m, struct codes_workload_op * mpi_op);
173
/* reverse of mpi wait function. */
174
static void codes_exec_mpi_wait_rc(
175
        nw_state* s, nw_message* m, tw_lp* lp, struct codes_workload_op * mpi_op);
176
/* executes MPI isend and send operations */
177 178
static void codes_exec_mpi_send(
        nw_state* s, tw_lp* lp, struct codes_workload_op * mpi_op);
179
/* execute MPI irecv operation */
180 181
static void codes_exec_mpi_recv(
        nw_state* s, tw_lp* lp, nw_message * m, struct codes_workload_op * mpi_op);
182
/* reverse of mpi recv function. */
183
static void codes_exec_mpi_recv_rc(
184
        nw_state* s, nw_message* m, tw_lp* lp, struct codes_workload_op * mpi_op);
185
/* execute the computational delay */
186 187
static void codes_exec_comp_delay(
        nw_state* s, tw_lp* lp, struct codes_workload_op * mpi_op);
188
/* execute collective operation, currently only skips these operations. */
189 190
static void codes_exec_mpi_col(
        nw_state* s, tw_lp* lp);
191
/* gets the next MPI operation from the network-workloads API. */
192 193
static void get_next_mpi_operation(
        nw_state* s, tw_bf * bf, nw_message * m, tw_lp * lp);
194
/* reverse handler of get next mpi operation. */
195 196
static void get_next_mpi_operation_rc(
        nw_state* s, tw_bf * bf, nw_message * m, tw_lp * lp);
197 198 199 200
/* Makes a call to get_next_mpi_operation. */
static void codes_issue_next_event(tw_lp* lp);

///////////////////// HELPER FUNCTIONS FOR MPI MESSAGE QUEUE HANDLING ///////////////
201
/* upon arrival of local completion message, inserts operation in completed send queue */
202 203
static void update_send_completion_queue(
        nw_state*s, tw_bf* bf, nw_message* m, tw_lp * lp);
204
/* reverse of the above function */
205 206
static void update_send_completion_queue_rc(
        nw_state*s, tw_bf* bf, nw_message* m, tw_lp * lp);
207
/* upon arrival of an isend operation, updates the arrival queue of the network */
208 209
static void update_arrival_queue(
        nw_state*s, tw_bf* bf, nw_message* m, tw_lp * lp);
210
/* reverse of the above function */
211 212
static void update_arrival_queue_rc(
        nw_state*s, tw_bf* bf, nw_message* m, tw_lp * lp);
213
/* callback to a message sender for computing message time */
214 215 216 217 218
static void update_message_time(
        nw_state*s, tw_bf* bf, nw_message* m, tw_lp * lp);
/* reverse for computing message time */
static void update_message_time_rc(
        nw_state*s, tw_bf* bf, nw_message* m, tw_lp * lp);
219

220
/* insert MPI operation in the waiting queue*/
221 222
static void mpi_pending_queue_insert_op(
        struct mpi_queue_ptrs* mpi_queue, struct codes_workload_op* mpi_op);
223
/* remove completed request IDs from the queue for reuse. Reverse of above function. */
224 225
static void remove_req_id(
        struct completed_requests** requests, int16_t req_id);
226
/* remove MPI operation from the waiting queue.*/
227 228
static int mpi_queue_remove_matching_op(
        nw_state* s, tw_lp* lp, nw_message * m, struct mpi_queue_ptrs* mpi_queue, struct codes_workload_op * mpi_op);
229
/* remove the tail of the MPI operation from waiting queue */
230 231
static int mpi_queue_remove_tail(
        tw_lpid lpid, struct mpi_queue_ptrs* mpi_queue);
232
/* insert completed MPI requests in the queue. */
233 234
static void mpi_completed_queue_insert_op(
        struct completed_requests** mpi_completed_queue, dumpi_req_id req_id);
235
/* notifies the wait operations (if any) about the completed receives and sends requests. */
236 237
static int notify_waits(
        nw_state* s, tw_bf* bf, tw_lp* lp, nw_message* m, dumpi_req_id req_id);
238
/* reverse of notify waits function. */
239 240
static void notify_waits_rc(
        nw_state* s, tw_bf* bf, tw_lp* lp, nw_message* m, dumpi_req_id completed_req);
241 242
/* conversion from seconds to eanaoseconds */
static tw_stime s_to_ns(tw_stime ns);
243

244 245 246 247 248
/* helper function - maps an MPI rank to an LP id */
static tw_lpid rank_to_lpid(int rank)
{
    return codes_mapping_get_lpid_from_relative(rank, NULL, "nw-lp", NULL, 0);
}
249

250 251 252 253 254 255 256 257 258 259 260 261
/* 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;
}

262
/* helper function: counts number of elements in the queue */
263 264
static int numQueue(struct mpi_queue_ptrs* mpi_queue)
{
265
	struct mpi_msgs_queue* tmp = mpi_queue->queue_head;
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
	int count = 0;

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

/* 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)
	{
287
		if(tmp->mpi_op->op_type == CODES_WK_SEND || tmp->mpi_op->op_type == CODES_WK_ISEND)
288 289 290
			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);
291
		else if(tmp->mpi_op->op_type == CODES_WK_IRECV || tmp->mpi_op->op_type == CODES_WK_RECV)
292 293 294 295 296 297 298 299 300 301 302
			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 */
303
static void mpi_queue_update(struct mpi_queue_ptrs* mpi_queue, struct codes_workload_op* mpi_op, int pos)
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
{
	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;
}

340
/* prints the elements of a queue (for debugging purposes). */
341 342 343 344
static void printCompletedQueue(nw_state* s, tw_lp* lp)
{
	   if(TRACE == lp->gid)
	   {
345
	   	printf("\n %lf contents of completed operations queue ", tw_now(lp));
346 347 348 349 350 351 352 353 354
	   	struct completed_requests* current = s->completed_reqs;
	   	while(current)
	    	{
			printf(" %d ",current->req_id);
			current = current->next;
	   	}
	   }
}

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
/* 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);
371
  
372
  printCompletedQueue(s, lp);
373
  
374
  if(m->u.rc.matched_op == 1)
375 376
	s->pending_waits->num_completed--;
   /* if a wait-elem exists, it means the request ID has been matched*/
377
   if(m->u.rc.matched_op == 2) 
378
    {
379 380 381 382 383
        if(lp->gid == TRACE)
        {
            printf("\n %lf matched req id %d ", tw_now(lp), completed_req);
            printCompletedQueue(s, lp);
        }
384
        struct pending_waits* wait_elem = m->u.rc.saved_pending_wait;
385 386
        s->wait_time = m->u.rc.saved_wait_time;
        int count = wait_elem->mpi_op->u.waits.count; 
387

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

391 392 393
        wait_elem->num_completed--;	
        s->pending_waits = wait_elem;
        tw_rand_reverse_unif(lp->rng);
394 395 396 397 398
   }
}

/* 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)
399 400 401 402 403 404 405
{
	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;
406
	m->u.rc.matched_op = 0;
407 408 409
	
	if(lp->gid == TRACE)
		printf("\n %lf notify waits req id %d ", tw_now(lp), completed_req);
410 411 412

	if(!wait_elem)
		return 0;
413

414 415
	int op_type = wait_elem->mpi_op->op_type;

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

466
/* reverse handler of MPI wait operation */
467
static void codes_exec_mpi_wait_rc(nw_state* s, nw_message* m, tw_lp* lp, struct codes_workload_op * mpi_op)
468 469 470 471
{
    if(s->pending_waits)
     {
    	s->pending_waits = NULL;
472
	    return;
473 474 475
     }
   else
    {
476 477
 	    mpi_completed_queue_insert_op(&s->completed_reqs, mpi_op->u.wait.req_id);	
	    tw_rand_reverse_unif(lp->rng);	
478
        //rc_stack_pop(s->st);
479 480
    }
}
481 482

/* execute MPI wait operation */
483
static void codes_exec_mpi_wait(nw_state* s, tw_lp* lp, nw_message * m, struct codes_workload_op * mpi_op)
484
{
Jonathan Jenkins's avatar
Jonathan Jenkins committed
485 486
    /* check in the completed receives queue if the request ID has already been completed.*/
    assert(!s->pending_waits);
487
    dumpi_req_id req_id = mpi_op->u.wait.req_id;
Jonathan Jenkins's avatar
Jonathan Jenkins committed
488 489 490 491 492 493 494 495 496 497

    struct completed_requests* current = s->completed_reqs;
    while(current) {
        if(current->req_id == req_id) {
            remove_req_id(&s->completed_reqs, req_id);
            m->u.rc.saved_wait_time = s->wait_time;
            codes_issue_next_event(lp);
            return;
        }
        current = current->next;
498 499
    }

Jonathan Jenkins's avatar
Jonathan Jenkins committed
500
    /* If not, add the wait operation in the pending 'waits' list. */
501
    struct pending_waits* wait_op = malloc(sizeof(struct pending_waits));
502
    wait_op->mpi_op = mpi_op;
Jonathan Jenkins's avatar
Jonathan Jenkins committed
503 504
    wait_op->num_completed = 0;
    wait_op->start_time = tw_now(lp);
505
    s->pending_waits = wait_op;
506

507
    //rc_stack_push(lp, wait_op, free, s->st);
508 509
}

510
static void codes_exec_mpi_wait_all_rc(nw_state* s, nw_message* m, tw_lp* lp, struct codes_workload_op * mpi_op)
511
{
512 513 514 515 516
  if(lp->gid == TRACE)
   {
       printf("\n %lf codes exec mpi waitall reverse %d ", tw_now(lp), m->u.rc.found_match);
       printCompletedQueue(s, lp); 
   } 
517
  if(m->u.rc.found_match)
518
    {
519
        int i;
520
        int count = mpi_op->u.waits.count;
521 522 523 524
        dumpi_req_id req_id[count];

        for( i = 0; i < count; i++)
        {
525
            req_id[i] = mpi_op->u.waits.req_ids[i];
526 527 528 529
            mpi_completed_queue_insert_op(&s->completed_reqs, req_id[i]);
        }
        tw_rand_reverse_unif(lp->rng);
   }
530 531
    else
    {
532
        struct pending_waits* wait_op = s->pending_waits;
533
        //rc_stack_pop(s->st);
534 535 536 537 538
        s->pending_waits = NULL;
        assert(!s->pending_waits);
        if(lp->gid == TRACE)
            printf("\n %lf Nullifying codes waitall ", tw_now(lp));
   }
539
}
540 541
static void codes_exec_mpi_wait_all(
        nw_state* s, tw_lp* lp, nw_message * m, struct codes_workload_op * mpi_op)
542 543
{
  //assert(!s->pending_waits);
544
  int count = mpi_op->u.waits.count;
545 546 547 548 549 550 551
  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 */ 
  if(lp->gid == TRACE)
    {
552
  	printf(" \n (%lf) MPI waitall posted %d count", tw_now(lp), mpi_op->u.waits.count);
553
	for(i = 0; i < count; i++)
554
		printf(" %d ", (int)mpi_op->u.waits.req_ids[i]);
555 556 557 558 559 560
   	printCompletedQueue(s, lp);	 
   }
  while(current) 
   {
	  for(i = 0; i < count; i++)
	   {
561
	     req_id[i] = mpi_op->u.waits.req_ids[i];
562
	     if(req_id[i] == current->req_id)
563
 		    num_completed++;
564 565 566 567 568
   	  }
	 current = current->next;
   }

  if(TRACE== lp->gid)
569
	  printf("\n %lf Num completed %d count %d ", tw_now(lp), num_completed, count);
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 579 580 581 582 583
	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));
584
	  wait_op->mpi_op = mpi_op;  
585
	  wait_op->num_completed = num_completed;
Jonathan Jenkins's avatar
Jonathan Jenkins committed
586
	  wait_op->start_time = tw_now(lp);
587
      //rc_stack_push(lp, wait_op, free, s->st);
588
      s->pending_waits = wait_op;
589 590 591 592
  }
}

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

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

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

	reqs->req_id = req_id;

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

643
/* 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. */
644 645
static void mpi_pending_queue_insert_op(
        struct mpi_queue_ptrs* mpi_queue, struct codes_workload_op* mpi_op)
646 647 648 649 650 651
{
	/* insert mpi operation */
	struct mpi_msgs_queue* elem = malloc(sizeof(struct mpi_msgs_queue));
	assert(elem);

	elem->mpi_op = mpi_op;
652
    elem->next = NULL;
653 654 655 656 657 658 659

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

	if(mpi_queue->queue_tail)
	    mpi_queue->queue_tail->next = elem;
	
660
    mpi_queue->queue_tail = elem;
661 662 663 664 665 666
	mpi_queue->num_elems++;

	return;
}

/* match the send/recv operations */
667 668
static int match_receive(
        nw_state* s, tw_lp* lp, tw_lpid lpid, struct codes_workload_op* op1, struct codes_workload_op* op2)
669
{
670 671 672 673 674 675 676 677 678
        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);
679
                        s->recv_time += tw_now(lp) - op1->sim_start_time;
680 681 682 683
                        mpi_completed_queue_insert_op(&s->completed_reqs, op1->u.recv.req_id);
                        return 1;
                   }
        return -1;
684 685 686
}

/* used for reverse computation. removes the tail of the queue */
687
static int mpi_queue_remove_tail(tw_lpid lpid, struct mpi_queue_ptrs* mpi_queue)
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
{
	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. */
722
static int mpi_queue_remove_matching_op(nw_state* s, tw_lp* lp, nw_message * m, struct mpi_queue_ptrs* mpi_queue, struct codes_workload_op * mpi_op)
723 724 725 726 727 728 729 730 731
{
	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 */
732
	int rcv_val = 0;
733
	if(mpi_op->op_type == CODES_WK_SEND || mpi_op->op_type == CODES_WK_ISEND)
734
	  {
735
		rcv_val = match_receive(s, lp, lp->gid, tmp->mpi_op, mpi_op);
736
		m->u.rc.saved_matched_req = tmp->mpi_op->u.recv.req_id;  
737
	 }
738
	else if(mpi_op->op_type == CODES_WK_RECV || mpi_op->op_type == CODES_WK_IRECV)
739
	  {
740
		rcv_val = match_receive(s, lp, lp->gid, mpi_op, tmp->mpi_op);
741
	  	m->u.rc.saved_matched_req = mpi_op->u.recv.req_id;
742 743
	  }
	if(rcv_val >= 0)
744
	{
745
		/* TODO: fix RC */
746
		m->u.rc.ptr_match_op = tmp->mpi_op;
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
		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;
769
	   
770
	    if(mpi_op->op_type == CODES_WK_SEND || mpi_op->op_type == CODES_WK_ISEND)
771
	     {
772
		    rcv_val = match_receive(s, lp, lp->gid, elem->mpi_op, mpi_op);
773
	     	m->u.rc.saved_matched_req = elem->mpi_op->u.recv.req_id; 
774
	     }
775
	    else if(mpi_op->op_type == CODES_WK_RECV || mpi_op->op_type == CODES_WK_IRECV)
776
	     {
777 778 779
            rcv_val = match_receive(s, lp, lp->gid, mpi_op, elem->mpi_op);
            m->u.rc.saved_matched_req = mpi_op->u.recv.req_id;
         }
780
   	     if(rcv_val >= 0)
781 782
		 {
		    m->u.rc.ptr_match_op = elem->mpi_op;
783
		    if(elem == mpi_queue->queue_tail)
784
			    mpi_queue->queue_tail = tmp;
785
		    
786 787 788 789
		    tmp->next = elem->next;

		    free(elem);
		    mpi_queue->num_elems--;
790
		
791
		    return indx;
792
		 }
793
	   tmp = tmp->next;
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 */
814 815
static void codes_exec_comp_delay(
        nw_state* s, tw_lp* lp, struct codes_workload_op * mpi_op)
816 817 818 819 820
{
	tw_event* e;
	tw_stime ts;
	nw_message* msg;

821 822 823 824 825 826 827 828 829
        if (disable_delay) {
            ts = 0.0; // no compute time sim
        }
        else {
            s->compute_time += s_to_ns(mpi_op->u.delay.seconds);
            ts = s_to_ns(mpi_op->u.delay.seconds);
        }

	ts += g_tw_lookahead + 0.1 + tw_rand_exponential(lp->rng, noise);
830 831 832 833 834 835
	
	e = tw_event_new( lp->gid, ts , lp );
	msg = tw_event_data(e);
	msg->msg_type = MPI_OP_GET_NEXT;

	tw_event_send(e); 
836
                
837 838 839
}

/* reverse computation operation for MPI irecv */
840
static void codes_exec_mpi_recv_rc(nw_state* s, nw_message* m, tw_lp* lp, struct codes_workload_op * mpi_op)
841
{
842
	num_bytes_recvd -= mpi_op->u.recv.num_bytes;
843 844
	s->recv_time = m->u.rc.saved_recv_time;
	if(m->u.rc.found_match >= 0)
845
	  {
846 847
		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);
848
		remove_req_id(&s->completed_reqs, mpi_op->u.recv.req_id);
849
		tw_rand_reverse_unif(lp->rng);
850
	  }
851
	else if(m->u.rc.found_match < 0)
852
	    {
853
		mpi_queue_remove_tail(lp->gid, s->pending_recvs_queue);
854
		if(mpi_op->op_type == CODES_WK_IRECV)
855
			tw_rand_reverse_unif(lp->rng);
856 857 858 859
	    }
}

/* Execute MPI Irecv operation (non-blocking receive) */ 
860
static void codes_exec_mpi_recv(nw_state* s, tw_lp* lp, nw_message * m, struct codes_workload_op * mpi_op)
861 862 863 864 865
{
/* 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. */

866
	m->u.rc.saved_recv_time = s->recv_time;
867
	mpi_op->sim_start_time = tw_now(lp);
868
	num_bytes_recvd += mpi_op->u.recv.num_bytes;
869 870

	if(lp->gid == TRACE)
871
		printf("\n %lf codes exec mpi recv req id %d", tw_now(lp), (int)mpi_op->u.recv.req_id);
872 873
	
	dumpi_req_id req_id;
874
	int found_matching_sends = mpi_queue_remove_matching_op(s, lp, m, s->arrival_queue, mpi_op);
875 876 877
	
	/* save the req id inserted in the completed queue for reverse computation. */
	//m->matched_recv = req_id;
878 879 880

	if(found_matching_sends < 0)
	  {
881
		m->u.rc.found_match = -1;
882 883 884
		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. */
885
		if(mpi_op->op_type == CODES_WK_IRECV)
886 887 888 889 890 891
		   {
			codes_issue_next_event(lp);	
			return;
		   }
		else
			printf("\n CODES MPI RECV OPERATION!!! ");
892
	  }
893
	else
894
	  {
895
	   	m->u.rc.found_match = found_matching_sends;
896
        codes_issue_next_event(lp); 
897 898 899 900
	 }
}

/* executes MPI send and isend operations */
901
static void codes_exec_mpi_send(nw_state* s, tw_lp* lp, struct codes_workload_op * mpi_op)
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
{
	/* 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;

927 928
	nw_message local_m;
	nw_message remote_m;
929

930 931 932 933 934 935 936 937
    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;