XdmfDSMBuffer.cpp 30.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
/*****************************************************************************/
/*                                    XDMF                                   */
/*                       eXtensible Data Model and Format                    */
/*                                                                           */
/*  Id : XdmfDSMBuffer.hpp                                                   */
/*                                                                           */
/*  Author:                                                                  */
/*     Andrew Burns                                                          */
/*     andrew.j.burns2@us.army.mil                                           */
/*     US Army Research Laboratory                                           */
/*     Aberdeen Proving Ground, MD                                           */
/*                                                                           */
/*     Copyright @ 2013 US Army Research Laboratory                          */
/*     All Rights Reserved                                                   */
/*     See Copyright.txt for details                                         */
/*                                                                           */
/*     This software is distributed WITHOUT ANY WARRANTY; without            */
/*     even the implied warranty of MERCHANTABILITY or FITNESS               */
/*     FOR A PARTICULAR PURPOSE.  See the above copyright notice             */
/*     for more information.                                                 */
/*                                                                           */
/*****************************************************************************/

/*=========================================================================
  This code is derived from an earlier work and is distributed
  with permission from, and thanks to ...
=========================================================================*/

/*============================================================================

  Project                 : H5FDdsm
  Module                  : H5FDdsmBufferService.cxx H5FDdsmBuffer.cxx

  Authors:
     John Biddiscombe     Jerome Soumagne
     biddisco@cscs.ch     soumagne@cscs.ch

  Copyright (C) CSCS - Swiss National Supercomputing Centre.
  You may use modify and and distribute this code freely providing
  1) This copyright notice appears on all copies of source code
  2) An acknowledgment appears with any substantial usage of the code
  3) If this code is contributed to any other open source project, it
  must not be reformatted such that the indentation, bracketing or
  overall style is modified significantly.

  This software is distributed WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  This work has received funding from the European Community's Seventh
  Framework Programme (FP7/2007-2013) under grant agreement 225967 âxtMuSEâOC

============================================================================*/

#include <XdmfDSMBuffer.hpp>
#include <XdmfDSMCommMPI.hpp>
#include <XdmfError.hpp>
#include <mpi.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>

XdmfDSMBuffer::XdmfDSMBuffer()
{
64 65 66 67 68 69 70 71 72 73
  this->CommChannel = XDMF_DSM_INTER_COMM;
  this->IsServer = true;
  this->StartAddress = this->EndAddress = 0;
  this->StartServerId = this->EndServerId = -1;
  this->Length = 0;
  this->TotalLength = 0;
  this->BlockLength = 0;
  this->Comm = NULL;
  this->DataPointer = NULL;
  this->IsConnected = false;
74 75 76 77
}

XdmfDSMBuffer::~XdmfDSMBuffer()
{
78 79 80 81
  if (this->DataPointer) {
    free(this->DataPointer);
  }
  this->DataPointer = NULL;
82 83 84 85
}

class XdmfDSMBuffer::CommandMsg
{
86 87 88 89 90 91
  public:
    int Opcode;
    int Source;
    int  Target;
    int Address;
    int Length;
92 93 94 95
};

class XdmfDSMBuffer::InfoMsg
{
96 97 98 99 100 101 102
  public:
    int type;
    unsigned int length;
    unsigned int total_length;
    unsigned int block_length;
    int start_server_id;
    int end_server_id;
103 104
};

105 106 107 108 109 110 111 112 113 114 115 116 117 118
int
XdmfDSMBuffer::AddressToId(int Address)
{
  int   ServerId = XDMF_DSM_FAIL;

  switch(this->DsmType) {
    case XDMF_DSM_TYPE_UNIFORM :
    case XDMF_DSM_TYPE_UNIFORM_RANGE :
      // All Servers have same length
      // This finds out which server the address provided starts on
      ServerId = this->StartServerId + (Address / this->Length);
      if(ServerId > this->EndServerId ){
        try {
          std::stringstream message;
119 120 121
          message << "ServerId " << ServerId << " for Address "
                  << Address << " is larger than EndServerId "
                  << this->EndServerId;
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
          XdmfError::message(XdmfError::FATAL, message.str());
        }
        catch (XdmfError e) {
          throw e;
        }
      }
      break;
    default :
      // Not Implemented
      try {
        std::stringstream message;
        message << "DsmType " << this->DsmType << " not yet implemented";
        XdmfError::message(XdmfError::FATAL, message.str());
      }
      catch (XdmfError e) {
        throw e;
      }
      break;
    }
    return(ServerId);
}

