torus.c 64.9 KB
Newer Older
1 2 3 4 5 6
/*
 * Copyright (C) 2013 University of Chicago.
 * See COPYRIGHT notice in top-level directory.
 *
 */

7 8
#include <ross.h>
#include <assert.h>
9
#include <string.h>
10 11 12 13 14 15

#include "codes/lp-io.h"
#include "codes/codes_mapping.h"
#include "codes/codes.h"
#include "codes/model-net.h"
#include "codes/model-net-method.h"
16 17
#include "codes/model-net-lp.h"
#include "codes/net/torus.h"
18
#include "codes/rc-stack.h"
19 20 21

#define DEBUG 1
#define MEAN_INTERVAL 100
22 23 24
// type casts to make compiler happy
#define TRACE ((unsigned long long)(-1))
#define TRACK ((tw_lpid)(-1))
25

26
#define STATICQ 0
27 28 29
/* collective specific parameters */
#define TREE_DEGREE 4
#define LEVEL_DELAY 1000
30
#define TORUS_COLLECTIVE_DEBUG 0
31 32 33 34
#define NUM_COLLECTIVES  1
#define COLLECTIVE_COMPUTATION_DELAY 5700
#define TORUS_FAN_OUT_DELAY 20.0

35 36 37
#define LP_CONFIG_NM (model_net_lp_config_names[TORUS])
#define LP_METHOD_NM (model_net_method_names[TORUS])

38 39
static double maxd(double a, double b) { return a < b ? b : a; }

40
/* Torus network model implementation of codes, implements the modelnet API */
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
typedef struct nodes_message_list nodes_message_list;
struct nodes_message_list {
    nodes_message msg;
    char* event_data;
    nodes_message_list *next;
    nodes_message_list *prev;
};

void init_nodes_message_list(nodes_message_list *this, nodes_message *inmsg) {
    this->msg = *inmsg;
    this->event_data = NULL;
    this->next = NULL;
    this->prev = NULL;
}

void delete_nodes_message_list(nodes_message_list *this) {
    if(this->event_data != NULL) free(this->event_data);
    free(this);
}

61 62 63 64 65 66 67 68
static void free_tmp(void * ptr)
{
    nodes_message_list * entry = ptr;
    if(entry->event_data != NULL)
        free(entry->event_data);

    free(entry);
}
69 70 71 72 73 74
typedef struct torus_param torus_param;
struct torus_param
{
    int n_dims; /*Dimension of the torus network, 5-D, 7-D or any other*/
    int* dim_length; /*Length of each torus dimension*/
    double link_bandwidth;/* bandwidth for each torus link */
75
    double cn_bandwidth; /* injection bandwidth */
76 77 78 79 80 81 82 83 84 85 86 87 88 89
    int buffer_size; /* number of buffer slots for each vc in flits*/
    int num_vc; /* number of virtual channels for each torus link */
    float mean_process;/* mean process time for each flit  */
    int chunk_size; /* chunk is the smallest unit--default set to 32 */

    /* "derived" torus parameters */

    /* factor, used in torus coordinate calculation */
    int * factor;
    /* half length of each dimension, used in torus coordinates calculation */
    int * half_length;

    double head_delay;
    double credit_delay;
90 91 92 93
    double cn_delay;

    double router_delay;
    int routing;
94
};
95 96

/* codes mapping group name, lp type name */
97
static char grp_name[MAX_NAME_LENGTH];
98
/* codes mapping group id, lp type id, repetition id and offset */
99
int mapping_grp_id, mapping_rep_id, mapping_type_id, mapping_offset;
100 101 102 103

/* for calculating torus model statistics, average and maximum travel time of a packet */
static tw_stime         total_time = 0;
static tw_stime         max_latency = 0;
104
static tw_stime         max_collective = 0;
105 106 107 108 109 110

/* number of finished packets on each PE */
static long long       N_finished_packets = 0;
/* total number of hops traversed by a message on each PE */
static long long       total_hops = 0;

111 112
/* annotation-specific parameters (unannotated entry occurs at the 
 * last index) */
113
static int                       num_params = 0;
114 115
static torus_param             * all_params = NULL;
static const config_anno_map_t * anno_map   = NULL;
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

typedef struct nodes_state nodes_state;

/* state of a torus node */
struct nodes_state
{
  /* counts the number of packets sent from this compute node */
  unsigned long long packet_counter;            
  /* availability time of each torus link */
  tw_stime** next_link_available_time; 
  /* availability of each torus credit link */
  tw_stime** next_credit_available_time;
  /* next flit generate time */
  tw_stime** next_flit_generate_time;
  /* buffer size for each torus virtual channel */
  int** buffer;
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  /* Head and tail of the terminal messages list */
  nodes_message_list **terminal_msgs;
  nodes_message_list **terminal_msgs_tail;
  int all_term_length;
  int *terminal_length, *queued_length;
  /* pending packets to be sent out */
  nodes_message_list ***pending_msgs;
  nodes_message_list ***pending_msgs_tail;
  nodes_message_list ***queued_msgs;
  nodes_message_list ***queued_msgs_tail;
  nodes_message_list **other_msgs;
  nodes_message_list **other_msgs_tail;
  int *in_send_loop;
  /* traffic through each torus link */
  int64_t *link_traffic;
147 148 149 150 151 152 153 154
  /* coordinates of the current torus node */
  int* dim_position;
  /* neighbor LP ids for this torus node */
  int* neighbour_minus_lpID;
  int* neighbour_plus_lpID;

  /* records torus statistics for this LP having different communication categories */
  struct mn_stats torus_stats_array[CATEGORY_MAX];
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
   /* for collective operations */

  /* collective init time */
  tw_stime collective_init_time;

  /* node ID in the tree */ 
   tw_lpid node_id;

   /* messages sent & received in collectives may get interchanged several times so we have to save the 
     origin server information in the node's state */
   tw_lpid origin_svr; 
  
  /* parent node ID of the current node */
   tw_lpid parent_node_id;
   /* array of children to be allocated in terminal_init*/
   tw_lpid* children;

   /* children of a node can be less than or equal to the tree degree */
   int num_children;

   short is_root;
   short is_leaf;

   /* to maintain a count of child nodes that have fanned in at the parent during the collective
      fan-in phase*/
   int num_fan_nodes;
181 182 183 184 185

   /* LPs annotation */
   const char * anno;
   /* LPs configuration */
   const torus_param * params;
186 187 188

   /* create the RC stack */
   struct rc_stack * st;
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

   /* finished chunks */
   long finished_chunks;

   /* finished packets */
   long finished_packets;

   /* total hops */
   double total_hops;

   /* total time */
   double total_time;

   /* total data */
   long total_data_sz;
   /* output buf */
   char output_buf[2048];
   char output_busy_buf[2048];

