source: GenericIO.cxx @ 1aa7cbe

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

use best speed for SZ - blosc comes next

  • Property mode set to 100644
RevLine 
[da65757]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
[00587dc]42#define _XOPEN_SOURCE 600
43#include "CRC64.h"
44#include "GenericIO.h"
45
46extern "C" {
47#include "blosc.h"
48}
[6461f57]49#include "sz.h"
[00587dc]50
51#include <sstream>
52#include <fstream>
53#include <stdexcept>
[14e73bb]54#include <iterator>
[00587dc]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__
[14e73bb]70#include <mpix.h>
[00587dc]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
[56b997e]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);
[00587dc]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
[56b997e]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);
[00587dc]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
[14e73bb]212      throw runtime_error("Unable to read " + D + " from file: " + FileName +
213                          ": " + strerror(errno));
[00587dc]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
[14e73bb]231      throw runtime_error("Unable to write " + D + " to file: " + FileName +
232                          ": " + strerror(errno));
[00587dc]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
[a4fee13]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
[00587dc]289static const size_t CRCSize = 8;
290
291static const size_t MagicSize = 8;
292static const char *MagicBE = "HACC01B";
293static const char *MagicLE = "HACC01L";
294
[a4fee13]295template <bool IsBigEndian>
[00587dc]296struct GlobalHeader {
297  char Magic[MagicSize];
[a4fee13]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};
[00587dc]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;
[a4fee13]324template <bool IsBigEndian>
[00587dc]325struct VariableHeader {
326  char Name[NameSize];
[a4fee13]327  endian_specific_value<uint64_t, IsBigEndian> Flags;
328  endian_specific_value<uint64_t, IsBigEndian> Size;
[5d57155]329  endian_specific_value<uint64_t, IsBigEndian> ElementSize;
[a4fee13]330};
[00587dc]331
[a4fee13]332template <bool IsBigEndian>
[00587dc]333struct RankHeader {
[a4fee13]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};
[00587dc]339
340static const size_t FilterNameSize = 8;
341static const size_t MaxFilters = 4;
[a4fee13]342template <bool IsBigEndian>
[00587dc]343struct BlockHeader {
344  char Filters[MaxFilters][FilterNameSize];
[a4fee13]345  endian_specific_value<uint64_t, IsBigEndian> Start;
346  endian_specific_value<uint64_t, IsBigEndian> Size;
347};
[00587dc]348
[a4fee13]349template <bool IsBigEndian>
[00587dc]350struct CompressHeader {
[a4fee13]351  endian_specific_value<uint64_t, IsBigEndian> OrigCRC;
352};
[00587dc]353const char *CompressName = "BLOSC";
354
[6461f57]355const char *LossyCompressName = "SZ";
356
[a4fee13]357#pragma pack()
358
[00587dc]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;
[6461f57]368static bool sz_initialized = false;
[00587dc]369
[eeacdad]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
[00587dc]395#ifndef GENERICIO_NO_MPI
[a4fee13]396void GenericIO::write() {
397  if (isBigEndian())
398    write<true>();
399  else
400    write<false>();
401}
402
[00587dc]403// Note: writing errors are not currently recoverable (one rank may fail
404// while the others don't).
[a4fee13]405template <bool IsBigEndian>
[00587dc]406void GenericIO::write() {
[a4fee13]407  const char *Magic = IsBigEndian ? MagicBE : MagicLE;
[00587dc]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
[a4fee13]478  RankHeader<IsBigEndian> RHLocal;
[00587dc]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
[a4fee13]512  vector<BlockHeader<IsBigEndian> > LocalBlockHeaders;
[00587dc]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).
[a4fee13]526      memset(&LocalBlockHeaders[i], 0, sizeof(BlockHeader<IsBigEndian>));
[00587dc]527      if (ShouldCompress) {
[eeacdad]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) {
[0654f4c]535#ifdef _OPENMP
536#pragma omp master
537  {
538#endif
539         if (!sz_initialized) {
540           SZ_Init(NULL);
[1aa7cbe]541           confparams_cpr->szMode = 0; // Best-speed mode.
[0654f4c]542           sz_initialized = true;
543         }
544
545#ifdef _OPENMP
546  }
547#endif
[eeacdad]548          int SZDT = GetSZDT(Vars[i]);
549          if (SZDT == -1)
550            goto nosz;
551
552          int EBM;
553          switch (Vars[i].LCI.Mode) {
554          case LossyCompressionInfo::LCModeAbs:
555            EBM = ABS;
556            break;
557          case LossyCompressionInfo::LCModeRel:
558            EBM = REL;
559            break;
560          case LossyCompressionInfo::LCModeAbsAndRel:
561            EBM = ABS_AND_REL;
562            break;
563          case LossyCompressionInfo::LCModeAbsOrRel:
564            EBM = ABS_OR_REL;
565            break;
566          case LossyCompressionInfo::LCModePSNR:
567            EBM = PSNR;
568            break;
569          }
570
571          size_t LOutSize;
572          unsigned char *LCompressedData = SZ_compress_args(SZDT, Vars[i].Data, &LOutSize, EBM,
573                                                            Vars[i].LCI.AbsErrThreshold, Vars[i].LCI.RelErrThreshold,
574                                                            Vars[i].LCI.PSNRThreshold, 0, 0, 0, 0, NElems);
575          if (!LCompressedData)
576            goto nosz;
577          if (LOutSize >= NElems*Vars[i].Size) {
578            free(LCompressedData);
579            goto nosz;
580          }
581
582          OrigData = LCompressedData;
583          FreeOrigData = true;
584          OrigUnitSize = 1;
585          OrigDataSize = LOutSize;
586
587          strncpy(LocalBlockHeaders[i].Filters[FilterIdx++], LossyCompressName, FilterNameSize);
588        }
589nosz:
590
[a4fee13]591        LocalCData[i].resize(sizeof(CompressHeader<IsBigEndian>));
[00587dc]592
[a4fee13]593        CompressHeader<IsBigEndian> *CH = (CompressHeader<IsBigEndian>*) &LocalCData[i][0];
[eeacdad]594        CH->OrigCRC = crc64_omp(OrigData, OrigDataSize);
[00587dc]595
596#ifdef _OPENMP
597#pragma omp master
598  {
599#endif
600
601       if (!blosc_initialized) {
602         blosc_init();
603         blosc_initialized = true;
604       }
605
606#ifdef _OPENMP
607       blosc_set_nthreads(omp_get_max_threads());
608  }
609#endif
610
[eeacdad]611        LocalCData[i].resize(LocalCData[i].size() + OrigDataSize);
612        if (blosc_compress(9, 1, OrigUnitSize, OrigDataSize, OrigData,
[a4fee13]613                           &LocalCData[i][0] + sizeof(CompressHeader<IsBigEndian>),
[eeacdad]614                           OrigDataSize) <= 0) {
615          if (FreeOrigData)
616            free(OrigData);
617
[00587dc]618          goto nocomp;
[eeacdad]619        }
[00587dc]620
[eeacdad]621        if (FreeOrigData)
622          free(OrigData);
623
624        strncpy(LocalBlockHeaders[i].Filters[FilterIdx++], CompressName, FilterNameSize);
[00587dc]625        size_t CNBytes, CCBytes, CBlockSize;
[a4fee13]626        blosc_cbuffer_sizes(&LocalCData[i][0] + sizeof(CompressHeader<IsBigEndian>),
[00587dc]627                            &CNBytes, &CCBytes, &CBlockSize);
[a4fee13]628        LocalCData[i].resize(CCBytes + sizeof(CompressHeader<IsBigEndian>));
[00587dc]629
630        LocalBlockHeaders[i].Size = LocalCData[i].size();
631        LocalCData[i].resize(LocalCData[i].size() + CRCSize);
632        LocalData[i] = &LocalCData[i][0];
633        LocalHasExtraSpace[i] = true;
634      } else {
635nocomp:
636        LocalBlockHeaders[i].Size = NElems*Vars[i].Size;
637        LocalData[i] = Vars[i].Data;
638        LocalHasExtraSpace[i] = Vars[i].HasExtraSpace;
639      }
640    }
641  }
642
643  double StartTime = MPI_Wtime();
644
645  if (SplitRank == 0) {
[a4fee13]646    uint64_t HeaderSize = sizeof(GlobalHeader<IsBigEndian>) + Vars.size()*sizeof(VariableHeader<IsBigEndian>) +
647                          SplitNRanks*sizeof(RankHeader<IsBigEndian>) + CRCSize;
[00587dc]648    if (NeedsBlockHeaders)
[a4fee13]649      HeaderSize += SplitNRanks*Vars.size()*sizeof(BlockHeader<IsBigEndian>);
[00587dc]650
651    vector<char> Header(HeaderSize, 0);
[a4fee13]652    GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &Header[0];
[00587dc]653    std::copy(Magic, Magic + MagicSize, GH->Magic);
654    GH->HeaderSize = HeaderSize - CRCSize;
655    GH->NElems = NElems; // This will be updated later
656    std::copy(Dims, Dims + 3, GH->Dims);
657    GH->NVars = Vars.size();
[a4fee13]658    GH->VarsSize = sizeof(VariableHeader<IsBigEndian>);
659    GH->VarsStart = sizeof(GlobalHeader<IsBigEndian>);
[00587dc]660    GH->NRanks = SplitNRanks;
[a4fee13]661    GH->RanksSize = sizeof(RankHeader<IsBigEndian>);
662    GH->RanksStart = GH->VarsStart + Vars.size()*sizeof(VariableHeader<IsBigEndian>);
663    GH->GlobalHeaderSize = sizeof(GlobalHeader<IsBigEndian>);
[00587dc]664    std::copy(PhysOrigin, PhysOrigin + 3, GH->PhysOrigin);
665    std::copy(PhysScale,  PhysScale  + 3, GH->PhysScale);
666    if (!NeedsBlockHeaders) {
667      GH->BlocksSize = GH->BlocksStart = 0;
668    } else {
[a4fee13]669      GH->BlocksSize = sizeof(BlockHeader<IsBigEndian>);
670      GH->BlocksStart = GH->RanksStart + SplitNRanks*sizeof(RankHeader<IsBigEndian>);
[00587dc]671    }
672
673    uint64_t RecordSize = 0;
[a4fee13]674    VariableHeader<IsBigEndian> *VH = (VariableHeader<IsBigEndian> *) &Header[GH->VarsStart];
[00587dc]675    for (size_t i = 0; i < Vars.size(); ++i, ++VH) {
676      string VName(Vars[i].Name);
677      VName.resize(NameSize);
678
679      std::copy(VName.begin(), VName.end(), VH->Name);
[a4fee13]680      uint64_t VFlags = 0;
681      if (Vars[i].IsFloat)  VFlags |= FloatValue;
682      if (Vars[i].IsSigned) VFlags |= SignedValue;
683      if (Vars[i].IsPhysCoordX) VFlags |= ValueIsPhysCoordX;
684      if (Vars[i].IsPhysCoordY) VFlags |= ValueIsPhysCoordY;
685      if (Vars[i].IsPhysCoordZ) VFlags |= ValueIsPhysCoordZ;
686      if (Vars[i].MaybePhysGhost) VFlags |= ValueMaybePhysGhost;
687      VH->Flags = VFlags;
[00587dc]688      RecordSize += VH->Size = Vars[i].Size;
[5d57155]689      VH->ElementSize = Vars[i].ElementSize;
[00587dc]690    }
691
692    MPI_Gather(&RHLocal, sizeof(RHLocal), MPI_BYTE,
693               &Header[GH->RanksStart], sizeof(RHLocal),
694               MPI_BYTE, 0, SplitComm);
695
696    if (NeedsBlockHeaders) {
697      MPI_Gather(&LocalBlockHeaders[0],
[a4fee13]698                 Vars.size()*sizeof(BlockHeader<IsBigEndian>), MPI_BYTE,
[00587dc]699                 &Header[GH->BlocksStart],
[a4fee13]700                 Vars.size()*sizeof(BlockHeader<IsBigEndian>), MPI_BYTE,
[00587dc]701                 0, SplitComm);
702
[a4fee13]703      BlockHeader<IsBigEndian> *BH = (BlockHeader<IsBigEndian> *) &Header[GH->BlocksStart];
[00587dc]704      for (int i = 0; i < SplitNRanks; ++i)
705      for (size_t j = 0; j < Vars.size(); ++j, ++BH) {
706        if (i == 0 && j == 0)
707          BH->Start = HeaderSize;
708        else
709          BH->Start = BH[-1].Start + BH[-1].Size + CRCSize;
710      }
711
[a4fee13]712      RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &Header[GH->RanksStart];
[00587dc]713      RH->Start = HeaderSize; ++RH;
714      for (int i = 1; i < SplitNRanks; ++i, ++RH) {
715        RH->Start =
[a4fee13]716          ((BlockHeader<IsBigEndian> *) &Header[GH->BlocksStart])[i*Vars.size()].Start;
[00587dc]717        GH->NElems += RH->NElems;
718      }
719
720      // Compute the total file size.
721      uint64_t LastData = BH[-1].Size + CRCSize;
722      FileSize = BH[-1].Start + LastData;
723    } else {
[a4fee13]724      RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &Header[GH->RanksStart];
[00587dc]725      RH->Start = HeaderSize; ++RH;
726      for (int i = 1; i < SplitNRanks; ++i, ++RH) {
727        uint64_t PrevNElems = RH[-1].NElems;
728        uint64_t PrevData = PrevNElems*RecordSize + CRCSize*Vars.size();
729        RH->Start = RH[-1].Start + PrevData;
730        GH->NElems += RH->NElems;
731      }
732
733      // Compute the total file size.
734      uint64_t LastNElems = RH[-1].NElems;
735      uint64_t LastData = LastNElems*RecordSize + CRCSize*Vars.size();
736      FileSize = RH[-1].Start + LastData;
737    }
738
739    // Now that the starting offset has been computed, send it back to each rank.
740    MPI_Scatter(&Header[GH->RanksStart], sizeof(RHLocal),
741                MPI_BYTE, &RHLocal, sizeof(RHLocal),
742                MPI_BYTE, 0, SplitComm);
743
744    if (NeedsBlockHeaders)
745      MPI_Scatter(&Header[GH->BlocksStart],
[a4fee13]746                  sizeof(BlockHeader<IsBigEndian>)*Vars.size(), MPI_BYTE,
[00587dc]747                  &LocalBlockHeaders[0],
[a4fee13]748                  sizeof(BlockHeader<IsBigEndian>)*Vars.size(), MPI_BYTE,
[00587dc]749                  0, SplitComm);
750
751    uint64_t HeaderCRC = crc64_omp(&Header[0], HeaderSize - CRCSize);
752    crc64_invert(HeaderCRC, &Header[HeaderSize - CRCSize]);
753
754    if (FileIOType == FileIOMPI)
755      FH.get() = new GenericFileIO_MPI(MPI_COMM_SELF);
756    else if (FileIOType == FileIOMPICollective)
757      FH.get() = new GenericFileIO_MPICollective(MPI_COMM_SELF);
758    else
759      FH.get() = new GenericFileIO_POSIX();
760
761    FH.get()->open(LocalFileName);
762    FH.get()->setSize(FileSize);
763    FH.get()->write(&Header[0], HeaderSize, 0, "header");
764
765    close();
766  } else {
767    MPI_Gather(&RHLocal, sizeof(RHLocal), MPI_BYTE, 0, 0, MPI_BYTE, 0, SplitComm);
768    if (NeedsBlockHeaders)
[a4fee13]769      MPI_Gather(&LocalBlockHeaders[0], Vars.size()*sizeof(BlockHeader<IsBigEndian>),
[00587dc]770                 MPI_BYTE, 0, 0, MPI_BYTE, 0, SplitComm);
771    MPI_Scatter(0, 0, MPI_BYTE, &RHLocal, sizeof(RHLocal), MPI_BYTE, 0, SplitComm);
772    if (NeedsBlockHeaders)
[a4fee13]773      MPI_Scatter(0, 0, MPI_BYTE, &LocalBlockHeaders[0], sizeof(BlockHeader<IsBigEndian>)*Vars.size(),
[00587dc]774                  MPI_BYTE, 0, SplitComm);
775  }
776
777  MPI_Barrier(SplitComm);
778
779  if (FileIOType == FileIOMPI)
780    FH.get() = new GenericFileIO_MPI(SplitComm);
781  else if (FileIOType == FileIOMPICollective)
782    FH.get() = new GenericFileIO_MPICollective(SplitComm);
783  else
784    FH.get() = new GenericFileIO_POSIX();
785
786  FH.get()->open(LocalFileName);
787
788  uint64_t Offset = RHLocal.Start;
789  for (size_t i = 0; i < Vars.size(); ++i) {
790    uint64_t WriteSize = NeedsBlockHeaders ?
791                         LocalBlockHeaders[i].Size : NElems*Vars[i].Size;
792    void *Data = NeedsBlockHeaders ? LocalData[i] : Vars[i].Data;
793    uint64_t CRC = crc64_omp(Data, WriteSize);
794    bool HasExtraSpace = NeedsBlockHeaders ?
795                         LocalHasExtraSpace[i] : Vars[i].HasExtraSpace;
796    char *CRCLoc = HasExtraSpace ?  ((char *) Data) + WriteSize : (char *) &CRC;
797
798    if (NeedsBlockHeaders)
799      Offset = LocalBlockHeaders[i].Start;
800
801    // When using extra space for the CRC write, preserve the original contents.
802    char CRCSave[CRCSize];
803    if (HasExtraSpace)
804      std::copy(CRCLoc, CRCLoc + CRCSize, CRCSave);
805
806    crc64_invert(CRC, CRCLoc);
807
808    if (HasExtraSpace) {
809      FH.get()->write(Data, WriteSize + CRCSize, Offset, Vars[i].Name + " with CRC");
810    } else {
811      FH.get()->write(Data, WriteSize, Offset, Vars[i].Name);
812      FH.get()->write(CRCLoc, CRCSize, Offset + WriteSize, Vars[i].Name + " CRC");
813    }
814
815    if (HasExtraSpace)
816       std::copy(CRCSave, CRCSave + CRCSize, CRCLoc);
817
818    Offset += WriteSize + CRCSize;
819  }
820
821  close();
822  MPI_Barrier(Comm);
823
824  double EndTime = MPI_Wtime();
825  double TotalTime = EndTime - StartTime;
826  double MaxTotalTime;
827  MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
828
829  if (SplitNRanks != NRanks) {
830    uint64_t ContribFileSize = (SplitRank == 0) ? FileSize : 0;
831    MPI_Reduce(&ContribFileSize, &FileSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
832  }
833
834  if (Rank == 0) {
835    double Rate = ((double) FileSize) / MaxTotalTime / (1024.*1024.);
[d6628a6]836    std::cout << "Wrote " << Vars.size() << " variables to " << FileName <<
837                  " (" << FileSize << " bytes) in " << MaxTotalTime << "s: " <<
838                  Rate << " MB/s" << std::endl;
[00587dc]839  }
840
841  MPI_Comm_free(&SplitComm);
842  SplitComm = MPI_COMM_NULL;
843}
844#endif // GENERICIO_NO_MPI
845
[a4fee13]846template <bool IsBigEndian>
[8f0a211]847void GenericIO::readHeaderLeader(void *GHPtr, MismatchBehavior MB, int NRanks,
848                                 int Rank, int SplitNRanks,
849                                 string &LocalFileName, uint64_t &HeaderSize,
850                                 vector<char> &Header) {
[a4fee13]851  GlobalHeader<IsBigEndian> &GH = *(GlobalHeader<IsBigEndian> *) GHPtr;
852
[8f0a211]853  if (MB == MismatchDisallowed) {
[a4fee13]854    if (SplitNRanks != (int) GH.NRanks) {
855      stringstream ss;
856      ss << "Won't read " << LocalFileName << ": communicator-size mismatch: " <<
857            "current: " << SplitNRanks << ", file: " << GH.NRanks;
858      throw runtime_error(ss.str());
859    }
860
861#ifndef GENERICIO_NO_MPI
862    int TopoStatus;
863    MPI_Topo_test(Comm, &TopoStatus);
864    if (TopoStatus == MPI_CART) {
865      int Dims[3], Periods[3], Coords[3];
866      MPI_Cart_get(Comm, 3, Dims, Periods, Coords);
867
868      bool DimsMatch = true;
869      for (int i = 0; i < 3; ++i) {
870        if ((uint64_t) Dims[i] != GH.Dims[i]) {
871          DimsMatch = false;
872          break;
873        }
874      }
875
876      if (!DimsMatch) {
877        stringstream ss;
878        ss << "Won't read " << LocalFileName <<
879              ": communicator-decomposition mismatch: " <<
880              "current: " << Dims[0] << "x" << Dims[1] << "x" << Dims[2] <<
881              ", file: " << GH.Dims[0] << "x" << GH.Dims[1] << "x" <<
882              GH.Dims[2];
883        throw runtime_error(ss.str());
884      }
885    }
886#endif
[8f0a211]887  } else if (MB == MismatchRedistribute && !Redistributing) {
888    Redistributing = true;
889
890    int NFileRanks = RankMap.empty() ? (int) GH.NRanks : (int) RankMap.size();
891    int NFileRanksPerRank = NFileRanks/NRanks;
892    int NRemFileRank = NFileRanks % NRanks;
893
894    if (!NFileRanksPerRank) {
895      // We have only the remainder, so the last NRemFileRank ranks get one
896      // file rank, and the others don't.
897      if (NRemFileRank && NRanks - Rank <= NRemFileRank)
898        SourceRanks.push_back(NRanks - (Rank + 1));
899    } else {
900      // Since NRemFileRank < NRanks, and we don't want to put any extra memory
901      // load on rank 0 (because rank 0's memory load is normally higher than
902      // the other ranks anyway), the last NRemFileRank will each take
903      // (NFileRanksPerRank+1) file ranks.
904
905      int FirstFileRank = 0, LastFileRank = NFileRanksPerRank - 1;
906      for (int i = 1; i <= Rank; ++i) {
907        FirstFileRank = LastFileRank + 1;
908        LastFileRank  = FirstFileRank + NFileRanksPerRank - 1;
909
910        if (NRemFileRank && NRanks - i <= NRemFileRank)
911          ++LastFileRank;
912      }
913
914      for (int i = FirstFileRank; i <= LastFileRank; ++i)
915        SourceRanks.push_back(i);
916    }
[a4fee13]917  }
918
919  HeaderSize = GH.HeaderSize;
920  Header.resize(HeaderSize + CRCSize, 0xFE /* poison */);
921  FH.get()->read(&Header[0], HeaderSize + CRCSize, 0, "header");
922
923  uint64_t CRC = crc64_omp(&Header[0], HeaderSize + CRCSize);
924  if (CRC != (uint64_t) -1) {
925    throw runtime_error("Header CRC check failed: " + LocalFileName);
926  }
927}
928
[00587dc]929// Note: Errors from this function should be recoverable. This means that if
930// one rank throws an exception, then all ranks should.
[8f0a211]931void GenericIO::openAndReadHeader(MismatchBehavior MB, int EffRank, bool CheckPartMap) {
[00587dc]932  int NRanks, Rank;
933#ifndef GENERICIO_NO_MPI
934  MPI_Comm_rank(Comm, &Rank);
935  MPI_Comm_size(Comm, &NRanks);
936#else
937  Rank = 0;
938  NRanks = 1;
939#endif
940
941  if (EffRank == -1)
[8f0a211]942    EffRank = MB == MismatchRedistribute ? 0 : Rank;
[00587dc]943
944  if (RankMap.empty() && CheckPartMap) {
945    // First, check to see if the file is a rank map.
946    unsigned long RanksInMap = 0;
947    if (Rank == 0) {
948      try {
949#ifndef GENERICIO_NO_MPI
950        GenericIO GIO(MPI_COMM_SELF, FileName, FileIOType);
951#else
952        GenericIO GIO(FileName, FileIOType);
953#endif
[8f0a211]954        GIO.openAndReadHeader(MismatchDisallowed, 0, false);
[00587dc]955        RanksInMap = GIO.readNumElems();
956
957        RankMap.resize(RanksInMap + GIO.requestedExtraSpace()/sizeof(int));
958        GIO.addVariable("$partition", RankMap, true);
959
960        GIO.readData(0, false);
961        RankMap.resize(RanksInMap);
962      } catch (...) {
963        RankMap.clear();
964        RanksInMap = 0;
965      }
966    }
967
968#ifndef GENERICIO_NO_MPI
969    MPI_Bcast(&RanksInMap, 1, MPI_UNSIGNED_LONG, 0, Comm);
970    if (RanksInMap > 0) {
971      RankMap.resize(RanksInMap);
972      MPI_Bcast(&RankMap[0], RanksInMap, MPI_INT, 0, Comm);
973    }
974#endif
975  }
976
977#ifndef GENERICIO_NO_MPI
978  if (SplitComm != MPI_COMM_NULL)
979    MPI_Comm_free(&SplitComm);
980#endif
981
982  string LocalFileName;
983  if (RankMap.empty()) {
984    LocalFileName = FileName;
985#ifndef GENERICIO_NO_MPI
[8f0a211]986    MPI_Comm_dup(MB == MismatchRedistribute ? MPI_COMM_SELF : Comm, &SplitComm);
[00587dc]987#endif
988  } else {
989    stringstream ss;
990    ss << FileName << "#" << RankMap[EffRank];
991    LocalFileName = ss.str();
992#ifndef GENERICIO_NO_MPI
[8f0a211]993    if (MB == MismatchRedistribute) {
994      MPI_Comm_dup(MPI_COMM_SELF, &SplitComm);
995    } else {
[00587dc]996#ifdef __bgq__
[8f0a211]997      MPI_Barrier(Comm);
[00587dc]998#endif
[8f0a211]999      MPI_Comm_split(Comm, RankMap[EffRank], Rank, &SplitComm);
1000    }
[00587dc]1001#endif
1002  }
1003
1004  if (LocalFileName == OpenFileName)
1005    return;
1006  FH.close();
1007
1008  int SplitNRanks, SplitRank;
1009#ifndef GENERICIO_NO_MPI
1010  MPI_Comm_rank(SplitComm, &SplitRank);
1011  MPI_Comm_size(SplitComm, &SplitNRanks);
1012#else
1013  SplitRank = 0;
1014  SplitNRanks = 1;
1015#endif
1016
1017  uint64_t HeaderSize;
1018  vector<char> Header;
1019
1020  if (SplitRank == 0) {
1021#ifndef GENERICIO_NO_MPI
1022    if (FileIOType == FileIOMPI)
1023      FH.get() = new GenericFileIO_MPI(MPI_COMM_SELF);
1024    else if (FileIOType == FileIOMPICollective)
1025      FH.get() = new GenericFileIO_MPICollective(MPI_COMM_SELF);
1026    else
1027#endif
1028      FH.get() = new GenericFileIO_POSIX();
1029
1030#ifndef GENERICIO_NO_MPI
1031    char True = 1, False = 0;
1032#endif
1033
1034    try {
1035      FH.get()->open(LocalFileName, true);
1036
[a4fee13]1037      GlobalHeader<false> GH; // endianness does not matter yet...
1038      FH.get()->read(&GH, sizeof(GlobalHeader<false>), 0, "global header");
[00587dc]1039
[a4fee13]1040      if (string(GH.Magic, GH.Magic + MagicSize - 1) == MagicLE) {
[8f0a211]1041        readHeaderLeader<false>(&GH, MB, NRanks, Rank, SplitNRanks, LocalFileName,
[a4fee13]1042                                HeaderSize, Header);
1043      } else if (string(GH.Magic, GH.Magic + MagicSize - 1) == MagicBE) {
[8f0a211]1044        readHeaderLeader<true>(&GH, MB, NRanks, Rank, SplitNRanks, LocalFileName,
[a4fee13]1045                               HeaderSize, Header);
1046      } else {
1047        string Error = "invalid file-type identifier";
[00587dc]1048        throw runtime_error("Won't read " + LocalFileName + ": " + Error);
1049      }
1050
1051#ifndef GENERICIO_NO_MPI
1052      close();
1053      MPI_Bcast(&True, 1, MPI_BYTE, 0, SplitComm);
1054#endif
1055    } catch (...) {
1056#ifndef GENERICIO_NO_MPI
1057      MPI_Bcast(&False, 1, MPI_BYTE, 0, SplitComm);
1058#endif
1059      close();
1060      throw;
1061    }
1062  } else {
1063#ifndef GENERICIO_NO_MPI
1064    char Okay;
1065    MPI_Bcast(&Okay, 1, MPI_BYTE, 0, SplitComm);
1066    if (!Okay)
1067      throw runtime_error("Failure broadcast from rank 0");
1068#endif
1069  }
1070
1071#ifndef GENERICIO_NO_MPI
1072  MPI_Bcast(&HeaderSize, 1, MPI_UINT64_T, 0, SplitComm);
1073#endif
1074
1075  Header.resize(HeaderSize, 0xFD /* poison */);
1076#ifndef GENERICIO_NO_MPI
1077  MPI_Bcast(&Header[0], HeaderSize, MPI_BYTE, 0, SplitComm);
1078#endif
1079
1080  FH.getHeaderCache().clear();
[a4fee13]1081
1082  GlobalHeader<false> *GH = (GlobalHeader<false> *) &Header[0];
1083  FH.setIsBigEndian(string(GH->Magic, GH->Magic + MagicSize - 1) == MagicBE);
1084
[00587dc]1085  FH.getHeaderCache().swap(Header);
1086  OpenFileName = LocalFileName;
1087
1088#ifndef GENERICIO_NO_MPI
[8f0a211]1089  if (!DisableCollErrChecking)
1090    MPI_Barrier(Comm);
[00587dc]1091
1092  if (FileIOType == FileIOMPI)
1093    FH.get() = new GenericFileIO_MPI(SplitComm);
1094  else if (FileIOType == FileIOMPICollective)
1095    FH.get() = new GenericFileIO_MPICollective(SplitComm);
1096  else
1097    FH.get() = new GenericFileIO_POSIX();
1098
1099  int OpenErr = 0, TotOpenErr;
1100  try {
1101    FH.get()->open(LocalFileName, true);
[8f0a211]1102    MPI_Allreduce(&OpenErr, &TotOpenErr, 1, MPI_INT, MPI_SUM,
1103                  DisableCollErrChecking ? MPI_COMM_SELF : Comm);
[00587dc]1104  } catch (...) {
1105    OpenErr = 1;
[8f0a211]1106    MPI_Allreduce(&OpenErr, &TotOpenErr, 1, MPI_INT, MPI_SUM,
1107                  DisableCollErrChecking ? MPI_COMM_SELF : Comm);
[00587dc]1108    throw;
1109  }
1110
1111  if (TotOpenErr > 0) {
1112    stringstream ss;
1113    ss << TotOpenErr << " ranks failed to open file: " << LocalFileName;
1114    throw runtime_error(ss.str());
1115  }
1116#endif
1117}
1118
1119int GenericIO::readNRanks() {
[a4fee13]1120  if (FH.isBigEndian())
1121    return readNRanks<true>();
1122  return readNRanks<false>();
1123}
1124
1125template <bool IsBigEndian>
1126int GenericIO::readNRanks() {
[00587dc]1127  if (RankMap.size())
1128    return RankMap.size();
1129
1130  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
[a4fee13]1131  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
[00587dc]1132  return (int) GH->NRanks;
1133}
1134
1135void GenericIO::readDims(int Dims[3]) {
[a4fee13]1136  if (FH.isBigEndian())
1137    readDims<true>(Dims);
1138  else
1139    readDims<false>(Dims);
1140}
1141
1142template <bool IsBigEndian>
1143void GenericIO::readDims(int Dims[3]) {
[00587dc]1144  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
[a4fee13]1145  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
[00587dc]1146  std::copy(GH->Dims, GH->Dims + 3, Dims);
1147}
1148
1149uint64_t GenericIO::readTotalNumElems() {
[a4fee13]1150  if (FH.isBigEndian())
1151    return readTotalNumElems<true>();
1152  return readTotalNumElems<false>();
1153}
1154
1155template <bool IsBigEndian>
1156uint64_t GenericIO::readTotalNumElems() {
[00587dc]1157  if (RankMap.size())
1158    return (uint64_t) -1;
1159
1160  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
[a4fee13]1161  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
[00587dc]1162  return GH->NElems;
1163}
1164
1165void GenericIO::readPhysOrigin(double Origin[3]) {
[a4fee13]1166  if (FH.isBigEndian())
1167    readPhysOrigin<true>(Origin);
1168  else
1169    readPhysOrigin<false>(Origin);
1170}
1171
1172// Define a "safe" version of offsetof (offsetof itself might not work for
1173// non-POD types, and at least xlC v12.1 will complain about this if you try).
1174#define offsetof_safe(S, F) (size_t(&(S)->F) - size_t(S))
1175
1176template <bool IsBigEndian>
1177void GenericIO::readPhysOrigin(double Origin[3]) {
[00587dc]1178  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
[a4fee13]1179  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1180  if (offsetof_safe(GH, PhysOrigin) >= GH->GlobalHeaderSize) {
[00587dc]1181    std::fill(Origin, Origin + 3, 0.0);
1182    return;
1183  }
1184
1185  std::copy(GH->PhysOrigin, GH->PhysOrigin + 3, Origin);
1186}
1187
1188void GenericIO::readPhysScale(double Scale[3]) {
[a4fee13]1189  if (FH.isBigEndian())
1190    readPhysScale<true>(Scale);
1191  else
1192    readPhysScale<false>(Scale);
1193}
1194
1195template <bool IsBigEndian>
1196void GenericIO::readPhysScale(double Scale[3]) {
[00587dc]1197  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
[a4fee13]1198  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1199  if (offsetof_safe(GH, PhysScale) >= GH->GlobalHeaderSize) {
[00587dc]1200    std::fill(Scale, Scale + 3, 0.0);
1201    return;
1202  }
1203
1204  std::copy(GH->PhysScale, GH->PhysScale + 3, Scale);
1205}
1206
[a4fee13]1207template <bool IsBigEndian>
1208static size_t getRankIndex(int EffRank, GlobalHeader<IsBigEndian> *GH,
[00587dc]1209                           vector<int> &RankMap, vector<char> &HeaderCache) {
[a4fee13]1210  if (RankMap.empty())
[00587dc]1211    return EffRank;
1212
1213  for (size_t i = 0; i < GH->NRanks; ++i) {
[a4fee13]1214    RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &HeaderCache[GH->RanksStart +
[00587dc]1215                                                 i*GH->RanksSize];
[a4fee13]1216    if (offsetof_safe(RH, GlobalRank) >= GH->RanksSize)
1217      return EffRank;
1218
[00587dc]1219    if ((int) RH->GlobalRank == EffRank)
1220      return i;
1221  }
1222
1223  assert(false && "Index requested of an invalid rank");
1224  return (size_t) -1;
1225}
1226
1227int GenericIO::readGlobalRankNumber(int EffRank) {
[a4fee13]1228  if (FH.isBigEndian())
1229    return readGlobalRankNumber<true>(EffRank);
1230  return readGlobalRankNumber<false>(EffRank);
1231}
1232
1233template <bool IsBigEndian>
1234int GenericIO::readGlobalRankNumber(int EffRank) {
[00587dc]1235  if (EffRank == -1) {
1236#ifndef GENERICIO_NO_MPI
1237    MPI_Comm_rank(Comm, &EffRank);
1238#else
1239    EffRank = 0;
1240#endif
1241  }
1242
[8f0a211]1243  openAndReadHeader(MismatchAllowed, EffRank, false);
[00587dc]1244
1245  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1246
[a4fee13]1247  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1248  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
[00587dc]1249
1250  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1251
[a4fee13]1252  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
[00587dc]1253                                               RankIndex*GH->RanksSize];
1254
[a4fee13]1255  if (offsetof_safe(RH, GlobalRank) >= GH->RanksSize)
1256    return EffRank;
1257
[00587dc]1258  return (int) RH->GlobalRank;
1259}
1260
[14e73bb]1261void GenericIO::getSourceRanks(vector<int> &SR) {
1262  SR.clear();
1263
1264  if (Redistributing) {
1265    std::copy(SourceRanks.begin(), SourceRanks.end(), std::back_inserter(SR));
1266    return;
1267  }
1268
1269  int Rank;
1270#ifndef GENERICIO_NO_MPI
1271  MPI_Comm_rank(Comm, &Rank);
1272#else
1273  Rank = 0;
1274#endif
1275
1276  SR.push_back(Rank);
1277}
1278
[00587dc]1279size_t GenericIO::readNumElems(int EffRank) {
[8f0a211]1280  if (EffRank == -1 && Redistributing) {
1281    DisableCollErrChecking = true;
1282
1283    size_t TotalSize = 0;
1284    for (int i = 0, ie = SourceRanks.size(); i != ie; ++i)
1285      TotalSize += readNumElems(SourceRanks[i]);
1286
1287    DisableCollErrChecking = false;
1288    return TotalSize;
1289  }
1290
[a4fee13]1291  if (FH.isBigEndian())
1292    return readNumElems<true>(EffRank);
1293  return readNumElems<false>(EffRank);
1294}
1295
1296template <bool IsBigEndian>
1297size_t GenericIO::readNumElems(int EffRank) {
[00587dc]1298  if (EffRank == -1) {
1299#ifndef GENERICIO_NO_MPI
1300    MPI_Comm_rank(Comm, &EffRank);
1301#else
1302    EffRank = 0;
1303#endif
1304  }
1305
[8f0a211]1306  openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed,
1307                    EffRank, false);
[00587dc]1308
1309  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1310
[a4fee13]1311  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1312  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
[00587dc]1313
1314  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1315
[a4fee13]1316  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
[00587dc]1317                                               RankIndex*GH->RanksSize];
1318  return (size_t) RH->NElems;
1319}
1320
1321void GenericIO::readCoords(int Coords[3], int EffRank) {
[8f0a211]1322  if (EffRank == -1 && Redistributing) {
1323    std::fill(Coords, Coords + 3, 0);
1324    return;
1325  }
1326
[a4fee13]1327  if (FH.isBigEndian())
1328    readCoords<true>(Coords, EffRank);
1329  else
1330    readCoords<false>(Coords, EffRank);
1331}
1332
1333template <bool IsBigEndian>
1334void GenericIO::readCoords(int Coords[3], int EffRank) {
[00587dc]1335  if (EffRank == -1) {
1336#ifndef GENERICIO_NO_MPI
1337    MPI_Comm_rank(Comm, &EffRank);
1338#else
1339    EffRank = 0;
1340#endif
1341  }
1342
[8f0a211]1343  openAndReadHeader(MismatchAllowed, EffRank, false);
[00587dc]1344
1345  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1346
[a4fee13]1347  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1348  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
[00587dc]1349
1350  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1351
[a4fee13]1352  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
[00587dc]1353                                               RankIndex*GH->RanksSize];
1354
1355  std::copy(RH->Coords, RH->Coords + 3, Coords);
1356}
1357
[a4fee13]1358void GenericIO::readData(int EffRank, bool PrintStats, bool CollStats) {
[00587dc]1359  int Rank;
1360#ifndef GENERICIO_NO_MPI
1361  MPI_Comm_rank(Comm, &Rank);
1362#else
1363  Rank = 0;
1364#endif
1365
[8f0a211]1366  uint64_t TotalReadSize = 0;
1367#ifndef GENERICIO_NO_MPI
1368  double StartTime = MPI_Wtime();
1369#else
1370  double StartTime = double(clock())/CLOCKS_PER_SEC;
1371#endif
1372
1373  int NErrs[3] = { 0, 0, 0 };
1374
1375  if (EffRank == -1 && Redistributing) {
1376    DisableCollErrChecking = true;
1377
1378    size_t RowOffset = 0;
1379    for (int i = 0, ie = SourceRanks.size(); i != ie; ++i) {
1380      readData(SourceRanks[i], RowOffset, Rank, TotalReadSize, NErrs);
1381      RowOffset += readNumElems(SourceRanks[i]);
1382    }
1383
1384    DisableCollErrChecking = false;
1385  } else {
1386    readData(EffRank, 0, Rank, TotalReadSize, NErrs);
1387  }
1388
1389  int AllNErrs[3];
1390#ifndef GENERICIO_NO_MPI
1391  MPI_Allreduce(NErrs, AllNErrs, 3, MPI_INT, MPI_SUM, Comm);
1392#else
1393  AllNErrs[0] = NErrs[0]; AllNErrs[1] = NErrs[1]; AllNErrs[2] = NErrs[2];
1394#endif
1395
1396  if (AllNErrs[0] > 0 || AllNErrs[1] > 0 || AllNErrs[2] > 0) {
1397    stringstream ss;
1398    ss << "Experienced " << AllNErrs[0] << " I/O error(s), " <<
1399          AllNErrs[1] << " CRC error(s) and " << AllNErrs[2] <<
1400          " decompression CRC error(s) reading: " << OpenFileName;
1401    throw runtime_error(ss.str());
1402  }
1403
1404#ifndef GENERICIO_NO_MPI
1405  MPI_Barrier(Comm);
1406#endif
1407
1408#ifndef GENERICIO_NO_MPI
1409  double EndTime = MPI_Wtime();
1410#else
1411  double EndTime = double(clock())/CLOCKS_PER_SEC;
1412#endif
1413
1414  double TotalTime = EndTime - StartTime;
1415  double MaxTotalTime;
1416#ifndef GENERICIO_NO_MPI
1417  if (CollStats)
1418    MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
1419  else
1420#endif
1421  MaxTotalTime = TotalTime;
1422
1423  uint64_t AllTotalReadSize;
1424#ifndef GENERICIO_NO_MPI
1425  if (CollStats)
1426    MPI_Reduce(&TotalReadSize, &AllTotalReadSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
1427  else
1428#endif
1429  AllTotalReadSize = TotalReadSize;
1430
1431  if (Rank == 0 && PrintStats) {
1432    double Rate = ((double) AllTotalReadSize) / MaxTotalTime / (1024.*1024.);
[d6628a6]1433    std::cout << "Read " << Vars.size() << " variables from " << FileName <<
1434                 " (" << AllTotalReadSize << " bytes) in " << MaxTotalTime << "s: " <<
1435                 Rate << " MB/s [excluding header read]" << std::endl;
[8f0a211]1436  }
1437}
1438
1439void GenericIO::readData(int EffRank, size_t RowOffset, int Rank,
1440                         uint64_t &TotalReadSize, int NErrs[3]) {
1441  if (FH.isBigEndian())
1442    readData<true>(EffRank, RowOffset, Rank, TotalReadSize, NErrs);
1443  else
1444    readData<false>(EffRank, RowOffset, Rank, TotalReadSize, NErrs);
1445}
1446
1447// Note: Errors from this function should be recoverable. This means that if
1448// one rank throws an exception, then all ranks should.
1449template <bool IsBigEndian>
1450void GenericIO::readData(int EffRank, size_t RowOffset, int Rank,
1451                         uint64_t &TotalReadSize, int NErrs[3]) {
1452  openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed,
1453                    EffRank, false);
[00587dc]1454
1455  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1456
1457  if (EffRank == -1)
1458    EffRank = Rank;
1459
[a4fee13]1460  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1461  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
[00587dc]1462
1463  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1464
[a4fee13]1465  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
[00587dc]1466                                               RankIndex*GH->RanksSize];
1467
1468  for (size_t i = 0; i < Vars.size(); ++i) {
1469    uint64_t Offset = RH->Start;
1470    bool VarFound = false;
1471    for (uint64_t j = 0; j < GH->NVars; ++j) {
[a4fee13]1472      VariableHeader<IsBigEndian> *VH = (VariableHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->VarsStart +
[00587dc]1473                                                           j*GH->VarsSize];
1474
1475      string VName(VH->Name, VH->Name + NameSize);
1476      size_t VNameNull = VName.find('\0');
1477      if (VNameNull < NameSize)
1478        VName.resize(VNameNull);
1479
1480      uint64_t ReadSize = RH->NElems*VH->Size + CRCSize;
1481      if (VName != Vars[i].Name) {
1482        Offset += ReadSize;
1483        continue;
1484      }
1485
[5d57155]1486      size_t ElementSize = VH->Size;
1487      if (offsetof_safe(VH, ElementSize) < GH->VarsSize)
1488        ElementSize = VH->ElementSize;
1489
[00587dc]1490      VarFound = true;
1491      bool IsFloat = (bool) (VH->Flags & FloatValue),
1492           IsSigned = (bool) (VH->Flags & SignedValue);
1493      if (VH->Size != Vars[i].Size) {
1494        stringstream ss;
1495        ss << "Size mismatch for variable " << Vars[i].Name <<
1496              " in: " << OpenFileName << ": current: " << Vars[i].Size <<
1497              ", file: " << VH->Size;
1498        throw runtime_error(ss.str());
[5d57155]1499      } else if (ElementSize != Vars[i].ElementSize) {
1500        stringstream ss;
1501        ss << "Element size mismatch for variable " << Vars[i].Name <<
1502              " in: " << OpenFileName << ": current: " << Vars[i].ElementSize <<
1503              ", file: " << ElementSize;
1504        throw runtime_error(ss.str());
[00587dc]1505      } else if (IsFloat != Vars[i].IsFloat) {
1506        string Float("float"), Int("integer");
1507        stringstream ss;
1508        ss << "Type mismatch for variable " << Vars[i].Name <<
1509              " in: " << OpenFileName << ": current: " <<
1510              (Vars[i].IsFloat ? Float : Int) <<
1511              ", file: " << (IsFloat ? Float : Int);
1512        throw runtime_error(ss.str());
1513      } else if (IsSigned != Vars[i].IsSigned) {
1514        string Signed("signed"), Uns("unsigned");
1515        stringstream ss;
1516        ss << "Type mismatch for variable " << Vars[i].Name <<
1517              " in: " << OpenFileName << ": current: " <<
1518              (Vars[i].IsSigned ? Signed : Uns) <<
1519              ", file: " << (IsSigned ? Signed : Uns);
1520        throw runtime_error(ss.str());
1521      }
1522
[8f0a211]1523      size_t VarOffset = RowOffset*Vars[i].Size;
1524      void *VarData = ((char *) Vars[i].Data) + VarOffset;
1525
[00587dc]1526      vector<unsigned char> LData;
[eeacdad]1527      bool HasSZ = false;
[8f0a211]1528      void *Data = VarData;
[00587dc]1529      bool HasExtraSpace = Vars[i].HasExtraSpace;
[a4fee13]1530      if (offsetof_safe(GH, BlocksStart) < GH->GlobalHeaderSize &&
[00587dc]1531          GH->BlocksSize > 0) {
[a4fee13]1532        BlockHeader<IsBigEndian> *BH = (BlockHeader<IsBigEndian> *)
[00587dc]1533          &FH.getHeaderCache()[GH->BlocksStart +
1534                               (RankIndex*GH->NVars + j)*GH->BlocksSize];
1535        ReadSize = BH->Size + CRCSize;
1536        Offset = BH->Start;
1537
[eeacdad]1538        int FilterIdx = 0;
1539
1540        if (strncmp(BH->Filters[FilterIdx], LossyCompressName, FilterNameSize) == 0) {
1541          ++FilterIdx;
1542          HasSZ = true;
1543        }
1544
1545        if (strncmp(BH->Filters[FilterIdx], CompressName, FilterNameSize) == 0) {
[00587dc]1546          LData.resize(ReadSize);
1547          Data = &LData[0];
1548          HasExtraSpace = true;
[eeacdad]1549        } else if (BH->Filters[FilterIdx][0] != '\0') {
[00587dc]1550          stringstream ss;
1551          ss << "Unknown filter \"" << BH->Filters[0] << "\" on variable " << Vars[i].Name;
1552          throw runtime_error(ss.str());
1553        }
1554      }
1555
1556      assert(HasExtraSpace && "Extra space required for reading");
1557
1558      char CRCSave[CRCSize];
1559      char *CRCLoc = ((char *) Data) + ReadSize - CRCSize;
1560      if (HasExtraSpace)
1561        std::copy(CRCLoc, CRCLoc + CRCSize, CRCSave);
1562
1563      int Retry = 0;
1564      {
1565        int RetryCount = 300;
1566        const char *EnvStr = getenv("GENERICIO_RETRY_COUNT");
1567        if (EnvStr)
1568          RetryCount = atoi(EnvStr);
1569
1570        int RetrySleep = 100; // ms
1571        EnvStr = getenv("GENERICIO_RETRY_SLEEP");
1572        if (EnvStr)
1573          RetrySleep = atoi(EnvStr);
1574
1575        for (; Retry < RetryCount; ++Retry) {
1576          try {
1577            FH.get()->read(Data, ReadSize, Offset, Vars[i].Name);
1578            break;
1579          } catch (...) { }
1580
1581          usleep(1000*RetrySleep);
1582        }
1583
1584        if (Retry == RetryCount) {
1585          ++NErrs[0];
1586          break;
1587        } else if (Retry > 0) {
1588          EnvStr = getenv("GENERICIO_VERBOSE");
1589          if (EnvStr) {
1590            int Mod = atoi(EnvStr);
1591            if (Mod > 0) {
1592              int Rank;
1593#ifndef GENERICIO_NO_MPI
1594              MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1595#else
1596              Rank = 0;
1597#endif
1598
1599              std::cerr << "Rank " << Rank << ": " << Retry <<
1600                           " I/O retries were necessary for reading " <<
1601                           Vars[i].Name << " from: " << OpenFileName << "\n";
1602
1603              std::cerr.flush();
1604            }
1605          }
1606        }
1607      }
1608
1609      TotalReadSize += ReadSize;
1610
1611      uint64_t CRC = crc64_omp(Data, ReadSize);
1612      if (CRC != (uint64_t) -1) {
1613        ++NErrs[1];
1614
1615        int Rank;
1616#ifndef GENERICIO_NO_MPI
1617        MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1618#else
1619        Rank = 0;
1620#endif
1621
1622        // All ranks will do this and have a good time!
1623        string dn = "gio_crc_errors";
1624        mkdir(dn.c_str(), 0777);
1625
1626        srand(time(0));
1627        int DumpNum = rand();
1628        stringstream ssd;
1629        ssd << dn << "/gio_crc_error_dump." << Rank << "." << DumpNum << ".bin";
1630
1631        stringstream ss;
1632        ss << dn << "/gio_crc_error_log." << Rank << ".txt";
1633
1634        ofstream ofs(ss.str().c_str(), ofstream::out | ofstream::app);
1635        ofs << "On-Disk CRC Error Report:\n";
1636        ofs << "Variable: " << Vars[i].Name << "\n";
1637        ofs << "File: " << OpenFileName << "\n";
1638        ofs << "I/O Retries: " << Retry << "\n";
1639        ofs << "Size: " << ReadSize << " bytes\n";
1640        ofs << "Offset: " << Offset << " bytes\n";
1641        ofs << "CRC: " << CRC << " (expected is -1)\n";
1642        ofs << "Dump file: " << ssd.str() << "\n";
1643        ofs << "\n";
1644        ofs.close();
1645
1646        ofstream dofs(ssd.str().c_str(), ofstream::out);
1647        dofs.write((const char *) Data, ReadSize);
1648        dofs.close();
[14e73bb]1649
1650        uint64_t RawCRC = crc64_omp(Data, ReadSize - CRCSize);
1651        unsigned char *UData = (unsigned char *) Data;
1652        crc64_invert(RawCRC, &UData[ReadSize - CRCSize]);
1653        uint64_t NewCRC = crc64_omp(Data, ReadSize);
1654        std::cerr << "Recalulated CRC: " << NewCRC << ((NewCRC == -1) ? "ok" : "bad") << "\n";
[00587dc]1655        break;
1656      }
1657
1658      if (HasExtraSpace)
1659        std::copy(CRCSave, CRCSave + CRCSize, CRCLoc);
1660
1661      if (LData.size()) {
[a4fee13]1662        CompressHeader<IsBigEndian> *CH = (CompressHeader<IsBigEndian>*) &LData[0];
[00587dc]1663
1664#ifdef _OPENMP
1665#pragma omp master
1666  {
1667#endif
1668
1669       if (!blosc_initialized) {
1670         blosc_init();
1671         blosc_initialized = true;
1672       }
1673
[eeacdad]1674       if (!sz_initialized) {
1675         SZ_Init(NULL);
1676         sz_initialized = true;
1677       }
1678
[00587dc]1679#ifdef _OPENMP
1680       blosc_set_nthreads(omp_get_max_threads());
1681  }
1682#endif
1683
[eeacdad]1684        void *OrigData = VarData;
1685        size_t OrigDataSize = Vars[i].Size*RH->NElems;
1686
1687        if (HasSZ) {
1688          size_t CNBytes, CCBytes, CBlockSize;
1689          blosc_cbuffer_sizes(&LData[0] + sizeof(CompressHeader<IsBigEndian>),
1690                              &CNBytes, &CCBytes, &CBlockSize);
1691
1692          OrigData = malloc(CNBytes);
1693          OrigDataSize = CNBytes;
1694        }
1695
[a4fee13]1696        blosc_decompress(&LData[0] + sizeof(CompressHeader<IsBigEndian>),
[eeacdad]1697                         OrigData, OrigDataSize);
[00587dc]1698
[eeacdad]1699        if (CH->OrigCRC != crc64_omp(OrigData, OrigDataSize)) {
[00587dc]1700          ++NErrs[2];
1701          break;
1702        }
[eeacdad]1703
1704        if (HasSZ) {
1705          int SZDT = GetSZDT(Vars[i]);
1706          size_t LDSz = SZ_decompress_args(SZDT, (unsigned char *)OrigData, OrigDataSize,
1707                                           VarData, 0, 0, 0, 0, RH->NElems);
1708          free(OrigData);
1709
[abca157]1710          if (LDSz != RH->NElems)
[eeacdad]1711            throw runtime_error("Variable " + Vars[i].Name +
1712                                ": SZ decompression yielded the wrong amount of data");
1713        }
[00587dc]1714      }
1715
[a4fee13]1716      // Byte swap the data if necessary.
[eeacdad]1717      if (IsBigEndian != isBigEndian() && !HasSZ)
[5d57155]1718        for (size_t j = 0;
1719             j < RH->NElems*(Vars[i].Size/Vars[i].ElementSize); ++j) {
1720          char *Offset = ((char *) VarData) + j*Vars[i].ElementSize;
1721          bswap(Offset, Vars[i].ElementSize);
[a4fee13]1722        }
1723
[00587dc]1724      break;
1725    }
1726
1727    if (!VarFound)
1728      throw runtime_error("Variable " + Vars[i].Name +
1729                          " not found in: " + OpenFileName);
1730
1731    // This is for debugging.
1732    if (NErrs[0] || NErrs[1] || NErrs[2]) {
1733      const char *EnvStr = getenv("GENERICIO_VERBOSE");
1734      if (EnvStr) {
1735        int Mod = atoi(EnvStr);
1736        if (Mod > 0) {
1737          int Rank;
1738#ifndef GENERICIO_NO_MPI
1739          MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1740#else
1741          Rank = 0;
1742#endif
1743
1744          std::cerr << "Rank " << Rank << ": " << NErrs[0] << " I/O error(s), " <<
1745          NErrs[1] << " CRC error(s) and " << NErrs[2] <<
1746          " decompression CRC error(s) reading: " << Vars[i].Name <<
1747          " from: " << OpenFileName << "\n";
1748
1749          std::cerr.flush();
1750        }
1751      }
1752    }
1753
1754    if (NErrs[0] || NErrs[1] || NErrs[2])
1755      break;
1756  }
1757}
1758
1759void GenericIO::getVariableInfo(vector<VariableInfo> &VI) {
[a4fee13]1760  if (FH.isBigEndian())
1761    getVariableInfo<true>(VI);
1762  else
1763    getVariableInfo<false>(VI);
1764}
1765
1766template <bool IsBigEndian>
1767void GenericIO::getVariableInfo(vector<VariableInfo> &VI) {
[00587dc]1768  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1769
[a4fee13]1770  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
[00587dc]1771  for (uint64_t j = 0; j < GH->NVars; ++j) {
[a4fee13]1772    VariableHeader<IsBigEndian> *VH = (VariableHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->VarsStart +
[00587dc]1773                                                         j*GH->VarsSize];
1774
1775    string VName(VH->Name, VH->Name + NameSize);
1776    size_t VNameNull = VName.find('\0');
1777    if (VNameNull < NameSize)
1778      VName.resize(VNameNull);
1779
[5d57155]1780    size_t ElementSize = VH->Size;
1781    if (offsetof_safe(VH, ElementSize) < GH->VarsSize)
1782      ElementSize = VH->ElementSize;
1783
[00587dc]1784    bool IsFloat = (bool) (VH->Flags & FloatValue),
1785         IsSigned = (bool) (VH->Flags & SignedValue),
1786         IsPhysCoordX = (bool) (VH->Flags & ValueIsPhysCoordX),
1787         IsPhysCoordY = (bool) (VH->Flags & ValueIsPhysCoordY),
1788         IsPhysCoordZ = (bool) (VH->Flags & ValueIsPhysCoordZ),
1789         MaybePhysGhost = (bool) (VH->Flags & ValueMaybePhysGhost);
1790    VI.push_back(VariableInfo(VName, (size_t) VH->Size, IsFloat, IsSigned,
1791                              IsPhysCoordX, IsPhysCoordY, IsPhysCoordZ,
[5d57155]1792                              MaybePhysGhost, ElementSize));
[00587dc]1793  }
1794}
1795
1796void GenericIO::setNaturalDefaultPartition() {
1797#ifdef __bgq__
[14e73bb]1798  DefaultPartition = MPIX_IO_link_id();
[00587dc]1799#else
1800#ifndef GENERICIO_NO_MPI
1801  bool UseName = true;
1802  const char *EnvStr = getenv("GENERICIO_PARTITIONS_USE_NAME");
1803  if (EnvStr) {
1804    int Mod = atoi(EnvStr);
1805    UseName = (Mod != 0);
1806  }
1807
1808  if (UseName) {
1809    // This is a heuristic to generate ~256 partitions based on the
1810    // names of the nodes.
1811    char Name[MPI_MAX_PROCESSOR_NAME];
1812    int Len = 0;
1813
1814    MPI_Get_processor_name(Name, &Len);
1815    unsigned char color = 0;
1816    for (int i = 0; i < Len; ++i)
1817      color += (unsigned char) Name[i];
1818
1819    DefaultPartition = color;
1820  }
1821
1822  // This is for debugging.
1823  EnvStr = getenv("GENERICIO_RANK_PARTITIONS");
1824  if (EnvStr) {
1825    int Mod = atoi(EnvStr);
1826    if (Mod > 0) {
1827      int Rank;
1828      MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1829      DefaultPartition += Rank % Mod;
1830    }
1831  }
1832#endif
1833#endif
1834}
1835
1836} /* END namespace cosmotk */
Note: See TracBrowser for help on using the repository browser.