void
XdmfDSMBuffer::BroadcastComm(int *comm, int root)
{
  int status;

  status = MPI_Bcast(comm, sizeof(int), MPI_UNSIGNED_CHAR, root, this->Comm->GetIntraComm());
  if (status != MPI_SUCCESS) {
    try {
      XdmfError(XdmfError::FATAL, "Broadcast of Comm failed");
    }
    catch (XdmfError e) {
      throw e;
    }
  }
}

int
XdmfDSMBuffer::BufferService(int *returnOpcode)
{
  int        opcode, who, status = XDMF_DSM_FAIL;
  int        aLength;
  int          address;
  char        *datap;
  static int syncId      = -1;

  if (this->CommChannel == XDMF_DSM_ANY_COMM) {
    if (this->Comm->GetId() == 0) {
      try {
        this->ProbeCommandHeader(&this->CommChannel);
      }
      catch (XdmfError e) {
        throw e;
      }
    }
    try {
      this->BroadcastComm(&this->CommChannel, 0);
    }
    catch (XdmfError e) {
      throw e;
    }
  }

  try {
187 188 189 190 191 192
    this->ReceiveCommandHeader(&opcode,
                               &who,
                               &address,
                               &aLength,
                               this->CommChannel,
                               syncId);
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  }
  catch (XdmfError e) {
    throw e;
  }

  // Connection is an ID for client or server,
  int communicatorId = this->CommChannel;

  switch(opcode) {

  // H5FD_DSM_OPCODE_PUT
  case XDMF_DSM_OPCODE_PUT:
    if (((unsigned int) aLength + address) > this->Length) {
      try {
        std::stringstream message;
208 209 210
        message << "Length " << aLength << " too long for Address " << address 
                << "\n" << "Server Start = " << this->StartAddress << " End = "
                << this->EndAddress;
211 212 213 214 215 216 217 218
        XdmfError::message(XdmfError::FATAL, message.str());
      }
      catch (XdmfError e) {
        throw e;
      }
    }
    if ((datap = this->DataPointer) == NULL) {
       try {
219 220
         XdmfError::message(XdmfError::FATAL,
                            "Null Data Pointer when trying to put data");
221 222 223 224 225 226 227
       }
       catch (XdmfError e) {
         throw e;
       }
    }
    datap += address;
    try {
228 229 230 231 232 233
      this->ReceiveData(who,
                        datap,
                        aLength,
                        XDMF_DSM_PUT_DATA_TAG,
                        0,
                        this->CommChannel);
234 235 236 237 238 239 240 241 242 243 244
    }
    catch (XdmfError e) {
      throw e;
    }
    break;

  // H5FD_DSM_OPCODE_GET
  case XDMF_DSM_OPCODE_GET:
    if (((unsigned int) aLength + address) > this->Length) {
      try {
        std::stringstream message;
245 246 247
        message << "Length " << aLength << " too long for Address " << address
                << "\n" << "Server Start = " << this->StartAddress << " End = "
                << this->EndAddress;
248 249 250 251 252 253 254 255
        XdmfError::message(XdmfError::FATAL, message.str());
      }
      catch (XdmfError e) {
        throw e;
      }
    }
    if ((datap = this->DataPointer) == NULL) {
      try {
256 257
         XdmfError::message(XdmfError::FATAL,
                            "Null Data Pointer when trying to put data");
258 259 260 261 262 263 264
       }
       catch (XdmfError e) {
         throw e;
       }
    }
    datap += address;
    try {
265 266 267 268 269 270
      this->SendData(who,
                     datap,
                     aLength,
                     XDMF_DSM_GET_DATA_TAG,
                     0,
                     this->CommChannel);
271 272 273 274 275 276 277 278 279 280
    }
    catch (XdmfError e) {
      throw e;
    }
    break;

// H5FD_DSM_ACCEPT
  // Comes from client
  case XDMF_DSM_ACCEPT:
    int numConnections;	
281 282 283 284
    this->ReceiveAcknowledgment(who,
                                numConnections,
                                XDMF_DSM_EXCHANGE_TAG,
                                XDMF_DSM_INTER_COMM);
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    this->Comm->Accept(numConnections);
    this->SendInfo();
    break;

  // H5FD_DSM_LOCK_ACQUIRE
  // Comes from client or server depending on communicator
  case XDMF_DSM_LOCK_ACQUIRE:
    // Currently unsupported
    break;

  // H5FD_DSM_LOCK_RELEASE
  // Comes from client or server depending on communicator
  case XDMF_DSM_LOCK_RELEASE:
    // Currently unsupported
    break;

  // H5FD_DSM_OPCODE_DONE
  // Always received on server
  case XDMF_DSM_OPCODE_DONE:
    break;

  // DEFAULT
  default :
    try {
      std::stringstream message;
      message << "Error: Unknown Opcode " << opcode;
      XdmfError::message(XdmfError::FATAL, message.str());
    }
    catch (XdmfError e) {
      throw e;
    }
  }

  if (returnOpcode) *returnOpcode = opcode;
  return(XDMF_DSM_SUCCESS);
}