   /* busy time */
   tw_stime * busy_time;
   tw_stime * last_buf_full;
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 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
static void append_to_node_message_list(  
        nodes_message_list ** thisq,
        nodes_message_list ** thistail,
        int index, 
        nodes_message_list *msg) {
    if(thisq[index] == NULL) {
        thisq[index] = msg;
    } else {
        thistail[index]->next = msg;
        msg->prev = thistail[index];
    } 
    thistail[index] = msg;
}
static void prepend_to_node_message_list(  
        nodes_message_list ** thisq,
        nodes_message_list ** thistail,
        int index, 
        nodes_message_list *msg) {
    if(thisq[index] == NULL) {
        thistail[index] = msg;
    } else {
        thisq[index]->prev = msg;
        msg->next = thisq[index];
    } 
    thisq[index] = msg;
}

static nodes_message_list* return_head(
        nodes_message_list ** thisq,
        nodes_message_list ** thistail,
        int index) {
    nodes_message_list *head = thisq[index];
    if(head != NULL) {
        thisq[index] = head->next;
        if(head->next != NULL) {
            head->next->prev = NULL;
            head->next = NULL;
        } else {
            thistail[index] = NULL;
        }
    }
    return head;
}

static nodes_message_list* return_tail(
        nodes_message_list ** thisq,
        nodes_message_list ** thistail,
        int index) {
    nodes_message_list *tail = thistail[index];
    if(tail->prev != NULL) {
        tail->prev->next = NULL;
        thistail[index] = tail->prev;
        tail->prev = NULL;
    } else {
        thistail[index] = NULL;
        thisq[index] = NULL;
    }
    return tail;
}

273 274 275 276
static void torus_read_config(
        const char         * anno,
        torus_param        * params){
    char dim_length_str[MAX_NAME_LENGTH];
277
    int i;
278 279 280 281

    // shorthand
    torus_param *p = params;

282 283
    int rc = configuration_get_value_int(&config, "PARAMS", "n_dims", anno, &p->n_dims);
    if(rc) {
284 285 286 287 288 289
        p->n_dims = 4; /* a 4-D torus */
        fprintf(stderr, 
                "Warning: Number of dimensions not specified, setting to %d\n",
                p->n_dims);
    }

290
   rc = configuration_get_value_double(&config, "PARAMS", "link_bandwidth", anno,
291
            &p->link_bandwidth);
292
    if(rc) {
293 294 295 296 297
        p->link_bandwidth = 2.0; /*default bg/q configuration */
        fprintf(stderr, "Link bandwidth not specified, setting to %lf\n",
                p->link_bandwidth);
    }

298 299
    rc = configuration_get_value_int(&config, "PARAMS", "buffer_size", anno, &p->buffer_size);
    if(rc) {
300 301 302 303 304
        p->buffer_size = 2048;
        fprintf(stderr, "Buffer size not specified, setting to %d",
                p->buffer_size);
    }

305

306 307 308
    rc = configuration_get_value_int(&config, "PARAMS", "chunk_size", anno, &p->chunk_size);
    if(rc) {
        p->chunk_size = 128;
309 310 311 312 313 314 315
        fprintf(stderr, "Warning: Chunk size not specified, setting to %d\n",
                p->chunk_size);
    }
        /* by default, we have one for taking packets,
         * another for taking credit*/
        p->num_vc = 1;

316
    rc = configuration_get_value(&config, "PARAMS", "dim_length", anno,
317 318 319 320 321 322 323 324 325
            dim_length_str, MAX_NAME_LENGTH);
    if (rc == 0){
        tw_error(TW_LOC, "couldn't read PARAMS:dim_length");
    }
    char* token;
    p->dim_length=malloc(p->n_dims*sizeof(*p->dim_length));
    token = strtok(dim_length_str, ",");
    i = 0;
    while(token != NULL)
326
    {
327 328 329 330 331 332 333 334 335 336 337 338
        sscanf(token, "%d", &p->dim_length[i]);
        if(p->dim_length[i] <= 0)
        {
            tw_error(TW_LOC, "Invalid torus dimension specified "
                    "(%d at pos %d), exiting... ", p->dim_length[i], i);
        }
        i++;
        token = strtok(NULL,",");
    }
    // create derived parameters
   
    // factor is an exclusive prefix product
339
    p->router_delay = 50;
340
    p->cn_delay = 10;
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    p->factor = malloc(p->n_dims * sizeof(int));
    p->factor[0] = 1;
    for(i = 1; i < p->n_dims; i++)
        p->factor[i] = p->factor[i-1] * p->dim_length[i-1];

    p->half_length = malloc(p->n_dims * sizeof(int));
    for (i = 0; i < p->n_dims; i++)
        p->half_length[i] = p->dim_length[i] / 2;

    // some latency numbers
    p->head_delay = (1.0 / p->link_bandwidth) * p->chunk_size;
    p->credit_delay = (1.0 / p->link_bandwidth) * p->chunk_size;
}

static void torus_configure(){
    anno_map = codes_mapping_get_lp_anno_map(LP_CONFIG_NM);
    assert(anno_map);
    num_params = anno_map->num_annos + (anno_map->has_unanno_lp > 0);
    all_params = malloc(num_params * sizeof(*all_params));

361
    for (int i = 0; i < anno_map->num_annos; i++){
362
        const char * anno = anno_map->annotations[i].ptr;
363 364 365 366
        torus_read_config(anno, &all_params[i]);
    }
    if (anno_map->has_unanno_lp > 0){
        torus_read_config(NULL, &all_params[anno_map->num_annos]);
367
    }
368 369
}

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
/* helper functions - convert between flat ids and torus n-dimensional ids */
static void to_dim_id(
        int flat_id,
        int ndims,
        const int *dim_lens,
        int *out_dim_ids)
{
    for (int i = 0; i < ndims; i++) {
        out_dim_ids[i] = flat_id % dim_lens[i];
        flat_id /= dim_lens[i];
    }
}

static int to_flat_id(
        int ndims,
        const int *dim_lens,
        const int *dim_ids)
{
    int flat_id = dim_ids[0];
    int mult = dim_lens[0];
    for (int i = 1; i < ndims; i++) {
        flat_id += dim_ids[i] * mult;
        mult *= dim_lens[i];
    }
    return flat_id;
}

397 398 399
void torus_collective_init(nodes_state * s,
           		   tw_lp * lp)
{
400 401
    // TODO: be annotation-aware somehow 
    codes_mapping_get_lp_info(lp->gid, grp_name, &mapping_grp_id, NULL, &mapping_type_id, NULL, &mapping_rep_id, &mapping_offset);
402
    tw_lpid num_lps = codes_mapping_get_lp_count(grp_name, 0, LP_CONFIG_NM, s->anno, 0);
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

    int i;
   /* handle collective operations by forming a tree of all the LPs */
   /* special condition for root of the tree */
   if( s->node_id == 0)
    {
        s->parent_node_id = -1;
        s->is_root = 1;
   }
   else
   {
       s->parent_node_id = (s->node_id - ((s->node_id - 1) % TREE_DEGREE)) / TREE_DEGREE;
       s->is_root = 0;
   }
   s->children = (tw_lpid*)malloc(TREE_DEGREE * sizeof(tw_lpid));

   /* set the isleaf to zero by default */
   s->is_leaf = 1;
   s->num_children = 0;

   /* calculate the children of the current node. If its a leaf, no need to set children,
      only set isleaf and break the loop*/

   for( i = 0; i < TREE_DEGREE; i++ )
    {
        tw_lpid next_child = (TREE_DEGREE * s->node_id) + i + 1;
429
        if(next_child < num_lps)
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
        {
            s->num_children++;
            s->is_leaf = 0;
            s->children[i] = next_child;
        }
        else
           s->children[i] = -1;
    }

#if TORUS_COLLECTIVE_DEBUG == 1
   printf("\n LP %ld parent node id ", s->node_id);

   for( i = 0; i < TREE_DEGREE; i++ )
        printf(" child node ID %ld ", s->children[i]);
   printf("\n");

   if(s->is_leaf)
        printf("\n LP %ld is leaf ", s->node_id);
#endif
}
450
/* torus packet reverse event */
451 452 453 454 455 456
static void torus_packet_event_rc(tw_lp *sender)
{
  codes_local_latency_reverse(sender);
  return;
}

457 458 459 460 461 462
/* returns the torus message size */
static int torus_get_msg_sz(void)
{
   return sizeof(nodes_message);
}

463
/* torus packet event , generates a torus packet on the compute node */
464 465 466 467 468 469 470 471 472 473
static tw_stime torus_packet_event(
        model_net_request const * req,
        uint64_t message_offset,
        uint64_t packet_size,
        tw_stime offset,
        mn_sched_params const * sched_params,
        void const * remote_event,
        void const * self_event,
        tw_lp *sender,
        int is_last_pckt)
474
{
475 476
    (void)message_offset; // not using atm...
    (void)sched_params; // not using atm...
477 478 479 480
    tw_event * e_new;
    tw_stime xfer_to_nic_time;
    nodes_message * msg;
    char* tmp_ptr;
481

482
    xfer_to_nic_time = codes_local_latency(sender); /* Throws an error of found last KP time > current event time otherwise */
483 484 485 486
    //e_new = tw_event_new(local_nic_id, xfer_to_nic_time+offset, sender);
    //msg = tw_event_data(e_new);
    e_new = model_net_method_event_new(sender->gid, xfer_to_nic_time+offset,
            sender, TORUS, (void**)&msg, (void**)&tmp_ptr);
487 488 489 490
    strcpy(msg->category, req->category);
    msg->final_dest_gid = req->final_dest_lp;
    msg->dest_lp = req->dest_mn_lp;
    msg->sender_svr= req->src_lp;
491
    msg->sender_node = sender->gid;
492
    msg->packet_size = packet_size;
493
    msg->travel_start_time = tw_now(sender);
494 495
    msg->remote_event_size_bytes = 0;
    msg->local_event_size_bytes = 0;
496
    msg->chunk_id = 0;
497
    msg->type = GENERATE;
498 499 500
    msg->is_pull = req->is_pull;
    msg->pull_size = req->pull_size;

501
    if(is_last_pckt) /* Its the last packet so pass in remote event information*/
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
    {
        if(req->remote_event_size > 0)
        {
            msg->remote_event_size_bytes = req->remote_event_size;
            memcpy(tmp_ptr, remote_event, req->remote_event_size);
            tmp_ptr += req->remote_event_size;
        }
        if(req->self_event_size > 0)
        {
            msg->local_event_size_bytes = req->self_event_size;
            memcpy(tmp_ptr, self_event, req->self_event_size);
            tmp_ptr += req->self_event_size;
        }
        // printf("\n torus remote event %d local event %d last packet %d %lf ", msg->remote_event_size_bytes, msg->local_event_size_bytes, is_last_pckt, xfer_to_nic_time);
    }
517
    tw_event_send(e_new);
518
    return xfer_to_nic_time;
519
}
520

521 522 523 524 525 526 527 528 529 530
/*Sends a 8-byte credit back to the torus node LP that sent the message */
static void credit_send( nodes_state * s, 
	    tw_lp * lp, 
	    nodes_message * msg,
            int sq)
{
    tw_event * e;
    nodes_message *m;
    tw_stime ts;

531
    ts = (1.1 * g_tw_lookahead) + s->params->credit_delay + tw_rand_unif(lp->rng);
532 533 534 535 536 537 538 539 540 541 542 543
    e = model_net_method_event_new(msg->sender_node, ts, lp, TORUS, 
        (void**)&m, NULL);
    if(sq == -1) {
        m->source_direction = msg->source_direction;
        m->source_dim = msg->source_dim;
    } else {
        m->source_direction = msg->saved_queue % 2;
        m->source_dim = msg->saved_queue / 2;
    }
    m->type = CREDIT;
    tw_event_send(e);
}
544 545 546 547 548
/*Initialize the torus model, this initialization part is borrowed from Ning's torus model */
static void torus_init( nodes_state * s, 
	   tw_lp * lp )
{
    int i, j;
549
    char anno[MAX_NAME_LENGTH];
550

551 552
    rc_stack_create(&s->st);

553
    codes_mapping_get_lp_info(lp->gid, grp_name, &mapping_grp_id, NULL, &mapping_type_id, anno, &mapping_rep_id, &mapping_offset);
554 555 556
    
    s->node_id = codes_mapping_get_lp_relative_id(lp->gid, 0, 0);

557 558 559 560 561
    if (anno[0] == '\0'){
        s->anno = NULL;
        s->params = &all_params[num_params-1];
    }
    else{
562
        s->anno = strdup(anno);
563 564 565
        int id = configuration_get_annotation_index(anno, anno_map);
        s->params = &all_params[id];
    }
566

567 568
    // shorthand
    const torus_param *p = s->params;
569

570 571 572
    s->finished_chunks = 0;
    s->finished_packets = 0;

573 574 575 576 577 578 579 580 581 582 583
    s->neighbour_minus_lpID = (int*)malloc(p->n_dims * sizeof(int));
    s->neighbour_plus_lpID = (int*)malloc(p->n_dims * sizeof(int));
    s->dim_position = (int*)malloc(p->n_dims * sizeof(int));
    s->buffer = (int**)malloc(2*p->n_dims * sizeof(int*));
    s->next_link_available_time = 
        (tw_stime**)malloc(2*p->n_dims * sizeof(tw_stime*));
    s->next_credit_available_time = 
        (tw_stime**)malloc(2*p->n_dims * sizeof(tw_stime*));
    s->next_flit_generate_time = 
        (tw_stime**)malloc(2*p->n_dims*sizeof(tw_stime*));

584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
    for(i=0; i < 2*p->n_dims; i++)
    {
        s->buffer[i] = (int*)malloc(p->num_vc * sizeof(int));
        s->next_link_available_time[i] =
                (tw_stime*)malloc(p->num_vc * sizeof(tw_stime));
        s->next_credit_available_time[i] = 
                (tw_stime*)malloc(p->num_vc * sizeof(tw_stime));
        s->next_flit_generate_time[i] = 
                (tw_stime*)malloc(p->num_vc * sizeof(tw_stime));
    }
    s->terminal_length = (int*)malloc(2*p->n_dims*sizeof(int));
    s->queued_length = (int*)malloc(2*p->n_dims*sizeof(int));
    s->terminal_msgs = 
        (nodes_message_list**)malloc(2*p->n_dims*sizeof(nodes_message_list*));
    s->terminal_msgs_tail = 
        (nodes_message_list**)malloc(2*p->n_dims*sizeof(nodes_message_list*));
    s->pending_msgs = 
        (nodes_message_list***)malloc(2*p->n_dims*sizeof(nodes_message_list**));
    s->pending_msgs_tail = 
        (nodes_message_list***)malloc(2*p->n_dims*sizeof(nodes_message_list**));
    s->queued_msgs = 
        (nodes_message_list***)malloc(2*p->n_dims*sizeof(nodes_message_list**));
    s->queued_msgs_tail = 
        (nodes_message_list***)malloc(2*p->n_dims*sizeof(nodes_message_list**));
608 609 610 611 612 613

    s->busy_time = 
        (tw_stime*)malloc(2*p->n_dims*sizeof(tw_stime));
    s->last_buf_full = 
        (tw_stime*)malloc(2*p->n_dims*sizeof(tw_stime));

614 615 616 617 618 619 620 621 622
    for(i = 0; i < 2*p->n_dims; i++) {
        s->pending_msgs[i] = 
            (nodes_message_list**)malloc(p->num_vc*sizeof(nodes_message_list*));
        s->pending_msgs_tail[i] = 
            (nodes_message_list**)malloc(p->num_vc*sizeof(nodes_message_list*));
        s->queued_msgs[i] = 
            (nodes_message_list**)malloc(p->num_vc*sizeof(nodes_message_list*));
        s->queued_msgs_tail[i] = 
            (nodes_message_list**)malloc(p->num_vc*sizeof(nodes_message_list*));
623

624 625 626 627 628 629 630 631 632
    }
    s->other_msgs = 
        (nodes_message_list**)malloc(2*p->n_dims*sizeof(nodes_message_list*));
    s->other_msgs_tail = 
        (nodes_message_list**)malloc(2*p->n_dims*sizeof(nodes_message_list*));
    s->in_send_loop = 
        (int *)malloc(2*p->n_dims*sizeof(int));

    s->link_traffic = (int64_t *)malloc(2*p->n_dims*sizeof(int64_t));
633 634
    s->total_data_sz = 0;

635
    for(i=0; i < 2*p->n_dims; i++)
636
    {
637 638 639 640 641 642 643
	s->buffer[i] = (int*)malloc(p->num_vc * sizeof(int));
	s->next_link_available_time[i] =
            (tw_stime*)malloc(p->num_vc * sizeof(tw_stime));
	s->next_credit_available_time[i] = 
            (tw_stime*)malloc(p->num_vc * sizeof(tw_stime));
	s->next_flit_generate_time[i] = 
            (tw_stime*)malloc(p->num_vc * sizeof(tw_stime));
644 645 646 647 648 649 650 651
        s->terminal_msgs[i] = NULL;
        s->terminal_msgs_tail[i] = NULL;
        s->other_msgs[i] = NULL;
        s->other_msgs_tail[i] = NULL;
        s->in_send_loop[i] = 0;
        s->terminal_length[i] = 0;
        s->queued_length[i] = 0;
        s->all_term_length = 0;
652 653
        s->busy_time[i] = 0;
        s->last_buf_full[i] = 0;
654 655
    }

656 657 658
    // calculate my torus coords
    to_dim_id(codes_mapping_get_lp_relative_id(lp->gid, 0, 1),
            s->params->n_dims, s->params->dim_length, s->dim_position);
659 660
    /* DEBUG */
    /*printf("%lu: my coords:", lp->gid);
Jonathan Jenkins's avatar
Jonathan Jenkins committed
661 662 663 664
    for (i = 0; i < p->n_dims; i++)
        printf(" %d", s->dim_position[i]);
    printf("\n");
    */
665

666 667
  int temp_dim_pos[ p->n_dims ];
  for ( i = 0; i < p->n_dims; i++ )
668 669 670
    temp_dim_pos[ i ] = s->dim_position[ i ];

  // calculate minus neighbour's lpID
671
  for ( j = 0; j < p->n_dims; j++ )
672
    {
673 674
      temp_dim_pos[ j ] = (s->dim_position[ j ] -1 + p->dim_length[ j ]) %
          p->dim_length[ j ];
675

676 677 678 679 680 681 682 683 684 685
      s->neighbour_minus_lpID[j] =
          to_flat_id(p->n_dims, p->dim_length, temp_dim_pos);

      /* DEBUG
      printf(" minus neighbor: flat:%d lpid:%lu\n",
              s->neighbour_minus_lpID[j],
              codes_mapping_get_lpid_from_relative(s->neighbour_minus_lpID[j],
                      NULL, LP_CONFIG_NM, s->anno, 1));
      */

686 687 688
      temp_dim_pos[ j ] = s->dim_position[ j ];
    }
  // calculate plus neighbour's lpID
689
  for ( j = 0; j < p->n_dims; j++ )
690
    {
691 692
      temp_dim_pos[ j ] = ( s->dim_position[ j ] + 1 + p->dim_length[ j ]) %
          p->dim_length[ j ];
693

694 695 696 697 698 699 700 701 702
      s->neighbour_plus_lpID[j] =
          to_flat_id(p->n_dims, p->dim_length, temp_dim_pos);

      /* DEBUG
      printf(" plus neighbor: flat:%d lpid:%lu\n",
              s->neighbour_plus_lpID[j],
              codes_mapping_get_lpid_from_relative(s->neighbour_plus_lpID[j],
                      NULL, LP_CONFIG_NM, s->anno, 1));
      */
703 704 705 706 707

      temp_dim_pos[ j ] = s->dim_position[ j ];
    }

  //printf("\n");
708
  for( j=0; j < 2 * p->n_dims; j++ )
709
   {
710
    for( i = 0; i < p->num_vc; i++ )
711 712 713 714
     {
       s->buffer[ j ][ i ] = 0; 
       s->next_link_available_time[ j ][ i ] = 0.0;
       s->next_credit_available_time[j][i] = 0.0; 
715 716 717 718
       s->pending_msgs[j][i] = NULL;
       s->pending_msgs_tail[j][i] = NULL;
       s->queued_msgs[j][i] = NULL;
       s->queued_msgs_tail[j][i] = NULL;
719 720 721 722
     }
   }
  // record LP time
    s->packet_counter = 0;
723 724 725 726 727
    torus_collective_init(s, lp);
}


/* collective operation for the torus network */
728
void torus_collective(char const * category, int message_size, int remote_event_size, const void* remote_event, tw_lp* sender)
729 730 731 732 733 734 735
{
    tw_event * e_new;
    tw_stime xfer_to_nic_time;
    nodes_message * msg;
    tw_lpid local_nic_id;
    char* tmp_ptr;

736 737 738 739 740
    // TODO: be annotation-aware
    codes_mapping_get_lp_info(sender->gid, grp_name, &mapping_grp_id, NULL,
            &mapping_type_id, NULL, &mapping_rep_id, &mapping_offset);
    codes_mapping_get_lp_id(grp_name, LP_CONFIG_NM, NULL, 1,
            mapping_rep_id, mapping_offset, &local_nic_id);
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

    xfer_to_nic_time = g_tw_lookahead + codes_local_latency(sender);
    e_new = model_net_method_event_new(local_nic_id, xfer_to_nic_time,
            sender, TORUS, (void**)&msg, (void**)&tmp_ptr);

    msg->remote_event_size_bytes = message_size;
    strcpy(msg->category, category);
    msg->sender_svr=sender->gid;
    msg->type = T_COLLECTIVE_INIT;

    tmp_ptr = (char*)msg;
    tmp_ptr += torus_get_msg_sz();
    if(remote_event_size > 0)
     {
            msg->remote_event_size_bytes = remote_event_size;
            memcpy(tmp_ptr, remote_event, remote_event_size);
            tmp_ptr += remote_event_size;
     }

    tw_event_send(e_new);
    return;
}

/* reverse for collective operation of the dragonfly network */
void torus_collective_rc(int message_size, tw_lp* sender)
{
767
    (void)message_size; // unneeded
768 769 770 771 772 773 774 775 776 777 778 779 780 781
     codes_local_latency_reverse(sender);
     return;
}

static void send_remote_event(nodes_state * s,
                        nodes_message * msg,
                        tw_lp * lp)
{
    // Trigger an event on receiving server
    if(msg->remote_event_size_bytes)
     {
            tw_event* e;
            tw_stime ts;
            nodes_message * m;
782
            ts = (1/s->params->link_bandwidth) * msg->remote_event_size_bytes;
783
            e = tw_event_new(s->origin_svr, ts, lp);
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
            m = tw_event_data(e);
            char* tmp_ptr = (char*)msg;
            tmp_ptr += torus_get_msg_sz();
            memcpy(m, tmp_ptr, msg->remote_event_size_bytes);
            tw_event_send(e);
     }
}

static void node_collective_init(nodes_state * s,
                        nodes_message * msg,
                        tw_lp * lp)
{
        tw_event * e_new;
        tw_lpid parent_nic_id;
        tw_stime xfer_to_nic_time;
        nodes_message * msg_new;
        int num_lps;

        msg->saved_collective_init_time = s->collective_init_time;
        s->collective_init_time = tw_now(lp);
	s->origin_svr = msg->sender_svr;
	
        if(s->is_leaf)
        {
            //printf("\n LP %ld sending message to parent %ld ", s->node_id, s->parent_node_id);
            /* get the global LP ID of the parent node */
810 811 812 813 814 815 816 817
            // TODO: be annotation-aware
            codes_mapping_get_lp_info(lp->gid, grp_name, &mapping_grp_id, NULL,
                    &mapping_type_id, NULL, &mapping_rep_id, &mapping_offset);
            num_lps = codes_mapping_get_lp_count(grp_name, 1, LP_CONFIG_NM,
                    NULL, 1);
            codes_mapping_get_lp_id(grp_name, LP_CONFIG_NM, NULL, 1,
                    s->parent_node_id/num_lps, (s->parent_node_id % num_lps),
                    &parent_nic_id);
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

           /* send a message to the parent that the LP has entered the collective operation */
            xfer_to_nic_time = g_tw_lookahead + LEVEL_DELAY;
            //e_new = codes_event_new(parent_nic_id, xfer_to_nic_time, lp);
	    void* m_data;
	    e_new = model_net_method_event_new(parent_nic_id, xfer_to_nic_time,
            	lp, TORUS, (void**)&msg_new, (void**)&m_data);
	    	
            memcpy(msg_new, msg, sizeof(nodes_message));
	    if (msg->remote_event_size_bytes){
        	memcpy(m_data, model_net_method_get_edata(TORUS, msg),
                	msg->remote_event_size_bytes);
      	    }
	    
            msg_new->type = T_COLLECTIVE_FAN_IN;
            msg_new->sender_node = s->node_id;

            tw_event_send(e_new);
        }
        return;
}

static void node_collective_fan_in(nodes_state * s,
                        tw_bf * bf,
                        nodes_message * msg,
                        tw_lp * lp)
{
        int i;
        s->num_fan_nodes++;

848 849 850 851 852
        // TODO: be annotation-aware
        codes_mapping_get_lp_info(lp->gid, grp_name, &mapping_grp_id, NULL,
                &mapping_type_id, NULL, &mapping_rep_id, &mapping_offset);
        int num_lps = codes_mapping_get_lp_count(grp_name, 1, LP_CONFIG_NM,
                NULL, 1);
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870

        tw_event* e_new;
        nodes_message * msg_new;
        tw_stime xfer_to_nic_time;

        bf->c1 = 0;
        bf->c2 = 0;

        /* if the number of fanned in nodes have completed at the current node then signal the parent */
        if((s->num_fan_nodes == s->num_children) && !s->is_root)
        {
            bf->c1 = 1;
            msg->saved_fan_nodes = s->num_fan_nodes-1;
            s->num_fan_nodes = 0;
            tw_lpid parent_nic_id;
            xfer_to_nic_time = g_tw_lookahead + LEVEL_DELAY;

            /* get the global LP ID of the parent node */
871 872 873
            codes_mapping_get_lp_id(grp_name, LP_CONFIG_NM, NULL, 1,
                    s->parent_node_id/num_lps, (s->parent_node_id % num_lps),
                    &parent_nic_id);
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

           /* send a message to the parent that the LP has entered the collective operation */
            //e_new = codes_event_new(parent_nic_id, xfer_to_nic_time, lp);
            //msg_new = tw_event_data(e_new);
	    void * m_data;
      	    e_new = model_net_method_event_new(parent_nic_id,
              xfer_to_nic_time,
              lp, TORUS, (void**)&msg_new, &m_data);
	    
            memcpy(msg_new, msg, sizeof(nodes_message));
            msg_new->type = T_COLLECTIVE_FAN_IN;
            msg_new->sender_node = s->node_id;

            if (msg->remote_event_size_bytes){
	        memcpy(m_data, model_net_method_get_edata(TORUS, msg),
        	        msg->remote_event_size_bytes);
      	   }
            tw_event_send(e_new);
      }

      /* root node starts off with the fan-out phase */
      if(s->is_root && (s->num_fan_nodes == s->num_children))
      {
           bf->c2 = 1;
           msg->saved_fan_nodes = s->num_fan_nodes-1;
           s->num_fan_nodes = 0;
900
           send_remote_event(s, msg, lp);
901 902 903 904 905 906 907 908

           for( i = 0; i < s->num_children; i++ )
           {
                tw_lpid child_nic_id;
                /* Do some computation and fan out immediate child nodes from the collective */
                xfer_to_nic_time = g_tw_lookahead + COLLECTIVE_COMPUTATION_DELAY + LEVEL_DELAY + tw_rand_exponential(lp->rng, (double)LEVEL_DELAY/50);

                /* get global LP ID of the child node */
909 910 911
                codes_mapping_get_lp_id(grp_name, LP_CONFIG_NM, NULL, 1,
                        s->children[i]/num_lps, (s->children[i] % num_lps),
                        &child_nic_id);
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
                //e_new = codes_event_new(child_nic_id, xfer_to_nic_time, lp);

                //msg_new = tw_event_data(e_new);
                void * m_data;
	        e_new = model_net_method_event_new(child_nic_id,
                xfer_to_nic_time,
		lp, TORUS, (void**)&msg_new, &m_data);

		memcpy(msg_new, msg, sizeof(nodes_message));
	        if (msg->remote_event_size_bytes){
	                memcpy(m_data, model_net_method_get_edata(TORUS, msg),
        	               msg->remote_event_size_bytes);
      		}
		
                msg_new->type = T_COLLECTIVE_FAN_OUT;
                msg_new->sender_node = s->node_id;

                tw_event_send(e_new);
           }
      }
932
}
933 934 935 936 937 938 939
	     
static void node_collective_fan_out(nodes_state * s,
                        tw_bf * bf,
                        nodes_message * msg,
                        tw_lp * lp)
{
        int i;
940 941 942
        //TODO: be annotation-aware
        int num_lps = codes_mapping_get_lp_count(grp_name, 1, LP_CONFIG_NM,
                NULL, 1);
943 944 945
        bf->c1 = 0;
        bf->c2 = 0;

946
        send_remote_event(s, msg, lp);
947

948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
        if(!s->is_leaf)
        {
            bf->c1 = 1;
            tw_event* e_new;
            nodes_message * msg_new;
            tw_stime xfer_to_nic_time;

           for( i = 0; i < s->num_children; i++ )
           {
                xfer_to_nic_time = g_tw_lookahead + TORUS_FAN_OUT_DELAY + tw_rand_exponential(lp->rng, (double)TORUS_FAN_OUT_DELAY/10);

                if(s->children[i] > 0)
                {
                        tw_lpid child_nic_id;

                        /* get global LP ID of the child node */
964 965 966
                        codes_mapping_get_lp_id(grp_name, LP_CONFIG_NM, NULL, 1,
                                s->children[i]/num_lps,
                                (s->children[i] % num_lps), &child_nic_id);
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
                        //e_new = codes_event_new(child_nic_id, xfer_to_nic_time, lp);
                        //msg_new = tw_event_data(e_new);
                        //memcpy(msg_new, msg, sizeof(nodes_message) + msg->remote_event_size_bytes);
			void* m_data;
			e_new = model_net_method_event_new(child_nic_id,
							xfer_to_nic_time,
					                lp, TORUS, (void**)&msg_new, &m_data);
		        memcpy(msg_new, msg, sizeof(nodes_message));
		        if (msg->remote_event_size_bytes){
			        memcpy(m_data, model_net_method_get_edata(TORUS, msg),
			                msg->remote_event_size_bytes);
      			}


                        msg_new->type = T_COLLECTIVE_FAN_OUT;
                        msg_new->sender_node = s->node_id;
                        tw_event_send(e_new);
                }
           }
         }
	//printf("\n Fan out phase completed %ld ", lp->gid);
        if(max_collective < tw_now(lp) - s->collective_init_time )
          {
              bf->c2 = 1;
              max_collective = tw_now(lp) - s->collective_init_time;
          }
}
    
995 996 997 998 999 1000
/*Returns the next neighbor to which the packet should be routed by using DOR (Taken from Ning's code of the torus model)*/
static void dimension_order_routing( nodes_state * s,
			     tw_lpid * dst_lp, 
			     int * dim, 
			     int * dir )
{
1001 1002
     int dest[s->params->n_dims];
     int dest_id;
1003

1004 1005 1006 1007
  /* dummys - check later */
  *dim = -1;
  *dir = -1;

1008 1009
  to_dim_id(codes_mapping_get_lp_relative_id(*dst_lp, 0, 1),
          s->params->n_dims, s->params->dim_length, dest);
1010

1011
  for(int i = 0; i < s->params->n_dims; i++ )
1012
    {
1013
      if ( s->dim_position[ i ] - dest[ i ] > s->params->half_length[ i ] )
1014 1015 1016 1017 1018 1019
	{
	  dest_id = s->neighbour_plus_lpID[ i ];
	  *dim = i;
	  *dir = 1;
	  break;
	}
1020
      if ( s->dim_position[ i ] - dest[ i ] < -s->params->half_length[ i ] )
1021 1022 1023 1024 1025 1026
	{
	  dest_id = s->neighbour_minus_lpID[ i ];
	  *dim = i;
	  *dir = 0;
	  break;
	}
1027 1028
      if ( ( s->dim_position[i] - dest[i] <= s->params->half_length[i] ) &&
              ( s->dim_position[ i ] - dest[ i ] > 0 ) )
1029 1030 1031 1032 1033 1034
	{
	  dest_id = s->neighbour_minus_lpID[ i ];
	  *dim = i;
	  *dir = 0;
	  break;
	}
1035 1036
      if (( s->dim_position[i] - dest[i] >= -s->params->half_length[i] ) &&
              ( s->dim_position[ i ] - dest[ i ] < 0) )
1037 1038 1039 1040 1041 1042 1043
	{
	  dest_id = s->neighbour_plus_lpID[ i ];
	  *dim = i;
	  *dir = 1;
	  break;
	}
    }
1044 1045

  assert(*dim != -1 && *dir != -1);
1046 1047
  *dst_lp = codes_mapping_get_lpid_from_relative(dest_id, NULL, LP_CONFIG_NM,
          s->anno, 1);
1048
}
1049
static void packet_generate( nodes_state * ns, 
1050 1051
        tw_bf * bf, 
        nodes_message * msg, 
1052 1053
        tw_lp * lp)
{
1054
    int tmp_dir=-1, tmp_dim=-1, queue, total_event_size;
1055
    tw_stime ts;
1056
    tw_event * e;
1057
    nodes_message *m;
1058
    
1059 1060
    tw_lpid intm_dst = msg->dest_lp;
    dimension_order_routing(ns, &intm_dst, &tmp_dim, &tmp_dir);
1061
    queue = tmp_dir + ( tmp_dim * 2 );
1062

1063
    msg->packet_ID = ns->packet_counter;
1064
    msg->my_N_hop = 0;
1065

1066 1067 1068 1069
    if(lp->gid == TRACK && msg->packet_ID == TRACE)
        tw_output(lp, "\n packet generated %lld at lp %d dest %d final dest %d", 
        msg->packet_ID, (int)lp->gid, (int)intm_dst, (int)msg->dest_lp);
    
1070
    uint64_t num_chunks = msg->packet_size/ns->params->chunk_size;
1071
    if(msg->packet_size % ns->params->chunk_size)
1072
        num_chunks++;
1073 1074
    if(!num_chunks)
        num_chunks = 1;
1075

1076
    ns->packet_counter++;
1077

1078 1079
    msg->source_direction = tmp_dir;
    msg->source_dim = tmp_dim;
1080 1081
    msg->next_stop = intm_dst;
    msg->saved_queue = -1;
1082

1083
    for(uint64_t j = 0; j < num_chunks; j++) { 
1084 1085
        nodes_message_list * cur_chunk = (nodes_message_list *)malloc( 
                sizeof(nodes_message_list));
1086

1087
        init_nodes_message_list(cur_chunk, msg);
1088

1089 1090 1091 1092
        if(msg->remote_event_size_bytes + msg->local_event_size_bytes > 0) {
            cur_chunk->event_data = (char*)malloc(
                msg->remote_event_size_bytes + msg->local_event_size_bytes);
        }
1093

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
        void *m_data_src = model_net_method_get_edata(TORUS, msg);
        if (msg->remote_event_size_bytes){
            memcpy(cur_chunk->event_data, m_data_src, msg->remote_event_size_bytes);
        }
        if (msg->local_event_size_bytes){
            m_data_src = (char*)m_data_src + msg->remote_event_size_bytes;
            memcpy((char*)cur_chunk->event_data + msg->remote_event_size_bytes, 
                m_data_src, msg->local_event_size_bytes);
        }
        cur_chunk->msg.chunk_id = j;
1104

1105
        append_to_node_message_list(ns->terminal_msgs,
1106 1107 1108 1109 1110 1111 1112
            ns->terminal_msgs_tail, queue, cur_chunk);
        ns->terminal_length[queue] += ns->params->chunk_size;
        ns->all_term_length += ns->params->chunk_size;
    }
  
   if(ns->in_send_loop[queue] == 0) {
       bf->c8 = 1;
1113
       ts = codes_local_latency(lp) + ns->params->cn_delay * msg->packet_size;
1114 1115 1116 1117 1118 1119 1120 1121
       e = model_net_method_event_new(lp->gid, ts, lp, TORUS, (void**)&m, NULL);
       m->type = SEND;
       m->source_direction = tmp_dir;
       m->source_dim = tmp_dim;
       ns->in_send_loop[queue] = 1;
       tw_event_send(e);
   }

1122
   /* record the statistics of the generated packets */
1123
   total_event_size = model_net_get_msg_sz(TORUS) + msg->remote_event_size_bytes + msg->local_event_size_bytes;   
1124
   mn_stats* stat;
1125
   stat = model_net_find_stats(msg->category, ns->torus_stats_array);
1126 1127
   stat->send_count++;  
   stat->send_bytes += msg->packet_size;
1128
   stat->send_time += (1/ns->params->link_bandwidth) * msg->packet_size;
1129 1130
   /* record the maximum ROSS event size */
   if(stat->max_event_size < total_event_size)
1131
	   stat->max_event_size = total_event_size;
1132
}
1133 1134
   /* record the maximum ROSS event size */

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
static void packet_generate_rc( nodes_state * s, 
		tw_bf * bf, 
		nodes_message * msg, 
		tw_lp * lp )
{
    s->packet_counter--;

    int queue = msg->source_direction + (msg->source_dim * 2);

    uint64_t num_chunks = msg->packet_size/s->params->chunk_size;
    if(msg->packet_size % s->params->chunk_size)
       num_chunks++;

     if(!num_chunks)
        num_chunks = 1;
    
1151
     for(uint64_t j = 0; j < num_chunks; j++)
1152
     {
1153
       nodes_message_list* cur_entry = return_tail(
1154 1155 1156 1157 1158 1159 1160
              s->terminal_msgs, s->terminal_msgs_tail, queue);
       s->terminal_length[queue] -= s->params->chunk_size;
       s->all_term_length -= s->params->chunk_size;
       delete_nodes_message_list(cur_entry);
     }

     if(bf->c8) {
1161
        codes_local_latency_reverse(lp);
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
        s->in_send_loop[queue] = 0;
     }
     mn_stats* stat;
     stat = model_net_find_stats(msg->category, s->torus_stats_array);
     stat->send_count--; 
     stat->send_bytes -= msg->packet_size;
     stat->send_time -= (1/s->params->link_bandwidth) * msg->packet_size;
}

static void packet_send_rc(nodes_state * s,
        tw_bf * bf,
        nodes_message * msg,
        tw_lp * lp)
{
    int queue = msg->source_direction + (msg->source_dim * 2);

1178
    if(bf->c1 || bf->c4)
1179
    {
1180 1181 1182 1183
        if(bf->c24)
        {
            s->last_buf_full[queue] = msg->saved_busy_time;
        }
1184 1185 1186 1187 1188 1189
        s->in_send_loop[queue] = 1;
        return;
    }
     if(bf->c3) {
         s->buffer[queue][STATICQ] -= s->params->chunk_size;
     }
1190 1191

     codes_local_latency_reverse(lp);
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
     s->next_link_available_time[queue][0] = msg->saved_available_time;

     if(bf->c20)
     {
        s->link_traffic[queue] -= msg->packet_size % s->params->chunk_size;
     }

     if(bf->c21)
     {
        s->link_traffic[queue] -= s->params->chunk_size;
     }

     if(bf->c6)
     {
        codes_local_latency_reverse(lp);
     }

1209 1210 1211
     nodes_message_list * cur_entry = rc_stack_pop(s->st);
     assert(cur_entry);

1212 1213
     if(bf->c31)
     {
1214
         prepend_to_node_message_list(s->terminal_msgs,
1215
                  s->terminal_msgs_tail, queue, cur_entry); 
1216 1217 1218 1219 1220 1221
        s->terminal_length[queue] += s->params->chunk_size;
        s->all_term_length += s->params->chunk_size;  
     }

     if(bf->c8)
     {
1222
        prepend_to_node_message_list(s->pending_msgs[queue],
1223
                s->pending_msgs_tail[queue], STATICQ, cur_entry);
1224 1225 1226 1227
     }

     if(bf->c9)
     {
1228
         codes_local_latency_reverse(lp);
1229 1230 1231 1232 1233 1234 1235
     }

     if(bf->c10)
     {
        s->in_send_loop[queue] = 1;
     }
}
1236 1237
/* send a packet from one torus node to another torus node
 A packet can be up to 256 bytes on BG/L and BG/P and up to 512 bytes on BG/Q */
1238
static void packet_send( nodes_state * s, 
1239
         tw_bf * bf, 
1240 1241 1242 1243 1244 1245
		 nodes_message * msg, 
		 tw_lp * lp )
{ 
    tw_stime ts;
    tw_event *e;
    nodes_message *m;
1246
    int isT = 0;
1247

1248
    int queue = msg->source_direction + (msg->source_dim * 2);
1249

1250 1251 1252 1253 1254 1255
    if(s->pending_msgs[queue][STATICQ] == NULL 
        && s->terminal_msgs[queue] == NULL) {
        bf->c1 = 1;
        s->in_send_loop[queue] = 0;
        return;
    }
1256

1257 1258
    nodes_message_list *cur_entry = s->pending_msgs[queue][STATICQ];
            
1259 1260 1261
    if(cur_entry == NULL) {
        /* Bubble flow control method here, checking if there are 2 empty
         * buffer slots only then forward newly injected packets */
1262 1263 1264 1265 1266 1267
                if((s->buffer[queue][STATICQ] + (2 * s->params->chunk_size) <= s->params->buffer_size)) {
                    bf->c3 = 1;
                    s->buffer[queue][STATICQ] += s->params->chunk_size;
                    cur_entry = s->terminal_msgs[queue];
                    isT = 1;
                }
1268 1269
              if(cur_entry == NULL)
              {
1270
                bf->c4 = 1;
1271 1272 1273 1274 1275 1276 1277
                if(!s->last_buf_full[queue])
                {
                    bf->c24 = 1;
                    msg->saved_busy_time = s->last_buf_full[queue];
                    s->last_buf_full[queue] = tw_now(lp);
                }

1278 1279 1280
                s->in_send_loop[queue] = 0;
                return;
            }
1281
        } 
1282

1283
    uint64_t num_chunks = cur_entry->msg.packet_size/s->params->chunk_size;
1284 1285
    if(cur_entry->msg.packet_size % s->params->chunk_size)
        num_chunks++;
1286

1287 1288 1289
    if(!num_chunks)
        num_chunks = 1;

1290 1291 1292 1293 1294 1295 1296
    double bytetime;
    if((cur_entry->msg.packet_size % s->params->chunk_size) && (cur_entry->msg.chunk_id == num_chunks - 1)) 
    {
        bytetime = s->params->head_delay * (cur_entry->msg.packet_size % s->params->chunk_size);
    } 
    else 
        bytetime = s->params->head_delay * s->params->chunk_size;
1297
    
1298
    ts = codes_local_latency(lp) + bytetime + s->params->router_delay;
1299

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    //For reverse computation 
    msg->saved_available_time = s->next_link_available_time[queue][0];
    s->next_link_available_time[queue][0] = maxd( s->next_link_available_time[queue][0], tw_now(lp) );
    s->next_link_available_time[queue][0] += ts;
    
    void * m_data;
    ts = s->next_link_available_time[queue][0] - tw_now(lp);
    e = model_net_method_event_new(cur_entry->msg.next_stop, ts,
            lp, TORUS, (void**)&m, &m_data);
    memcpy(m, &cur_entry->msg, sizeof(nodes_message));
    if (m->remote_event_size_bytes){
        memcpy(m_data, cur_entry->event_data, m->remote_event_size_bytes);
    }
1313

1314 1315 1316
//    if(cur_entry->msg.packet_ID == TRACE && lp->gid == TRACK)
//        printf("\n packet sent %lld at lp %d dest %d final dest %d", 
//        msg->packet_ID, (int)lp->gid, (int)intm_dst, (int)msg->dest_lp);
1317 1318 1319 1320
    m->type = ARRIVAL;
    m->sender_node = lp->gid;
    m->local_event_size_bytes = 0; /* We just deliver the local event here */

1321 1322 1323 1324 1325
    /*if(lp->gid == TRACK && msg->packet_ID == TRACE)
       {
        tw_output(lp, "[%d] Packet sent: next stop %d dest %d chunk %d hops %d \n", 
                lp->gid, m->next_stop, m->final_dest_gid, m->chunk_id, m->my_N_hop);
       }*/
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
    tw_event_send( e );
    if((cur_entry->msg.packet_size % s->params->chunk_size) && (cur_entry->msg.chunk_id == num_chunks - 1)) {
        bf->c20 = 1;
        s->link_traffic[queue] += cur_entry->msg.packet_size %
            s->params->chunk_size;
    } else {
        bf->c21 = 1;
        s->link_traffic[queue] += s->params->chunk_size;
    }
    
    if(cur_entry->msg.chunk_id == num_chunks - 1)
1337
    {
1338 1339 1340 1341 1342 1343 1344
        /* Invoke an event on the sending server */
        if(cur_entry->msg.local_event_size_bytes > 0)
        {
            bf->c6 = 1;
            tw_event* e_new;
            nodes_message* m_new;
            void* local_event;
1345
            e_new = tw_event_new(cur_entry->msg.sender_svr, codes_local_latency(lp), lp);
1346 1347 1348 1349 1350 1351 1352 1353
            m_new = tw_event_data(e_new);
            local_event = (char*)cur_entry->event_data + 
                cur_entry->msg.remote_event_size_bytes;
            memcpy(m_new, local_event, cur_entry->msg.local_event_size_bytes);
            tw_event_send(e_new);
        }
    }

1354
    /* isT=1 means that we can send the newly injected packets */
1355
    if(isT) {
1356
        bf->c31 = 1;
1357
        cur_entry = return_head(s->terminal_msgs, s->terminal_msgs_tail, 
1358 1359 1360 1361 1362
            queue);
        s->terminal_length[queue] -= s->params->chunk_size; 
        s->all_term_length -= s->params->chunk_size;
    } else {
        bf->c8 = 1;
1363
        cur_entry = return_head(s->pending_msgs[queue],
1364 1365 1366
            s->pending_msgs_tail[queue], STATICQ);
    }

1367
    rc_stack_push(lp, cur_entry, free_tmp, s->st);
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379

    if(isT) {
        cur_entry = s->terminal_msgs[queue];
    } else {
        cur_entry = s->pending_msgs[queue][STATICQ];
            if(cur_entry == NULL) {
                cur_entry = s->terminal_msgs[queue];
            }
    }

    if(cur_entry != NULL) {
        bf->c9 = 1;
1380
        ts = ts + codes_local_latency(lp);
1381 1382
        e = model_net_method_event_new(lp->gid, ts, lp, TORUS, (void**)&m, NULL);
        m->type = SEND;
1383 1384
        m->source_direction = msg->source_direction;
        m->source_dim = msg->source_dim;
1385 1386 1387 1388 1389
        tw_event_send(e);
    } else {
        bf->c10 = 1;
        s->in_send_loop[queue] = 0;
        return;
1390
    }
1391 1392
}

1393 1394 1395 1396 1397
static void packet_arrive_rc(nodes_state * s,
        tw_bf * bf,
        nodes_message * msg,
        tw_lp * lp)
{
1398 1399
    codes_local_latency_reverse(lp);
    s->finished_chunks--;
1400 1401 1402 1403

    if(bf->c1)
    {
        tw_rand_reverse_unif(lp->rng);
1404 1405
        s->total_data_sz -= s->params->chunk_size;
        if(bf->c2)
1406
        {
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
            struct mn_stats* stat;  
            stat = model_net_find_stats(msg->category, s->torus_stats_array);
            stat->recv_count--; 
            stat->recv_bytes -= msg->packet_size;
            stat->recv_time = msg->saved_recv_time;
            s->total_time = msg->saved_recv_time;
            N_finished_packets--;
            s->finished_packets--;

            total_time = msg->saved_total_time;
            total_hops -= msg->my_N_hop;
            s->total_hops -= msg->my_N_hop;
        
            if(bf->c3)
            {
                max_latency = msg->saved_available_time;
            }
1424

1425 1426 1427 1428
            if(bf->c31)
            {
                model_net_event_rc2(lp, &msg->event_rc);
            }
1429 1430 1431 1432 1433
        }
    }

    if(bf->c6)
    {
1434
        int queue = msg->source_channel;
1435 1436 1437 1438
        nodes_message_list * cur_entry = NULL;

       if(bf->c30)
       {
1439
        cur_entry = return_tail(s->queued_msgs[queue],   
1440 1441 1442 1443 1444 1445
                s->queued_msgs_tail[queue], STATICQ);
        s->queued_length[queue] -= s->params->chunk_size;
        if(bf->c24)
        {
            s->last_buf_full[queue] = msg->saved_busy_time;
        }
1446 1447 1448 1449
       }
        
       if(bf->c9 || bf->c11)
       {
1450
        cur_entry = return_tail(s->pending_msgs[queue],
1451 1452
                s->pending_msgs_tail[queue], STATICQ); 
        s->buffer[queue][STATICQ] -= s->params->chunk_size;
1453 1454 1455 1456 1457
        tw_rand_reverse_unif(lp->rng); 
       }

       if(bf->c8)
       {
1458
        cur_entry = return_tail(s->other_msgs,
1459 1460 1461
                s->other_msgs_tail, queue);
        if(bf->c24)
            s->last_buf_full[queue] = msg->saved_busy_time;
1462
       }
1463 1464
       assert(cur_entry);

1465 1466 1467 1468 1469
       delete_nodes_message_list(cur_entry);
        
        if(bf->c13)
        {
           codes_local_latency_reverse(lp); 
1470
           s->in_send_loop[queue] = 0; 
1471 1472
        }
    }
1473
    msg->my_N_hop--;
1474
}
1475 1476 1477
/*Processes the packet after it arrives from the neighboring torus node 
 * routes it to the next compute node if this is not the destination
 * OR if this is the destination then a remote event at the server is issued. */
1478 1479 1480 1481 1482 1483 1484 1485
static void packet_arrive( nodes_state * s, 
		    tw_bf * bf, 
		    nodes_message * msg, 
		    tw_lp * lp )
{
  tw_event *e;
  tw_stime ts;
  nodes_message *m;
1486
  mn_stats* stat;
1487

1488 1489
  ts = codes_local_latency(lp);

1490
  msg->my_N_hop++;
1491 1492
  s->finished_chunks++;

1493
  if( lp->gid == msg->dest_lp )
1494
    {
1495 1496 1497 1498 1499
          if(lp->gid == TRACK && msg->packet_ID == TRACE)
          {
              tw_output(lp, "\n packet %ld arrived at lp %d from %ld final dest %d hops %d", 
                      msg->packet_ID, (int)lp->gid, msg->sender_node, (int)msg->dest_lp, msg->my_N_hop);
          }
1500
        bf->c1 = 1;
1501 1502
        s->total_data_sz += s->params->chunk_size;

1503
        credit_send( s, lp, msg, -1);
1504

1505 1506 1507 1508
        uint64_t num_chunks = msg->packet_size/s->params->chunk_size;
        if(msg->packet_size % s->params->chunk_size)
            num_chunks++;

1509 1510 1511
        if(!num_chunks)
            num_chunks = 1;

1512 1513 1514
        if( msg->chunk_id == num_chunks - 1 )    
        {
	    bf->c2 = 1;
1515 1516 1517
	    stat = model_net_find_stats(msg->category, s->torus_stats_array);
	    stat->recv_count++;
	    stat->recv_bytes += msg->packet_size;
1518 1519
	    msg->saved_recv_time = s->total_time;
        s->total_time += tw_now( lp ) - msg->travel_start_time;
1520
        stat->recv_time += tw_now( lp ) - msg->travel_start_time;
1521 1522

	    /*count the number of packets completed overall*/
1523
	    N_finished_packets++;
1524 1525
        s->finished_packets++;

1526 1527
	    msg->saved_total_time = total_time;
        total_time += tw_now( lp ) - msg->travel_start_time;
1528
	    total_hops += msg->my_N_hop;
1529
        s->total_hops += msg->my_N_hop;
1530 1531 1532 1533 1534 1535 1536 1537 1538

	    if (max_latency < tw_now( lp ) - msg->travel_start_time) {
		  bf->c3 = 1;
		  msg->saved_available_time = max_latency;
	          max_latency=tw_now( lp ) - msg->travel_start_time;
     		}
	    // Trigger an event on receiving server
	    if(msg->remote_event_size_bytes)
	    {
1539
               void *tmp_ptr = model_net_method_get_edata(TORUS, msg);
1540
               if (msg->is_pull){
1541
                   bf->c31 = 1;
1542
                   int net_id = model_net_get_id(LP_METHOD_NM);
1543 1544 1545 1546
                   struct codes_mctx mc_dst =
                       codes_mctx_set_global_direct(msg->sender_node);
                   struct codes_mctx mc_src =
                       codes_mctx_set_global_direct(lp->gid);
1547
                   msg->event_rc = model_net_event_mctx(net_id, &mc_src, &mc_dst,
1548 1549 1550
                           msg->category, msg->sender_svr, msg->pull_size,
                           0.0, msg->remote_event_size_bytes, tmp_ptr, 0,
                           NULL, lp);
1551
               }
1552 1553
               else
               {
1554
                   e = tw_event_new(msg->final_dest_gid, ts, lp);
1555 1556
                   void * m_remote = tw_event_data(e);
                   memcpy(m_remote, tmp_ptr, msg->remote_event_size_bytes);
1557 1558
                   tw_event_send(e);
               }
1559 1560 1561 1562 1563
	    }
       }
    }
  else
    {
1564
        bf->c6 = 1;
1565
        int tmp_dir = -1, tmp_dim = -1, queue;
1566
        tw_lpid dst_lp = msg->dest_lp;
1567

1568 1569
        dimension_order_routing(s, &dst_lp, &tmp_dim, &tmp_dir);
        queue = tmp_dir + (tmp_dim * 2);
1570

1571