source: GenericIO.cxx @ 6461f57

Revision 6461f57, 52.2 KB checked in by Hal Finkel <hfinkel@…>, 6 years ago (diff)

start working on sz intrgration

  • 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
370#ifndef GENERICIO_NO_MPI
371void GenericIO::write() {
372  if (isBigEndian())
373    write<true>();
374  else
375    write<false>();
376}
377
378// Note: writing errors are not currently recoverable (one rank may fail
379// while the others don't).
380template <bool IsBigEndian>
381void GenericIO::write() {
382  const char *Magic = IsBigEndian ? MagicBE : MagicLE;
383
384  uint64_t FileSize = 0;
385
386  int NRanks, Rank;
387  MPI_Comm_rank(Comm, &Rank);
388  MPI_Comm_size(Comm, &NRanks);
389
390#ifdef __bgq__
391  MPI_Barrier(Comm);
392#endif
393  MPI_Comm_split(Comm, Partition, Rank, &SplitComm);
394
395  int SplitNRanks, SplitRank;
396  MPI_Comm_rank(SplitComm, &SplitRank);
397  MPI_Comm_size(SplitComm, &SplitNRanks);
398
399  string LocalFileName;
400  if (SplitNRanks != NRanks) {
401    if (Rank == 0) {
402      // In split mode, the specified file becomes the rank map, and the real
403      // data is partitioned.
404
405      vector<int> MapRank, MapPartition;
406      MapRank.resize(NRanks);
407      for (int i = 0; i < NRanks; ++i) MapRank[i] = i;
408
409      MapPartition.resize(NRanks);
410      MPI_Gather(&Partition, 1, MPI_INT, &MapPartition[0], 1, MPI_INT, 0, Comm);
411
412      GenericIO GIO(MPI_COMM_SELF, FileName, FileIOType);
413      GIO.setNumElems(NRanks);
414      GIO.addVariable("$rank", MapRank); /* this is for use by humans; the reading
415                                            code assumes that the partitions are in
416                                            rank order */
417      GIO.addVariable("$partition", MapPartition);
418
419      vector<int> CX, CY, CZ;
420      int TopoStatus;
421      MPI_Topo_test(Comm, &TopoStatus);
422      if (TopoStatus == MPI_CART) {
423        CX.resize(NRanks);
424        CY.resize(NRanks);
425        CZ.resize(NRanks);
426
427        for (int i = 0; i < NRanks; ++i) {
428          int C[3];
429          MPI_Cart_coords(Comm, i, 3, C);
430
431          CX[i] = C[0];
432          CY[i] = C[1];
433          CZ[i] = C[2];
434        }
435
436        GIO.addVariable("$x", CX);
437        GIO.addVariable("$y", CY);
438        GIO.addVariable("$z", CZ);
439      }
440
441      GIO.write();
442    } else {
443      MPI_Gather(&Partition, 1, MPI_INT, 0, 0, MPI_INT, 0, Comm);
444    }
445
446    stringstream ss;
447    ss << FileName << "#" << Partition;
448    LocalFileName = ss.str();
449  } else {
450    LocalFileName = FileName;
451  }
452
453  RankHeader<IsBigEndian> RHLocal;
454  int Dims[3], Periods[3], Coords[3];
455
456  int TopoStatus;
457  MPI_Topo_test(Comm, &TopoStatus);
458  if (TopoStatus == MPI_CART) {
459    MPI_Cart_get(Comm, 3, Dims, Periods, Coords);
460  } else {
461    Dims[0] = NRanks;
462    std::fill(Dims + 1, Dims + 3, 1);
463    std::fill(Periods, Periods + 3, 0);
464    Coords[0] = Rank;
465    std::fill(Coords + 1, Coords + 3, 0);
466  }
467
468  std::copy(Coords, Coords + 3, RHLocal.Coords);
469  RHLocal.NElems = NElems;
470  RHLocal.Start = 0;
471  RHLocal.GlobalRank = Rank;
472
473  bool ShouldCompress = DefaultShouldCompress;
474  const char *EnvStr = getenv("GENERICIO_COMPRESS");
475  if (EnvStr) {
476    int Mod = atoi(EnvStr);
477    ShouldCompress = (Mod > 0);
478  }
479
480  bool NeedsBlockHeaders = ShouldCompress;
481  EnvStr = getenv("GENERICIO_FORCE_BLOCKS");
482  if (!NeedsBlockHeaders && EnvStr) {
483    int Mod = atoi(EnvStr);
484    NeedsBlockHeaders = (Mod > 0);
485  }
486
487  vector<BlockHeader<IsBigEndian> > LocalBlockHeaders;
488  vector<void *> LocalData;
489  vector<bool> LocalHasExtraSpace;
490  vector<vector<unsigned char> > LocalCData;
491  if (NeedsBlockHeaders) {
492    LocalBlockHeaders.resize(Vars.size());
493    LocalData.resize(Vars.size());
494    LocalHasExtraSpace.resize(Vars.size());
495    if (ShouldCompress)
496      LocalCData.resize(Vars.size());
497
498    for (size_t i = 0; i < Vars.size(); ++i) {
499      // Filters null by default, leave null starting address (needs to be
500      // calculated by the header-writing rank).
501      memset(&LocalBlockHeaders[i], 0, sizeof(BlockHeader<IsBigEndian>));
502      if (ShouldCompress) {
503        LocalCData[i].resize(sizeof(CompressHeader<IsBigEndian>));
504
505        CompressHeader<IsBigEndian> *CH = (CompressHeader<IsBigEndian>*) &LocalCData[i][0];
506        CH->OrigCRC = crc64_omp(Vars[i].Data, Vars[i].Size*NElems);
507
508#ifdef _OPENMP
509#pragma omp master
510  {
511#endif
512
513       if (!blosc_initialized) {
514         blosc_init();
515         blosc_initialized = true;
516       }
517
518#ifdef _OPENMP
519       blosc_set_nthreads(omp_get_max_threads());
520  }
521#endif
522
523        LocalCData[i].resize(LocalCData[i].size() + NElems*Vars[i].Size);
524        if (blosc_compress(9, 1, Vars[i].Size, NElems*Vars[i].Size, Vars[i].Data,
525                           &LocalCData[i][0] + sizeof(CompressHeader<IsBigEndian>),
526                           NElems*Vars[i].Size) <= 0)
527          goto nocomp;
528
529        strncpy(LocalBlockHeaders[i].Filters[0], CompressName, FilterNameSize);
530        size_t CNBytes, CCBytes, CBlockSize;
531        blosc_cbuffer_sizes(&LocalCData[i][0] + sizeof(CompressHeader<IsBigEndian>),
532                            &CNBytes, &CCBytes, &CBlockSize);
533        LocalCData[i].resize(CCBytes + sizeof(CompressHeader<IsBigEndian>));
534
535        LocalBlockHeaders[i].Size = LocalCData[i].size();
536        LocalCData[i].resize(LocalCData[i].size() + CRCSize);
537        LocalData[i] = &LocalCData[i][0];
538        LocalHasExtraSpace[i] = true;
539      } else {
540nocomp:
541        LocalBlockHeaders[i].Size = NElems*Vars[i].Size;
542        LocalData[i] = Vars[i].Data;
543        LocalHasExtraSpace[i] = Vars[i].HasExtraSpace;
544      }
545    }
546  }
547
548  double StartTime = MPI_Wtime();
549
550  if (SplitRank == 0) {
551    uint64_t HeaderSize = sizeof(GlobalHeader<IsBigEndian>) + Vars.size()*sizeof(VariableHeader<IsBigEndian>) +
552                          SplitNRanks*sizeof(RankHeader<IsBigEndian>) + CRCSize;
553    if (NeedsBlockHeaders)
554      HeaderSize += SplitNRanks*Vars.size()*sizeof(BlockHeader<IsBigEndian>);
555
556    vector<char> Header(HeaderSize, 0);
557    GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &Header[0];
558    std::copy(Magic, Magic + MagicSize, GH->Magic);
559    GH->HeaderSize = HeaderSize - CRCSize;
560    GH->NElems = NElems; // This will be updated later
561    std::copy(Dims, Dims + 3, GH->Dims);
562    GH->NVars = Vars.size();
563    GH->VarsSize = sizeof(VariableHeader<IsBigEndian>);
564    GH->VarsStart = sizeof(GlobalHeader<IsBigEndian>);
565    GH->NRanks = SplitNRanks;
566    GH->RanksSize = sizeof(RankHeader<IsBigEndian>);
567    GH->RanksStart = GH->VarsStart + Vars.size()*sizeof(VariableHeader<IsBigEndian>);
568    GH->GlobalHeaderSize = sizeof(GlobalHeader<IsBigEndian>);
569    std::copy(PhysOrigin, PhysOrigin + 3, GH->PhysOrigin);
570    std::copy(PhysScale,  PhysScale  + 3, GH->PhysScale);
571    if (!NeedsBlockHeaders) {
572      GH->BlocksSize = GH->BlocksStart = 0;
573    } else {
574      GH->BlocksSize = sizeof(BlockHeader<IsBigEndian>);
575      GH->BlocksStart = GH->RanksStart + SplitNRanks*sizeof(RankHeader<IsBigEndian>);
576    }
577
578    uint64_t RecordSize = 0;
579    VariableHeader<IsBigEndian> *VH = (VariableHeader<IsBigEndian> *) &Header[GH->VarsStart];
580    for (size_t i = 0; i < Vars.size(); ++i, ++VH) {
581      string VName(Vars[i].Name);
582      VName.resize(NameSize);
583
584      std::copy(VName.begin(), VName.end(), VH->Name);
585      uint64_t VFlags = 0;
586      if (Vars[i].IsFloat)  VFlags |= FloatValue;
587      if (Vars[i].IsSigned) VFlags |= SignedValue;
588      if (Vars[i].IsPhysCoordX) VFlags |= ValueIsPhysCoordX;
589      if (Vars[i].IsPhysCoordY) VFlags |= ValueIsPhysCoordY;
590      if (Vars[i].IsPhysCoordZ) VFlags |= ValueIsPhysCoordZ;
591      if (Vars[i].MaybePhysGhost) VFlags |= ValueMaybePhysGhost;
592      VH->Flags = VFlags;
593      RecordSize += VH->Size = Vars[i].Size;
594      VH->ElementSize = Vars[i].ElementSize;
595    }
596
597    MPI_Gather(&RHLocal, sizeof(RHLocal), MPI_BYTE,
598               &Header[GH->RanksStart], sizeof(RHLocal),
599               MPI_BYTE, 0, SplitComm);
600
601    if (NeedsBlockHeaders) {
602      MPI_Gather(&LocalBlockHeaders[0],
603                 Vars.size()*sizeof(BlockHeader<IsBigEndian>), MPI_BYTE,
604                 &Header[GH->BlocksStart],
605                 Vars.size()*sizeof(BlockHeader<IsBigEndian>), MPI_BYTE,
606                 0, SplitComm);
607
608      BlockHeader<IsBigEndian> *BH = (BlockHeader<IsBigEndian> *) &Header[GH->BlocksStart];
609      for (int i = 0; i < SplitNRanks; ++i)
610      for (size_t j = 0; j < Vars.size(); ++j, ++BH) {
611        if (i == 0 && j == 0)
612          BH->Start = HeaderSize;
613        else
614          BH->Start = BH[-1].Start + BH[-1].Size + CRCSize;
615      }
616
617      RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &Header[GH->RanksStart];
618      RH->Start = HeaderSize; ++RH;
619      for (int i = 1; i < SplitNRanks; ++i, ++RH) {
620        RH->Start =
621          ((BlockHeader<IsBigEndian> *) &Header[GH->BlocksStart])[i*Vars.size()].Start;
622        GH->NElems += RH->NElems;
623      }
624
625      // Compute the total file size.
626      uint64_t LastData = BH[-1].Size + CRCSize;
627      FileSize = BH[-1].Start + LastData;
628    } else {
629      RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &Header[GH->RanksStart];
630      RH->Start = HeaderSize; ++RH;
631      for (int i = 1; i < SplitNRanks; ++i, ++RH) {
632        uint64_t PrevNElems = RH[-1].NElems;
633        uint64_t PrevData = PrevNElems*RecordSize + CRCSize*Vars.size();
634        RH->Start = RH[-1].Start + PrevData;
635        GH->NElems += RH->NElems;
636      }
637
638      // Compute the total file size.
639      uint64_t LastNElems = RH[-1].NElems;
640      uint64_t LastData = LastNElems*RecordSize + CRCSize*Vars.size();
641      FileSize = RH[-1].Start + LastData;
642    }
643
644    // Now that the starting offset has been computed, send it back to each rank.
645    MPI_Scatter(&Header[GH->RanksStart], sizeof(RHLocal),
646                MPI_BYTE, &RHLocal, sizeof(RHLocal),
647                MPI_BYTE, 0, SplitComm);
648
649    if (NeedsBlockHeaders)
650      MPI_Scatter(&Header[GH->BlocksStart],
651                  sizeof(BlockHeader<IsBigEndian>)*Vars.size(), MPI_BYTE,
652                  &LocalBlockHeaders[0],
653                  sizeof(BlockHeader<IsBigEndian>)*Vars.size(), MPI_BYTE,
654                  0, SplitComm);
655
656    uint64_t HeaderCRC = crc64_omp(&Header[0], HeaderSize - CRCSize);
657    crc64_invert(HeaderCRC, &Header[HeaderSize - CRCSize]);
658
659    if (FileIOType == FileIOMPI)
660      FH.get() = new GenericFileIO_MPI(MPI_COMM_SELF);
661    else if (FileIOType == FileIOMPICollective)
662      FH.get() = new GenericFileIO_MPICollective(MPI_COMM_SELF);
663    else
664      FH.get() = new GenericFileIO_POSIX();
665
666    FH.get()->open(LocalFileName);
667    FH.get()->setSize(FileSize);
668    FH.get()->write(&Header[0], HeaderSize, 0, "header");
669
670    close();
671  } else {
672    MPI_Gather(&RHLocal, sizeof(RHLocal), MPI_BYTE, 0, 0, MPI_BYTE, 0, SplitComm);
673    if (NeedsBlockHeaders)
674      MPI_Gather(&LocalBlockHeaders[0], Vars.size()*sizeof(BlockHeader<IsBigEndian>),
675                 MPI_BYTE, 0, 0, MPI_BYTE, 0, SplitComm);
676    MPI_Scatter(0, 0, MPI_BYTE, &RHLocal, sizeof(RHLocal), MPI_BYTE, 0, SplitComm);
677    if (NeedsBlockHeaders)
678      MPI_Scatter(0, 0, MPI_BYTE, &LocalBlockHeaders[0], sizeof(BlockHeader<IsBigEndian>)*Vars.size(),
679                  MPI_BYTE, 0, SplitComm);
680  }
681
682  MPI_Barrier(SplitComm);
683
684  if (FileIOType == FileIOMPI)
685    FH.get() = new GenericFileIO_MPI(SplitComm);
686  else if (FileIOType == FileIOMPICollective)
687    FH.get() = new GenericFileIO_MPICollective(SplitComm);
688  else
689    FH.get() = new GenericFileIO_POSIX();
690
691  FH.get()->open(LocalFileName);
692
693  uint64_t Offset = RHLocal.Start;
694  for (size_t i = 0; i < Vars.size(); ++i) {
695    uint64_t WriteSize = NeedsBlockHeaders ?
696                         LocalBlockHeaders[i].Size : NElems*Vars[i].Size;
697    void *Data = NeedsBlockHeaders ? LocalData[i] : Vars[i].Data;
698    uint64_t CRC = crc64_omp(Data, WriteSize);
699    bool HasExtraSpace = NeedsBlockHeaders ?
700                         LocalHasExtraSpace[i] : Vars[i].HasExtraSpace;
701    char *CRCLoc = HasExtraSpace ?  ((char *) Data) + WriteSize : (char *) &CRC;
702
703    if (NeedsBlockHeaders)
704      Offset = LocalBlockHeaders[i].Start;
705
706    // When using extra space for the CRC write, preserve the original contents.
707    char CRCSave[CRCSize];
708    if (HasExtraSpace)
709      std::copy(CRCLoc, CRCLoc + CRCSize, CRCSave);
710
711    crc64_invert(CRC, CRCLoc);
712
713    if (HasExtraSpace) {
714      FH.get()->write(Data, WriteSize + CRCSize, Offset, Vars[i].Name + " with CRC");
715    } else {
716      FH.get()->write(Data, WriteSize, Offset, Vars[i].Name);
717      FH.get()->write(CRCLoc, CRCSize, Offset + WriteSize, Vars[i].Name + " CRC");
718    }
719
720    if (HasExtraSpace)
721       std::copy(CRCSave, CRCSave + CRCSize, CRCLoc);
722
723    Offset += WriteSize + CRCSize;
724  }
725
726  close();
727  MPI_Barrier(Comm);
728
729  double EndTime = MPI_Wtime();
730  double TotalTime = EndTime - StartTime;
731  double MaxTotalTime;
732  MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
733
734  if (SplitNRanks != NRanks) {
735    uint64_t ContribFileSize = (SplitRank == 0) ? FileSize : 0;
736    MPI_Reduce(&ContribFileSize, &FileSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
737  }
738
739  if (Rank == 0) {
740    double Rate = ((double) FileSize) / MaxTotalTime / (1024.*1024.);
741    std::cout << "Wrote " << Vars.size() << " variables to " << FileName <<
742                  " (" << FileSize << " bytes) in " << MaxTotalTime << "s: " <<
743                  Rate << " MB/s" << std::endl;
744  }
745
746  MPI_Comm_free(&SplitComm);
747  SplitComm = MPI_COMM_NULL;
748}
749#endif // GENERICIO_NO_MPI
750
751template <bool IsBigEndian>
752void GenericIO::readHeaderLeader(void *GHPtr, MismatchBehavior MB, int NRanks,
753                                 int Rank, int SplitNRanks,
754                                 string &LocalFileName, uint64_t &HeaderSize,
755                                 vector<char> &Header) {
756  GlobalHeader<IsBigEndian> &GH = *(GlobalHeader<IsBigEndian> *) GHPtr;
757
758  if (MB == MismatchDisallowed) {
759    if (SplitNRanks != (int) GH.NRanks) {
760      stringstream ss;
761      ss << "Won't read " << LocalFileName << ": communicator-size mismatch: " <<
762            "current: " << SplitNRanks << ", file: " << GH.NRanks;
763      throw runtime_error(ss.str());
764    }
765
766#ifndef GENERICIO_NO_MPI
767    int TopoStatus;
768    MPI_Topo_test(Comm, &TopoStatus);
769    if (TopoStatus == MPI_CART) {
770      int Dims[3], Periods[3], Coords[3];
771      MPI_Cart_get(Comm, 3, Dims, Periods, Coords);
772
773      bool DimsMatch = true;
774      for (int i = 0; i < 3; ++i) {
775        if ((uint64_t) Dims[i] != GH.Dims[i]) {
776          DimsMatch = false;
777          break;
778        }
779      }
780
781      if (!DimsMatch) {
782        stringstream ss;
783        ss << "Won't read " << LocalFileName <<
784              ": communicator-decomposition mismatch: " <<
785              "current: " << Dims[0] << "x" << Dims[1] << "x" << Dims[2] <<
786              ", file: " << GH.Dims[0] << "x" << GH.Dims[1] << "x" <<
787              GH.Dims[2];
788        throw runtime_error(ss.str());
789      }
790    }
791#endif
792  } else if (MB == MismatchRedistribute && !Redistributing) {
793    Redistributing = true;
794
795    int NFileRanks = RankMap.empty() ? (int) GH.NRanks : (int) RankMap.size();
796    int NFileRanksPerRank = NFileRanks/NRanks;
797    int NRemFileRank = NFileRanks % NRanks;
798
799    if (!NFileRanksPerRank) {
800      // We have only the remainder, so the last NRemFileRank ranks get one
801      // file rank, and the others don't.
802      if (NRemFileRank && NRanks - Rank <= NRemFileRank)
803        SourceRanks.push_back(NRanks - (Rank + 1));
804    } else {
805      // Since NRemFileRank < NRanks, and we don't want to put any extra memory
806      // load on rank 0 (because rank 0's memory load is normally higher than
807      // the other ranks anyway), the last NRemFileRank will each take
808      // (NFileRanksPerRank+1) file ranks.
809
810      int FirstFileRank = 0, LastFileRank = NFileRanksPerRank - 1;
811      for (int i = 1; i <= Rank; ++i) {
812        FirstFileRank = LastFileRank + 1;
813        LastFileRank  = FirstFileRank + NFileRanksPerRank - 1;
814
815        if (NRemFileRank && NRanks - i <= NRemFileRank)
816          ++LastFileRank;
817      }
818
819      for (int i = FirstFileRank; i <= LastFileRank; ++i)
820        SourceRanks.push_back(i);
821    }
822  }
823
824  HeaderSize = GH.HeaderSize;
825  Header.resize(HeaderSize + CRCSize, 0xFE /* poison */);
826  FH.get()->read(&Header[0], HeaderSize + CRCSize, 0, "header");
827
828  uint64_t CRC = crc64_omp(&Header[0], HeaderSize + CRCSize);
829  if (CRC != (uint64_t) -1) {
830    throw runtime_error("Header CRC check failed: " + LocalFileName);
831  }
832}
833
834// Note: Errors from this function should be recoverable. This means that if
835// one rank throws an exception, then all ranks should.
836void GenericIO::openAndReadHeader(MismatchBehavior MB, int EffRank, bool CheckPartMap) {
837  int NRanks, Rank;
838#ifndef GENERICIO_NO_MPI
839  MPI_Comm_rank(Comm, &Rank);
840  MPI_Comm_size(Comm, &NRanks);
841#else
842  Rank = 0;
843  NRanks = 1;
844#endif
845
846  if (EffRank == -1)
847    EffRank = MB == MismatchRedistribute ? 0 : Rank;
848
849  if (RankMap.empty() && CheckPartMap) {
850    // First, check to see if the file is a rank map.
851    unsigned long RanksInMap = 0;
852    if (Rank == 0) {
853      try {
854#ifndef GENERICIO_NO_MPI
855        GenericIO GIO(MPI_COMM_SELF, FileName, FileIOType);
856#else
857        GenericIO GIO(FileName, FileIOType);
858#endif
859        GIO.openAndReadHeader(MismatchDisallowed, 0, false);
860        RanksInMap = GIO.readNumElems();
861
862        RankMap.resize(RanksInMap + GIO.requestedExtraSpace()/sizeof(int));
863        GIO.addVariable("$partition", RankMap, true);
864
865        GIO.readData(0, false);
866        RankMap.resize(RanksInMap);
867      } catch (...) {
868        RankMap.clear();
869        RanksInMap = 0;
870      }
871    }
872
873#ifndef GENERICIO_NO_MPI
874    MPI_Bcast(&RanksInMap, 1, MPI_UNSIGNED_LONG, 0, Comm);
875    if (RanksInMap > 0) {
876      RankMap.resize(RanksInMap);
877      MPI_Bcast(&RankMap[0], RanksInMap, MPI_INT, 0, Comm);
878    }
879#endif
880  }
881
882#ifndef GENERICIO_NO_MPI
883  if (SplitComm != MPI_COMM_NULL)
884    MPI_Comm_free(&SplitComm);
885#endif
886
887  string LocalFileName;
888  if (RankMap.empty()) {
889    LocalFileName = FileName;
890#ifndef GENERICIO_NO_MPI
891    MPI_Comm_dup(MB == MismatchRedistribute ? MPI_COMM_SELF : Comm, &SplitComm);
892#endif
893  } else {
894    stringstream ss;
895    ss << FileName << "#" << RankMap[EffRank];
896    LocalFileName = ss.str();
897#ifndef GENERICIO_NO_MPI
898    if (MB == MismatchRedistribute) {
899      MPI_Comm_dup(MPI_COMM_SELF, &SplitComm);
900    } else {
901#ifdef __bgq__
902      MPI_Barrier(Comm);
903#endif
904      MPI_Comm_split(Comm, RankMap[EffRank], Rank, &SplitComm);
905    }
906#endif
907  }
908
909  if (LocalFileName == OpenFileName)
910    return;
911  FH.close();
912
913  int SplitNRanks, SplitRank;
914#ifndef GENERICIO_NO_MPI
915  MPI_Comm_rank(SplitComm, &SplitRank);
916  MPI_Comm_size(SplitComm, &SplitNRanks);
917#else
918  SplitRank = 0;
919  SplitNRanks = 1;
920#endif
921
922  uint64_t HeaderSize;
923  vector<char> Header;
924
925  if (SplitRank == 0) {
926#ifndef GENERICIO_NO_MPI
927    if (FileIOType == FileIOMPI)
928      FH.get() = new GenericFileIO_MPI(MPI_COMM_SELF);
929    else if (FileIOType == FileIOMPICollective)
930      FH.get() = new GenericFileIO_MPICollective(MPI_COMM_SELF);
931    else
932#endif
933      FH.get() = new GenericFileIO_POSIX();
934
935#ifndef GENERICIO_NO_MPI
936    char True = 1, False = 0;
937#endif
938
939    try {
940      FH.get()->open(LocalFileName, true);
941
942      GlobalHeader<false> GH; // endianness does not matter yet...
943      FH.get()->read(&GH, sizeof(GlobalHeader<false>), 0, "global header");
944
945      if (string(GH.Magic, GH.Magic + MagicSize - 1) == MagicLE) {
946        readHeaderLeader<false>(&GH, MB, NRanks, Rank, SplitNRanks, LocalFileName,
947                                HeaderSize, Header);
948      } else if (string(GH.Magic, GH.Magic + MagicSize - 1) == MagicBE) {
949        readHeaderLeader<true>(&GH, MB, NRanks, Rank, SplitNRanks, LocalFileName,
950                               HeaderSize, Header);
951      } else {
952        string Error = "invalid file-type identifier";
953        throw runtime_error("Won't read " + LocalFileName + ": " + Error);
954      }
955
956#ifndef GENERICIO_NO_MPI
957      close();
958      MPI_Bcast(&True, 1, MPI_BYTE, 0, SplitComm);
959#endif
960    } catch (...) {
961#ifndef GENERICIO_NO_MPI
962      MPI_Bcast(&False, 1, MPI_BYTE, 0, SplitComm);
963#endif
964      close();
965      throw;
966    }
967  } else {
968#ifndef GENERICIO_NO_MPI
969    char Okay;
970    MPI_Bcast(&Okay, 1, MPI_BYTE, 0, SplitComm);
971    if (!Okay)
972      throw runtime_error("Failure broadcast from rank 0");
973#endif
974  }
975
976#ifndef GENERICIO_NO_MPI
977  MPI_Bcast(&HeaderSize, 1, MPI_UINT64_T, 0, SplitComm);
978#endif
979
980  Header.resize(HeaderSize, 0xFD /* poison */);
981#ifndef GENERICIO_NO_MPI
982  MPI_Bcast(&Header[0], HeaderSize, MPI_BYTE, 0, SplitComm);
983#endif
984
985  FH.getHeaderCache().clear();
986
987  GlobalHeader<false> *GH = (GlobalHeader<false> *) &Header[0];
988  FH.setIsBigEndian(string(GH->Magic, GH->Magic + MagicSize - 1) == MagicBE);
989
990  FH.getHeaderCache().swap(Header);
991  OpenFileName = LocalFileName;
992
993#ifndef GENERICIO_NO_MPI
994  if (!DisableCollErrChecking)
995    MPI_Barrier(Comm);
996
997  if (FileIOType == FileIOMPI)
998    FH.get() = new GenericFileIO_MPI(SplitComm);
999  else if (FileIOType == FileIOMPICollective)
1000    FH.get() = new GenericFileIO_MPICollective(SplitComm);
1001  else
1002    FH.get() = new GenericFileIO_POSIX();
1003
1004  int OpenErr = 0, TotOpenErr;
1005  try {
1006    FH.get()->open(LocalFileName, true);
1007    MPI_Allreduce(&OpenErr, &TotOpenErr, 1, MPI_INT, MPI_SUM,
1008                  DisableCollErrChecking ? MPI_COMM_SELF : Comm);
1009  } catch (...) {
1010    OpenErr = 1;
1011    MPI_Allreduce(&OpenErr, &TotOpenErr, 1, MPI_INT, MPI_SUM,
1012                  DisableCollErrChecking ? MPI_COMM_SELF : Comm);
1013    throw;
1014  }
1015
1016  if (TotOpenErr > 0) {
1017    stringstream ss;
1018    ss << TotOpenErr << " ranks failed to open file: " << LocalFileName;
1019    throw runtime_error(ss.str());
1020  }
1021#endif
1022}
1023
1024int GenericIO::readNRanks() {
1025  if (FH.isBigEndian())
1026    return readNRanks<true>();
1027  return readNRanks<false>();
1028}
1029
1030template <bool IsBigEndian>
1031int GenericIO::readNRanks() {
1032  if (RankMap.size())
1033    return RankMap.size();
1034
1035  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1036  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1037  return (int) GH->NRanks;
1038}
1039
1040void GenericIO::readDims(int Dims[3]) {
1041  if (FH.isBigEndian())
1042    readDims<true>(Dims);
1043  else
1044    readDims<false>(Dims);
1045}
1046
1047template <bool IsBigEndian>
1048void GenericIO::readDims(int Dims[3]) {
1049  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1050  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1051  std::copy(GH->Dims, GH->Dims + 3, Dims);
1052}
1053
1054uint64_t GenericIO::readTotalNumElems() {
1055  if (FH.isBigEndian())
1056    return readTotalNumElems<true>();
1057  return readTotalNumElems<false>();
1058}
1059
1060template <bool IsBigEndian>
1061uint64_t GenericIO::readTotalNumElems() {
1062  if (RankMap.size())
1063    return (uint64_t) -1;
1064
1065  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1066  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1067  return GH->NElems;
1068}
1069
1070void GenericIO::readPhysOrigin(double Origin[3]) {
1071  if (FH.isBigEndian())
1072    readPhysOrigin<true>(Origin);
1073  else
1074    readPhysOrigin<false>(Origin);
1075}
1076
1077// Define a "safe" version of offsetof (offsetof itself might not work for
1078// non-POD types, and at least xlC v12.1 will complain about this if you try).
1079#define offsetof_safe(S, F) (size_t(&(S)->F) - size_t(S))
1080
1081template <bool IsBigEndian>
1082void GenericIO::readPhysOrigin(double Origin[3]) {
1083  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1084  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1085  if (offsetof_safe(GH, PhysOrigin) >= GH->GlobalHeaderSize) {
1086    std::fill(Origin, Origin + 3, 0.0);
1087    return;
1088  }
1089
1090  std::copy(GH->PhysOrigin, GH->PhysOrigin + 3, Origin);
1091}
1092
1093void GenericIO::readPhysScale(double Scale[3]) {
1094  if (FH.isBigEndian())
1095    readPhysScale<true>(Scale);
1096  else
1097    readPhysScale<false>(Scale);
1098}
1099
1100template <bool IsBigEndian>
1101void GenericIO::readPhysScale(double Scale[3]) {
1102  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1103  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1104  if (offsetof_safe(GH, PhysScale) >= GH->GlobalHeaderSize) {
1105    std::fill(Scale, Scale + 3, 0.0);
1106    return;
1107  }
1108
1109  std::copy(GH->PhysScale, GH->PhysScale + 3, Scale);
1110}
1111
1112template <bool IsBigEndian>
1113static size_t getRankIndex(int EffRank, GlobalHeader<IsBigEndian> *GH,
1114                           vector<int> &RankMap, vector<char> &HeaderCache) {
1115  if (RankMap.empty())
1116    return EffRank;
1117
1118  for (size_t i = 0; i < GH->NRanks; ++i) {
1119    RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &HeaderCache[GH->RanksStart +
1120                                                 i*GH->RanksSize];
1121    if (offsetof_safe(RH, GlobalRank) >= GH->RanksSize)
1122      return EffRank;
1123
1124    if ((int) RH->GlobalRank == EffRank)
1125      return i;
1126  }
1127
1128  assert(false && "Index requested of an invalid rank");
1129  return (size_t) -1;
1130}
1131
1132int GenericIO::readGlobalRankNumber(int EffRank) {
1133  if (FH.isBigEndian())
1134    return readGlobalRankNumber<true>(EffRank);
1135  return readGlobalRankNumber<false>(EffRank);
1136}
1137
1138template <bool IsBigEndian>
1139int GenericIO::readGlobalRankNumber(int EffRank) {
1140  if (EffRank == -1) {
1141#ifndef GENERICIO_NO_MPI
1142    MPI_Comm_rank(Comm, &EffRank);
1143#else
1144    EffRank = 0;
1145#endif
1146  }
1147
1148  openAndReadHeader(MismatchAllowed, EffRank, false);
1149
1150  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1151
1152  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1153  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
1154
1155  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1156
1157  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
1158                                               RankIndex*GH->RanksSize];
1159
1160  if (offsetof_safe(RH, GlobalRank) >= GH->RanksSize)
1161    return EffRank;
1162
1163  return (int) RH->GlobalRank;
1164}
1165
1166void GenericIO::getSourceRanks(vector<int> &SR) {
1167  SR.clear();
1168
1169  if (Redistributing) {
1170    std::copy(SourceRanks.begin(), SourceRanks.end(), std::back_inserter(SR));
1171    return;
1172  }
1173
1174  int Rank;
1175#ifndef GENERICIO_NO_MPI
1176  MPI_Comm_rank(Comm, &Rank);
1177#else
1178  Rank = 0;
1179#endif
1180
1181  SR.push_back(Rank);
1182}
1183
1184size_t GenericIO::readNumElems(int EffRank) {
1185  if (EffRank == -1 && Redistributing) {
1186    DisableCollErrChecking = true;
1187
1188    size_t TotalSize = 0;
1189    for (int i = 0, ie = SourceRanks.size(); i != ie; ++i)
1190      TotalSize += readNumElems(SourceRanks[i]);
1191
1192    DisableCollErrChecking = false;
1193    return TotalSize;
1194  }
1195
1196  if (FH.isBigEndian())
1197    return readNumElems<true>(EffRank);
1198  return readNumElems<false>(EffRank);
1199}
1200
1201template <bool IsBigEndian>
1202size_t GenericIO::readNumElems(int EffRank) {
1203  if (EffRank == -1) {
1204#ifndef GENERICIO_NO_MPI
1205    MPI_Comm_rank(Comm, &EffRank);
1206#else
1207    EffRank = 0;
1208#endif
1209  }
1210
1211  openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed,
1212                    EffRank, false);
1213
1214  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1215
1216  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1217  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
1218
1219  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1220
1221  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
1222                                               RankIndex*GH->RanksSize];
1223  return (size_t) RH->NElems;
1224}
1225
1226void GenericIO::readCoords(int Coords[3], int EffRank) {
1227  if (EffRank == -1 && Redistributing) {
1228    std::fill(Coords, Coords + 3, 0);
1229    return;
1230  }
1231
1232  if (FH.isBigEndian())
1233    readCoords<true>(Coords, EffRank);
1234  else
1235    readCoords<false>(Coords, EffRank);
1236}
1237
1238template <bool IsBigEndian>
1239void GenericIO::readCoords(int Coords[3], int EffRank) {
1240  if (EffRank == -1) {
1241#ifndef GENERICIO_NO_MPI
1242    MPI_Comm_rank(Comm, &EffRank);
1243#else
1244    EffRank = 0;
1245#endif
1246  }
1247
1248  openAndReadHeader(MismatchAllowed, EffRank, false);
1249
1250  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1251
1252  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1253  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
1254
1255  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1256
1257  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
1258                                               RankIndex*GH->RanksSize];
1259
1260  std::copy(RH->Coords, RH->Coords + 3, Coords);
1261}
1262
1263void GenericIO::readData(int EffRank, bool PrintStats, bool CollStats) {
1264  int Rank;
1265#ifndef GENERICIO_NO_MPI
1266  MPI_Comm_rank(Comm, &Rank);
1267#else
1268  Rank = 0;
1269#endif
1270
1271  uint64_t TotalReadSize = 0;
1272#ifndef GENERICIO_NO_MPI
1273  double StartTime = MPI_Wtime();
1274#else
1275  double StartTime = double(clock())/CLOCKS_PER_SEC;
1276#endif
1277
1278  int NErrs[3] = { 0, 0, 0 };
1279
1280  if (EffRank == -1 && Redistributing) {
1281    DisableCollErrChecking = true;
1282
1283    size_t RowOffset = 0;
1284    for (int i = 0, ie = SourceRanks.size(); i != ie; ++i) {
1285      readData(SourceRanks[i], RowOffset, Rank, TotalReadSize, NErrs);
1286      RowOffset += readNumElems(SourceRanks[i]);
1287    }
1288
1289    DisableCollErrChecking = false;
1290  } else {
1291    readData(EffRank, 0, Rank, TotalReadSize, NErrs);
1292  }
1293
1294  int AllNErrs[3];
1295#ifndef GENERICIO_NO_MPI
1296  MPI_Allreduce(NErrs, AllNErrs, 3, MPI_INT, MPI_SUM, Comm);
1297#else
1298  AllNErrs[0] = NErrs[0]; AllNErrs[1] = NErrs[1]; AllNErrs[2] = NErrs[2];
1299#endif
1300
1301  if (AllNErrs[0] > 0 || AllNErrs[1] > 0 || AllNErrs[2] > 0) {
1302    stringstream ss;
1303    ss << "Experienced " << AllNErrs[0] << " I/O error(s), " <<
1304          AllNErrs[1] << " CRC error(s) and " << AllNErrs[2] <<
1305          " decompression CRC error(s) reading: " << OpenFileName;
1306    throw runtime_error(ss.str());
1307  }
1308
1309#ifndef GENERICIO_NO_MPI
1310  MPI_Barrier(Comm);
1311#endif
1312
1313#ifndef GENERICIO_NO_MPI
1314  double EndTime = MPI_Wtime();
1315#else
1316  double EndTime = double(clock())/CLOCKS_PER_SEC;
1317#endif
1318
1319  double TotalTime = EndTime - StartTime;
1320  double MaxTotalTime;
1321#ifndef GENERICIO_NO_MPI
1322  if (CollStats)
1323    MPI_Reduce(&TotalTime, &MaxTotalTime, 1, MPI_DOUBLE, MPI_MAX, 0, Comm);
1324  else
1325#endif
1326  MaxTotalTime = TotalTime;
1327
1328  uint64_t AllTotalReadSize;
1329#ifndef GENERICIO_NO_MPI
1330  if (CollStats)
1331    MPI_Reduce(&TotalReadSize, &AllTotalReadSize, 1, MPI_UINT64_T, MPI_SUM, 0, Comm);
1332  else
1333#endif
1334  AllTotalReadSize = TotalReadSize;
1335
1336  if (Rank == 0 && PrintStats) {
1337    double Rate = ((double) AllTotalReadSize) / MaxTotalTime / (1024.*1024.);
1338    std::cout << "Read " << Vars.size() << " variables from " << FileName <<
1339                 " (" << AllTotalReadSize << " bytes) in " << MaxTotalTime << "s: " <<
1340                 Rate << " MB/s [excluding header read]" << std::endl;
1341  }
1342}
1343
1344void GenericIO::readData(int EffRank, size_t RowOffset, int Rank,
1345                         uint64_t &TotalReadSize, int NErrs[3]) {
1346  if (FH.isBigEndian())
1347    readData<true>(EffRank, RowOffset, Rank, TotalReadSize, NErrs);
1348  else
1349    readData<false>(EffRank, RowOffset, Rank, TotalReadSize, NErrs);
1350}
1351
1352// Note: Errors from this function should be recoverable. This means that if
1353// one rank throws an exception, then all ranks should.
1354template <bool IsBigEndian>
1355void GenericIO::readData(int EffRank, size_t RowOffset, int Rank,
1356                         uint64_t &TotalReadSize, int NErrs[3]) {
1357  openAndReadHeader(Redistributing ? MismatchRedistribute : MismatchAllowed,
1358                    EffRank, false);
1359
1360  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1361
1362  if (EffRank == -1)
1363    EffRank = Rank;
1364
1365  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1366  size_t RankIndex = getRankIndex<IsBigEndian>(EffRank, GH, RankMap, FH.getHeaderCache());
1367
1368  assert(RankIndex < GH->NRanks && "Invalid rank specified");
1369
1370  RankHeader<IsBigEndian> *RH = (RankHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->RanksStart +
1371                                               RankIndex*GH->RanksSize];
1372
1373  for (size_t i = 0; i < Vars.size(); ++i) {
1374    uint64_t Offset = RH->Start;
1375    bool VarFound = false;
1376    for (uint64_t j = 0; j < GH->NVars; ++j) {
1377      VariableHeader<IsBigEndian> *VH = (VariableHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->VarsStart +
1378                                                           j*GH->VarsSize];
1379
1380      string VName(VH->Name, VH->Name + NameSize);
1381      size_t VNameNull = VName.find('\0');
1382      if (VNameNull < NameSize)
1383        VName.resize(VNameNull);
1384
1385      uint64_t ReadSize = RH->NElems*VH->Size + CRCSize;
1386      if (VName != Vars[i].Name) {
1387        Offset += ReadSize;
1388        continue;
1389      }
1390
1391      size_t ElementSize = VH->Size;
1392      if (offsetof_safe(VH, ElementSize) < GH->VarsSize)
1393        ElementSize = VH->ElementSize;
1394
1395      VarFound = true;
1396      bool IsFloat = (bool) (VH->Flags & FloatValue),
1397           IsSigned = (bool) (VH->Flags & SignedValue);
1398      if (VH->Size != Vars[i].Size) {
1399        stringstream ss;
1400        ss << "Size mismatch for variable " << Vars[i].Name <<
1401              " in: " << OpenFileName << ": current: " << Vars[i].Size <<
1402              ", file: " << VH->Size;
1403        throw runtime_error(ss.str());
1404      } else if (ElementSize != Vars[i].ElementSize) {
1405        stringstream ss;
1406        ss << "Element size mismatch for variable " << Vars[i].Name <<
1407              " in: " << OpenFileName << ": current: " << Vars[i].ElementSize <<
1408              ", file: " << ElementSize;
1409        throw runtime_error(ss.str());
1410      } else if (IsFloat != Vars[i].IsFloat) {
1411        string Float("float"), Int("integer");
1412        stringstream ss;
1413        ss << "Type mismatch for variable " << Vars[i].Name <<
1414              " in: " << OpenFileName << ": current: " <<
1415              (Vars[i].IsFloat ? Float : Int) <<
1416              ", file: " << (IsFloat ? Float : Int);
1417        throw runtime_error(ss.str());
1418      } else if (IsSigned != Vars[i].IsSigned) {
1419        string Signed("signed"), Uns("unsigned");
1420        stringstream ss;
1421        ss << "Type mismatch for variable " << Vars[i].Name <<
1422              " in: " << OpenFileName << ": current: " <<
1423              (Vars[i].IsSigned ? Signed : Uns) <<
1424              ", file: " << (IsSigned ? Signed : Uns);
1425        throw runtime_error(ss.str());
1426      }
1427
1428      size_t VarOffset = RowOffset*Vars[i].Size;
1429      void *VarData = ((char *) Vars[i].Data) + VarOffset;
1430
1431      vector<unsigned char> LData;
1432      void *Data = VarData;
1433      bool HasExtraSpace = Vars[i].HasExtraSpace;
1434      if (offsetof_safe(GH, BlocksStart) < GH->GlobalHeaderSize &&
1435          GH->BlocksSize > 0) {
1436        BlockHeader<IsBigEndian> *BH = (BlockHeader<IsBigEndian> *)
1437          &FH.getHeaderCache()[GH->BlocksStart +
1438                               (RankIndex*GH->NVars + j)*GH->BlocksSize];
1439        ReadSize = BH->Size + CRCSize;
1440        Offset = BH->Start;
1441
1442        if (strncmp(BH->Filters[0], CompressName, FilterNameSize) == 0) {
1443          LData.resize(ReadSize);
1444          Data = &LData[0];
1445          HasExtraSpace = true;
1446        } else if (BH->Filters[0][0] != '\0') {
1447          stringstream ss;
1448          ss << "Unknown filter \"" << BH->Filters[0] << "\" on variable " << Vars[i].Name;
1449          throw runtime_error(ss.str());
1450        }
1451      }
1452
1453      assert(HasExtraSpace && "Extra space required for reading");
1454
1455      char CRCSave[CRCSize];
1456      char *CRCLoc = ((char *) Data) + ReadSize - CRCSize;
1457      if (HasExtraSpace)
1458        std::copy(CRCLoc, CRCLoc + CRCSize, CRCSave);
1459
1460      int Retry = 0;
1461      {
1462        int RetryCount = 300;
1463        const char *EnvStr = getenv("GENERICIO_RETRY_COUNT");
1464        if (EnvStr)
1465          RetryCount = atoi(EnvStr);
1466
1467        int RetrySleep = 100; // ms
1468        EnvStr = getenv("GENERICIO_RETRY_SLEEP");
1469        if (EnvStr)
1470          RetrySleep = atoi(EnvStr);
1471
1472        for (; Retry < RetryCount; ++Retry) {
1473          try {
1474            FH.get()->read(Data, ReadSize, Offset, Vars[i].Name);
1475            break;
1476          } catch (...) { }
1477
1478          usleep(1000*RetrySleep);
1479        }
1480
1481        if (Retry == RetryCount) {
1482          ++NErrs[0];
1483          break;
1484        } else if (Retry > 0) {
1485          EnvStr = getenv("GENERICIO_VERBOSE");
1486          if (EnvStr) {
1487            int Mod = atoi(EnvStr);
1488            if (Mod > 0) {
1489              int Rank;
1490#ifndef GENERICIO_NO_MPI
1491              MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1492#else
1493              Rank = 0;
1494#endif
1495
1496              std::cerr << "Rank " << Rank << ": " << Retry <<
1497                           " I/O retries were necessary for reading " <<
1498                           Vars[i].Name << " from: " << OpenFileName << "\n";
1499
1500              std::cerr.flush();
1501            }
1502          }
1503        }
1504      }
1505
1506      TotalReadSize += ReadSize;
1507
1508      uint64_t CRC = crc64_omp(Data, ReadSize);
1509      if (CRC != (uint64_t) -1) {
1510        ++NErrs[1];
1511
1512        int Rank;
1513#ifndef GENERICIO_NO_MPI
1514        MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1515#else
1516        Rank = 0;
1517#endif
1518
1519        // All ranks will do this and have a good time!
1520        string dn = "gio_crc_errors";
1521        mkdir(dn.c_str(), 0777);
1522
1523        srand(time(0));
1524        int DumpNum = rand();
1525        stringstream ssd;
1526        ssd << dn << "/gio_crc_error_dump." << Rank << "." << DumpNum << ".bin";
1527
1528        stringstream ss;
1529        ss << dn << "/gio_crc_error_log." << Rank << ".txt";
1530
1531        ofstream ofs(ss.str().c_str(), ofstream::out | ofstream::app);
1532        ofs << "On-Disk CRC Error Report:\n";
1533        ofs << "Variable: " << Vars[i].Name << "\n";
1534        ofs << "File: " << OpenFileName << "\n";
1535        ofs << "I/O Retries: " << Retry << "\n";
1536        ofs << "Size: " << ReadSize << " bytes\n";
1537        ofs << "Offset: " << Offset << " bytes\n";
1538        ofs << "CRC: " << CRC << " (expected is -1)\n";
1539        ofs << "Dump file: " << ssd.str() << "\n";
1540        ofs << "\n";
1541        ofs.close();
1542
1543        ofstream dofs(ssd.str().c_str(), ofstream::out);
1544        dofs.write((const char *) Data, ReadSize);
1545        dofs.close();
1546
1547        uint64_t RawCRC = crc64_omp(Data, ReadSize - CRCSize);
1548        unsigned char *UData = (unsigned char *) Data;
1549        crc64_invert(RawCRC, &UData[ReadSize - CRCSize]);
1550        uint64_t NewCRC = crc64_omp(Data, ReadSize);
1551        std::cerr << "Recalulated CRC: " << NewCRC << ((NewCRC == -1) ? "ok" : "bad") << "\n";
1552        break;
1553      }
1554
1555      if (HasExtraSpace)
1556        std::copy(CRCSave, CRCSave + CRCSize, CRCLoc);
1557
1558      if (LData.size()) {
1559        CompressHeader<IsBigEndian> *CH = (CompressHeader<IsBigEndian>*) &LData[0];
1560
1561#ifdef _OPENMP
1562#pragma omp master
1563  {
1564#endif
1565
1566       if (!blosc_initialized) {
1567         blosc_init();
1568         blosc_initialized = true;
1569       }
1570
1571#ifdef _OPENMP
1572       blosc_set_nthreads(omp_get_max_threads());
1573  }
1574#endif
1575
1576        blosc_decompress(&LData[0] + sizeof(CompressHeader<IsBigEndian>),
1577                         VarData, Vars[i].Size*RH->NElems);
1578
1579        if (CH->OrigCRC != crc64_omp(VarData, Vars[i].Size*RH->NElems)) {
1580          ++NErrs[2];
1581          break;
1582        }
1583      }
1584
1585      // Byte swap the data if necessary.
1586      if (IsBigEndian != isBigEndian())
1587        for (size_t j = 0;
1588             j < RH->NElems*(Vars[i].Size/Vars[i].ElementSize); ++j) {
1589          char *Offset = ((char *) VarData) + j*Vars[i].ElementSize;
1590          bswap(Offset, Vars[i].ElementSize);
1591        }
1592
1593      break;
1594    }
1595
1596    if (!VarFound)
1597      throw runtime_error("Variable " + Vars[i].Name +
1598                          " not found in: " + OpenFileName);
1599
1600    // This is for debugging.
1601    if (NErrs[0] || NErrs[1] || NErrs[2]) {
1602      const char *EnvStr = getenv("GENERICIO_VERBOSE");
1603      if (EnvStr) {
1604        int Mod = atoi(EnvStr);
1605        if (Mod > 0) {
1606          int Rank;
1607#ifndef GENERICIO_NO_MPI
1608          MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1609#else
1610          Rank = 0;
1611#endif
1612
1613          std::cerr << "Rank " << Rank << ": " << NErrs[0] << " I/O error(s), " <<
1614          NErrs[1] << " CRC error(s) and " << NErrs[2] <<
1615          " decompression CRC error(s) reading: " << Vars[i].Name <<
1616          " from: " << OpenFileName << "\n";
1617
1618          std::cerr.flush();
1619        }
1620      }
1621    }
1622
1623    if (NErrs[0] || NErrs[1] || NErrs[2])
1624      break;
1625  }
1626}
1627
1628void GenericIO::getVariableInfo(vector<VariableInfo> &VI) {
1629  if (FH.isBigEndian())
1630    getVariableInfo<true>(VI);
1631  else
1632    getVariableInfo<false>(VI);
1633}
1634
1635template <bool IsBigEndian>
1636void GenericIO::getVariableInfo(vector<VariableInfo> &VI) {
1637  assert(FH.getHeaderCache().size() && "HeaderCache must not be empty");
1638
1639  GlobalHeader<IsBigEndian> *GH = (GlobalHeader<IsBigEndian> *) &FH.getHeaderCache()[0];
1640  for (uint64_t j = 0; j < GH->NVars; ++j) {
1641    VariableHeader<IsBigEndian> *VH = (VariableHeader<IsBigEndian> *) &FH.getHeaderCache()[GH->VarsStart +
1642                                                         j*GH->VarsSize];
1643
1644    string VName(VH->Name, VH->Name + NameSize);
1645    size_t VNameNull = VName.find('\0');
1646    if (VNameNull < NameSize)
1647      VName.resize(VNameNull);
1648
1649    size_t ElementSize = VH->Size;
1650    if (offsetof_safe(VH, ElementSize) < GH->VarsSize)
1651      ElementSize = VH->ElementSize;
1652
1653    bool IsFloat = (bool) (VH->Flags & FloatValue),
1654         IsSigned = (bool) (VH->Flags & SignedValue),
1655         IsPhysCoordX = (bool) (VH->Flags & ValueIsPhysCoordX),
1656         IsPhysCoordY = (bool) (VH->Flags & ValueIsPhysCoordY),
1657         IsPhysCoordZ = (bool) (VH->Flags & ValueIsPhysCoordZ),
1658         MaybePhysGhost = (bool) (VH->Flags & ValueMaybePhysGhost);
1659    VI.push_back(VariableInfo(VName, (size_t) VH->Size, IsFloat, IsSigned,
1660                              IsPhysCoordX, IsPhysCoordY, IsPhysCoordZ,
1661                              MaybePhysGhost, ElementSize));
1662  }
1663}
1664
1665void GenericIO::setNaturalDefaultPartition() {
1666#ifdef __bgq__
1667  DefaultPartition = MPIX_IO_link_id();
1668#else
1669#ifndef GENERICIO_NO_MPI
1670  bool UseName = true;
1671  const char *EnvStr = getenv("GENERICIO_PARTITIONS_USE_NAME");
1672  if (EnvStr) {
1673    int Mod = atoi(EnvStr);
1674    UseName = (Mod != 0);
1675  }
1676
1677  if (UseName) {
1678    // This is a heuristic to generate ~256 partitions based on the
1679    // names of the nodes.
1680    char Name[MPI_MAX_PROCESSOR_NAME];
1681    int Len = 0;
1682
1683    MPI_Get_processor_name(Name, &Len);
1684    unsigned char color = 0;
1685    for (int i = 0; i < Len; ++i)
1686      color += (unsigned char) Name[i];
1687
1688    DefaultPartition = color;
1689  }
1690
1691  // This is for debugging.
1692  EnvStr = getenv("GENERICIO_RANK_PARTITIONS");
1693  if (EnvStr) {
1694    int Mod = atoi(EnvStr);
1695    if (Mod > 0) {
1696      int Rank;
1697      MPI_Comm_rank(MPI_COMM_WORLD, &Rank);
1698      DefaultPartition += Rank % Mod;
1699    }
1700  }
1701#endif
1702#endif
1703}
1704
1705} /* END namespace cosmotk */
Note: See TracBrowser for help on using the repository browser.