void
XdmfDSMBuffer::BufferServiceLoop(int *returnOpcode)
{
  int op, status = XDMF_DSM_SUCCESS;
  while (status == XDMF_DSM_SUCCESS) {
    try {
      status = this->BufferService(&op);
    }
    catch (XdmfError e) {
      throw e;
    }
    if (returnOpcode) *returnOpcode = op;
    if (op == XDMF_DSM_OPCODE_DONE) {
      break;
    }
  }
}

340 341 342 343 344
void
XdmfDSMBuffer::ConfigureUniform(XdmfDSMCommMPI *aComm, long aLength,
                                int startId, int endId, long aBlockLength,
                                bool random)
{
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
  if (startId < 0) {
    startId = 0;
  }
  if (endId < 0) {
    endId = aComm->GetIntraSize() - 1;
  }
  this->SetDsmType(XDMF_DSM_TYPE_UNIFORM_RANGE);
  if ((startId == 0) && (endId == aComm->GetIntraSize() - 1)) {
    this->SetDsmType(XDMF_DSM_TYPE_UNIFORM);
  }
  if (aBlockLength) {
    if (!random) {
      this->SetDsmType(XDMF_DSM_TYPE_BLOCK_CYCLIC);
    }
    else {
      this->SetDsmType(XDMF_DSM_TYPE_BLOCK_RANDOM);
    }
    this->SetBlockLength(aBlockLength);
  }
  this->StartServerId = startId;
  this->EndServerId = endId;
  this->SetComm(aComm);
367 368 369
  if ((aComm->GetId() >= startId) &&
      (aComm->GetId() <= endId) &&
      this->IsServer) {
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    try {
      if (aBlockLength) {
        // For optimization we make the DSM length fit to a multiple of block size
        this->SetLength(((long)(aLength / aBlockLength)) * aBlockLength);
      }
      else {
        this->SetLength(aLength);
      }
    }
    catch (XdmfError e) {
      throw e;
    }
    this->StartAddress = (aComm->GetId() - startId) * aLength;
    this->EndAddress = this->StartAddress + aLength - 1;
  }
  else {
    if (aBlockLength) {
      this->Length = ((long)(aLength / aBlockLength)) * aBlockLength;
    }
    else {
      this->Length = aLength;
    }
  }
  this->TotalLength = this->GetLength() * (endId - startId + 1);
394 395 396
}

void
397
XdmfDSMBuffer::Get(long Address, long aLength, void *Data)
398
{
399 400 401
  int   who, MyId = this->Comm->GetInterId();
  int   astart, aend, len;
  char   *datap = (char *)Data;
402

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
  // While there is length left
  while(aLength) {
    // Figure out what server core the address is located on
    who = this->AddressToId(Address);
    if(who == XDMF_DSM_FAIL){
      try {
        XdmfError::message(XdmfError::FATAL, "Address Error");
      }
      catch (XdmfError e) {
        throw e;
      }
    }
    // Get the start and end of the block listed
    this->GetAddressRangeForId(who, &astart, &aend);
    // Determine the amount of data to be written to that core
418 419
    // Basically, it's how much data will fit from
    // the starting point of the address to the end
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
    len = std::min(aLength, aend - Address + 1);
    // If the data is on the core running this code, then the put is simple
    if(who == MyId){
      char *dp;
      dp = this->DataPointer;
      dp += Address - this->StartAddress;
      memcpy(datap, dp, len);
    }
    else{
      // Otherwise send it to the appropriate core to deal with
      int   status;
      int   dataComm = XDMF_DSM_INTRA_COMM;
      if (this->Comm->GetInterComm() != MPI_COMM_NULL) {
        dataComm = XDMF_DSM_INTER_COMM;
      }
      try {
        this->SendCommandHeader(XDMF_DSM_OPCODE_GET, who, Address - astart, len, dataComm);
      }
      catch (XdmfError e) {
        throw e;
      }
      try {
        this->ReceiveData(who, datap, len, XDMF_DSM_GET_DATA_TAG, Address - astart, dataComm);
      }
      catch (XdmfError e) {
        throw e;
      }
    }
    // Shift all the numbers by the length of the data written
    // Until aLength = 0
    aLength -= len;
    Address += len;
    datap += len;
  }
454 455
}

