source: GenericIO.cxx @ abca157

Revision abca157, 55.9 KB checked in by Hal Finkel <hfinkel@…>, 6 years ago (diff)

fix the SZ size check

  • Property mode set to 100644
Line 
1/*
2 *                    Copyright (C) 2015, UChicago Argonne, LLC
3 *                               All Rights Reserved
4 *
5 *                               Generic IO (ANL-15-066)
6 *                     Hal Finkel, Argonne National Laboratory
7 *
8 *                              OPEN SOURCE LICENSE
9 *
10 * Under the terms of Contract No. DE-AC02-06CH11357 with UChicago Argonne,
11 * LLC, the U.S. Government retains certain rights in this software.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions are met:
15 *
16 *   1. Redistributions of source code must retain the above copyright notice,
17 *      this list of conditions and the following disclaimer.
18 *
19 *   2. Redistributions in binary form must reproduce the above copyright
20 *      notice, this list of conditions and the following disclaimer in the
21 *      documentation and/or other materials provided with the distribution.
22 *
23 *   3. Neither the names of UChicago Argonne, LLC or the Department of Energy
24 *      nor the names of its contributors may be used to endorse or promote
25 *      products derived from this software without specific prior written
26 *      permission.
27 *
28 * *****************************************************************************
29 *
30 *                                  DISCLAIMER
31 * THE SOFTWARE IS SUPPLIED “AS IS” WITHOUT WARRANTY OF ANY KIND.  NEITHER THE
32 * UNTED STATES GOVERNMENT, NOR THE UNITED STATES DEPARTMENT OF ENERGY, NOR
33 * UCHICAGO ARGONNE, LLC, NOR ANY OF THEIR EMPLOYEES, MAKES ANY WARRANTY,
34 * EXPRESS OR IMPLIED, OR ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE
35 * ACCURACY, COMPLETENESS, OR USEFULNESS OF ANY INFORMATION, DATA, APPARATUS,
36 * PRODUCT, OR PROCESS DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE
37 * PRIVATELY OWNED RIGHTS.
38 *
39 * *****************************************************************************
40 */
41
42#define _XOPEN_SOURCE 600
43#include "CRC64.h"
44#include "GenericIO.h"
45
46extern "C" {
47#include "blosc.h"
48}
49#include "sz.h"
50
51#include <sstream>
52#include <fstream>
53#include <stdexcept>
54#include <iterator>
55#include <algorithm>
56#include <cassert>
57#include <cstddef>
58#include <cstring>
59
60#ifndef GENERICIO_NO_MPI
61#include <ctime>
62#endif
63
64#include <sys/types.h>
65#include <sys/stat.h>
66#include <fcntl.h>
67#include <errno.h>
68
69#ifdef __bgq__
70#include <mpix.h>
71#endif
72
73#ifndef MPI_UINT64_T
74#define MPI_UINT64_T (sizeof(long) == 8 ? MPI_LONG : MPI_LONG_LONG)
75#endif
76
77using namespace std;
78
79namespace gio {
80
81
82#ifndef GENERICIO_NO_MPI
83GenericFileIO_MPI::~GenericFileIO_MPI() {
84  (void) MPI_File_close(&FH);
85}
86
87void GenericFileIO_MPI::open(const std::string &FN, bool ForReading) {
88  FileName = FN;
89
90  int amode = ForReading ? MPI_MODE_RDONLY : (MPI_MODE_WRONLY | MPI_MODE_CREATE);
91  if (MPI_File_open(Comm, const_cast<char *>(FileName.c_str()), amode,
92                    MPI_INFO_NULL, &FH) != MPI_SUCCESS)
93    throw runtime_error((!ForReading ? "Unable to create the file: " :
94                                       "Unable to open the file: ") +
95                        FileName);
96}
97
98void GenericFileIO_MPI::setSize(size_t sz) {
99  if (MPI_File_set_size(FH, sz) != MPI_SUCCESS)
100    throw runtime_error("Unable to set size for file: " + FileName);
101}
102
103void GenericFileIO_MPI::read(void *buf, size_t count, off_t offset,
104                             const std::string &D) {
105  while (count > 0) {
106    MPI_Status status;
107    if (MPI_File_read_at(FH, offset, buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
108      throw runtime_error("Unable to read " + D + " from file: " + FileName);
109
110    int scount;
111    (void) MPI_Get_count(&status, MPI_BYTE, &scount);
112
113    count -= scount;
114    buf = ((char *) buf) + scount;
115    offset += scount;
116  }
117}
118
119void GenericFileIO_MPI::write(const void *buf, size_t count, off_t offset,
120                              const std::string &D) {
121  while (count > 0) {
122    MPI_Status status;
123    if (MPI_File_write_at(FH, offset, (void *) buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
124      throw runtime_error("Unable to write " + D + " to file: " + FileName);
125
126    int scount = 0;
127    // On some systems, MPI_Get_count will not return zero even when count is zero.
128    if (count > 0)
129      (void) MPI_Get_count(&status, MPI_BYTE, &scount);
130
131    count -= scount;
132    buf = ((char *) buf) + scount;
133    offset += scount;
134  }
135}
136
137void GenericFileIO_MPICollective::read(void *buf, size_t count, off_t offset,
138                             const std::string &D) {
139  int Continue = 0;
140
141  do {
142    MPI_Status status;
143    if (MPI_File_read_at_all(FH, offset, buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
144      throw runtime_error("Unable to read " + D + " from file: " + FileName);
145
146    int scount = 0;
147    // On some systems, MPI_Get_count will not return zero even when count is zero.
148    if (count > 0)
149      (void) MPI_Get_count(&status, MPI_BYTE, &scount);
150
151    count -= scount;
152    buf = ((char *) buf) + scount;
153    offset += scount;
154
155    int NeedContinue = (count > 0);
156    MPI_Allreduce(&NeedContinue, &Continue, 1, MPI_INT, MPI_SUM, Comm);
157  } while (Continue);
158}
159
160void GenericFileIO_MPICollective::write(const void *buf, size_t count, off_t offset,
161                              const std::string &D) {
162  int Continue = 0;
163
164  do {
165    MPI_Status status;
166    if (MPI_File_write_at_all(FH, offset, (void *) buf, count, MPI_BYTE, &status) != MPI_SUCCESS)
167      throw runtime_error("Unable to write " + D + " to file: " + FileName);
168
169    int scount;
170    (void) MPI_Get_count(&status, MPI_BYTE, &scount);
171
172    count -= scount;
173    buf = ((char *) buf) + scount;
174    offset += scount;
175
176    int NeedContinue = (count > 0);
177    MPI_Allreduce(&NeedContinue, &Continue, 1, MPI_INT, MPI_SUM, Comm);
178  } while (Continue);
179}
180#endif
181
182GenericFileIO_POSIX::~GenericFileIO_POSIX() {
183  if (FH != -1) close(FH);
184}
185
186void GenericFileIO_POSIX::open(const std::string &FN, bool ForReading) {
187  FileName = FN;
188
189  int flags = ForReading ? O_RDONLY : (O_WRONLY | O_CREAT);
190  int mode = S_IRUSR | S_IWUSR | S_IRGRP;
191  errno = 0;
192  if ((FH = ::open(FileName.c_str(), flags, mode)) == -1)
193    throw runtime_error((!ForReading ? "Unable to create the file: " :
194                                       "Unable to open the file: ") +
195                        FileName + ": " + strerror(errno));
196}
197
198void GenericFileIO_POSIX::setSize(size_t sz) {
199  if (ftruncate(FH, sz) == -1)
200    throw runtime_error("Unable to set size for file: " + FileName);
201}
202
203void GenericFileIO_POSIX::read(void *buf, size_t count, off_t offset,
204                               const std::string &D) {
205  while (count > 0) {
206    ssize_t scount;
207    errno = 0;
208    if ((scount = pread(FH, buf, count, offset)) == -1) {
209      if (errno == EINTR)
210        continue;
211
212      throw runtime_error("Unable to read " + D + " from file: " + FileName +
213                          ": " + strerror(errno));
214    }
215
216    count -= scount;
217    buf = ((char *) buf) + scount;
218    offset += scount;
219  }
220}
221
222void GenericFileIO_POSIX::write(const void *buf, size_t count, off_t offset,
223                                const std::string &D) {
224  while (count > 0) {
225    ssize_t scount;
226    errno = 0;
227    if ((scount = pwrite(FH, buf, count, offset)) == -1) {
228      if (errno == EINTR)
229        continue;
230
231      throw runtime_error("Unable to write " + D + " to file: " + FileName +
232                          ": " + strerror(errno));
233    }
234
235    count -= scount;
236    buf = ((char *) buf) + scount;
237    offset += scount;
238  }
239}
240
241static bool isBigEndian() {
242  const uint32_t one = 1;
243  return !(*((char *)(&one)));
244}
245
246static void bswap(void *v, size_t s) {
247  char *p = (char *) v;
248  for (size_t i = 0; i < s/2; ++i)
249    std::swap(p[i], p[s - (i+1)]);
250}
251
252// Using #pragma pack here, instead of __attribute__((packed)) because xlc, at
253// least as of v12.1, won't take __attribute__((packed)) on non-POD and/or
254// templated types.
255#pragma pack(1)
256
257template <typename T, bool IsBigEndian>
258struct endian_specific_value {
259  operator T() const {
260    T rvalue = value;
261    if (IsBigEndian != isBigEndian())
262      bswap(&rvalue, sizeof(T));
263
264    return rvalue;
265  };
266
267  endian_specific_value &operator = (T nvalue) {
268    if (IsBigEndian != isBigEndian())
269      bswap(&nvalue, sizeof(T));
270
271    value = nvalue;
272    return *this;
273  }
274
275  endian_specific_value &operator += (T nvalue) {
276    *this = *this + nvalue;
277    return *this;
278  }
279
280  endian_specific_value &operator -= (T nvalue) {
281    *this = *this - nvalue;
282    return *this;
283  }
284
285private:
286  T value;
287};
288
289static const size_t CRCSize = 8;
290
291static const size_t MagicSize = 8;
292static const char *MagicBE = "HACC01B";
293static const char *MagicLE = "HACC01L";
294
295template <bool IsBigEndian>
296struct GlobalHeader {
297  char Magic[MagicSize];
298  endian_specific_value<uint64_t, IsBigEndian> HeaderSize;
299  endian_specific_value<uint64_t, IsBigEndian> NElems; // The global total
300  endian_specific_value<uint64_t, IsBigEndian> Dims[3];
301  endian_specific_value<uint64_t, IsBigEndian> NVars;
302  endian_specific_value<uint64_t, IsBigEndian> VarsSize;
303  endian_specific_value<uint64_t, IsBigEndian> VarsStart;
304  endian_specific_value<uint64_t, IsBigEndian> NRanks;
305  endian_specific_value<uint64_t, IsBigEndian> RanksSize;
306  endian_specific_value<uint64_t, IsBigEndian> RanksStart;
307  endian_specific_value<uint64_t, IsBigEndian> GlobalHeaderSize;
308  endian_specific_value<double,   IsBigEndian> PhysOrigin[3];
309  endian_specific_value<double,   IsBigEndian> PhysScale[3];
310  endian_specific_value<uint64_t, IsBigEndian> BlocksSize;
311  endian_specific_value<uint64_t, IsBigEndian> BlocksStart;
312};
313
314enum {
315  FloatValue          = (1 << 0),
316  SignedValue         = (1 << 1),
317  ValueIsPhysCoordX   = (1 << 2),
318  ValueIsPhysCoordY   = (1 << 3),
319  ValueIsPhysCoordZ   = (1 << 4),
320  ValueMaybePhysGhost = (1 << 5)
321};
322
323static const size_t NameSize = 256;
324template <bool IsBigEndian>
325struct VariableHeader {
326  char Name[NameSize];
327  endian_specific_value<uint64_t, IsBigEndian> Flags;
328  endian_specific_value<uint64_t, IsBigEndian> Size;
329  endian_specific_value<uint64_t, IsBigEndian> ElementSize;
330};
331
332template <bool IsBigEndian>
333struct RankHeader {
334  endian_specific_value<uint64_t, IsBigEndian> Coords[3];
335  endian_specific_value<uint64_t, IsBigEndian> NElems;
336  endian_specific_value<uint64_t, IsBigEndian> Start;
337  endian_specific_value<uint64_t, IsBigEndian> GlobalRank;
338};
339
340static const size_t FilterNameSize = 8;
341static const size_t MaxFilters = 4;
342template <bool IsBigEndian>
343struct BlockHeader {
344  char Filters[MaxFilters][FilterNameSize];
345  endian_specific_value<uint64_t, IsBigEndian> Start;
346  endian_specific_value<uint64_t, IsBigEndian> Size;
347};
348
349template <bool IsBigEndian>
350struct CompressHeader {
351  endian_specific_value<uint64_t, IsBigEndian> OrigCRC;
352};
353const char *CompressName = "BLOSC";
354
355const char *LossyCompressName = "SZ";
356
357#pragma pack()
358
359unsigned GenericIO::DefaultFileIOType = FileIOPOSIX;
360int GenericIO::DefaultPartition = 0;
361bool GenericIO::DefaultShouldCompress = false;
362
363#ifndef GENERICIO_NO_MPI
364std::size_t GenericIO::CollectiveMPIIOThreshold = 0;
365#endif
366
367static bool blosc_initialized = false;
368static bool sz_initialized = false;
369
370static int GetSZDT(GenericIO::Variable &Var) {
371  if (Var.hasElementType<float>())
372    return SZ_FLOAT;
373  else if (Var.hasElementType<double>())
374    return SZ_DOUBLE;
375  else if (Var.hasElementType<uint8_t>())
376    return SZ_UINT8;
377  else if (Var.hasElementType<int8_t>())
378    return SZ_INT8;
379  else if (Var.hasElementType<uint16_t>())
380    return SZ_UINT16;
381  else if (Var.hasElementType<int16_t>())
382    return SZ_INT16;
383  else if (Var.hasElementType<uint32_t>())
384    return SZ_UINT32;
385  else if (Var.hasElementType<int32_t>())
386    return SZ_INT32;
387  else if (Var.hasElementType<uint64_t>())
388    return SZ_UINT64;
389  else if (Var.hasElementType<int64_t>())
390    return SZ_INT64;
391  else
392    return -1;
393}
394
395#ifndef GENERICIO_NO_MPI
396void GenericIO::write() {
397  if (isBigEndian())
398    write<true>();
399  else
400    write<false>();
401}
402
403// Note: writing errors are not currently recoverable (one rank may fail
404// while the others don't).
405template <bool IsBigEndian>
406void GenericIO::write() {
407  const char *Magic = IsBigEndian ? MagicBE : MagicLE;
408
409  uint64_t FileSize = 0;
410
411  int NRanks, Rank;
412  MPI_Comm_rank(Comm, &Rank);
413  MPI_Comm_size(Comm, &NRanks);
414
415#ifdef __bgq__
416  MPI_Barrier(Comm);
417#endif
418  MPI_Comm_split(Comm, Partition, Rank, &SplitComm);
419
420  int SplitNRanks, SplitRank;
421  MPI_Comm_rank(SplitComm, &SplitRank);
422  MPI_Comm_size(SplitComm, &SplitNRanks);
423
424  string LocalFileName;
425  if (SplitNRanks != NRanks) {
426    if (Rank == 0) {
427      // In split mode, the specified file becomes the rank map, and the real
428      // data is partitioned.
429
430      vector<int> MapRank, MapPartition;
431      MapRank.resize(NRanks);
432      for (int i = 0; i < NRanks; ++i) MapRank[i] = i;
433
434      MapPartition.resize(NRanks);
435      MPI_Gather(&Partition, 1, MPI_INT, &MapPartition[0], 1, MPI_INT, 0, Comm);
436
437      GenericIO GIO(MPI_COMM_SELF, FileName, FileIOType);
438      GIO.setNumElems(NRanks);
439      GIO.addVariable("$rank", MapRank); /* this is for use by humans; the reading
440                                            code assumes that the partitions are in
441                                            rank order */
442      GIO.addVariable("$partition", MapPartition);
443
444      vector<int> CX, CY, CZ;
445      int TopoStatus;
446      MPI_Topo_test(Comm, &TopoStatus);
447      if (TopoStatus == MPI_CART) {
448        CX.resize(NRanks);
449        CY.resize(NRanks);
450        CZ.resize(NRanks);
451
452        for (int i = 0; i < NRanks; ++i) {
453          int C[3];
454          MPI_Cart_coords(Comm, i, 3, C);
455
456          CX[i] = C[0];
457          CY[i] = C[1];
458          CZ[i] = C[2];
459        }
460
461        GIO.addVariable("$x", CX);
462        GIO.addVariable("$y", CY);
463        GIO.addVariable("$z", CZ);
464      }
465
466      GIO.write();
467    } else {
468      MPI_Gather(&Partition, 1, MPI_INT, 0, 0, MPI_INT, 0, Comm);
469    }
470
471    stringstream ss;
472    ss << FileName << "#" << Partition;
473    LocalFileName = ss.str();
474  } else {
475    LocalFileName = FileName;
476  }
477
478  RankHeader<IsBigEndian> RHLocal;
479  int Dims[3], Periods[3], Coords[3];
480
481  int TopoStatus;
482  MPI_Topo_test(Comm, &TopoStatus);
483  if (TopoStatus == MPI_CART) {
484    MPI_Cart_get(Comm, 3, Dims, Periods, Coords);
485  } else {
486    Dims[0] = NRanks;
487    std::fill(Dims + 1, Dims + 3, 1);
488    std::fill(Periods, Periods + 3, 0);
489    Coords[0] = Rank;
490    std::fill(Coords + 1, Coords + 3, 0);
491  }
492
493  std::copy(Coords, Coords + 3, RHLocal.Coords);
494  RHLocal.NElems = NElems;
495  RHLocal.Start = 0;
496  RHLocal.GlobalRank = Rank;
497
498  bool ShouldCompress = DefaultShouldCompress;
499  const char *EnvStr = getenv("GENERICIO_COMPRESS");
500  if (EnvStr) {
501    int Mod = atoi(EnvStr);
502    ShouldCompress = (Mod > 0);
503  }
504
505  bool NeedsBlockHeaders = ShouldCompress;
506  EnvStr = getenv("GENERICIO_FORCE_BLOCKS");
507  if (!NeedsBlockHeaders && EnvStr) {
508    int Mod = atoi(EnvStr);
509    NeedsBlockHeaders = (Mod > 0);
510  }
511
512  vector<BlockHeader<IsBigEndian> > LocalBlockHeaders;
513  vector<void *> LocalData;
514  vector<bool> LocalHasExtraSpace;
515  vector<vector<unsigned char> > LocalCData;
516  if (NeedsBlockHeaders) {
517    LocalBlockHeaders.resize(Vars.size());
518    LocalData.resize(Vars.size());
519    LocalHasExtraSpace.resize(Vars.size());
520    if (ShouldCompress)
521      LocalCData.resize(Vars.size());
522
523    for (size_t i = 0; i < Vars.size(); ++i) {
524      // Filters null by default, leave null starting address (needs to be
525      // calculated by the header-writing rank).
526      memset(&LocalBlockHeaders[i], 0, sizeof(BlockHeader<IsBigEndian>));
527      if (ShouldCompress) {
528        void *OrigData = Vars[i].Data;
529        bool FreeOrigData = false;
530        size_t OrigUnitSize = Vars[i].Size;
531        size_t OrigDataSize = NElems*Vars[i].Size;
532
533        int FilterIdx = 0;
534        if (Vars[i].LCI.Mode != LossyCompressionInfo::LCModeNone) {
535#ifdef _OPENMP
536#pragma omp master
537  {
538#endif
539         if (!sz_initialized) {
540           SZ_Init(NULL);
541           sz_initialized = true;
542         }
543
544#ifdef _OPENMP
545  }
546#endif
547          int SZDT = GetSZDT(Vars[i]);
548          if (SZDT == -1)
549            goto nosz;
550
551          int EBM;
552          switch (Vars[i].LCI.Mode) {
553          case LossyCompressionInfo::LCModeAbs:
554            EBM = ABS;
555            break;
556          case LossyCompressionInfo::LCModeRel:
557            EBM = REL;
558            break;
559          case LossyCompressionInfo::LCModeAbsAndRel:
560            EBM = ABS_AND_REL;
561            break;
562          case LossyCompressionInfo::LCModeAbsOrRel:
563            EBM = ABS_OR_REL;
564            break;
565          case LossyCompressionInfo::LCModePSNR:
566            EBM = PSNR;
567            break;
568          }
569
570          size_t LOutSize;
571          unsigned char *LCompressedData = SZ_compress_args(SZDT, Vars[i].Data, &LOutSize, EBM,
572                                                            Vars[i].LCI.AbsErrThreshold, Vars[i].LCI.RelErrThreshold,
573                                                            Vars[i].LCI.PSNRThreshold, 0, 0, 0, 0, NElems);
574          if (!LCompressedData)
575            goto nosz;
576          if (LOutSize >= NElems*Vars[i].Size) {
577            free(LCompressedData);
578            goto nosz;
579          }
580
581          OrigData = LCompressedData;
582          FreeOrigData = true;
583          OrigUnitSize = 1;
584          OrigDataSize = LOutSize;
585
586          strncpy(LocalBlockHeaders[i].Filters[FilterIdx++], LossyCompressName, FilterNameSize);
587        }
588nosz:
589
590        LocalCData[i].resize(sizeof(CompressHeader<IsBigEndian>));
591
592        CompressHeader<IsBigEndian> *CH = (CompressHeader<IsBigEndian>*) &LocalCData[i][0];
593        CH->OrigCRC = crc64_omp(OrigData, OrigDataSize);
594
595#ifdef _OPENMP
596#pragma omp master
597  {
598#endif
599
600       if (!blosc_initialized) {
601         blosc_init();
602         blosc_initialized = true;
603       }
604
605#ifdef _OPENMP
606       blosc_set_nthreads(omp_get_max_threads());
607  }
608#endif
609
610        LocalCData[i].resize(LocalCData[i].size() + OrigDataSize);
611        if (blosc_compress(9, 1, OrigUnitSize, OrigDataSize, OrigData,
612                           &LocalCData[i][0] + sizeof(CompressHeader<IsBigEndian>),
613                           OrigDataSize) <= 0) {
614          if (FreeOrigData)
615            free(OrigData);
616
617          goto nocomp;
618        }
619
620        if (FreeOrigData)
621          free(OrigData);
622
623        strncpy(LocalBlockHeaders[i].Filters[FilterIdx++], CompressName, FilterNameSize);
624        size_t CNBytes, CCBytes, CBlockSize;
625        blosc_cbuffer_sizes(&LocalCData[i][0] + sizeof(CompressHeader<IsBigEndian>),
626                            &CNBytes, &CCBytes, &CBlockSize);
627        LocalCData[i].resize(CCBytes + sizeof(CompressHeader<IsBigEndian>));
628
629        LocalBlockHeaders[i].Size = LocalCData[i].size();
630        LocalCData[i].resize(LocalCData[i].size() + CRCSize);
631        LocalData[i] = &LocalCData[i][0];
632        LocalHasExtraSpace[i] = true;
633      } else {
634nocomp:
635        LocalBlockHeaders[i].Size = NElems*Vars[i].Size;
636        LocalData[i] = Vars[i].Data;
637        LocalHasExtraSpace[i] = Vars[i].HasExtraSpace;
638      }
639    }
640  }
641
642  double StartTime = MPI_Wtime();
643
644  if (SplitRank == 0) {
645    uint64_t HeaderSize = sizeof(GlobalHeader<IsBigEndian>) + Vars.size()*sizeof(VariableHeader<IsBigEndian>) +
646                          SplitNRanks*sizeof(RankHeader<IsBigEndian>) + CRCSize;
647    if (NeedsBlockHeaders)
648      HeaderSize += SplitNRanks*Vars.size()*sizeof(BlockHeader<IsBigEndian>);
649
650    vector<char> Header(HeaderSize, 0);
651    GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &Header[0];
652    std::copy(Magic, Magic + MagicSize, GH->Magic);
653    GH->HeaderSize = HeaderSize - CRCSize;
654    GH->NElems = NElems; // This will be updated later
655    std::copy(Dims, Dims + 3, GH->Dims);
656    GH->NVars = Vars.size();
657    GH->VarsSize = sizeof(VariableHeader<IsBigEndian>);
658    GH->VarsStart = sizeof(GlobalHeader<IsBigEndian>);
659    GH->NRanks = SplitNRanks;
660    GH->RanksSize = sizeof(RankHeader<IsBigEndian>);
661    GH->RanksStart = GH->VarsStart + Vars.size()*sizeof(VariableHeader<IsBigEndian>);
662    GH->GlobalHeaderSize = sizeof(GlobalHeader<IsBigEndian>);
663    std::copy(PhysOrigin, PhysOrigin + 3, GH->PhysOrigin);
664    std::copy(PhysScale,  PhysScale  + 3, GH->PhysScale);
665    if (!NeedsBlockHeaders) {
666      GH->BlocksSize = GH->BlocksStart = 0;
667    } else {
668      GH->BlocksSize = sizeof(BlockHeader<IsBigEndian>);
669      GH->BlocksStart = GH->RanksStart + SplitNRanks*sizeof(RankHeader<IsBigEndian>);
670    }
671
672    uint64_t RecordSize = 0;
673    VariableHeader<IsBigEndian> *VH = (VariableHeader<IsBigEndian> *) &Header[GH->VarsStart];
674    for (size_t i = 0; i < Vars.size(); ++i, ++VH) {
675      string VName(Vars[i].Name);
676      VName.resize(NameSize);
677
678      std::copy(VName.begin(), VName.end(), VH->Name);
679      uint64_t VFlags = 0;
680      if (Vars[i].IsFloat)  VFlags |= FloatValue;
681      if (Vars[i].IsSigned) VFlags |= SignedValue;
682      if (Vars[i].IsPhysCoordX) VFlags |= ValueIsPhysCoordX;
683      if (Vars[i].IsPhysCoordY) VFlags |= ValueIsPhysCoordY;
684      if (Vars[i].IsPhysCoordZ) VFlags |= ValueIsPhysCoordZ;
685      if (Vars[i].MaybePhysGhost) VFlags |= ValueMaybePhysGhost;
686      VH->Flags = VFlags;
687      RecordSize += VH->Size = Vars[i].Size;
688      VH->ElementSize = Vars[i].ElementSize;
689    }
690
691    MPI_Gather(&RHLocal, sizeof(RHLocal), MPI_BYTE,
692               &Header[GH->RanksStart], sizeof(RHLocal),
693               MPI_BYTE, 0, SplitComm);
694
695    if (NeedsBlockHeaders) {
696      MPI_Gather(&LocalBlockHeaders[0],
697                 Vars.size()*sizeof(BlockHeader<IsBigEndian>), MPI_BYTE,
698                 &Header[GH->BlocksStart],
699                 Vars.size()*sizeof(BlockHeader<IsBigEndian>), MPI_BYTE,
700                 0, SplitComm);
701
702      BlockHeader<IsBigEndian> *BH = (BlockHeader<IsBigEndian> *) &Header[GH->BlocksStart];
703      for (int i = 0; i < SplitNRanks; ++i)
704      for (size_t j = 0; j < Vars.size(); ++j, ++BH) {
705        if (i == 0 && j == 0)
706          BH->Start = HeaderSize;
707        else
708          BH->Start = BH[-1].Start + BH[-1].Size + CRCSize;
709      }
710
711      RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &Header[GH->RanksStart];
712      RH->Start = HeaderSize; ++RH;
713      for (int i = 1; i < SplitNRanks; ++i, ++RH) {
714        RH->Start =
715          ((BlockHeader<IsBigEndian> *) &Header[GH->BlocksStart])[i*Vars.size()].Start;
716        GH->NElems += RH->NElems;
717      }
718
719      // Compute the total file size.
720      uint64_t LastData = BH[-1].Size + CRCSize;
721      FileSize = BH[-1].Start + LastData;
722    } else {
723      RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &Header[GH->RanksStart];
724      RH->Start = HeaderSize; ++RH;
725      for (int i = 1; i < SplitNRanks; ++i, ++RH) {
726        uint64_t PrevNElems = RH[-1].NElems;
727        uint64_t PrevData = PrevNElems*RecordSize + CRCSize*Vars.size();
728        RH->Start = RH[-1].Start + PrevData;
729        GH->NElems += RH->NElems;
730      }
731
732      // Compute the total file size.
733      uint64_t LastNElems = RH[-1].NElems;
734      uint64_t LastData = LastNElems*RecordSize + CRCSize*Vars.size();
735      FileSize = RH[-1].Start + LastData;
736    }
737
738    // Now that the starting offset has been computed, send it back to each rank.
739    MPI_Scatter(&Header[GH->RanksStart], sizeof(RHLocal),
740                MPI_BYTE, &RHLocal, sizeof(RHLocal),
741                MPI_BYTE, 0, SplitComm);
742
743    if (NeedsBlockHeaders)
744      MPI_Scatter(&Header[GH->BlocksStart],
745                  sizeof(BlockHeader<IsBigEndian>)*Vars.size(), MPI_BYTE,
746                  &LocalBlockHeaders[0],
747                  sizeof(BlockHeader<IsBigEndian>)*Vars.size(), MPI_BYTE,
748                  0, SplitComm);
749
750    uint64_t HeaderCRC = crc64_omp(&Header[0], HeaderSize - CRCSize);
751    crc64_invert(HeaderCRC, &Header[HeaderSize - CRCSize]);
752
753    if (FileIOType == FileIOMPI)
754      FH.get() = new GenericFileIO_MPI(MPI_COMM_SELF);
755    else if (FileIOType == FileIOMPICollective)
756      FH.get() = new GenericFileIO_MPICollective(MPI_COMM_SELF);
757    else
758      FH.get() = new GenericFileIO_POSIX();
759
760    FH.get()->open(LocalFileName);
761    FH.get()->setSize(FileSize);
762    FH.get()->write(&Header[0], HeaderSize, 0, "header");
763
764    close();
765  } else {
766    MPI_Gather(&RHLocal, sizeof(RHLocal), MPI_BYTE, 0, 0, MPI_BYTE, 0, SplitComm);
767    if (NeedsBlockHeaders)
768      MPI_Gather(&LocalBlockHeaders[0], Vars.size()*sizeof(BlockHeader<IsBigEndian>),
769                 MPI_BYTE, 0, 0, MPI_BYTE, 0, SplitComm);
770    MPI_Scatter(0, 0, MPI_BYTE, &RHLocal, sizeof(RHLocal), MPI_BYTE, 0, SplitComm);
771    if (NeedsBlockHeaders)
772      MPI_Scatter(0, 0, MPI_BYTE, &LocalBlockHeaders[0], sizeof(BlockHeader<IsBigEndian>)*Vars.size(),
773                  MPI_BYTE, 0, SplitComm);
774  }
775
776  MPI_Barrier(SplitComm);
777
778  if (FileIOType == FileIOMPI)
779    FH.get() = new GenericFileIO_MPI(SplitComm);
780  else if (FileIOType == FileIOMPICollective)
781    FH.get() = new GenericFileIO_MPICollective(SplitComm);
782  else
783    FH.get() = new GenericFileIO_POSIX();
784
785  FH.get()->open(LocalFileName);
786
787  uint64_t Offset = RHLocal.Start;
788  for (size_t i = 0; i < Vars.size(); ++i) {
789    uint64_t WriteSize = NeedsBlockHeaders ?
790                         LocalBlockHeaders[i].Size : NElems*Vars[i].Size;
791    void *Data = NeedsBlockHeaders ? LocalData[i] : Vars[i].Data;
792    uint64_t CRC = crc64_omp(Data, WriteSize);
793    bool HasExtraSpace = NeedsBlockHeaders ?
794                         LocalHasExtraSpace[i] : Vars[i].HasExtraSpace;
795    char *CRCLoc = HasExtraSpace ?  ((char *) Data) + WriteSize : (char *) &CRC;
796
797    if (NeedsBlockHeaders)
798      Offset = LocalBlockHeaders[i].Start;
799
800    // When using extra space for the CRC write, preserve the original contents.
801    char CRCSave[CRCSize];
802    if (HasExtraSpace)
803      std::copy(CRCLoc, CRCLoc + CRCSize, CRCSave);
804
805    crc64_invert(CRC, CRCLoc);
806
807    if (HasExtraSpace) {
808      FH.get()->write(Data, WriteSize + CRCSize, Offset, Vars[i].Name + " with CRC");
809    } else {
810      FH.get()->write(Data, WriteSize, Offset, Vars[i].Name);
811      FH.get()->write(CRCLoc, CRCSize, Offset + WriteSize, Vars[i].Name + " CRC");
812    }
813
814    if (HasExtraSpace)
815       std::copy(CRCSave, CRCSave + CRCSize, CRCLoc);
816
817    Offset += WriteSize + CRCSize;
818  }
819
820  close();
821  MPI_Barrier(Comm);
822
823  double EndTime = MPI_Wtime();
824  double TotalTime = EndTime - StartTime;
825  double MaxTotalTime;
826  MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
827
828  if (SplitNRanks != NRanks) {
829    uint64_t ContribFileSize = (SplitRank == 0) ? FileSize : 0;
830    MPI_Reduce(&ContribFileSize, &FileSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
831  }
832
833  if (Rank == 0) {
834    double Rate = ((double) FileSize) / MaxTotalTime / (1024.*1024.);
835    std::cout << "Wrote " << Vars.size() << " variables to " << FileName <<
836                  " (" << FileSize << " bytes) in " << MaxTotalTime << "s: " <<
837                  Rate << " MB/s" << std::endl;
838  }
839
840  MPI_Comm_free(&SplitComm);
841  SplitComm = MPI_COMM_NULL;
842}
843#endif // GENERICIO_NO_MPI
844
845template <bool IsBigEndian>
846void GenericIO::readHeaderLeader(void *GHPtr, MismatchBehavior MB, int NRanks,
847                                 int Rank, int SplitNRanks,
848                                 string &LocalFileName, uint64_t &HeaderSize,
849                                 vector<char> &Header) {
850  GlobalHeader<IsBigEndian> &GH = *(GlobalHeader<IsBigEndian> *) GHPtr;
851
852  if (MB == MismatchDisallowed) {
853    if (SplitNRanks != (int) GH.NRanks) {
854      stringstream ss;
855      ss << "Won't read " << LocalFileName << ": communicator-size mismatch: " <<
856            "current: " << SplitNRanks << ", file: " << GH.NRanks;
857      throw runtime_error(ss.str());
858    }
859
860#ifndef GENERICIO_NO_MPI
861    int TopoStatus;
862    MPI_Topo_test(Comm, &TopoStatus);
863    if (TopoStatus == MPI_CART) {
864      int Dims[3], Periods[3], Coords[3];
865      MPI_Cart_get(Comm, 3, Dims, Periods, Coords);
866
867      bool DimsMatch = true;
868      for (int i = 0; i < 3; ++i) {
869        if ((uint64_t) Dims[i] != GH.Dims[i]) {
870          DimsMatch = false;
871          break;
872        }
873      }
874
875      if (!DimsMatch) {
876        stringstream ss;
877        ss << "Won't read " << LocalFileName <<
878              ": communicator-decomposition mismatch: " <<
879              "current: " << Dims[0] << "x" << Dims[1] << "x" << Dims[2] <<
880              ", file: " << GH.Dims[0] << "x" << GH.Dims[1] << "x" <<
881              GH.Dims[2];
882        throw runtime_error(ss.str());
883      }
884    }
885#endif
886  } else if (MB == MismatchRedistribute && !Redistributing) {
887    Redistributing = true;
888
889    int NFileRanks = RankMap.empty() ? (int) GH.NRanks : (int) RankMap.size();
890    int NFileRanksPerRank = NFileRanks/NRanks;
891    int NRemFileRank = NFileRanks % NRanks;
892
893    if (!NFileRanksPerRank) {
894      // We have only the remainder, so the last NRemFileRank ranks get one
895      // file rank, and the others don't.
896      if (NRemFileRank && NRanks - Rank <= NRemFileRank)
897        SourceRanks.push_back(NRanks - (Rank + 1));
898    } else {
899      // Since NRemFileRank < NRanks, and we don't want to put any extra memory
900      // load on rank 0 (because rank 0's memory load is normally higher than
901      // the other ranks anyway), the last NRemFileRank will each take
902      // (NFileRanksPerRank+1) file ranks.
903
904      int FirstFileRank = 0, LastFileRank = NFileRanksPerRank - 1;
905      for (int i = 1; i <= Rank; ++i) {
906        FirstFileRank = LastFileRank + 1;
907        LastFileRank  = FirstFileRank + NFileRanksPerRank - 1;
908
909        if (NRemFileRank && NRanks - i <= NRemFileRank)
910          ++LastFileRank;
911      }
912
913      for (int i = FirstFileRank; i <= LastFileRank; ++i)
914        SourceRanks.push_back(i);
915    }
916  }
917
918  HeaderSize = GH.HeaderSize;
919  Header.resize(HeaderSize + CRCSize, 0xFE /* poison */);
920  FH.get()->read(&Header[0], HeaderSize + CRCSize, 0, "header");
921
922  uint64_t CRC = crc64_omp(&Header[0], HeaderSize + CRCSize);
923  if (CRC != (uint64_t) -1) {
924    throw runtime_error("Header CRC check failed: " + LocalFileName);
925  }
926}
927
928// Note: Errors from this function should be recoverable. This means that if
929// one rank throws an exception, then all ranks should.
930void GenericIO::openAndReadHeader(MismatchBehavior MB, int EffRank, bool CheckPartMap) {
931  int NRanks, Rank;
932#ifndef GENERICIO_NO_MPI
933  MPI_Comm_rank(Comm, &Rank);
934  MPI_Comm_size(Comm, &NRanks);
935#else
936  Rank = 0;
937  NRanks = 1;
938#endif
939
940  if (EffRank == -1)
941    EffRank = MB == MismatchRedistribute ? 0 : Rank;
942
943  if (RankMap.empty() && CheckPartMap) {
944    // First, check to see if the file is a rank map.
945    unsigned long RanksInMap = 0;
946    if (Rank == 0) {
947      try {
948#ifndef GENERICIO_NO_MPI
949        GenericIO GIO(MPI_COMM_SELF, FileName, FileIOType);
950#else
951        GenericIO GIO(FileName, FileIOType);
952#endif
953        GIO.openAndReadHeader(MismatchDisallowed, 0, false);
954        RanksInMap = GIO.readNumElems();
955
956        RankMap.resize(RanksInMap + GIO.requestedExtraSpace()/sizeof(int));
957        GIO.addVariable("$partition", RankMap, true);
958
959        GIO.readData(0, false);
960        RankMap.resize(RanksInMap);
961      } catch (...) {
962        RankMap.clear();
963        RanksInMap = 0;
964      }
965    }
966
967#ifndef GENERICIO_NO_MPI
968    MPI_Bcast(&RanksInMap, 1, MPI_UNSIGNED_LONG, 0, Comm);
969    if (RanksInMap > 0) {
970      RankMap.resize(RanksInMap);
971      MPI_Bcast(&RankMap[0], RanksInMap, MPI_INT, 0, Comm);
972    }
973#endif
974  }
975
976#ifndef GENERICIO_NO_MPI
977  if (SplitComm != MPI_COMM_NULL)
978    MPI_Comm_free(&SplitComm);
979#endif
980
981  string LocalFileName;
982  if (RankMap.empty()) {
983    LocalFileName = FileName;
984#ifndef GENERICIO_NO_MPI
985    MPI_Comm_dup(MB == MismatchRedistribute ? MPI_COMM_SELF : Comm, &SplitComm);
986#endif
987  } else {
988    stringstream ss;
989    ss << FileName << "#" << RankMap[EffRank];
990    LocalFileName = ss.str();
991#ifndef GENERICIO_NO_MPI
992    if (MB == MismatchRedistribute) {
993      MPI_Comm_dup(MPI_COMM_SELF, &SplitComm);
994    } else {
995#ifdef __bgq__
996      MPI_Barrier(Comm);
997#endif
998      MPI_Comm_split(Comm, RankMap[EffRank], Rank, &SplitComm);
999    }
1000#endif
1001  }
1002
1003  if (LocalFileName == OpenFileName)
1004    return;
1005  FH.close();
1006
1007  int SplitNRanks, SplitRank;
1008#ifndef GENERICIO_NO_MPI
1009  MPI_Comm_rank(SplitComm, &SplitRank);
1010  MPI_Comm_size(SplitComm, &SplitNRanks);
1011#else
1012  SplitRank = 0;
1013  SplitNRanks = 1;
1014#endif
1015
1016  uint64_t HeaderSize;
1017  vector<char> Header;
1018
1019  if (SplitRank == 0) {
1020#ifndef GENERICIO_NO_MPI
1021    if (FileIOType == FileIOMPI)
1022      FH.get() = new GenericFileIO_MPI(MPI_COMM_SELF);
1023    else if (FileIOType == FileIOMPICollective)
1024      FH.get() = new GenericFileIO_MPICollective(MPI_COMM_SELF);
1025    else
1026#endif
1027      FH.get() = new GenericFileIO_POSIX();
1028
1029#ifndef GENERICIO_NO_MPI
1030    char True = 1, False = 0;
1031#endif
1032
1033    try {
1034      FH.get()->open(LocalFileName, true);
1035
1036      GlobalHeader<false> GH; // endianness does not matter yet...
1037      FH.get()->read(&GH, sizeof(GlobalHeader<false>), 0, "global header");
1038
1039      if (string(GH.Magic, GH.Magic + MagicSize - 1) == MagicLE) {
1040        readHeaderLeader<false>(&GH, MB, NRanks, Rank, SplitNRanks, LocalFileName,
1041                                HeaderSize, Header);
1042      } else if (string(GH.Magic, GH.Magic + MagicSize - 1) == MagicBE) {
1043        readHeaderLeader<true>(&GH, MB, NRanks, Rank, SplitNRanks, LocalFileName,
1044                               HeaderSize, Header);
1045      } else {
1046        string Error = "invalid file-type identifier";
1047        throw runtime_error("Won't read " + LocalFileName + ": " + Error);
1048      }
1049
1050#ifndef GENERICIO_NO_MPI
1051      close();
1052      MPI_Bcast(&True, 1, MPI_BYTE, 0, SplitComm);
1053#endif
1054    } catch (...) {
1055#ifndef GENERICIO_NO_MPI
1056      MPI_Bcast(&False, 1, MPI_BYTE, 0, SplitComm);
1057#endif
1058      close();
1059      throw;
1060    }
1061  } else {
1062#ifndef GENERICIO_NO_MPI
1063    char Okay;
1064    MPI_Bcast(&Okay, 1, MPI_BYTE, 0, SplitComm);
1065    if (!Okay)
1066      throw runtime_error("Failure broadcast from rank 0");
1067#endif
1068  }
1069
1070#ifndef GENERICIO_NO_MPI
1071  MPI_Bcast(&HeaderSize, 1, MPI_UINT64_T, 0, SplitComm);
1072#endif
1073
1074  Header.resize(HeaderSize, 0xFD /* poison */);
1075#ifndef GENERICIO_NO_MPI
1076  MPI_Bcast(&Header[0], HeaderSize, MPI_BYTE, 0, SplitComm);
1077#endif
1078
1079  FH.getHeaderCache().clear();
1080
1081  GlobalHeader<false> *GH = (GlobalHeader<false> *) &Header[0];
1082  FH.setIsBigEndian(string(GH->Magic, GH->Magic + MagicSize - 1) == MagicBE);
1083
1084  FH.getHeaderCache().swap(Header);
1085  OpenFileName = LocalFileName;
1086
1087#ifndef GENERICIO_NO_MPI
1088  if (!DisableCollErrChecking)
1089    MPI_Barrier(Comm);
1090
1091  if (FileIOType == FileIOMPI)
1092    FH.get() = new GenericFileIO_MPI(SplitComm);
1093  else if (FileIOType == FileIOMPICollective)
1094    FH.get() = new GenericFileIO_MPICollective(SplitComm);
1095  else
1096    FH.get() = new GenericFileIO_POSIX();
1097
1098  int OpenErr = 0, TotOpenErr;
1099  try {
1100    FH.get()->open(LocalFileName, true);
1101    MPI_Allreduce(&OpenErr, &TotOpenErr, 1, MPI_INT, MPI_SUM,
1102                  DisableCollErrChecking ? MPI_COMM_SELF : Comm);
1103  } catch (...) {
1104    OpenErr = 1;
1105    MPI_Allreduce(&OpenErr, &TotOpenErr, 1, MPI_INT, MPI_SUM,
1106                  DisableCollErrChecking ? MPI_COMM_SELF : Comm);
1107    throw;
1108  }
1109
1110  if (TotOpenErr > 0) {
1111    stringstream ss;
1112    ss << TotOpenErr << " ranks failed to open file: " << LocalFileName;
1113    throw runtime_error(ss.str());
1114  }
1115#endif
1116}
1117
1118int GenericIO::readNRanks() {
1119  if (FH.isBigEndian())
1120    return readNRanks<true>();
1121  return readNRanks<false>();
1122}
1123
1124template <bool IsBigEndian>
1125int GenericIO::readNRanks() {
1126  if (RankMap.size())
1127    return RankMap.size();
1128
1129  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1130  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1131  return (int) GH->NRanks;
1132}
1133
1134void GenericIO::readDims(int Dims[3]) {
1135  if (FH.isBigEndian())
1136    readDims<true>(Dims);
1137  else
1138    readDims<false>(Dims);
1139}
1140
1141template <bool IsBigEndian>
1142void GenericIO::readDims(int Dims[3]) {
1143  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1144  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1145  std::copy(GH->Dims, GH->Dims + 3, Dims);
1146}
1147
1148uint64_t GenericIO::readTotalNumElems() {
1149  if (FH.isBigEndian())
1150    return readTotalNumElems<true>();
1151  return readTotalNumElems<false>();
1152}
1153
1154template <bool IsBigEndian>
1155uint64_t GenericIO::readTotalNumElems() {
1156  if (RankMap.size())
1157    return (uint64_t) -1;
1158
1159  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1160  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1161  return GH->NElems;
1162}
1163
1164void GenericIO::readPhysOrigin(double Origin[3]) {
1165  if (FH.isBigEndian())
1166    readPhysOrigin<true>(Origin);
1167  else
1168    readPhysOrigin<false>(Origin);
1169}
1170
1171// Define a "safe" version of offsetof (offsetof itself might not work for
1172// non-POD types, and at least xlC v12.1 will complain about this if you try).
1173#define offsetof_safe(S, F) (size_t(&(S)->F) - size_t(S))
1174
1175template <bool IsBigEndian>
1176void GenericIO::readPhysOrigin(double Origin[3]) {
1177  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1178  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1179  if (offsetof_safe(GH, PhysOrigin) >= GH->GlobalHeaderSize) {
1180    std::fill(Origin, Origin + 3, 0.0);
1181    return;
1182  }
1183
1184  std::copy(GH->PhysOrigin, GH->PhysOrigin + 3, Origin);
1185}
1186
1187void GenericIO::readPhysScale(double Scale[3]) {
1188  if (FH.isBigEndian())
1189    readPhysScale<true>(Scale);
1190  else
1191    readPhysScale<false>(Scale);
1192}
1193
1194template <bool IsBigEndian>
1195void GenericIO::readPhysScale(double Scale[3]) {
1196  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1197  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1198  if (offsetof_safe(GH, PhysScale) >= GH->GlobalHeaderSize) {
1199    std::fill(Scale, Scale + 3, 0.0);
1200    return;
1201  }
1202
1203  std::copy(GH->PhysScale, GH->PhysScale + 3, Scale);
1204}
1205
1206template <bool IsBigEndian>
1207static size_t getRankIndex(int EffRank, GlobalHeader<IsBigEndian> *GH,
1208                           vector<int> &RankMap, vector<char> &HeaderCache) {
1209  if (RankMap.empty())
1210    return EffRank;
1211
1212  for (size_t i = 0; i < GH->NRanks; ++i) {
1213    RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &HeaderCache[GH->RanksStart +
1214                                                 i*GH->RanksSize];
1215    if (offsetof_safe(RH, GlobalRank) >= GH->RanksSize)
1216      return EffRank;
1217
1218    if ((int) RH->GlobalRank == EffRank)
1219      return i;
1220  }
1221
1222  assert(false && "Index requested of an invalid rank");
1223  return (size_t) -1;
1224}
1225
1226int GenericIO::readGlobalRankNumber(int EffRank) {
1227  if (FH.isBigEndian())
1228    return readGlobalRankNumber<true>(EffRank);
1229  return readGlobalRankNumber<false>(EffRank);
1230}
1231
1232template <bool IsBigEndian>
1233int GenericIO::readGlobalRankNumber(int EffRank) {
1234  if (EffRank == -1) {
1235#ifndef GENERICIO_NO_MPI
1236    MPI_Comm_rank(Comm, &EffRank);
1237#else
1238    EffRank = 0;
1239#endif
1240  }
1241
1242  openAndReadHeader(MismatchAllowed, EffRank, false);
1243
1244  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1245
1246  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1247  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
1248
1249  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1250
1251  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
1252                                               RankIndex*GH->RanksSize];
1253
1254  if (offsetof_safe(RH, GlobalRank) >= GH->RanksSize)
1255    return EffRank;
1256
1257  return (int) RH->GlobalRank;
1258}
1259
1260void GenericIO::getSourceRanks(vector<int> &SR) {
1261  SR.clear();
1262
1263  if (Redistributing) {
1264    std::copy(SourceRanks.begin(), SourceRanks.end(), std::back_inserter(SR));
1265    return;
1266  }
1267
1268  int Rank;
1269#ifndef GENERICIO_NO_MPI
1270  MPI_Comm_rank(Comm, &Rank);
1271#else
1272  Rank = 0;
1273#endif
1274
1275  SR.push_back(Rank);
1276}
1277
1278size_t GenericIO::readNumElems(int EffRank) {
1279  if (EffRank == -1 && Redistributing) {
1280    DisableCollErrChecking = true;
1281
1282    size_t TotalSize = 0;
1283    for (int i = 0, ie = SourceRanks.size(); i != ie; ++i)
1284      TotalSize += readNumElems(SourceRanks[i]);
1285
1286    DisableCollErrChecking = false;
1287    return TotalSize;
1288  }
1289
1290  if (FH.isBigEndian())
1291    return readNumElems<true>(EffRank);
1292  return readNumElems<false>(EffRank);
1293}
1294
1295template <bool IsBigEndian>
1296size_t GenericIO::readNumElems(int EffRank) {
1297  if (EffRank == -1) {
1298#ifndef GENERICIO_NO_MPI
1299    MPI_Comm_rank(Comm, &EffRank);
1300#else
1301    EffRank = 0;
1302#endif
1303  }
1304
1305  openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed,
1306                    EffRank, false);
1307
1308  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1309
1310  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1311  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
1312
1313  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1314
1315  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
1316                                               RankIndex*GH->RanksSize];
1317  return (size_t) RH->NElems;
1318}
1319
1320void GenericIO::readCoords(int Coords[3], int EffRank) {
1321  if (EffRank == -1 && Redistributing) {
1322    std::fill(Coords, Coords + 3, 0);
1323    return;
1324  }
1325
1326  if (FH.isBigEndian())
1327    readCoords<true>(Coords, EffRank);
1328  else
1329    readCoords<false>(Coords, EffRank);
1330}
1331
1332template <bool IsBigEndian>
1333void GenericIO::readCoords(int Coords[3], int EffRank) {
1334  if (EffRank == -1) {
1335#ifndef GENERICIO_NO_MPI
1336    MPI_Comm_rank(Comm, &EffRank);
1337#else
1338    EffRank = 0;
1339#endif
1340  }
1341
1342  openAndReadHeader(MismatchAllowed, EffRank, false);
1343
1344  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1345
1346  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1347  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
1348
1349  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1350
1351  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
1352                                               RankIndex*GH->RanksSize];
1353
1354  std::copy(RH->Coords, RH->Coords + 3, Coords);
1355}
1356
1357void GenericIO::readData(int EffRank, bool PrintStats, bool CollStats) {
1358  int Rank;
1359#ifndef GENERICIO_NO_MPI
1360  MPI_Comm_rank(Comm, &Rank);
1361#else
1362  Rank = 0;
1363#endif
1364
1365  uint64_t TotalReadSize = 0;
1366#ifndef GENERICIO_NO_MPI
1367  double StartTime = MPI_Wtime();
1368#else
1369  double StartTime = double(clock())/CLOCKS_PER_SEC;
1370#endif
1371
1372  int NErrs[3] = { 0, 0, 0 };
1373
1374  if (EffRank == -1 && Redistributing) {
1375    DisableCollErrChecking = true;
1376
1377    size_t RowOffset = 0;
1378    for (int i = 0, ie = SourceRanks.size(); i != ie; ++i) {
1379      readData(SourceRanks[i], RowOffset, Rank, TotalReadSize, NErrs);
1380      RowOffset += readNumElems(SourceRanks[i]);
1381    }
1382
1383    DisableCollErrChecking = false;
1384  } else {
1385    readData(EffRank, 0, Rank, TotalReadSize, NErrs);
1386  }
1387
1388  int AllNErrs[3];
1389#ifndef GENERICIO_NO_MPI
1390  MPI_Allreduce(NErrs, AllNErrs, 3, MPI_INT, MPI_SUM, Comm);
1391#else
1392  AllNErrs[0] = NErrs[0]; AllNErrs[1] = NErrs[1]; AllNErrs[2] = NErrs[2];
1393#endif
1394
1395  if (AllNErrs[0] > 0 || AllNErrs[1] > 0 || AllNErrs[2] > 0) {
1396    stringstream ss;
1397    ss << "Experienced " << AllNErrs[0] << " I/O error(s), " <<
1398          AllNErrs[1] << " CRC error(s) and " << AllNErrs[2] <<
1399          " decompression CRC error(s) reading: " << OpenFileName;
1400    throw runtime_error(ss.str());
1401  }
1402
1403#ifndef GENERICIO_NO_MPI
1404  MPI_Barrier(Comm);
1405#endif
1406
1407#ifndef GENERICIO_NO_MPI
1408  double EndTime = MPI_Wtime();
1409#else
1410  double EndTime = double(clock())/CLOCKS_PER_SEC;
1411#endif
1412
1413  double TotalTime = EndTime - StartTime;
1414  double MaxTotalTime;
1415#ifndef GENERICIO_NO_MPI
1416  if (CollStats)
1417    MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
1418  else
1419#endif
1420  MaxTotalTime = TotalTime;
1421
1422  uint64_t AllTotalReadSize;
1423#ifndef GENERICIO_NO_MPI
1424  if (CollStats)
1425    MPI_Reduce(&TotalReadSize, &AllTotalReadSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
1426  else
1427#endif
1428  AllTotalReadSize = TotalReadSize;
1429
1430  if (Rank == 0 && PrintStats) {
1431    double Rate = ((double) AllTotalReadSize) / MaxTotalTime / (1024.*1024.);
1432    std::cout << "Read " << Vars.size() << " variables from " << FileName <<
1433                 " (" << AllTotalReadSize << " bytes) in " << MaxTotalTime << "s: " <<
1434                 Rate << " MB/s [excluding header read]" << std::endl;
1435  }
1436}
1437
1438void GenericIO::readData(int EffRank, size_t RowOffset, int Rank,
1439                         uint64_t &TotalReadSize, int NErrs[3]) {
1440  if (FH.isBigEndian())
1441    readData<true>(EffRank, RowOffset, Rank, TotalReadSize, NErrs);
1442  else
1443    readData<false>(EffRank, RowOffset, Rank, TotalReadSize, NErrs);
1444}
1445
1446// Note: Errors from this function should be recoverable. This means that if
1447// one rank throws an exception, then all ranks should.
1448template <bool IsBigEndian>
1449void GenericIO::readData(int EffRank, size_t RowOffset, int Rank,
1450                         uint64_t &TotalReadSize, int NErrs[3]) {
1451  openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed,
1452                    EffRank, false);
1453
1454  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1455
1456  if (EffRank == -1)
1457    EffRank = Rank;
1458
1459  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1460  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
1461
1462  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1463
1464  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
1465                                               RankIndex*GH->RanksSize];
1466
1467  for (size_t i = 0; i < Vars.size(); ++i) {
1468    uint64_t Offset = RH->Start;
1469    bool VarFound = false;
1470    for (uint64_t j = 0; j < GH->NVars; ++j) {
1471      VariableHeader<IsBigEndian> *VH = (VariableHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->VarsStart +
1472                                                           j*GH->VarsSize];
1473
1474      string VName(VH->Name, VH->Name + NameSize);
1475      size_t VNameNull = VName.find('\0');
1476      if (VNameNull < NameSize)
1477        VName.resize(VNameNull);
1478
1479      uint64_t ReadSize = RH->NElems*VH->Size + CRCSize;
1480      if (VName != Vars[i].Name) {
1481        Offset += ReadSize;
1482        continue;
1483      }
1484
1485      size_t ElementSize = VH->Size;
1486      if (offsetof_safe(VH, ElementSize) < GH->VarsSize)
1487        ElementSize = VH->ElementSize;
1488
1489      VarFound = true;
1490      bool IsFloat = (bool) (VH->Flags & FloatValue),
1491           IsSigned = (bool) (VH->Flags & SignedValue);
1492      if (VH->Size != Vars[i].Size) {
1493        stringstream ss;
1494        ss << "Size mismatch for variable " << Vars[i].Name <<
1495              " in: " << OpenFileName << ": current: " << Vars[i].Size <<
1496              ", file: " << VH->Size;
1497        throw runtime_error(ss.str());
1498      } else if (ElementSize != Vars[i].ElementSize) {
1499        stringstream ss;
1500        ss << "Element size mismatch for variable " << Vars[i].Name <<
1501              " in: " << OpenFileName << ": current: " << Vars[i].ElementSize <<
1502              ", file: " << ElementSize;
1503        throw runtime_error(ss.str());
1504      } else if (IsFloat != Vars[i].IsFloat) {
1505        string Float("float"), Int("integer");
1506        stringstream ss;
1507        ss << "Type mismatch for variable " << Vars[i].Name <<
1508              " in: " << OpenFileName << ": current: " <<
1509              (Vars[i].IsFloat ? Float : Int) <<
1510              ", file: " << (IsFloat ? Float : Int);
1511        throw runtime_error(ss.str());
1512      } else if (IsSigned != Vars[i].IsSigned) {
1513        string Signed("signed"), Uns("unsigned");
1514        stringstream ss;
1515        ss << "Type mismatch for variable " << Vars[i].Name <<
1516              " in: " << OpenFileName << ": current: " <<
1517              (Vars[i].IsSigned ? Signed : Uns) <<
1518              ", file: " << (IsSigned ? Signed : Uns);
1519        throw runtime_error(ss.str());
1520      }
1521
1522      size_t VarOffset = RowOffset*Vars[i].Size;
1523      void *VarData = ((char *) Vars[i].Data) + VarOffset;
1524
1525      vector<unsigned char> LData;
1526      bool HasSZ = false;
1527      void *Data = VarData;
1528      bool HasExtraSpace = Vars[i].HasExtraSpace;
1529      if (offsetof_safe(GH, BlocksStart) < GH->GlobalHeaderSize &&
1530          GH->BlocksSize > 0) {
1531        BlockHeader<IsBigEndian> *BH = (BlockHeader<IsBigEndian> *)
1532          &FH.getHeaderCache()[GH->BlocksStart +
1533                               (RankIndex*GH->NVars + j)*GH->BlocksSize];
1534        ReadSize = BH->Size + CRCSize;
1535        Offset = BH->Start;
1536
1537        int FilterIdx = 0;
1538
1539        if (strncmp(BH->Filters[FilterIdx], LossyCompressName, FilterNameSize) == 0) {
1540          ++FilterIdx;
1541          HasSZ = true;
1542        }
1543
1544        if (strncmp(BH->Filters[FilterIdx], CompressName, FilterNameSize) == 0) {
1545          LData.resize(ReadSize);
1546          Data = &LData[0];
1547          HasExtraSpace = true;
1548        } else if (BH->Filters[FilterIdx][0] != '\0') {
1549          stringstream ss;
1550          ss << "Unknown filter \"" << BH->Filters[0] << "\" on variable " << Vars[i].Name;
1551          throw runtime_error(ss.str());
1552        }
1553      }
1554
1555      assert(HasExtraSpace && "Extra space required for reading");
1556
1557      char CRCSave[CRCSize];
1558      char *CRCLoc = ((char *) Data) + ReadSize - CRCSize;
1559      if (HasExtraSpace)
1560        std::copy(CRCLoc, CRCLoc + CRCSize, CRCSave);
1561
1562      int Retry = 0;
1563      {
1564        int RetryCount = 300;
1565        const char *EnvStr = getenv("GENERICIO_RETRY_COUNT");
1566        if (EnvStr)
1567          RetryCount = atoi(EnvStr);
1568
1569        int RetrySleep = 100; // ms
1570        EnvStr = getenv("GENERICIO_RETRY_SLEEP");
1571        if (EnvStr)
1572          RetrySleep = atoi(EnvStr);
1573
1574        for (; Retry < RetryCount; ++Retry) {
1575          try {
1576            FH.get()->read(Data, ReadSize, Offset, Vars[i].Name);
1577            break;
1578          } catch (...) { }
1579
1580          usleep(1000*RetrySleep);
1581        }
1582
1583        if (Retry == RetryCount) {
1584          ++NErrs[0];
1585          break;
1586        } else if (Retry > 0) {
1587          EnvStr = getenv("GENERICIO_VERBOSE");
1588          if (EnvStr) {
1589            int Mod = atoi(EnvStr);
1590            if (Mod > 0) {
1591              int Rank;
1592#ifndef GENERICIO_NO_MPI
1593              MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1594#else
1595              Rank = 0;
1596#endif
1597
1598              std::cerr << "Rank " << Rank << ": " << Retry <<
1599                           " I/O retries were necessary for reading " <<
1600                           Vars[i].Name << " from: " << OpenFileName << "\n";
1601
1602              std::cerr.flush();
1603            }
1604          }
1605        }
1606      }
1607
1608      TotalReadSize += ReadSize;
1609
1610      uint64_t CRC = crc64_omp(Data, ReadSize);
1611      if (CRC != (uint64_t) -1) {
1612        ++NErrs[1];
1613
1614        int Rank;
1615#ifndef GENERICIO_NO_MPI
1616        MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1617#else
1618        Rank = 0;
1619#endif
1620
1621        // All ranks will do this and have a good time!
1622        string dn = "gio_crc_errors";
1623        mkdir(dn.c_str(), 0777);
1624
1625        srand(time(0));
1626        int DumpNum = rand();
1627        stringstream ssd;
1628        ssd << dn << "/gio_crc_error_dump." << Rank << "." << DumpNum << ".bin";
1629
1630        stringstream ss;
1631        ss << dn << "/gio_crc_error_log." << Rank << ".txt";
1632
1633        ofstream ofs(ss.str().c_str(), ofstream::out | ofstream::app);
1634        ofs << "On-Disk CRC Error Report:\n";
1635        ofs << "Variable: " << Vars[i].Name << "\n";
1636        ofs << "File: " << OpenFileName << "\n";
1637        ofs << "I/O Retries: " << Retry << "\n";
1638        ofs << "Size: " << ReadSize << " bytes\n";
1639        ofs << "Offset: " << Offset << " bytes\n";
1640        ofs << "CRC: " << CRC << " (expected is -1)\n";
1641        ofs << "Dump file: " << ssd.str() << "\n";
1642        ofs << "\n";
1643        ofs.close();
1644
1645        ofstream dofs(ssd.str().c_str(), ofstream::out);
1646        dofs.write((const char *) Data, ReadSize);
1647        dofs.close();
1648
1649        uint64_t RawCRC = crc64_omp(Data, ReadSize - CRCSize);
1650        unsigned char *UData = (unsigned char *) Data;
1651        crc64_invert(RawCRC, &UData[ReadSize - CRCSize]);
1652        uint64_t NewCRC = crc64_omp(Data, ReadSize);
1653        std::cerr << "Recalulated CRC: " << NewCRC << ((NewCRC == -1) ? "ok" : "bad") << "\n";
1654        break;
1655      }
1656
1657      if (HasExtraSpace)
1658        std::copy(CRCSave, CRCSave + CRCSize, CRCLoc);
1659
1660      if (LData.size()) {
1661        CompressHeader<IsBigEndian> *CH = (CompressHeader<IsBigEndian>*) &LData[0];
1662
1663#ifdef _OPENMP
1664#pragma omp master
1665  {
1666#endif
1667
1668       if (!blosc_initialized) {
1669         blosc_init();
1670         blosc_initialized = true;
1671       }
1672
1673       if (!sz_initialized) {
1674         SZ_Init(NULL);
1675         sz_initialized = true;
1676       }
1677
1678#ifdef _OPENMP
1679       blosc_set_nthreads(omp_get_max_threads());
1680  }
1681#endif
1682
1683        void *OrigData = VarData;
1684        size_t OrigDataSize = Vars[i].Size*RH->NElems;
1685
1686        if (HasSZ) {
1687          size_t CNBytes, CCBytes, CBlockSize;
1688          blosc_cbuffer_sizes(&LData[0] + sizeof(CompressHeader<IsBigEndian>),
1689                              &CNBytes, &CCBytes, &CBlockSize);
1690
1691          OrigData = malloc(CNBytes);
1692          OrigDataSize = CNBytes;
1693        }
1694
1695        blosc_decompress(&LData[0] + sizeof(CompressHeader<IsBigEndian>),
1696                         OrigData, OrigDataSize);
1697
1698        if (CH->OrigCRC != crc64_omp(OrigData, OrigDataSize)) {
1699          ++NErrs[2];
1700          break;
1701        }
1702
1703        if (HasSZ) {
1704          int SZDT = GetSZDT(Vars[i]);
1705          size_t LDSz = SZ_decompress_args(SZDT, (unsigned char *)OrigData, OrigDataSize,
1706                                           VarData, 0, 0, 0, 0, RH->NElems);
1707          free(OrigData);
1708
1709          if (LDSz != RH->NElems)
1710            throw runtime_error("Variable " + Vars[i].Name +
1711                                ": SZ decompression yielded the wrong amount of data");
1712        }
1713      }
1714
1715      // Byte swap the data if necessary.
1716      if (IsBigEndian != isBigEndian() && !HasSZ)
1717        for (size_t j = 0;
1718             j < RH->NElems*(Vars[i].Size/Vars[i].ElementSize); ++j) {
1719          char *Offset = ((char *) VarData) + j*Vars[i].ElementSize;
1720          bswap(Offset, Vars[i].ElementSize);
1721        }
1722
1723      break;
1724    }
1725
1726    if (!VarFound)
1727      throw runtime_error("Variable " + Vars[i].Name +
1728                          " not found in: " + OpenFileName);
1729
1730    // This is for debugging.
1731    if (NErrs[0] || NErrs[1] || NErrs[2]) {
1732      const char *EnvStr = getenv("GENERICIO_VERBOSE");
1733      if (EnvStr) {
1734        int Mod = atoi(EnvStr);
1735        if (Mod > 0) {
1736          int Rank;
1737#ifndef GENERICIO_NO_MPI
1738          MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1739#else
1740          Rank = 0;
1741#endif
1742
1743          std::cerr << "Rank " << Rank << ": " << NErrs[0] << " I/O error(s), " <<
1744          NErrs[1] << " CRC error(s) and " << NErrs[2] <<
1745          " decompression CRC error(s) reading: " << Vars[i].Name <<
1746          " from: " << OpenFileName << "\n";
1747
1748          std::cerr.flush();
1749        }
1750      }
1751    }
1752
1753    if (NErrs[0] || NErrs[1] || NErrs[2])
1754      break;
1755  }
1756}
1757
1758void GenericIO::getVariableInfo(vector<VariableInfo> &VI) {
1759  if (FH.isBigEndian())
1760    getVariableInfo<true>(VI);
1761  else
1762    getVariableInfo<false>(VI);
1763}
1764
1765template <bool IsBigEndian>
1766void GenericIO::getVariableInfo(vector<VariableInfo> &VI) {
1767  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1768
1769  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1770  for (uint64_t j = 0; j < GH->NVars; ++j) {
1771    VariableHeader<IsBigEndian> *VH = (VariableHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->VarsStart +
1772                                                         j*GH->VarsSize];
1773
1774    string VName(VH->Name, VH->Name + NameSize);
1775    size_t VNameNull = VName.find('\0');
1776    if (VNameNull < NameSize)
1777      VName.resize(VNameNull);
1778
1779    size_t ElementSize = VH->Size;
1780    if (offsetof_safe(VH, ElementSize) < GH->VarsSize)
1781      ElementSize = VH->ElementSize;
1782
1783    bool IsFloat = (bool) (VH->Flags & FloatValue),
1784         IsSigned = (bool) (VH->Flags & SignedValue),
1785         IsPhysCoordX = (bool) (VH->Flags & ValueIsPhysCoordX),
1786         IsPhysCoordY = (bool) (VH->Flags & ValueIsPhysCoordY),
1787         IsPhysCoordZ = (bool) (VH->Flags & ValueIsPhysCoordZ),
1788         MaybePhysGhost = (bool) (VH->Flags & ValueMaybePhysGhost);
1789    VI.push_back(VariableInfo(VName, (size_t) VH->Size, IsFloat, IsSigned,
1790                              IsPhysCoordX, IsPhysCoordY, IsPhysCoordZ,
1791                              MaybePhysGhost, ElementSize));
1792  }
1793}
1794
1795void GenericIO::setNaturalDefaultPartition() {
1796#ifdef __bgq__
1797  DefaultPartition = MPIX_IO_link_id();
1798#else
1799#ifndef GENERICIO_NO_MPI
1800  bool UseName = true;
1801  const char *EnvStr = getenv("GENERICIO_PARTITIONS_USE_NAME");
1802  if (EnvStr) {
1803    int Mod = atoi(EnvStr);
1804    UseName = (Mod != 0);
1805  }
1806
1807  if (UseName) {
1808    // This is a heuristic to generate ~256 partitions based on the
1809    // names of the nodes.
1810    char Name[MPI_MAX_PROCESSOR_NAME];
1811    int Len = 0;
1812
1813    MPI_Get_processor_name(Name, &Len);
1814    unsigned char color = 0;
1815    for (int i = 0; i < Len; ++i)
1816      color += (unsigned char) Name[i];
1817
1818    DefaultPartition = color;
1819  }
1820
1821  // This is for debugging.
1822  EnvStr = getenv("GENERICIO_RANK_PARTITIONS");
1823  if (EnvStr) {
1824    int Mod = atoi(EnvStr);
1825    if (Mod > 0) {
1826      int Rank;
1827      MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1828      DefaultPartition += Rank % Mod;
1829    }
1830  }
1831#endif
1832#endif
1833}
1834
1835} /* END namespace cosmotk */
Note: See TracBrowser for help on using the repository browser.