456 457 458 459 460 461
void
XdmfDSMBuffer::GetAddressRangeForId(int Id, int *Start, int *End){
    switch(this->DsmType) {
      case XDMF_DSM_TYPE_UNIFORM :
      case XDMF_DSM_TYPE_UNIFORM_RANGE :
        // All Servers have same length
462 463 464 465
        // Start index is equal to the id inside the servers times
        // the length of the block per server
        // It is the starting index of the server's data block relative
        // to the entire block
466
        *Start = (Id - this->StartServerId) * this->Length;
467 468
        // End index is simply the start index + the length of the
        // server's data block.
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        // The range produced is the start of the server's data block to its end.
        *End = *Start + Length - 1;
        break;
      default :
        // Not Implemented
        try {
          std::stringstream message;
          message << "DsmType " << this->DsmType << " not yet implemented";
          XdmfError::message(XdmfError::FATAL, message.str());
        }
        catch (XdmfError e) {
          throw e;
        }
        break;
    }
}

long
XdmfDSMBuffer::GetBlockLength()
488
{
489
  return this->BlockLength;
490 491
}

492 493
XdmfDSMCommMPI *
XdmfDSMBuffer::GetComm()
494
{
495
  return this->Comm;
496 497
}

498 499
char *
XdmfDSMBuffer::GetDataPointer()
500
{
501
  return this->DataPointer;
502 503
}

504 505
int
XdmfDSMBuffer::GetDsmType()
506
{
507
  return this->DsmType;
508 509
}

510 511
int
XdmfDSMBuffer::GetEndAddress()
512
{
513
  return this->EndAddress;
514 515
}

516 517
int
XdmfDSMBuffer::GetEndServerId()
518
{
519
  return this->EndServerId;
520 521
}

522 523
bool
XdmfDSMBuffer::GetIsConnected()
524
{
525
  return IsConnected;
526 527
}

528 529
bool
XdmfDSMBuffer::GetIsServer()
530
{
531
  return this->IsServer;
532 533
}

534 535
long
XdmfDSMBuffer::GetLength()
536
{
537 538
  return this->Length;
}
539

540 541 542 543
int
XdmfDSMBuffer::GetStartAddress()
{
  return this->StartAddress;
544 545
}

546 547
int
XdmfDSMBuffer::GetStartServerId()
548
{
549 550
  return this->StartServerId;
}
551

552 553 554 555
long
XdmfDSMBuffer::GetTotalLength()
{
  return this->TotalLength;
556 557 558
}

void
559
XdmfDSMBuffer::ProbeCommandHeader(int *comm)
560
{
561 562
  // Used for finding a comm that has a waiting command, then sets the comm
  int status = XDMF_DSM_FAIL;
563 564
  MPI_Status signalStatus;

565
  int flag;
566 567
  MPI_Comm probeComm =
    static_cast<XdmfDSMCommMPI *>(this->Comm)->GetIntraComm();
568

569 570
  // Spin until a message is found on one of the communicators
  while (status != XDMF_DSM_SUCCESS) {
571 572 573 574 575
    status = MPI_Iprobe(XDMF_DSM_ANY_SOURCE,
                        XDMF_DSM_ANY_TAG,
                        probeComm,
                        &flag,
                        &signalStatus);
576 577 578
    if (status != MPI_SUCCESS)
    {
       try {
579 580
         XdmfError::message(XdmfError::FATAL,
                            "Error: Failed to probe for command header");
581 582 583 584 585 586 587 588 589 590 591 592
       }
       catch (XdmfError e) {
         throw e;
       }
    }
    if (flag) {
      status = XDMF_DSM_SUCCESS;
    }
    else {
      if (static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm() != MPI_COMM_NULL) {
        if (probeComm == static_cast<XdmfDSMCommMPI *>(this->Comm)->GetIntraComm()) {
          probeComm = static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm();
593 594
  }
  else {
595
          probeComm = static_cast<XdmfDSMCommMPI *>(this->Comm)->GetIntraComm();
596
  }
597
      }
598 599
    }
  }
600 601 602 603 604 605
  if (probeComm == static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm()) {
    *comm = XDMF_DSM_INTER_COMM;
  }
  else
  {
    *comm = XDMF_DSM_INTRA_COMM;
606
  }
607

608 609
  probeComm = MPI_COMM_NULL;
}
610 611

void
612
XdmfDSMBuffer::Put(long Address, long aLength, const void *Data)
613
{
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
  int   who, MyId = this->Comm->GetInterId();
  int   astart, aend, len;
  char    *datap = (char *)Data;

  // While there is length left
  while(aLength){
    // Figure out what server core the address is located on
    who = this->AddressToId(Address);
    if(who == XDMF_DSM_FAIL){
      try {
        XdmfError::message(XdmfError::FATAL, "Address Error");
      }
      catch (XdmfError e) {
        throw e;
      }
629
    }
630 631 632
    // Get the start and end of the block listed
    this->GetAddressRangeForId(who, &astart, &aend);
    // Determine the amount of data to be written to that core
633 634
    // Basically, it's how much data will fit from the starting point of
    // the address to the end
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
    len = std::min(aLength, aend - Address + 1);
    // If the data is on the core running this code, then the put is simple
    if(who == MyId){
      char *dp;
      dp = this->DataPointer;
      dp += Address - this->StartAddress;
      memcpy(dp, datap, len);
    }
    else{
      // Otherwise send it to the appropriate core to deal with
      int   status;
      int   dataComm = XDMF_DSM_INTRA_COMM;
      if (this->Comm->GetInterComm() != MPI_COMM_NULL) {
        dataComm = XDMF_DSM_INTER_COMM;
      }
      try {
651 652 653 654 655
        this->SendCommandHeader(XDMF_DSM_OPCODE_PUT,
                                who,
                                Address - astart,
                                len,
                                dataComm);
656 657 658 659 660
      }
      catch (XdmfError e) {
        throw e;
      }
      try {
661 662 663 664 665 666
        this->SendData(who,
                       datap, 
                       len,
                       XDMF_DSM_PUT_DATA_TAG,
                       Address - astart,
                       dataComm);
667 668 669 670
      }
      catch (XdmfError e) {
        throw e;
      }
671
    }
672 673 674 675 676
    // Shift all the numbers by the length of the data written
    // Until aLength = 0
    aLength -= len;
    Address += len;
    datap += len;
677
  }
678 679 680
}

void
681
XdmfDSMBuffer::ReceiveAcknowledgment(int source, int &data, int tag, int comm)
682
{
683 684 685
  int status;
  MPI_Status signalStatus;
  if (comm == XDMF_DSM_INTRA_COMM) {
686 687 688 689 690 691 692
    status = MPI_Recv(&data, 
                      sizeof(int), 
                      MPI_UNSIGNED_CHAR, 
                      source, 
                      tag, 
                      static_cast<XdmfDSMCommMPI *>(this->Comm)->GetIntraComm(),
                      &signalStatus);
693 694
  }
  else if (comm == XDMF_DSM_INTER_COMM) {
695 696 697 698 699 700 701
    status = MPI_Recv(&data,
                      sizeof(int),
                      MPI_UNSIGNED_CHAR,
                      source,
                      tag,
                      static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm(),
                      &signalStatus);
702 703
  }
  else {
704
    MPI_Comm tempComm = MPI_Comm_f2c(comm);
705 706 707 708 709
    status = MPI_Recv(&data,
                      sizeof(int),
                      MPI_UNSIGNED_CHAR,
                      source,
                      tag,
710
                      tempComm,
711
                      &signalStatus);
712
  }
713

714 715 716 717 718 719 720 721
  if (status != MPI_SUCCESS) {
    try {
      XdmfError::message(XdmfError::FATAL, "Error: Failed to receive data");
    }
    catch (XdmfError e) {
      throw e;
    }
  }
722 723 724
}

void
725
XdmfDSMBuffer::ReceiveCommandHeader(int *opcode, int *source, int *address, int *aLength, int comm, int remoteSource)
726
{
727 728 729 730 731 732 733 734
  CommandMsg cmd;
  memset(&cmd, 0, sizeof(CommandMsg));
  int status = MPI_ERR_OTHER;
  MPI_Status signalStatus;

  if (remoteSource < 0) {
    remoteSource = MPI_ANY_SOURCE;
  }
735 736

  if (comm == XDMF_DSM_INTRA_COMM) {
737 738 739 740 741 742 743
    status = MPI_Recv(&cmd,
                      sizeof(CommandMsg),
                      MPI_UNSIGNED_CHAR,
                      remoteSource,
                      XDMF_DSM_COMMAND_TAG,
                      static_cast<XdmfDSMCommMPI *>(this->Comm)->GetIntraComm(),
                      &signalStatus);
744 745
  }
  else if (comm == XDMF_DSM_INTER_COMM) {
746 747 748 749 750 751 752
    status = MPI_Recv(&cmd,
                      sizeof(CommandMsg),
                      MPI_UNSIGNED_CHAR,
                      remoteSource,
                      XDMF_DSM_COMMAND_TAG,
                      static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm(),
                      &signalStatus);
753 754
  }
  else {
755
    // In this case the integer is probably a pointer to an MPI_Comm object
756
    MPI_Comm tempComm = MPI_Comm_f2c(comm);
757 758 759 760 761
    status = MPI_Recv(&cmd,
                      sizeof(CommandMsg),
                      MPI_UNSIGNED_CHAR,
                      remoteSource,
                      XDMF_DSM_COMMAND_TAG,
762
                      tempComm,
763
                      &signalStatus);
764
  }
765

766 767
  if (status != MPI_SUCCESS) {
    try {
768
      XdmfError::message(XdmfError::FATAL, "Error: Failed to receive command header");
769 770 771 772 773
    }
    catch (XdmfError e) {
      throw e;
    }
  }
774 775 776 777 778 779
  else {
    *opcode  = cmd.Opcode;
                *source  = cmd.Source;
    *address = cmd.Address;
    *aLength = cmd.Length;
  }
780 781 782
}

void
783
XdmfDSMBuffer::ReceiveData(int source, char * data, int aLength, int tag, int aAddress, int comm)
784
{
785 786 787
  int status;
  MPI_Status signalStatus;
  if (comm == XDMF_DSM_INTRA_COMM) {
788 789 790 791 792 793 794
    status = MPI_Recv(data,
                      aLength,
                      MPI_UNSIGNED_CHAR,
                      source,
                      tag,
                      static_cast<XdmfDSMCommMPI *>(this->Comm)->GetIntraComm(),
                      &signalStatus);
795 796
  }
  else if (comm == XDMF_DSM_INTER_COMM) {
797 798 799 800 801 802 803
    status = MPI_Recv(data,
                      aLength,
                      MPI_UNSIGNED_CHAR,
                      source,
                      tag,
                      static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm(),
                      &signalStatus);
804 805
  }
  else {
806
    MPI_Comm tempComm = MPI_Comm_f2c(comm);
807 808 809 810 811
    status = MPI_Recv(data,
                      aLength,
                      MPI_UNSIGNED_CHAR,
                      source,
                      tag,
812
                      tempComm,
813
                      &signalStatus);
814 815 816 817 818 819 820 821 822
  }
  if (status != MPI_SUCCESS) {
    try {
      XdmfError::message(XdmfError::FATAL, "Error: Failed to receive data");
    }
    catch (XdmfError e) {
      throw e;
    }
  }
823 824 825
}

void
826
XdmfDSMBuffer::ReceiveInfo()
827
{
828 829
  InfoMsg  dsmInfo;
  int status;
830
  MPI_Status signalStatus;
831 832

  memset(&dsmInfo, 0, sizeof(InfoMsg));
833 834 835

  int infoStatus = 0;

836
  if (this->Comm->GetId() == 0) {
837
    infoStatus = 1;
838
  }
839

840
  int * groupInfoStatus = new int[this->Comm->GetInterSize()]();
841

842
  MPI_Allgather(&infoStatus, 1, MPI_INT, &(groupInfoStatus[0]), 1, MPI_INT, this->Comm->GetInterComm());
843 844 845 846 847 848

  int sendCore = 0;

  for (int i = 0; i < this->Comm->GetInterSize(); ++i) {
    if (groupInfoStatus[i] == 2) {
      sendCore = i;
849 850
    }
  }
851 852 853 854 855
  status = MPI_Bcast(&dsmInfo, 
                     sizeof(InfoMsg),
                     MPI_UNSIGNED_CHAR,
                     sendCore,
                     static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm());
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
  if (status != MPI_SUCCESS) {
    try {
      XdmfError::message(XdmfError::FATAL, "Error: Failed to broadcast info");
    }
    catch (XdmfError e) {
      throw e;
    }
  }
  this->SetDsmType(dsmInfo.type);
  // We are a client so don't allocate anything but only set a virtual remote length
  this->SetLength(dsmInfo.length);
  this->TotalLength = dsmInfo.total_length;
  this->SetBlockLength(dsmInfo.block_length);
  this->StartServerId = dsmInfo.start_server_id;
  this->EndServerId = dsmInfo.end_server_id;
871 872 873
}

void
874 875
XdmfDSMBuffer::SendAccept(unsigned int numConnections)
{
876
  for (int i = this->StartServerId; i <= this->EndServerId; ++i) {
877
    if (i != this->Comm->GetInterId()){
878 879
      this->SendCommandHeader(XDMF_DSM_ACCEPT, i, 0, 0, XDMF_DSM_INTER_COMM);
      this->SendAcknowledgment(i, numConnections, XDMF_DSM_EXCHANGE_TAG, XDMF_DSM_INTER_COMM);
880 881 882 883 884 885 886 887
    }
  }
  this->Comm->Accept(numConnections);
  this->SendInfo();
}

void
XdmfDSMBuffer::SendAcknowledgment(int dest, int data, int tag, int comm)
888
{
889 890
  int status;

891
  if (comm == XDMF_DSM_INTRA_COMM) {
892 893 894 895 896 897
    status = MPI_Send(&data,
             sizeof(int),
             MPI_UNSIGNED_CHAR,
             dest,
             tag,
             static_cast<XdmfDSMCommMPI *>(this->Comm)->GetIntraComm());
898 899
  }
  else if (comm == XDMF_DSM_INTER_COMM) {
900 901 902 903 904 905
    status = MPI_Send(&data,
                      sizeof(int),
                      MPI_UNSIGNED_CHAR,
                      dest,
                      tag,
                      static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm());
906 907
  }
  else {
908
    MPI_Comm tempComm = MPI_Comm_f2c(comm);
909 910 911 912 913
    status = MPI_Send(&data,
                      sizeof(int),
                      MPI_UNSIGNED_CHAR,
                      dest,
                      tag,
914
                      tempComm);
915
  }
916 917
  if (status != MPI_SUCCESS) {
    try {
918
      XdmfError::message(XdmfError::FATAL, "Error: Failed to receive data");
919 920 921 922 923
    }
    catch (XdmfError e) {
      throw e;
    }
  }
924 925 926
}

void
927
XdmfDSMBuffer::SendCommandHeader(int opcode, int dest, int address, int aLength, int comm)
928
{
929 930 931 932 933 934 935 936 937 938
  int status;
  CommandMsg cmd;
  memset(&cmd, 0, sizeof(CommandMsg));
  cmd.Opcode = opcode;
  cmd.Source = this->Comm->GetId();
  cmd.Target = dest;
  cmd.Address = address;
  cmd.Length = aLength;

  if (comm == XDMF_DSM_INTRA_COMM) {
939 940 941 942 943 944
    status = MPI_Send(&cmd,
                      sizeof(CommandMsg),
                      MPI_UNSIGNED_CHAR,
                      dest,
                      XDMF_DSM_COMMAND_TAG,
                      static_cast<XdmfDSMCommMPI *>(this->Comm)->GetIntraComm());
945 946 947 948 949
  }
  else if (comm == XDMF_DSM_INTER_COMM) {
    int interSource = 0;
    MPI_Comm_rank(static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm(), &interSource);
    cmd.Source = interSource;
950 951 952 953 954 955
    status = MPI_Send(&cmd,
                      sizeof(CommandMsg),
                      MPI_UNSIGNED_CHAR,
                      dest,
                      XDMF_DSM_COMMAND_TAG,
                      static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm());
956 957 958
  }
  else {
    // In this case the comm should be a pointer to an MPI_Comm object
959
    MPI_Comm tempComm = MPI_Comm_f2c(comm);
960 961 962 963 964
    status = MPI_Send(&cmd,
                      sizeof(CommandMsg),
                      MPI_UNSIGNED_CHAR,
                      dest,
                      XDMF_DSM_COMMAND_TAG,
965
                      tempComm);
966 967
  }
  if (status != MPI_SUCCESS) {
968
    try {
969
      XdmfError::message(XdmfError::FATAL, "Error: Failed to send command header");
970 971 972 973 974 975 976
    }
    catch (XdmfError e) {
      throw e;
    }
  }
}

977 978
void
XdmfDSMBuffer::SendData(int dest, char * data, int aLength, int tag, int aAddress, int comm)
979
{
980 981
  int status;
  if (comm == XDMF_DSM_INTRA_COMM) {
982 983 984 985 986 987
    status = MPI_Send(data,
                      aLength,
                      MPI_UNSIGNED_CHAR,
                      dest,
                      tag,
                       static_cast<XdmfDSMCommMPI *>(this->Comm)->GetIntraComm());
988 989
  }
  else if (comm == XDMF_DSM_INTER_COMM) {
990 991 992 993 994 995
    status = MPI_Send(data,
                      aLength,
                      MPI_UNSIGNED_CHAR,
                      dest,
                      tag,
                      static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm());
996 997
  }
  else {
998 999
    MPI_Comm tempComm = MPI_Comm_f2c(comm);
    status = MPI_Send(data, aLength, MPI_UNSIGNED_CHAR, dest, tag, tempComm);
1000 1001
  }
  if (status != MPI_SUCCESS) {
1002
    try {
1003
      XdmfError::message(XdmfError::FATAL, "Error: Failed to send data");
1004 1005 1006 1007 1008
    }
    catch (XdmfError e) {
      throw e;
    }
  }
1009
}
1010

1011 1012 1013
void
XdmfDSMBuffer::SendDone()
{
1014
  try {
1015
    if (static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm() == MPI_COMM_NULL)
1016
    {
1017
      for (int i = this->StartServerId; i <= this->EndServerId; ++i) {
1018 1019 1020 1021 1022 1023 1024
        if (i != this->Comm->GetId()){
          this->SendCommandHeader(XDMF_DSM_OPCODE_DONE, i, 0, 0, XDMF_DSM_INTRA_COMM);
        }
      }
    }
    else
    {
1025
      for (int i = this->StartServerId; i <= this->EndServerId; ++i) {
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
        if (i != this->Comm->GetId()){
          this->SendCommandHeader(XDMF_DSM_OPCODE_DONE, i, 0, 0, XDMF_DSM_INTER_COMM);
        }
      }
    }
  }
  catch (XdmfError e) {
    throw e;
  }
}

void
1038
XdmfDSMBuffer::SendInfo()
1039
{
1040 1041
  InfoMsg  dsmInfo;
  int status;
1042

1043 1044 1045 1046 1047 1048 1049
  memset(&dsmInfo, 0, sizeof(InfoMsg));
  dsmInfo.type = this->GetDsmType();
  dsmInfo.length = this->GetLength();
  dsmInfo.total_length = this->GetTotalLength();
  dsmInfo.block_length = this->GetBlockLength();
  dsmInfo.start_server_id = this->GetStartServerId();
  dsmInfo.end_server_id = this->GetEndServerId();
1050

1051 1052 1053
  int infoStatus = 3;
  if (this->Comm->GetId() == 0) {
    infoStatus = 2;
1054
  }
1055

1056
  int * groupInfoStatus = new int[this->Comm->GetInterSize()]();
1057

1058 1059 1060
  MPI_Allgather(&infoStatus,
                1,
                MPI_INT,
1061
                &(groupInfoStatus[0]),
1062 1063 1064
                1,
                MPI_INT,
                this->Comm->GetInterComm());
1065 1066 1067 1068 1069 1070

  int sendCore = 0;

  for (int i = 0; i < this->Comm->GetInterSize(); ++i) {
    if (groupInfoStatus[i] == 2) {
      sendCore = i;
1071 1072 1073
    }
  }

1074 1075 1076 1077 1078
  status = MPI_Bcast(&dsmInfo,
                     sizeof(InfoMsg),
                     MPI_UNSIGNED_CHAR,
                     sendCore,
                     static_cast<XdmfDSMCommMPI *>(this->Comm)->GetInterComm());
1079 1080 1081 1082 1083 1084 1085 1086
  if (status != MPI_SUCCESS) {
    try {
      XdmfError::message(XdmfError::FATAL, "Error: Failed to send info");
    }
    catch (XdmfError e) {
      throw e;
    }
  }
1087 1088
}

1089 1090
void
XdmfDSMBuffer::SetBlockLength(long newBlock)
1091
{
1092 1093
  this->BlockLength = newBlock;
}
1094

1095 1096 1097 1098
void
XdmfDSMBuffer::SetComm(XdmfDSMCommMPI * newComm)
{
  this->Comm = newComm;
1099 1100 1101
}

void
1102 1103 1104
XdmfDSMBuffer::SetDsmType(int newDsmType)
{
  this->DsmType = newDsmType;
1105 1106 1107
}

void
1108
XdmfDSMBuffer::SetIsConnected(bool newStatus)
1109
{
1110 1111
  IsConnected =  newStatus;
}
1112

1113 1114 1115 1116
void
XdmfDSMBuffer::SetIsServer(bool newIsServer)
{
  this->IsServer = newIsServer;
1117 1118 1119
}

void
1120
XdmfDSMBuffer::SetLength(long aLength)
1121
{
1122 1123 1124 1125
  this->Length = aLength;
  if (this->DataPointer) {
    // Try to reallocate
    // This should not be called in most cases
1126 1127
    this->DataPointer =
      static_cast<char *>(realloc(this->DataPointer, this->Length*sizeof(char)));
1128 1129 1130 1131 1132 1133 1134 1135 1136
  }
  else {
#ifdef _WIN32
    this->DataPointer = calloc(this->Length, sizeof(char));
#else
    posix_memalign((void **)(&this->DataPointer), getpagesize(), this->Length);
    memset(this->DataPointer, 0, this->Length);
#endif
  }
1137

1138 1139 1140 1141
  if (this->DataPointer == NULL) {
    std::stringstream message;
    message << "Allocation Failed, unable to allocate " << this->Length;
    XdmfError::message(XdmfError::FATAL, message.str());
1142
  }
1143
}