Coverage Report

Created: 2026-11-22 07:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/hdf5/src/H5Dchunk.c
Line
Count
Source
1
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2
 * Copyright by The HDF Group.                                               *
3
 * All rights reserved.                                                      *
4
 *                                                                           *
5
 * This file is part of HDF5.  The full HDF5 copyright notice, including     *
6
 * terms governing use, modification, and redistribution, is contained in    *
7
 * the LICENSE file, which can be found at the root of the source code       *
8
 * distribution tree, or in https://www.hdfgroup.org/licenses.               *
9
 * If you do not have access to either file, you may request a copy from     *
10
 * help@hdfgroup.org.                                                        *
11
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12
13
/* Purpose: Abstract indexed (chunked) I/O functions.  The logical
14
 *          multi-dimensional dataspace is regularly partitioned into
15
 *          same-sized "chunks", the first of which is aligned with the
16
 *          logical origin.  The chunks are indexed by different methods,
17
 *          that map a chunk index to disk address.  Each chunk can be
18
 *          compressed independently and the chunks may move around in the
19
 *          file as their storage requirements change.
20
 *
21
 * Cache:   Disk I/O is performed in units of chunks and H5MF_alloc()
22
 *          contains code to optionally align chunks on disk block
23
 *          boundaries for performance.
24
 *
25
 *          The chunk cache is an extendible hash indexed by a function
26
 *          of storage B-tree address and chunk N-dimensional offset
27
 *          within the dataset.  Collisions are not resolved -- one of
28
 *          the two chunks competing for the hash slot must be preempted
29
 *          from the cache.  All entries in the hash also participate in
30
 *          a doubly-linked list and entries are penalized by moving them
31
 *          toward the front of the list.  When a new chunk is about to
32
 *          be added to the cache the heap is pruned by preempting
33
 *          entries near the front of the list to make room for the new
34
 *          entry which is added to the end of the list.
35
 */
36
37
/****************/
38
/* Module Setup */
39
/****************/
40
41
#include "H5Dmodule.h" /* This source code file is part of the H5D module */
42
43
/***********/
44
/* Headers */
45
/***********/
46
#include "H5private.h" /* Generic Functions                        */
47
#ifdef H5_HAVE_PARALLEL
48
#include "H5ACprivate.h" /* Metadata cache                           */
49
#endif                   /* H5_HAVE_PARALLEL */
50
#include "H5CXprivate.h" /* API Contexts                             */
51
#include "H5Dpkg.h"      /* Dataset functions                        */
52
#include "H5Eprivate.h"  /* Error handling                           */
53
#include "H5Fprivate.h"  /* File functions                           */
54
#include "H5FLprivate.h" /* Free Lists                               */
55
#include "H5Iprivate.h"  /* IDs                                      */
56
#include "H5MMprivate.h" /* Memory management                        */
57
#include "H5MFprivate.h" /* File memory management                   */
58
#include "H5PBprivate.h" /* Page Buffer                              */
59
#include "H5SLprivate.h" /* Skip Lists                               */
60
#include "H5VMprivate.h" /* Vector and array functions               */
61
62
/****************/
63
/* Local Macros */
64
/****************/
65
66
/* Macros for iterating over chunks to operate on */
67
#define H5D_CHUNK_GET_FIRST_NODE(dinfo)                                                                      \
68
0
    (dinfo->layout_io_info.chunk_map->use_single                                                             \
69
0
         ? (H5SL_node_t *)(1)                                                                                \
70
0
         : H5SL_first(dinfo->layout_io_info.chunk_map->dset_sel_pieces))
71
#define H5D_CHUNK_GET_NODE_INFO(dinfo, node)                                                                 \
72
0
    (dinfo->layout_io_info.chunk_map->use_single ? dinfo->layout_io_info.chunk_map->single_piece_info        \
73
0
                                                 : (H5D_piece_info_t *)H5SL_item(node))
74
#define H5D_CHUNK_GET_NEXT_NODE(dinfo, node)                                                                 \
75
0
    (dinfo->layout_io_info.chunk_map->use_single ? (H5SL_node_t *)NULL : H5SL_next(node))
76
#define H5D_CHUNK_GET_NODE_COUNT(dinfo)                                                                      \
77
0
    (dinfo->layout_io_info.chunk_map->use_single                                                             \
78
0
         ? (size_t)1                                                                                         \
79
0
         : H5SL_count(dinfo->layout_io_info.chunk_map->dset_sel_pieces))
80
81
/* Sanity check on chunk index types: commonly used by a lot of routines in this file */
82
#define H5D_CHUNK_STORAGE_INDEX_CHK(storage)                                                                 \
83
182
    do {                                                                                                     \
84
182
        assert((H5D_CHUNK_IDX_EARRAY == (storage)->idx_type && H5D_COPS_EARRAY == (storage)->ops) ||         \
85
182
               (H5D_CHUNK_IDX_FARRAY == (storage)->idx_type && H5D_COPS_FARRAY == (storage)->ops) ||         \
86
182
               (H5D_CHUNK_IDX_BT2 == (storage)->idx_type && H5D_COPS_BT2 == (storage)->ops) ||               \
87
182
               (H5D_CHUNK_IDX_BTREE == (storage)->idx_type && H5D_COPS_BTREE == (storage)->ops) ||           \
88
182
               (H5D_CHUNK_IDX_SINGLE == (storage)->idx_type && H5D_COPS_SINGLE == (storage)->ops) ||         \
89
182
               (H5D_CHUNK_IDX_NONE == (storage)->idx_type && H5D_COPS_NONE == (storage)->ops));              \
90
182
    } while (0)
91
92
/* Macro to Check for chunk size being too big to encode. Early versions were simply limited to 32 bits.
93
 * Version 4, except for the single chunk index, was limited using a formula described below. Version 5 uses
94
 * 64 bits, as does the single chunk index (with all versions). We additionally impose the restriction that
95
 * version 4 cannot encode more than 32 bits, even though it is not precluded by the file format, because
96
 * those versions of the library cannot handle chunks larger than 32 bits internally. */
97
#define H5D_CHUNK_ENCODE_SIZE_CHECK(layout, length, err)                                                     \
98
0
    do {                                                                                                     \
99
0
        if ((layout)->version <= H5O_LAYOUT_VERSION_4) {                                                     \
100
0
            if ((length) > UINT32_MAX)                                                                       \
101
0
                HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, err,                                                  \
102
0
                            "chunk size is greater than UINT32_MAX and can't be encoded with this file "     \
103
0
                            "format version - see H5Pset_libver_bounds()");                                  \
104
0
                                                                                                             \
105
0
            if ((layout)->version == H5O_LAYOUT_VERSION_4 &&                                                 \
106
0
                (layout)->storage.u.chunk.idx_type != H5D_CHUNK_IDX_SINGLE) {                                \
107
0
                unsigned allow_chunk_size_len; /* Allowed size of encoded chunk size */                      \
108
0
                unsigned new_chunk_size_len;   /* Size of encoded chunk size */                              \
109
0
                                                                                                             \
110
0
                /* Compute the size required for encoding the size of a chunk, allowing */                   \
111
0
                /* for an extra byte, in case the filter makes the chunk larger. */                          \
112
0
                allow_chunk_size_len = 1 + ((H5VM_log2_gen((uint64_t)((layout)->u.chunk.size)) + 8) / 8);    \
113
0
                if (allow_chunk_size_len > 8)                                                                \
114
0
                    allow_chunk_size_len = 8;                                                                \
115
0
                                                                                                             \
116
0
                /* Compute encoded size of chunk */                                                          \
117
0
                new_chunk_size_len = (H5VM_log2_gen((uint64_t)(length)) + 8) / 8;                            \
118
0
                if (new_chunk_size_len > 8)                                                                  \
119
0
                    HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, err,                                              \
120
0
                                "encoded chunk size is more than 8 bytes?!?");                               \
121
0
                                                                                                             \
122
0
                /* Check if the chunk became too large to be encoded */                                      \
123
0
                if (new_chunk_size_len > allow_chunk_size_len)                                               \
124
0
                    HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, FAIL,                                             \
125
0
                                "filter increased chunk size by too much and it cannot be encoded with "     \
126
0
                                "this file format version - see H5Pset_libver_bounds()");                    \
127
0
            }                                                                                                \
128
0
        }                                                                                                    \
129
0
    } while (0)
130
131
/*
132
 * Feature: If this constant is defined then every cache preemption and load
133
 *        causes a character to be printed on the standard error stream:
134
 *
135
 *     `.': Entry was preempted because it has been completely read or
136
 *        completely written but not partially read and not partially
137
 *        written. This is often a good reason for preemption because such
138
 *        a chunk will be unlikely to be referenced in the near future.
139
 *
140
 *     `:': Entry was preempted because it hasn't been used recently.
141
 *
142
 *     `#': Entry was preempted because another chunk collided with it. This
143
 *        is usually a relatively bad thing.  If there are too many of
144
 *        these then the number of entries in the cache can be increased.
145
 *
146
 *       c: Entry was preempted because the file is closing.
147
 *
148
 *     w: A chunk read operation was eliminated because the library is
149
 *        about to write new values to the entire chunk.  This is a good
150
 *        thing, especially on files where the chunk size is the same as
151
 *        the disk block size, chunks are aligned on disk block boundaries,
152
 *        and the operating system can also eliminate a read operation.
153
 */
154
155
/*#define H5D_CHUNK_DEBUG */
156
157
/* Flags for the "edge_chunk_state" field below */
158
0
#define H5D_RDCC_DISABLE_FILTERS 0x01U /* Disable filters on this chunk */
159
#define H5D_RDCC_NEWLY_DISABLED_FILTERS                                                                      \
160
0
    0x02U /* Filters have been disabled since                                                                \
161
           * the last flush */
162
163
/******************/
164
/* Local Typedefs */
165
/******************/
166
167
/* Raw data chunks are cached.  Each entry in the cache is: */
168
typedef struct H5D_rdcc_ent_t {
169
    bool                   locked;                   /*entry is locked in cache        */
170
    bool                   dirty;                    /*needs to be written to disk?        */
171
    bool                   deleted;                  /*chunk about to be deleted        */
172
    unsigned               edge_chunk_state;         /*states related to edge chunks (see above) */
173
    hsize_t                scaled[H5O_LAYOUT_NDIMS]; /*scaled chunk 'name' (coordinates) */
174
    hsize_t                rd_count;                 /*bytes remaining to be read        */
175
    hsize_t                wr_count;                 /*bytes remaining to be written        */
176
    H5F_block_t            chunk_block;              /*offset/length of chunk in file        */
177
    hsize_t                chunk_idx;                /*index of chunk in dataset             */
178
    uint8_t               *chunk;                    /*the unfiltered chunk data        */
179
    unsigned               idx;                      /*index in hash table            */
180
    struct H5D_rdcc_ent_t *next;                     /*next item in doubly-linked list    */
181
    struct H5D_rdcc_ent_t *prev;                     /*previous item in doubly-linked list    */
182
    struct H5D_rdcc_ent_t *tmp_next;                 /*next item in temporary doubly-linked list */
183
    struct H5D_rdcc_ent_t *tmp_prev;                 /*previous item in temporary doubly-linked list */
184
} H5D_rdcc_ent_t;
185
typedef H5D_rdcc_ent_t *H5D_rdcc_ent_ptr_t; /* For free lists */
186
187
/* Callback info for iteration to prune chunks */
188
typedef struct H5D_chunk_it_ud1_t {
189
    H5D_chunk_common_ud_t     common;          /* Common info for B-tree user data (must be first) */
190
    const H5D_chk_idx_info_t *idx_info;        /* Chunked index info */
191
    const H5D_io_info_t      *io_info;         /* I/O info for dataset operation */
192
    const H5D_dset_io_info_t *dset_info;       /* Dataset specific I/O info */
193
    const hsize_t            *space_dim;       /* New dataset dimensions    */
194
    const bool               *shrunk_dim;      /* Dimensions which have been shrunk */
195
    H5S_t                    *chunk_space;     /* Dataspace for a chunk */
196
    hsize_t                   elmts_per_chunk; /* Elements in chunk */
197
    hsize_t                  *hyper_start;     /* Starting location of hyperslab */
198
    H5D_fill_buf_info_t       fb_info;         /* Dataset's fill buffer info */
199
    bool                      fb_info_init;    /* Whether the fill value buffer has been initialized */
200
} H5D_chunk_it_ud1_t;
201
202
/* Callback info for iteration to obtain chunk address and the index of the chunk for all chunks in the
203
 * B-tree. */
204
typedef struct H5D_chunk_it_ud2_t {
205
    /* down */
206
    H5D_chunk_common_ud_t common; /* Common info for B-tree user data (must be first) */
207
208
    /* up */
209
    haddr_t *chunk_addr; /* Array of chunk addresses to fill in */
210
} H5D_chunk_it_ud2_t;
211
212
/* Callback info for iteration to copy data */
213
typedef struct H5D_chunk_it_ud3_t {
214
    H5D_chunk_common_ud_t common;         /* Common info for B-tree user data (must be first) */
215
    H5F_t                *file_src;       /* Source file for copy */
216
    H5D_chk_idx_info_t   *idx_info_dst;   /* Dest. chunk index info object */
217
    void                 *buf;            /* Buffer to hold chunk data for read/write */
218
    void                 *bkg;            /* Buffer for background information during type conversion */
219
    size_t                buf_size;       /* Buffer size */
220
    size_t                bkg_size;       /* Background buffer size */
221
    size_t                src_chunk_size; /* Size of (unfiltered) chunk in source file */
222
    bool                  do_convert;     /* Whether to perform type conversions */
223
224
    /* needed for converting variable-length data */
225
    const H5T_t *dt_src;           /* Source datatype */
226
    const H5T_t *dt_dst;           /* Destination datatype */
227
    const H5T_t *dt_mem;           /* Memory datatype */
228
    H5T_path_t  *tpath_src_mem;    /* Datatype conversion path from source file to memory */
229
    H5T_path_t  *tpath_mem_dst;    /* Datatype conversion path from memory to dest. file */
230
    void        *reclaim_buf;      /* Buffer for reclaiming data */
231
    size_t       reclaim_buf_size; /* Reclaim buffer size */
232
    size_t       nelmts;           /* Number of elements in buffer */
233
    H5S_t       *buf_space;        /* Dataspace describing buffer */
234
235
    /* needed for compressed variable-length data */
236
    const H5O_pline_t *pline;      /* Filter pipeline */
237
    unsigned           dset_ndims; /* Number of dimensions in dataset */
238
    const hsize_t     *dset_dims;  /* Dataset dimensions */
239
240
    /* needed for copy object pointed by refs */
241
    H5O_copy_t *cpy_info; /* Copy options */
242
243
    /* needed for getting raw data from chunk cache */
244
    bool     chunk_in_cache;
245
    uint8_t *chunk; /* the unfiltered chunk data        */
246
} H5D_chunk_it_ud3_t;
247
248
/* Callback info for iteration to dump index */
249
typedef struct H5D_chunk_it_ud4_t {
250
    FILE    *stream;           /* Output stream    */
251
    bool     header_displayed; /* Node's header is displayed? */
252
    unsigned ndims;            /* Number of dimensions for chunk/dataset */
253
    hsize_t *chunk_dim;        /* Chunk dimensions */
254
} H5D_chunk_it_ud4_t;
255
256
/* Callback info for iteration to format convert chunks */
257
typedef struct H5D_chunk_it_ud5_t {
258
    H5D_chk_idx_info_t *new_idx_info; /* Dest. chunk index info object */
259
    unsigned            dset_ndims;   /* Number of dimensions in dataset */
260
    hsize_t            *dset_dims;    /* Dataset dimensions */
261
} H5D_chunk_it_ud5_t;
262
263
/* Typedef for chunk info iterator callback */
264
typedef struct H5D_chunk_info_iter_ud_t {
265
    hsize_t  scaled[H5O_LAYOUT_NDIMS]; /* Logical offset of the chunk */
266
    hsize_t  ndims;                    /* Number of dimensions in the dataset */
267
    hsize_t  nbytes;                   /* Size of stored data in the chunk */
268
    unsigned filter_mask;              /* Excluded filters */
269
    haddr_t  chunk_addr;               /* Address of the chunk in file */
270
    hsize_t  chunk_idx;                /* Chunk index, where the iteration needs to stop */
271
    hsize_t  curr_idx;                 /* Current index, where the iteration is */
272
    unsigned idx_hint;                 /* Index of chunk in cache, if present */
273
    bool     found;                    /* Whether the chunk was found */
274
} H5D_chunk_info_iter_ud_t;
275
276
#ifdef H5_HAVE_PARALLEL
277
/* information to construct a collective I/O operation for filling chunks */
278
typedef struct H5D_chunk_coll_fill_info_t {
279
    size_t num_chunks; /* Number of chunks in the write operation */
280
    struct chunk_coll_fill_info {
281
        haddr_t addr;       /* File address of the chunk */
282
        size_t  chunk_size; /* Size of the chunk in the file */
283
        bool    unfiltered_partial_chunk;
284
    } *chunk_info;
285
} H5D_chunk_coll_fill_info_t;
286
#endif /* H5_HAVE_PARALLEL */
287
288
typedef struct H5D_chunk_iter_ud_t {
289
    H5D_chunk_iter_op_t op;        /* User defined callback */
290
    void               *op_data;   /* User data for user defined callback */
291
    H5O_layout_chunk_t *chunk;     /* Chunk layout */
292
    haddr_t             base_addr; /* Base address of the file, taking user block into account */
293
} H5D_chunk_iter_ud_t;
294
295
/********************/
296
/* Local Prototypes */
297
/********************/
298
299
/* Chunked layout operation callbacks */
300
static herr_t H5D__chunk_construct(H5F_t *f, H5D_t *dset);
301
static herr_t H5D__chunk_init(H5F_t *f, H5D_t *dset, hid_t dapl_id, bool open_op);
302
static herr_t H5D__chunk_io_init(H5D_io_info_t *io_info, H5D_dset_io_info_t *dinfo);
303
static herr_t H5D__chunk_io_init_selections(H5D_io_info_t *io_info, H5D_dset_io_info_t *dinfo);
304
static herr_t H5D__chunk_mdio_init(H5D_io_info_t *io_info, H5D_dset_io_info_t *dinfo);
305
static herr_t H5D__chunk_read(H5D_io_info_t *io_info, H5D_dset_io_info_t *dinfo);
306
static herr_t H5D__chunk_write(H5D_io_info_t *io_info, H5D_dset_io_info_t *dinfo);
307
static herr_t H5D__chunk_flush(H5D_t *dset);
308
static herr_t H5D__chunk_io_term(H5D_io_info_t *io_info, H5D_dset_io_info_t *di);
309
static herr_t H5D__chunk_dest(H5D_t *dset);
310
311
/* Chunk query operation callbacks */
312
static int H5D__get_num_chunks_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata);
313
static int H5D__get_chunk_info_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata);
314
static int H5D__get_chunk_info_by_coord_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata);
315
static int H5D__chunk_iter_cb(const H5D_chunk_rec_t *chunk_rec, void *udata);
316
317
/* Format convert cb */
318
static int H5D__chunk_format_convert_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata);
319
320
/* Helper routines */
321
static herr_t   H5D__chunk_set_info_real(H5O_layout_chunk_t *layout, unsigned ndims, const hsize_t *curr_dims,
322
                                         const hsize_t *max_dims);
323
static herr_t   H5D__chunk_set_sizes(H5D_t *dset);
324
static herr_t   H5D__chunk_cinfo_cache_reset(H5D_chunk_cached_t *last);
325
static herr_t   H5D__chunk_cinfo_cache_update(H5D_chunk_cached_t *last, const H5D_chunk_ud_t *udata);
326
static bool     H5D__chunk_cinfo_cache_found(const H5D_chunk_cached_t *last, H5D_chunk_ud_t *udata);
327
static herr_t   H5D__create_piece_map_single(H5D_dset_io_info_t *di, H5D_io_info_t *io_info);
328
static herr_t   H5D__create_piece_file_map_all(H5D_dset_io_info_t *di, H5D_io_info_t *io_info);
329
static herr_t   H5D__create_piece_file_map_hyper(H5D_dset_io_info_t *di, H5D_io_info_t *io_info);
330
static herr_t   H5D__create_piece_mem_map_1d(const H5D_dset_io_info_t *di);
331
static herr_t   H5D__create_piece_mem_map_hyper(const H5D_dset_io_info_t *di);
332
static herr_t   H5D__piece_file_cb(void *elem, const H5T_t *type, unsigned ndims, const hsize_t *coords,
333
                                   void *_opdata);
334
static herr_t   H5D__piece_mem_cb(void *elem, const H5T_t *type, unsigned ndims, const hsize_t *coords,
335
                                  void *_opdata);
336
static herr_t   H5D__chunk_may_use_select_io(H5D_io_info_t *io_info, const H5D_dset_io_info_t *dset_info);
337
static unsigned H5D__chunk_hash_val(const H5D_shared_t *shared, const hsize_t *scaled);
338
static herr_t   H5D__chunk_flush_entry(const H5D_t *dset, H5D_rdcc_ent_t *ent, bool reset);
339
static herr_t   H5D__chunk_cache_evict(const H5D_t *dset, H5D_rdcc_ent_t *ent, bool flush);
340
static void    *H5D__chunk_lock(const H5D_io_info_t *io_info, const H5D_dset_io_info_t *dset_info,
341
                                H5D_chunk_ud_t *udata, bool relax, bool prev_unfilt_chunk);
342
static herr_t   H5D__chunk_unlock(const H5D_io_info_t *io_info, const H5D_dset_io_info_t *dset_info,
343
                                  const H5D_chunk_ud_t *udata, bool dirty, void *chunk, hsize_t naccessed);
344
static herr_t   H5D__chunk_cache_prune(const H5D_t *dset, size_t size);
345
static herr_t   H5D__chunk_prune_fill(H5D_chunk_it_ud1_t *udata, bool new_unfilt_chunk);
346
#ifdef H5_HAVE_PARALLEL
347
static herr_t H5D__chunk_collective_fill(const H5D_t *dset, H5D_chunk_coll_fill_info_t *chunk_fill_info,
348
                                         const void *fill_buf, const void *partial_chunk_fill_buf);
349
static int    H5D__chunk_cmp_coll_fill_info(const void *_entry1, const void *_entry2);
350
#endif /* H5_HAVE_PARALLEL */
351
352
/* Debugging helper routine callback */
353
static int H5D__chunk_dump_index_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata);
354
355
/*********************/
356
/* Package Variables */
357
/*********************/
358
359
/* Chunked storage layout I/O ops */
360
const H5D_layout_ops_t H5D_LOPS_CHUNK[1] = {{
361
    H5D__chunk_construct,      /* construct */
362
    H5D__chunk_init,           /* init */
363
    H5D__chunk_is_space_alloc, /* is_space_alloc */
364
    H5D__chunk_is_data_cached, /* is_data_cached */
365
    H5D__chunk_io_init,        /* io_init */
366
    H5D__chunk_mdio_init,      /* mdio_init */
367
    H5D__chunk_read,           /* ser_read */
368
    H5D__chunk_write,          /* ser_write */
369
    NULL,                      /* readvv */
370
    NULL,                      /* writevv */
371
    H5D__chunk_flush,          /* flush */
372
    H5D__chunk_io_term,        /* io_term */
373
    H5D__chunk_dest            /* dest */
374
}};
375
376
/*******************/
377
/* Local Variables */
378
/*******************/
379
380
/* Declare a free list to manage the H5F_rdcc_ent_ptr_t sequence information */
381
H5FL_SEQ_DEFINE_STATIC(H5D_rdcc_ent_ptr_t);
382
383
/* Declare a free list to manage H5D_rdcc_ent_t objects */
384
H5FL_DEFINE_STATIC(H5D_rdcc_ent_t);
385
386
/* Declare a free list to manage the H5D_chunk_info_t struct */
387
H5FL_DEFINE_STATIC(H5D_chunk_map_t);
388
389
/* Declare a free list to manage the H5D_piece_info_t struct */
390
H5FL_DEFINE(H5D_piece_info_t);
391
392
/* Declare a free list to manage the chunk sequence information */
393
H5FL_BLK_DEFINE_STATIC(chunk);
394
395
/* Declare extern free list to manage the H5S_sel_iter_t struct */
396
H5FL_EXTERN(H5S_sel_iter_t);
397
398
/* Declare the external PQ free list for the sieve buffer information */
399
H5FL_BLK_EXTERN(sieve_buf);
400
401
/*-------------------------------------------------------------------------
402
 * Function:    H5D__chunk_direct_write
403
 *
404
 * Purpose:    Internal routine to write a chunk directly into the file.
405
 *
406
 * Return:    Non-negative on success/Negative on failure
407
 *
408
 *-------------------------------------------------------------------------
409
 */
410
herr_t
411
H5D__chunk_direct_write(H5D_t *dset, uint32_t filters, hsize_t *offset, size_t data_size, const void *buf)
412
0
{
413
0
    const H5O_layout_t *layout = &(dset->shared->layout); /* Dataset layout */
414
0
    H5D_chunk_ud_t      udata;                            /* User data for querying chunk info */
415
0
    H5F_block_t         old_chunk;                        /* Offset/length of old chunk */
416
0
    H5D_chk_idx_info_t  idx_info;                         /* Chunked index info */
417
0
    hsize_t             scaled[H5S_MAX_RANK];             /* Scaled coordinates for this chunk */
418
0
    bool                need_insert = false;   /* Whether the chunk needs to be inserted into the index */
419
0
    herr_t              ret_value   = SUCCEED; /* Return value */
420
421
0
    FUNC_ENTER_PACKAGE_TAG(dset->oloc.addr)
422
423
    /* Sanity checks */
424
0
    assert(layout->type == H5D_CHUNKED);
425
426
    /* Allocate dataspace and initialize it if it hasn't been. */
427
0
    if (!H5D__chunk_is_space_alloc(&layout->storage))
428
0
        if (H5D__alloc_storage(dset, H5D_ALLOC_WRITE, false, NULL) < 0)
429
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to initialize storage");
430
431
    /* Calculate the index of this chunk */
432
0
    H5VM_chunk_scaled(dset->shared->ndims, offset, layout->u.chunk.dim, scaled);
433
0
    scaled[dset->shared->ndims] = 0;
434
435
    /* Find out the file address of the chunk (if any) */
436
0
    if (H5D__chunk_lookup(dset, scaled, &udata) < 0)
437
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
438
439
    /* Sanity check */
440
0
    assert((H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length > 0) ||
441
0
           (!H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length == 0));
442
443
    /* Set the file block information for the old chunk */
444
    /* (Which is only defined when overwriting an existing chunk) */
445
0
    old_chunk.offset = udata.chunk_block.offset;
446
0
    old_chunk.length = udata.chunk_block.length;
447
448
    /* Check if the chunk needs to be inserted (it also could exist already
449
     *      and the chunk allocate operation could resize it)
450
     */
451
452
    /* Compose chunked index info struct */
453
0
    idx_info.f      = dset->oloc.file;
454
0
    idx_info.pline  = &(dset->shared->dcpl_cache.pline);
455
0
    idx_info.layout = &(dset->shared->layout);
456
457
    /* Set up the size of chunk for user data */
458
0
    udata.chunk_block.length = data_size;
459
460
    /* Check for hsize_t overflow */
461
0
    if (H5_UNLIKELY((size_t)udata.chunk_block.length != data_size))
462
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, FAIL, "chunk size too big to fit in hsize_t");
463
464
0
    if (0 == idx_info.pline->nused && H5_addr_defined(old_chunk.offset))
465
        /* If there are no filters and we are overwriting the chunk we can just set values */
466
0
        need_insert = false;
467
0
    else {
468
        /* Otherwise, create the chunk it if it doesn't exist, or reallocate the chunk
469
         * if its size has changed.
470
         */
471
0
        if (H5D__chunk_file_alloc(&idx_info, &old_chunk, &udata.chunk_block, &need_insert, scaled) < 0)
472
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTALLOC, FAIL, "unable to allocate chunk");
473
474
        /* Cache the new chunk information */
475
0
        H5D__chunk_cinfo_cache_update(&dset->shared->cache.chunk.last, &udata);
476
0
    } /* end else */
477
478
    /* Make sure the address of the chunk is returned. */
479
0
    if (!H5_addr_defined(udata.chunk_block.offset))
480
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "chunk address isn't defined");
481
482
    /* Evict the (old) entry from the cache if present, but do not flush
483
     * it to disk */
484
0
    if (UINT_MAX != udata.idx_hint) {
485
0
        const H5D_rdcc_t *rdcc = &(dset->shared->cache.chunk); /*raw data chunk cache */
486
487
0
        if (H5D__chunk_cache_evict(dset, rdcc->slot[udata.idx_hint], false) < 0)
488
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTREMOVE, FAIL, "unable to evict chunk");
489
0
    } /* end if */
490
491
    /* Write the data to the file */
492
0
    if (H5F_shared_block_write(H5F_SHARED(dset->oloc.file), H5FD_MEM_DRAW, udata.chunk_block.offset,
493
0
                               data_size, buf) < 0)
494
0
        HGOTO_ERROR(H5E_DATASET, H5E_WRITEERROR, FAIL, "unable to write raw data to file");
495
496
    /* Insert the chunk record into the index */
497
0
    if (need_insert && layout->storage.u.chunk.ops->insert) {
498
        /* Set the chunk's filter mask to the new settings */
499
0
        udata.filter_mask = filters;
500
501
0
        if ((layout->storage.u.chunk.ops->insert)(&idx_info, &udata, dset) < 0)
502
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL, "unable to insert chunk addr into index");
503
0
    } /* end if */
504
505
0
done:
506
0
    FUNC_LEAVE_NOAPI_TAG(ret_value)
507
0
} /* end H5D__chunk_direct_write() */
508
509
/*-------------------------------------------------------------------------
510
 * Function:    H5D__chunk_direct_read
511
 *
512
 * Purpose:     Internal routine to read a chunk directly from the file.
513
 *
514
 * Return:      Non-negative on success/Negative on failure
515
 *
516
 *-------------------------------------------------------------------------
517
 */
518
herr_t
519
H5D__chunk_direct_read(const H5D_t *dset, hsize_t *offset, uint32_t *filters, void *buf, size_t *nalloc)
520
0
{
521
0
    const H5O_layout_t *layout = &(dset->shared->layout);      /* Dataset layout */
522
0
    const H5D_rdcc_t   *rdcc   = &(dset->shared->cache.chunk); /* raw data chunk cache */
523
0
    H5D_chunk_ud_t      udata;                                 /* User data for querying chunk info */
524
0
    hsize_t             scaled[H5S_MAX_RANK];                  /* Scaled coordinates for this chunk */
525
0
    herr_t              ret_value = SUCCEED;                   /* Return value */
526
527
0
    FUNC_ENTER_PACKAGE_TAG(dset->oloc.addr)
528
529
    /* Check args */
530
0
    assert(dset && H5D_CHUNKED == layout->type);
531
0
    assert(offset);
532
0
    assert(filters);
533
0
    assert(buf || nalloc);
534
535
0
    *filters = 0;
536
537
    /* Allocate dataspace and initialize it if it hasn't been. */
538
0
    if (!H5D__chunk_is_space_alloc(&layout->storage) && !H5D__chunk_is_data_cached(dset->shared))
539
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "storage is not initialized");
540
541
    /* Calculate the index of this chunk */
542
0
    H5VM_chunk_scaled(dset->shared->ndims, offset, layout->u.chunk.dim, scaled);
543
0
    scaled[dset->shared->ndims] = 0;
544
545
    /* Reset fields about the chunk we are looking for */
546
0
    udata.filter_mask        = 0;
547
0
    udata.chunk_block.offset = HADDR_UNDEF;
548
0
    udata.chunk_block.length = 0;
549
0
    udata.idx_hint           = UINT_MAX;
550
551
    /* Find out the file address of the chunk */
552
0
    if (H5D__chunk_lookup(dset, scaled, &udata) < 0)
553
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
554
555
    /* Sanity check */
556
0
    assert((H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length > 0) ||
557
0
           (!H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length == 0));
558
559
    /* Check for size_t overflow */
560
0
    if (H5_UNLIKELY((hsize_t)((size_t)udata.chunk_block.length) != udata.chunk_block.length))
561
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, FAIL, "chunk size does not fit in size_t");
562
563
    /* Check if the requested chunk exists in the chunk cache */
564
0
    if (UINT_MAX != udata.idx_hint) {
565
0
        H5D_rdcc_ent_t *ent = rdcc->slot[udata.idx_hint];
566
0
        bool            flush;
567
568
        /* Sanity checks  */
569
0
        assert(udata.idx_hint < rdcc->nslots);
570
0
        assert(rdcc->slot[udata.idx_hint]);
571
572
0
        flush = (ent->dirty == true) ? true : false;
573
574
        /* Flush the chunk to disk and clear the cache entry */
575
0
        if (H5D__chunk_cache_evict(dset, rdcc->slot[udata.idx_hint], flush) < 0)
576
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTREMOVE, FAIL, "unable to evict chunk");
577
578
        /* Reset fields about the chunk we are looking for */
579
0
        udata.filter_mask        = 0;
580
0
        udata.chunk_block.offset = HADDR_UNDEF;
581
0
        udata.chunk_block.length = 0;
582
0
        udata.idx_hint           = UINT_MAX;
583
584
        /* Get the new file address / chunk size after flushing */
585
0
        if (H5D__chunk_lookup(dset, scaled, &udata) < 0)
586
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
587
0
    }
588
589
    /* Make sure the address of the chunk is returned. */
590
0
    if (!H5_addr_defined(udata.chunk_block.offset))
591
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "chunk address isn't defined");
592
593
    /* If nalloc is provided, check if *nalloc is large enough.  If not provided, assume it is large enough
594
     * (this is the insecure older behaviour that is disallowed by H5Dread_chunk2(), but we must support it
595
     * here for the deprecated H5Dreach_chunk1()). */
596
0
    if (udata.chunk_block.length > 0 && buf && (!nalloc || *nalloc >= udata.chunk_block.length))
597
        /* Read the chunk data into the supplied buffer */
598
0
        if (H5F_shared_block_read(H5F_SHARED(dset->oloc.file), H5FD_MEM_DRAW, udata.chunk_block.offset,
599
0
                                  (size_t)udata.chunk_block.length, buf) < 0)
600
0
            HGOTO_ERROR(H5E_IO, H5E_READERROR, FAIL, "unable to read raw data chunk");
601
602
    /* Return the size of the chunk block in *nalloc if nalloc is provided */
603
0
    if (nalloc)
604
0
        *nalloc = (size_t)udata.chunk_block.length;
605
606
    /* Return the filter mask */
607
0
    *filters = udata.filter_mask;
608
609
0
done:
610
0
    FUNC_LEAVE_NOAPI_TAG(ret_value)
611
0
} /* end H5D__chunk_direct_read() */
612
613
/*-------------------------------------------------------------------------
614
 * Function:    H5D__get_chunk_storage_size
615
 *
616
 * Purpose:     Internal routine to read the storage size of a chunk on disk.
617
 *
618
 * Return:      Non-negative on success/Negative on failure
619
 *
620
 *-------------------------------------------------------------------------
621
 */
622
herr_t
623
H5D__get_chunk_storage_size(H5D_t *dset, const hsize_t *offset, hsize_t *storage_size)
624
0
{
625
0
    const H5O_layout_t *layout = &(dset->shared->layout);      /* Dataset layout */
626
0
    const H5D_rdcc_t   *rdcc   = &(dset->shared->cache.chunk); /* raw data chunk cache */
627
0
    hsize_t             scaled[H5S_MAX_RANK];                  /* Scaled coordinates for this chunk */
628
0
    H5D_chunk_ud_t      udata;                                 /* User data for querying chunk info */
629
0
    herr_t              ret_value = SUCCEED;                   /* Return value */
630
631
0
    FUNC_ENTER_PACKAGE_TAG(dset->oloc.addr)
632
633
    /* Check args */
634
0
    assert(dset && H5D_CHUNKED == layout->type);
635
0
    assert(offset);
636
0
    assert(storage_size);
637
638
    /* Allocate dataspace and initialize it if it hasn't been. */
639
0
    if (!(*layout->ops->is_space_alloc)(&layout->storage))
640
0
        HGOTO_DONE(SUCCEED);
641
642
    /* Calculate the index of this chunk */
643
0
    H5VM_chunk_scaled(dset->shared->ndims, offset, layout->u.chunk.dim, scaled);
644
0
    scaled[dset->shared->ndims] = 0;
645
646
    /* Reset fields about the chunk we are looking for */
647
0
    udata.chunk_block.offset = HADDR_UNDEF;
648
0
    udata.chunk_block.length = 0;
649
0
    udata.idx_hint           = UINT_MAX;
650
651
    /* Find out the file address of the chunk */
652
0
    if (H5D__chunk_lookup(dset, scaled, &udata) < 0)
653
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
654
655
    /* Sanity check */
656
0
    assert((H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length > 0) ||
657
0
           (!H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length == 0));
658
659
    /* The requested chunk is not in cache or on disk */
660
0
    if (!H5_addr_defined(udata.chunk_block.offset) && UINT_MAX == udata.idx_hint)
661
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "chunk storage is not allocated");
662
663
    /* Check if there are filters registered to the dataset */
664
0
    if (dset->shared->dcpl_cache.pline.nused > 0) {
665
        /* Check if the requested chunk exists in the chunk cache */
666
0
        if (UINT_MAX != udata.idx_hint) {
667
0
            H5D_rdcc_ent_t *ent = rdcc->slot[udata.idx_hint];
668
669
            /* Sanity checks  */
670
0
            assert(udata.idx_hint < rdcc->nslots);
671
0
            assert(rdcc->slot[udata.idx_hint]);
672
673
            /* If the cached chunk is dirty, it must be flushed to get accurate size */
674
0
            if (ent->dirty == true) {
675
                /* Flush the chunk to disk and clear the cache entry */
676
0
                if (H5D__chunk_cache_evict(dset, rdcc->slot[udata.idx_hint], true) < 0)
677
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTREMOVE, FAIL, "unable to evict chunk");
678
679
                /* Reset fields about the chunk we are looking for */
680
0
                udata.chunk_block.offset = HADDR_UNDEF;
681
0
                udata.chunk_block.length = 0;
682
0
                udata.idx_hint           = UINT_MAX;
683
684
                /* Get the new file address / chunk size after flushing */
685
0
                if (H5D__chunk_lookup(dset, scaled, &udata) < 0)
686
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
687
0
            }
688
0
        }
689
690
        /* Make sure the address of the chunk is returned. */
691
0
        if (!H5_addr_defined(udata.chunk_block.offset))
692
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "chunk address isn't defined");
693
694
        /* Return the chunk size on disk */
695
0
        *storage_size = udata.chunk_block.length;
696
0
    }
697
    /* There are no filters registered, return the chunk size from the storage layout */
698
0
    else
699
0
        *storage_size = dset->shared->layout.u.chunk.size;
700
701
0
done:
702
0
    FUNC_LEAVE_NOAPI_TAG(ret_value)
703
0
} /* H5D__get_chunk_storage_size */
704
705
/*-------------------------------------------------------------------------
706
 * Function:    H5D__chunk_set_info_real
707
 *
708
 * Purpose:     Internal routine to set the information about chunks for a dataset
709
 *
710
 * Return:      SUCCEED/FAIL
711
 *-------------------------------------------------------------------------
712
 */
713
static herr_t
714
H5D__chunk_set_info_real(H5O_layout_chunk_t *layout, unsigned ndims, const hsize_t *curr_dims,
715
                         const hsize_t *max_dims)
716
67
{
717
67
    herr_t ret_value = SUCCEED;
718
719
67
    FUNC_ENTER_PACKAGE
720
721
67
    assert(layout);
722
67
    assert(curr_dims);
723
724
    /* Can happen when corrupt files are parsed */
725
67
    if (ndims == 0)
726
27
        HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "number of dimensions cannot be zero");
727
728
    /* Compute the # of chunks in dataset dimensions */
729
40
    layout->nchunks     = 1;
730
40
    layout->max_nchunks = 1;
731
128
    for (unsigned u = 0; u < ndims; u++) {
732
        /* Round up to the next integer # of chunks, to accommodate partial chunks */
733
88
        layout->chunks[u] = ((curr_dims[u] + layout->dim[u]) - 1) / layout->dim[u];
734
88
        if (H5S_UNLIMITED == max_dims[u])
735
0
            layout->max_chunks[u] = H5S_UNLIMITED;
736
88
        else {
737
            /* Sanity check */
738
88
            if (layout->dim[u] == 0)
739
0
                HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "dimension size must be > 0, dim = %u ", u);
740
741
88
            layout->max_chunks[u] = ((max_dims[u] + layout->dim[u]) - 1) / layout->dim[u];
742
88
        }
743
744
        /* Accumulate the # of chunks */
745
88
        layout->nchunks *= layout->chunks[u];
746
88
        layout->max_nchunks *= layout->max_chunks[u];
747
88
    }
748
749
    /* Get the "down" sizes for each dimension */
750
40
    H5VM_array_down(ndims, layout->chunks, layout->down_chunks);
751
40
    H5VM_array_down(ndims, layout->max_chunks, layout->max_down_chunks);
752
753
67
done:
754
67
    FUNC_LEAVE_NOAPI(ret_value)
755
67
} /* end H5D__chunk_set_info_real() */
756
757
/*-------------------------------------------------------------------------
758
 * Function:    H5D__chunk_set_info
759
 *
760
 * Purpose:    Sets the information about chunks for a dataset
761
 *
762
 * Return:    Non-negative on success/Negative on failure
763
 *
764
 *-------------------------------------------------------------------------
765
 */
766
herr_t
767
H5D__chunk_set_info(const H5D_t *dset)
768
67
{
769
67
    herr_t ret_value = SUCCEED; /* Return value */
770
771
67
    FUNC_ENTER_PACKAGE
772
773
    /* Sanity checks */
774
67
    assert(dset);
775
776
    /* Set the base layout information */
777
67
    if (H5D__chunk_set_info_real(&dset->shared->layout.u.chunk, dset->shared->ndims, dset->shared->curr_dims,
778
67
                                 dset->shared->max_dims) < 0)
779
27
        HGOTO_ERROR(H5E_DATASET, H5E_CANTSET, FAIL, "can't set layout's chunk info");
780
781
    /* Call the index's "resize" callback */
782
40
    if (dset->shared->layout.storage.u.chunk.ops->resize &&
783
0
        (dset->shared->layout.storage.u.chunk.ops->resize)(&dset->shared->layout.u.chunk) < 0)
784
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTSET, FAIL, "unable to resize chunk index information");
785
786
67
done:
787
67
    FUNC_LEAVE_NOAPI(ret_value)
788
67
} /* end H5D__chunk_set_info() */
789
790
/*-------------------------------------------------------------------------
791
 * Function:    H5D__chunk_set_sizes
792
 *
793
 * Purpose:     Sets chunk and type sizes.
794
 *
795
 * Return:      SUCCEED/FAIL
796
 *
797
 *-------------------------------------------------------------------------
798
 */
799
static herr_t
800
H5D__chunk_set_sizes(H5D_t *dset)
801
40
{
802
40
    uint64_t chunk_size;            /* Size of chunk in bytes */
803
40
    unsigned max_enc_bytes_per_dim; /* Max. number of bytes required to encode this dimension */
804
40
    unsigned u;                     /* Iterator */
805
40
    herr_t   ret_value = SUCCEED;   /* Return value */
806
807
40
    FUNC_ENTER_PACKAGE
808
809
    /* Sanity checks */
810
40
    assert(dset);
811
40
    assert(dset->shared->layout.u.chunk.ndims > 0);
812
813
    /* In this function, some of these sizes may have already been set since they are sometimes stored in the
814
     * file. If this is the case, verify the calculated sizes match the stored sizes. */
815
    /* Set the last dimension of the chunk size to the size of the datatype */
816
40
    if (dset->shared->layout.u.chunk.dim[dset->shared->layout.u.chunk.ndims - 1]) {
817
40
        if (dset->shared->layout.u.chunk.dim[dset->shared->layout.u.chunk.ndims - 1] !=
818
40
            (hsize_t)H5T_GET_SIZE(dset->shared->type))
819
36
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL,
820
40
                        "stored datatype size in chunk layout does not match datatype description");
821
40
    }
822
0
    else
823
0
        dset->shared->layout.u.chunk.dim[dset->shared->layout.u.chunk.ndims - 1] =
824
0
            (hsize_t)H5T_GET_SIZE(dset->shared->type);
825
826
    /* Compute number of bytes to use for encoding chunk dimensions */
827
4
    max_enc_bytes_per_dim = 0;
828
32
    for (u = 0; u < (unsigned)dset->shared->layout.u.chunk.ndims; u++) {
829
28
        unsigned enc_bytes_per_dim; /* Number of bytes required to encode this dimension */
830
831
        /* Get encoded size of dim, in bytes */
832
28
        enc_bytes_per_dim = (H5VM_log2_gen(dset->shared->layout.u.chunk.dim[u]) + 8) / 8;
833
834
        /* Check if this is the largest value so far */
835
28
        if (enc_bytes_per_dim > max_enc_bytes_per_dim)
836
4
            max_enc_bytes_per_dim = enc_bytes_per_dim;
837
28
    } /* end for */
838
4
    assert(max_enc_bytes_per_dim > 0 && max_enc_bytes_per_dim <= 8);
839
840
    /* Set encoding length in layout */
841
4
    if (dset->shared->layout.u.chunk.enc_bytes_per_dim) {
842
0
        if (dset->shared->layout.u.chunk.enc_bytes_per_dim < max_enc_bytes_per_dim)
843
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL,
844
0
                        "stored chunk dimension encoding length is insufficient to encode chunk dimensions");
845
0
    }
846
4
    else
847
4
        dset->shared->layout.u.chunk.enc_bytes_per_dim = max_enc_bytes_per_dim;
848
849
    /* Compute and store the total size of a chunk */
850
    /* (Use 64-bit value to ensure that we can detect >4GB chunks) */
851
4
    for (u = 1, chunk_size = (uint64_t)dset->shared->layout.u.chunk.dim[0];
852
28
         u < dset->shared->layout.u.chunk.ndims; u++)
853
24
        chunk_size *= (uint64_t)dset->shared->layout.u.chunk.dim[u];
854
855
    /* Store chunk size in layout */
856
4
    dset->shared->layout.u.chunk.size = (hsize_t)chunk_size;
857
858
    /* Check for overflow converting uint64_t to hsize_t */
859
4
    if ((uint64_t)dset->shared->layout.u.chunk.size != chunk_size)
860
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, FAIL, "chunk size too big to fit in hsize_t");
861
862
40
done:
863
40
    FUNC_LEAVE_NOAPI(ret_value)
864
40
} /* end H5D__chunk_set_sizes */
865
866
/*-------------------------------------------------------------------------
867
 * Function:    H5D__chunk_construct
868
 *
869
 * Purpose:    Constructs new chunked layout information for dataset and upgrade layout version if appropriate
870
 *
871
 * Return:    Non-negative on success/Negative on failure
872
 *
873
 *-------------------------------------------------------------------------
874
 */
875
static herr_t
876
H5D__chunk_construct(H5F_t *f, H5D_t *dset)
877
0
{
878
0
    H5O_layout_t *layout;
879
0
    unsigned      version_req = H5O_LAYOUT_VERSION_1; /* Required layout version */
880
0
    unsigned version_perf = H5O_LAYOUT_VERSION_1; /* Version we would like to upgrade to for performance */
881
0
    unsigned u;                                   /* Local index variable */
882
0
    herr_t   ret_value = SUCCEED;                 /* Return value */
883
884
0
    FUNC_ENTER_PACKAGE
885
886
    /* Sanity checks */
887
0
    assert(f);
888
0
    assert(dset);
889
0
    assert(dset->shared);
890
891
    /* Set converience pointer */
892
0
    layout = &dset->shared->layout;
893
894
    /* Check for invalid chunk dimension rank */
895
0
    if (0 == dset->shared->layout.u.chunk.ndims)
896
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "no chunk information set?");
897
0
    if (layout->u.chunk.ndims != dset->shared->ndims)
898
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "dimensionality of chunks doesn't match the dataspace");
899
900
    /* Increment # of chunk dimensions, to account for datatype size as last element */
901
0
    layout->u.chunk.ndims++;
902
903
    /* Set chunk sizes */
904
0
    if (H5D__chunk_set_sizes(dset) < 0)
905
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "unable to set chunk sizes");
906
0
    assert((unsigned)(layout->u.chunk.ndims) <= NELMTS(layout->u.chunk.dim));
907
908
    /* Calculate layout version */
909
    /* Do not downgrade version */
910
0
    version_req = layout->version;
911
912
    /* Always prefer at least version 4 for performance due to new indexes */
913
0
    version_perf = H5O_LAYOUT_VERSION_4;
914
915
    /* First check for chunk larger than can be represented in 32-bits - this requires layout version 5. While
916
     * it could be encoded as version 4, those versions of the library would not be able to read it. */
917
0
    if (layout->u.chunk.size > (hsize_t)0xffffffff) {
918
0
        if (H5O_layout_ver_bounds[H5F_HIGH_BOUND(f)] < H5O_LAYOUT_VERSION_5)
919
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL,
920
0
                        "chunk size > 4GB requires H5F_LIBVER_V200 or later format version - see "
921
0
                        "H5Pset_libver_bounds()");
922
923
        /* Set required version */
924
0
        version_req = MAX(version_req, H5O_LAYOUT_VERSION_5);
925
0
    }
926
#ifndef NDEBUG
927
    else {
928
        /* Make sure no individual chunk dimension is greater than 32 bits. Should be impossible since the
929
         * chunk size is less than 32 bits. */
930
        for (u = 0; u < dset->shared->ndims; u++)
931
            assert(layout->u.chunk.dim[u] <= (hsize_t)0xffffffff);
932
    }
933
#endif /* NDEBUG */
934
935
    /* Now check if we can or must upgrade to version or above - if so set the new indexing */
936
0
    if ((H5O_layout_ver_bounds[H5F_LOW_BOUND(f)] >= H5O_LAYOUT_VERSION_4) ||
937
0
        (version_req >= H5O_LAYOUT_VERSION_4)) {
938
0
        unsigned unlim_count = 0;    /* Count of unlimited max. dimensions */
939
0
        bool     single      = true; /* Fulfill single chunk indexing */
940
941
        /* It should be impossible to create a chunked dataset with a scalar/null dataspace */
942
0
        assert(dset->shared->ndims > 0);
943
944
        /* Spin through the max. dimensions, looking for unlimited dimensions */
945
0
        for (u = 0; u < dset->shared->ndims; u++) {
946
0
            if (dset->shared->max_dims[u] == H5S_UNLIMITED)
947
0
                unlim_count++;
948
0
            if (dset->shared->curr_dims[u] != dset->shared->max_dims[u] ||
949
0
                dset->shared->curr_dims[u] != layout->u.chunk.dim[u])
950
0
                single = false;
951
0
        }
952
953
        /* Chunked datasets with unlimited dimension(s) */
954
0
        if (unlim_count) {          /* dataset with unlimited dimension(s) must be chunked */
955
0
            if (1 == unlim_count) { /* Chunked dataset with only 1 unlimited dimension */
956
                /* Set the chunk index type to an extensible array */
957
0
                layout->u.chunk.idx_type         = H5D_CHUNK_IDX_EARRAY;
958
0
                layout->storage.u.chunk.idx_type = H5D_CHUNK_IDX_EARRAY;
959
0
                layout->storage.u.chunk.ops      = H5D_COPS_EARRAY;
960
961
                /* Set the extensible array creation parameters */
962
                /* (use hard-coded defaults for now, until we give applications
963
                 *          control over this with a property list - QAK)
964
                 */
965
0
                layout->u.chunk.u.earray.cparam.max_nelmts_bits       = H5D_EARRAY_MAX_NELMTS_BITS;
966
0
                layout->u.chunk.u.earray.cparam.idx_blk_elmts         = H5D_EARRAY_IDX_BLK_ELMTS;
967
0
                layout->u.chunk.u.earray.cparam.sup_blk_min_data_ptrs = H5D_EARRAY_SUP_BLK_MIN_DATA_PTRS;
968
0
                layout->u.chunk.u.earray.cparam.data_blk_min_elmts    = H5D_EARRAY_DATA_BLK_MIN_ELMTS;
969
0
                layout->u.chunk.u.earray.cparam.max_dblk_page_nelmts_bits =
970
0
                    H5D_EARRAY_MAX_DBLOCK_PAGE_NELMTS_BITS;
971
972
                /* If there are filters, we prefer version 5 since that version can handle greatly expanding
973
                 * filters */
974
0
                if (dset->shared->dcpl_cache.pline.nused)
975
0
                    version_perf = H5O_LAYOUT_VERSION_5;
976
0
            }
977
0
            else { /* Chunked dataset with > 1 unlimited dimensions */
978
                /* Set the chunk index type to v2 B-tree */
979
0
                layout->u.chunk.idx_type         = H5D_CHUNK_IDX_BT2;
980
0
                layout->storage.u.chunk.idx_type = H5D_CHUNK_IDX_BT2;
981
0
                layout->storage.u.chunk.ops      = H5D_COPS_BT2;
982
983
                /* Set the v2 B-tree creation parameters */
984
                /* (use hard-coded defaults for now, until we give applications
985
                 *          control over this with a property list - QAK)
986
                 */
987
0
                layout->u.chunk.u.btree2.cparam.node_size     = H5D_BT2_NODE_SIZE;
988
0
                layout->u.chunk.u.btree2.cparam.split_percent = H5D_BT2_SPLIT_PERC;
989
0
                layout->u.chunk.u.btree2.cparam.merge_percent = H5D_BT2_MERGE_PERC;
990
991
                /* If there are filters, we prefer version 5 since that version can handle greatly expanding
992
                 * filters */
993
0
                if (dset->shared->dcpl_cache.pline.nused)
994
0
                    version_perf = H5O_LAYOUT_VERSION_5;
995
0
            }
996
0
        }
997
0
        else { /* Chunked dataset with fixed dimensions */
998
            /* Check for correct condition for using "single chunk" chunk index */
999
0
            if (single) {
1000
0
                layout->u.chunk.idx_type         = H5D_CHUNK_IDX_SINGLE;
1001
0
                layout->storage.u.chunk.idx_type = H5D_CHUNK_IDX_SINGLE;
1002
0
                layout->storage.u.chunk.ops      = H5D_COPS_SINGLE;
1003
1004
                /* If there are filters, we prefer version 5 since that version can handle greatly expanding
1005
                 * filters (>4 GiB) (technically allowed by the v4 format but disallowed by library since
1006
                 * older library version can't handle >4 GiB chunks even if the format can) */
1007
0
                if (dset->shared->dcpl_cache.pline.nused)
1008
0
                    version_perf = H5O_LAYOUT_VERSION_5;
1009
0
            }
1010
0
            else if (!dset->shared->dcpl_cache.pline.nused &&
1011
0
                     dset->shared->dcpl_cache.fill.alloc_time == H5D_ALLOC_TIME_EARLY) {
1012
1013
                /* Set the chunk index type to "none" Index */
1014
0
                layout->u.chunk.idx_type         = H5D_CHUNK_IDX_NONE;
1015
0
                layout->storage.u.chunk.idx_type = H5D_CHUNK_IDX_NONE;
1016
0
                layout->storage.u.chunk.ops      = H5D_COPS_NONE;
1017
1018
                /* No need to upgrade to version 5 since the none index isn't used with filters */
1019
0
            }
1020
0
            else {
1021
                /* Set the chunk index type to Fixed Array */
1022
0
                layout->u.chunk.idx_type         = H5D_CHUNK_IDX_FARRAY;
1023
0
                layout->storage.u.chunk.idx_type = H5D_CHUNK_IDX_FARRAY;
1024
0
                layout->storage.u.chunk.ops      = H5D_COPS_FARRAY;
1025
1026
                /* Set the fixed array creation parameters */
1027
                /* (use hard-coded defaults for now, until we give applications
1028
                 *          control over this with a property list - QAK)
1029
                 */
1030
0
                layout->u.chunk.u.farray.cparam.max_dblk_page_nelmts_bits =
1031
0
                    H5D_FARRAY_MAX_DBLK_PAGE_NELMTS_BITS;
1032
1033
                /* If there are filters, we prefer version 5 since that version can handle greatly expanding
1034
                 * filters */
1035
0
                if (dset->shared->dcpl_cache.pline.nused)
1036
0
                    version_perf = H5O_LAYOUT_VERSION_5;
1037
0
            }
1038
0
        }
1039
0
    }
1040
1041
    /* Calculate final version - choose the maximum of the current version, the required version, and the
1042
     * minimum of the low bound and the version we would like to upgrade to for performance. This ensures that
1043
     * we are never below the current version or the required version, and that we always upgrade to at least
1044
     * the low bound when useful, but never farther unless required otherwise. */
1045
0
    layout->version =
1046
0
        MAX3(layout->version, version_req, MIN(H5O_layout_ver_bounds[H5F_LOW_BOUND(f)], version_perf));
1047
1048
    /* The logic above should guarantee the calculated layout version is not above the high bound */
1049
0
    assert(layout->version <= H5O_layout_ver_bounds[H5F_HIGH_BOUND(f)]);
1050
1051
    /* Chunked storage is not compatible with external storage (currently) */
1052
0
    if (dset->shared->dcpl_cache.efl.nused > 0)
1053
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "external storage not supported with chunked layout");
1054
1055
    /* Sanity check dimensions */
1056
0
    for (u = 0; u < layout->u.chunk.ndims - 1; u++) {
1057
        /* Don't allow zero-sized chunk dimensions */
1058
0
        if (0 == layout->u.chunk.dim[u])
1059
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "chunk size must be > 0, dim = %u ", u);
1060
1061
        /*
1062
         * The chunk size of a dimension with a fixed size cannot exceed
1063
         * the maximum dimension size. If any dimension size is zero, there
1064
         * will be no such restriction.
1065
         */
1066
0
        if (dset->shared->curr_dims[u] && dset->shared->max_dims[u] != H5S_UNLIMITED &&
1067
0
            dset->shared->max_dims[u] < layout->u.chunk.dim[u])
1068
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL,
1069
0
                        "chunk size must be <= maximum dimension size for fixed-sized dimensions");
1070
0
    } /* end for */
1071
1072
    /* Reset address and pointer of the array struct for the chunked storage index */
1073
0
    if (H5D_chunk_idx_reset(&layout->storage.u.chunk, true) < 0)
1074
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to reset chunked storage index");
1075
1076
0
done:
1077
0
    FUNC_LEAVE_NOAPI(ret_value)
1078
0
} /* end H5D__chunk_construct() */
1079
1080
/*-------------------------------------------------------------------------
1081
 * Function:    H5D__chunk_init
1082
 *
1083
 * Purpose:    Initialize the raw data chunk cache for a dataset.  This is
1084
 *        called when the dataset is initialized.
1085
 *
1086
 * Return:    Non-negative on success/Negative on failure
1087
 *
1088
 *-------------------------------------------------------------------------
1089
 */
1090
static herr_t
1091
H5D__chunk_init(H5F_t *f, H5D_t *dset, hid_t dapl_id, bool open_op)
1092
91
{
1093
91
    H5D_chk_idx_info_t idx_info;                            /* Chunked index info */
1094
91
    H5D_rdcc_t        *rdcc = &(dset->shared->cache.chunk); /* Convenience pointer to dataset's chunk cache */
1095
91
    H5P_genplist_t    *dapl;                                /* Data access property list object pointer */
1096
91
    H5O_storage_chunk_t *sc        = &(dset->shared->layout.storage.u.chunk);
1097
91
    bool                 idx_init  = false;
1098
91
    herr_t               ret_value = SUCCEED; /* Return value */
1099
1100
91
    FUNC_ENTER_PACKAGE
1101
1102
    /* Sanity check */
1103
91
    assert(f);
1104
91
    assert(dset);
1105
91
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
1106
1107
91
    if (NULL == (dapl = (H5P_genplist_t *)H5I_object(dapl_id)))
1108
0
        HGOTO_ERROR(H5E_ID, H5E_BADID, FAIL, "can't find object for fapl ID");
1109
1110
    /* Use the properties in dapl_id if they have been set, otherwise use the properties from the file */
1111
91
    if (H5P_get(dapl, H5D_ACS_DATA_CACHE_NUM_SLOTS_NAME, &rdcc->nslots) < 0)
1112
0
        HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get data cache number of slots");
1113
91
    if (rdcc->nslots == H5D_CHUNK_CACHE_NSLOTS_DEFAULT)
1114
91
        rdcc->nslots = H5F_RDCC_NSLOTS(f);
1115
1116
91
    if (H5P_get(dapl, H5D_ACS_DATA_CACHE_BYTE_SIZE_NAME, &rdcc->nbytes_max) < 0)
1117
0
        HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get data cache byte size");
1118
91
    if (rdcc->nbytes_max == H5D_CHUNK_CACHE_NBYTES_DEFAULT)
1119
91
        rdcc->nbytes_max = H5F_RDCC_NBYTES(f);
1120
1121
91
    if (H5P_get(dapl, H5D_ACS_PREEMPT_READ_CHUNKS_NAME, &rdcc->w0) < 0)
1122
0
        HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't get preempt read chunks");
1123
91
    if (rdcc->w0 < 0)
1124
91
        rdcc->w0 = H5F_RDCC_W0(f);
1125
1126
    /* If nbytes_max or nslots is 0, set them both to 0 and avoid allocating space */
1127
91
    if (!rdcc->nbytes_max || !rdcc->nslots)
1128
0
        rdcc->nbytes_max = rdcc->nslots = 0;
1129
91
    else {
1130
91
        rdcc->slot = H5FL_SEQ_CALLOC(H5D_rdcc_ent_ptr_t, rdcc->nslots);
1131
91
        if (NULL == rdcc->slot)
1132
0
            HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed");
1133
1134
        /* Reset any cached chunk info for this dataset */
1135
91
        H5D__chunk_cinfo_cache_reset(&(rdcc->last));
1136
91
    } /* end else */
1137
1138
    /* Compute scaled dimension info, if dataset dims > 1 */
1139
91
    if (dset->shared->ndims > 1) {
1140
59
        unsigned u; /* Local index value */
1141
1142
179
        for (u = 0; u < dset->shared->ndims; u++) {
1143
124
            hsize_t scaled_power2up; /* Scaled value, rounded to next power of 2 */
1144
1145
            /* Initial scaled dimension sizes */
1146
124
            if (dset->shared->layout.u.chunk.dim[u] == 0)
1147
4
                HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "chunk size must be > 0, dim = %u ", u);
1148
1149
            /* Round up to the next integer # of chunks, to accommodate partial chunks */
1150
120
            rdcc->scaled_dims[u] = (dset->shared->curr_dims[u] + dset->shared->layout.u.chunk.dim[u] - 1) /
1151
120
                                   dset->shared->layout.u.chunk.dim[u];
1152
1153
120
            if (!(scaled_power2up = H5VM_power2up(rdcc->scaled_dims[u])))
1154
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "unable to get the next power of 2");
1155
1156
            /* Initial 'power2up' values for scaled dimensions */
1157
120
            rdcc->scaled_power2up[u] = scaled_power2up;
1158
1159
            /* Number of bits required to encode scaled dimension size */
1160
120
            rdcc->scaled_encode_bits[u] = H5VM_log2_gen(rdcc->scaled_power2up[u]);
1161
120
        } /* end for */
1162
59
    }     /* end if */
1163
1164
    /* Compose chunked index info struct */
1165
87
    idx_info.f      = f;
1166
87
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
1167
87
    idx_info.layout = &dset->shared->layout;
1168
1169
    /* Allocate any indexing structures */
1170
87
    if (sc->ops->init && (sc->ops->init)(&idx_info, dset->shared->space, dset->oloc.addr) < 0)
1171
20
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "can't initialize indexing information");
1172
67
    idx_init = true;
1173
1174
    /* Set the number of chunks in dataset, etc. */
1175
67
    if (H5D__chunk_set_info(dset) < 0)
1176
27
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to set # of chunks for dataset");
1177
1178
    /* Set chunk sizes if not done already (during a create operation the construct callback does this) */
1179
40
    if (open_op && (H5D__chunk_set_sizes(dset) < 0))
1180
36
        HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "unable to set chunk sizes");
1181
1182
    /* Check for chunk larger than can be represented in 32-bits encoded as v1 b-tree. We don't allow creation
1183
     * of files with layout version < 5 with 64 bit chunks but we'll try to open them if they exist because
1184
     * they're not disallowed by the file format. */
1185
4
    if (dset->shared->layout.u.chunk.size > (hsize_t)0xffffffff &&
1186
4
        dset->shared->layout.u.chunk.idx_type == H5D_CHUNK_IDX_BTREE)
1187
4
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "chunk size must be < 4GB with v1 b-tree index");
1188
1189
91
done:
1190
91
    if (FAIL == ret_value) {
1191
91
        if (rdcc->slot)
1192
91
            rdcc->slot = H5FL_SEQ_FREE(H5D_rdcc_ent_ptr_t, rdcc->slot);
1193
1194
91
        if (idx_init && sc->ops->dest && (sc->ops->dest)(&idx_info) < 0)
1195
0
            HDONE_ERROR(H5E_DATASET, H5E_CANTFREE, FAIL, "unable to release chunk index info");
1196
91
    }
1197
91
    FUNC_LEAVE_NOAPI(ret_value)
1198
91
} /* end H5D__chunk_init() */
1199
1200
/*-------------------------------------------------------------------------
1201
 * Function:    H5D__chunk_is_space_alloc
1202
 *
1203
 * Purpose:    Query if space is allocated for layout
1204
 *
1205
 * Return:    Non-negative on success/Negative on failure
1206
 *
1207
 *-------------------------------------------------------------------------
1208
 */
1209
bool
1210
H5D__chunk_is_space_alloc(const H5O_storage_t *storage)
1211
0
{
1212
0
    const H5O_storage_chunk_t *sc        = &(storage->u.chunk);
1213
0
    bool                       ret_value = false; /* Return value */
1214
1215
0
    FUNC_ENTER_PACKAGE_NOERR
1216
1217
    /* Sanity checks */
1218
0
    assert(storage);
1219
0
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
1220
1221
    /* Query index layer */
1222
0
    ret_value = (sc->ops->is_space_alloc)(sc);
1223
1224
0
    FUNC_LEAVE_NOAPI(ret_value)
1225
0
} /* end H5D__chunk_is_space_alloc() */
1226
1227
/*-------------------------------------------------------------------------
1228
 * Function:    H5D__chunk_is_data_cached
1229
 *
1230
 * Purpose:     Query if raw data is cached for dataset
1231
 *
1232
 * Return:      Non-negative on success/Negative on failure
1233
 *
1234
 *-------------------------------------------------------------------------
1235
 */
1236
bool
1237
H5D__chunk_is_data_cached(const H5D_shared_t *shared_dset)
1238
0
{
1239
0
    FUNC_ENTER_PACKAGE_NOERR
1240
1241
    /* Sanity checks */
1242
0
    assert(shared_dset);
1243
1244
0
    FUNC_LEAVE_NOAPI(shared_dset->cache.chunk.nused > 0)
1245
0
} /* end H5D__chunk_is_data_cached() */
1246
1247
/*-------------------------------------------------------------------------
1248
 * Function:    H5D__chunk_io_init
1249
 *
1250
 * Purpose:    Performs initialization before any sort of I/O on the raw data
1251
 *
1252
 * Return:    Non-negative on success/Negative on failure
1253
 *
1254
 *-------------------------------------------------------------------------
1255
 */
1256
static herr_t
1257
H5D__chunk_io_init(H5D_io_info_t *io_info, H5D_dset_io_info_t *dinfo)
1258
0
{
1259
0
    const H5D_t     *dataset = dinfo->dset;         /* Local pointer to dataset info */
1260
0
    H5D_chunk_map_t *fm;                            /* Convenience pointer to chunk map */
1261
0
    hssize_t         old_offset[H5O_LAYOUT_NDIMS];  /* Old selection offset */
1262
0
    htri_t           file_space_normalized = false; /* File dataspace was normalized */
1263
0
    unsigned         f_ndims;                       /* The number of dimensions of the file's dataspace */
1264
0
    int              sm_ndims; /* The number of dimensions of the memory buffer's dataspace (signed) */
1265
0
    unsigned         u;        /* Local index variable */
1266
0
    herr_t           ret_value = SUCCEED; /* Return value        */
1267
1268
0
    FUNC_ENTER_PACKAGE
1269
1270
    /* Allocate chunk map */
1271
0
    if (NULL == (dinfo->layout_io_info.chunk_map = H5FL_MALLOC(H5D_chunk_map_t)))
1272
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTALLOC, FAIL, "unable to allocate chunk map");
1273
0
    fm = dinfo->layout_io_info.chunk_map;
1274
1275
    /* Get layout for dataset */
1276
0
    dinfo->layout = &(dataset->shared->layout);
1277
1278
    /* Initialize "last chunk" information */
1279
0
    fm->last_index      = (hsize_t)-1;
1280
0
    fm->last_piece_info = NULL;
1281
1282
    /* Clear other fields */
1283
0
    fm->mchunk_tmpl       = NULL;
1284
0
    fm->dset_sel_pieces   = NULL;
1285
0
    fm->single_space      = NULL;
1286
0
    fm->single_piece_info = NULL;
1287
1288
    /* Initialize selection type in memory and file */
1289
0
    fm->msel_type = H5S_SEL_ERROR;
1290
0
    fm->fsel_type = H5S_SEL_ERROR;
1291
1292
    /* Check if the memory space is scalar & make equivalent memory space */
1293
0
    if ((sm_ndims = H5S_GET_EXTENT_NDIMS(dinfo->mem_space)) < 0)
1294
0
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "unable to get dimension number");
1295
    /* Set the number of dimensions for the memory dataspace */
1296
0
    H5_CHECKED_ASSIGN(fm->m_ndims, unsigned, sm_ndims, int);
1297
1298
    /* Get rank for file dataspace */
1299
0
    fm->f_ndims = f_ndims = dataset->shared->layout.u.chunk.ndims - 1;
1300
1301
    /* Normalize hyperslab selections by adjusting them by the offset */
1302
    /* (It might be worthwhile to normalize both the file and memory dataspaces
1303
     * before any (contiguous, chunked, etc) file I/O operation, in order to
1304
     * speed up hyperslab calculations by removing the extra checks and/or
1305
     * additions involving the offset and the hyperslab selection -QAK)
1306
     */
1307
0
    if ((file_space_normalized = H5S_hyper_normalize_offset(dinfo->file_space, old_offset)) < 0)
1308
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTSET, FAIL, "unable to normalize selection");
1309
1310
    /* Decide the number of chunks in each dimension */
1311
0
    for (u = 0; u < f_ndims; u++)
1312
        /* Keep the size of the chunk dimensions as hsize_t for various routines */
1313
0
        fm->chunk_dim[u] = dinfo->layout->u.chunk.dim[u];
1314
1315
0
    if (H5D__chunk_io_init_selections(io_info, dinfo) < 0)
1316
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to create file and memory chunk selections");
1317
1318
    /* Check if we're performing selection I/O and save the result if it hasn't
1319
     * been disabled already */
1320
0
    if (io_info->use_select_io != H5D_SELECTION_IO_MODE_OFF)
1321
0
        if (H5D__chunk_may_use_select_io(io_info, dinfo) < 0)
1322
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't check if selection I/O is possible");
1323
1324
    /* Calculate type conversion buffer size if necessary.  Currently only implemented for selection I/O. */
1325
0
    if (io_info->use_select_io != H5D_SELECTION_IO_MODE_OFF &&
1326
0
        !(dinfo->type_info.is_xform_noop && dinfo->type_info.is_conv_noop)) {
1327
0
        H5SL_node_t *chunk_node; /* Current node in chunk skip list */
1328
1329
        /* Iterate through nodes in chunk skip list */
1330
0
        chunk_node = H5D_CHUNK_GET_FIRST_NODE(dinfo);
1331
0
        while (chunk_node) {
1332
0
            H5D_piece_info_t *piece_info; /* Chunk information */
1333
1334
            /* Get the actual chunk information from the skip list node */
1335
0
            piece_info = H5D_CHUNK_GET_NODE_INFO(dinfo, chunk_node);
1336
1337
            /* Handle type conversion buffer */
1338
0
            H5D_INIT_PIECE_TCONV(io_info, dinfo, piece_info)
1339
1340
            /* Advance to next chunk in list */
1341
0
            chunk_node = H5D_CHUNK_GET_NEXT_NODE(dinfo, chunk_node);
1342
0
        }
1343
0
    }
1344
1345
#ifdef H5_HAVE_PARALLEL
1346
    /*
1347
     * If collective metadata reads are enabled, ensure all ranks
1348
     * have the dataset's chunk index open (if it was created) to
1349
     * prevent possible metadata inconsistency issues or unintentional
1350
     * independent metadata reads later on.
1351
     */
1352
    if (H5F_SHARED_HAS_FEATURE(io_info->f_sh, H5FD_FEAT_HAS_MPI) &&
1353
        H5F_shared_get_coll_metadata_reads(io_info->f_sh) &&
1354
        H5D__chunk_is_space_alloc(&dataset->shared->layout.storage)) {
1355
        H5O_storage_chunk_t *sc = &(dataset->shared->layout.storage.u.chunk);
1356
        H5D_chk_idx_info_t   idx_info;
1357
        bool                 index_is_open;
1358
1359
        idx_info.f      = dataset->oloc.file;
1360
        idx_info.pline  = &dataset->shared->dcpl_cache.pline;
1361
        idx_info.layout = &dataset->shared->layout;
1362
1363
        assert(sc && sc->ops && sc->ops->is_open);
1364
        if (sc->ops->is_open(&idx_info, &index_is_open) < 0)
1365
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "unable to check if dataset chunk index is open");
1366
1367
        if (!index_is_open) {
1368
            assert(sc->ops->open);
1369
            if (sc->ops->open(&idx_info) < 0)
1370
                HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to open dataset chunk index");
1371
        }
1372
1373
        /*
1374
         * Load any other chunk index metadata that we can,
1375
         * such as fixed array data blocks, while we know all
1376
         * MPI ranks will do so with collective metadata reads
1377
         * enabled
1378
         */
1379
        if (sc->ops->load_metadata && sc->ops->load_metadata(&idx_info) < 0)
1380
            HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to load additional chunk index metadata");
1381
    }
1382
#endif
1383
1384
0
done:
1385
0
    if (file_space_normalized == true)
1386
0
        if (H5S_hyper_denormalize_offset(dinfo->file_space, old_offset) < 0)
1387
0
            HDONE_ERROR(H5E_DATASET, H5E_CANTSET, FAIL, "can't denormalize selection");
1388
1389
0
    FUNC_LEAVE_NOAPI(ret_value)
1390
0
} /* end H5D__chunk_io_init() */
1391
1392
/*-------------------------------------------------------------------------
1393
 * Function:    H5D__chunk_io_init_selections
1394
 *
1395
 * Purpose:        Initialize the chunk mappings
1396
 *
1397
 * Return:        Non-negative on success/Negative on failure
1398
 *
1399
 *-------------------------------------------------------------------------
1400
 */
1401
static herr_t
1402
H5D__chunk_io_init_selections(H5D_io_info_t *io_info, H5D_dset_io_info_t *dinfo)
1403
0
{
1404
0
    H5D_chunk_map_t   *fm;                 /* Convenience pointer to chunk map */
1405
0
    const H5D_t       *dataset;            /* Local pointer to dataset info */
1406
0
    const H5T_t       *mem_type;           /* Local pointer to memory datatype */
1407
0
    H5S_t             *tmp_mspace = NULL;  /* Temporary memory dataspace */
1408
0
    bool               iter_init  = false; /* Selection iteration info has been initialized */
1409
0
    char               bogus;              /* "bogus" buffer to pass to selection iterator */
1410
0
    H5D_io_info_wrap_t io_info_wrap;
1411
0
    herr_t             ret_value = SUCCEED; /* Return value        */
1412
1413
0
    FUNC_ENTER_PACKAGE
1414
1415
0
    assert(io_info);
1416
0
    assert(dinfo);
1417
1418
    /* Set convenience pointers */
1419
0
    fm = dinfo->layout_io_info.chunk_map;
1420
0
    assert(fm);
1421
0
    dataset  = dinfo->dset;
1422
0
    mem_type = dinfo->type_info.mem_type;
1423
1424
    /* Special case for only one element in selection */
1425
    /* (usually appending a record) */
1426
0
    if (dinfo->nelmts == 1
1427
#ifdef H5_HAVE_PARALLEL
1428
        && !(io_info->using_mpi_vfd)
1429
#endif /* H5_HAVE_PARALLEL */
1430
0
        && H5S_SEL_ALL != H5S_GET_SELECT_TYPE(dinfo->file_space)) {
1431
        /* Initialize skip list for chunk selections */
1432
0
        fm->use_single = true;
1433
1434
        /* Initialize single chunk dataspace */
1435
0
        if (NULL == dataset->shared->cache.chunk.single_space) {
1436
            /* Make a copy of the dataspace for the dataset */
1437
0
            if ((dataset->shared->cache.chunk.single_space = H5S_copy(dinfo->file_space, true, false)) ==
1438
0
                NULL)
1439
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "unable to copy file space");
1440
1441
            /* Resize chunk's dataspace dimensions to size of chunk */
1442
0
            if (H5S_set_extent_real(dataset->shared->cache.chunk.single_space, fm->chunk_dim) < 0)
1443
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSET, FAIL, "can't adjust chunk dimensions");
1444
1445
            /* Set the single chunk dataspace to 'all' selection */
1446
0
            if (H5S_select_all(dataset->shared->cache.chunk.single_space, true) < 0)
1447
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTSELECT, FAIL, "unable to set all selection");
1448
0
        } /* end if */
1449
0
        fm->single_space = dataset->shared->cache.chunk.single_space;
1450
0
        assert(fm->single_space);
1451
1452
        /* Allocate the single chunk information */
1453
0
        if (NULL == dataset->shared->cache.chunk.single_piece_info)
1454
0
            if (NULL == (dataset->shared->cache.chunk.single_piece_info = H5FL_MALLOC(H5D_piece_info_t)))
1455
0
                HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "can't allocate chunk info");
1456
0
        fm->single_piece_info = dataset->shared->cache.chunk.single_piece_info;
1457
0
        assert(fm->single_piece_info);
1458
1459
        /* Reset chunk template information */
1460
0
        fm->mchunk_tmpl = NULL;
1461
1462
        /* Set up chunk mapping for single element */
1463
0
        if (H5D__create_piece_map_single(dinfo, io_info) < 0)
1464
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL,
1465
0
                        "unable to create chunk selections for single element");
1466
0
    } /* end if */
1467
0
    else {
1468
0
        bool sel_hyper_flag; /* Whether file selection is a hyperslab */
1469
1470
        /* Initialize skip list for chunk selections */
1471
0
        if (NULL == dataset->shared->cache.chunk.sel_chunks)
1472
0
            if (NULL == (dataset->shared->cache.chunk.sel_chunks = H5SL_create(H5SL_TYPE_HSIZE, NULL)))
1473
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTCREATE, FAIL, "can't create skip list for chunk selections");
1474
0
        fm->dset_sel_pieces = dataset->shared->cache.chunk.sel_chunks;
1475
0
        assert(fm->dset_sel_pieces);
1476
1477
        /* We are not using single element mode */
1478
0
        fm->use_single = false;
1479
1480
        /* Get type of selection on disk & in memory */
1481
0
        if ((fm->fsel_type = H5S_GET_SELECT_TYPE(dinfo->file_space)) < H5S_SEL_NONE)
1482
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADSELECT, FAIL, "unable to get type of selection");
1483
0
        if ((fm->msel_type = H5S_GET_SELECT_TYPE(dinfo->mem_space)) < H5S_SEL_NONE)
1484
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADSELECT, FAIL, "unable to get type of selection");
1485
1486
        /* If the selection is NONE or POINTS, set the flag to false */
1487
0
        if (fm->fsel_type == H5S_SEL_POINTS || fm->fsel_type == H5S_SEL_NONE)
1488
0
            sel_hyper_flag = false;
1489
0
        else
1490
0
            sel_hyper_flag = true;
1491
1492
        /* Check if file selection is a not a hyperslab selection */
1493
0
        if (sel_hyper_flag) {
1494
            /* Build the file selection for each chunk */
1495
0
            if (H5S_SEL_ALL == fm->fsel_type) {
1496
0
                if (H5D__create_piece_file_map_all(dinfo, io_info) < 0)
1497
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to create file chunk selections");
1498
0
            } /* end if */
1499
0
            else {
1500
                /* Sanity check */
1501
0
                assert(fm->fsel_type == H5S_SEL_HYPERSLABS);
1502
1503
0
                if (H5D__create_piece_file_map_hyper(dinfo, io_info) < 0)
1504
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to create file chunk selections");
1505
0
            } /* end else */
1506
0
        }     /* end if */
1507
0
        else {
1508
0
            H5S_sel_iter_op_t iter_op; /* Operator for iteration */
1509
1510
            /* set opdata for H5D__piece_mem_cb */
1511
0
            io_info_wrap.io_info = io_info;
1512
0
            io_info_wrap.dinfo   = dinfo;
1513
0
            iter_op.op_type      = H5S_SEL_ITER_OP_LIB;
1514
0
            iter_op.u.lib_op     = H5D__piece_file_cb;
1515
1516
            /* Spaces might not be the same shape, iterate over the file selection directly */
1517
0
            if (H5S_select_iterate(&bogus, dataset->shared->type, dinfo->file_space, &iter_op,
1518
0
                                   &io_info_wrap) < 0)
1519
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to create file chunk selections");
1520
1521
            /* Reset "last piece" info */
1522
0
            fm->last_index      = (hsize_t)-1;
1523
0
            fm->last_piece_info = NULL;
1524
0
        } /* end else */
1525
1526
        /* Build the memory selection for each chunk */
1527
0
        if (sel_hyper_flag && H5S_SELECT_SHAPE_SAME(dinfo->file_space, dinfo->mem_space) == true) {
1528
            /* Reset chunk template information */
1529
0
            fm->mchunk_tmpl = NULL;
1530
1531
            /* If the selections are the same shape, use the file chunk
1532
             * information to generate the memory chunk information quickly.
1533
             */
1534
0
            if (H5D__create_piece_mem_map_hyper(dinfo) < 0)
1535
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to create memory chunk selections");
1536
0
        } /* end if */
1537
0
        else if (sel_hyper_flag && fm->f_ndims == 1 && fm->m_ndims == 1 &&
1538
0
                 H5S_SELECT_IS_REGULAR(dinfo->mem_space) && H5S_SELECT_IS_SINGLE(dinfo->mem_space)) {
1539
0
            if (H5D__create_piece_mem_map_1d(dinfo) < 0)
1540
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to create file chunk selections");
1541
0
        } /* end else-if */
1542
0
        else {
1543
0
            H5S_sel_iter_op_t iter_op;   /* Operator for iteration */
1544
0
            size_t            elmt_size; /* Memory datatype size */
1545
1546
            /* Make a copy of equivalent memory space */
1547
0
            if ((tmp_mspace = H5S_copy(dinfo->mem_space, true, false)) == NULL)
1548
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "unable to copy memory space");
1549
1550
            /* De-select the mem space copy */
1551
0
            if (H5S_select_none(tmp_mspace) < 0)
1552
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to de-select memory space");
1553
1554
            /* Save chunk template information */
1555
0
            fm->mchunk_tmpl = tmp_mspace;
1556
1557
            /* Create selection iterator for memory selection */
1558
0
            if (0 == (elmt_size = H5T_get_size(mem_type)))
1559
0
                HGOTO_ERROR(H5E_DATATYPE, H5E_BADSIZE, FAIL, "datatype size invalid");
1560
0
            if (H5S_select_iter_init(&(fm->mem_iter), dinfo->mem_space, elmt_size, 0) < 0)
1561
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to initialize selection iterator");
1562
0
            iter_init = true; /* Selection iteration info has been initialized */
1563
1564
            /* set opdata for H5D__piece_mem_cb */
1565
0
            io_info_wrap.io_info = io_info;
1566
0
            io_info_wrap.dinfo   = dinfo;
1567
0
            iter_op.op_type      = H5S_SEL_ITER_OP_LIB;
1568
0
            iter_op.u.lib_op     = H5D__piece_mem_cb;
1569
1570
            /* Spaces aren't the same shape, iterate over the memory selection directly */
1571
0
            if (H5S_select_iterate(&bogus, dataset->shared->type, dinfo->file_space, &iter_op,
1572
0
                                   &io_info_wrap) < 0)
1573
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to create memory chunk selections");
1574
0
        } /* end else */
1575
0
    }     /* end else */
1576
1577
0
done:
1578
    /* Release the [potentially partially built] chunk mapping information if an error occurs */
1579
0
    if (ret_value < 0) {
1580
0
        if (tmp_mspace && !fm->mchunk_tmpl)
1581
0
            if (H5S_close(tmp_mspace) < 0)
1582
0
                HDONE_ERROR(H5E_DATASPACE, H5E_CANTRELEASE, FAIL,
1583
0
                            "can't release memory chunk dataspace template");
1584
0
        if (H5D__chunk_io_term(io_info, dinfo) < 0)
1585
0
            HDONE_ERROR(H5E_DATASPACE, H5E_CANTRELEASE, FAIL, "unable to release chunk mapping");
1586
0
    } /* end if */
1587
1588
0
    if (iter_init && H5S_SELECT_ITER_RELEASE(&(fm->mem_iter)) < 0)
1589
0
        HDONE_ERROR(H5E_DATASPACE, H5E_CANTRELEASE, FAIL, "unable to release selection iterator");
1590
1591
0
    FUNC_LEAVE_NOAPI(ret_value)
1592
0
} /* end H5D__chunk_io_init_selections() */
1593
1594
/*-------------------------------------------------------------------------
1595
 * Function:    H5D__chunk_mem_alloc
1596
 *
1597
 * Purpose:    Allocate space for a chunk in memory.  This routine allocates
1598
 *              memory space for non-filtered chunks from a block free list
1599
 *              and uses malloc()/free() for filtered chunks.
1600
 *
1601
 * Return:    Pointer to memory for chunk on success/NULL on failure
1602
 *
1603
 *-------------------------------------------------------------------------
1604
 */
1605
void *
1606
H5D__chunk_mem_alloc(size_t size, void *pline)
1607
0
{
1608
0
    H5O_pline_t *_pline    = (H5O_pline_t *)pline;
1609
0
    void        *ret_value = NULL; /* Return value */
1610
1611
0
    FUNC_ENTER_PACKAGE_NOERR
1612
1613
0
    assert(size);
1614
1615
0
    if (_pline && _pline->nused)
1616
0
        ret_value = H5MM_malloc(size);
1617
0
    else
1618
0
        ret_value = H5FL_BLK_MALLOC(chunk, size);
1619
1620
0
    FUNC_LEAVE_NOAPI(ret_value)
1621
0
} /* H5D__chunk_mem_alloc() */
1622
1623
/*-------------------------------------------------------------------------
1624
 * Function:    H5D__chunk_mem_xfree
1625
 *
1626
 * Purpose:    Free space for a chunk in memory.  This routine releases
1627
 *              memory space for non-filtered chunks from a block free list
1628
 *              and uses malloc()/free() for filtered chunks.
1629
 *
1630
 * Return:    NULL (never fails)
1631
 *
1632
 *-------------------------------------------------------------------------
1633
 */
1634
void *
1635
H5D__chunk_mem_xfree(void *chk, const void *pline)
1636
0
{
1637
0
    const H5O_pline_t *_pline = (const H5O_pline_t *)pline;
1638
1639
0
    FUNC_ENTER_PACKAGE_NOERR
1640
1641
0
    if (chk) {
1642
0
        if (_pline && _pline->nused)
1643
0
            H5MM_xfree(chk);
1644
0
        else
1645
0
            chk = H5FL_BLK_FREE(chunk, chk);
1646
0
    } /* end if */
1647
1648
0
    FUNC_LEAVE_NOAPI(NULL)
1649
0
} /* H5D__chunk_mem_xfree() */
1650
1651
/*-------------------------------------------------------------------------
1652
 * Function:    H5D__chunk_mem_free
1653
 *
1654
 * Purpose:    Wrapper with H5MM_free_t-compatible signature that just
1655
 *             calls H5D__chunk_mem_xfree and discards the return value.
1656
 *-------------------------------------------------------------------------
1657
 */
1658
void
1659
H5D__chunk_mem_free(void *chk, void *pline)
1660
0
{
1661
0
    FUNC_ENTER_PACKAGE_NAMECHECK_ONLY
1662
1663
0
    H5D__chunk_mem_xfree(chk, pline);
1664
1665
0
    FUNC_LEAVE_NOAPI_VOID_NAMECHECK_ONLY
1666
0
}
1667
1668
/*-------------------------------------------------------------------------
1669
 * Function:    H5D__chunk_mem_realloc
1670
 *
1671
 * Purpose:     Reallocate space for a chunk in memory.  This routine allocates
1672
 *              memory space for non-filtered chunks from a block free list
1673
 *              and uses malloc()/free() for filtered chunks.
1674
 *
1675
 * Return:      Pointer to memory for chunk on success/NULL on failure
1676
 *
1677
 *-------------------------------------------------------------------------
1678
 */
1679
void *
1680
H5D__chunk_mem_realloc(void *chk, size_t size, const H5O_pline_t *pline)
1681
0
{
1682
0
    void *ret_value = NULL; /* Return value */
1683
1684
0
    FUNC_ENTER_PACKAGE_NOERR
1685
1686
0
    assert(size);
1687
0
    assert(pline);
1688
1689
0
    if (pline->nused > 0)
1690
0
        ret_value = H5MM_realloc(chk, size);
1691
0
    else
1692
0
        ret_value = H5FL_BLK_REALLOC(chunk, chk, size);
1693
1694
0
    FUNC_LEAVE_NOAPI(ret_value)
1695
0
} /* H5D__chunk_mem_realloc() */
1696
1697
/*--------------------------------------------------------------------------
1698
 NAME
1699
    H5D__free_piece_info
1700
 PURPOSE
1701
    Performs initialization before any sort of I/O on the raw data
1702
    This was derived from H5D__free_chunk_info for multi-dset work.
1703
 USAGE
1704
    herr_t H5D__free_piece_info(chunk_info, key, opdata)
1705
        void *chunk_info;    IN: Pointer to chunk info to destroy
1706
        void *key;           Unused
1707
        void *opdata;        Unused
1708
 RETURNS
1709
    Non-negative on success, negative on failure
1710
 DESCRIPTION
1711
    Releases all the memory for a chunk info node.  Called by H5SL_free
1712
 GLOBAL VARIABLES
1713
 COMMENTS, BUGS, ASSUMPTIONS
1714
 EXAMPLES
1715
 REVISION LOG
1716
--------------------------------------------------------------------------*/
1717
herr_t
1718
H5D__free_piece_info(void *item, void H5_ATTR_UNUSED *key, void H5_ATTR_UNUSED *opdata)
1719
392
{
1720
392
    H5D_piece_info_t *piece_info = (H5D_piece_info_t *)item;
1721
1722
392
    FUNC_ENTER_PACKAGE_NOERR
1723
1724
392
    assert(piece_info);
1725
1726
    /* Close the piece's file dataspace, if it's not shared */
1727
392
    if (!piece_info->fspace_shared)
1728
392
        (void)H5S_close(piece_info->fspace);
1729
0
    else
1730
0
        H5S_select_all(piece_info->fspace, true);
1731
1732
    /* Close the piece's memory dataspace, if it's not shared */
1733
392
    if (!piece_info->mspace_shared && piece_info->mspace)
1734
0
        (void)H5S_close((H5S_t *)piece_info->mspace);
1735
1736
    /* Free the actual piece info */
1737
392
    piece_info = H5FL_FREE(H5D_piece_info_t, piece_info);
1738
1739
392
    FUNC_LEAVE_NOAPI(0)
1740
392
} /* H5D__free_piece_info() */
1741
1742
/*-------------------------------------------------------------------------
1743
 * Function:    H5D__create_piece_map_single
1744
 *
1745
 * Purpose:    Create piece selections when appending a single record
1746
 *             This was derived from H5D__create_chunk_map_single for
1747
 *             multi-dset work.
1748
 *
1749
 * Return:    Non-negative on success/Negative on failure
1750
 *
1751
 *-------------------------------------------------------------------------
1752
 */
1753
static herr_t
1754
H5D__create_piece_map_single(H5D_dset_io_info_t *di, H5D_io_info_t *io_info)
1755
0
{
1756
0
    H5D_chunk_map_t  *fm;                          /* Convenience pointer to chunk map */
1757
0
    H5D_piece_info_t *piece_info;                  /* Piece information to insert into skip list */
1758
0
    hsize_t           coords[H5O_LAYOUT_NDIMS];    /* Coordinates of chunk */
1759
0
    hsize_t           sel_start[H5O_LAYOUT_NDIMS]; /* Offset of low bound of file selection */
1760
0
    hsize_t           sel_end[H5O_LAYOUT_NDIMS];   /* Offset of high bound of file selection */
1761
0
    unsigned          u;                           /* Local index variable */
1762
0
    herr_t            ret_value = SUCCEED;         /* Return value */
1763
1764
0
    FUNC_ENTER_PACKAGE
1765
1766
    /* Set convenience pointer */
1767
0
    fm = di->layout_io_info.chunk_map;
1768
1769
    /* Sanity checks */
1770
0
    assert(fm);
1771
0
    assert(fm->f_ndims > 0);
1772
1773
    /* Get coordinate for selection */
1774
0
    if (H5S_SELECT_BOUNDS(di->file_space, sel_start, sel_end) < 0)
1775
0
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "can't get file selection bound info");
1776
1777
    /* Initialize the 'single piece' file & memory piece information */
1778
0
    piece_info               = fm->single_piece_info;
1779
0
    piece_info->piece_points = 1;
1780
1781
    /* Set chunk location & hyperslab size */
1782
0
    for (u = 0; u < fm->f_ndims; u++) {
1783
        /* Validate this chunk dimension */
1784
0
        if (di->layout->u.chunk.dim[u] == 0)
1785
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "chunk size must be > 0, dim = %u ", u);
1786
0
        assert(sel_start[u] == sel_end[u]);
1787
0
        piece_info->scaled[u] = sel_start[u] / di->layout->u.chunk.dim[u];
1788
0
        coords[u]             = piece_info->scaled[u] * di->layout->u.chunk.dim[u];
1789
0
    } /* end for */
1790
0
    piece_info->scaled[fm->f_ndims] = 0;
1791
1792
    /* Calculate the index of this chunk */
1793
0
    piece_info->index =
1794
0
        H5VM_array_offset_pre(fm->f_ndims, di->layout->u.chunk.down_chunks, piece_info->scaled);
1795
1796
    /* Copy selection for file's dataspace into chunk dataspace */
1797
0
    if (H5S_select_copy(fm->single_space, di->file_space, false) < 0)
1798
0
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "unable to copy file selection");
1799
1800
    /* Move selection back to have correct offset in chunk */
1801
0
    if (H5S_SELECT_ADJUST_U(fm->single_space, coords) < 0)
1802
0
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't adjust chunk selection");
1803
1804
    /* Set the file dataspace for the chunk to the shared 'single' dataspace */
1805
0
    piece_info->fspace = fm->single_space;
1806
1807
    /* Indicate that the chunk's file dataspace is shared */
1808
0
    piece_info->fspace_shared = true;
1809
1810
    /* Just point at the memory dataspace & selection */
1811
0
    piece_info->mspace = di->mem_space;
1812
1813
    /* Indicate that the chunk's memory dataspace is shared */
1814
0
    piece_info->mspace_shared = true;
1815
1816
    /* Initialize in-place type conversion info. Start with it disabled. */
1817
0
    piece_info->in_place_tconv = false;
1818
0
    piece_info->buf_off        = 0;
1819
1820
    /* Check if chunk is in a dataset with filters applied */
1821
0
    piece_info->filtered_dset = di->dset->shared->dcpl_cache.pline.nused > 0;
1822
1823
    /* make connection to related dset info from this piece_info */
1824
0
    piece_info->dset_info = di;
1825
1826
    /* Add piece to global piece_count */
1827
0
    io_info->piece_count++;
1828
1829
0
done:
1830
0
    FUNC_LEAVE_NOAPI(ret_value)
1831
0
} /* end H5D__create_piece_map_single() */
1832
1833
/*-------------------------------------------------------------------------
1834
 * Function:    H5D__create_piece_file_map_all
1835
 *
1836
 * Purpose:    Create all chunk selections in file, for an "all" selection.
1837
 *
1838
 * Return:    Non-negative on success/Negative on failure
1839
 *
1840
 *-------------------------------------------------------------------------
1841
 */
1842
static herr_t
1843
H5D__create_piece_file_map_all(H5D_dset_io_info_t *di, H5D_io_info_t *io_info)
1844
0
{
1845
0
    H5D_chunk_map_t *fm;                      /* Convenience pointer to chunk map */
1846
0
    H5S_t           *tmp_fchunk = NULL;       /* Temporary file dataspace */
1847
0
    hsize_t          file_dims[H5S_MAX_RANK]; /* File dataspace dims */
1848
0
    hsize_t          sel_points;              /* Number of elements in file selection */
1849
0
    hsize_t zeros[H5S_MAX_RANK];   /* All zero vector (for start parameter to setting hyperslab on partial
1850
                                      chunks) */
1851
0
    hsize_t  coords[H5S_MAX_RANK]; /* Current coordinates of chunk */
1852
0
    hsize_t  end[H5S_MAX_RANK];    /* Final coordinates of chunk */
1853
0
    hsize_t  scaled[H5S_MAX_RANK]; /* Scaled coordinates for this chunk */
1854
0
    hsize_t  chunk_index;          /* "Index" of chunk */
1855
0
    hsize_t  curr_partial_clip[H5S_MAX_RANK]; /* Current partial dimension sizes to clip against */
1856
0
    hsize_t  partial_dim_size[H5S_MAX_RANK];  /* Size of a partial dimension */
1857
0
    bool     is_partial_dim[H5S_MAX_RANK];    /* Whether a dimension is currently a partial chunk */
1858
0
    bool     filtered_dataset;                /* Whether the dataset in question has filters applied */
1859
0
    unsigned num_partial_dims;                /* Current number of partial dimensions */
1860
0
    unsigned u;                               /* Local index variable */
1861
0
    herr_t   ret_value = SUCCEED;             /* Return value */
1862
1863
0
    FUNC_ENTER_PACKAGE
1864
1865
    /* Set convenience pointer */
1866
0
    fm = di->layout_io_info.chunk_map;
1867
1868
    /* Sanity checks */
1869
0
    assert(fm);
1870
0
    assert(fm->f_ndims > 0);
1871
1872
    /* Get number of elements selected in file */
1873
0
    sel_points = di->nelmts;
1874
1875
    /* Get dataspace dimensions */
1876
0
    if (H5S_get_simple_extent_dims(di->file_space, file_dims, NULL) < 0)
1877
0
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "can't get file selection bound info");
1878
1879
    /* Set initial chunk location, partial dimensions, etc */
1880
0
    num_partial_dims = 0;
1881
0
    memset(zeros, 0, sizeof(zeros));
1882
0
    for (u = 0; u < fm->f_ndims; u++) {
1883
        /* Validate this chunk dimension */
1884
0
        if (di->layout->u.chunk.dim[u] == 0)
1885
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "chunk size must be > 0, dim = %u ", u);
1886
1887
        /* Set up start / end coordinates for first chunk */
1888
0
        scaled[u] = 0;
1889
0
        coords[u] = 0;
1890
0
        end[u]    = fm->chunk_dim[u] - 1;
1891
1892
        /* Initialize partial chunk dimension information */
1893
0
        partial_dim_size[u] = file_dims[u] % fm->chunk_dim[u];
1894
0
        if (file_dims[u] < fm->chunk_dim[u]) {
1895
0
            curr_partial_clip[u] = partial_dim_size[u];
1896
0
            is_partial_dim[u]    = true;
1897
0
            num_partial_dims++;
1898
0
        } /* end if */
1899
0
        else {
1900
0
            curr_partial_clip[u] = fm->chunk_dim[u];
1901
0
            is_partial_dim[u]    = false;
1902
0
        } /* end else */
1903
0
    }     /* end for */
1904
1905
    /* Set the index of this chunk */
1906
0
    chunk_index = 0;
1907
1908
    /* Check whether dataset has filters applied */
1909
0
    filtered_dataset = di->dset->shared->dcpl_cache.pline.nused > 0;
1910
1911
    /* Create "temporary" chunk for selection operations (copy file space) */
1912
0
    if (NULL == (tmp_fchunk = H5S_create_simple(fm->f_ndims, fm->chunk_dim, NULL)))
1913
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTCREATE, FAIL, "unable to create dataspace for chunk");
1914
1915
    /* Iterate through each chunk in the dataset */
1916
0
    while (sel_points) {
1917
0
        H5D_piece_info_t *new_piece_info; /* Piece information to insert into skip list */
1918
0
        hsize_t           chunk_points;   /* Number of elements in chunk selection */
1919
1920
        /* Add temporary chunk to the list of pieces */
1921
1922
        /* Allocate the file & memory chunk information */
1923
0
        if (NULL == (new_piece_info = H5FL_MALLOC(H5D_piece_info_t)))
1924
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTALLOC, FAIL, "can't allocate piece info");
1925
1926
        /* Initialize the chunk information */
1927
1928
        /* Set the chunk index */
1929
0
        new_piece_info->index = chunk_index;
1930
1931
        /* Set the file chunk dataspace */
1932
0
        if (NULL == (new_piece_info->fspace = H5S_copy(tmp_fchunk, true, false)))
1933
0
            HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "unable to copy chunk dataspace");
1934
0
        new_piece_info->fspace_shared = false;
1935
1936
        /* If there are partial dimensions for this chunk, set the hyperslab for them */
1937
0
        if (num_partial_dims > 0)
1938
0
            if (H5S_select_hyperslab(new_piece_info->fspace, H5S_SELECT_SET, zeros, NULL, curr_partial_clip,
1939
0
                                     NULL) < 0)
1940
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTSELECT, FAIL, "can't create chunk selection");
1941
1942
        /* Set the memory chunk dataspace */
1943
0
        new_piece_info->mspace        = NULL;
1944
0
        new_piece_info->mspace_shared = false;
1945
1946
        /* Copy the chunk's scaled coordinates */
1947
0
        H5MM_memcpy(new_piece_info->scaled, scaled, sizeof(hsize_t) * fm->f_ndims);
1948
0
        new_piece_info->scaled[fm->f_ndims] = 0;
1949
1950
        /* make connection to related dset info from this piece_info */
1951
0
        new_piece_info->dset_info = di;
1952
1953
        /* Initialize in-place type conversion info. Start with it disabled. */
1954
0
        new_piece_info->in_place_tconv = false;
1955
0
        new_piece_info->buf_off        = 0;
1956
1957
0
        new_piece_info->filtered_dset = filtered_dataset;
1958
1959
        /* Insert the new chunk into the skip list */
1960
0
        if (H5SL_insert(fm->dset_sel_pieces, new_piece_info, &new_piece_info->index) < 0) {
1961
0
            H5D__free_piece_info(new_piece_info, NULL, NULL);
1962
0
            HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't insert chunk into skip list");
1963
0
        } /* end if */
1964
1965
        /* Add piece to global piece_count*/
1966
0
        io_info->piece_count++;
1967
1968
        /* Get number of elements selected in chunk */
1969
0
        chunk_points                 = H5S_GET_SELECT_NPOINTS(new_piece_info->fspace);
1970
0
        new_piece_info->piece_points = chunk_points;
1971
1972
        /* Decrement # of points left in file selection */
1973
0
        sel_points -= chunk_points;
1974
1975
        /* Advance to next chunk if we are not done */
1976
0
        if (sel_points > 0) {
1977
0
            int curr_dim; /* Current dimension to increment */
1978
1979
            /* Increment chunk index */
1980
0
            chunk_index++;
1981
1982
            /* Set current increment dimension */
1983
0
            curr_dim = (int)fm->f_ndims - 1;
1984
1985
            /* Increment chunk location in fastest changing dimension */
1986
0
            coords[curr_dim] += fm->chunk_dim[curr_dim];
1987
0
            scaled[curr_dim]++;
1988
0
            end[curr_dim] += fm->chunk_dim[curr_dim];
1989
1990
            /* Bring chunk location back into bounds, if necessary */
1991
0
            if (coords[curr_dim] >= file_dims[curr_dim]) {
1992
0
                do {
1993
                    /* Reset current dimension's location to 0 */
1994
0
                    coords[curr_dim] = 0;
1995
0
                    scaled[curr_dim] = 0;
1996
0
                    end[curr_dim]    = fm->chunk_dim[curr_dim] - 1;
1997
1998
                    /* Check for previous partial chunk in this dimension */
1999
0
                    if (is_partial_dim[curr_dim] && end[curr_dim] < file_dims[curr_dim]) {
2000
                        /* Sanity check */
2001
0
                        assert(num_partial_dims > 0);
2002
2003
                        /* Reset partial chunk information for this dimension */
2004
0
                        curr_partial_clip[curr_dim] = fm->chunk_dim[curr_dim];
2005
0
                        is_partial_dim[curr_dim]    = false;
2006
0
                        num_partial_dims--;
2007
0
                    } /* end if */
2008
2009
                    /* Decrement current dimension */
2010
0
                    curr_dim--;
2011
2012
                    /* Check for valid current dim */
2013
0
                    if (curr_dim >= 0) {
2014
                        /* Increment chunk location in current dimension */
2015
0
                        coords[curr_dim] += fm->chunk_dim[curr_dim];
2016
0
                        scaled[curr_dim]++;
2017
0
                        end[curr_dim] = (coords[curr_dim] + fm->chunk_dim[curr_dim]) - 1;
2018
0
                    } /* end if */
2019
0
                } while (curr_dim >= 0 && (coords[curr_dim] >= file_dims[curr_dim]));
2020
0
            } /* end if */
2021
2022
            /* Check for valid current dim */
2023
0
            if (curr_dim >= 0) {
2024
                /* Check for partial chunk in this dimension */
2025
0
                if (!is_partial_dim[curr_dim] && file_dims[curr_dim] <= end[curr_dim]) {
2026
                    /* Set partial chunk information for this dimension */
2027
0
                    curr_partial_clip[curr_dim] = partial_dim_size[curr_dim];
2028
0
                    is_partial_dim[curr_dim]    = true;
2029
0
                    num_partial_dims++;
2030
2031
                    /* Sanity check */
2032
0
                    assert(num_partial_dims <= fm->f_ndims);
2033
0
                } /* end if */
2034
0
            }     /* end if */
2035
0
        }         /* end if */
2036
0
    }             /* end while */
2037
2038
0
done:
2039
    /* Clean up */
2040
0
    if (tmp_fchunk && H5S_close(tmp_fchunk) < 0)
2041
0
        HDONE_ERROR(H5E_DATASET, H5E_CANTRELEASE, FAIL, "can't release temporary dataspace");
2042
2043
0
    FUNC_LEAVE_NOAPI(ret_value)
2044
0
} /* end H5D__create_chunk_file_map_all() */
2045
2046
/*-------------------------------------------------------------------------
2047
 * Function:    H5D__create_piece_file_map_hyper
2048
 *
2049
 * Purpose:     Create all chunk selections in file.
2050
 *              This was derived from H5D__create_chunk_file_map_hyper for
2051
 *              multi-dset work.
2052
 *
2053
 * Return:    Non-negative on success/Negative on failure
2054
 *
2055
 *-------------------------------------------------------------------------
2056
 */
2057
static herr_t
2058
H5D__create_piece_file_map_hyper(H5D_dset_io_info_t *dinfo, H5D_io_info_t *io_info)
2059
0
{
2060
0
    H5D_chunk_map_t *fm;                             /* Convenience pointer to chunk map */
2061
0
    H5S_t           *tmp_fchunk = NULL;              /* Temporary file dataspace */
2062
0
    hsize_t          sel_start[H5O_LAYOUT_NDIMS];    /* Offset of low bound of file selection */
2063
0
    hsize_t          sel_end[H5O_LAYOUT_NDIMS];      /* Offset of high bound of file selection */
2064
0
    hsize_t          sel_points;                     /* Number of elements in file selection */
2065
0
    hsize_t          start_coords[H5O_LAYOUT_NDIMS]; /* Starting coordinates of selection */
2066
0
    hsize_t          coords[H5O_LAYOUT_NDIMS];       /* Current coordinates of chunk */
2067
0
    hsize_t          end[H5O_LAYOUT_NDIMS];          /* Final coordinates of chunk */
2068
0
    hsize_t          chunk_index;                    /* Index of chunk */
2069
0
    hsize_t          start_scaled[H5S_MAX_RANK];     /* Starting scaled coordinates of selection */
2070
0
    hsize_t          scaled[H5S_MAX_RANK];           /* Scaled coordinates for this chunk */
2071
0
    bool             filtered_dataset;               /* Whether the dataset in question has filters applied */
2072
0
    int              curr_dim;                       /* Current dimension to increment */
2073
0
    unsigned         u;                              /* Local index variable */
2074
0
    herr_t           ret_value = SUCCEED;            /* Return value */
2075
2076
0
    FUNC_ENTER_PACKAGE
2077
2078
    /* Set convenience pointer */
2079
0
    fm = dinfo->layout_io_info.chunk_map;
2080
2081
    /* Sanity checks */
2082
0
    assert(fm);
2083
0
    assert(fm->f_ndims > 0);
2084
2085
    /* Get number of elements selected in file */
2086
0
    sel_points = dinfo->nelmts;
2087
2088
    /* Get bounding box for selection (to reduce the number of chunks to iterate over) */
2089
0
    if (H5S_SELECT_BOUNDS(dinfo->file_space, sel_start, sel_end) < 0)
2090
0
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "can't get file selection bound info");
2091
2092
    /* Set initial chunk location & hyperslab size */
2093
0
    for (u = 0; u < fm->f_ndims; u++) {
2094
        /* Validate this chunk dimension */
2095
0
        if (dinfo->layout->u.chunk.dim[u] == 0)
2096
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "chunk size must be > 0, dim = %u ", u);
2097
0
        scaled[u] = start_scaled[u] = sel_start[u] / dinfo->layout->u.chunk.dim[u];
2098
0
        coords[u] = start_coords[u] = scaled[u] * dinfo->layout->u.chunk.dim[u];
2099
0
        end[u]                      = (coords[u] + fm->chunk_dim[u]) - 1;
2100
0
    } /* end for */
2101
2102
    /* Calculate the index of this chunk */
2103
0
    chunk_index = H5VM_array_offset_pre(fm->f_ndims, dinfo->layout->u.chunk.down_chunks, scaled);
2104
2105
    /* Check whether dataset has filters applied */
2106
0
    filtered_dataset = dinfo->dset->shared->dcpl_cache.pline.nused > 0;
2107
2108
    /* Iterate through each chunk in the dataset */
2109
0
    while (sel_points) {
2110
        /* Check for intersection of current chunk and file selection */
2111
0
        if (true == H5S_SELECT_INTERSECT_BLOCK(dinfo->file_space, coords, end)) {
2112
0
            H5D_piece_info_t *new_piece_info; /* chunk information to insert into skip list */
2113
0
            hsize_t           chunk_points;   /* Number of elements in chunk selection */
2114
2115
            /* Create dataspace for chunk, 'AND'ing the overall selection with
2116
             *  the current chunk.
2117
             */
2118
0
            if (H5S_combine_hyperslab(dinfo->file_space, H5S_SELECT_AND, coords, NULL, fm->chunk_dim, NULL,
2119
0
                                      &tmp_fchunk) < 0)
2120
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL,
2121
0
                            "unable to combine file space selection with chunk block");
2122
2123
            /* Resize chunk's dataspace dimensions to size of chunk */
2124
0
            if (H5S_set_extent_real(tmp_fchunk, fm->chunk_dim) < 0)
2125
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTSELECT, FAIL, "can't adjust chunk dimensions");
2126
2127
            /* Move selection back to have correct offset in chunk */
2128
0
            if (H5S_SELECT_ADJUST_U(tmp_fchunk, coords) < 0)
2129
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTSELECT, FAIL, "can't adjust chunk selection");
2130
2131
            /* Add temporary chunk to the list of chunks */
2132
2133
            /* Allocate the file & memory chunk information */
2134
0
            if (NULL == (new_piece_info = H5FL_MALLOC(H5D_piece_info_t)))
2135
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTALLOC, FAIL, "can't allocate chunk info");
2136
2137
            /* Initialize the chunk information */
2138
2139
            /* Set the chunk index */
2140
0
            new_piece_info->index = chunk_index;
2141
2142
            /* Set the file chunk dataspace */
2143
0
            new_piece_info->fspace        = tmp_fchunk;
2144
0
            new_piece_info->fspace_shared = false;
2145
0
            tmp_fchunk                    = NULL;
2146
2147
            /* Set the memory chunk dataspace */
2148
0
            new_piece_info->mspace        = NULL;
2149
0
            new_piece_info->mspace_shared = false;
2150
2151
            /* Copy the chunk's scaled coordinates */
2152
0
            H5MM_memcpy(new_piece_info->scaled, scaled, sizeof(hsize_t) * fm->f_ndims);
2153
0
            new_piece_info->scaled[fm->f_ndims] = 0;
2154
2155
            /* make connection to related dset info from this piece_info */
2156
0
            new_piece_info->dset_info = dinfo;
2157
2158
            /* Initialize in-place type conversion info. Start with it disabled. */
2159
0
            new_piece_info->in_place_tconv = false;
2160
0
            new_piece_info->buf_off        = 0;
2161
2162
0
            new_piece_info->filtered_dset = filtered_dataset;
2163
2164
            /* Add piece to global piece_count */
2165
0
            io_info->piece_count++;
2166
2167
            /* Insert the new piece into the skip list */
2168
0
            if (H5SL_insert(fm->dset_sel_pieces, new_piece_info, &new_piece_info->index) < 0) {
2169
0
                H5D__free_piece_info(new_piece_info, NULL, NULL);
2170
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't insert piece into skip list");
2171
0
            } /* end if */
2172
2173
            /* Get number of elements selected in chunk */
2174
0
            chunk_points                 = H5S_GET_SELECT_NPOINTS(new_piece_info->fspace);
2175
0
            new_piece_info->piece_points = chunk_points;
2176
2177
            /* Decrement # of points left in file selection */
2178
0
            sel_points -= chunk_points;
2179
2180
            /* Leave if we are done */
2181
0
            if (sel_points == 0)
2182
0
                HGOTO_DONE(SUCCEED);
2183
0
        } /* end if */
2184
2185
        /* Increment chunk index */
2186
0
        chunk_index++;
2187
2188
        /* Set current increment dimension */
2189
0
        curr_dim = (int)fm->f_ndims - 1;
2190
2191
        /* Increment chunk location in fastest changing dimension */
2192
0
        coords[curr_dim] += fm->chunk_dim[curr_dim];
2193
0
        end[curr_dim] += fm->chunk_dim[curr_dim];
2194
0
        scaled[curr_dim]++;
2195
2196
        /* Bring chunk location back into bounds, if necessary */
2197
0
        if (coords[curr_dim] > sel_end[curr_dim]) {
2198
0
            do {
2199
                /* Reset current dimension's location to 0 */
2200
0
                scaled[curr_dim] = start_scaled[curr_dim];
2201
0
                coords[curr_dim] = start_coords[curr_dim];
2202
0
                end[curr_dim]    = (coords[curr_dim] + fm->chunk_dim[curr_dim]) - 1;
2203
2204
                /* Decrement current dimension */
2205
0
                curr_dim--;
2206
2207
                /* Check for valid current dim */
2208
0
                if (curr_dim >= 0) {
2209
                    /* Increment chunk location in current dimension */
2210
0
                    scaled[curr_dim]++;
2211
0
                    coords[curr_dim] += fm->chunk_dim[curr_dim];
2212
0
                    end[curr_dim] = (coords[curr_dim] + fm->chunk_dim[curr_dim]) - 1;
2213
0
                } /* end if */
2214
0
            } while (curr_dim >= 0 && (coords[curr_dim] > sel_end[curr_dim]));
2215
2216
            /* Re-calculate the index of this chunk */
2217
0
            chunk_index = H5VM_array_offset_pre(fm->f_ndims, dinfo->layout->u.chunk.down_chunks, scaled);
2218
0
        } /* end if */
2219
0
    }     /* end while */
2220
2221
0
done:
2222
    /* Clean up on failure */
2223
0
    if (ret_value < 0)
2224
0
        if (tmp_fchunk && H5S_close(tmp_fchunk) < 0)
2225
0
            HDONE_ERROR(H5E_DATASET, H5E_CANTRELEASE, FAIL, "can't release temporary dataspace");
2226
2227
0
    FUNC_LEAVE_NOAPI(ret_value)
2228
0
} /* end H5D__create_piece_file_map_hyper() */
2229
2230
/*-------------------------------------------------------------------------
2231
 * Function:    H5D__create_piece_mem_map_hyper
2232
 *
2233
 * Purpose:     Create all chunk selections in memory by copying the file
2234
 *              chunk selections and adjusting their offsets to be correct
2235
 *              or the memory.
2236
 *              This was derived from H5D__create_chunk_mem_map_hyper for
2237
 *              multi-dset work.
2238
 *
2239
 * Return:      Non-negative on success/Negative on failure
2240
 *
2241
 * Assumptions: That the file and memory selections are the same shape.
2242
 *-------------------------------------------------------------------------
2243
 */
2244
static herr_t
2245
H5D__create_piece_mem_map_hyper(const H5D_dset_io_info_t *dinfo)
2246
0
{
2247
0
    H5D_chunk_map_t  *fm;                           /* Convenience pointer to chunk map */
2248
0
    H5D_piece_info_t *piece_info;                   /* Pointer to piece information */
2249
0
    H5SL_node_t      *curr_node;                    /* Current node in skip list */
2250
0
    hsize_t           file_sel_start[H5S_MAX_RANK]; /* Offset of low bound of file selection */
2251
0
    hsize_t           file_sel_end[H5S_MAX_RANK];   /* Offset of high bound of file selection */
2252
0
    hsize_t           mem_sel_start[H5S_MAX_RANK];  /* Offset of low bound of file selection */
2253
0
    hsize_t           mem_sel_end[H5S_MAX_RANK];    /* Offset of high bound of file selection */
2254
0
    hssize_t          adjust[H5S_MAX_RANK];         /* Adjustment to make to all file chunks */
2255
0
    unsigned          u;                            /* Local index variable */
2256
0
    herr_t            ret_value = SUCCEED;          /* Return value */
2257
2258
0
    FUNC_ENTER_PACKAGE
2259
2260
    /* Sanity check */
2261
0
    assert(dinfo->layout_io_info.chunk_map->f_ndims > 0);
2262
2263
    /* Set convenience pointer */
2264
0
    fm = dinfo->layout_io_info.chunk_map;
2265
2266
    /* Check for all I/O going to a single chunk */
2267
0
    if (H5SL_count(fm->dset_sel_pieces) == 1) {
2268
        /* Get the node */
2269
0
        curr_node = H5SL_first(fm->dset_sel_pieces);
2270
2271
        /* Get pointer to piece's information */
2272
0
        piece_info = (H5D_piece_info_t *)H5SL_item(curr_node);
2273
0
        assert(piece_info);
2274
2275
        /* Just point at the memory dataspace & selection */
2276
0
        piece_info->mspace = dinfo->mem_space;
2277
2278
        /* Indicate that the piece's memory space is shared */
2279
0
        piece_info->mspace_shared = true;
2280
0
    } /* end if */
2281
0
    else {
2282
        /* Get bounding box for file selection */
2283
0
        if (H5S_SELECT_BOUNDS(dinfo->file_space, file_sel_start, file_sel_end) < 0)
2284
0
            HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "can't get file selection bound info");
2285
2286
        /* Get bounding box for memory selection */
2287
0
        if (H5S_SELECT_BOUNDS(dinfo->mem_space, mem_sel_start, mem_sel_end) < 0)
2288
0
            HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "can't get file selection bound info");
2289
2290
        /* Calculate the adjustment for memory selection from file selection */
2291
0
        assert(fm->m_ndims == fm->f_ndims);
2292
0
        for (u = 0; u < fm->f_ndims; u++) {
2293
0
            H5_CHECK_OVERFLOW(file_sel_start[u], hsize_t, hssize_t);
2294
0
            H5_CHECK_OVERFLOW(mem_sel_start[u], hsize_t, hssize_t);
2295
0
            adjust[u] = (hssize_t)file_sel_start[u] - (hssize_t)mem_sel_start[u];
2296
0
        } /* end for */
2297
2298
        /* Iterate over each chunk in the chunk list */
2299
0
        assert(fm->dset_sel_pieces);
2300
0
        curr_node = H5SL_first(fm->dset_sel_pieces);
2301
0
        while (curr_node) {
2302
0
            hsize_t      coords[H5S_MAX_RANK];       /* Current coordinates of chunk */
2303
0
            hssize_t     piece_adjust[H5S_MAX_RANK]; /* Adjustment to make to a particular chunk */
2304
0
            H5S_sel_type chunk_sel_type;             /* Chunk's selection type */
2305
2306
            /* Get pointer to piece's information */
2307
0
            piece_info = (H5D_piece_info_t *)H5SL_item(curr_node);
2308
0
            assert(piece_info);
2309
2310
            /* Compute the chunk coordinates from the scaled coordinates */
2311
0
            for (u = 0; u < fm->f_ndims; u++)
2312
0
                coords[u] = piece_info->scaled[u] * dinfo->layout->u.chunk.dim[u];
2313
2314
            /* Copy the information */
2315
2316
            /* Copy the memory dataspace */
2317
0
            if ((piece_info->mspace = H5S_copy(dinfo->mem_space, true, false)) == NULL)
2318
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "unable to copy memory space");
2319
2320
            /* Get the chunk's selection type */
2321
0
            if ((chunk_sel_type = H5S_GET_SELECT_TYPE(piece_info->fspace)) < H5S_SEL_NONE)
2322
0
                HGOTO_ERROR(H5E_DATASET, H5E_BADSELECT, FAIL, "unable to get type of selection");
2323
2324
            /* Set memory selection for "all" chunk selections */
2325
0
            if (H5S_SEL_ALL == chunk_sel_type) {
2326
                /* Adjust the chunk coordinates */
2327
0
                for (u = 0; u < fm->f_ndims; u++)
2328
0
                    coords[u] = (hsize_t)((hssize_t)coords[u] - adjust[u]);
2329
2330
                /* Set to same shape as chunk */
2331
0
                if (H5S_select_hyperslab(piece_info->mspace, H5S_SELECT_SET, coords, NULL, fm->chunk_dim,
2332
0
                                         NULL) < 0)
2333
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTSELECT, FAIL, "can't create chunk memory selection");
2334
0
            } /* end if */
2335
0
            else {
2336
                /* Sanity check */
2337
0
                assert(H5S_SEL_HYPERSLABS == chunk_sel_type);
2338
2339
                /* Copy the file chunk's selection */
2340
0
                if (H5S_SELECT_COPY(piece_info->mspace, piece_info->fspace, false) < 0)
2341
0
                    HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "unable to copy selection");
2342
2343
                /* Compute the adjustment for this chunk */
2344
0
                for (u = 0; u < fm->f_ndims; u++) {
2345
                    /* Compensate for the chunk offset */
2346
0
                    H5_CHECK_OVERFLOW(coords[u], hsize_t, hssize_t);
2347
0
                    piece_adjust[u] = adjust[u] - (hssize_t)coords[u];
2348
0
                } /* end for */
2349
2350
                /* Adjust the selection */
2351
0
                if (H5S_SELECT_ADJUST_S(piece_info->mspace, piece_adjust) < 0)
2352
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTSET, FAIL, "unable to adjust selection");
2353
0
            } /* end else */
2354
2355
            /* Get the next piece node in the skip list */
2356
0
            curr_node = H5SL_next(curr_node);
2357
0
        } /* end while */
2358
0
    }     /* end else */
2359
2360
0
done:
2361
0
    FUNC_LEAVE_NOAPI(ret_value)
2362
0
} /* end H5D__create_piece_mem_map_hyper() */
2363
2364
/*-------------------------------------------------------------------------
2365
 * Function:    H5D__create_piece_mem_map_1d
2366
 *
2367
 * Purpose:    Create all chunk selections for 1-dimensional regular memory space
2368
 *          that has only one single block in the selection
2369
 *
2370
 * Return:    Non-negative on success/Negative on failure
2371
 *
2372
 *-------------------------------------------------------------------------
2373
 */
2374
static herr_t
2375
H5D__create_piece_mem_map_1d(const H5D_dset_io_info_t *dinfo)
2376
0
{
2377
0
    H5D_chunk_map_t  *fm;                  /* Convenience pointer to chunk map */
2378
0
    H5D_piece_info_t *piece_info;          /* Pointer to chunk information */
2379
0
    H5SL_node_t      *curr_node;           /* Current node in skip list */
2380
0
    herr_t            ret_value = SUCCEED; /* Return value */
2381
2382
0
    FUNC_ENTER_PACKAGE
2383
2384
    /* Sanity check */
2385
0
    assert(dinfo->layout_io_info.chunk_map->f_ndims > 0);
2386
2387
    /* Set convenience pointer */
2388
0
    fm = dinfo->layout_io_info.chunk_map;
2389
0
    assert(fm);
2390
2391
    /* Check for all I/O going to a single chunk */
2392
0
    if (H5SL_count(fm->dset_sel_pieces) == 1) {
2393
        /* Get the node */
2394
0
        curr_node = H5SL_first(fm->dset_sel_pieces);
2395
2396
        /* Get pointer to chunk's information */
2397
0
        piece_info = (H5D_piece_info_t *)H5SL_item(curr_node);
2398
0
        assert(piece_info);
2399
2400
        /* Just point at the memory dataspace & selection */
2401
0
        piece_info->mspace = dinfo->mem_space;
2402
2403
        /* Indicate that the chunk's memory space is shared */
2404
0
        piece_info->mspace_shared = true;
2405
0
    } /* end if */
2406
0
    else {
2407
0
        hsize_t mem_sel_start[H5S_MAX_RANK]; /* Offset of low bound of file selection */
2408
0
        hsize_t mem_sel_end[H5S_MAX_RANK];   /* Offset of high bound of file selection */
2409
2410
0
        assert(fm->m_ndims == 1);
2411
2412
0
        if (H5S_SELECT_BOUNDS(dinfo->mem_space, mem_sel_start, mem_sel_end) < 0)
2413
0
            HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "can't get file selection bound info");
2414
2415
        /* Iterate over each chunk in the chunk list */
2416
0
        curr_node = H5SL_first(fm->dset_sel_pieces);
2417
0
        while (curr_node) {
2418
0
            hsize_t chunk_points; /* Number of elements in chunk selection */
2419
0
            hsize_t tmp_count = 1;
2420
2421
            /* Get pointer to chunk's information */
2422
0
            piece_info = (H5D_piece_info_t *)H5SL_item(curr_node);
2423
0
            assert(piece_info);
2424
2425
            /* Copy the memory dataspace */
2426
0
            if ((piece_info->mspace = H5S_copy(dinfo->mem_space, true, false)) == NULL)
2427
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "unable to copy memory space");
2428
2429
0
            chunk_points = H5S_GET_SELECT_NPOINTS(piece_info->fspace);
2430
2431
0
            if (H5S_select_hyperslab(piece_info->mspace, H5S_SELECT_SET, mem_sel_start, NULL, &tmp_count,
2432
0
                                     &chunk_points) < 0)
2433
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTSELECT, FAIL, "can't create chunk memory selection");
2434
2435
0
            mem_sel_start[0] += chunk_points;
2436
2437
            /* Get the next chunk node in the skip list */
2438
0
            curr_node = H5SL_next(curr_node);
2439
0
        } /* end while */
2440
0
    }     /* end else */
2441
2442
0
done:
2443
0
    FUNC_LEAVE_NOAPI(ret_value)
2444
0
} /* end H5D__create_piece_mem_map_1d() */
2445
2446
/*-------------------------------------------------------------------------
2447
 * Function:    H5D__piece_file_cb
2448
 *
2449
 * Purpose:     Callback routine for file selection iterator.  Used when
2450
 *              creating selections in file for each point selected.
2451
 *
2452
 * Return:      Non-negative on success/Negative on failure
2453
 *
2454
 *-------------------------------------------------------------------------
2455
 */
2456
static herr_t
2457
H5D__piece_file_cb(void H5_ATTR_UNUSED *elem, const H5T_t H5_ATTR_UNUSED *type, unsigned ndims,
2458
                   const hsize_t *coords, void *_opdata)
2459
0
{
2460
0
    H5D_io_info_wrap_t *opdata  = (H5D_io_info_wrap_t *)_opdata;
2461
0
    H5D_io_info_t      *io_info = (H5D_io_info_t *)opdata->io_info;    /* io info for multi dset */
2462
0
    H5D_dset_io_info_t *dinfo   = (H5D_dset_io_info_t *)opdata->dinfo; /* File<->memory piece mapping info */
2463
0
    H5D_chunk_map_t    *fm;                                            /* Convenience pointer to chunk map */
2464
0
    H5D_piece_info_t   *piece_info;                        /* Chunk information for current piece */
2465
0
    hsize_t             coords_in_chunk[H5O_LAYOUT_NDIMS]; /* Coordinates of element in chunk */
2466
0
    hsize_t             chunk_index;                       /* Chunk index */
2467
0
    hsize_t             scaled[H5S_MAX_RANK];              /* Scaled coordinates for this chunk */
2468
0
    unsigned            u;                                 /* Local index variable */
2469
0
    herr_t              ret_value = SUCCEED;               /* Return value        */
2470
2471
0
    FUNC_ENTER_PACKAGE
2472
2473
    /* Set convenience pointer */
2474
0
    fm = dinfo->layout_io_info.chunk_map;
2475
2476
    /* Calculate the index of this chunk */
2477
0
    chunk_index = H5VM_chunk_index_scaled(ndims, coords, dinfo->layout->u.chunk.dim,
2478
0
                                          dinfo->layout->u.chunk.down_chunks, scaled);
2479
2480
    /* Find correct chunk in file & memory skip list */
2481
0
    if (chunk_index == fm->last_index) {
2482
        /* If the chunk index is the same as the last chunk index we used,
2483
         * get the cached info to operate on.
2484
         */
2485
0
        piece_info = fm->last_piece_info;
2486
0
    } /* end if */
2487
0
    else {
2488
        /* If the chunk index is not the same as the last chunk index we used,
2489
         * find the chunk in the skip list.  If we do not find it, create
2490
         * a new node. */
2491
0
        if (NULL == (piece_info = (H5D_piece_info_t *)H5SL_search(fm->dset_sel_pieces, &chunk_index))) {
2492
0
            H5S_t *fspace; /* Memory chunk's dataspace */
2493
2494
            /* Allocate the file & memory chunk information */
2495
0
            if (NULL == (piece_info = H5FL_MALLOC(H5D_piece_info_t)))
2496
0
                HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "can't allocate chunk info");
2497
2498
            /* Initialize the chunk information */
2499
2500
            /* Set the chunk index */
2501
0
            piece_info->index = chunk_index;
2502
2503
            /* Create a dataspace for the chunk */
2504
0
            if ((fspace = H5S_create_simple(fm->f_ndims, fm->chunk_dim, NULL)) == NULL) {
2505
0
                piece_info = H5FL_FREE(H5D_piece_info_t, piece_info);
2506
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCREATE, FAIL, "unable to create dataspace for chunk");
2507
0
            } /* end if */
2508
2509
            /* De-select the chunk space */
2510
0
            if (H5S_select_none(fspace) < 0) {
2511
0
                (void)H5S_close(fspace);
2512
0
                piece_info = H5FL_FREE(H5D_piece_info_t, piece_info);
2513
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to de-select dataspace");
2514
0
            } /* end if */
2515
2516
            /* Set the file chunk dataspace */
2517
0
            piece_info->fspace        = fspace;
2518
0
            piece_info->fspace_shared = false;
2519
2520
            /* Set the memory chunk dataspace */
2521
0
            piece_info->mspace        = NULL;
2522
0
            piece_info->mspace_shared = false;
2523
2524
            /* Set the number of selected elements in chunk to zero */
2525
0
            piece_info->piece_points = 0;
2526
2527
            /* Set the chunk's scaled coordinates */
2528
0
            H5MM_memcpy(piece_info->scaled, scaled, sizeof(hsize_t) * fm->f_ndims);
2529
0
            piece_info->scaled[fm->f_ndims] = 0;
2530
2531
            /* Initialize in-place type conversion info. Start with it disabled. */
2532
0
            piece_info->in_place_tconv = false;
2533
0
            piece_info->buf_off        = 0;
2534
2535
0
            piece_info->filtered_dset = dinfo->dset->shared->dcpl_cache.pline.nused > 0;
2536
2537
            /* Make connection to related dset info from this piece_info */
2538
0
            piece_info->dset_info = dinfo;
2539
2540
            /* Insert the new chunk into the skip list */
2541
0
            if (H5SL_insert(fm->dset_sel_pieces, piece_info, &piece_info->index) < 0) {
2542
0
                H5D__free_piece_info(piece_info, NULL, NULL);
2543
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't insert chunk into dataset skip list");
2544
0
            } /* end if */
2545
2546
            /* Add piece to global piece_count */
2547
0
            io_info->piece_count++;
2548
0
        } /* end if */
2549
2550
        /* Update the "last chunk seen" information */
2551
0
        fm->last_index      = chunk_index;
2552
0
        fm->last_piece_info = piece_info;
2553
0
    } /* end else */
2554
2555
    /* Get the offset of the element within the chunk */
2556
0
    for (u = 0; u < fm->f_ndims; u++)
2557
0
        coords_in_chunk[u] = coords[u] - (scaled[u] * dinfo->layout->u.chunk.dim[u]);
2558
2559
    /* Add point to file selection for chunk */
2560
0
    if (H5S_select_elements(piece_info->fspace, H5S_SELECT_APPEND, (size_t)1, coords_in_chunk) < 0)
2561
0
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "unable to select element");
2562
2563
    /* Increment the number of elemented selected in chunk */
2564
0
    piece_info->piece_points++;
2565
2566
0
done:
2567
0
    FUNC_LEAVE_NOAPI(ret_value)
2568
0
} /* end H5D__piece_file_cb */
2569
2570
/*-------------------------------------------------------------------------
2571
 * Function:    H5D__piece_mem_cb
2572
 *
2573
 * Purpose:     Callback routine for file selection iterator.  Used when
2574
 *              creating selections in memory for each piece.
2575
 *              This was derived from H5D__chunk_mem_cb for multi-dset
2576
 *              work.
2577
 *
2578
 * Return:    Non-negative on success/Negative on failure
2579
 *
2580
 *-------------------------------------------------------------------------
2581
 */
2582
static herr_t
2583
H5D__piece_mem_cb(void H5_ATTR_UNUSED *elem, const H5T_t H5_ATTR_UNUSED *type, unsigned ndims,
2584
                  const hsize_t *coords, void *_opdata)
2585
0
{
2586
0
    H5D_io_info_wrap_t *opdata = (H5D_io_info_wrap_t *)_opdata;
2587
0
    H5D_dset_io_info_t *dinfo  = (H5D_dset_io_info_t *)opdata->dinfo; /* File<->memory chunk mapping info */
2588
0
    H5D_piece_info_t   *piece_info;                  /* Chunk information for current chunk */
2589
0
    H5D_chunk_map_t    *fm;                          /* Convenience pointer to chunk map */
2590
0
    hsize_t             coords_in_mem[H5S_MAX_RANK]; /* Coordinates of element in memory */
2591
0
    hsize_t             chunk_index;                 /* Chunk index */
2592
0
    herr_t              ret_value = SUCCEED;         /* Return value        */
2593
2594
0
    FUNC_ENTER_PACKAGE
2595
2596
    /* Set convenience pointer */
2597
0
    fm = dinfo->layout_io_info.chunk_map;
2598
2599
    /* Calculate the index of this chunk */
2600
0
    chunk_index =
2601
0
        H5VM_chunk_index(ndims, coords, dinfo->layout->u.chunk.dim, dinfo->layout->u.chunk.down_chunks);
2602
2603
    /* Find correct chunk in file & memory skip list */
2604
0
    if (chunk_index == fm->last_index) {
2605
        /* If the chunk index is the same as the last chunk index we used,
2606
         * get the cached spaces to operate on.
2607
         */
2608
0
        piece_info = fm->last_piece_info;
2609
0
    } /* end if */
2610
0
    else {
2611
        /* If the chunk index is not the same as the last chunk index we used,
2612
         * find the chunk in the dataset skip list.
2613
         */
2614
        /* Get the chunk node from the skip list */
2615
0
        if (NULL == (piece_info = (H5D_piece_info_t *)H5SL_search(fm->dset_sel_pieces, &chunk_index)))
2616
0
            HGOTO_ERROR(H5E_DATASPACE, H5E_NOTFOUND, H5_ITER_ERROR,
2617
0
                        "can't locate piece in dataset skip list");
2618
2619
        /* Check if the chunk already has a memory space */
2620
0
        if (NULL == piece_info->mspace)
2621
            /* Copy the template memory chunk dataspace */
2622
0
            if (NULL == (piece_info->mspace = H5S_copy(fm->mchunk_tmpl, false, false)))
2623
0
                HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, H5_ITER_ERROR, "unable to copy file space");
2624
2625
        /* Update the "last chunk seen" information */
2626
0
        fm->last_index      = chunk_index;
2627
0
        fm->last_piece_info = piece_info;
2628
0
    } /* end else */
2629
2630
    /* Get coordinates of selection iterator for memory */
2631
0
    if (H5S_SELECT_ITER_COORDS(&fm->mem_iter, coords_in_mem) < 0)
2632
0
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, H5_ITER_ERROR, "unable to get iterator coordinates");
2633
2634
    /* Add point to memory selection for chunk */
2635
0
    if (fm->msel_type == H5S_SEL_POINTS) {
2636
0
        if (H5S_select_elements(piece_info->mspace, H5S_SELECT_APPEND, (size_t)1, coords_in_mem) < 0)
2637
0
            HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, H5_ITER_ERROR, "unable to select element");
2638
0
    } /* end if */
2639
0
    else {
2640
0
        if (H5S_hyper_add_span_element(piece_info->mspace, fm->m_ndims, coords_in_mem) < 0)
2641
0
            HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, H5_ITER_ERROR, "unable to select element");
2642
0
    } /* end else */
2643
2644
    /* Move memory selection iterator to next element in selection */
2645
0
    if (H5S_SELECT_ITER_NEXT(&fm->mem_iter, (size_t)1) < 0)
2646
0
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTNEXT, H5_ITER_ERROR, "unable to move to next iterator location");
2647
2648
0
done:
2649
0
    FUNC_LEAVE_NOAPI(ret_value)
2650
0
} /* end H5D__piece_mem_cb() */
2651
2652
/*-------------------------------------------------------------------------
2653
 * Function:   H5D__chunk_mdio_init
2654
 *
2655
 * Purpose:    Performs second phase of initialization for multi-dataset
2656
 *             I/O.  Currently looks up chunk addresses and adds chunks to
2657
 *             sel_pieces.
2658
 *
2659
 * Return:     Non-negative on success/Negative on failure
2660
 *
2661
 *-------------------------------------------------------------------------
2662
 */
2663
static herr_t
2664
H5D__chunk_mdio_init(H5D_io_info_t *io_info, H5D_dset_io_info_t *dinfo)
2665
0
{
2666
0
    H5SL_node_t      *piece_node;          /* Current node in chunk skip list */
2667
0
    H5D_piece_info_t *piece_info;          /* Piece information for current piece */
2668
0
    H5D_chunk_ud_t    udata;               /* Chunk data from index */
2669
0
    herr_t            ret_value = SUCCEED; /* Return value */
2670
2671
0
    FUNC_ENTER_PACKAGE
2672
2673
    /* Get first node in skip list.  Note we don't check for failure since NULL
2674
     * simply indicates an empty skip list. */
2675
0
    piece_node = H5D_CHUNK_GET_FIRST_NODE(dinfo);
2676
2677
    /* Iterate over skip list */
2678
0
    while (piece_node) {
2679
        /* Get piece info */
2680
0
        if (NULL == (piece_info = (H5D_piece_info_t *)H5D_CHUNK_GET_NODE_INFO(dinfo, piece_node)))
2681
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "couldn't get piece info from list");
2682
2683
        /* Get the info for the chunk in the file */
2684
0
        if (H5D__chunk_lookup(dinfo->dset, piece_info->scaled, &udata) < 0)
2685
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
2686
2687
        /* Save chunk file address */
2688
0
        piece_info->faddr = udata.chunk_block.offset;
2689
2690
        /* Add piece to MDIO operation if it has a file address */
2691
0
        if (H5_addr_defined(piece_info->faddr)) {
2692
0
            assert(io_info->sel_pieces);
2693
0
            assert(io_info->pieces_added < io_info->piece_count);
2694
2695
            /* Add to sel_pieces and update pieces_added */
2696
0
            io_info->sel_pieces[io_info->pieces_added++] = piece_info;
2697
2698
0
            if (piece_info->filtered_dset)
2699
0
                io_info->filtered_pieces_added++;
2700
0
        }
2701
2702
        /* Advance to next skip list node */
2703
0
        piece_node = H5D_CHUNK_GET_NEXT_NODE(dinfo, piece_node);
2704
0
    }
2705
2706
0
done:
2707
0
    FUNC_LEAVE_NOAPI(ret_value)
2708
0
} /* end H5D__chunk_mdio_init() */
2709
2710
/*-------------------------------------------------------------------------
2711
 * Function:    H5D__chunk_cacheable
2712
 *
2713
 * Purpose:    A small internal function to if it's possible to load the
2714
 *              chunk into cache.
2715
 *
2716
 * Return:    true or false
2717
 *
2718
 *-------------------------------------------------------------------------
2719
 */
2720
htri_t
2721
H5D__chunk_cacheable(const H5D_io_info_t H5_ATTR_PARALLEL_USED *io_info, H5D_dset_io_info_t *dset_info,
2722
                     haddr_t caddr, bool write_op)
2723
0
{
2724
0
    const H5D_t *dataset     = NULL;  /* Local pointer to dataset info */
2725
0
    bool         has_filters = false; /* Whether there are filters on the chunk or not */
2726
0
    htri_t       ret_value   = FAIL;  /* Return value */
2727
2728
0
    FUNC_ENTER_PACKAGE
2729
2730
    /* Sanity check */
2731
0
    assert(dset_info);
2732
0
    dataset = dset_info->dset;
2733
0
    assert(dataset);
2734
2735
    /* Must bring the whole chunk in if there are any filters on the chunk.
2736
     * Make sure to check if filters are on the dataset but disabled for the
2737
     * chunk because it is a partial edge chunk. */
2738
0
    if (dataset->shared->dcpl_cache.pline.nused > 0) {
2739
0
        if (dataset->shared->layout.u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS) {
2740
0
            has_filters =
2741
0
                !H5D__chunk_is_partial_edge_chunk(dataset->shared->ndims, dataset->shared->layout.u.chunk.dim,
2742
0
                                                  dset_info->store->chunk.scaled, dataset->shared->curr_dims);
2743
0
        } /* end if */
2744
0
        else
2745
0
            has_filters = true;
2746
0
    } /* end if */
2747
2748
0
    if (has_filters)
2749
0
        ret_value = true;
2750
0
    else {
2751
#ifdef H5_HAVE_PARALLEL
2752
        /* If MPI based VFD is used and the file is opened for write access, must
2753
         *         bypass the chunk-cache scheme because other MPI processes could
2754
         *         be writing to other elements in the same chunk.  Do a direct
2755
         *         write-through of only the elements requested.
2756
         */
2757
        if (io_info->using_mpi_vfd && (H5F_ACC_RDWR & H5F_INTENT(dataset->oloc.file)))
2758
            ret_value = false;
2759
        else {
2760
#endif /* H5_HAVE_PARALLEL */
2761
            /* If the chunk is too large to keep in the cache and if we don't
2762
             * need to write the fill value, then don't load the chunk into the
2763
             * cache, just write the data to it directly.
2764
             */
2765
            /* If the chunk is too big to fit in size_t, assume it is too big to fit in cache */
2766
0
            if (!(((hsize_t)((size_t)dataset->shared->layout.u.chunk.size) ==
2767
0
                   dataset->shared->layout.u.chunk.size) &&
2768
0
                  ((size_t)dataset->shared->layout.u.chunk.size <=
2769
0
                   dataset->shared->cache.chunk.nbytes_max))) {
2770
0
                if (write_op && !H5_addr_defined(caddr)) {
2771
0
                    const H5O_fill_t *fill = &(dataset->shared->dcpl_cache.fill); /* Fill value info */
2772
0
                    H5D_fill_value_t  fill_status;                                /* Fill value status */
2773
2774
                    /* Revtrieve the fill value status */
2775
0
                    if (H5P_is_fill_value_defined(fill, &fill_status) < 0)
2776
0
                        HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't tell if fill value defined");
2777
2778
                    /* If the fill value needs to be written then we will need
2779
                     * to use the cache to write the fill value */
2780
0
                    if (fill->fill_time == H5D_FILL_TIME_ALLOC ||
2781
0
                        (fill->fill_time == H5D_FILL_TIME_IFSET &&
2782
0
                         (fill_status == H5D_FILL_VALUE_USER_DEFINED ||
2783
0
                          fill_status == H5D_FILL_VALUE_DEFAULT))) {
2784
                        /* Check for size_t overflow */
2785
0
                        if (H5_UNLIKELY((hsize_t)((size_t)dataset->shared->layout.u.chunk.size) !=
2786
0
                                        dataset->shared->layout.u.chunk.size))
2787
0
                            HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, FAIL,
2788
0
                                        "must fill chunk but it is too big to fit in size_t - try using "
2789
0
                                        "early allocation");
2790
0
                        ret_value = true;
2791
0
                    }
2792
0
                    else
2793
0
                        ret_value = false;
2794
0
                }
2795
0
                else
2796
0
                    ret_value = false;
2797
0
            }
2798
0
            else
2799
0
                ret_value = true;
2800
#ifdef H5_HAVE_PARALLEL
2801
        } /* end else */
2802
#endif    /* H5_HAVE_PARALLEL */
2803
0
    }     /* end else */
2804
2805
0
done:
2806
0
    FUNC_LEAVE_NOAPI(ret_value)
2807
0
} /* end H5D__chunk_cacheable() */
2808
2809
/*-------------------------------------------------------------------------
2810
 * Function:    H5D__chunk_may_use_select_io
2811
 *
2812
 * Purpose:    A small internal function to if it may be possible to use
2813
 *             selection I/O.
2814
 *
2815
 * Return:    true or false
2816
 *
2817
 *-------------------------------------------------------------------------
2818
 */
2819
static herr_t
2820
H5D__chunk_may_use_select_io(H5D_io_info_t *io_info, const H5D_dset_io_info_t *dset_info)
2821
0
{
2822
0
    const H5D_t *dataset   = NULL;    /* Local pointer to dataset info */
2823
0
    herr_t       ret_value = SUCCEED; /* Return value */
2824
2825
0
    FUNC_ENTER_PACKAGE
2826
2827
    /* Sanity check */
2828
0
    assert(io_info);
2829
0
    assert(dset_info);
2830
2831
0
    dataset = dset_info->dset;
2832
0
    assert(dataset);
2833
2834
    /* Don't use selection I/O if there are filters on the dataset (for now) */
2835
0
    if (dataset->shared->dcpl_cache.pline.nused > 0) {
2836
0
        io_info->use_select_io = H5D_SELECTION_IO_MODE_OFF;
2837
0
        io_info->no_selection_io_cause |= H5D_SEL_IO_DATASET_FILTER;
2838
0
    }
2839
0
    else {
2840
0
        bool page_buf_enabled;
2841
2842
        /* Check if the page buffer is enabled */
2843
0
        if (H5PB_enabled(io_info->f_sh, H5FD_MEM_DRAW, &page_buf_enabled) < 0)
2844
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't check if page buffer is enabled");
2845
0
        if (page_buf_enabled) {
2846
            /* Note that page buffer is disabled in parallel */
2847
0
            io_info->use_select_io = H5D_SELECTION_IO_MODE_OFF;
2848
0
            io_info->no_selection_io_cause |= H5D_SEL_IO_PAGE_BUFFER;
2849
0
        }
2850
0
        else {
2851
            /* Check if chunks in this dataset may be cached, if so don't use
2852
             * selection I/O (for now).  Note that chunks temporarily cached for
2853
             * the purpose of writing the fill value don't count, since they are
2854
             * immediately evicted. */
2855
#ifdef H5_HAVE_PARALLEL
2856
            /* If MPI based VFD is used and the file is opened for write access,
2857
             * must bypass the chunk-cache scheme because other MPI processes
2858
             * could be writing to other elements in the same chunk.
2859
             */
2860
            if (!(io_info->using_mpi_vfd && (H5F_ACC_RDWR & H5F_INTENT(dataset->oloc.file)))) {
2861
#endif /* H5_HAVE_PARALLEL */
2862
                /* Check if the chunk is too large to keep in the cache */
2863
                /* If the chunk is too big to fit in size_t, assume it is too big to fit in cache */
2864
0
                if (((hsize_t)((size_t)dataset->shared->layout.u.chunk.size) ==
2865
0
                     dataset->shared->layout.u.chunk.size) &&
2866
0
                    ((size_t)dataset->shared->layout.u.chunk.size <=
2867
0
                     dataset->shared->cache.chunk.nbytes_max)) {
2868
0
                    io_info->use_select_io = H5D_SELECTION_IO_MODE_OFF;
2869
0
                    io_info->no_selection_io_cause |= H5D_SEL_IO_CHUNK_CACHE;
2870
0
                }
2871
#ifdef H5_HAVE_PARALLEL
2872
            } /* end else */
2873
#endif        /* H5_HAVE_PARALLEL */
2874
0
        }     /* end else */
2875
0
    }         /* end else */
2876
2877
0
done:
2878
0
    FUNC_LEAVE_NOAPI(ret_value)
2879
0
} /* end H5D__chunk_may_use_select_io() */
2880
2881
/*-------------------------------------------------------------------------
2882
 * Function:    H5D__chunk_read
2883
 *
2884
 * Purpose:    Read from a chunked dataset.
2885
 *
2886
 * Return:    Non-negative on success/Negative on failure
2887
 *
2888
 *-------------------------------------------------------------------------
2889
 */
2890
static herr_t
2891
H5D__chunk_read(H5D_io_info_t *io_info, H5D_dset_io_info_t *dset_info)
2892
0
{
2893
0
    H5SL_node_t       *chunk_node;                  /* Current node in chunk skip list */
2894
0
    H5D_dset_io_info_t ctg_dset_info;               /* Contiguous I/O dset info object */
2895
0
    H5D_dset_io_info_t cpt_dset_info;               /* Compact I/O dset info object */
2896
0
    hsize_t            src_accessed_bytes  = 0;     /* Total accessed size in a chunk */
2897
0
    bool               skip_missing_chunks = false; /* Whether to skip missing chunks */
2898
0
    H5S_t            **chunk_mem_spaces    = NULL;  /* Array of chunk memory spaces */
2899
0
    H5S_t             *chunk_mem_spaces_local[8];   /* Local buffer for chunk_mem_spaces */
2900
0
    H5S_t            **chunk_file_spaces = NULL;    /* Array of chunk file spaces */
2901
0
    H5S_t             *chunk_file_spaces_local[8];  /* Local buffer for chunk_file_spaces */
2902
0
    haddr_t           *chunk_addrs = NULL;          /* Array of chunk addresses */
2903
0
    haddr_t            chunk_addrs_local[8];        /* Local buffer for chunk_addrs */
2904
0
    void              *chunk        = NULL;         /* Pointer to locked chunk buffer */
2905
0
    bool               chunk_locked = false;        /* Indicates whether the chunk is locked */
2906
0
    H5D_chunk_ud_t     udata;                       /* Chunk index pass-through    */
2907
0
    herr_t             ret_value = SUCCEED;         /*return value        */
2908
2909
0
    FUNC_ENTER_PACKAGE
2910
2911
    /* Sanity check */
2912
0
    assert(io_info);
2913
0
    assert(dset_info);
2914
0
    assert(dset_info->buf.vp);
2915
2916
0
    {
2917
0
        const H5O_fill_t *fill = &(dset_info->dset->shared->dcpl_cache.fill); /* Fill value info */
2918
0
        H5D_fill_value_t  fill_status;                                        /* Fill value status */
2919
2920
        /* Check the fill value status */
2921
0
        if (H5P_is_fill_value_defined(fill, &fill_status) < 0)
2922
0
            HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't tell if fill value defined");
2923
2924
        /* If we are never to return fill values, or if we would return them
2925
         * but they aren't set, set the flag to skip missing chunks.
2926
         */
2927
0
        if (fill->fill_time == H5D_FILL_TIME_NEVER ||
2928
0
            (fill->fill_time == H5D_FILL_TIME_IFSET && fill_status != H5D_FILL_VALUE_USER_DEFINED &&
2929
0
             fill_status != H5D_FILL_VALUE_DEFAULT))
2930
0
            skip_missing_chunks = true;
2931
0
    }
2932
2933
    /* Different blocks depending on whether we're using selection I/O */
2934
0
    if (io_info->use_select_io == H5D_SELECTION_IO_MODE_ON) {
2935
0
        size_t num_chunks       = 0;
2936
0
        size_t element_sizes[2] = {dset_info->type_info.src_type_size, 0};
2937
0
        void  *bufs[2]          = {dset_info->buf.vp, NULL};
2938
2939
        /* Only create selection I/O arrays if not performing multi dataset I/O,
2940
         * otherwise the higher level will handle it */
2941
0
        if (H5D_LAYOUT_CB_PERFORM_IO(io_info)) {
2942
            /* Cache number of chunks */
2943
0
            num_chunks = H5D_CHUNK_GET_NODE_COUNT(dset_info);
2944
2945
            /* Allocate arrays of dataspaces and offsets for use with selection I/O,
2946
             * or point to local buffers */
2947
0
            assert(sizeof(chunk_mem_spaces_local) / sizeof(chunk_mem_spaces_local[0]) ==
2948
0
                   sizeof(chunk_file_spaces_local) / sizeof(chunk_file_spaces_local[0]));
2949
0
            assert(sizeof(chunk_mem_spaces_local) / sizeof(chunk_mem_spaces_local[0]) ==
2950
0
                   sizeof(chunk_addrs_local) / sizeof(chunk_addrs_local[0]));
2951
0
            if (num_chunks > (sizeof(chunk_mem_spaces_local) / sizeof(chunk_mem_spaces_local[0]))) {
2952
0
                if (NULL == (chunk_mem_spaces = H5MM_malloc(num_chunks * sizeof(H5S_t *))))
2953
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_CANTALLOC, FAIL,
2954
0
                                "memory allocation failed for memory space list");
2955
0
                if (NULL == (chunk_file_spaces = H5MM_malloc(num_chunks * sizeof(H5S_t *))))
2956
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_CANTALLOC, FAIL,
2957
0
                                "memory allocation failed for file space list");
2958
0
                if (NULL == (chunk_addrs = H5MM_malloc(num_chunks * sizeof(haddr_t))))
2959
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_CANTALLOC, FAIL,
2960
0
                                "memory allocation failed for chunk address list");
2961
0
            } /* end if */
2962
0
            else {
2963
0
                chunk_mem_spaces  = chunk_mem_spaces_local;
2964
0
                chunk_file_spaces = chunk_file_spaces_local;
2965
0
                chunk_addrs       = chunk_addrs_local;
2966
0
            } /* end else */
2967
2968
            /* Reset num_chunks */
2969
0
            num_chunks = 0;
2970
0
        } /* end if */
2971
2972
        /* Iterate through nodes in chunk skip list */
2973
0
        chunk_node = H5D_CHUNK_GET_FIRST_NODE(dset_info);
2974
0
        while (chunk_node) {
2975
0
            H5D_piece_info_t *chunk_info; /* Chunk information */
2976
2977
            /* Get the actual chunk information from the skip list node */
2978
0
            chunk_info = H5D_CHUNK_GET_NODE_INFO(dset_info, chunk_node);
2979
2980
            /* Get the info for the chunk in the file */
2981
0
            if (H5D__chunk_lookup(dset_info->dset, chunk_info->scaled, &udata) < 0)
2982
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
2983
2984
            /* There should be no chunks cached */
2985
0
            assert(UINT_MAX == udata.idx_hint);
2986
2987
            /* Sanity check */
2988
0
            assert((H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length > 0) ||
2989
0
                   (!H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length == 0));
2990
2991
            /* Check for non-existent chunk & skip it if appropriate */
2992
0
            if (H5_addr_defined(udata.chunk_block.offset)) {
2993
                /* Add chunk to list for selection I/O, if not performing multi dataset I/O */
2994
0
                if (H5D_LAYOUT_CB_PERFORM_IO(io_info)) {
2995
0
                    chunk_mem_spaces[num_chunks]  = chunk_info->mspace;
2996
0
                    chunk_file_spaces[num_chunks] = chunk_info->fspace;
2997
0
                    chunk_addrs[num_chunks]       = udata.chunk_block.offset;
2998
0
                    num_chunks++;
2999
0
                } /* end if */
3000
0
                else {
3001
                    /* Add to mdset selection I/O arrays */
3002
0
                    assert(io_info->mem_spaces);
3003
0
                    assert(io_info->file_spaces);
3004
0
                    assert(io_info->addrs);
3005
0
                    assert(io_info->element_sizes);
3006
0
                    assert(io_info->rbufs);
3007
0
                    assert(io_info->pieces_added < io_info->piece_count);
3008
3009
0
                    io_info->mem_spaces[io_info->pieces_added]    = chunk_info->mspace;
3010
0
                    io_info->file_spaces[io_info->pieces_added]   = chunk_info->fspace;
3011
0
                    io_info->addrs[io_info->pieces_added]         = udata.chunk_block.offset;
3012
0
                    io_info->element_sizes[io_info->pieces_added] = element_sizes[0];
3013
0
                    io_info->rbufs[io_info->pieces_added]         = bufs[0];
3014
0
                    if (io_info->sel_pieces)
3015
0
                        io_info->sel_pieces[io_info->pieces_added] = chunk_info;
3016
0
                    io_info->pieces_added++;
3017
3018
0
                    if (io_info->sel_pieces && chunk_info->filtered_dset)
3019
0
                        io_info->filtered_pieces_added++;
3020
0
                }
3021
0
            }
3022
0
            else if (!skip_missing_chunks)
3023
                /* Write fill values to memory buffer */
3024
0
                if (H5D__fill(dset_info->dset->shared->dcpl_cache.fill.buf, dset_info->dset->shared->type,
3025
0
                              dset_info->buf.vp, dset_info->type_info.mem_type, chunk_info->mspace) < 0)
3026
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "filling buf failed");
3027
3028
            /* Advance to next chunk in list */
3029
0
            chunk_node = H5D_CHUNK_GET_NEXT_NODE(dset_info, chunk_node);
3030
0
        } /* end while */
3031
3032
        /* Only perform I/O if not performing multi dataset I/O or type conversion, otherwise the
3033
         * higher level will handle it after all datasets have been processed */
3034
0
        if (H5D_LAYOUT_CB_PERFORM_IO(io_info)) {
3035
            /* Issue selection I/O call (we can skip the page buffer because we've
3036
             * already verified it won't be used, and the metadata accumulator
3037
             * because this is raw data) */
3038
0
            H5_CHECK_OVERFLOW(num_chunks, size_t, uint32_t);
3039
0
            if (H5F_shared_select_read(H5F_SHARED(dset_info->dset->oloc.file), H5FD_MEM_DRAW,
3040
0
                                       (uint32_t)num_chunks, chunk_mem_spaces, chunk_file_spaces, chunk_addrs,
3041
0
                                       element_sizes, bufs) < 0)
3042
0
                HGOTO_ERROR(H5E_DATASET, H5E_READERROR, FAIL, "chunk selection read failed");
3043
3044
            /* Clean up memory */
3045
0
            if (chunk_mem_spaces != chunk_mem_spaces_local) {
3046
0
                assert(chunk_file_spaces != chunk_file_spaces_local);
3047
0
                assert(chunk_addrs != chunk_addrs_local);
3048
0
                chunk_mem_spaces  = H5MM_xfree(chunk_mem_spaces);
3049
0
                chunk_file_spaces = H5MM_xfree(chunk_file_spaces);
3050
0
                chunk_addrs       = H5MM_xfree(chunk_addrs);
3051
0
            } /* end if */
3052
0
        }     /* end if */
3053
3054
#ifdef H5_HAVE_PARALLEL
3055
        /* Report that collective chunk I/O was used (will only be set on the DXPL if collective I/O was
3056
         * requested) */
3057
        io_info->actual_io_mode |= H5D_MPIO_CHUNK_COLLECTIVE;
3058
#endif /* H5_HAVE_PARALLEL */
3059
0
    }  /* end if */
3060
0
    else {
3061
0
        H5D_io_info_t ctg_io_info; /* Contiguous I/O info object */
3062
0
        H5D_storage_t ctg_store;   /* Chunk storage information as contiguous dataset */
3063
0
        H5D_io_info_t cpt_io_info; /* Compact I/O info object */
3064
0
        H5D_storage_t cpt_store;   /* Chunk storage information as compact dataset */
3065
0
        bool          cpt_dirty;   /* Temporary placeholder for compact storage "dirty" flag */
3066
3067
        /* Set up contiguous I/O info object */
3068
0
        H5MM_memcpy(&ctg_io_info, io_info, sizeof(ctg_io_info));
3069
0
        H5MM_memcpy(&ctg_dset_info, dset_info, sizeof(ctg_dset_info));
3070
0
        ctg_dset_info.store      = &ctg_store;
3071
0
        ctg_dset_info.layout_ops = *H5D_LOPS_CONTIG;
3072
0
        ctg_io_info.dsets_info   = &ctg_dset_info;
3073
0
        ctg_io_info.count        = 1;
3074
3075
        /* Ensure dataset I/O sieve buffer is properly setup for when the contiguous
3076
         * dataset I/O routines are used for chunks. Force reset of sieve buffer here
3077
         * on each I/O until more advanced use cases like H5Dset_extent between writes
3078
         * and subsequent writes or reads can be supported.
3079
         */
3080
0
        dset_info->dset->shared->cache.sieve.sieve_buf_size = H5F_SIEVE_BUF_SIZE(dset_info->dset->oloc.file);
3081
0
        dset_info->dset->shared->cache.sieve.sieve_loc      = HADDR_UNDEF;
3082
0
        dset_info->dset->shared->cache.sieve.sieve_size     = 0;
3083
0
        assert(!dset_info->dset->shared->cache.sieve.sieve_dirty); /* Any writes should have been flushed */
3084
3085
        /* Initialize temporary contiguous storage info */
3086
0
        ctg_store.contig.dset_size = dset_info->dset->shared->layout.u.chunk.size;
3087
3088
        /* Set up compact I/O info object */
3089
0
        H5MM_memcpy(&cpt_io_info, io_info, sizeof(cpt_io_info));
3090
0
        H5MM_memcpy(&cpt_dset_info, dset_info, sizeof(cpt_dset_info));
3091
0
        cpt_dset_info.store      = &cpt_store;
3092
0
        cpt_dset_info.layout_ops = *H5D_LOPS_COMPACT;
3093
0
        cpt_io_info.dsets_info   = &cpt_dset_info;
3094
0
        cpt_io_info.count        = 1;
3095
3096
        /* Initialize temporary compact storage info */
3097
0
        cpt_store.compact.dirty = &cpt_dirty;
3098
3099
        /* Iterate through nodes in chunk skip list */
3100
0
        chunk_node = H5D_CHUNK_GET_FIRST_NODE(dset_info);
3101
0
        while (chunk_node) {
3102
0
            H5D_piece_info_t *chunk_info; /* Chunk information */
3103
0
            htri_t            cacheable;  /* Whether the chunk is cacheable */
3104
3105
            /* Get the actual chunk information from the skip list node */
3106
0
            chunk_info = H5D_CHUNK_GET_NODE_INFO(dset_info, chunk_node);
3107
3108
            /* Get the info for the chunk in the file */
3109
0
            if (H5D__chunk_lookup(dset_info->dset, chunk_info->scaled, &udata) < 0)
3110
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
3111
3112
            /* Sanity check */
3113
0
            assert((H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length > 0) ||
3114
0
                   (!H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length == 0));
3115
3116
            /* Check for non-existent chunk & skip it if appropriate */
3117
0
            if (H5_addr_defined(udata.chunk_block.offset) || UINT_MAX != udata.idx_hint ||
3118
0
                !skip_missing_chunks) {
3119
0
                H5D_io_info_t *chk_io_info = NULL; /* Pointer to I/O info object for this chunk */
3120
3121
                /* Set chunk's [scaled] coordinates */
3122
0
                dset_info->store->chunk.scaled = chunk_info->scaled;
3123
3124
                /* Don't lock the chunk if it doesn't exist on disk or in cache, to avoid unnecessary
3125
                 * allocation and conversion */
3126
0
                if (H5_addr_defined(udata.chunk_block.offset) || UINT_MAX != udata.idx_hint) {
3127
                    /* Determine if we should use the chunk cache */
3128
0
                    if ((cacheable =
3129
0
                             H5D__chunk_cacheable(io_info, dset_info, udata.chunk_block.offset, false)) < 0)
3130
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't tell if chunk is cacheable");
3131
0
                    if (cacheable) {
3132
                        /* Load the chunk into cache and lock it. */
3133
3134
                        /* Compute # of bytes accessed in chunk */
3135
0
                        H5_CHECK_OVERFLOW(dset_info->type_info.src_type_size, /*From:*/ size_t,
3136
0
                                          /*To:*/ hsize_t);
3137
0
                        src_accessed_bytes =
3138
0
                            chunk_info->piece_points * (hsize_t)dset_info->type_info.src_type_size;
3139
3140
                        /* Lock the chunk into the cache */
3141
0
                        if (NULL == (chunk = H5D__chunk_lock(io_info, dset_info, &udata, false, false)))
3142
0
                            HGOTO_ERROR(H5E_IO, H5E_CANTLOCK, FAIL, "unable to lock raw data chunk");
3143
0
                        chunk_locked = true;
3144
3145
                        /* Set up the storage buffer information for this chunk */
3146
0
                        cpt_store.compact.buf = chunk;
3147
3148
                        /* Point I/O info at contiguous I/O info for this chunk */
3149
0
                        chk_io_info = &cpt_io_info;
3150
0
                    }
3151
0
                    else {
3152
                        /* Since the chunk isn't cacheable it must not be in cache, therefore it must exist on
3153
                         * disk if it made it into the outer if statement */
3154
0
                        assert(H5_addr_defined(udata.chunk_block.offset));
3155
3156
                        /* Set up the storage address information for this chunk */
3157
0
                        ctg_store.contig.dset_addr = udata.chunk_block.offset;
3158
3159
                        /* Point I/O info at temporary I/O info for this chunk */
3160
0
                        chk_io_info = &ctg_io_info;
3161
0
                    }
3162
3163
                    /* Perform the actual read operation */
3164
0
                    assert(chk_io_info);
3165
0
                    assert(chk_io_info->count == 1);
3166
0
                    chk_io_info->dsets_info[0].layout_io_info.contig_piece_info = chunk_info;
3167
0
                    chk_io_info->dsets_info[0].file_space                       = chunk_info->fspace;
3168
0
                    chk_io_info->dsets_info[0].mem_space                        = chunk_info->mspace;
3169
0
                    chk_io_info->dsets_info[0].nelmts                           = chunk_info->piece_points;
3170
0
                    if ((dset_info->io_ops.single_read)(chk_io_info, &chk_io_info->dsets_info[0]) < 0)
3171
0
                        HGOTO_ERROR(H5E_DATASET, H5E_READERROR, FAIL, "chunked read failed");
3172
3173
                    /* Release the cache lock on the chunk */
3174
0
                    chunk_locked = false;
3175
0
                    if (chunk &&
3176
0
                        H5D__chunk_unlock(io_info, dset_info, &udata, false, chunk, src_accessed_bytes) < 0)
3177
0
                        HGOTO_ERROR(H5E_IO, H5E_CANTUNLOCK, FAIL, "unable to unlock raw data chunk");
3178
0
                    chunk = NULL;
3179
0
                } /* end if */
3180
0
                else
3181
                    /* Write fill values to memory buffer */
3182
0
                    if (H5D__fill(dset_info->dset->shared->dcpl_cache.fill.buf, dset_info->dset->shared->type,
3183
0
                                  dset_info->buf.vp, dset_info->type_info.mem_type, chunk_info->mspace) < 0)
3184
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "filling buf failed");
3185
0
            }
3186
3187
            /* Advance to next chunk in list */
3188
0
            chunk_node = H5D_CHUNK_GET_NEXT_NODE(dset_info, chunk_node);
3189
0
        } /* end while */
3190
0
    }     /* end else */
3191
3192
0
done:
3193
    /* Release chunk lock if we failed while holding it */
3194
0
    if (chunk_locked && chunk)
3195
0
        if (H5D__chunk_unlock(io_info, dset_info, &udata, false, chunk, src_accessed_bytes) < 0)
3196
0
            HDONE_ERROR(H5E_IO, H5E_CANTUNLOCK, FAIL, "unable to unlock raw data chunk");
3197
3198
    /* Free dataset sieve buffer and reset cached fields */
3199
0
    if (dset_info->dset->shared->cache.sieve.sieve_buf) {
3200
0
        dset_info->dset->shared->cache.sieve.sieve_loc  = HADDR_UNDEF;
3201
0
        dset_info->dset->shared->cache.sieve.sieve_size = 0;
3202
0
        dset_info->dset->shared->cache.sieve.sieve_buf =
3203
0
            (unsigned char *)H5FL_BLK_FREE(sieve_buf, dset_info->dset->shared->cache.sieve.sieve_buf);
3204
0
    }
3205
3206
    /* Cleanup on failure */
3207
0
    if (ret_value < 0) {
3208
0
        if (chunk_mem_spaces != chunk_mem_spaces_local)
3209
0
            chunk_mem_spaces = H5MM_xfree(chunk_mem_spaces);
3210
0
        if (chunk_file_spaces != chunk_file_spaces_local)
3211
0
            chunk_file_spaces = H5MM_xfree(chunk_file_spaces);
3212
0
        if (chunk_addrs != chunk_addrs_local)
3213
0
            chunk_addrs = H5MM_xfree(chunk_addrs);
3214
0
    } /* end if */
3215
3216
    /* Make sure we cleaned up */
3217
0
    assert(!chunk_mem_spaces || chunk_mem_spaces == chunk_mem_spaces_local);
3218
0
    assert(!chunk_file_spaces || chunk_file_spaces == chunk_file_spaces_local);
3219
0
    assert(!chunk_addrs || chunk_addrs == chunk_addrs_local);
3220
3221
0
    FUNC_LEAVE_NOAPI(ret_value)
3222
0
} /* H5D__chunk_read() */
3223
3224
/*-------------------------------------------------------------------------
3225
 * Function:    H5D__chunk_write
3226
 *
3227
 * Purpose:    Writes to a chunked dataset.
3228
 *
3229
 * Return:    Non-negative on success/Negative on failure
3230
 *
3231
 *-------------------------------------------------------------------------
3232
 */
3233
static herr_t
3234
H5D__chunk_write(H5D_io_info_t *io_info, H5D_dset_io_info_t *dset_info)
3235
0
{
3236
0
    H5SL_node_t       *chunk_node;                /* Current node in chunk skip list */
3237
0
    H5D_io_info_t      ctg_io_info;               /* Contiguous I/O info object */
3238
0
    H5D_dset_io_info_t ctg_dset_info;             /* Contiguous I/O dset info object */
3239
0
    H5D_storage_t      ctg_store;                 /* Chunk storage information as contiguous dataset */
3240
0
    H5D_io_info_t      cpt_io_info;               /* Compact I/O info object */
3241
0
    H5D_dset_io_info_t cpt_dset_info;             /* Compact I/O dset info object */
3242
0
    H5D_storage_t      cpt_store;                 /* Chunk storage information as compact dataset */
3243
0
    bool               cpt_dirty;                 /* Temporary placeholder for compact storage "dirty" flag */
3244
0
    hsize_t            dst_accessed_bytes = 0;    /* Total accessed size in a chunk */
3245
0
    H5S_t            **chunk_mem_spaces   = NULL; /* Array of chunk memory spaces */
3246
0
    H5S_t             *chunk_mem_spaces_local[8]; /* Local buffer for chunk_mem_spaces */
3247
0
    H5S_t            **chunk_file_spaces = NULL;  /* Array of chunk file spaces */
3248
0
    H5S_t             *chunk_file_spaces_local[8]; /* Local buffer for chunk_file_spaces */
3249
0
    haddr_t           *chunk_addrs = NULL;         /* Array of chunk addresses */
3250
0
    haddr_t            chunk_addrs_local[8];       /* Local buffer for chunk_addrs */
3251
0
    void              *chunk = NULL;               /* Pointer to locked chunk buffer */
3252
0
    H5D_chunk_ud_t     udata;                      /* Index pass-through    */
3253
0
    bool               chunk_locked = false;       /* Indicates whether the chunk is locked */
3254
0
    bool               chunk_dirty  = false;       /* Indicates whether writing is needed   */
3255
0
    herr_t             ret_value    = SUCCEED;     /* Return value        */
3256
3257
0
    FUNC_ENTER_PACKAGE
3258
3259
    /* Sanity check */
3260
0
    assert(io_info);
3261
0
    assert(dset_info);
3262
0
    assert(dset_info->buf.cvp);
3263
3264
    /* Set up contiguous I/O info object */
3265
0
    H5MM_memcpy(&ctg_io_info, io_info, sizeof(ctg_io_info));
3266
0
    H5MM_memcpy(&ctg_dset_info, dset_info, sizeof(ctg_dset_info));
3267
0
    ctg_dset_info.store      = &ctg_store;
3268
0
    ctg_dset_info.layout_ops = *H5D_LOPS_CONTIG;
3269
0
    ctg_io_info.dsets_info   = &ctg_dset_info;
3270
0
    ctg_io_info.count        = 1;
3271
3272
    /* Ensure dataset I/O sieve buffer is properly setup for when the contiguous
3273
     * dataset I/O routines are used for chunks. Force reset of sieve buffer here
3274
     * on each I/O until more advanced use cases like H5Dset_extent between writes
3275
     * and subsequent writes or reads can be supported.
3276
     */
3277
0
    dset_info->dset->shared->cache.sieve.sieve_buf_size = H5F_SIEVE_BUF_SIZE(dset_info->dset->oloc.file);
3278
0
    dset_info->dset->shared->cache.sieve.sieve_loc      = HADDR_UNDEF;
3279
0
    dset_info->dset->shared->cache.sieve.sieve_size     = 0;
3280
3281
    /* Initialize temporary contiguous storage info */
3282
0
    ctg_store.contig.dset_size = dset_info->dset->shared->layout.u.chunk.size;
3283
3284
    /* Set up compact I/O info object */
3285
0
    H5MM_memcpy(&cpt_io_info, io_info, sizeof(cpt_io_info));
3286
0
    H5MM_memcpy(&cpt_dset_info, dset_info, sizeof(cpt_dset_info));
3287
0
    cpt_dset_info.store      = &cpt_store;
3288
0
    cpt_dset_info.layout_ops = *H5D_LOPS_COMPACT;
3289
0
    cpt_io_info.dsets_info   = &cpt_dset_info;
3290
0
    cpt_io_info.count        = 1;
3291
3292
    /* Initialize temporary compact storage info */
3293
0
    cpt_store.compact.dirty = &cpt_dirty;
3294
3295
    /* Different blocks depending on whether we're using selection I/O */
3296
0
    if (io_info->use_select_io == H5D_SELECTION_IO_MODE_ON) {
3297
0
        size_t      num_chunks       = 0;
3298
0
        size_t      element_sizes[2] = {dset_info->type_info.dst_type_size, 0};
3299
0
        const void *bufs[2]          = {dset_info->buf.cvp, NULL};
3300
3301
        /* Only create selection I/O arrays if not performing multi dataset I/O,
3302
         * otherwise the higher level will handle it */
3303
0
        if (H5D_LAYOUT_CB_PERFORM_IO(io_info)) {
3304
            /* Cache number of chunks */
3305
0
            num_chunks = H5D_CHUNK_GET_NODE_COUNT(dset_info);
3306
3307
            /* Allocate arrays of dataspaces and offsets for use with selection I/O,
3308
             * or point to local buffers */
3309
0
            assert(sizeof(chunk_mem_spaces_local) / sizeof(chunk_mem_spaces_local[0]) ==
3310
0
                   sizeof(chunk_file_spaces_local) / sizeof(chunk_file_spaces_local[0]));
3311
0
            assert(sizeof(chunk_mem_spaces_local) / sizeof(chunk_mem_spaces_local[0]) ==
3312
0
                   sizeof(chunk_addrs_local) / sizeof(chunk_addrs_local[0]));
3313
0
            if (num_chunks > (sizeof(chunk_mem_spaces_local) / sizeof(chunk_mem_spaces_local[0]))) {
3314
0
                if (NULL == (chunk_mem_spaces = H5MM_malloc(num_chunks * sizeof(H5S_t *))))
3315
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_CANTALLOC, FAIL,
3316
0
                                "memory allocation failed for memory space list");
3317
0
                if (NULL == (chunk_file_spaces = H5MM_malloc(num_chunks * sizeof(H5S_t *))))
3318
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_CANTALLOC, FAIL,
3319
0
                                "memory allocation failed for file space list");
3320
0
                if (NULL == (chunk_addrs = H5MM_malloc(num_chunks * sizeof(haddr_t))))
3321
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_CANTALLOC, FAIL,
3322
0
                                "memory allocation failed for chunk address list");
3323
0
            } /* end if */
3324
0
            else {
3325
0
                chunk_mem_spaces  = chunk_mem_spaces_local;
3326
0
                chunk_file_spaces = chunk_file_spaces_local;
3327
0
                chunk_addrs       = chunk_addrs_local;
3328
0
            } /* end else */
3329
3330
            /* Reset num_chunks */
3331
0
            num_chunks = 0;
3332
0
        } /* end if */
3333
3334
        /* Iterate through nodes in chunk skip list */
3335
0
        chunk_node = H5D_CHUNK_GET_FIRST_NODE(dset_info);
3336
0
        while (chunk_node) {
3337
0
            H5D_piece_info_t  *chunk_info; /* Chunk information */
3338
0
            H5D_chk_idx_info_t idx_info;   /* Chunked index info */
3339
0
            htri_t             cacheable;  /* Whether the chunk is cacheable */
3340
0
            bool need_insert = false;      /* Whether the chunk needs to be inserted into the index */
3341
3342
            /* Get the actual chunk information from the skip list node */
3343
0
            chunk_info = H5D_CHUNK_GET_NODE_INFO(dset_info, chunk_node);
3344
3345
            /* Get the info for the chunk in the file */
3346
0
            if (H5D__chunk_lookup(dset_info->dset, chunk_info->scaled, &udata) < 0)
3347
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
3348
3349
            /* There should be no chunks cached */
3350
0
            assert(UINT_MAX == udata.idx_hint);
3351
3352
            /* Sanity check */
3353
0
            assert((H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length > 0) ||
3354
0
                   (!H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length == 0));
3355
3356
            /* Set chunk's [scaled] coordinates */
3357
0
            dset_info->store->chunk.scaled = chunk_info->scaled;
3358
3359
            /* Determine if we should use the chunk cache */
3360
0
            if ((cacheable = H5D__chunk_cacheable(io_info, dset_info, udata.chunk_block.offset, true)) < 0)
3361
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't tell if chunk is cacheable");
3362
0
            if (cacheable) {
3363
                /* Load the chunk into cache.  But if the whole chunk is written,
3364
                 * simply allocate space instead of load the chunk. */
3365
0
                bool entire_chunk = true; /* Whether whole chunk is selected */
3366
3367
                /* Compute # of bytes accessed in chunk */
3368
0
                H5_CHECK_OVERFLOW(dset_info->type_info.dst_type_size, /*From:*/ size_t, /*To:*/ hsize_t);
3369
0
                dst_accessed_bytes = chunk_info->piece_points * (hsize_t)dset_info->type_info.dst_type_size;
3370
3371
                /* Determine if we will access all the data in the chunk */
3372
0
                if (dst_accessed_bytes != ctg_store.contig.dset_size ||
3373
0
                    (chunk_info->piece_points * dset_info->type_info.src_type_size) !=
3374
0
                        ctg_store.contig.dset_size ||
3375
0
                    dset_info->layout_io_info.chunk_map->fsel_type == H5S_SEL_POINTS)
3376
0
                    entire_chunk = false;
3377
3378
                /* Lock the chunk into the cache */
3379
0
                if (NULL == (chunk = H5D__chunk_lock(io_info, dset_info, &udata, entire_chunk, false)))
3380
0
                    HGOTO_ERROR(H5E_IO, H5E_CANTLOCK, FAIL, "unable to lock raw data chunk");
3381
0
                chunk_locked = true;
3382
3383
                /* Set up the storage buffer information for this chunk */
3384
0
                cpt_store.compact.buf = chunk;
3385
3386
                /* Set up compact dataset info for write to cached chunk */
3387
0
                cpt_dset_info.layout_io_info.contig_piece_info = chunk_info;
3388
0
                cpt_dset_info.file_space                       = chunk_info->fspace;
3389
0
                cpt_dset_info.mem_space                        = chunk_info->mspace;
3390
0
                cpt_dset_info.nelmts                           = chunk_info->piece_points;
3391
3392
                /* Set request_nelmts.  This is not normally set by the upper layers because selection I/O
3393
                 * usually does not use strip mining (H5D__scatgath_write), and instead allocates buffers
3394
                 * large enough for the entire I/O.  Set request_nelmts to be large enough for all selected
3395
                 * elements in this chunk because it must be at least that large */
3396
0
                H5_CHECKED_ASSIGN(cpt_dset_info.type_info.request_nelmts, size_t, cpt_dset_info.nelmts,
3397
0
                                  hsize_t);
3398
3399
                /* Perform the actual write operation */
3400
0
                if ((dset_info->io_ops.single_write)(&cpt_io_info, &cpt_dset_info) < 0)
3401
0
                    HGOTO_ERROR(H5E_DATASET, H5E_WRITEERROR, FAIL, "chunked write failed");
3402
0
                chunk_dirty = true;
3403
3404
                /* Release the cache lock on the chunk */
3405
0
                chunk_locked = false;
3406
0
                if (H5D__chunk_unlock(io_info, dset_info, &udata, chunk_dirty, chunk, dst_accessed_bytes) < 0)
3407
0
                    HGOTO_ERROR(H5E_IO, H5E_CANTUNLOCK, FAIL, "unable to unlock raw data chunk");
3408
0
                chunk = NULL;
3409
0
            } /* end if */
3410
0
            else {
3411
                /* If the chunk hasn't been allocated on disk, do so now. */
3412
0
                if (!H5_addr_defined(udata.chunk_block.offset)) {
3413
                    /* Compose chunked index info struct */
3414
0
                    idx_info.f      = dset_info->dset->oloc.file;
3415
0
                    idx_info.pline  = &(dset_info->dset->shared->dcpl_cache.pline);
3416
0
                    idx_info.layout = &(dset_info->dset->shared->layout);
3417
3418
                    /* Set up the size of chunk for user data */
3419
0
                    udata.chunk_block.length = dset_info->dset->shared->layout.u.chunk.size;
3420
3421
                    /* Allocate the chunk */
3422
0
                    if (H5D__chunk_file_alloc(&idx_info, NULL, &udata.chunk_block, &need_insert,
3423
0
                                              chunk_info->scaled) < 0)
3424
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL,
3425
0
                                    "unable to insert/resize chunk on chunk level");
3426
3427
                    /* Make sure the address of the chunk is returned. */
3428
0
                    if (!H5_addr_defined(udata.chunk_block.offset))
3429
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "chunk address isn't defined");
3430
3431
                    /* Cache the new chunk information */
3432
0
                    H5D__chunk_cinfo_cache_update(&dset_info->dset->shared->cache.chunk.last, &udata);
3433
3434
                    /* Insert chunk into index */
3435
0
                    if (need_insert && dset_info->dset->shared->layout.storage.u.chunk.ops->insert)
3436
0
                        if ((dset_info->dset->shared->layout.storage.u.chunk.ops->insert)(&idx_info, &udata,
3437
0
                                                                                          NULL) < 0)
3438
0
                            HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL,
3439
0
                                        "unable to insert chunk addr into index");
3440
0
                } /* end if */
3441
3442
                /* Add chunk to list for selection I/O, if not performing multi dataset I/O */
3443
0
                if (H5D_LAYOUT_CB_PERFORM_IO(io_info)) {
3444
0
                    chunk_mem_spaces[num_chunks]  = chunk_info->mspace;
3445
0
                    chunk_file_spaces[num_chunks] = chunk_info->fspace;
3446
0
                    chunk_addrs[num_chunks]       = udata.chunk_block.offset;
3447
0
                    num_chunks++;
3448
0
                } /* end if */
3449
0
                else {
3450
                    /* Add to mdset selection I/O arrays */
3451
0
                    assert(io_info->mem_spaces);
3452
0
                    assert(io_info->file_spaces);
3453
0
                    assert(io_info->addrs);
3454
0
                    assert(io_info->element_sizes);
3455
0
                    assert(io_info->wbufs);
3456
0
                    assert(io_info->pieces_added < io_info->piece_count);
3457
3458
0
                    io_info->mem_spaces[io_info->pieces_added]    = chunk_info->mspace;
3459
0
                    io_info->file_spaces[io_info->pieces_added]   = chunk_info->fspace;
3460
0
                    io_info->addrs[io_info->pieces_added]         = udata.chunk_block.offset;
3461
0
                    io_info->element_sizes[io_info->pieces_added] = element_sizes[0];
3462
0
                    io_info->wbufs[io_info->pieces_added]         = bufs[0];
3463
0
                    if (io_info->sel_pieces)
3464
0
                        io_info->sel_pieces[io_info->pieces_added] = chunk_info;
3465
0
                    io_info->pieces_added++;
3466
3467
0
                    if (io_info->sel_pieces && chunk_info->filtered_dset)
3468
0
                        io_info->filtered_pieces_added++;
3469
0
                }
3470
0
            } /* end else */
3471
3472
            /* Advance to next chunk in list */
3473
0
            chunk_node = H5D_CHUNK_GET_NEXT_NODE(dset_info, chunk_node);
3474
0
        } /* end while */
3475
3476
        /* Only perform I/O if not performing multi dataset I/O or type conversion, otherwise the
3477
         * higher level will handle it after all datasets have been processed */
3478
0
        if (H5D_LAYOUT_CB_PERFORM_IO(io_info)) {
3479
            /* Issue selection I/O call (we can skip the page buffer because we've
3480
             * already verified it won't be used, and the metadata accumulator
3481
             * because this is raw data) */
3482
0
            H5_CHECK_OVERFLOW(num_chunks, size_t, uint32_t);
3483
0
            if (H5F_shared_select_write(H5F_SHARED(dset_info->dset->oloc.file), H5FD_MEM_DRAW,
3484
0
                                        (uint32_t)num_chunks, chunk_mem_spaces, chunk_file_spaces,
3485
0
                                        chunk_addrs, element_sizes, bufs) < 0)
3486
0
                HGOTO_ERROR(H5E_DATASET, H5E_WRITEERROR, FAIL, "chunk selection write failed");
3487
3488
            /* Clean up memory */
3489
0
            if (chunk_mem_spaces != chunk_mem_spaces_local) {
3490
0
                assert(chunk_file_spaces != chunk_file_spaces_local);
3491
0
                assert(chunk_addrs != chunk_addrs_local);
3492
0
                chunk_mem_spaces  = H5MM_xfree(chunk_mem_spaces);
3493
0
                chunk_file_spaces = H5MM_xfree(chunk_file_spaces);
3494
0
                chunk_addrs       = H5MM_xfree(chunk_addrs);
3495
0
            } /* end if */
3496
0
        }     /* end if */
3497
3498
#ifdef H5_HAVE_PARALLEL
3499
        /* Report that collective chunk I/O was used (will only be set on the DXPL if collective I/O was
3500
         * requested) */
3501
        io_info->actual_io_mode |= H5D_MPIO_CHUNK_COLLECTIVE;
3502
#endif /* H5_HAVE_PARALLEL */
3503
0
    }  /* end if */
3504
0
    else {
3505
        /* Iterate through nodes in chunk skip list */
3506
0
        chunk_node = H5D_CHUNK_GET_FIRST_NODE(dset_info);
3507
0
        while (chunk_node) {
3508
0
            H5D_piece_info_t  *chunk_info;         /* Chunk information */
3509
0
            H5D_chk_idx_info_t idx_info;           /* Chunked index info */
3510
0
            H5D_io_info_t     *chk_io_info = NULL; /* Pointer to I/O info object for this chunk */
3511
0
            htri_t             cacheable;          /* Whether the chunk is cacheable */
3512
0
            bool need_insert = false;              /* Whether the chunk needs to be inserted into the index */
3513
3514
            /* Get the actual chunk information from the skip list node */
3515
0
            chunk_info = H5D_CHUNK_GET_NODE_INFO(dset_info, chunk_node);
3516
3517
            /* Look up the chunk */
3518
0
            if (H5D__chunk_lookup(dset_info->dset, chunk_info->scaled, &udata) < 0)
3519
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
3520
3521
            /* Sanity check */
3522
0
            assert((H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length > 0) ||
3523
0
                   (!H5_addr_defined(udata.chunk_block.offset) && udata.chunk_block.length == 0));
3524
3525
            /* Set chunk's [scaled] coordinates */
3526
0
            dset_info->store->chunk.scaled = chunk_info->scaled;
3527
3528
            /* Determine if we should use the chunk cache */
3529
0
            if ((cacheable = H5D__chunk_cacheable(io_info, dset_info, udata.chunk_block.offset, true)) < 0)
3530
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't tell if chunk is cacheable");
3531
0
            if (cacheable) {
3532
                /* Load the chunk into cache.  But if the whole chunk is written,
3533
                 * simply allocate space instead of load the chunk. */
3534
0
                bool entire_chunk = true; /* Whether whole chunk is selected */
3535
3536
                /* Compute # of bytes accessed in chunk */
3537
0
                H5_CHECK_OVERFLOW(dset_info->type_info.dst_type_size, /*From:*/ size_t, /*To:*/ hsize_t);
3538
0
                dst_accessed_bytes = chunk_info->piece_points * (hsize_t)dset_info->type_info.dst_type_size;
3539
3540
                /* Determine if we will access all the data in the chunk */
3541
0
                if (dst_accessed_bytes != ctg_store.contig.dset_size ||
3542
0
                    (chunk_info->piece_points * dset_info->type_info.src_type_size) !=
3543
0
                        ctg_store.contig.dset_size ||
3544
0
                    dset_info->layout_io_info.chunk_map->fsel_type == H5S_SEL_POINTS)
3545
0
                    entire_chunk = false;
3546
3547
                /* Lock the chunk into the cache */
3548
0
                if (NULL == (chunk = H5D__chunk_lock(io_info, dset_info, &udata, entire_chunk, false)))
3549
0
                    HGOTO_ERROR(H5E_IO, H5E_CANTLOCK, FAIL, "unable to lock raw data chunk");
3550
0
                chunk_locked = true;
3551
3552
                /* Set up the storage buffer information for this chunk */
3553
0
                cpt_store.compact.buf = chunk;
3554
3555
                /* Point I/O info at main I/O info for this chunk */
3556
0
                chk_io_info = &cpt_io_info;
3557
0
            } /* end if */
3558
0
            else {
3559
                /* If the chunk hasn't been allocated on disk, do so now. */
3560
0
                if (!H5_addr_defined(udata.chunk_block.offset)) {
3561
                    /* Compose chunked index info struct */
3562
0
                    idx_info.f      = dset_info->dset->oloc.file;
3563
0
                    idx_info.pline  = &(dset_info->dset->shared->dcpl_cache.pline);
3564
0
                    idx_info.layout = &(dset_info->dset->shared->layout);
3565
3566
                    /* Set up the size of chunk for user data */
3567
0
                    udata.chunk_block.length = dset_info->dset->shared->layout.u.chunk.size;
3568
3569
                    /* Allocate the chunk */
3570
0
                    if (H5D__chunk_file_alloc(&idx_info, NULL, &udata.chunk_block, &need_insert,
3571
0
                                              chunk_info->scaled) < 0)
3572
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL,
3573
0
                                    "unable to insert/resize chunk on chunk level");
3574
3575
                    /* Make sure the address of the chunk is returned. */
3576
0
                    if (!H5_addr_defined(udata.chunk_block.offset))
3577
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "chunk address isn't defined");
3578
3579
                    /* Cache the new chunk information */
3580
0
                    H5D__chunk_cinfo_cache_update(&dset_info->dset->shared->cache.chunk.last, &udata);
3581
0
                } /* end if */
3582
3583
                /* Set up the storage address information for this chunk */
3584
0
                ctg_store.contig.dset_addr = udata.chunk_block.offset;
3585
3586
                /* No chunk cached */
3587
0
                chunk = NULL;
3588
3589
                /* Point I/O info at temporary I/O info for this chunk */
3590
0
                chk_io_info = &ctg_io_info;
3591
0
            } /* end else */
3592
3593
            /* Perform the actual write operation */
3594
0
            assert(chk_io_info);
3595
0
            assert(chk_io_info->count == 1);
3596
0
            chk_io_info->dsets_info[0].layout_io_info.contig_piece_info = chunk_info;
3597
0
            chk_io_info->dsets_info[0].file_space                       = chunk_info->fspace;
3598
0
            chk_io_info->dsets_info[0].mem_space                        = chunk_info->mspace;
3599
0
            chk_io_info->dsets_info[0].nelmts                           = chunk_info->piece_points;
3600
0
            if ((dset_info->io_ops.single_write)(chk_io_info, &chk_io_info->dsets_info[0]) < 0)
3601
0
                HGOTO_ERROR(H5E_DATASET, H5E_READERROR, FAIL, "chunked write failed");
3602
0
            chunk_dirty = true;
3603
3604
            /* Release the cache lock on the chunk, or insert chunk into index. */
3605
0
            if (chunk) {
3606
0
                chunk_locked = false;
3607
0
                if (H5D__chunk_unlock(io_info, dset_info, &udata, chunk_dirty, chunk, dst_accessed_bytes) < 0)
3608
0
                    HGOTO_ERROR(H5E_IO, H5E_CANTUNLOCK, FAIL, "unable to unlock raw data chunk");
3609
0
                chunk = NULL;
3610
0
            } /* end if */
3611
0
            else {
3612
0
                if (need_insert && dset_info->dset->shared->layout.storage.u.chunk.ops->insert)
3613
0
                    if ((dset_info->dset->shared->layout.storage.u.chunk.ops->insert)(&idx_info, &udata,
3614
0
                                                                                      NULL) < 0)
3615
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL,
3616
0
                                    "unable to insert chunk addr into index");
3617
0
            } /* end else */
3618
3619
            /* Advance to next chunk in list */
3620
0
            chunk_node = H5D_CHUNK_GET_NEXT_NODE(dset_info, chunk_node);
3621
0
        } /* end while */
3622
3623
        /*
3624
         * Flush any data in sieve buffer - for now, don't keep data cached
3625
         * in sieve buffer between writes / writes and reads.
3626
         */
3627
0
        if (H5D__flush_sieve_buf(dset_info->dset) < 0)
3628
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTFLUSH, FAIL, "unable to flush sieve buffer");
3629
0
    } /* end else */
3630
3631
0
done:
3632
    /* Release chunk lock if we failed while holding it */
3633
0
    if (chunk_locked && chunk)
3634
0
        if (H5D__chunk_unlock(io_info, dset_info, &udata, chunk_dirty, chunk, dst_accessed_bytes) < 0)
3635
0
            HDONE_ERROR(H5E_IO, H5E_CANTUNLOCK, FAIL, "unable to unlock raw data chunk");
3636
3637
    /* Free dataset sieve buffer and reset cached fields */
3638
0
    if (dset_info->dset->shared->cache.sieve.sieve_buf) {
3639
0
        dset_info->dset->shared->cache.sieve.sieve_loc  = HADDR_UNDEF;
3640
0
        dset_info->dset->shared->cache.sieve.sieve_size = 0;
3641
3642
        /* Drop any unflushed sieve buffer data on failure - reads expect
3643
         * that sieve buffer will be clean
3644
         */
3645
0
        dset_info->dset->shared->cache.sieve.sieve_dirty = false;
3646
3647
0
        dset_info->dset->shared->cache.sieve.sieve_buf =
3648
0
            (unsigned char *)H5FL_BLK_FREE(sieve_buf, dset_info->dset->shared->cache.sieve.sieve_buf);
3649
0
    }
3650
3651
    /* Cleanup on failure */
3652
0
    if (ret_value < 0) {
3653
0
        if (chunk_mem_spaces != chunk_mem_spaces_local)
3654
0
            chunk_mem_spaces = H5MM_xfree(chunk_mem_spaces);
3655
0
        if (chunk_file_spaces != chunk_file_spaces_local)
3656
0
            chunk_file_spaces = H5MM_xfree(chunk_file_spaces);
3657
0
        if (chunk_addrs != chunk_addrs_local)
3658
0
            chunk_addrs = H5MM_xfree(chunk_addrs);
3659
0
    } /* end if */
3660
3661
    /* Make sure we cleaned up */
3662
0
    assert(!chunk_mem_spaces || chunk_mem_spaces == chunk_mem_spaces_local);
3663
0
    assert(!chunk_file_spaces || chunk_file_spaces == chunk_file_spaces_local);
3664
0
    assert(!chunk_addrs || chunk_addrs == chunk_addrs_local);
3665
3666
0
    FUNC_LEAVE_NOAPI(ret_value)
3667
0
} /* H5D__chunk_write() */
3668
3669
/*-------------------------------------------------------------------------
3670
 * Function:    H5D__chunk_flush
3671
 *
3672
 * Purpose:    Writes all dirty chunks to disk and optionally preempts them
3673
 *        from the cache.
3674
 *
3675
 * Return:    Non-negative on success/Negative on failure
3676
 *
3677
 *-------------------------------------------------------------------------
3678
 */
3679
static herr_t
3680
H5D__chunk_flush(H5D_t *dset)
3681
0
{
3682
0
    H5D_rdcc_t     *rdcc = &(dset->shared->cache.chunk);
3683
0
    H5D_rdcc_ent_t *ent, *next;
3684
0
    unsigned        nerrors   = 0;       /* Count of any errors encountered when flushing chunks */
3685
0
    herr_t          ret_value = SUCCEED; /* Return value */
3686
3687
0
    FUNC_ENTER_PACKAGE
3688
3689
    /* Sanity check */
3690
0
    assert(dset);
3691
3692
    /* Flush any data in sieve buffer */
3693
0
    if (H5D__flush_sieve_buf(dset) < 0)
3694
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTFLUSH, FAIL, "unable to flush sieve buffer");
3695
3696
    /* Loop over all entries in the chunk cache */
3697
0
    for (ent = rdcc->head; ent; ent = next) {
3698
0
        next = ent->next;
3699
0
        if (H5D__chunk_flush_entry(dset, ent, false) < 0)
3700
0
            nerrors++;
3701
0
    } /* end for */
3702
0
    if (nerrors)
3703
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTFLUSH, FAIL, "unable to flush one or more raw data chunks");
3704
3705
0
done:
3706
0
    FUNC_LEAVE_NOAPI(ret_value)
3707
0
} /* end H5D__chunk_flush() */
3708
3709
/*-------------------------------------------------------------------------
3710
 * Function:    H5D__chunk_io_term
3711
 *
3712
 * Purpose:    Destroy I/O operation information.
3713
 *
3714
 * Return:    Non-negative on success/Negative on failure
3715
 *
3716
 *-------------------------------------------------------------------------
3717
 */
3718
static herr_t
3719
H5D__chunk_io_term(H5D_io_info_t H5_ATTR_UNUSED *io_info, H5D_dset_io_info_t *di)
3720
0
{
3721
0
    H5D_chunk_map_t *fm;                  /* Convenience pointer to chunk map */
3722
0
    herr_t           ret_value = SUCCEED; /*return value        */
3723
3724
0
    FUNC_ENTER_PACKAGE
3725
3726
0
    assert(di);
3727
3728
    /* Set convenience pointer */
3729
0
    fm = di->layout_io_info.chunk_map;
3730
3731
    /* Single element I/O vs. multiple element I/O cleanup */
3732
0
    if (fm->use_single) {
3733
        /* Sanity checks */
3734
0
        assert(fm->dset_sel_pieces == NULL);
3735
0
        assert(fm->last_piece_info == NULL);
3736
0
        assert(fm->single_piece_info);
3737
0
        assert(fm->single_piece_info->fspace_shared);
3738
0
        assert(fm->single_piece_info->mspace_shared);
3739
3740
        /* Reset the selection for the single element I/O */
3741
0
        H5S_select_all(fm->single_space, true);
3742
0
    } /* end if */
3743
0
    else {
3744
        /* Release the nodes on the list of selected pieces, or the last (only)
3745
         * piece if the skiplist is not available */
3746
0
        if (fm->dset_sel_pieces) {
3747
0
            if (H5SL_free(fm->dset_sel_pieces, H5D__free_piece_info, NULL) < 0)
3748
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTNEXT, FAIL, "can't free dataset skip list");
3749
0
        } /* end if */
3750
0
        else if (fm->last_piece_info) {
3751
0
            if (H5D__free_piece_info(fm->last_piece_info, NULL, NULL) < 0)
3752
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTFREE, FAIL, "can't free piece info");
3753
0
            fm->last_piece_info = NULL;
3754
0
        } /* end if */
3755
0
    }     /* end else */
3756
3757
    /* Free the memory piece dataspace template */
3758
0
    if (fm->mchunk_tmpl)
3759
0
        if (H5S_close(fm->mchunk_tmpl) < 0)
3760
0
            HGOTO_ERROR(H5E_DATASPACE, H5E_CANTRELEASE, FAIL,
3761
0
                        "can't release memory chunk dataspace template");
3762
3763
    /* Free chunk map */
3764
0
    di->layout_io_info.chunk_map = H5FL_FREE(H5D_chunk_map_t, di->layout_io_info.chunk_map);
3765
3766
0
done:
3767
0
    FUNC_LEAVE_NOAPI(ret_value)
3768
0
} /* end H5D__chunk_io_term() */
3769
3770
/*-------------------------------------------------------------------------
3771
 * Function:    H5D__chunk_dest
3772
 *
3773
 * Purpose:    Destroy the entire chunk cache by flushing dirty entries,
3774
 *        preempting all entries, and freeing the cache itself.
3775
 *
3776
 * Return:    Non-negative on success/Negative on failure
3777
 *
3778
 *-------------------------------------------------------------------------
3779
 */
3780
static herr_t
3781
H5D__chunk_dest(H5D_t *dset)
3782
0
{
3783
0
    H5D_chk_idx_info_t   idx_info;                            /* Chunked index info */
3784
0
    H5D_rdcc_t          *rdcc = &(dset->shared->cache.chunk); /* Dataset's chunk cache */
3785
0
    H5D_rdcc_ent_t      *ent = NULL, *next = NULL;            /* Pointer to current & next cache entries */
3786
0
    int                  nerrors   = 0;                       /* Accumulated count of errors */
3787
0
    H5O_storage_chunk_t *sc        = &(dset->shared->layout.storage.u.chunk);
3788
0
    herr_t               ret_value = SUCCEED; /* Return value */
3789
3790
0
    FUNC_ENTER_PACKAGE_TAG(dset->oloc.addr)
3791
3792
    /* Sanity checks */
3793
0
    assert(dset);
3794
0
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
3795
3796
    /* Flush all the cached chunks */
3797
0
    for (ent = rdcc->head; ent; ent = next) {
3798
0
        next = ent->next;
3799
0
        if (H5D__chunk_cache_evict(dset, ent, true) < 0)
3800
0
            nerrors++;
3801
0
    } /* end for */
3802
3803
    /* Continue even if there are failures. */
3804
0
    if (nerrors)
3805
0
        HDONE_ERROR(H5E_IO, H5E_CANTFLUSH, FAIL, "unable to flush one or more raw data chunks");
3806
3807
    /* Release cache structures */
3808
0
    if (rdcc->slot)
3809
0
        rdcc->slot = H5FL_SEQ_FREE(H5D_rdcc_ent_ptr_t, rdcc->slot);
3810
0
    memset(rdcc, 0, sizeof(H5D_rdcc_t));
3811
3812
    /* Compose chunked index info struct */
3813
0
    idx_info.f      = dset->oloc.file;
3814
0
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
3815
0
    idx_info.layout = &dset->shared->layout;
3816
3817
    /* Free any index structures */
3818
0
    if (sc->ops->dest && (sc->ops->dest)(&idx_info) < 0)
3819
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTFREE, FAIL, "unable to release chunk index info");
3820
3821
0
done:
3822
0
    FUNC_LEAVE_NOAPI_TAG(ret_value)
3823
0
} /* end H5D__chunk_dest() */
3824
3825
/*-------------------------------------------------------------------------
3826
 * Function:    H5D_chunk_idx_reset
3827
 *
3828
 * Purpose:    Reset index information
3829
 *
3830
 * Return:    Non-negative on success/Negative on failure
3831
 *
3832
 *-------------------------------------------------------------------------
3833
 */
3834
herr_t
3835
H5D_chunk_idx_reset(H5O_storage_chunk_t *storage, bool reset_addr)
3836
91
{
3837
91
    herr_t ret_value = SUCCEED; /* Return value */
3838
3839
91
    FUNC_ENTER_NOAPI(FAIL)
3840
3841
    /* Sanity checks */
3842
91
    assert(storage);
3843
91
    assert(storage->ops);
3844
91
    H5D_CHUNK_STORAGE_INDEX_CHK(storage);
3845
3846
    /* Reset index structures */
3847
91
    if ((storage->ops->reset)(storage, reset_addr) < 0)
3848
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTFREE, FAIL, "unable to reset chunk index info");
3849
3850
91
done:
3851
91
    FUNC_LEAVE_NOAPI(ret_value)
3852
91
} /* end H5D_chunk_idx_reset() */
3853
3854
/*-------------------------------------------------------------------------
3855
 * Function:    H5D__chunk_cinfo_cache_reset
3856
 *
3857
 * Purpose:    Reset the cached chunk info
3858
 *
3859
 * Return:    Non-negative on success/Negative on failure
3860
 *
3861
 *-------------------------------------------------------------------------
3862
 */
3863
static herr_t
3864
H5D__chunk_cinfo_cache_reset(H5D_chunk_cached_t *last)
3865
91
{
3866
91
    FUNC_ENTER_PACKAGE_NOERR
3867
3868
    /* Sanity check */
3869
91
    assert(last);
3870
3871
    /* Indicate that the cached info is not valid */
3872
91
    last->valid = false;
3873
3874
91
    FUNC_LEAVE_NOAPI(SUCCEED)
3875
91
} /* H5D__chunk_cinfo_cache_reset() */
3876
3877
/*-------------------------------------------------------------------------
3878
 * Function:    H5D__chunk_cinfo_cache_update
3879
 *
3880
 * Purpose:    Update the cached chunk info
3881
 *
3882
 * Return:    Non-negative on success/Negative on failure
3883
 *
3884
 *-------------------------------------------------------------------------
3885
 */
3886
static herr_t
3887
H5D__chunk_cinfo_cache_update(H5D_chunk_cached_t *last, const H5D_chunk_ud_t *udata)
3888
0
{
3889
0
    FUNC_ENTER_PACKAGE_NOERR
3890
3891
    /* Sanity check */
3892
0
    assert(last);
3893
0
    assert(udata);
3894
0
    assert(udata->common.layout);
3895
0
    assert(udata->common.scaled);
3896
3897
    /* Stored the information to cache */
3898
0
    H5MM_memcpy(last->scaled, udata->common.scaled, sizeof(hsize_t) * udata->common.layout->ndims);
3899
0
    last->addr        = udata->chunk_block.offset;
3900
0
    last->nbytes      = udata->chunk_block.length;
3901
0
    last->chunk_idx   = udata->chunk_idx;
3902
0
    last->filter_mask = udata->filter_mask;
3903
3904
    /* Indicate that the cached info is valid */
3905
0
    last->valid = true;
3906
3907
0
    FUNC_LEAVE_NOAPI(SUCCEED)
3908
0
} /* H5D__chunk_cinfo_cache_update() */
3909
3910
/*-------------------------------------------------------------------------
3911
 * Function:    H5D__chunk_cinfo_cache_found
3912
 *
3913
 * Purpose:    Look for chunk info in cache
3914
 *
3915
 * Return:    true/false/FAIL
3916
 *
3917
 *-------------------------------------------------------------------------
3918
 */
3919
static bool
3920
H5D__chunk_cinfo_cache_found(const H5D_chunk_cached_t *last, H5D_chunk_ud_t *udata)
3921
0
{
3922
0
    bool ret_value = false; /* Return value */
3923
3924
0
    FUNC_ENTER_PACKAGE_NOERR
3925
3926
    /* Sanity check */
3927
0
    assert(last);
3928
0
    assert(udata);
3929
0
    assert(udata->common.layout);
3930
0
    assert(udata->common.scaled);
3931
3932
    /* Check if the cached information is what is desired */
3933
0
    if (last->valid) {
3934
0
        unsigned u; /* Local index variable */
3935
3936
        /* Check that the scaled offset is the same */
3937
0
        for (u = 0; u < udata->common.layout->ndims; u++)
3938
0
            if (last->scaled[u] != udata->common.scaled[u])
3939
0
                HGOTO_DONE(false);
3940
3941
        /* Retrieve the information from the cache */
3942
0
        udata->chunk_block.offset = last->addr;
3943
0
        udata->chunk_block.length = last->nbytes;
3944
0
        udata->chunk_idx          = last->chunk_idx;
3945
0
        udata->filter_mask        = last->filter_mask;
3946
3947
        /* Indicate that the data was found */
3948
0
        HGOTO_DONE(true);
3949
0
    } /* end if */
3950
3951
0
done:
3952
0
    FUNC_LEAVE_NOAPI(ret_value)
3953
0
} /* H5D__chunk_cinfo_cache_found() */
3954
3955
/*-------------------------------------------------------------------------
3956
 * Function:    H5D__chunk_create
3957
 *
3958
 * Purpose:    Creates a new chunked storage index and initializes the
3959
 *        layout information with information about the storage.  The
3960
 *        layout info should be immediately written to the object header.
3961
 *
3962
 * Return:    Non-negative on success (with the layout information initialized
3963
 *        and ready to write to an object header). Negative on failure.
3964
 *
3965
 *-------------------------------------------------------------------------
3966
 */
3967
herr_t
3968
H5D__chunk_create(const H5D_t *dset /*in,out*/)
3969
0
{
3970
0
    H5D_chk_idx_info_t   idx_info; /* Chunked index info */
3971
0
    H5O_storage_chunk_t *sc        = &(dset->shared->layout.storage.u.chunk);
3972
0
    herr_t               ret_value = SUCCEED; /* Return value */
3973
3974
0
    FUNC_ENTER_PACKAGE
3975
3976
    /* Check args */
3977
0
    assert(dset);
3978
0
    assert(H5D_CHUNKED == dset->shared->layout.type);
3979
0
    assert(dset->shared->layout.u.chunk.ndims > 0 && dset->shared->layout.u.chunk.ndims <= H5O_LAYOUT_NDIMS);
3980
0
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
3981
3982
#ifndef NDEBUG
3983
    {
3984
        unsigned u; /* Local index variable */
3985
3986
        for (u = 0; u < dset->shared->layout.u.chunk.ndims; u++)
3987
            assert(dset->shared->layout.u.chunk.dim[u] > 0);
3988
    }
3989
#endif
3990
3991
    /* Compose chunked index info struct */
3992
0
    idx_info.f      = dset->oloc.file;
3993
0
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
3994
0
    idx_info.layout = &dset->shared->layout;
3995
3996
    /* Create the index for the chunks */
3997
0
    if ((sc->ops->create)(&idx_info) < 0)
3998
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "can't create chunk index");
3999
4000
0
done:
4001
0
    FUNC_LEAVE_NOAPI(ret_value)
4002
0
} /* end H5D__chunk_create() */
4003
4004
/*-------------------------------------------------------------------------
4005
 * Function:    H5D__chunk_hash_val
4006
 *
4007
 * Purpose:     To calculate an index based on the dataset's scaled
4008
 *              coordinates and sizes of the faster dimensions.
4009
 *
4010
 * Return:    Hash value index
4011
 *
4012
 *-------------------------------------------------------------------------
4013
 */
4014
static unsigned
4015
H5D__chunk_hash_val(const H5D_shared_t *shared, const hsize_t *scaled)
4016
0
{
4017
0
    hsize_t  val;                   /* Intermediate value */
4018
0
    unsigned ndims = shared->ndims; /* Rank of dataset */
4019
0
    unsigned ret   = 0;             /* Value to return */
4020
0
    unsigned u;                     /* Local index variable */
4021
4022
0
    FUNC_ENTER_PACKAGE_NOERR
4023
4024
    /* Sanity check */
4025
0
    assert(shared);
4026
0
    assert(scaled);
4027
4028
    /* If the fastest changing dimension doesn't have enough entropy, use
4029
     *  other dimensions too
4030
     */
4031
0
    val = scaled[0];
4032
0
    for (u = 1; u < ndims; u++) {
4033
0
        val <<= shared->cache.chunk.scaled_encode_bits[u];
4034
0
        val ^= scaled[u];
4035
0
    } /* end for */
4036
4037
    /* Modulo value against the number of array slots */
4038
0
    ret = (unsigned)(val % shared->cache.chunk.nslots);
4039
4040
0
    FUNC_LEAVE_NOAPI(ret)
4041
0
} /* H5D__chunk_hash_val() */
4042
4043
/*-------------------------------------------------------------------------
4044
 * Function:    H5D__chunk_lookup
4045
 *
4046
 * Purpose:    Loops up a chunk in cache and on disk, and retrieves
4047
 *              information about that chunk.
4048
 *
4049
 * Return:    Non-negative on success/Negative on failure
4050
 *
4051
 *-------------------------------------------------------------------------
4052
 */
4053
herr_t
4054
H5D__chunk_lookup(const H5D_t *dset, const hsize_t *scaled, H5D_chunk_ud_t *udata)
4055
0
{
4056
0
    H5D_rdcc_ent_t      *ent   = NULL; /* Cache entry */
4057
0
    H5O_storage_chunk_t *sc    = &(dset->shared->layout.storage.u.chunk);
4058
0
    unsigned             idx   = 0;     /* Index of chunk in cache, if present */
4059
0
    bool                 found = false; /* In cache? */
4060
#ifdef H5_HAVE_PARALLEL
4061
    H5P_coll_md_read_flag_t md_reads_file_flag;
4062
    bool                    md_reads_context_flag;
4063
    bool                    restore_md_reads_state = false;
4064
#endif
4065
0
    herr_t ret_value = SUCCEED; /* Return value */
4066
4067
0
    FUNC_ENTER_PACKAGE
4068
4069
    /* Sanity checks */
4070
0
    assert(dset);
4071
0
    assert(dset->shared->layout.u.chunk.ndims > 0);
4072
0
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
4073
0
    assert(scaled);
4074
0
    assert(udata);
4075
4076
    /* Initialize the query information about the chunk we are looking for */
4077
0
    udata->common.layout  = &(dset->shared->layout.u.chunk);
4078
0
    udata->common.storage = sc;
4079
0
    udata->common.scaled  = scaled;
4080
4081
    /* Reset information about the chunk we are looking for */
4082
0
    udata->chunk_block.offset = HADDR_UNDEF;
4083
0
    udata->chunk_block.length = 0;
4084
0
    udata->filter_mask        = 0;
4085
0
    udata->new_unfilt_chunk   = false;
4086
4087
    /* Check for chunk in cache */
4088
0
    if (dset->shared->cache.chunk.nslots > 0) {
4089
        /* Determine the chunk's location in the hash table */
4090
0
        idx = H5D__chunk_hash_val(dset->shared, scaled);
4091
4092
        /* Get the chunk cache entry for that location */
4093
0
        ent = dset->shared->cache.chunk.slot[idx];
4094
0
        if (ent) {
4095
0
            unsigned u; /* Counter */
4096
4097
            /* Speculatively set the 'found' flag */
4098
0
            found = true;
4099
4100
            /* Verify that the cache entry is the correct chunk */
4101
0
            for (u = 0; u < dset->shared->ndims; u++)
4102
0
                if (scaled[u] != ent->scaled[u]) {
4103
0
                    found = false;
4104
0
                    break;
4105
0
                } /* end if */
4106
0
        }         /* end if */
4107
0
    }             /* end if */
4108
4109
    /* Retrieve chunk addr */
4110
0
    if (found) {
4111
0
        udata->idx_hint           = idx;
4112
0
        udata->chunk_block.offset = ent->chunk_block.offset;
4113
0
        udata->chunk_block.length = ent->chunk_block.length;
4114
0
        udata->chunk_idx          = ent->chunk_idx;
4115
0
    } /* end if */
4116
0
    else {
4117
        /* Invalidate idx_hint, to signal that the chunk is not in cache */
4118
0
        udata->idx_hint = UINT_MAX;
4119
4120
        /* Check for cached information */
4121
0
        if (!H5D__chunk_cinfo_cache_found(&dset->shared->cache.chunk.last, udata)) {
4122
0
            H5D_chk_idx_info_t idx_info; /* Chunked index info */
4123
4124
            /* Compose chunked index info struct */
4125
0
            idx_info.f      = dset->oloc.file;
4126
0
            idx_info.pline  = &dset->shared->dcpl_cache.pline;
4127
0
            idx_info.layout = &dset->shared->layout;
4128
4129
#ifdef H5_HAVE_PARALLEL
4130
            if (H5F_HAS_FEATURE(idx_info.f, H5FD_FEAT_HAS_MPI)) {
4131
                /* Disable collective metadata read for chunk indexes as it is
4132
                 * highly unlikely that users would read the same chunks from all
4133
                 * processes.
4134
                 */
4135
                if (H5F_get_coll_metadata_reads(idx_info.f)) {
4136
#ifndef NDEBUG
4137
                    bool index_is_open;
4138
4139
                    /*
4140
                     * The dataset's chunk index should be open at this point.
4141
                     * Otherwise, we will end up reading it in independently,
4142
                     * which may not be desired.
4143
                     */
4144
                    sc->ops->is_open(&idx_info, &index_is_open);
4145
                    assert(index_is_open);
4146
#endif
4147
4148
                    md_reads_file_flag    = H5P_FORCE_FALSE;
4149
                    md_reads_context_flag = false;
4150
                    H5F_set_coll_metadata_reads(idx_info.f, &md_reads_file_flag, &md_reads_context_flag);
4151
                    restore_md_reads_state = true;
4152
                }
4153
            }
4154
#endif /* H5_HAVE_PARALLEL */
4155
4156
            /* Go get the chunk information */
4157
0
            if ((sc->ops->get_addr)(&idx_info, udata) < 0)
4158
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't query chunk address");
4159
4160
                /*
4161
                 * Cache the information retrieved.
4162
                 *
4163
                 * Note that if we are writing to the dataset in parallel and filters
4164
                 * are involved, we skip caching this information as it is highly likely
4165
                 * that the chunk information will be invalidated as a result of the
4166
                 * filter operation (e.g. the chunk gets re-allocated to a different
4167
                 * address in the file and/or gets re-allocated with a different size).
4168
                 * If we were to cache this information, subsequent reads/writes would
4169
                 * retrieve the invalid information and cause a variety of issues.
4170
                 *
4171
                 * It has been verified that in the serial library, when writing to chunks
4172
                 * with the real chunk cache disabled and with filters involved, the
4173
                 * functions within this file are correctly called in such a manner that
4174
                 * this single chunk cache is always updated correctly. Therefore, this
4175
                 * check is not needed for the serial library.
4176
                 *
4177
                 * This is an ugly and potentially frail check, but the
4178
                 * H5D__chunk_cinfo_cache_reset() function is not currently available
4179
                 * to functions outside of this file, so outside functions can not
4180
                 * invalidate this single chunk cache. Even if the function were available,
4181
                 * this check prevents us from doing the work of going through and caching
4182
                 * each chunk in the write operation, when we're only going to invalidate
4183
                 * the cache at the end of a parallel write anyway.
4184
                 *
4185
                 *  - JTH (7/13/2018)
4186
                 */
4187
#ifdef H5_HAVE_PARALLEL
4188
            if (!((H5F_HAS_FEATURE(idx_info.f, H5FD_FEAT_HAS_MPI)) &&
4189
                  (H5F_INTENT(dset->oloc.file) & H5F_ACC_RDWR) && dset->shared->dcpl_cache.pline.nused))
4190
#endif
4191
0
                H5D__chunk_cinfo_cache_update(&dset->shared->cache.chunk.last, udata);
4192
0
        } /* end if */
4193
0
    }     /* end else */
4194
4195
0
done:
4196
#ifdef H5_HAVE_PARALLEL
4197
    /* Re-enable collective metadata reads if we disabled them */
4198
    if (restore_md_reads_state)
4199
        H5F_set_coll_metadata_reads(dset->oloc.file, &md_reads_file_flag, &md_reads_context_flag);
4200
#endif /* H5_HAVE_PARALLEL */
4201
4202
0
    FUNC_LEAVE_NOAPI(ret_value)
4203
0
} /* H5D__chunk_lookup() */
4204
4205
/*-------------------------------------------------------------------------
4206
 * Function:    H5D__chunk_flush_entry
4207
 *
4208
 * Purpose:    Writes a chunk to disk.  If RESET is non-zero then the
4209
 *        entry is cleared -- it's slightly faster to flush a chunk if
4210
 *        the RESET flag is turned on because it results in one fewer
4211
 *        memory copy.
4212
 *
4213
 * Return:    Non-negative on success/Negative on failure
4214
 *
4215
 *-------------------------------------------------------------------------
4216
 */
4217
static herr_t
4218
H5D__chunk_flush_entry(const H5D_t *dset, H5D_rdcc_ent_t *ent, bool reset)
4219
0
{
4220
0
    void                *buf                = NULL; /* Temporary buffer        */
4221
0
    bool                 point_of_no_return = false;
4222
0
    H5O_storage_chunk_t *sc                 = &(dset->shared->layout.storage.u.chunk);
4223
0
    herr_t               ret_value          = SUCCEED; /* Return value            */
4224
4225
0
    FUNC_ENTER_PACKAGE
4226
4227
0
    assert(dset);
4228
0
    assert(dset->shared);
4229
0
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
4230
0
    assert(ent);
4231
0
    assert(!ent->locked);
4232
4233
0
    buf = ent->chunk;
4234
0
    if (ent->dirty) {
4235
0
        H5D_chk_idx_info_t idx_info;            /* Chunked index info */
4236
0
        H5D_chunk_ud_t     udata;               /* pass through B-tree        */
4237
0
        bool               must_alloc  = false; /* Whether the chunk must be allocated */
4238
0
        bool               need_insert = false; /* Whether the chunk needs to be inserted into the index */
4239
4240
        /* Set up user data for index callbacks */
4241
0
        udata.common.layout      = &dset->shared->layout.u.chunk;
4242
0
        udata.common.storage     = sc;
4243
0
        udata.common.scaled      = ent->scaled;
4244
0
        udata.chunk_block.offset = ent->chunk_block.offset;
4245
0
        udata.chunk_block.length = dset->shared->layout.u.chunk.size;
4246
0
        udata.filter_mask        = 0;
4247
0
        udata.chunk_idx          = ent->chunk_idx;
4248
4249
        /* Should the chunk be filtered before writing it to disk? */
4250
0
        if (dset->shared->dcpl_cache.pline.nused && !(ent->edge_chunk_state & H5D_RDCC_DISABLE_FILTERS)) {
4251
0
            H5Z_EDC_t err_detect; /* Error detection info */
4252
0
            H5Z_cb_t  filter_cb;  /* I/O filter callback function */
4253
0
            size_t    alloc;      /* Bytes allocated for BUF    */
4254
0
            size_t    nbytes;     /* Chunk size (in bytes) */
4255
4256
            /* Assign alloc and check for overflow */
4257
0
            H5_CHECKED_ASSIGN(alloc, size_t, udata.chunk_block.length, hsize_t);
4258
4259
            /* Retrieve filter settings from API context */
4260
0
            if (H5CX_get_err_detect(&err_detect) < 0)
4261
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't get error detection info");
4262
0
            if (H5CX_get_filter_cb(&filter_cb) < 0)
4263
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't get I/O filter callback function");
4264
4265
0
            if (!reset) {
4266
                /*
4267
                 * Copy the chunk to a new buffer before running it through
4268
                 * the pipeline because we'll want to save the original buffer
4269
                 * for later.
4270
                 */
4271
0
                if (NULL == (buf = H5MM_malloc(alloc)))
4272
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed for pipeline");
4273
0
                H5MM_memcpy(buf, ent->chunk, alloc);
4274
0
            } /* end if */
4275
0
            else {
4276
                /*
4277
                 * If we are resetting and something goes wrong after this
4278
                 * point then it's too late to recover because we may have
4279
                 * destroyed the original data by calling H5Z_pipeline().
4280
                 * The only safe option is to continue with the reset
4281
                 * even if we can't write the data to disk.
4282
                 */
4283
0
                point_of_no_return = true;
4284
0
                ent->chunk         = NULL;
4285
0
            } /* end else */
4286
0
            H5_CHECKED_ASSIGN(nbytes, size_t, udata.chunk_block.length, hsize_t);
4287
0
            if (H5Z_pipeline(&(dset->shared->dcpl_cache.pline), 0, &(udata.filter_mask), err_detect,
4288
0
                             filter_cb, &nbytes, &alloc, &buf) < 0)
4289
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTFILTER, FAIL, "output pipeline failed");
4290
4291
0
            H5_CHECKED_ASSIGN(udata.chunk_block.length, hsize_t, nbytes, size_t);
4292
4293
            /* Indicate that the chunk must be allocated */
4294
0
            must_alloc = true;
4295
0
        } /* end if */
4296
0
        else if (!H5_addr_defined(udata.chunk_block.offset)) {
4297
            /* Indicate that the chunk must be allocated */
4298
0
            must_alloc = true;
4299
4300
            /* This flag could be set for this chunk, just remove and ignore it
4301
             */
4302
0
            ent->edge_chunk_state &= ~H5D_RDCC_NEWLY_DISABLED_FILTERS;
4303
0
        } /* end else */
4304
0
        else if (ent->edge_chunk_state & H5D_RDCC_NEWLY_DISABLED_FILTERS) {
4305
            /* Chunk on disk is still filtered, must insert to allocate correct
4306
             * size */
4307
0
            must_alloc = true;
4308
4309
            /* Set the disable filters field back to the standard disable
4310
             * filters setting, as it no longer needs to be inserted with every
4311
             * flush */
4312
0
            ent->edge_chunk_state &= ~H5D_RDCC_NEWLY_DISABLED_FILTERS;
4313
0
        } /* end else */
4314
4315
0
        assert(!(ent->edge_chunk_state & H5D_RDCC_NEWLY_DISABLED_FILTERS));
4316
4317
        /* Check if the chunk needs to be allocated (it also could exist already
4318
         *      and the chunk alloc operation could resize it)
4319
         */
4320
0
        if (must_alloc) {
4321
            /* Compose chunked index info struct */
4322
0
            idx_info.f      = dset->oloc.file;
4323
0
            idx_info.pline  = &dset->shared->dcpl_cache.pline;
4324
0
            idx_info.layout = &dset->shared->layout;
4325
4326
            /* Create the chunk it if it doesn't exist, or reallocate the chunk
4327
             *  if its size changed.
4328
             */
4329
0
            if (H5D__chunk_file_alloc(&idx_info, &(ent->chunk_block), &udata.chunk_block, &need_insert,
4330
0
                                      ent->scaled) < 0)
4331
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL,
4332
0
                            "unable to insert/resize chunk on chunk level");
4333
4334
            /* Update the chunk entry's info, in case it was allocated or relocated */
4335
0
            ent->chunk_block.offset = udata.chunk_block.offset;
4336
0
            ent->chunk_block.length = udata.chunk_block.length;
4337
0
        } /* end if */
4338
4339
        /* Write the data to the file */
4340
0
        assert(H5_addr_defined(udata.chunk_block.offset));
4341
0
        H5_CHECK_OVERFLOW(udata.chunk_block.length, hsize_t, size_t);
4342
0
        if (H5F_shared_block_write(H5F_SHARED(dset->oloc.file), H5FD_MEM_DRAW, udata.chunk_block.offset,
4343
0
                                   (size_t)udata.chunk_block.length, buf) < 0)
4344
0
            HGOTO_ERROR(H5E_DATASET, H5E_WRITEERROR, FAIL, "unable to write raw data to file");
4345
4346
        /* Insert the chunk record into the index */
4347
0
        if (need_insert && sc->ops->insert)
4348
0
            if ((sc->ops->insert)(&idx_info, &udata, dset) < 0)
4349
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL, "unable to insert chunk addr into index");
4350
4351
        /* Cache the chunk's info, in case it's accessed again shortly */
4352
0
        H5D__chunk_cinfo_cache_update(&dset->shared->cache.chunk.last, &udata);
4353
4354
        /* Mark cache entry as clean */
4355
0
        ent->dirty = false;
4356
4357
        /* Increment # of flushed entries */
4358
0
        dset->shared->cache.chunk.stats.nflushes++;
4359
0
    } /* end if */
4360
4361
    /* Reset, but do not free or removed from list */
4362
0
    if (reset) {
4363
0
        point_of_no_return = false;
4364
0
        if (buf == ent->chunk)
4365
0
            buf = NULL;
4366
0
        if (ent->chunk != NULL)
4367
0
            ent->chunk = (uint8_t *)H5D__chunk_mem_xfree(ent->chunk,
4368
0
                                                         ((ent->edge_chunk_state & H5D_RDCC_DISABLE_FILTERS)
4369
0
                                                              ? NULL
4370
0
                                                              : &(dset->shared->dcpl_cache.pline)));
4371
0
    } /* end if */
4372
4373
0
done:
4374
    /* Free the temp buffer only if it's different than the entry chunk */
4375
0
    if (buf != ent->chunk)
4376
0
        H5MM_xfree(buf);
4377
4378
    /*
4379
     * If we reached the point of no return then we have no choice but to
4380
     * reset the entry.  This can only happen if RESET is true but the
4381
     * output pipeline failed.  Do not free the entry or remove it from the
4382
     * list.
4383
     */
4384
0
    if (ret_value < 0 && point_of_no_return)
4385
0
        if (ent->chunk)
4386
0
            ent->chunk = (uint8_t *)H5D__chunk_mem_xfree(ent->chunk,
4387
0
                                                         ((ent->edge_chunk_state & H5D_RDCC_DISABLE_FILTERS)
4388
0
                                                              ? NULL
4389
0
                                                              : &(dset->shared->dcpl_cache.pline)));
4390
4391
0
    FUNC_LEAVE_NOAPI(ret_value)
4392
0
} /* end H5D__chunk_flush_entry() */
4393
4394
/*-------------------------------------------------------------------------
4395
 * Function:    H5D__chunk_cache_evict
4396
 *
4397
 * Purpose:     Preempts the specified entry from the cache, flushing it to
4398
 *              disk if necessary.
4399
 *
4400
 * Return:      Non-negative on success/Negative on failure
4401
 *
4402
 *-------------------------------------------------------------------------
4403
 */
4404
static herr_t
4405
H5D__chunk_cache_evict(const H5D_t *dset, H5D_rdcc_ent_t *ent, bool flush)
4406
0
{
4407
0
    H5D_rdcc_t *rdcc      = &(dset->shared->cache.chunk);
4408
0
    herr_t      ret_value = SUCCEED; /* Return value */
4409
4410
0
    FUNC_ENTER_PACKAGE
4411
4412
    /* Sanity checks */
4413
0
    assert(dset);
4414
0
    assert(ent);
4415
0
    assert(!ent->locked);
4416
0
    assert(ent->idx < rdcc->nslots);
4417
4418
0
    if (flush) {
4419
        /* Flush */
4420
0
        if (H5D__chunk_flush_entry(dset, ent, true) < 0)
4421
0
            HDONE_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "cannot flush indexed storage buffer");
4422
0
    } /* end if */
4423
0
    else {
4424
        /* Don't flush, just free chunk */
4425
0
        if (ent->chunk != NULL)
4426
0
            ent->chunk = (uint8_t *)H5D__chunk_mem_xfree(ent->chunk,
4427
0
                                                         ((ent->edge_chunk_state & H5D_RDCC_DISABLE_FILTERS)
4428
0
                                                              ? NULL
4429
0
                                                              : &(dset->shared->dcpl_cache.pline)));
4430
0
    } /* end else */
4431
4432
    /* Unlink from list */
4433
0
    if (ent->prev)
4434
0
        ent->prev->next = ent->next;
4435
0
    else
4436
0
        rdcc->head = ent->next;
4437
0
    if (ent->next)
4438
0
        ent->next->prev = ent->prev;
4439
0
    else
4440
0
        rdcc->tail = ent->prev;
4441
0
    ent->prev = ent->next = NULL;
4442
4443
    /* Unlink from temporary list */
4444
0
    if (ent->tmp_prev) {
4445
0
        assert(rdcc->tmp_head->tmp_next);
4446
0
        ent->tmp_prev->tmp_next = ent->tmp_next;
4447
0
        if (ent->tmp_next) {
4448
0
            ent->tmp_next->tmp_prev = ent->tmp_prev;
4449
0
            ent->tmp_next           = NULL;
4450
0
        } /* end if */
4451
0
        ent->tmp_prev = NULL;
4452
0
    } /* end if */
4453
0
    else
4454
        /* Only clear hash table slot if the chunk was not on the temporary list
4455
         */
4456
0
        rdcc->slot[ent->idx] = NULL;
4457
4458
    /* Remove from cache */
4459
0
    assert(rdcc->slot[ent->idx] != ent);
4460
0
    ent->idx = UINT_MAX;
4461
0
    rdcc->nbytes_used -= (size_t)dset->shared->layout.u.chunk.size;
4462
0
    --rdcc->nused;
4463
4464
    /* Free */
4465
0
    ent = H5FL_FREE(H5D_rdcc_ent_t, ent);
4466
4467
0
    FUNC_LEAVE_NOAPI(ret_value)
4468
0
} /* end H5D__chunk_cache_evict() */
4469
4470
/*-------------------------------------------------------------------------
4471
 * Function:    H5D__chunk_cache_prune
4472
 *
4473
 * Purpose:    Prune the cache by preempting some things until the cache has
4474
 *        room for something which is SIZE bytes.  Only unlocked
4475
 *        entries are considered for preemption.
4476
 *
4477
 * Return:    Non-negative on success/Negative on failure
4478
 *
4479
 *-------------------------------------------------------------------------
4480
 */
4481
static herr_t
4482
H5D__chunk_cache_prune(const H5D_t *dset, size_t size)
4483
0
{
4484
0
    const H5D_rdcc_t *rdcc  = &(dset->shared->cache.chunk);
4485
0
    size_t            total = rdcc->nbytes_max;
4486
0
    const int         nmeth = 2;           /* Number of methods */
4487
0
    int               w[1];                /* Weighting as an interval */
4488
0
    H5D_rdcc_ent_t   *p[2], *cur;          /* List pointers */
4489
0
    H5D_rdcc_ent_t   *n[2];                /* List next pointers */
4490
0
    int               nerrors   = 0;       /* Accumulated error count during preemptions */
4491
0
    herr_t            ret_value = SUCCEED; /* Return value */
4492
4493
0
    FUNC_ENTER_PACKAGE
4494
4495
    /*
4496
     * Preemption is accomplished by having multiple pointers (currently two)
4497
     * slide down the list beginning at the head. Pointer p(N+1) will start
4498
     * traversing the list when pointer pN reaches wN percent of the original
4499
     * list.  In other words, preemption method N gets to consider entries in
4500
     * approximate least recently used order w0 percent before method N+1
4501
     * where 100% means the method N will run to completion before method N+1
4502
     * begins.  The pointers participating in the list traversal are each
4503
     * given a chance at preemption before any of the pointers are advanced.
4504
     */
4505
0
    w[0] = (int)(rdcc->nused * rdcc->w0);
4506
0
    p[0] = rdcc->head;
4507
0
    p[1] = NULL;
4508
4509
0
    while ((p[0] || p[1]) && (rdcc->nbytes_used + size) > total) {
4510
0
        int i; /* Local index variable */
4511
4512
        /* Introduce new pointers */
4513
0
        for (i = 0; i < nmeth - 1; i++)
4514
0
            if (0 == w[i])
4515
0
                p[i + 1] = rdcc->head;
4516
4517
        /* Compute next value for each pointer */
4518
0
        for (i = 0; i < nmeth; i++)
4519
0
            n[i] = p[i] ? p[i]->next : NULL;
4520
4521
        /* Give each method a chance */
4522
0
        for (i = 0; i < nmeth && (rdcc->nbytes_used + size) > total; i++) {
4523
0
            if (0 == i && p[0] && !p[0]->locked &&
4524
0
                ((0 == p[0]->rd_count && 0 == p[0]->wr_count) ||
4525
0
                 (0 == p[0]->rd_count && dset->shared->layout.u.chunk.size == p[0]->wr_count) ||
4526
0
                 (dset->shared->layout.u.chunk.size == p[0]->rd_count && 0 == p[0]->wr_count))) {
4527
                /*
4528
                 * Method 0: Preempt entries that have been completely written
4529
                 * and/or completely read but not entries that are partially
4530
                 * written or partially read.
4531
                 */
4532
0
                cur = p[0];
4533
0
            }
4534
0
            else if (1 == i && p[1] && !p[1]->locked) {
4535
                /*
4536
                 * Method 1: Preempt the entry without regard to
4537
                 * considerations other than being locked.  This is the last
4538
                 * resort preemption.
4539
                 */
4540
0
                cur = p[1];
4541
0
            }
4542
0
            else {
4543
                /* Nothing to preempt at this point */
4544
0
                cur = NULL;
4545
0
            }
4546
4547
0
            if (cur) {
4548
0
                int j; /* Local index variable */
4549
4550
0
                for (j = 0; j < nmeth; j++) {
4551
0
                    if (p[j] == cur)
4552
0
                        p[j] = NULL;
4553
0
                    if (n[j] == cur)
4554
0
                        n[j] = cur->next;
4555
0
                } /* end for */
4556
0
                if (H5D__chunk_cache_evict(dset, cur, true) < 0)
4557
0
                    nerrors++;
4558
0
            } /* end if */
4559
0
        }     /* end for */
4560
4561
        /* Advance pointers */
4562
0
        for (i = 0; i < nmeth; i++)
4563
0
            p[i] = n[i];
4564
0
        for (i = 0; i < nmeth - 1; i++)
4565
0
            w[i] -= 1;
4566
0
    } /* end while */
4567
4568
0
    if (nerrors)
4569
0
        HGOTO_ERROR(H5E_IO, H5E_CANTFLUSH, FAIL, "unable to preempt one or more raw data cache entry");
4570
4571
0
done:
4572
0
    FUNC_LEAVE_NOAPI(ret_value)
4573
0
} /* end H5D__chunk_cache_prune() */
4574
4575
/*-------------------------------------------------------------------------
4576
 * Function:    H5D__chunk_lock
4577
 *
4578
 * Purpose:    Return a pointer to a dataset chunk.  The pointer points
4579
 *        directly into the chunk cache and should not be freed
4580
 *        by the caller but will be valid until it is unlocked.  The
4581
 *        input value IDX_HINT is used to speed up cache lookups and
4582
 *        it's output value should be given to H5D__chunk_unlock().
4583
 *        IDX_HINT is ignored if it is out of range, and if it points
4584
 *        to the wrong entry then we fall back to the normal search
4585
 *        method.
4586
 *
4587
 *        If RELAX is non-zero and the chunk isn't in the cache then
4588
 *        don't try to read it from the file, but just allocate an
4589
 *        uninitialized buffer to hold the result.  This is intended
4590
 *        for output functions that are about to overwrite the entire
4591
 *        chunk.
4592
 *
4593
 * Return:    Success:    Ptr to a file chunk.
4594
 *
4595
 *        Failure:    NULL
4596
 *
4597
 *-------------------------------------------------------------------------
4598
 */
4599
static void *
4600
H5D__chunk_lock(const H5D_io_info_t H5_ATTR_NDEBUG_UNUSED *io_info, const H5D_dset_io_info_t *dset_info,
4601
                H5D_chunk_ud_t *udata, bool relax, bool prev_unfilt_chunk)
4602
0
{
4603
0
    const H5D_t *dset;      /* Convenience pointer to the dataset */
4604
0
    H5O_pline_t *pline;     /* I/O pipeline info - always equal to the pline passed to H5D__chunk_mem_alloc */
4605
0
    H5O_pline_t *old_pline; /* Old pipeline, i.e. pipeline used to read the chunk */
4606
0
    const H5O_layout_t *layout;                  /* Dataset layout */
4607
0
    const H5O_fill_t   *fill;                    /* Fill value info */
4608
0
    H5D_fill_buf_info_t fb_info;                 /* Dataset's fill buffer info */
4609
0
    bool                fb_info_init = false;    /* Whether the fill value buffer has been initialized */
4610
0
    H5D_rdcc_t         *rdcc;                    /*raw data chunk cache*/
4611
0
    H5D_rdcc_ent_t     *ent;                     /*cache entry        */
4612
0
    size_t              chunk_size;              /*size of a chunk    */
4613
0
    bool                disable_filters = false; /* Whether to disable filters (when adding to cache) */
4614
0
    void               *chunk           = NULL;  /*the file chunk    */
4615
0
    void               *ret_value       = NULL;  /* Return value         */
4616
4617
0
    FUNC_ENTER_PACKAGE
4618
4619
    /* Sanity checks */
4620
0
    assert(io_info);
4621
0
    assert(dset_info);
4622
0
    assert(dset_info->store);
4623
0
    dset = dset_info->dset;
4624
0
    assert(dset);
4625
0
    assert(udata);
4626
0
    assert(!(udata->new_unfilt_chunk && prev_unfilt_chunk));
4627
4628
    /* Set convenience pointers */
4629
0
    pline     = &(dset->shared->dcpl_cache.pline);
4630
0
    old_pline = pline;
4631
0
    layout    = &(dset->shared->layout);
4632
0
    fill      = &(dset->shared->dcpl_cache.fill);
4633
0
    rdcc      = &(dset->shared->cache.chunk);
4634
4635
0
    assert(!rdcc->tmp_head);
4636
4637
    /* Get the chunk's size */
4638
0
    assert(layout->u.chunk.size > 0);
4639
0
    if (H5_UNLIKELY((hsize_t)((size_t)layout->u.chunk.size) != layout->u.chunk.size))
4640
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, NULL, "chunk too big to fit in size_t");
4641
0
    chunk_size = (size_t)layout->u.chunk.size;
4642
4643
    /* Check if the chunk is in the cache */
4644
0
    if (UINT_MAX != udata->idx_hint) {
4645
        /* Sanity check */
4646
0
        assert(udata->idx_hint < rdcc->nslots);
4647
0
        assert(rdcc->slot[udata->idx_hint]);
4648
4649
        /* Get the entry */
4650
0
        ent = rdcc->slot[udata->idx_hint];
4651
4652
#ifndef NDEBUG
4653
        {
4654
            unsigned u; /*counters        */
4655
4656
            /* Make sure this is the right chunk */
4657
            for (u = 0; u < layout->u.chunk.ndims - 1; u++)
4658
                assert(dset_info->store->chunk.scaled[u] == ent->scaled[u]);
4659
        }
4660
#endif /* NDEBUG */
4661
4662
        /*
4663
         * Already in the cache.  Count a hit.
4664
         */
4665
0
        rdcc->stats.nhits++;
4666
4667
        /* Make adjustments if the edge chunk status changed recently */
4668
0
        if (pline->nused) {
4669
            /* If the chunk recently became an unfiltered partial edge chunk
4670
             * while in cache, we must make some changes to the entry */
4671
0
            if (udata->new_unfilt_chunk) {
4672
                /* If this flag is set then partial chunk filters must be
4673
                 * disabled, and the chunk must not have previously been a
4674
                 * partial chunk (with disabled filters) */
4675
0
                assert(layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS);
4676
0
                assert(!(ent->edge_chunk_state & H5D_RDCC_DISABLE_FILTERS));
4677
0
                assert(old_pline->nused);
4678
4679
                /* Disable filters.  Set pline to NULL instead of just the
4680
                 * default pipeline to make a quick failure more likely if the
4681
                 * code is changed in an inappropriate/incomplete way. */
4682
0
                pline = NULL;
4683
4684
                /* Reallocate the chunk so H5D__chunk_mem_xfree doesn't get confused
4685
                 */
4686
0
                if (NULL == (chunk = H5D__chunk_mem_alloc(chunk_size, pline)))
4687
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL,
4688
0
                                "memory allocation failed for raw data chunk");
4689
0
                H5MM_memcpy(chunk, ent->chunk, chunk_size);
4690
0
                ent->chunk = (uint8_t *)H5D__chunk_mem_xfree(ent->chunk, old_pline);
4691
0
                ent->chunk = (uint8_t *)chunk;
4692
0
                chunk      = NULL;
4693
4694
                /* Mark the chunk as having filters disabled as well as "newly
4695
                 * disabled" so it is inserted on flush */
4696
0
                ent->edge_chunk_state |= H5D_RDCC_DISABLE_FILTERS;
4697
0
                ent->edge_chunk_state |= H5D_RDCC_NEWLY_DISABLED_FILTERS;
4698
0
            } /* end if */
4699
0
            else if (prev_unfilt_chunk) {
4700
                /* If this flag is set then partial chunk filters must be
4701
                 * disabled, and the chunk must have previously been a partial
4702
                 * chunk (with disabled filters) */
4703
0
                assert(layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS);
4704
0
                assert((ent->edge_chunk_state & H5D_RDCC_DISABLE_FILTERS));
4705
0
                assert(pline->nused);
4706
4707
                /* Mark the old pipeline as having been disabled */
4708
0
                old_pline = NULL;
4709
4710
                /* Reallocate the chunk so H5D__chunk_mem_xfree doesn't get confused
4711
                 */
4712
0
                if (NULL == (chunk = H5D__chunk_mem_alloc(chunk_size, pline)))
4713
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL,
4714
0
                                "memory allocation failed for raw data chunk");
4715
0
                H5MM_memcpy(chunk, ent->chunk, chunk_size);
4716
4717
0
                ent->chunk = (uint8_t *)H5D__chunk_mem_xfree(ent->chunk, old_pline);
4718
0
                ent->chunk = (uint8_t *)chunk;
4719
0
                chunk      = NULL;
4720
4721
                /* Mark the chunk as having filters enabled */
4722
0
                ent->edge_chunk_state &= ~(H5D_RDCC_DISABLE_FILTERS | H5D_RDCC_NEWLY_DISABLED_FILTERS);
4723
0
            } /* end else */
4724
0
        }     /* end if */
4725
4726
        /*
4727
         * If the chunk is not at the beginning of the cache; move it backward
4728
         * by one slot.  This is how we implement the LRU preemption
4729
         * algorithm.
4730
         */
4731
0
        if (ent->next) {
4732
0
            if (ent->next->next)
4733
0
                ent->next->next->prev = ent;
4734
0
            else
4735
0
                rdcc->tail = ent;
4736
0
            ent->next->prev = ent->prev;
4737
0
            if (ent->prev)
4738
0
                ent->prev->next = ent->next;
4739
0
            else
4740
0
                rdcc->head = ent->next;
4741
0
            ent->prev       = ent->next;
4742
0
            ent->next       = ent->next->next;
4743
0
            ent->prev->next = ent;
4744
0
        } /* end if */
4745
0
    }     /* end if */
4746
0
    else {
4747
0
        haddr_t chunk_addr;      /* Address of chunk on disk */
4748
0
        hsize_t chunk_disk_size; /* Length of chunk on disk */
4749
4750
        /* Save the chunk info so the cache stays consistent */
4751
0
        chunk_addr      = udata->chunk_block.offset;
4752
0
        chunk_disk_size = udata->chunk_block.length;
4753
4754
        /* Check if we should disable filters on this chunk */
4755
0
        if (pline->nused) {
4756
0
            if (udata->new_unfilt_chunk) {
4757
0
                assert(layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS);
4758
4759
                /* Disable the filters for writing */
4760
0
                disable_filters = true;
4761
0
                pline           = NULL;
4762
0
            } /* end if */
4763
0
            else if (prev_unfilt_chunk) {
4764
0
                assert(layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS);
4765
4766
                /* Mark the filters as having been previously disabled (for the
4767
                 * chunk as currently on disk) - disable the filters for reading
4768
                 */
4769
0
                old_pline = NULL;
4770
0
            } /* end if */
4771
0
            else if (layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS) {
4772
                /* Check if this is an edge chunk */
4773
0
                if (H5D__chunk_is_partial_edge_chunk(dset->shared->ndims, layout->u.chunk.dim,
4774
0
                                                     dset_info->store->chunk.scaled,
4775
0
                                                     dset->shared->curr_dims)) {
4776
                    /* Disable the filters for both writing and reading */
4777
0
                    disable_filters = true;
4778
0
                    old_pline       = NULL;
4779
0
                    pline           = NULL;
4780
0
                } /* end if */
4781
0
            }     /* end if */
4782
0
        }         /* end if */
4783
4784
        /* If the chunk on disk is unfiltered, verify the index returned the correct size for the chunk */
4785
0
        if (H5_UNLIKELY((chunk_disk_size != (hsize_t)chunk_size) && H5_addr_defined(chunk_addr) &&
4786
0
                        (!old_pline || !old_pline->nused)))
4787
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, NULL,
4788
0
                        "incorrect chunk size returned from index for unfiltered chunk");
4789
4790
0
        if (relax) {
4791
            /*
4792
             * Not in the cache, but we're about to overwrite the whole thing
4793
             * anyway, so just allocate a buffer for it but don't initialize that
4794
             * buffer with the file contents. Count this as a hit instead of a
4795
             * miss because we saved ourselves lots of work.
4796
             */
4797
0
            rdcc->stats.nhits++;
4798
4799
0
            if (NULL == (chunk = H5D__chunk_mem_alloc(chunk_size, pline)))
4800
0
                HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed for raw data chunk");
4801
4802
            /* In the case that some dataset functions look through this data,
4803
             * clear it to all 0s. */
4804
0
            memset(chunk, 0, chunk_size);
4805
0
        } /* end if */
4806
0
        else {
4807
            /*
4808
             * Not in the cache.  Count this as a miss if it's in the file
4809
             *      or an init if it isn't.
4810
             */
4811
4812
            /* Check if the chunk exists on disk */
4813
0
            if (H5_addr_defined(chunk_addr)) {
4814
0
                size_t chunk_nbytes; /* Length of the chunk in memory */
4815
0
                size_t buf_alloc;    /* [Re-]allocated chunk buffer size */
4816
4817
                /* Assign chunk_nbytes and check for overflow */
4818
0
                H5_CHECKED_ASSIGN(chunk_nbytes, size_t, chunk_disk_size, hsize_t);
4819
4820
                /* Allocate at MAX(chunk_disk_size, chunk_size) so the buffer is
4821
                 * large enough for the uncompressed output before filters run.
4822
                 * This ensures *buf_size accurately reflects the allocation that
4823
                 * filters receive, avoiding a buffer overflow if any filter writes
4824
                 * up to *buf_size bytes into *buf.  For incompressible chunks
4825
                 * chunk_disk_size >= chunk_size so buf_alloc stays at chunk_nbytes. */
4826
0
                buf_alloc = (chunk_nbytes < chunk_size) ? chunk_size : chunk_nbytes;
4827
4828
0
                if (NULL ==
4829
0
                    (chunk = H5D__chunk_mem_alloc(buf_alloc, (udata->new_unfilt_chunk ? old_pline : pline))))
4830
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL,
4831
0
                                "memory allocation failed for raw data chunk");
4832
4833
                /* Read chunk from disk */
4834
0
                if (H5F_shared_block_read(H5F_SHARED(dset->oloc.file), H5FD_MEM_DRAW, chunk_addr,
4835
0
                                          chunk_disk_size, chunk) < 0)
4836
0
                    HGOTO_ERROR(H5E_IO, H5E_READERROR, NULL, "unable to read raw data chunk");
4837
4838
                /* Unfilter chunk */
4839
0
                if (old_pline && old_pline->nused) {
4840
0
                    H5Z_EDC_t err_detect; /* Error detection info */
4841
0
                    H5Z_cb_t  filter_cb;  /* I/O filter callback function */
4842
4843
                    /* Retrieve filter settings from API context */
4844
0
                    if (H5CX_get_err_detect(&err_detect) < 0)
4845
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, NULL, "can't get error detection info");
4846
0
                    if (H5CX_get_filter_cb(&filter_cb) < 0)
4847
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, NULL, "can't get I/O filter callback function");
4848
4849
                    /* Perform filter pipeline */
4850
0
                    if (H5Z_pipeline(old_pline, H5Z_FLAG_REVERSE, &(udata->filter_mask), err_detect,
4851
0
                                     filter_cb, &chunk_nbytes, &buf_alloc, &chunk) < 0)
4852
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTFILTER, NULL, "data pipeline read failed");
4853
4854
                    /* Make sure the chunk is the correct size after being unfiltered */
4855
0
                    if (chunk_nbytes != chunk_size)
4856
0
                        HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, NULL,
4857
0
                                    "chunk size is incorrect after being unfiltered");
4858
4859
                    /* Reallocate chunk if necessary */
4860
0
                    if (udata->new_unfilt_chunk) {
4861
0
                        void *tmp_chunk = chunk;
4862
4863
0
                        if (NULL == (chunk = H5D__chunk_mem_alloc(chunk_nbytes, pline))) {
4864
0
                            (void)H5D__chunk_mem_xfree(tmp_chunk, old_pline);
4865
0
                            HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL,
4866
0
                                        "memory allocation failed for raw data chunk");
4867
0
                        } /* end if */
4868
0
                        H5MM_memcpy(chunk, tmp_chunk, chunk_size);
4869
0
                        (void)H5D__chunk_mem_xfree(tmp_chunk, old_pline);
4870
0
                    } /* end if */
4871
0
                }     /* end if */
4872
4873
                /* Assert that the chunk is the correct size and the buffer is big enough */
4874
0
                assert(chunk_nbytes == chunk_size);
4875
0
                assert(buf_alloc >= chunk_size);
4876
4877
                /* Increment # of cache misses */
4878
0
                rdcc->stats.nmisses++;
4879
0
            } /* end if */
4880
0
            else {
4881
0
                H5D_fill_value_t fill_status;
4882
4883
                /* Sanity check */
4884
0
                assert(fill->alloc_time != H5D_ALLOC_TIME_EARLY);
4885
4886
                /* Allocate chunk buffer large enough to hold an unfiltered (in cache) chunk */
4887
0
                if (NULL == (chunk = H5D__chunk_mem_alloc(chunk_size, pline)))
4888
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL,
4889
0
                                "memory allocation failed for raw data chunk");
4890
4891
0
                if (H5P_is_fill_value_defined(fill, &fill_status) < 0)
4892
0
                    HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, NULL, "can't tell if fill value defined");
4893
4894
0
                if (fill->fill_time == H5D_FILL_TIME_ALLOC ||
4895
0
                    (fill->fill_time == H5D_FILL_TIME_IFSET &&
4896
0
                     (fill_status == H5D_FILL_VALUE_USER_DEFINED || fill_status == H5D_FILL_VALUE_DEFAULT))) {
4897
                    /*
4898
                     * The chunk doesn't exist in the file.  Replicate the fill
4899
                     * value throughout the chunk, if the fill value is defined.
4900
                     */
4901
4902
                    /* Initialize the fill value buffer */
4903
                    /* (use the compact dataset storage buffer as the fill value buffer) */
4904
0
                    if (H5D__fill_init(&fb_info, chunk, NULL, NULL, NULL, NULL,
4905
0
                                       &dset->shared->dcpl_cache.fill, dset->shared->type, (size_t)0,
4906
0
                                       chunk_size) < 0)
4907
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, NULL, "can't initialize fill buffer info");
4908
0
                    fb_info_init = true;
4909
4910
                    /* Check for VL datatype & non-default fill value */
4911
0
                    if (fb_info.has_vlen_fill_type)
4912
                        /* Fill the buffer with VL datatype fill values */
4913
0
                        if (H5D__fill_refill_vl(&fb_info, fb_info.elmts_per_buf) < 0)
4914
0
                            HGOTO_ERROR(H5E_DATASET, H5E_CANTCONVERT, NULL, "can't refill fill value buffer");
4915
0
                } /* end if */
4916
0
                else
4917
0
                    memset(chunk, 0, chunk_size);
4918
4919
                /* Increment # of creations */
4920
0
                rdcc->stats.ninits++;
4921
0
            } /* end else */
4922
0
        }     /* end else */
4923
4924
        /* See if the chunk can be cached */
4925
0
        if (rdcc->nslots > 0 && chunk_size <= rdcc->nbytes_max) {
4926
            /* Calculate the index */
4927
0
            udata->idx_hint = H5D__chunk_hash_val(dset->shared, udata->common.scaled);
4928
4929
            /* Add the chunk to the cache only if the slot is not already locked */
4930
0
            ent = rdcc->slot[udata->idx_hint];
4931
0
            if (!ent || !ent->locked) {
4932
                /* Preempt enough things from the cache to make room */
4933
0
                if (ent) {
4934
0
                    if (H5D__chunk_cache_evict(dset, ent, true) < 0)
4935
0
                        HGOTO_ERROR(H5E_IO, H5E_CANTINIT, NULL, "unable to preempt chunk from cache");
4936
0
                } /* end if */
4937
0
                if (H5D__chunk_cache_prune(dset, chunk_size) < 0)
4938
0
                    HGOTO_ERROR(H5E_IO, H5E_CANTINIT, NULL, "unable to preempt chunk(s) from cache");
4939
4940
                /* Create a new entry */
4941
0
                if (NULL == (ent = H5FL_CALLOC(H5D_rdcc_ent_t)))
4942
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTALLOC, NULL, "can't allocate raw data chunk entry");
4943
4944
0
                ent->edge_chunk_state = disable_filters ? H5D_RDCC_DISABLE_FILTERS : 0;
4945
0
                if (udata->new_unfilt_chunk)
4946
0
                    ent->edge_chunk_state |= H5D_RDCC_NEWLY_DISABLED_FILTERS;
4947
4948
                /* Initialize the new entry */
4949
0
                ent->chunk_block.offset = chunk_addr;
4950
0
                ent->chunk_block.length = chunk_disk_size;
4951
0
                ent->chunk_idx          = udata->chunk_idx;
4952
0
                H5MM_memcpy(ent->scaled, udata->common.scaled, sizeof(hsize_t) * layout->u.chunk.ndims);
4953
0
                H5_CHECKED_ASSIGN(ent->rd_count, hsize_t, chunk_size, size_t);
4954
0
                H5_CHECKED_ASSIGN(ent->wr_count, hsize_t, chunk_size, size_t);
4955
0
                ent->chunk = (uint8_t *)chunk;
4956
4957
                /* Add it to the cache */
4958
0
                assert(NULL == rdcc->slot[udata->idx_hint]);
4959
0
                rdcc->slot[udata->idx_hint] = ent;
4960
0
                ent->idx                    = udata->idx_hint;
4961
0
                rdcc->nbytes_used += chunk_size;
4962
0
                rdcc->nused++;
4963
4964
                /* Add it to the linked list */
4965
0
                if (rdcc->tail) {
4966
0
                    rdcc->tail->next = ent;
4967
0
                    ent->prev        = rdcc->tail;
4968
0
                    rdcc->tail       = ent;
4969
0
                } /* end if */
4970
0
                else
4971
0
                    rdcc->head = rdcc->tail = ent;
4972
0
                ent->tmp_next = NULL;
4973
0
                ent->tmp_prev = NULL;
4974
4975
0
            } /* end if */
4976
0
            else
4977
                /* We did not add the chunk to cache */
4978
0
                ent = NULL;
4979
0
        }    /* end else */
4980
0
        else /* No cache set up, or chunk is too large: chunk is uncacheable */
4981
0
            ent = NULL;
4982
0
    } /* end else */
4983
4984
    /* Lock the chunk into the cache */
4985
0
    if (ent) {
4986
0
        assert(!ent->locked);
4987
0
        ent->locked = true;
4988
0
        chunk       = ent->chunk;
4989
0
    } /* end if */
4990
0
    else
4991
        /*
4992
         * The chunk cannot be placed in cache so we don't cache it. This is the
4993
         * reason all those arguments have to be repeated for the unlock
4994
         * function.
4995
         */
4996
0
        udata->idx_hint = UINT_MAX;
4997
4998
    /* Set return value */
4999
0
    ret_value = chunk;
5000
5001
0
done:
5002
    /* Release the fill buffer info, if it's been initialized */
5003
0
    if (fb_info_init && H5D__fill_term(&fb_info) < 0)
5004
0
        HDONE_ERROR(H5E_DATASET, H5E_CANTFREE, NULL, "Can't release fill buffer info");
5005
5006
    /* Release the chunk allocated, on error */
5007
0
    if (!ret_value)
5008
0
        if (chunk)
5009
0
            chunk = H5D__chunk_mem_xfree(chunk, pline);
5010
5011
0
    FUNC_LEAVE_NOAPI(ret_value)
5012
0
} /* end H5D__chunk_lock() */
5013
5014
/*-------------------------------------------------------------------------
5015
 * Function:    H5D__chunk_unlock
5016
 *
5017
 * Purpose:    Unlocks a previously locked chunk. The LAYOUT, COMP, and
5018
 *        OFFSET arguments should be the same as for H5D__chunk_lock().
5019
 *        The DIRTY argument should be set to non-zero if the chunk has
5020
 *        been modified since it was locked. The IDX_HINT argument is
5021
 *        the returned index hint from the lock operation and BUF is
5022
 *        the return value from the lock.
5023
 *
5024
 *        The NACCESSED argument should be the number of bytes accessed
5025
 *        for reading or writing (depending on the value of DIRTY).
5026
 *        It's only purpose is to provide additional information to the
5027
 *        preemption policy.
5028
 *
5029
 * Return:    Non-negative on success/Negative on failure
5030
 *
5031
 *-------------------------------------------------------------------------
5032
 */
5033
static herr_t
5034
H5D__chunk_unlock(const H5D_io_info_t H5_ATTR_NDEBUG_UNUSED *io_info, const H5D_dset_io_info_t *dset_info,
5035
                  const H5D_chunk_ud_t *udata, bool dirty, void *chunk, hsize_t naccessed)
5036
0
{
5037
0
    const H5O_layout_t *layout; /* Dataset layout */
5038
0
    const H5D_rdcc_t   *rdcc;
5039
0
    const H5D_t        *dset;                /* Local pointer to the dataset info */
5040
0
    herr_t              ret_value = SUCCEED; /* Return value */
5041
5042
0
    FUNC_ENTER_PACKAGE
5043
5044
    /* Sanity check */
5045
0
    assert(io_info);
5046
0
    assert(dset_info);
5047
0
    assert(udata);
5048
5049
    /* Set convenience pointers */
5050
0
    layout = &(dset_info->dset->shared->layout);
5051
0
    rdcc   = &(dset_info->dset->shared->cache.chunk);
5052
0
    dset   = dset_info->dset;
5053
5054
0
    if (UINT_MAX == udata->idx_hint) {
5055
        /*
5056
         * It's not in the cache, probably because it's too big.  If it's
5057
         * dirty then flush it to disk.  In any case, free the chunk.
5058
         */
5059
0
        bool is_unfiltered_edge_chunk = false; /* Whether the chunk is an unfiltered edge chunk */
5060
5061
        /* Check if we should disable filters on this chunk */
5062
0
        if (udata->new_unfilt_chunk) {
5063
0
            assert(layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS);
5064
5065
0
            is_unfiltered_edge_chunk = true;
5066
0
        } /* end if */
5067
0
        else if (layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS) {
5068
            /* Check if the chunk is an edge chunk, and disable filters if so */
5069
0
            is_unfiltered_edge_chunk =
5070
0
                H5D__chunk_is_partial_edge_chunk(dset->shared->ndims, layout->u.chunk.dim,
5071
0
                                                 dset_info->store->chunk.scaled, dset->shared->curr_dims);
5072
0
        } /* end if */
5073
5074
0
        if (dirty) {
5075
0
            H5D_rdcc_ent_t fake_ent; /* "fake" chunk cache entry */
5076
5077
0
            memset(&fake_ent, 0, sizeof(fake_ent));
5078
0
            fake_ent.dirty = true;
5079
0
            if (is_unfiltered_edge_chunk)
5080
0
                fake_ent.edge_chunk_state = H5D_RDCC_DISABLE_FILTERS;
5081
0
            if (udata->new_unfilt_chunk)
5082
0
                fake_ent.edge_chunk_state |= H5D_RDCC_NEWLY_DISABLED_FILTERS;
5083
0
            H5MM_memcpy(fake_ent.scaled, udata->common.scaled, sizeof(hsize_t) * layout->u.chunk.ndims);
5084
0
            assert(layout->u.chunk.size > 0);
5085
0
            fake_ent.chunk_idx          = udata->chunk_idx;
5086
0
            fake_ent.chunk_block.offset = udata->chunk_block.offset;
5087
0
            fake_ent.chunk_block.length = udata->chunk_block.length;
5088
0
            fake_ent.chunk              = (uint8_t *)chunk;
5089
5090
0
            if (H5D__chunk_flush_entry(dset, &fake_ent, true) < 0)
5091
0
                HGOTO_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "cannot flush indexed storage buffer");
5092
0
        } /* end if */
5093
0
        else {
5094
0
            if (chunk)
5095
0
                chunk = H5D__chunk_mem_xfree(
5096
0
                    chunk, (is_unfiltered_edge_chunk ? NULL : &(dset->shared->dcpl_cache.pline)));
5097
0
        } /* end else */
5098
0
    }     /* end if */
5099
0
    else {
5100
0
        H5D_rdcc_ent_t *ent; /* Chunk's entry in the cache */
5101
5102
        /* Sanity check */
5103
0
        assert(udata->idx_hint < rdcc->nslots);
5104
0
        assert(rdcc->slot[udata->idx_hint]);
5105
0
        assert(rdcc->slot[udata->idx_hint]->chunk == chunk);
5106
5107
        /*
5108
         * It's in the cache so unlock it.
5109
         */
5110
0
        ent = rdcc->slot[udata->idx_hint];
5111
0
        assert(ent->locked);
5112
0
        if (dirty) {
5113
0
            ent->dirty = true;
5114
0
            ent->wr_count -= MIN(ent->wr_count, naccessed);
5115
0
        } /* end if */
5116
0
        else
5117
0
            ent->rd_count -= MIN(ent->rd_count, naccessed);
5118
0
        ent->locked = false;
5119
0
    } /* end else */
5120
5121
0
done:
5122
0
    FUNC_LEAVE_NOAPI(ret_value)
5123
0
} /* end H5D__chunk_unlock() */
5124
5125
/*-------------------------------------------------------------------------
5126
 * Function:    H5D__chunk_allocated_cb
5127
 *
5128
 * Purpose:    Simply counts the number of chunks for a dataset.
5129
 *
5130
 * Return:    Success:    Non-negative
5131
 *        Failure:    Negative
5132
 *
5133
 *-------------------------------------------------------------------------
5134
 */
5135
static int
5136
H5D__chunk_allocated_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata)
5137
0
{
5138
0
    hsize_t *nbytes = (hsize_t *)_udata;
5139
5140
0
    FUNC_ENTER_PACKAGE_NOERR
5141
5142
0
    *(hsize_t *)nbytes += chunk_rec->nbytes;
5143
5144
0
    FUNC_LEAVE_NOAPI(H5_ITER_CONT)
5145
0
} /* H5D__chunk_allocated_cb() */
5146
5147
/*-------------------------------------------------------------------------
5148
 * Function:    H5D__chunk_allocated
5149
 *
5150
 * Purpose:    Return the number of bytes allocated in the file for storage
5151
 *        of raw data in the chunked dataset
5152
 *
5153
 * Return:    Success:    Number of bytes stored in all chunks.
5154
 *        Failure:    0
5155
 *
5156
 *-------------------------------------------------------------------------
5157
 */
5158
herr_t
5159
H5D__chunk_allocated(const H5D_t *dset, hsize_t *nbytes)
5160
0
{
5161
0
    H5D_chk_idx_info_t   idx_info;                            /* Chunked index info */
5162
0
    const H5D_rdcc_t    *rdcc = &(dset->shared->cache.chunk); /* Raw data chunk cache */
5163
0
    H5D_rdcc_ent_t      *ent;                                 /* Cache entry  */
5164
0
    hsize_t              chunk_bytes = 0;                     /* Number of bytes allocated for chunks */
5165
0
    H5O_storage_chunk_t *sc          = &(dset->shared->layout.storage.u.chunk);
5166
0
    herr_t               ret_value   = SUCCEED; /* Return value */
5167
5168
0
    FUNC_ENTER_PACKAGE
5169
5170
0
    assert(dset);
5171
0
    assert(dset->shared);
5172
0
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
5173
5174
    /* Search for cached chunks that haven't been written out */
5175
0
    for (ent = rdcc->head; ent; ent = ent->next)
5176
        /* Flush the chunk out to disk, to make certain the size is correct later */
5177
0
        if (H5D__chunk_flush_entry(dset, ent, false) < 0)
5178
0
            HGOTO_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "cannot flush indexed storage buffer");
5179
5180
    /* Compose chunked index info struct */
5181
0
    idx_info.f      = dset->oloc.file;
5182
0
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
5183
0
    idx_info.layout = &dset->shared->layout;
5184
5185
    /* Iterate over the chunks */
5186
0
    if ((sc->ops->iterate)(&idx_info, H5D__chunk_allocated_cb, &chunk_bytes) < 0)
5187
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL,
5188
0
                    "unable to retrieve allocated chunk information from index");
5189
5190
    /* Set number of bytes for caller */
5191
0
    *nbytes = chunk_bytes;
5192
5193
0
done:
5194
0
    FUNC_LEAVE_NOAPI(ret_value)
5195
0
} /* end H5D__chunk_allocated() */
5196
5197
/*-------------------------------------------------------------------------
5198
 * Function:    H5D__chunk_allocate
5199
 *
5200
 * Purpose:    Allocate file space for all chunks that are not allocated yet.
5201
 *        Return SUCCEED if all needed allocation succeed, otherwise
5202
 *        FAIL.
5203
 *
5204
 * Return:    Non-negative on success/Negative on failure
5205
 *
5206
 *-------------------------------------------------------------------------
5207
 */
5208
herr_t
5209
H5D__chunk_allocate(const H5D_t *dset, bool full_overwrite, const hsize_t old_dim[])
5210
0
{
5211
0
    H5D_chk_idx_info_t     idx_info;                                       /* Chunked index info */
5212
0
    const H5D_chunk_ops_t *ops = dset->shared->layout.storage.u.chunk.ops; /* Chunk operations */
5213
0
    hsize_t min_unalloc[H5O_LAYOUT_NDIMS]; /* First chunk in each dimension that is unallocated (in scaled
5214
                                              coordinates) */
5215
0
    hsize_t max_unalloc[H5O_LAYOUT_NDIMS]; /* Last chunk in each dimension that is unallocated (in scaled
5216
                                              coordinates) */
5217
0
    hsize_t           scaled[H5O_LAYOUT_NDIMS]; /* Offset of current chunk (in scaled coordinates) */
5218
0
    size_t            orig_chunk_size = 0;      /* Original size of chunk in bytes */
5219
0
    hsize_t           chunk_size;               /* Actual size of chunk in bytes, possibly filtered */
5220
0
    unsigned          filter_mask = 0;          /* Filter mask for chunks that have them */
5221
0
    H5O_layout_t     *layout      = &(dset->shared->layout);           /* Dataset layout */
5222
0
    H5O_pline_t      *pline       = &(dset->shared->dcpl_cache.pline); /* I/O pipeline info */
5223
0
    H5O_pline_t       def_pline   = H5O_CRT_PIPELINE_DEF;              /* Default pipeline */
5224
0
    const H5O_fill_t *fill        = &(dset->shared->dcpl_cache.fill);  /* Fill value info */
5225
0
    H5D_fill_value_t  fill_status;                                     /* The fill value status */
5226
0
    bool              should_fill     = false; /* Whether fill values should be written */
5227
0
    void             *unfilt_fill_buf = NULL;  /* Unfiltered fill value buffer */
5228
0
    void            **fill_buf        = NULL;  /* Pointer to the fill buffer to use for a chunk */
5229
#ifdef H5_HAVE_PARALLEL
5230
    bool blocks_written = false; /* Flag to indicate that chunk was actually written */
5231
    bool using_mpi =
5232
        false; /* Flag to indicate that the file is being accessed with an MPI-capable file driver */
5233
    H5D_chunk_coll_fill_info_t chunk_fill_info; /* chunk address information for doing I/O */
5234
#endif                                          /* H5_HAVE_PARALLEL */
5235
0
    bool                carry; /* Flag to indicate that chunk increment carrys to higher dimension (sorta) */
5236
0
    unsigned            space_ndims;                     /* Dataset's space rank */
5237
0
    const hsize_t      *space_dim;                       /* Dataset's dataspace dimensions */
5238
0
    const hsize_t      *chunk_dim = layout->u.chunk.dim; /* Convenience pointer to chunk dimensions */
5239
0
    unsigned            op_dim;                          /* Current operating dimension */
5240
0
    H5D_fill_buf_info_t fb_info;                         /* Dataset's fill buffer info */
5241
0
    bool                fb_info_init = false; /* Whether the fill value buffer has been initialized */
5242
0
    bool has_unfilt_edge_chunks = false; /* Whether there are partial edge chunks with disabled filters */
5243
0
    bool unfilt_edge_chunk_dim[H5O_LAYOUT_NDIMS]; /* Whether there are unfiltered edge chunks at the edge
5244
                                                        of each dimension */
5245
0
    hsize_t edge_chunk_scaled[H5O_LAYOUT_NDIMS];  /* Offset of the unfiltered edge chunks at the edge of each
5246
                                                     dimension */
5247
0
    unsigned             nunfilt_edge_chunk_dims = 0; /* Number of dimensions on an edge */
5248
0
    H5O_storage_chunk_t *sc                      = &(layout->storage.u.chunk); /* Convenience variable */
5249
0
    herr_t               ret_value               = SUCCEED;                    /* Return value */
5250
5251
0
    FUNC_ENTER_PACKAGE
5252
5253
    /* Check args */
5254
0
    assert(dset && H5D_CHUNKED == layout->type);
5255
0
    assert(layout->u.chunk.ndims > 0 && layout->u.chunk.ndims <= H5O_LAYOUT_NDIMS);
5256
0
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
5257
5258
    /* Retrieve the dataset dimensions */
5259
0
    space_dim   = dset->shared->curr_dims;
5260
0
    space_ndims = dset->shared->ndims;
5261
5262
    /* The last dimension in scaled chunk coordinates is always 0 */
5263
0
    scaled[space_ndims] = (hsize_t)0;
5264
5265
    /* Check if any space dimensions are 0, if so we do not have to do anything
5266
     */
5267
0
    for (op_dim = 0; op_dim < (unsigned)space_ndims; op_dim++)
5268
0
        if (space_dim[op_dim] == 0) {
5269
            /* Reset any cached chunk info for this dataset */
5270
0
            H5D__chunk_cinfo_cache_reset(&dset->shared->cache.chunk.last);
5271
0
            HGOTO_DONE(SUCCEED);
5272
0
        } /* end if */
5273
5274
#ifdef H5_HAVE_PARALLEL
5275
    /* Retrieve MPI parameters */
5276
    if (H5F_HAS_FEATURE(dset->oloc.file, H5FD_FEAT_HAS_MPI)) {
5277
        /* Set the MPI-capable file driver flag */
5278
        using_mpi = true;
5279
5280
        /* init chunk info stuff for collective I/O */
5281
        chunk_fill_info.num_chunks = 0;
5282
        chunk_fill_info.chunk_info = NULL;
5283
    }  /* end if */
5284
#endif /* H5_HAVE_PARALLEL */
5285
5286
    /* Calculate the minimum and maximum chunk offsets in each dimension, and
5287
     * determine if there are any unfiltered partial edge chunks.  Note that we
5288
     * assume here that all elements of space_dim are > 0.  This is checked at
5289
     * the top of this function. */
5290
0
    for (op_dim = 0; op_dim < space_ndims; op_dim++) {
5291
        /* Validate this chunk dimension */
5292
0
        if (chunk_dim[op_dim] == 0)
5293
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "chunk size must be > 0, dim = %u ", op_dim);
5294
0
        min_unalloc[op_dim] = (old_dim[op_dim] + chunk_dim[op_dim] - 1) / chunk_dim[op_dim];
5295
0
        max_unalloc[op_dim] = (space_dim[op_dim] - 1) / chunk_dim[op_dim];
5296
5297
        /* Calculate if there are unfiltered edge chunks at the edge of this
5298
         * dimension.  Note the edge_chunk_scaled is uninitialized for
5299
         * dimensions where unfilt_edge_chunk_dim is false.  Also  */
5300
0
        if ((layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS) && pline->nused > 0 &&
5301
0
            space_dim[op_dim] % chunk_dim[op_dim] != 0) {
5302
0
            has_unfilt_edge_chunks        = true;
5303
0
            unfilt_edge_chunk_dim[op_dim] = true;
5304
0
            edge_chunk_scaled[op_dim]     = max_unalloc[op_dim];
5305
0
        } /* end if */
5306
0
        else
5307
0
            unfilt_edge_chunk_dim[op_dim] = false;
5308
0
    } /* end for */
5309
5310
    /* Check the dataset's fill-value status */
5311
0
    if (H5P_is_fill_value_defined(fill, &fill_status) < 0)
5312
0
        HGOTO_ERROR(H5E_PLIST, H5E_CANTGET, FAIL, "can't tell if fill value defined");
5313
5314
    /* If we are filling the dataset on allocation or "if set" and
5315
     * the fill value _is_ set, _and_ we are not overwriting the new blocks,
5316
     * or if there are any pipeline filters defined,
5317
     * set the "should fill" flag
5318
     */
5319
0
    if ((!full_overwrite &&
5320
0
         (fill->fill_time == H5D_FILL_TIME_ALLOC ||
5321
0
          (fill->fill_time == H5D_FILL_TIME_IFSET &&
5322
0
           (fill_status == H5D_FILL_VALUE_USER_DEFINED || fill_status == H5D_FILL_VALUE_DEFAULT)))) ||
5323
0
        pline->nused > 0)
5324
0
        should_fill = true;
5325
5326
    /* Check if fill values should be written to chunks */
5327
0
    if (should_fill) {
5328
        /* Get original chunk size */
5329
0
        orig_chunk_size = (size_t)layout->u.chunk.size;
5330
5331
        /* Check for overflow */
5332
0
        if (H5_UNLIKELY((hsize_t)orig_chunk_size != layout->u.chunk.size))
5333
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, FAIL, "chunk size too big to fit in size_t");
5334
5335
        /* Initialize the fill value buffer */
5336
        /* (delay allocating fill buffer for VL datatypes until refilling) */
5337
0
        if (H5D__fill_init(&fb_info, NULL, H5D__chunk_mem_alloc, pline, H5D__chunk_mem_free, pline,
5338
0
                           &dset->shared->dcpl_cache.fill, dset->shared->type, (size_t)0,
5339
0
                           orig_chunk_size) < 0)
5340
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "can't initialize fill buffer info");
5341
0
        fb_info_init = true;
5342
5343
        /* Initialize the fill_buf pointer to the buffer in fb_info.  If edge
5344
         * chunk filters are disabled, we will switch the buffer as appropriate
5345
         * for each chunk. */
5346
0
        fill_buf = &fb_info.fill_buf;
5347
5348
        /* Check if there are filters which need to be applied to the chunk */
5349
        /* (only do this in advance when the chunk info can be reused (i.e.
5350
         *      it doesn't contain any non-default VL datatype fill values)
5351
         */
5352
0
        if (!fb_info.has_vlen_fill_type && pline->nused > 0) {
5353
0
            H5Z_EDC_t err_detect; /* Error detection info */
5354
0
            H5Z_cb_t  filter_cb;  /* I/O filter callback function */
5355
0
            size_t    buf_size = orig_chunk_size;
5356
5357
            /* If the dataset has disabled partial chunk filters, create a copy
5358
             * of the unfiltered fill_buf to use for partial chunks */
5359
0
            if (has_unfilt_edge_chunks) {
5360
0
                if (NULL == (unfilt_fill_buf = H5D__chunk_mem_alloc(orig_chunk_size, &def_pline)))
5361
0
                    HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL,
5362
0
                                "memory allocation failed for raw data chunk");
5363
0
                H5MM_memcpy(unfilt_fill_buf, fb_info.fill_buf, orig_chunk_size);
5364
0
            } /* end if */
5365
5366
            /* Retrieve filter settings from API context */
5367
0
            if (H5CX_get_err_detect(&err_detect) < 0)
5368
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't get error detection info");
5369
0
            if (H5CX_get_filter_cb(&filter_cb) < 0)
5370
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't get I/O filter callback function");
5371
5372
            /* Push the chunk through the filters */
5373
0
            if (H5Z_pipeline(pline, 0, &filter_mask, err_detect, filter_cb, &orig_chunk_size, &buf_size,
5374
0
                             &fb_info.fill_buf) < 0)
5375
0
                HGOTO_ERROR(H5E_PLINE, H5E_WRITEERROR, FAIL, "output pipeline failed");
5376
0
        } /* end if */
5377
5378
        /* Set chunk size */
5379
0
        H5_CHECKED_ASSIGN(chunk_size, hsize_t, orig_chunk_size, size_t);
5380
0
    } /* end if */
5381
0
    else
5382
        /* Set chunk size */
5383
0
        chunk_size = layout->u.chunk.size;
5384
5385
    /* Compose chunked index info struct */
5386
0
    idx_info.f      = dset->oloc.file;
5387
0
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
5388
0
    idx_info.layout = &dset->shared->layout;
5389
5390
    /* Loop over all chunks */
5391
    /* The algorithm is:
5392
     *  For each dimension:
5393
     *   -Allocate all chunks in the new dataspace that are beyond the original
5394
     *    dataspace in the operating dimension, except those that have already
5395
     *    been allocated.
5396
     *
5397
     * This is accomplished mainly using the min_unalloc and max_unalloc arrays.
5398
     * min_unalloc represents the lowest offset in each dimension of chunks that
5399
     * have not been allocated (whether or not they need to be).  max_unalloc
5400
     * represents the highest offset in each dimension of chunks in the new
5401
     * dataset that have not been allocated by this routine (they may have been
5402
     * allocated previously).
5403
     *
5404
     * Every time the algorithm finishes allocating chunks allocated beyond a
5405
     * certain dimension, max_unalloc is updated in order to avoid allocating
5406
     * those chunks again.
5407
     *
5408
     * Note that min_unalloc & max_unalloc are in scaled coordinates.
5409
     *
5410
     */
5411
0
    for (op_dim = 0; op_dim < space_ndims; op_dim++) {
5412
0
        H5D_chunk_ud_t udata; /* User data for querying chunk info */
5413
0
        unsigned       u;     /* Local index variable */
5414
0
        int            i;     /* Local index variable */
5415
5416
        /* Check if allocation along this dimension is really necessary */
5417
0
        if (min_unalloc[op_dim] > max_unalloc[op_dim])
5418
0
            continue;
5419
0
        else {
5420
            /* Reset the chunk offset indices */
5421
0
            memset(scaled, 0, (space_ndims * sizeof(scaled[0])));
5422
0
            scaled[op_dim] = min_unalloc[op_dim];
5423
5424
0
            if (has_unfilt_edge_chunks) {
5425
                /* Initialize nunfilt_edge_chunk_dims */
5426
0
                nunfilt_edge_chunk_dims = 0;
5427
0
                for (u = 0; u < space_ndims; u++)
5428
0
                    if (unfilt_edge_chunk_dim[u] && scaled[u] == edge_chunk_scaled[u])
5429
0
                        nunfilt_edge_chunk_dims++;
5430
5431
                /* Initialize chunk_size and fill_buf */
5432
0
                if (should_fill && !fb_info.has_vlen_fill_type) {
5433
0
                    assert(fb_info_init);
5434
0
                    assert(unfilt_fill_buf);
5435
0
                    assert(orig_chunk_size);
5436
0
                    if (nunfilt_edge_chunk_dims) {
5437
0
                        fill_buf   = &unfilt_fill_buf;
5438
0
                        chunk_size = layout->u.chunk.size;
5439
0
                    } /* end if */
5440
0
                    else {
5441
0
                        fill_buf   = &fb_info.fill_buf;
5442
0
                        chunk_size = orig_chunk_size;
5443
0
                        assert(chunk_size == (size_t)orig_chunk_size);
5444
0
                    } /* end else */
5445
0
                }     /* end if */
5446
0
            }         /* end if */
5447
5448
0
            carry = false;
5449
0
        } /* end else */
5450
5451
0
        while (!carry) {
5452
0
            bool need_insert = false; /* Whether the chunk needs to be inserted into the index */
5453
5454
            /* Look up this chunk */
5455
0
            if (H5D__chunk_lookup(dset, scaled, &udata) < 0)
5456
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
5457
#ifndef NDEBUG
5458
            /* None of the chunks should be allocated */
5459
            if (H5D_CHUNK_IDX_NONE != sc->idx_type)
5460
                assert(!H5_addr_defined(udata.chunk_block.offset));
5461
5462
            /* Make sure the chunk is really in the dataset and outside the
5463
             * original dimensions */
5464
            {
5465
                unsigned v; /* Local index variable */
5466
                bool     outside_orig = false;
5467
5468
                for (v = 0; v < space_ndims; v++) {
5469
                    assert((scaled[v] * chunk_dim[v]) < space_dim[v]);
5470
                    if ((scaled[v] * chunk_dim[v]) >= old_dim[v])
5471
                        outside_orig = true;
5472
                } /* end for */
5473
                assert(outside_orig);
5474
            } /* end block */
5475
#endif        /* NDEBUG */
5476
5477
            /* Check for VL datatype & non-default fill value */
5478
0
            if (fb_info_init && fb_info.has_vlen_fill_type) {
5479
                /* Sanity check */
5480
0
                assert(should_fill);
5481
0
                assert(!unfilt_fill_buf);
5482
0
                assert(orig_chunk_size);
5483
#ifdef H5_HAVE_PARALLEL
5484
                assert(!using_mpi); /* Can't write VL datatypes in parallel currently */
5485
#endif
5486
5487
                /* Check to make sure the buffer is large enough.  It is
5488
                 * possible (though ill-advised) for the filter to shrink the
5489
                 * buffer.
5490
                 */
5491
0
                if (fb_info.fill_buf_size < orig_chunk_size) {
5492
0
                    if (NULL ==
5493
0
                        (fb_info.fill_buf = H5D__chunk_mem_realloc(fb_info.fill_buf, orig_chunk_size, pline)))
5494
0
                        HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL,
5495
0
                                    "memory reallocation failed for raw data chunk");
5496
0
                    fb_info.fill_buf_size = orig_chunk_size;
5497
0
                } /* end if */
5498
5499
                /* Fill the buffer with VL datatype fill values */
5500
0
                if (H5D__fill_refill_vl(&fb_info, fb_info.elmts_per_buf) < 0)
5501
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTCONVERT, FAIL, "can't refill fill value buffer");
5502
5503
                /* Check if there are filters which need to be applied to the chunk */
5504
0
                if ((pline->nused > 0) && !nunfilt_edge_chunk_dims) {
5505
0
                    H5Z_EDC_t err_detect; /* Error detection info */
5506
0
                    H5Z_cb_t  filter_cb;  /* I/O filter callback function */
5507
0
                    size_t    nbytes = orig_chunk_size;
5508
5509
                    /* Retrieve filter settings from API context */
5510
0
                    if (H5CX_get_err_detect(&err_detect) < 0)
5511
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't get error detection info");
5512
0
                    if (H5CX_get_filter_cb(&filter_cb) < 0)
5513
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't get I/O filter callback function");
5514
5515
                    /* Push the chunk through the filters */
5516
0
                    if (H5Z_pipeline(pline, 0, &filter_mask, err_detect, filter_cb, &nbytes,
5517
0
                                     &fb_info.fill_buf_size, &fb_info.fill_buf) < 0)
5518
0
                        HGOTO_ERROR(H5E_PLINE, H5E_WRITEERROR, FAIL, "output pipeline failed");
5519
5520
                    /* Keep the number of bytes the chunk turned in to */
5521
0
                    H5_CHECKED_ASSIGN(chunk_size, hsize_t, nbytes, size_t);
5522
0
                } /* end if */
5523
0
                else
5524
0
                    chunk_size = layout->u.chunk.size;
5525
5526
0
                assert(*fill_buf == fb_info.fill_buf);
5527
0
            } /* end if */
5528
5529
            /* Initialize the chunk information */
5530
0
            udata.common.layout      = &layout->u.chunk;
5531
0
            udata.common.storage     = sc;
5532
0
            udata.common.scaled      = scaled;
5533
0
            udata.chunk_block.offset = HADDR_UNDEF;
5534
0
            udata.chunk_block.length = chunk_size;
5535
0
            udata.filter_mask        = filter_mask;
5536
5537
            /* Allocate the chunk (with all processes) */
5538
0
            if (H5D__chunk_file_alloc(&idx_info, NULL, &udata.chunk_block, &need_insert, scaled) < 0)
5539
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL,
5540
0
                            "unable to insert/resize chunk on chunk level");
5541
0
            assert(H5_addr_defined(udata.chunk_block.offset));
5542
5543
            /* Check if fill values should be written to chunks */
5544
0
            if (should_fill) {
5545
                /* Sanity check */
5546
0
                assert(fb_info_init);
5547
0
                assert(udata.chunk_block.length == chunk_size);
5548
5549
#ifdef H5_HAVE_PARALLEL
5550
                /* Check if this file is accessed with an MPI-capable file driver */
5551
                if (using_mpi) {
5552
                    /* collect all chunk addresses to be written to
5553
                       write collectively at the end */
5554
5555
                    /* allocate/resize chunk info array if no more space left */
5556
                    if (0 == chunk_fill_info.num_chunks % 1024) {
5557
                        void *tmp_realloc;
5558
5559
                        if (NULL == (tmp_realloc = H5MM_realloc(chunk_fill_info.chunk_info,
5560
                                                                (chunk_fill_info.num_chunks + 1024) *
5561
                                                                    sizeof(struct chunk_coll_fill_info))))
5562
                            HGOTO_ERROR(H5E_DATASET, H5E_CANTALLOC, FAIL,
5563
                                        "memory allocation failed for chunk fill info");
5564
5565
                        chunk_fill_info.chunk_info = tmp_realloc;
5566
                    }
5567
5568
                    /* Store info about the chunk for later */
5569
                    chunk_fill_info.chunk_info[chunk_fill_info.num_chunks].addr = udata.chunk_block.offset;
5570
                    H5_CHECKED_ASSIGN(chunk_fill_info.chunk_info[chunk_fill_info.num_chunks].chunk_size,
5571
                                      size_t, chunk_size, hsize_t);
5572
                    chunk_fill_info.chunk_info[chunk_fill_info.num_chunks].unfiltered_partial_chunk =
5573
                        (*fill_buf == unfilt_fill_buf);
5574
                    chunk_fill_info.num_chunks++;
5575
5576
                    /* Indicate that blocks will be written */
5577
                    blocks_written = true;
5578
                } /* end if */
5579
                else
5580
#endif /* H5_HAVE_PARALLEL */
5581
0
                {
5582
0
                    H5_CHECK_OVERFLOW(chunk_size, hsize_t, size_t);
5583
0
                    if (H5F_shared_block_write(H5F_SHARED(dset->oloc.file), H5FD_MEM_DRAW,
5584
0
                                               udata.chunk_block.offset, (size_t)chunk_size, *fill_buf) < 0)
5585
0
                        HGOTO_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "unable to write raw data to file");
5586
0
                }
5587
0
            } /* end if */
5588
5589
            /* Insert the chunk record into the index */
5590
0
            if (need_insert && ops->insert)
5591
0
                if ((ops->insert)(&idx_info, &udata, dset) < 0)
5592
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL, "unable to insert chunk addr into index");
5593
5594
            /* Increment indices and adjust the edge chunk state */
5595
0
            carry = true;
5596
0
            for (i = ((int)space_ndims - 1); i >= 0; --i) {
5597
0
                scaled[i]++;
5598
0
                if (scaled[i] > max_unalloc[i]) {
5599
0
                    if ((unsigned)i == op_dim)
5600
0
                        scaled[i] = min_unalloc[i];
5601
0
                    else
5602
0
                        scaled[i] = 0;
5603
5604
                    /* Check if we just left the edge in this dimension */
5605
0
                    if (unfilt_edge_chunk_dim[i] && edge_chunk_scaled[i] == max_unalloc[i] &&
5606
0
                        scaled[i] < edge_chunk_scaled[i]) {
5607
0
                        nunfilt_edge_chunk_dims--;
5608
0
                        if (should_fill && nunfilt_edge_chunk_dims == 0 && !fb_info.has_vlen_fill_type) {
5609
0
                            assert(
5610
0
                                !H5D__chunk_is_partial_edge_chunk(space_ndims, chunk_dim, scaled, space_dim));
5611
0
                            assert(orig_chunk_size);
5612
0
                            fill_buf = &fb_info.fill_buf;
5613
0
                            H5_CHECKED_ASSIGN(chunk_size, hsize_t, orig_chunk_size, size_t);
5614
0
                        } /* end if */
5615
0
                    }     /* end if */
5616
0
                }         /* end if */
5617
0
                else {
5618
                    /* Check if we just entered the edge in this dimension */
5619
0
                    if (unfilt_edge_chunk_dim[i] && scaled[i] == edge_chunk_scaled[i]) {
5620
0
                        assert(edge_chunk_scaled[i] == max_unalloc[i]);
5621
0
                        nunfilt_edge_chunk_dims++;
5622
0
                        if (should_fill && nunfilt_edge_chunk_dims == 1 && !fb_info.has_vlen_fill_type) {
5623
0
                            assert(
5624
0
                                H5D__chunk_is_partial_edge_chunk(space_ndims, chunk_dim, scaled, space_dim));
5625
0
                            fill_buf   = &unfilt_fill_buf;
5626
0
                            chunk_size = layout->u.chunk.size;
5627
0
                        } /* end if */
5628
0
                    }     /* end if */
5629
5630
0
                    carry = false;
5631
0
                    break;
5632
0
                } /* end else */
5633
0
            }     /* end for */
5634
0
        }         /* end while(!carry) */
5635
5636
        /* Adjust max_unalloc so we don't allocate the same chunk twice.  Also
5637
         * check if this dimension started from 0 (and hence allocated all of
5638
         * the chunks. */
5639
0
        if (min_unalloc[op_dim] == 0)
5640
0
            break;
5641
0
        else
5642
0
            max_unalloc[op_dim] = min_unalloc[op_dim] - 1;
5643
0
    } /* end for(op_dim=0...) */
5644
5645
#ifdef H5_HAVE_PARALLEL
5646
    /* do final collective I/O */
5647
    if (using_mpi && blocks_written)
5648
        if (H5D__chunk_collective_fill(dset, &chunk_fill_info, fb_info.fill_buf, unfilt_fill_buf) < 0)
5649
            HGOTO_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "unable to write raw data to file");
5650
#endif /* H5_HAVE_PARALLEL */
5651
5652
    /* Reset any cached chunk info for this dataset */
5653
0
    H5D__chunk_cinfo_cache_reset(&dset->shared->cache.chunk.last);
5654
5655
0
done:
5656
    /* Release the fill buffer info, if it's been initialized */
5657
0
    if (fb_info_init && H5D__fill_term(&fb_info) < 0)
5658
0
        HDONE_ERROR(H5E_DATASET, H5E_CANTFREE, FAIL, "Can't release fill buffer info");
5659
5660
    /* Free the unfiltered fill value buffer */
5661
0
    unfilt_fill_buf = H5D__chunk_mem_xfree(unfilt_fill_buf, &def_pline);
5662
5663
#ifdef H5_HAVE_PARALLEL
5664
    if (using_mpi && chunk_fill_info.chunk_info)
5665
        H5MM_free(chunk_fill_info.chunk_info);
5666
#endif
5667
5668
0
    FUNC_LEAVE_NOAPI(ret_value)
5669
0
} /* end H5D__chunk_allocate() */
5670
5671
/*-------------------------------------------------------------------------
5672
 * Function:    H5D__chunk_update_old_edge_chunks
5673
 *
5674
 * Purpose:     Update all chunks which were previously partial edge
5675
 *              chunks and are now complete.  Determines exactly which
5676
 *              chunks need to be updated and locks each into cache using
5677
 *              the 'prev_unfilt_chunk' flag, then unlocks it, causing
5678
 *              filters to be applied as necessary.
5679
 *
5680
 * Return:      Non-negative on success/Negative on failure
5681
 *
5682
 *-------------------------------------------------------------------------
5683
 */
5684
herr_t
5685
H5D__chunk_update_old_edge_chunks(H5D_t *dset, hsize_t old_dim[])
5686
0
{
5687
0
    hsize_t old_edge_chunk_sc[H5O_LAYOUT_NDIMS]; /* Offset of first previously incomplete chunk in each
5688
                                                    dimension */
5689
0
    hsize_t max_edge_chunk_sc[H5O_LAYOUT_NDIMS]; /* largest offset of chunks that might need to be modified in
5690
                                                    each dimension */
5691
0
    bool new_full_dim[H5O_LAYOUT_NDIMS];         /* Whether the plane of chunks in this dimension needs to be
5692
                                                       modified */
5693
0
    const H5O_layout_t *layout = &(dset->shared->layout); /* Dataset layout */
5694
0
    hsize_t             chunk_sc[H5O_LAYOUT_NDIMS];       /* Offset of current chunk */
5695
0
    const hsize_t      *chunk_dim = layout->u.chunk.dim;  /* Convenience pointer to chunk dimensions */
5696
0
    unsigned            space_ndims;                      /* Dataset's space rank */
5697
0
    const hsize_t      *space_dim;                        /* Dataset's dataspace dimensions */
5698
0
    unsigned            op_dim;                           /* Current operating dimension */
5699
0
    H5D_io_info_t       chk_io_info;                      /* Chunked I/O info object */
5700
0
    H5D_chunk_ud_t      chk_udata;                        /* User data for locking chunk */
5701
0
    H5D_storage_t       chk_store;                        /* Chunk storage information */
5702
0
    H5D_dset_io_info_t  chk_dset_info;                    /* Chunked I/O dset info object */
5703
0
    void               *chunk = NULL;                     /* The file chunk  */
5704
0
    bool                carry; /* Flag to indicate that chunk increment carrys to higher dimension (sorta) */
5705
0
    herr_t              ret_value = SUCCEED; /* Return value */
5706
5707
0
    FUNC_ENTER_PACKAGE
5708
5709
    /* Check args */
5710
0
    assert(dset && H5D_CHUNKED == layout->type);
5711
0
    assert(layout->u.chunk.ndims > 0 && layout->u.chunk.ndims <= H5O_LAYOUT_NDIMS);
5712
0
    H5D_CHUNK_STORAGE_INDEX_CHK(&layout->storage.u.chunk);
5713
0
    assert(dset->shared->dcpl_cache.pline.nused > 0);
5714
0
    assert(layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS);
5715
5716
    /* Retrieve the dataset dimensions */
5717
0
    space_dim   = dset->shared->curr_dims;
5718
0
    space_ndims = dset->shared->ndims;
5719
5720
    /* The last dimension in chunk_offset is always 0 */
5721
0
    chunk_sc[space_ndims] = (hsize_t)0;
5722
5723
    /* Check if any current dimensions are smaller than the chunk size, or if
5724
     * any old dimensions are 0.  If so we do not have to do anything. */
5725
0
    for (op_dim = 0; op_dim < space_ndims; op_dim++)
5726
0
        if ((space_dim[op_dim] < chunk_dim[op_dim]) || old_dim[op_dim] == 0) {
5727
            /* Reset any cached chunk info for this dataset */
5728
0
            H5D__chunk_cinfo_cache_reset(&dset->shared->cache.chunk.last);
5729
0
            HGOTO_DONE(SUCCEED);
5730
0
        } /* end if */
5731
5732
    /* Set up chunked I/O info object, for operations on chunks (in callback).
5733
     * Note that we only need to set chunk_offset once, as the array's address
5734
     * will never change. */
5735
0
    chk_store.chunk.scaled = chunk_sc;
5736
5737
0
    chk_io_info.op_type = H5D_IO_OP_READ;
5738
5739
0
    chk_dset_info.dset     = dset;
5740
0
    chk_dset_info.store    = &chk_store;
5741
0
    chk_dset_info.buf.vp   = NULL;
5742
0
    chk_io_info.dsets_info = &chk_dset_info;
5743
5744
    /*
5745
     * Determine the edges of the dataset which need to be modified
5746
     */
5747
0
    for (op_dim = 0; op_dim < space_ndims; op_dim++) {
5748
        /* Start off with this dimension marked as not needing to be modified */
5749
0
        new_full_dim[op_dim] = false;
5750
5751
        /* Validate this chunk dimension */
5752
0
        if (chunk_dim[op_dim] == 0)
5753
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "chunk size must be > 0, dim = %u ", op_dim);
5754
5755
        /* Calculate offset of first previously incomplete chunk in this
5756
         * dimension */
5757
0
        old_edge_chunk_sc[op_dim] = (old_dim[op_dim] / chunk_dim[op_dim]);
5758
5759
        /* Calculate the largest offset of chunks that might need to be
5760
         * modified in this dimension */
5761
0
        max_edge_chunk_sc[op_dim] = MIN((old_dim[op_dim] - 1) / chunk_dim[op_dim],
5762
0
                                        MAX((space_dim[op_dim] / chunk_dim[op_dim]), 1) - 1);
5763
5764
        /* Check for old_dim aligned with chunk boundary in this dimension, if
5765
         * so we do not need to modify chunks along the edge in this dimension
5766
         */
5767
0
        if (old_dim[op_dim] % chunk_dim[op_dim] == 0)
5768
0
            continue;
5769
5770
        /* Check if the dataspace expanded enough to cause the old edge chunks
5771
         * in this dimension to become full */
5772
0
        if ((space_dim[op_dim] / chunk_dim[op_dim]) >= (old_edge_chunk_sc[op_dim] + 1))
5773
0
            new_full_dim[op_dim] = true;
5774
0
    } /* end for */
5775
5776
    /* Main loop: fix old edge chunks */
5777
0
    for (op_dim = 0; op_dim < space_ndims; op_dim++) {
5778
        /* Check if allocation along this dimension is really necessary */
5779
0
        if (!new_full_dim[op_dim])
5780
0
            continue;
5781
0
        else {
5782
0
            assert(max_edge_chunk_sc[op_dim] == old_edge_chunk_sc[op_dim]);
5783
5784
            /* Reset the chunk offset indices */
5785
0
            memset(chunk_sc, 0, (space_ndims * sizeof(chunk_sc[0])));
5786
0
            chunk_sc[op_dim] = old_edge_chunk_sc[op_dim];
5787
5788
0
            carry = false;
5789
0
        } /* end if */
5790
5791
0
        while (!carry) {
5792
0
            int i; /* Local index variable */
5793
5794
            /* Make sure the chunk is really a former edge chunk */
5795
0
            assert(H5D__chunk_is_partial_edge_chunk(space_ndims, chunk_dim, chunk_sc, old_dim) &&
5796
0
                   !H5D__chunk_is_partial_edge_chunk(space_ndims, chunk_dim, chunk_sc, space_dim));
5797
5798
            /* Lookup the chunk */
5799
0
            if (H5D__chunk_lookup(dset, chunk_sc, &chk_udata) < 0)
5800
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
5801
5802
            /* If this chunk does not exist in cache or on disk, no need to do
5803
             * anything */
5804
0
            if (H5_addr_defined(chk_udata.chunk_block.offset) || (UINT_MAX != chk_udata.idx_hint)) {
5805
                /* Lock the chunk into cache.  H5D__chunk_lock will take care of
5806
                 * updating the chunk to no longer be an edge chunk. */
5807
0
                if (NULL ==
5808
0
                    (chunk = (void *)H5D__chunk_lock(&chk_io_info, &chk_dset_info, &chk_udata, false, true)))
5809
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTLOCK, FAIL, "unable to lock raw data chunk");
5810
5811
                /* Unlock the chunk */
5812
0
                if (H5D__chunk_unlock(&chk_io_info, &chk_dset_info, &chk_udata, true, chunk, (hsize_t)0) < 0)
5813
0
                    HGOTO_ERROR(H5E_IO, H5E_CANTUNLOCK, FAIL, "unable to unlock raw data chunk");
5814
0
                chunk = NULL;
5815
0
            } /* end if */
5816
5817
            /* Increment indices */
5818
0
            carry = true;
5819
0
            for (i = ((int)space_ndims - 1); i >= 0; --i) {
5820
0
                if ((unsigned)i != op_dim) {
5821
0
                    ++chunk_sc[i];
5822
0
                    if (chunk_sc[i] > (hsize_t)max_edge_chunk_sc[i])
5823
0
                        chunk_sc[i] = 0;
5824
0
                    else {
5825
0
                        carry = false;
5826
0
                        break;
5827
0
                    } /* end else */
5828
0
                }     /* end if */
5829
0
            }         /* end for */
5830
0
        }             /* end while(!carry) */
5831
5832
        /* Adjust max_edge_chunk_sc so we don't modify the same chunk twice.
5833
         * Also check if this dimension started from 0 (and hence modified all
5834
         * of the old edge chunks. */
5835
0
        if (old_edge_chunk_sc[op_dim] == 0)
5836
0
            break;
5837
0
        else
5838
0
            --max_edge_chunk_sc[op_dim];
5839
0
    } /* end for(op_dim=0...) */
5840
5841
    /* Reset any cached chunk info for this dataset */
5842
0
    H5D__chunk_cinfo_cache_reset(&dset->shared->cache.chunk.last);
5843
5844
0
done:
5845
0
    FUNC_LEAVE_NOAPI(ret_value)
5846
0
} /* end H5D__chunk_update_old_edge_chunks() */
5847
5848
#ifdef H5_HAVE_PARALLEL
5849
5850
/*-------------------------------------------------------------------------
5851
 * Function:    H5D__chunk_collective_fill
5852
 *
5853
 * Purpose:     Use MPIO selection vector I/O for writing fill chunks
5854
 *
5855
 * Return:      Non-negative on success/Negative on failure
5856
 *
5857
 *-------------------------------------------------------------------------
5858
 */
5859
static herr_t
5860
H5D__chunk_collective_fill(const H5D_t *dset, H5D_chunk_coll_fill_info_t *chunk_fill_info,
5861
                           const void *fill_buf, const void *partial_chunk_fill_buf)
5862
{
5863
    MPI_Comm         mpi_comm = MPI_COMM_NULL; /* MPI communicator for file */
5864
    int              mpi_rank = (-1);          /* This process's rank  */
5865
    int              mpi_size = (-1);          /* MPI Comm size  */
5866
    int              mpi_code;                 /* MPI return code */
5867
    size_t           num_blocks;               /* Number of blocks between processes. */
5868
    size_t           leftover_blocks;          /* Number of leftover blocks to handle */
5869
    int              blocks;                   /* converted to int for MPI */
5870
    int              leftover;                 /* converted to int for MPI */
5871
    H5FD_mpio_xfer_t prev_xfer_mode;           /* Previous data xfer mode */
5872
    bool             have_xfer_mode = false;   /* Whether the previous xffer mode has been retrieved */
5873
    size_t           i;                        /* Local index variable */
5874
    haddr_t         *io_addrs = NULL;
5875
    size_t          *io_sizes = NULL;
5876
    const void     **io_wbufs = NULL;
5877
    H5FD_mem_t       io_types[2];
5878
    bool             all_same_block_len = true;
5879
    bool             need_sort          = false;
5880
    size_t           io_2sizes[2];
5881
    herr_t           ret_value = SUCCEED; /* Return value */
5882
5883
    FUNC_ENTER_PACKAGE
5884
5885
    assert(chunk_fill_info->num_chunks != 0);
5886
5887
    /*
5888
     * If a separate fill buffer is provided for partial chunks, ensure
5889
     * that the "don't filter partial edge chunks" flag is set.
5890
     */
5891
    if (partial_chunk_fill_buf)
5892
        assert(dset->shared->layout.u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS);
5893
5894
    /* Get the MPI communicator */
5895
    if (MPI_COMM_NULL == (mpi_comm = H5F_mpi_get_comm(dset->oloc.file)))
5896
        HGOTO_ERROR(H5E_INTERNAL, H5E_MPI, FAIL, "Can't retrieve MPI communicator");
5897
5898
    /* Get the MPI rank */
5899
    if ((mpi_rank = H5F_mpi_get_rank(dset->oloc.file)) < 0)
5900
        HGOTO_ERROR(H5E_INTERNAL, H5E_MPI, FAIL, "Can't retrieve MPI rank");
5901
5902
    /* Get the MPI size */
5903
    if ((mpi_size = H5F_mpi_get_size(dset->oloc.file)) < 0)
5904
        HGOTO_ERROR(H5E_INTERNAL, H5E_MPI, FAIL, "Can't retrieve MPI size");
5905
5906
    /* Distribute evenly the number of blocks between processes. */
5907
    if (mpi_size == 0)
5908
        HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "Resulted in division by zero");
5909
5910
    num_blocks =
5911
        (size_t)(chunk_fill_info->num_chunks / (size_t)mpi_size); /* value should be the same on all procs */
5912
5913
    /* After evenly distributing the blocks between processes, are there any
5914
     * leftover blocks for each individual process (round-robin)?
5915
     */
5916
    leftover_blocks = (size_t)(chunk_fill_info->num_chunks % (size_t)mpi_size);
5917
5918
    /* Cast values to types needed by MPI */
5919
    H5_CHECKED_ASSIGN(blocks, int, num_blocks, size_t);
5920
    H5_CHECKED_ASSIGN(leftover, int, leftover_blocks, size_t);
5921
5922
    /* Check if we have any chunks to write on this rank */
5923
    if (num_blocks > 0 || leftover > mpi_rank) {
5924
5925
        if (NULL == (io_addrs = H5MM_malloc((size_t)(blocks + 1) * sizeof(*io_addrs))))
5926
            HGOTO_ERROR(H5E_RESOURCE, H5E_CANTALLOC, FAIL,
5927
                        "couldn't allocate space for I/O addresses vector");
5928
5929
        if (NULL == (io_wbufs = H5MM_malloc((size_t)(blocks + 1) * sizeof(*io_wbufs))))
5930
            HGOTO_ERROR(H5E_RESOURCE, H5E_CANTALLOC, FAIL, "couldn't allocate space for I/O buffers vector");
5931
    }
5932
5933
    /*
5934
     * Perform initial scan of chunk info list to:
5935
     *  - make sure that chunk addresses are monotonically non-decreasing
5936
     *  - check if all blocks have the same length
5937
     */
5938
    for (i = 1; i < chunk_fill_info->num_chunks; i++) {
5939
        if (chunk_fill_info->chunk_info[i].addr < chunk_fill_info->chunk_info[i - 1].addr)
5940
            need_sort = true;
5941
5942
        if (chunk_fill_info->chunk_info[i].chunk_size != chunk_fill_info->chunk_info[i - 1].chunk_size)
5943
            all_same_block_len = false;
5944
    }
5945
5946
    /*
5947
     * Note that we sort all of the chunks here, and not just a subset
5948
     * corresponding to this rank. We do this since we have found MPI I/O to work
5949
     * better when each rank writes blocks that are contiguous in the file,
5950
     * and by sorting the full list we maximize the chance of that happening.
5951
     */
5952
    if (need_sort)
5953
        qsort(chunk_fill_info->chunk_info, chunk_fill_info->num_chunks, sizeof(struct chunk_coll_fill_info),
5954
              H5D__chunk_cmp_coll_fill_info);
5955
5956
    /*
5957
     * If all the chunks have the same length, use the compressed feature
5958
     * to store the size.
5959
     * Otherwise, allocate the array of sizes for storing chunk sizes.
5960
     */
5961
    if (all_same_block_len) {
5962
        io_2sizes[0] = chunk_fill_info->chunk_info[0].chunk_size;
5963
        io_2sizes[1] = 0;
5964
    }
5965
    else {
5966
        if (NULL == (io_sizes = H5MM_malloc((size_t)(blocks + 1) * sizeof(*io_sizes))))
5967
            HGOTO_ERROR(H5E_RESOURCE, H5E_CANTALLOC, FAIL, "couldn't allocate space for I/O sizes vector");
5968
    }
5969
5970
    /*
5971
     * Since the type of all chunks is raw data, use the compressed feature
5972
     * to store the chunk type.
5973
     */
5974
    io_types[0] = H5FD_MEM_DRAW;
5975
    io_types[1] = H5FD_MEM_NOLIST;
5976
5977
    /*
5978
     * For the chunks corresponding to this rank, fill in the
5979
     * address, size and buf pointer for each chunk.
5980
     */
5981
    for (i = 0; i < (size_t)blocks; i++) {
5982
        size_t idx = i + (size_t)(mpi_rank * blocks);
5983
5984
        io_addrs[i] = chunk_fill_info->chunk_info[idx].addr;
5985
5986
        if (!all_same_block_len)
5987
            io_sizes[i] = chunk_fill_info->chunk_info[idx].chunk_size;
5988
5989
        if (chunk_fill_info->chunk_info[idx].unfiltered_partial_chunk)
5990
            io_wbufs[i] = partial_chunk_fill_buf;
5991
        else
5992
            io_wbufs[i] = fill_buf;
5993
    }
5994
5995
    /*
5996
     * For the leftover chunk corresponding to this rank, fill in the
5997
     * address, size and buf pointer for the chunk.
5998
     */
5999
    if (leftover > mpi_rank) {
6000
        io_addrs[blocks] = chunk_fill_info->chunk_info[(blocks * mpi_size) + mpi_rank].addr;
6001
6002
        if (!all_same_block_len)
6003
            io_sizes[blocks] = chunk_fill_info->chunk_info[(blocks * mpi_size) + mpi_rank].chunk_size;
6004
6005
        if (chunk_fill_info->chunk_info[(blocks * mpi_size) + mpi_rank].unfiltered_partial_chunk) {
6006
            assert(partial_chunk_fill_buf);
6007
            io_wbufs[blocks] = partial_chunk_fill_buf;
6008
        }
6009
        else
6010
            io_wbufs[blocks] = fill_buf;
6011
6012
        blocks++;
6013
    }
6014
6015
    /* Get current transfer mode */
6016
    if (H5CX_get_io_xfer_mode(&prev_xfer_mode) < 0)
6017
        HGOTO_ERROR(H5E_DATASET, H5E_CANTSET, FAIL, "can't set transfer mode");
6018
    have_xfer_mode = true;
6019
6020
    /* Set transfer mode */
6021
    if (H5CX_set_io_xfer_mode(H5FD_MPIO_COLLECTIVE) < 0)
6022
        HGOTO_ERROR(H5E_DATASET, H5E_CANTSET, FAIL, "can't set transfer mode");
6023
6024
    /* Barrier so processes don't race ahead */
6025
    if (MPI_SUCCESS != (mpi_code = MPI_Barrier(mpi_comm)))
6026
        HMPI_GOTO_ERROR(FAIL, "MPI_Barrier failed", mpi_code)
6027
6028
    /* Perform the selection vector I/O for the chunks */
6029
    if (H5F_shared_vector_write(H5F_SHARED(dset->oloc.file), (uint32_t)blocks, io_types, io_addrs,
6030
                                all_same_block_len ? io_2sizes : io_sizes, io_wbufs) < 0)
6031
        HGOTO_ERROR(H5E_DATASET, H5E_WRITEERROR, FAIL, "vector write call failed");
6032
6033
done:
6034
    if (have_xfer_mode)
6035
        /* Restore transfer mode */
6036
        if (H5CX_set_io_xfer_mode(prev_xfer_mode) < 0)
6037
            HDONE_ERROR(H5E_DATASET, H5E_CANTSET, FAIL, "can't set transfer mode");
6038
6039
    H5MM_xfree(io_addrs);
6040
    H5MM_xfree(io_wbufs);
6041
    H5MM_xfree(io_sizes);
6042
6043
    FUNC_LEAVE_NOAPI(ret_value)
6044
} /* end H5D__chunk_collective_fill() */
6045
6046
static int
6047
H5D__chunk_cmp_coll_fill_info(const void *_entry1, const void *_entry2)
6048
{
6049
    const struct chunk_coll_fill_info *entry1;
6050
    const struct chunk_coll_fill_info *entry2;
6051
    int                                ret_value = 0;
6052
6053
    FUNC_ENTER_PACKAGE_NOERR
6054
6055
    entry1 = (const struct chunk_coll_fill_info *)_entry1;
6056
    entry2 = (const struct chunk_coll_fill_info *)_entry2;
6057
6058
    ret_value = H5_addr_cmp(entry1->addr, entry2->addr);
6059
6060
    FUNC_LEAVE_NOAPI(ret_value)
6061
} /* end H5D__chunk_cmp_coll_fill_info() */
6062
6063
#endif /* H5_HAVE_PARALLEL */
6064
6065
/*-------------------------------------------------------------------------
6066
 * Function:    H5D__chunk_prune_fill
6067
 *
6068
 * Purpose:    Write the fill value to the parts of the chunk that are no
6069
 *              longer part of the dataspace
6070
 *
6071
 * Return:    Non-negative on success/Negative on failure
6072
 *
6073
 *-------------------------------------------------------------------------
6074
 */
6075
static herr_t
6076
H5D__chunk_prune_fill(H5D_chunk_it_ud1_t *udata, bool new_unfilt_chunk)
6077
0
{
6078
0
    const H5D_io_info_t *io_info         = udata->io_info;          /* Local pointer to I/O info */
6079
0
    const H5D_t         *dset            = udata->dset_info->dset;  /* Local pointer to the dataset info */
6080
0
    const H5O_layout_t  *layout          = &(dset->shared->layout); /* Dataset's layout */
6081
0
    unsigned             rank            = udata->common.layout->ndims - 1; /* Dataset rank */
6082
0
    const hsize_t       *scaled          = udata->common.scaled;            /* Scaled chunk offset */
6083
0
    H5S_sel_iter_t      *chunk_iter      = NULL;  /* Memory selection iteration info */
6084
0
    bool                 chunk_iter_init = false; /* Whether the chunk iterator has been initialized */
6085
0
    hsize_t              sel_nelmts;              /* Number of elements in selection */
6086
0
    hsize_t              count[H5O_LAYOUT_NDIMS]; /* Element count of hyperslab */
6087
0
    size_t               chunk_size;              /*size of a chunk       */
6088
0
    void                *chunk = NULL;            /* The file chunk  */
6089
0
    H5D_chunk_ud_t       chk_udata;               /* User data for locking chunk */
6090
0
    hsize_t              bytes_accessed = 0;      /* Bytes accessed in chunk */
6091
0
    unsigned             u;                       /* Local index variable */
6092
0
    bool                 chunk_locked = false;    /* Indicates whether the chunk is locked */
6093
0
    bool                 chunk_dirty  = false;    /* Indicates whether writing is needed */
6094
0
    herr_t               ret_value    = SUCCEED;  /* Return value */
6095
6096
0
    FUNC_ENTER_PACKAGE
6097
6098
    /* Get the chunk's size */
6099
0
    assert(layout->u.chunk.size > 0);
6100
0
    H5_CHECKED_ASSIGN(chunk_size, size_t, layout->u.chunk.size, hsize_t);
6101
6102
    /* Get the info for the chunk in the file */
6103
0
    if (H5D__chunk_lookup(dset, scaled, &chk_udata) < 0)
6104
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk address");
6105
0
    chk_udata.new_unfilt_chunk = new_unfilt_chunk;
6106
6107
    /* If this chunk does not exist in cache or on disk, no need to do anything */
6108
0
    if (!H5_addr_defined(chk_udata.chunk_block.offset) && UINT_MAX == chk_udata.idx_hint)
6109
0
        HGOTO_DONE(SUCCEED);
6110
6111
    /* Initialize the fill value buffer, if necessary */
6112
0
    if (!udata->fb_info_init) {
6113
0
        H5_CHECK_OVERFLOW(udata->elmts_per_chunk, hsize_t, size_t);
6114
0
        if (H5D__fill_init(&udata->fb_info, NULL, NULL, NULL, NULL, NULL, &dset->shared->dcpl_cache.fill,
6115
0
                           dset->shared->type, (size_t)udata->elmts_per_chunk, chunk_size) < 0)
6116
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "can't initialize fill buffer info");
6117
0
        udata->fb_info_init = true;
6118
0
    } /* end if */
6119
6120
    /* Compute the # of elements to leave with existing value, in each dimension */
6121
0
    for (u = 0; u < rank; u++) {
6122
0
        count[u] = MIN(layout->u.chunk.dim[u], (udata->space_dim[u] - (scaled[u] * layout->u.chunk.dim[u])));
6123
0
        assert(count[u] > 0);
6124
0
    } /* end for */
6125
6126
    /* Select all elements in chunk, to begin with */
6127
0
    if (H5S_select_all(udata->chunk_space, true) < 0)
6128
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTSELECT, FAIL, "unable to select space");
6129
6130
    /* "Subtract out" the elements to keep */
6131
0
    if (H5S_select_hyperslab(udata->chunk_space, H5S_SELECT_NOTB, udata->hyper_start, NULL, count, NULL) < 0)
6132
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTSELECT, FAIL, "unable to select hyperslab");
6133
6134
    /* Lock the chunk into the cache, to get a pointer to the chunk buffer */
6135
0
    if (NULL == (chunk = (void *)H5D__chunk_lock(io_info, udata->dset_info, &chk_udata, false, false)))
6136
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTLOCK, FAIL, "unable to lock raw data chunk");
6137
0
    chunk_locked = true;
6138
6139
    /* Fill the selection in the memory buffer */
6140
    /* Use the size of the elements in the chunk directly instead of */
6141
    /* relying on the fill.size, which might be set to 0 if there is */
6142
    /* no fill-value defined for the dataset -QAK */
6143
6144
    /* Get the number of elements in the selection */
6145
0
    sel_nelmts = H5S_GET_SELECT_NPOINTS(udata->chunk_space);
6146
0
    H5_CHECK_OVERFLOW(sel_nelmts, hsize_t, size_t);
6147
6148
    /* Check for VL datatype & non-default fill value */
6149
0
    if (udata->fb_info.has_vlen_fill_type)
6150
        /* Re-fill the buffer to use for this I/O operation */
6151
0
        if (H5D__fill_refill_vl(&udata->fb_info, (size_t)sel_nelmts) < 0)
6152
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTCONVERT, FAIL, "can't refill fill value buffer");
6153
6154
    /* Allocate the chunk selection iterator */
6155
0
    if (NULL == (chunk_iter = H5FL_MALLOC(H5S_sel_iter_t)))
6156
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTALLOC, FAIL, "can't allocate chunk selection iterator");
6157
6158
    /* Create a selection iterator for scattering the elements to memory buffer */
6159
0
    H5_CHECK_OVERFLOW(layout->u.chunk.dim[rank], hsize_t, size_t);
6160
0
    if (H5S_select_iter_init(chunk_iter, udata->chunk_space, (size_t)layout->u.chunk.dim[rank], 0) < 0)
6161
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to initialize chunk selection information");
6162
0
    chunk_iter_init = true;
6163
6164
    /* Scatter the data into memory */
6165
0
    if (H5D__scatter_mem(udata->fb_info.fill_buf, chunk_iter, (size_t)sel_nelmts, chunk /*out*/) < 0)
6166
0
        HGOTO_ERROR(H5E_DATASET, H5E_WRITEERROR, FAIL, "scatter failed");
6167
0
    chunk_dirty = true;
6168
6169
    /* The number of bytes accessed in the chunk */
6170
    /* (i.e. the bytes replaced with fill values) */
6171
0
    bytes_accessed = sel_nelmts * layout->u.chunk.dim[rank];
6172
6173
    /* Release lock on chunk */
6174
0
    chunk_locked = false;
6175
0
    if (H5D__chunk_unlock(io_info, udata->dset_info, &chk_udata, chunk_dirty, chunk, bytes_accessed) < 0)
6176
0
        HGOTO_ERROR(H5E_IO, H5E_CANTUNLOCK, FAIL, "unable to unlock raw data chunk");
6177
0
    chunk = NULL;
6178
6179
0
done:
6180
    /* Release chunk lock if we failed while holding it */
6181
0
    if (chunk_locked && chunk)
6182
0
        if (H5D__chunk_unlock(io_info, udata->dset_info, &chk_udata, chunk_dirty, chunk, bytes_accessed) < 0)
6183
0
            HDONE_ERROR(H5E_IO, H5E_CANTUNLOCK, FAIL, "unable to unlock raw data chunk");
6184
6185
    /* Release the selection iterator */
6186
0
    if (chunk_iter_init && H5S_SELECT_ITER_RELEASE(chunk_iter) < 0)
6187
0
        HDONE_ERROR(H5E_DATASET, H5E_CANTFREE, FAIL, "can't release selection iterator");
6188
0
    if (chunk_iter)
6189
0
        chunk_iter = H5FL_FREE(H5S_sel_iter_t, chunk_iter);
6190
6191
0
    FUNC_LEAVE_NOAPI(ret_value)
6192
0
} /* H5D__chunk_prune_fill */
6193
6194
/*-------------------------------------------------------------------------
6195
 * Function:    H5D__chunk_prune_by_extent
6196
 *
6197
 * Purpose:    This function searches for chunks that are no longer necessary
6198
 *              both in the raw data cache and in the chunk index.
6199
 *
6200
 * Return:    Non-negative on success/Negative on failure
6201
 *
6202
 * The algorithm is:
6203
 *
6204
 *  For chunks that are no longer necessary:
6205
 *
6206
 *  1. Search in the raw data cache for each chunk
6207
 *  2. If found then preempt it from the cache
6208
 *  3. Search in the B-tree for each chunk
6209
 *  4. If found then remove it from the B-tree and deallocate file storage for the chunk
6210
 *
6211
 * This example shows a 2d dataset of 90x90 with a chunk size of 20x20.
6212
 *
6213
 *
6214
 *     0         20        40        60        80    90   100
6215
 *    0 +---------+---------+---------+---------+-----+...+
6216
 *      |:::::X::::::::::::::         :         :     |   :
6217
 *      |:::::::X::::::::::::         :         :     |   :   Key
6218
 *      |::::::::::X:::::::::         :         :     |   :   --------
6219
 *      |::::::::::::X:::::::         :         :     |   :  +-+ Dataset
6220
 *    20+::::::::::::::::::::.........:.........:.....+...:  | | Extent
6221
 *      |         :::::X:::::         :         :     |   :  +-+
6222
 *      |         :::::::::::         :         :     |   :
6223
 *      |         :::::::::::         :         :     |   :  ... Chunk
6224
 *      |         :::::::X:::         :         :     |   :  : : Boundary
6225
 *    40+.........:::::::::::.........:.........:.....+...:  :.:
6226
 *      |         :         :         :         :     |   :
6227
 *      |         :         :         :         :     |   :  ... Allocated
6228
 *      |         :         :         :         :     |   :  ::: & Filled
6229
 *      |         :         :         :         :     |   :  ::: Chunk
6230
 *    60+.........:.........:.........:.........:.....+...:
6231
 *      |         :         :::::::X:::         :     |   :   X  Element
6232
 *      |         :         :::::::::::         :     |   :      Written
6233
 *      |         :         :::::::::::         :     |   :
6234
 *      |         :         :::::::::::         :     |   :
6235
 *    80+.........:.........:::::::::::.........:.....+...:   O  Fill Val
6236
 *      |         :         :         :::::::::::     |   :      Explicitly
6237
 *      |         :         :         ::::::X::::     |   :      Written
6238
 *    90+---------+---------+---------+---------+-----+   :
6239
 *      :         :         :         :::::::::::         :
6240
 *   100:.........:.........:.........:::::::::::.........:
6241
 *
6242
 *
6243
 * We have 25 total chunks for this dataset, 5 of which have space
6244
 * allocated in the file because they were written to one or more
6245
 * elements. These five chunks (and only these five) also have entries in
6246
 * the storage B-tree for this dataset.
6247
 *
6248
 * Now lets say we want to shrink the dataset down to 70x70:
6249
 *
6250
 *
6251
 *      0         20        40        60   70   80    90   100
6252
 *    0 +---------+---------+---------+----+----+-----+...+
6253
 *      |:::::X::::::::::::::         :    |    :     |   :
6254
 *      |:::::::X::::::::::::         :    |    :     |   :    Key
6255
 *      |::::::::::X:::::::::         :    |    :     |   :    --------
6256
 *      |::::::::::::X:::::::         :    |    :     |   :   +-+ Dataset
6257
 *    20+::::::::::::::::::::.........:....+....:.....|...:   | | Extent
6258
 *      |         :::::X:::::         :    |    :     |   :   +-+
6259
 *      |         :::::::::::         :    |    :     |   :
6260
 *      |         :::::::::::         :    |    :     |   :   ... Chunk
6261
 *      |         :::::::X:::         :    |    :     |   :   : : Boundary
6262
 *    40+.........:::::::::::.........:....+....:.....|...:   :.:
6263
 *      |         :         :         :    |    :     |   :
6264
 *      |         :         :         :    |    :     |   :   ... Allocated
6265
 *      |         :         :         :    |    :     |   :   ::: & Filled
6266
 *      |         :         :         :    |    :     |   :   ::: Chunk
6267
 *    60+.........:.........:.........:....+....:.....|...:
6268
 *      |         :         :::::::X:::    |    :     |   :    X  Element
6269
 *      |         :         :::::::::::    |    :     |   :       Written
6270
 *      +---------+---------+---------+----+    :     |   :
6271
 *      |         :         :::::::::::         :     |   :
6272
 *    80+.........:.........:::::::::X:.........:.....|...:    O  Fill Val
6273
 *      |         :         :         :::::::::::     |   :       Explicitly
6274
 *      |         :         :         ::::::X::::     |   :       Written
6275
 *    90+---------+---------+---------+---------+-----+   :
6276
 *      :         :         :         :::::::::::         :
6277
 *   100:.........:.........:.........:::::::::::.........:
6278
 *
6279
 *
6280
 * That means that the nine chunks along the bottom and right side should
6281
 * no longer exist. Of those nine chunks, (0,80), (20,80), (40,80),
6282
 * (60,80), (80,80), (80,60), (80,40), (80,20), and (80,0), one is actually allocated
6283
 * that needs to be released.
6284
 * To release the chunks, we traverse the B-tree to obtain a list of unused
6285
 * allocated chunks, and then call H5B_remove() for each chunk.
6286
 *
6287
 *-------------------------------------------------------------------------
6288
 */
6289
herr_t
6290
H5D__chunk_prune_by_extent(H5D_t *dset, const hsize_t *old_dim)
6291
0
{
6292
0
    hsize_t min_mod_chunk_sc[H5O_LAYOUT_NDIMS]; /* Scaled offset of first chunk to modify in each dimension */
6293
0
    hsize_t max_mod_chunk_sc[H5O_LAYOUT_NDIMS]; /* Scaled offset of last chunk to modify in each dimension */
6294
0
    hssize_t max_fill_chunk_sc[H5O_LAYOUT_NDIMS]; /* Scaled offset of last chunk that might be filled in each
6295
                                                     dimension */
6296
0
    bool fill_dim[H5O_LAYOUT_NDIMS]; /* Whether the plane of edge chunks in this dimension needs to be
6297
                                           filled */
6298
0
    hsize_t min_partial_chunk_sc[H5O_LAYOUT_NDIMS]; /* Offset of first partial (or empty) chunk in each
6299
                                                       dimension */
6300
0
    bool new_unfilt_dim[H5O_LAYOUT_NDIMS]; /* Whether the plane of edge chunks in this dimension are newly
6301
                                                 unfiltered */
6302
0
    H5D_chk_idx_info_t  idx_info;          /* Chunked index info */
6303
0
    H5D_io_info_t       chk_io_info;       /* Chunked I/O info object */
6304
0
    H5D_dset_io_info_t  chk_dset_info;     /* Chunked I/O dset info object */
6305
0
    H5D_storage_t       chk_store;         /* Chunk storage information */
6306
0
    const H5O_layout_t *layout = &(dset->shared->layout);      /* Dataset's layout */
6307
0
    const H5D_rdcc_t   *rdcc   = &(dset->shared->cache.chunk); /*raw data chunk cache */
6308
0
    unsigned            space_ndims;                           /* Dataset's space rank */
6309
0
    const hsize_t      *space_dim;                             /* Current dataspace dimensions */
6310
0
    unsigned            op_dim;                                /* Current operating dimension */
6311
0
    bool                shrunk_dim[H5O_LAYOUT_NDIMS];          /* Dimensions which have shrunk */
6312
0
    H5D_chunk_it_ud1_t  udata;                                 /* Chunk index iterator user data */
6313
0
    bool udata_init = false;         /* Whether the chunk index iterator user data has been initialized */
6314
0
    H5D_chunk_common_ud_t idx_udata; /* User data for index removal routine */
6315
0
    H5S_t                *chunk_space = NULL;            /* Dataspace for a chunk */
6316
0
    hsize_t               chunk_dim[H5O_LAYOUT_NDIMS];   /* Chunk dimensions */
6317
0
    hsize_t               scaled[H5O_LAYOUT_NDIMS];      /* Scaled offset of current chunk */
6318
0
    hsize_t               hyper_start[H5O_LAYOUT_NDIMS]; /* Starting location of hyperslab */
6319
0
    hsize_t               elmts_per_chunk;               /* Elements in chunk */
6320
0
    bool     disable_edge_filters = false; /* Whether to disable filters on partial edge chunks */
6321
0
    bool     new_unfilt_chunk     = false; /* Whether the chunk is newly unfiltered */
6322
0
    unsigned u;                            /* Local index variable */
6323
0
    const H5O_storage_chunk_t *sc        = &(layout->storage.u.chunk);
6324
0
    herr_t                     ret_value = SUCCEED; /* Return value */
6325
6326
0
    FUNC_ENTER_PACKAGE
6327
6328
    /* Check args */
6329
0
    assert(dset && H5D_CHUNKED == layout->type);
6330
0
    assert(layout->u.chunk.ndims > 0 && layout->u.chunk.ndims <= H5O_LAYOUT_NDIMS);
6331
0
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
6332
6333
    /* Go get the rank & dimensions (including the element size) */
6334
0
    space_dim   = dset->shared->curr_dims;
6335
0
    space_ndims = dset->shared->ndims;
6336
6337
    /* The last dimension in scaled is always 0 */
6338
0
    scaled[space_ndims] = (hsize_t)0;
6339
6340
    /* Check if any old dimensions are 0, if so we do not have to do anything */
6341
0
    for (op_dim = 0; op_dim < (unsigned)space_ndims; op_dim++)
6342
0
        if (old_dim[op_dim] == 0) {
6343
            /* Reset any cached chunk info for this dataset */
6344
0
            H5D__chunk_cinfo_cache_reset(&dset->shared->cache.chunk.last);
6345
0
            HGOTO_DONE(SUCCEED);
6346
0
        } /* end if */
6347
6348
    /* Round up to the next integer # of chunks, to accommodate partial chunks */
6349
    /* Use current dims because the indices have already been updated! -NAF */
6350
    /* (also compute the number of elements per chunk) */
6351
    /* (also copy the chunk dimensions into 'hsize_t' array for creating dataspace) */
6352
    /* (also compute the dimensions which have been shrunk) */
6353
0
    elmts_per_chunk = 1;
6354
0
    for (u = 0; u < space_ndims; u++) {
6355
0
        elmts_per_chunk *= layout->u.chunk.dim[u];
6356
0
        chunk_dim[u]  = layout->u.chunk.dim[u];
6357
0
        shrunk_dim[u] = (space_dim[u] < old_dim[u]);
6358
0
    } /* end for */
6359
6360
    /* Create a dataspace for a chunk & set the extent */
6361
0
    if (NULL == (chunk_space = H5S_create_simple(space_ndims, chunk_dim, NULL)))
6362
0
        HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCREATE, FAIL, "can't create simple dataspace");
6363
6364
    /* Reset hyperslab start array */
6365
    /* (hyperslabs will always start from origin) */
6366
0
    memset(hyper_start, 0, sizeof(hyper_start));
6367
6368
    /* Set up chunked I/O info object, for operations on chunks (in callback)
6369
     * Note that we only need to set scaled once, as the array's address
6370
     * will never change. */
6371
0
    chk_store.chunk.scaled = scaled;
6372
6373
0
    chk_io_info.op_type = H5D_IO_OP_READ;
6374
6375
0
    chk_dset_info.dset     = dset;
6376
0
    chk_dset_info.store    = &chk_store;
6377
0
    chk_dset_info.buf.vp   = NULL;
6378
0
    chk_io_info.dsets_info = &chk_dset_info;
6379
0
    chk_io_info.count      = 1;
6380
6381
    /* Compose chunked index info struct */
6382
0
    idx_info.f      = dset->oloc.file;
6383
0
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
6384
0
    idx_info.layout = &dset->shared->layout;
6385
6386
    /* Initialize the user data for the iteration */
6387
0
    memset(&udata, 0, sizeof udata);
6388
0
    udata.common.layout   = &layout->u.chunk;
6389
0
    udata.common.storage  = sc;
6390
0
    udata.common.scaled   = scaled;
6391
0
    udata.io_info         = &chk_io_info;
6392
0
    udata.dset_info       = &chk_dset_info;
6393
0
    udata.idx_info        = &idx_info;
6394
0
    udata.space_dim       = space_dim;
6395
0
    udata.shrunk_dim      = shrunk_dim;
6396
0
    udata.elmts_per_chunk = elmts_per_chunk;
6397
0
    udata.chunk_space     = chunk_space;
6398
0
    udata.hyper_start     = hyper_start;
6399
0
    udata_init            = true;
6400
6401
    /* Initialize user data for removal */
6402
0
    idx_udata.layout  = &layout->u.chunk;
6403
0
    idx_udata.storage = sc;
6404
6405
    /* Determine if partial edge chunk filters are disabled */
6406
0
    disable_edge_filters = (layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS) &&
6407
0
                           (idx_info.pline->nused > 0);
6408
6409
    /*
6410
     * Determine the chunks which need to be filled or removed
6411
     */
6412
0
    memset(min_mod_chunk_sc, 0, sizeof(min_mod_chunk_sc));
6413
0
    memset(max_mod_chunk_sc, 0, sizeof(max_mod_chunk_sc));
6414
0
    for (op_dim = 0; op_dim < (unsigned)space_ndims; op_dim++) {
6415
        /* Validate this chunk dimension */
6416
0
        if (chunk_dim[op_dim] == 0)
6417
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "chunk size must be > 0, dim = %u ", op_dim);
6418
6419
        /* Calculate the largest offset of chunks that might need to be
6420
         * modified in this dimension */
6421
0
        max_mod_chunk_sc[op_dim] = (old_dim[op_dim] - 1) / chunk_dim[op_dim];
6422
6423
        /* Calculate the largest offset of chunks that might need to be
6424
         * filled in this dimension */
6425
0
        if (0 == space_dim[op_dim])
6426
0
            max_fill_chunk_sc[op_dim] = -1;
6427
0
        else
6428
0
            max_fill_chunk_sc[op_dim] =
6429
0
                (hssize_t)(((MIN(space_dim[op_dim], old_dim[op_dim]) - 1) / chunk_dim[op_dim]));
6430
6431
0
        if (shrunk_dim[op_dim]) {
6432
            /* Calculate the smallest offset of chunks that might need to be
6433
             * modified in this dimension.  Note that this array contains
6434
             * garbage for all dimensions which are not shrunk.  These locations
6435
             * must not be read from! */
6436
0
            min_mod_chunk_sc[op_dim] = space_dim[op_dim] / chunk_dim[op_dim];
6437
6438
            /* Determine if we need to fill chunks in this dimension */
6439
0
            if ((hssize_t)min_mod_chunk_sc[op_dim] == max_fill_chunk_sc[op_dim]) {
6440
0
                fill_dim[op_dim] = true;
6441
6442
                /* If necessary, check if chunks in this dimension that need to
6443
                 * be filled are new partial edge chunks */
6444
0
                if (disable_edge_filters && old_dim[op_dim] >= (min_mod_chunk_sc[op_dim] + 1))
6445
0
                    new_unfilt_dim[op_dim] = true;
6446
0
                else
6447
0
                    new_unfilt_dim[op_dim] = false;
6448
0
            } /* end if */
6449
0
            else {
6450
0
                fill_dim[op_dim]       = false;
6451
0
                new_unfilt_dim[op_dim] = false;
6452
0
            } /* end else */
6453
0
        }     /* end if */
6454
0
        else {
6455
0
            fill_dim[op_dim]       = false;
6456
0
            new_unfilt_dim[op_dim] = false;
6457
0
        } /* end else */
6458
6459
        /* If necessary, calculate the smallest offset of non-previously full
6460
         * chunks in this dimension, so we know these chunks were previously
6461
         * unfiltered */
6462
0
        if (disable_edge_filters)
6463
0
            min_partial_chunk_sc[op_dim] = old_dim[op_dim] / chunk_dim[op_dim];
6464
0
    } /* end for */
6465
6466
    /* Main loop: fill or remove chunks */
6467
0
    for (op_dim = 0; op_dim < (unsigned)space_ndims; op_dim++) {
6468
0
        bool dims_outside_fill[H5O_LAYOUT_NDIMS]; /* Dimensions in chunk offset outside fill dimensions */
6469
0
        int  ndims_outside_fill; /* Number of dimensions in chunk offset outside fill dimensions */
6470
0
        bool carry; /* Flag to indicate that chunk increment carrys to higher dimension (sorta) */
6471
6472
        /* Check if modification along this dimension is really necessary */
6473
0
        if (!shrunk_dim[op_dim])
6474
0
            continue;
6475
0
        else {
6476
0
            assert(max_mod_chunk_sc[op_dim] >= min_mod_chunk_sc[op_dim]);
6477
6478
            /* Reset the chunk offset indices */
6479
0
            memset(scaled, 0, (space_ndims * sizeof(scaled[0])));
6480
0
            scaled[op_dim] = min_mod_chunk_sc[op_dim];
6481
6482
            /* Initialize "dims_outside_fill" array */
6483
0
            ndims_outside_fill = 0;
6484
0
            for (u = 0; u < space_ndims; u++)
6485
0
                if ((hssize_t)scaled[u] > max_fill_chunk_sc[u]) {
6486
0
                    dims_outside_fill[u] = true;
6487
0
                    ndims_outside_fill++;
6488
0
                } /* end if */
6489
0
                else
6490
0
                    dims_outside_fill[u] = false;
6491
0
        } /* end else */
6492
6493
0
        carry = false;
6494
0
        while (!carry) {
6495
0
            int i; /* Local index variable */
6496
6497
0
            udata.common.scaled = scaled;
6498
6499
0
            if (0 == ndims_outside_fill) {
6500
0
                assert(fill_dim[op_dim]);
6501
0
                assert(scaled[op_dim] == min_mod_chunk_sc[op_dim]);
6502
6503
                /* Make sure this is an edge chunk */
6504
0
                assert(H5D__chunk_is_partial_edge_chunk(space_ndims, layout->u.chunk.dim, scaled, space_dim));
6505
6506
                /* Determine if the chunk just became an unfiltered chunk */
6507
0
                if (new_unfilt_dim[op_dim]) {
6508
0
                    new_unfilt_chunk = true;
6509
0
                    for (u = 0; u < space_ndims; u++)
6510
0
                        if (scaled[u] == min_partial_chunk_sc[u]) {
6511
0
                            new_unfilt_chunk = false;
6512
0
                            break;
6513
0
                        } /* end if */
6514
0
                }         /* end if */
6515
6516
                /* Make sure that, if we think this is a new unfiltered chunk,
6517
                 * it was previously not an edge chunk */
6518
0
                assert(!new_unfilt_dim[op_dim] ||
6519
0
                       (!new_unfilt_chunk != !H5D__chunk_is_partial_edge_chunk(
6520
0
                                                 space_ndims, layout->u.chunk.dim, scaled, old_dim)));
6521
0
                assert(!new_unfilt_chunk || new_unfilt_dim[op_dim]);
6522
6523
                /* Fill the unused parts of the chunk */
6524
0
                if (H5D__chunk_prune_fill(&udata, new_unfilt_chunk) < 0)
6525
0
                    HGOTO_ERROR(H5E_DATASET, H5E_WRITEERROR, FAIL, "unable to write fill value");
6526
0
            } /* end if */
6527
0
            else {
6528
0
                H5D_chunk_ud_t chk_udata; /* User data for getting chunk info */
6529
6530
#ifndef NDEBUG
6531
                /* Make sure this chunk is really outside the new dimensions */
6532
                {
6533
                    bool outside_dim = false;
6534
6535
                    for (u = 0; u < space_ndims; u++)
6536
                        if ((scaled[u] * chunk_dim[u]) >= space_dim[u]) {
6537
                            outside_dim = true;
6538
                            break;
6539
                        } /* end if */
6540
                    assert(outside_dim);
6541
                } /* end block */
6542
#endif            /* NDEBUG */
6543
6544
                /* Check if the chunk exists in cache or on disk */
6545
0
                if (H5D__chunk_lookup(dset, scaled, &chk_udata) < 0)
6546
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "error looking up chunk");
6547
6548
                /* Evict the entry from the cache if present, but do not flush
6549
                 * it to disk */
6550
0
                if (UINT_MAX != chk_udata.idx_hint)
6551
0
                    if (H5D__chunk_cache_evict(dset, rdcc->slot[chk_udata.idx_hint], false) < 0)
6552
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTREMOVE, FAIL, "unable to evict chunk");
6553
6554
                /* Remove the chunk from disk, if present */
6555
0
                if (H5_addr_defined(chk_udata.chunk_block.offset)) {
6556
                    /* Update the offset in idx_udata */
6557
0
                    idx_udata.scaled = udata.common.scaled;
6558
6559
                    /* Remove the chunk from disk */
6560
0
                    if ((sc->ops->remove)(&idx_info, &idx_udata) < 0)
6561
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTDELETE, FAIL,
6562
0
                                    "unable to remove chunk entry from index");
6563
0
                } /* end if */
6564
0
            }     /* end else */
6565
6566
            /* Increment indices */
6567
0
            carry = true;
6568
0
            for (i = (int)(space_ndims - 1); i >= 0; --i) {
6569
0
                scaled[i]++;
6570
0
                if (scaled[i] > max_mod_chunk_sc[i]) {
6571
                    /* Left maximum dimensions, "wrap around" and check if this
6572
                     * dimension is no longer outside the fill dimension */
6573
0
                    if ((unsigned)i == op_dim) {
6574
0
                        scaled[i] = min_mod_chunk_sc[i];
6575
0
                        if (dims_outside_fill[i] && fill_dim[i]) {
6576
0
                            dims_outside_fill[i] = false;
6577
0
                            ndims_outside_fill--;
6578
0
                        } /* end if */
6579
0
                    }     /* end if */
6580
0
                    else {
6581
0
                        scaled[i] = 0;
6582
0
                        if (dims_outside_fill[i] && max_fill_chunk_sc[i] >= 0) {
6583
0
                            dims_outside_fill[i] = false;
6584
0
                            ndims_outside_fill--;
6585
0
                        } /* end if */
6586
0
                    }     /* end else */
6587
0
                }         /* end if */
6588
0
                else {
6589
                    /* Check if we just went outside the fill dimension */
6590
0
                    if (!dims_outside_fill[i] && (hssize_t)scaled[i] > max_fill_chunk_sc[i]) {
6591
0
                        dims_outside_fill[i] = true;
6592
0
                        ndims_outside_fill++;
6593
0
                    } /* end if */
6594
6595
                    /* We found the next chunk, so leave the loop */
6596
0
                    carry = false;
6597
0
                    break;
6598
0
                } /* end else */
6599
0
            }     /* end for */
6600
0
        }         /* end while(!carry) */
6601
6602
        /* Adjust max_mod_chunk_sc so we don't modify the same chunk twice.
6603
         * Also check if this dimension started from 0 (and hence removed all
6604
         * of the chunks). */
6605
0
        if (min_mod_chunk_sc[op_dim] == 0)
6606
0
            break;
6607
0
        else
6608
0
            max_mod_chunk_sc[op_dim] = min_mod_chunk_sc[op_dim] - 1;
6609
0
    } /* end for(op_dim=0...) */
6610
6611
    /* Reset any cached chunk info for this dataset */
6612
0
    H5D__chunk_cinfo_cache_reset(&dset->shared->cache.chunk.last);
6613
6614
0
done:
6615
    /* Release resources */
6616
0
    if (chunk_space && H5S_close(chunk_space) < 0)
6617
0
        HDONE_ERROR(H5E_DATASET, H5E_CLOSEERROR, FAIL, "unable to release dataspace");
6618
0
    if (udata_init)
6619
0
        if (udata.fb_info_init && H5D__fill_term(&udata.fb_info) < 0)
6620
0
            HDONE_ERROR(H5E_DATASET, H5E_CANTFREE, FAIL, "Can't release fill buffer info");
6621
6622
0
    FUNC_LEAVE_NOAPI(ret_value)
6623
0
} /* end H5D__chunk_prune_by_extent() */
6624
6625
#ifdef H5_HAVE_PARALLEL
6626
6627
/*-------------------------------------------------------------------------
6628
 * Function:    H5D__chunk_addrmap_cb
6629
 *
6630
 * Purpose:     Callback when obtaining the chunk addresses for all existing chunks
6631
 *
6632
 * Return:    Success:    Non-negative
6633
 *        Failure:    Negative
6634
 *
6635
 *-------------------------------------------------------------------------
6636
 */
6637
static int
6638
H5D__chunk_addrmap_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata)
6639
{
6640
    H5D_chunk_it_ud2_t *udata = (H5D_chunk_it_ud2_t *)_udata;    /* User data for callback */
6641
    unsigned            rank  = udata->common.layout->ndims - 1; /* # of dimensions of dataset */
6642
    hsize_t             chunk_index;
6643
6644
    FUNC_ENTER_PACKAGE_NOERR
6645
6646
    /* Compute the index for this chunk */
6647
    chunk_index = H5VM_array_offset_pre(rank, udata->common.layout->down_chunks, chunk_rec->scaled);
6648
6649
    /* Set it in the userdata to return */
6650
    udata->chunk_addr[chunk_index] = chunk_rec->chunk_addr;
6651
6652
    FUNC_LEAVE_NOAPI(H5_ITER_CONT)
6653
} /* H5D__chunk_addrmap_cb() */
6654
6655
/*-------------------------------------------------------------------------
6656
 * Function:    H5D__chunk_addrmap
6657
 *
6658
 * Purpose:     Obtain the chunk addresses for all existing chunks
6659
 *
6660
 * Return:    Success:    Non-negative on succeed.
6661
 *        Failure:    negative value
6662
 *
6663
 *-------------------------------------------------------------------------
6664
 */
6665
herr_t
6666
H5D__chunk_addrmap(const H5D_t *dset, haddr_t chunk_addr[])
6667
{
6668
    H5D_chk_idx_info_t   idx_info; /* Chunked index info */
6669
    H5D_chunk_it_ud2_t   udata;    /* User data for iteration callback */
6670
    H5O_storage_chunk_t *sc;
6671
    herr_t               ret_value = SUCCEED; /* Return value */
6672
6673
    FUNC_ENTER_PACKAGE
6674
6675
    assert(dset);
6676
    assert(dset->shared);
6677
    sc = &(dset->shared->layout.storage.u.chunk);
6678
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
6679
    assert(chunk_addr);
6680
6681
    /* Set up user data for B-tree callback */
6682
    memset(&udata, 0, sizeof(udata));
6683
    udata.common.layout  = &dset->shared->layout.u.chunk;
6684
    udata.common.storage = sc;
6685
    udata.chunk_addr     = chunk_addr;
6686
6687
    /* Compose chunked index info struct */
6688
    idx_info.f      = dset->oloc.file;
6689
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
6690
    idx_info.layout = &dset->shared->layout;
6691
6692
    /* Iterate over chunks to build mapping of chunk addresses */
6693
    if ((sc->ops->iterate)(&idx_info, H5D__chunk_addrmap_cb, &udata) < 0)
6694
        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL,
6695
                    "unable to iterate over chunk index to build address map");
6696
6697
done:
6698
    FUNC_LEAVE_NOAPI(ret_value)
6699
} /* end H5D__chunk_addrmap() */
6700
#endif /* H5_HAVE_PARALLEL */
6701
6702
/*-------------------------------------------------------------------------
6703
 * Function:    H5D__chunk_delete
6704
 *
6705
 * Purpose:    Delete raw data storage for entire dataset (i.e. all chunks)
6706
 *
6707
 * Return:    Success:    Non-negative
6708
 *        Failure:    negative
6709
 *
6710
 *-------------------------------------------------------------------------
6711
 */
6712
herr_t
6713
H5D__chunk_delete(H5F_t *f, H5O_t *oh, H5O_layout_t *layout)
6714
0
{
6715
0
    H5D_chk_idx_info_t idx_info;            /* Chunked index info */
6716
0
    H5O_pline_t        pline;               /* I/O pipeline message */
6717
0
    bool               pline_read = false;  /* Whether the I/O pipeline message was read from the file */
6718
0
    htri_t             exists;              /* Flag if header message of interest exists */
6719
0
    herr_t             ret_value = SUCCEED; /* Return value */
6720
6721
0
    FUNC_ENTER_PACKAGE
6722
6723
    /* Sanity check */
6724
0
    assert(f);
6725
0
    assert(oh);
6726
0
    assert(layout);
6727
0
    H5D_CHUNK_STORAGE_INDEX_CHK(&layout->storage.u.chunk);
6728
6729
    /* Check for I/O pipeline message */
6730
0
    if ((exists = H5O_msg_exists_oh(oh, H5O_PLINE_ID)) < 0)
6731
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to check for object header message");
6732
0
    else if (exists) {
6733
0
        if (NULL == H5O_msg_read_oh(f, oh, H5O_PLINE_ID, &pline))
6734
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't get I/O pipeline message");
6735
0
        pline_read = true;
6736
0
    } /* end else if */
6737
0
    else
6738
0
        memset(&pline, 0, sizeof(pline));
6739
6740
    /* Compose chunked index info struct */
6741
0
    idx_info.f      = f;
6742
0
    idx_info.pline  = &pline;
6743
0
    idx_info.layout = layout;
6744
6745
    /* Delete the chunked storage information in the file */
6746
0
    if ((layout->storage.u.chunk.ops->idx_delete)(&idx_info) < 0)
6747
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTDELETE, FAIL, "unable to delete chunk index");
6748
6749
0
done:
6750
    /* Clean up any messages read in */
6751
0
    if (pline_read)
6752
0
        if (H5O_msg_reset(H5O_PLINE_ID, &pline) < 0)
6753
0
            HDONE_ERROR(H5E_DATASET, H5E_CANTRESET, FAIL, "unable to reset I/O pipeline message");
6754
6755
0
    FUNC_LEAVE_NOAPI(ret_value)
6756
0
} /* end H5D__chunk_delete() */
6757
6758
/*-------------------------------------------------------------------------
6759
 * Function:    H5D__chunk_update_cache
6760
 *
6761
 * Purpose:    Update any cached chunks index values after the dataspace
6762
 *              size has changed
6763
 *
6764
 * Return:    Success:    Non-negative
6765
 *        Failure:    negative
6766
 *
6767
 *-------------------------------------------------------------------------
6768
 */
6769
herr_t
6770
H5D__chunk_update_cache(H5D_t *dset)
6771
0
{
6772
0
    H5D_rdcc_t     *rdcc = &(dset->shared->cache.chunk); /*raw data chunk cache */
6773
0
    H5D_rdcc_ent_t *ent, *next;                          /*cache entry  */
6774
0
    H5D_rdcc_ent_t  tmp_head;                            /* Sentinel entry for temporary entry list */
6775
0
    H5D_rdcc_ent_t *tmp_tail;                            /* Tail pointer for temporary entry list */
6776
0
    herr_t          ret_value = SUCCEED;                 /* Return value */
6777
6778
0
    FUNC_ENTER_PACKAGE
6779
6780
    /* Check args */
6781
0
    assert(dset && H5D_CHUNKED == dset->shared->layout.type);
6782
0
    assert(dset->shared->layout.u.chunk.ndims > 0 && dset->shared->layout.u.chunk.ndims <= H5O_LAYOUT_NDIMS);
6783
6784
    /* Check the rank */
6785
0
    assert((dset->shared->layout.u.chunk.ndims - 1) > 1);
6786
6787
    /* Add temporary entry list to rdcc */
6788
0
    (void)memset(&tmp_head, 0, sizeof(tmp_head));
6789
0
    rdcc->tmp_head = &tmp_head;
6790
0
    tmp_tail       = &tmp_head;
6791
6792
    /* Recompute the index for each cached chunk that is in a dataset */
6793
0
    for (ent = rdcc->head; ent; ent = next) {
6794
0
        unsigned old_idx; /* Previous index number    */
6795
6796
        /* Get the pointer to the next cache entry */
6797
0
        next = ent->next;
6798
6799
        /* Compute the index for the chunk entry */
6800
0
        old_idx  = ent->idx; /* Save for later */
6801
0
        ent->idx = H5D__chunk_hash_val(dset->shared, ent->scaled);
6802
6803
0
        if (old_idx != ent->idx) {
6804
0
            H5D_rdcc_ent_t *old_ent; /* Old cache entry  */
6805
6806
            /* Check if there is already a chunk at this chunk's new location */
6807
0
            old_ent = rdcc->slot[ent->idx];
6808
0
            if (old_ent != NULL) {
6809
0
                assert(old_ent->locked == false);
6810
0
                assert(old_ent->deleted == false);
6811
6812
                /* Insert the old entry into the temporary list, but do not
6813
                 * evict (yet).  Make sure we do not make any calls to the index
6814
                 * until all chunks have updated indices! */
6815
0
                assert(!old_ent->tmp_next);
6816
0
                assert(!old_ent->tmp_prev);
6817
0
                tmp_tail->tmp_next = old_ent;
6818
0
                old_ent->tmp_prev  = tmp_tail;
6819
0
                tmp_tail           = old_ent;
6820
0
            } /* end if */
6821
6822
            /* Insert this chunk into correct location in hash table */
6823
0
            rdcc->slot[ent->idx] = ent;
6824
6825
            /* If this chunk was previously on the temporary list and therefore
6826
             * not in the hash table, remove it from the temporary list.
6827
             * Otherwise clear the old hash table slot. */
6828
0
            if (ent->tmp_prev) {
6829
0
                assert(tmp_head.tmp_next);
6830
0
                assert(tmp_tail != &tmp_head);
6831
0
                ent->tmp_prev->tmp_next = ent->tmp_next;
6832
0
                if (ent->tmp_next) {
6833
0
                    ent->tmp_next->tmp_prev = ent->tmp_prev;
6834
0
                    ent->tmp_next           = NULL;
6835
0
                } /* end if */
6836
0
                else {
6837
0
                    assert(tmp_tail == ent);
6838
0
                    tmp_tail = ent->tmp_prev;
6839
0
                } /* end else */
6840
0
                ent->tmp_prev = NULL;
6841
0
            } /* end if */
6842
0
            else
6843
0
                rdcc->slot[old_idx] = NULL;
6844
0
        } /* end if */
6845
0
    }     /* end for */
6846
6847
    /* tmp_tail is no longer needed, and will be invalidated by
6848
     * H5D_chunk_cache_evict anyways. */
6849
0
    tmp_tail = NULL;
6850
6851
    /* Evict chunks that are still on the temporary list */
6852
0
    while (tmp_head.tmp_next) {
6853
0
        ent = tmp_head.tmp_next;
6854
6855
        /* Remove the old entry from the cache */
6856
0
        if (H5D__chunk_cache_evict(dset, ent, true) < 0)
6857
0
            HGOTO_ERROR(H5E_IO, H5E_CANTFLUSH, FAIL, "unable to flush one or more raw data chunks");
6858
0
    } /* end while */
6859
6860
0
done:
6861
    /* Remove temporary list from rdcc */
6862
0
    rdcc->tmp_head = NULL;
6863
6864
0
    FUNC_LEAVE_NOAPI(ret_value)
6865
0
} /* end H5D__chunk_update_cache() */
6866
6867
/*-------------------------------------------------------------------------
6868
 * Function:    H5D__chunk_copy_cb
6869
 *
6870
 * Purpose:     Copy chunked raw data from source file and insert to the
6871
 *              index in the destination file
6872
 *
6873
 * Return:      Non-negative on success/Negative on failure
6874
 *
6875
 *-------------------------------------------------------------------------
6876
 */
6877
static int
6878
H5D__chunk_copy_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata)
6879
0
{
6880
0
    H5D_chunk_it_ud3_t *udata = (H5D_chunk_it_ud3_t *)_udata; /* User data for callback */
6881
0
    H5D_chunk_ud_t      udata_dst;                            /* User data about new destination chunk */
6882
0
    bool                is_vlen     = false;                  /* Whether datatype is variable-length */
6883
0
    bool                fix_ref     = false; /* Whether to fix up references in the dest. file */
6884
0
    bool                need_insert = false; /* Whether the chunk needs to be inserted into the index */
6885
6886
    /* General information about chunk copy */
6887
0
    const H5T_t       *dt_src = udata->dt_src;
6888
0
    void              *bkg    = udata->bkg;   /* Background buffer for datatype conversion */
6889
0
    const H5O_pline_t *pline  = udata->pline; /* I/O pipeline for applying filters */
6890
6891
    /* needed for compressed variable length data */
6892
0
    bool     must_filter = false;      /* Whether chunk must be filtered during copy */
6893
0
    size_t   nbytes;                   /* Size of chunk in file (in bytes) */
6894
0
    H5Z_cb_t filter_cb;                /* Filter failure callback struct */
6895
0
    int      ret_value = H5_ITER_CONT; /* Return value */
6896
6897
0
    FUNC_ENTER_PACKAGE
6898
6899
    /* Get 'size_t' local value for number of bytes in chunk */
6900
0
    H5_CHECKED_ASSIGN(nbytes, size_t, chunk_rec->nbytes, hsize_t);
6901
6902
    /* Initialize the filter callback struct */
6903
0
    filter_cb.op_data = NULL;
6904
0
    filter_cb.func    = NULL; /* no callback function when failed */
6905
6906
    /* Check for filtered chunks */
6907
    /* Check for an edge chunk that is not filtered */
6908
0
    if (pline && pline->nused) {
6909
0
        must_filter = true;
6910
0
        if ((udata->common.layout->flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS) &&
6911
0
            H5D__chunk_is_partial_edge_chunk(udata->dset_ndims, udata->common.layout->dim, chunk_rec->scaled,
6912
0
                                             udata->dset_dims))
6913
0
            must_filter = false;
6914
0
    }
6915
6916
    /* If the chunk on disk is unfiltered, verify the index returned the correct size for the chunk */
6917
0
    if (H5_UNLIKELY((nbytes != udata->src_chunk_size) && H5_addr_defined(chunk_rec->chunk_addr) &&
6918
0
                    !must_filter))
6919
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, H5_ITER_ERROR,
6920
0
                    "incorrect chunk size returned from index for unfiltered chunk");
6921
6922
    /* Check parameter for type conversion */
6923
0
    if (udata->do_convert) {
6924
0
        if (H5T_detect_class(dt_src, H5T_VLEN, false) > 0)
6925
0
            is_vlen = true;
6926
0
        else if ((H5T_get_class(dt_src, false) == H5T_REFERENCE) &&
6927
0
                 (udata->file_src != udata->idx_info_dst->f))
6928
0
            fix_ref = true;
6929
0
        else
6930
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTCOPY, H5_ITER_ERROR, "unable to copy dataset elements");
6931
0
    } /* end if */
6932
6933
    /* Resize the buf if it is too small to hold the data */
6934
0
    if (nbytes > udata->buf_size) {
6935
0
        void *new_buf; /* New buffer for data */
6936
6937
        /* Re-allocate memory for copying the chunk */
6938
0
        if (NULL == (new_buf = H5MM_realloc(udata->buf, nbytes)))
6939
0
            HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, H5_ITER_ERROR,
6940
0
                        "memory allocation failed for raw data chunk");
6941
0
        udata->buf      = new_buf;
6942
0
        udata->buf_size = nbytes;
6943
6944
        /* No need to reallocate bkg since it should always be big enough */
6945
0
    } /* end if */
6946
6947
0
    if (udata->chunk_in_cache && udata->chunk) {
6948
0
        assert(!H5_addr_defined(chunk_rec->chunk_addr));
6949
0
        H5MM_memcpy(udata->buf, udata->chunk, nbytes);
6950
0
        udata->chunk = NULL;
6951
0
    }
6952
0
    else {
6953
0
        H5D_rdcc_ent_t *ent = NULL; /* Cache entry */
6954
0
        unsigned        idx;        /* Index of chunk in cache, if present */
6955
0
        unsigned        u;          /* Counter */
6956
0
        H5D_shared_t   *shared_fo = (H5D_shared_t *)udata->cpy_info->shared_fo;
6957
6958
        /* See if the written chunk is in the chunk cache */
6959
0
        if (shared_fo && shared_fo->cache.chunk.nslots > 0) {
6960
            /* Determine the chunk's location in the hash table */
6961
0
            idx = H5D__chunk_hash_val(shared_fo, chunk_rec->scaled);
6962
6963
            /* Get the chunk cache entry for that location */
6964
0
            ent = shared_fo->cache.chunk.slot[idx];
6965
0
            if (ent) {
6966
                /* Speculatively set the 'found' flag */
6967
0
                udata->chunk_in_cache = true;
6968
6969
                /* Verify that the cache entry is the correct chunk */
6970
0
                for (u = 0; u < shared_fo->ndims; u++)
6971
0
                    if (chunk_rec->scaled[u] != ent->scaled[u]) {
6972
0
                        udata->chunk_in_cache = false;
6973
0
                        break;
6974
0
                    } /* end if */
6975
0
            }         /* end if */
6976
0
        }             /* end if */
6977
6978
0
        if (udata->chunk_in_cache) {
6979
6980
0
            if (NULL == ent)
6981
0
                HGOTO_ERROR(H5E_IO, H5E_BADVALUE, H5_ITER_ERROR, "NULL chunk entry pointer");
6982
6983
0
            assert(H5_addr_defined(chunk_rec->chunk_addr));
6984
0
            assert(H5_addr_defined(ent->chunk_block.offset));
6985
6986
0
            H5_CHECKED_ASSIGN(nbytes, size_t, shared_fo->layout.u.chunk.size, hsize_t);
6987
0
            H5MM_memcpy(udata->buf, ent->chunk, nbytes);
6988
0
        }
6989
0
        else {
6990
            /* read chunk data from the source file */
6991
0
            if (H5F_block_read(udata->file_src, H5FD_MEM_DRAW, chunk_rec->chunk_addr, nbytes, udata->buf) < 0)
6992
0
                HGOTO_ERROR(H5E_IO, H5E_READERROR, H5_ITER_ERROR, "unable to read raw data chunk");
6993
0
        }
6994
0
    }
6995
6996
    /* Need to uncompress filtered variable-length & reference data elements that are not found in chunk cache
6997
     */
6998
0
    if (must_filter && (is_vlen || fix_ref) && !udata->chunk_in_cache) {
6999
0
        unsigned filter_mask = chunk_rec->filter_mask;
7000
7001
        /* Execute filter pipeline */
7002
0
        if (H5Z_pipeline(pline, H5Z_FLAG_REVERSE, &filter_mask, H5Z_NO_EDC, filter_cb, &nbytes,
7003
0
                         &udata->buf_size, &udata->buf) < 0)
7004
0
            HGOTO_ERROR(H5E_PLINE, H5E_CANTFILTER, H5_ITER_ERROR, "data pipeline read failed");
7005
7006
        /* Make sure the chunk is the correct size after being unfiltered */
7007
0
        if (H5_UNLIKELY(nbytes != udata->src_chunk_size))
7008
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, H5_ITER_ERROR,
7009
0
                        "chunk size is incorrect after being unfiltered");
7010
0
    } /* end if */
7011
7012
    /* Perform datatype conversion, if necessary */
7013
0
    if (is_vlen) {
7014
0
        H5T_path_t  *tpath_src_mem    = udata->tpath_src_mem;
7015
0
        H5T_path_t  *tpath_mem_dst    = udata->tpath_mem_dst;
7016
0
        const H5T_t *dt_dst           = udata->dt_dst;
7017
0
        const H5T_t *dt_mem           = udata->dt_mem;
7018
0
        H5S_t       *buf_space        = udata->buf_space;
7019
0
        void        *reclaim_buf      = udata->reclaim_buf;
7020
0
        size_t       reclaim_buf_size = udata->reclaim_buf_size;
7021
7022
        /* Convert from source file to memory */
7023
0
        if (H5T_convert(tpath_src_mem, dt_src, dt_mem, udata->nelmts, (size_t)0, (size_t)0, udata->buf, bkg) <
7024
0
            0)
7025
0
            HGOTO_ERROR(H5E_DATATYPE, H5E_CANTCONVERT, H5_ITER_ERROR, "datatype conversion failed");
7026
7027
        /* Copy into another buffer, to reclaim memory later */
7028
0
        H5MM_memcpy(reclaim_buf, udata->buf, reclaim_buf_size);
7029
7030
        /* Set background buffer to all zeros */
7031
0
        memset(bkg, 0, udata->bkg_size);
7032
7033
        /* Convert from memory to destination file */
7034
0
        if (H5T_convert(tpath_mem_dst, dt_mem, dt_dst, udata->nelmts, (size_t)0, (size_t)0, udata->buf, bkg) <
7035
0
            0)
7036
0
            HGOTO_ERROR(H5E_DATATYPE, H5E_CANTCONVERT, H5_ITER_ERROR, "datatype conversion failed");
7037
7038
        /* Reclaim space from variable length data */
7039
0
        if (H5T_reclaim(dt_mem, buf_space, reclaim_buf) < 0)
7040
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTFREE, H5_ITER_ERROR, "unable to reclaim variable-length data");
7041
0
    } /* end if */
7042
0
    else if (fix_ref) {
7043
        /* Check for expanding references */
7044
        /* (background buffer has already been zeroed out, if not expanding) */
7045
0
        if (udata->cpy_info->expand_ref) {
7046
            /* Copy the reference elements */
7047
0
            if (H5O_copy_expand_ref(udata->file_src, dt_src, udata->buf, nbytes, udata->idx_info_dst->f, bkg,
7048
0
                                    udata->cpy_info) < 0)
7049
0
                HGOTO_ERROR(H5E_DATASET, H5E_CANTCOPY, H5_ITER_ERROR, "unable to copy reference attribute");
7050
0
        } /* end if */
7051
7052
        /* After fix ref, copy the new reference elements to the buffer to write out */
7053
0
        assert(nbytes <= udata->bkg_size);
7054
0
        H5MM_memcpy(udata->buf, bkg, nbytes);
7055
0
    } /* end if */
7056
7057
    /* Set up destination chunk callback information for insertion */
7058
0
    udata_dst.common.layout      = &udata->idx_info_dst->layout->u.chunk;
7059
0
    udata_dst.common.storage     = &udata->idx_info_dst->layout->storage.u.chunk;
7060
0
    udata_dst.common.scaled      = chunk_rec->scaled;
7061
0
    udata_dst.chunk_block.offset = HADDR_UNDEF;
7062
0
    udata_dst.chunk_block.length = chunk_rec->nbytes;
7063
0
    udata_dst.filter_mask        = chunk_rec->filter_mask;
7064
7065
    /* Need to compress variable-length or reference data elements or a chunk found in cache before writing to
7066
     * file */
7067
0
    if (must_filter && (is_vlen || fix_ref || udata->chunk_in_cache)) {
7068
0
        if (H5Z_pipeline(pline, 0, &(udata_dst.filter_mask), H5Z_NO_EDC, filter_cb, &nbytes, &udata->buf_size,
7069
0
                         &udata->buf) < 0)
7070
0
            HGOTO_ERROR(H5E_PLINE, H5E_CANTFILTER, H5_ITER_ERROR, "output pipeline failed");
7071
7072
0
        H5_CHECKED_ASSIGN(udata_dst.chunk_block.length, hsize_t, nbytes, size_t);
7073
0
    } /* end if */
7074
7075
0
    udata->chunk_in_cache = false;
7076
7077
0
    udata_dst.chunk_idx =
7078
0
        H5VM_array_offset_pre(udata_dst.common.layout->ndims - 1, udata_dst.common.layout->max_down_chunks,
7079
0
                              udata_dst.common.scaled);
7080
7081
    /* Allocate chunk in the file */
7082
0
    if (H5D__chunk_file_alloc(udata->idx_info_dst, NULL, &udata_dst.chunk_block, &need_insert,
7083
0
                              udata_dst.common.scaled) < 0)
7084
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL, "unable to insert/resize chunk on chunk level");
7085
7086
    /* Write chunk data to destination file */
7087
0
    assert(H5_addr_defined(udata_dst.chunk_block.offset));
7088
0
    if (H5F_block_write(udata->idx_info_dst->f, H5FD_MEM_DRAW, udata_dst.chunk_block.offset, nbytes,
7089
0
                        udata->buf) < 0)
7090
0
        HGOTO_ERROR(H5E_DATASET, H5E_WRITEERROR, H5_ITER_ERROR, "unable to write raw data to file");
7091
7092
    /* Set metadata tag in API context */
7093
0
    H5_BEGIN_TAG(H5AC__COPIED_TAG)
7094
7095
    /* Insert chunk record into index */
7096
0
    if (need_insert && udata->idx_info_dst->layout->storage.u.chunk.ops->insert)
7097
0
        if ((udata->idx_info_dst->layout->storage.u.chunk.ops->insert)(udata->idx_info_dst, &udata_dst,
7098
0
                                                                       NULL) < 0)
7099
0
            HGOTO_ERROR_TAG(H5E_DATASET, H5E_CANTINSERT, H5_ITER_ERROR,
7100
0
                            "unable to insert chunk addr into index");
7101
7102
    /* Reset metadata tag in API context */
7103
0
    H5_END_TAG
7104
7105
0
done:
7106
0
    FUNC_LEAVE_NOAPI(ret_value)
7107
0
} /* end H5D__chunk_copy_cb() */
7108
7109
/*-------------------------------------------------------------------------
7110
 * Function:    H5D__chunk_copy
7111
 *
7112
 * Purpose:    Copy chunked storage from SRC file to DST file.
7113
 *
7114
 * Return:    Success:    Non-negative
7115
 *        Failure:    negative
7116
 *
7117
 *-------------------------------------------------------------------------
7118
 */
7119
herr_t
7120
H5D__chunk_copy(H5F_t *f_src, H5O_layout_t *layout_src, H5F_t *f_dst, H5O_layout_t *layout_dst,
7121
                const H5S_extent_t *ds_extent_src, H5T_t *dt_src, const H5O_pline_t *pline_src,
7122
                H5O_copy_t *cpy_info)
7123
0
{
7124
0
    H5D_chunk_it_ud3_t udata = {0};                 /* User data for iteration callback */
7125
0
    H5D_chk_idx_info_t idx_info_dst;                /* Dest. chunked index info */
7126
0
    H5D_chk_idx_info_t idx_info_src;                /* Source chunked index info */
7127
0
    int                sndims;                      /* Rank of dataspace */
7128
0
    hsize_t            curr_dims[H5O_LAYOUT_NDIMS]; /* Curr. size of dataset dimensions */
7129
0
    hsize_t            max_dims[H5O_LAYOUT_NDIMS];  /* Curr. size of dataset dimensions */
7130
0
    H5O_pline_t        _pline;                      /* Temporary pipeline info */
7131
0
    const H5O_pline_t *pline;                       /* Pointer to pipeline info to use */
7132
0
    H5T_path_t        *tpath_src_mem = NULL;        /* Source datatype conversion path */
7133
0
    H5T_path_t        *tpath_mem_dst = NULL;        /* Memory datatype conversion path */
7134
0
    H5T_t             *dt_dst        = NULL;        /* Destination datatype */
7135
0
    H5T_t             *dt_mem        = NULL;        /* Memory datatype */
7136
0
    size_t             buf_size;                    /* Size of copy buffer */
7137
0
    size_t             bkg_size;                    /* Size of background buffer */
7138
0
    size_t             reclaim_buf_size;            /* Size of reclaim buffer */
7139
0
    void              *reclaim_buf     = NULL;      /* Buffer for reclaiming data */
7140
0
    H5S_t             *buf_space       = NULL;      /* Dataspace describing buffer */
7141
0
    size_t             nelmts          = 0;         /* Number of elements in buffer */
7142
0
    bool               do_convert      = false;     /* Indicate that type conversions should be performed */
7143
0
    bool               copy_setup_done = false;     /* Indicate that 'copy setup' is done */
7144
0
    herr_t             ret_value       = SUCCEED;   /* Return value */
7145
7146
0
    FUNC_ENTER_PACKAGE
7147
7148
    /* Check args */
7149
0
    assert(f_src);
7150
0
    assert(layout_src);
7151
0
    H5D_CHUNK_STORAGE_INDEX_CHK(&layout_src->storage.u.chunk);
7152
0
    assert(f_dst);
7153
0
    assert(layout_dst);
7154
0
    H5D_CHUNK_STORAGE_INDEX_CHK(&layout_dst->storage.u.chunk);
7155
0
    assert(ds_extent_src);
7156
0
    assert(dt_src);
7157
7158
    /* Initialize the temporary pipeline info */
7159
0
    if (NULL == pline_src) {
7160
0
        memset(&_pline, 0, sizeof(_pline));
7161
0
        pline = &_pline;
7162
0
    } /* end if */
7163
0
    else
7164
0
        pline = pline_src;
7165
7166
    /* Layout is not created in the destination file, reset index address */
7167
0
    if (H5D_chunk_idx_reset(&layout_dst->storage.u.chunk, true) < 0)
7168
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to reset chunked storage index in dest");
7169
7170
    /* Initialize layout information */
7171
0
    {
7172
0
        unsigned ndims; /* Rank of dataspace */
7173
7174
        /* Get the dim info for dataset */
7175
0
        if ((sndims = H5S_extent_get_dims(ds_extent_src, curr_dims, max_dims)) < 0)
7176
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't get dataspace dimensions");
7177
0
        H5_CHECKED_ASSIGN(ndims, unsigned, sndims, int);
7178
7179
        /* Set the source layout chunk information */
7180
0
        if (H5D__chunk_set_info_real(&layout_src->u.chunk, ndims, curr_dims, max_dims) < 0)
7181
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTSET, FAIL, "can't set source layout's chunk info");
7182
7183
        /* Set the destination layout chunk information */
7184
0
        if (H5D__chunk_set_info_real(&layout_dst->u.chunk, ndims, curr_dims, max_dims) < 0)
7185
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTSET, FAIL, "can't set destination layout's chunk info");
7186
0
    } /* end block */
7187
7188
    /* Compose source & dest chunked index info structs */
7189
0
    idx_info_src.f      = f_src;
7190
0
    idx_info_src.pline  = pline;
7191
0
    idx_info_src.layout = layout_src;
7192
7193
0
    idx_info_dst.f      = f_dst;
7194
0
    idx_info_dst.pline  = pline; /* Use same I/O filter pipeline for dest. */
7195
0
    idx_info_dst.layout = layout_dst;
7196
7197
    /* Call the index-specific "copy setup" routine */
7198
0
    if ((layout_src->storage.u.chunk.ops->copy_setup)(&idx_info_src, &idx_info_dst) < 0)
7199
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL,
7200
0
                    "unable to set up index-specific chunk copying information");
7201
0
    copy_setup_done = true;
7202
7203
    /* If there's a VLEN source datatype, set up type conversion information */
7204
0
    if (H5T_detect_class(dt_src, H5T_VLEN, false) > 0) {
7205
0
        size_t   mem_dt_size;     /* Memory datatype size */
7206
0
        size_t   tmp_dt_size;     /* Temp. datatype size */
7207
0
        size_t   max_dt_size;     /* Max datatype size */
7208
0
        size_t   max_dst_dt_size; /* Max destination atatype size */
7209
0
        hsize_t  buf_dim;         /* Dimension for buffer */
7210
0
        uint64_t nelmts_64;       /* nelmts as a uint64_t */
7211
0
        unsigned u;
7212
7213
        /* create a memory copy of the variable-length datatype */
7214
0
        if (NULL == (dt_mem = H5T_copy(dt_src, H5T_COPY_TRANSIENT)))
7215
0
            HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, FAIL, "unable to copy");
7216
7217
        /* create variable-length datatype at the destination file */
7218
0
        if (NULL == (dt_dst = H5T_copy(dt_src, H5T_COPY_TRANSIENT)))
7219
0
            HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, FAIL, "unable to copy");
7220
0
        if (H5T_set_loc(dt_dst, H5F_VOL_OBJ(f_dst), H5T_LOC_DISK) < 0) {
7221
0
            (void)H5T_close_real(dt_dst);
7222
0
            HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, FAIL, "cannot mark datatype on disk");
7223
0
        } /* end if */
7224
7225
        /* Set up the conversion functions */
7226
0
        if (NULL == (tpath_src_mem = H5T_path_find(dt_src, dt_mem)))
7227
0
            HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, FAIL, "unable to convert between src and mem datatypes");
7228
0
        if (NULL == (tpath_mem_dst = H5T_path_find(dt_mem, dt_dst)))
7229
0
            HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, FAIL, "unable to convert between mem and dst datatypes");
7230
7231
        /* Determine largest datatype size */
7232
0
        if (0 == (max_dt_size = H5T_get_size(dt_src)))
7233
0
            HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, FAIL, "unable to determine datatype size");
7234
0
        if (0 == (mem_dt_size = max_dst_dt_size = H5T_get_size(dt_mem)))
7235
0
            HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, FAIL, "unable to determine datatype size");
7236
0
        max_dt_size = MAX(max_dt_size, mem_dt_size);
7237
0
        if (0 == (tmp_dt_size = H5T_get_size(dt_dst)))
7238
0
            HGOTO_ERROR(H5E_DATATYPE, H5E_CANTINIT, FAIL, "unable to determine datatype size");
7239
0
        max_dt_size     = MAX(max_dt_size, tmp_dt_size);
7240
0
        max_dst_dt_size = MAX(max_dst_dt_size, tmp_dt_size);
7241
7242
        /* Compute the number of elements per chunk */
7243
0
        nelmts_64 = 1;
7244
0
        for (u = 0; u < (layout_src->u.chunk.ndims - 1); u++)
7245
0
            nelmts_64 *= layout_src->u.chunk.dim[u];
7246
0
        nelmts = (size_t)nelmts_64;
7247
0
        if ((uint64_t)nelmts != nelmts_64)
7248
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, FAIL, "number of chunk elements too big to fit in size_t");
7249
7250
        /* Create the space and set the initial extent */
7251
0
        buf_dim = nelmts;
7252
0
        if (NULL == (buf_space = H5S_create_simple((unsigned)1, &buf_dim, NULL)))
7253
0
            HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCREATE, FAIL, "can't create simple dataspace");
7254
7255
        /* Set initial buffer sizes */
7256
0
        buf_size         = nelmts * max_dt_size;
7257
0
        bkg_size         = nelmts * max_dst_dt_size;
7258
0
        reclaim_buf_size = nelmts * mem_dt_size;
7259
7260
        /* Allocate memory for reclaim buf */
7261
0
        if (NULL == (reclaim_buf = H5MM_malloc(reclaim_buf_size)))
7262
0
            HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed for raw data chunk");
7263
7264
        /* Indicate that type conversion should be performed */
7265
0
        do_convert = true;
7266
0
    } /* end if */
7267
0
    else {
7268
0
        if (H5T_get_class(dt_src, false) == H5T_REFERENCE) {
7269
            /* Indicate that type conversion should be performed */
7270
0
            do_convert = true;
7271
0
        } /* end if */
7272
7273
0
        H5_CHECKED_ASSIGN(buf_size, size_t, layout_src->u.chunk.size, hsize_t);
7274
0
        bkg_size         = buf_size;
7275
0
        reclaim_buf_size = 0;
7276
0
    } /* end else */
7277
7278
    /* Set up conversion buffer, if appropriate */
7279
0
    if (do_convert) {
7280
        /* Allocate background memory for converting the chunk */
7281
0
        if (NULL == (udata.bkg = H5MM_malloc(bkg_size)))
7282
0
            HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed for raw data chunk");
7283
7284
        /* Check for reference datatype and no expanding references & clear background buffer */
7285
0
        if (!cpy_info->expand_ref && ((H5T_get_class(dt_src, false) == H5T_REFERENCE) && (f_src != f_dst)))
7286
            /* Reset value to zero */
7287
0
            memset(udata.bkg, 0, bkg_size);
7288
0
    } /* end if */
7289
7290
    /* Allocate memory for copying the chunk */
7291
0
    if (NULL == (udata.buf = H5MM_malloc(buf_size)))
7292
0
        HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed for raw data chunk");
7293
7294
    /* Initialize the callback structure for the source */
7295
0
    udata.common.layout    = &layout_src->u.chunk;
7296
0
    udata.common.storage   = &layout_src->storage.u.chunk;
7297
0
    udata.file_src         = f_src;
7298
0
    udata.idx_info_dst     = &idx_info_dst;
7299
0
    udata.buf_size         = buf_size;
7300
0
    udata.bkg_size         = bkg_size;
7301
0
    udata.dt_src           = dt_src;
7302
0
    udata.dt_dst           = dt_dst;
7303
0
    udata.dt_mem           = dt_mem;
7304
0
    udata.do_convert       = do_convert;
7305
0
    udata.tpath_src_mem    = tpath_src_mem;
7306
0
    udata.tpath_mem_dst    = tpath_mem_dst;
7307
0
    udata.reclaim_buf      = reclaim_buf;
7308
0
    udata.reclaim_buf_size = reclaim_buf_size;
7309
0
    udata.buf_space        = buf_space;
7310
0
    udata.nelmts           = nelmts;
7311
0
    udata.pline            = pline;
7312
0
    udata.dset_ndims       = (unsigned)sndims;
7313
0
    udata.dset_dims        = curr_dims;
7314
0
    udata.cpy_info         = cpy_info;
7315
0
    udata.chunk_in_cache   = false;
7316
0
    udata.chunk            = NULL;
7317
0
    H5_CHECKED_ASSIGN(udata.src_chunk_size, size_t, layout_src->u.chunk.size, hsize_t);
7318
7319
    /* Iterate over chunks to copy data */
7320
0
    if ((layout_src->storage.u.chunk.ops->iterate)(&idx_info_src, H5D__chunk_copy_cb, &udata) < 0)
7321
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADITER, FAIL, "unable to iterate over chunk index to copy data");
7322
7323
    /* Iterate over the chunk cache to copy data for chunks with undefined address */
7324
0
    if (udata.cpy_info->shared_fo) {
7325
0
        H5D_rdcc_ent_t *ent, *next;
7326
0
        H5D_chunk_rec_t chunk_rec;
7327
0
        H5D_shared_t   *shared_fo = (H5D_shared_t *)udata.cpy_info->shared_fo;
7328
7329
0
        chunk_rec.nbytes      = layout_src->u.chunk.size;
7330
0
        chunk_rec.filter_mask = 0;
7331
0
        chunk_rec.chunk_addr  = HADDR_UNDEF;
7332
7333
0
        for (ent = shared_fo->cache.chunk.head; ent; ent = next) {
7334
0
            if (!H5_addr_defined(ent->chunk_block.offset)) {
7335
0
                H5MM_memcpy(chunk_rec.scaled, ent->scaled, sizeof(chunk_rec.scaled));
7336
0
                udata.chunk          = ent->chunk;
7337
0
                udata.chunk_in_cache = true;
7338
0
                if (H5D__chunk_copy_cb(&chunk_rec, &udata) < 0)
7339
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTCOPY, FAIL, "unable to copy chunk data in cache");
7340
0
            }
7341
0
            next = ent->next;
7342
0
        } /* end for */
7343
0
    }
7344
7345
0
done:
7346
0
    if (dt_dst && (H5T_close(dt_dst) < 0))
7347
0
        HDONE_ERROR(H5E_DATASET, H5E_CANTCLOSEOBJ, FAIL, "can't close temporary datatype");
7348
0
    if (dt_mem && (H5T_close(dt_mem) < 0))
7349
0
        HDONE_ERROR(H5E_DATASET, H5E_CANTCLOSEOBJ, FAIL, "can't close temporary datatype");
7350
0
    if (buf_space && H5S_close(buf_space) < 0)
7351
0
        HDONE_ERROR(H5E_DATASET, H5E_CANTCLOSEOBJ, FAIL, "can't close temporary dataspace");
7352
7353
0
    H5MM_xfree(udata.buf);
7354
0
    H5MM_xfree(udata.bkg);
7355
0
    H5MM_xfree(reclaim_buf);
7356
7357
    /* Clean up any index information */
7358
0
    if (copy_setup_done)
7359
0
        if (layout_src->storage.u.chunk.ops->copy_shutdown &&
7360
0
            (layout_src->storage.u.chunk.ops->copy_shutdown)(&layout_src->storage.u.chunk,
7361
0
                                                             &layout_dst->storage.u.chunk) < 0)
7362
0
            HDONE_ERROR(H5E_DATASET, H5E_CANTRELEASE, FAIL, "unable to shut down index copying info");
7363
7364
0
    FUNC_LEAVE_NOAPI(ret_value)
7365
0
} /* end H5D__chunk_copy() */
7366
7367
/*-------------------------------------------------------------------------
7368
 * Function:    H5D__chunk_bh_info
7369
 *
7370
 * Purpose:     Retrieve the amount of index storage for chunked dataset
7371
 *
7372
 * Return:      Success:        Non-negative
7373
 *              Failure:        negative
7374
 *
7375
 *-------------------------------------------------------------------------
7376
 */
7377
herr_t
7378
H5D__chunk_bh_info(const H5O_loc_t *loc, H5O_t *oh, H5O_layout_t *layout, hsize_t *index_size)
7379
0
{
7380
0
    H5D_chk_idx_info_t   idx_info;     /* Chunked index info */
7381
0
    H5S_t               *space = NULL; /* Dataset's dataspace */
7382
0
    H5O_pline_t          pline;        /* I/O pipeline message */
7383
0
    H5O_storage_chunk_t *sc = &(layout->storage.u.chunk);
7384
0
    htri_t               exists;                  /* Flag if header message of interest exists */
7385
0
    bool                 idx_info_init = false;   /* Whether the chunk index info has been initialized */
7386
0
    bool                 pline_read    = false;   /* Whether the I/O pipeline message was read */
7387
0
    herr_t               ret_value     = SUCCEED; /* Return value */
7388
7389
0
    FUNC_ENTER_PACKAGE
7390
7391
    /* Check args */
7392
0
    assert(loc);
7393
0
    assert(loc->file);
7394
0
    assert(H5_addr_defined(loc->addr));
7395
0
    assert(layout);
7396
0
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
7397
0
    assert(index_size);
7398
7399
    /* Check for I/O pipeline message */
7400
0
    if ((exists = H5O_msg_exists_oh(oh, H5O_PLINE_ID)) < 0)
7401
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to read object header");
7402
0
    else if (exists) {
7403
0
        if (NULL == H5O_msg_read_oh(loc->file, oh, H5O_PLINE_ID, &pline))
7404
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't find I/O pipeline message");
7405
0
        pline_read = true;
7406
0
    } /* end else if */
7407
0
    else
7408
0
        memset(&pline, 0, sizeof(pline));
7409
7410
    /* Compose chunked index info struct */
7411
0
    idx_info.f      = loc->file;
7412
0
    idx_info.pline  = &pline;
7413
0
    idx_info.layout = layout;
7414
7415
    /* Get the dataspace for the dataset */
7416
0
    if (NULL == (space = H5S_read(loc)))
7417
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "unable to load dataspace info from dataset header");
7418
7419
    /* Allocate any indexing structures */
7420
0
    if (sc->ops->init && (sc->ops->init)(&idx_info, space, loc->addr) < 0)
7421
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINIT, FAIL, "can't initialize indexing information");
7422
0
    idx_info_init = true;
7423
7424
    /* Get size of index structure */
7425
0
    if (sc->ops->size && (sc->ops->size)(&idx_info, index_size) < 0)
7426
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "unable to retrieve chunk index info");
7427
7428
0
done:
7429
    /* Free resources, if they've been initialized */
7430
0
    if (idx_info_init && sc->ops->dest && (sc->ops->dest)(&idx_info) < 0)
7431
0
        HDONE_ERROR(H5E_DATASET, H5E_CANTFREE, FAIL, "unable to release chunk index info");
7432
0
    if (pline_read && H5O_msg_reset(H5O_PLINE_ID, &pline) < 0)
7433
0
        HDONE_ERROR(H5E_DATASET, H5E_CANTRESET, FAIL, "unable to reset I/O pipeline message");
7434
0
    if (space && H5S_close(space) < 0)
7435
0
        HDONE_ERROR(H5E_DATASET, H5E_CLOSEERROR, FAIL, "unable to release dataspace");
7436
7437
0
    FUNC_LEAVE_NOAPI(ret_value)
7438
0
} /* end H5D__chunk_bh_info() */
7439
7440
/*-------------------------------------------------------------------------
7441
 * Function:    H5D__chunk_dump_index_cb
7442
 *
7443
 * Purpose:    If the UDATA.STREAM member is non-null then debugging
7444
 *              information is written to that stream.
7445
 *
7446
 * Return:    Success:    Non-negative
7447
 *
7448
 *        Failure:    Negative
7449
 *
7450
 *-------------------------------------------------------------------------
7451
 */
7452
static int
7453
H5D__chunk_dump_index_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata)
7454
0
{
7455
0
    H5D_chunk_it_ud4_t *udata = (H5D_chunk_it_ud4_t *)_udata; /* User data from caller */
7456
7457
0
    FUNC_ENTER_PACKAGE_NOERR
7458
7459
0
    if (udata->stream) {
7460
0
        unsigned u; /* Local index variable */
7461
7462
        /* Print header if not already displayed */
7463
0
        if (!udata->header_displayed) {
7464
0
            fprintf(udata->stream, "           Flags    Bytes     Address          Logical Offset\n");
7465
0
            fprintf(udata->stream, "        ========== ======== ========== ==============================\n");
7466
7467
            /* Set flag that the headers has been printed */
7468
0
            udata->header_displayed = true;
7469
0
        } /* end if */
7470
7471
        /* Print information about this chunk */
7472
0
        fprintf(udata->stream, "        0x%08x %8" PRIuHSIZE " %10" PRIuHADDR " [", chunk_rec->filter_mask,
7473
0
                chunk_rec->nbytes, chunk_rec->chunk_addr);
7474
0
        for (u = 0; u < udata->ndims; u++)
7475
0
            fprintf(udata->stream, "%s%" PRIuHSIZE, (u ? ", " : ""),
7476
0
                    (chunk_rec->scaled[u] * udata->chunk_dim[u]));
7477
0
        fputs("]\n", udata->stream);
7478
0
    } /* end if */
7479
7480
0
    FUNC_LEAVE_NOAPI(H5_ITER_CONT)
7481
0
} /* H5D__chunk_dump_index_cb() */
7482
7483
/*-------------------------------------------------------------------------
7484
 * Function:    H5D__chunk_dump_index
7485
 *
7486
 * Purpose:    Prints information about the storage index to the specified
7487
 *        stream.
7488
 *
7489
 * Return:    Success:    Non-negative
7490
 *        Failure:    negative
7491
 *
7492
 *-------------------------------------------------------------------------
7493
 */
7494
herr_t
7495
H5D__chunk_dump_index(H5D_t *dset, FILE *stream)
7496
0
{
7497
0
    H5O_storage_chunk_t *sc        = &(dset->shared->layout.storage.u.chunk);
7498
0
    herr_t               ret_value = SUCCEED; /* Return value */
7499
7500
0
    FUNC_ENTER_PACKAGE
7501
7502
    /* Sanity check */
7503
0
    assert(dset);
7504
0
    H5D_CHUNK_STORAGE_INDEX_CHK(sc);
7505
7506
    /* Only display info if stream is defined */
7507
0
    if (stream) {
7508
0
        H5D_chk_idx_info_t idx_info; /* Chunked index info */
7509
0
        H5D_chunk_it_ud4_t udata;    /* User data for callback */
7510
7511
        /* Display info for index */
7512
0
        if ((sc->ops->dump)(sc, stream) < 0)
7513
0
            HGOTO_ERROR(H5E_DATASET, H5E_UNSUPPORTED, FAIL, "unable to dump chunk index info");
7514
7515
        /* Compose chunked index info struct */
7516
0
        idx_info.f      = dset->oloc.file;
7517
0
        idx_info.pline  = &dset->shared->dcpl_cache.pline;
7518
0
        idx_info.layout = &dset->shared->layout;
7519
7520
        /* Set up user data for callback */
7521
0
        udata.stream           = stream;
7522
0
        udata.header_displayed = false;
7523
0
        udata.ndims            = dset->shared->layout.u.chunk.ndims;
7524
0
        udata.chunk_dim        = dset->shared->layout.u.chunk.dim;
7525
7526
        /* Iterate over index and dump chunk info */
7527
0
        if ((sc->ops->iterate)(&idx_info, H5D__chunk_dump_index_cb, &udata) < 0)
7528
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADITER, FAIL,
7529
0
                        "unable to iterate over chunk index to dump chunk info");
7530
0
    } /* end if */
7531
7532
0
done:
7533
0
    FUNC_LEAVE_NOAPI(ret_value)
7534
0
} /* end H5D__chunk_dump_index() */
7535
7536
#ifdef H5D_CHUNK_DEBUG
7537
7538
/*-------------------------------------------------------------------------
7539
 * Function:    H5D__chunk_stats
7540
 *
7541
 * Purpose:    Print raw data cache statistics to the debug stream.  If
7542
 *        HEADERS is non-zero then print table column headers,
7543
 *        otherwise assume that the H5AC layer has already printed them.
7544
 *
7545
 * Return:    Non-negative on success/Negative on failure
7546
 *
7547
 *-------------------------------------------------------------------------
7548
 */
7549
herr_t
7550
H5D__chunk_stats(const H5D_t *dset, bool headers)
7551
{
7552
    H5D_rdcc_t *rdcc = &(dset->shared->cache.chunk);
7553
    double      miss_rate;
7554
    char        ascii[32];
7555
    herr_t      ret_value = SUCCEED; /* Return value */
7556
7557
    FUNC_ENTER_PACKAGE_NOERR
7558
7559
    if (!H5DEBUG(AC))
7560
        HGOTO_DONE(SUCCEED);
7561
7562
    if (headers) {
7563
        fprintf(H5DEBUG(AC), "H5D: raw data cache statistics\n");
7564
        fprintf(H5DEBUG(AC), "   %-18s %8s %8s %8s %8s+%-8s\n", "Layer", "Hits", "Misses", "MissRate",
7565
                "Inits", "Flushes");
7566
        fprintf(H5DEBUG(AC), "   %-18s %8s %8s %8s %8s-%-8s\n", "-----", "----", "------", "--------",
7567
                "-----", "-------");
7568
    }
7569
7570
#ifdef H5AC_DEBUG
7571
    if (H5DEBUG(AC))
7572
        headers = true;
7573
#endif
7574
7575
    if (headers) {
7576
        if (rdcc->stats.nhits > 0 || rdcc->stats.nmisses > 0) {
7577
            miss_rate = 100.0 * rdcc->stats.nmisses / (rdcc->stats.nhits + rdcc->stats.nmisses);
7578
        }
7579
        else {
7580
            miss_rate = 0.0;
7581
        }
7582
        if (miss_rate > 100) {
7583
            snprintf(ascii, sizeof(ascii), "%7d%%", (int)(miss_rate + 0.5));
7584
        }
7585
        else {
7586
            snprintf(ascii, sizeof(ascii), "%7.2f%%", miss_rate);
7587
        }
7588
7589
        fprintf(H5DEBUG(AC), "   %-18s %8u %8u %7s %8d+%-9ld\n", "raw data chunks", rdcc->stats.nhits,
7590
                rdcc->stats.nmisses, ascii, rdcc->stats.ninits,
7591
                (long)(rdcc->stats.nflushes) - (long)(rdcc->stats.ninits));
7592
    }
7593
7594
done:
7595
    FUNC_LEAVE_NOAPI(ret_value)
7596
} /* end H5D__chunk_stats() */
7597
#endif /* H5D_CHUNK_DEBUG */
7598
7599
/*-------------------------------------------------------------------------
7600
 * Function:    H5D__chunk_is_partial_edge_chunk
7601
 *
7602
 * Purpose:     Checks to see if the chunk is a partial edge chunk.
7603
 *              Either dset or (dset_dims and dset_ndims) must be
7604
 *              provided.
7605
 *
7606
 * Return:      Non-negative on success/Negative on failure
7607
 *
7608
 *-------------------------------------------------------------------------
7609
 */
7610
bool
7611
H5D__chunk_is_partial_edge_chunk(unsigned dset_ndims, const hsize_t *chunk_dims, const hsize_t scaled[],
7612
                                 const hsize_t *dset_dims)
7613
0
{
7614
0
    unsigned u;                 /* Local index variable */
7615
0
    bool     ret_value = false; /* Return value */
7616
7617
0
    FUNC_ENTER_PACKAGE_NOERR
7618
7619
    /* Check args */
7620
0
    assert(scaled);
7621
0
    assert(dset_ndims > 0);
7622
0
    assert(dset_dims);
7623
0
    assert(chunk_dims);
7624
7625
    /* check if this is a partial edge chunk */
7626
0
    for (u = 0; u < dset_ndims; u++)
7627
0
        if (((scaled[u] + 1) * chunk_dims[u]) > dset_dims[u])
7628
0
            HGOTO_DONE(true);
7629
7630
0
done:
7631
0
    FUNC_LEAVE_NOAPI(ret_value)
7632
0
} /* H5D__chunk_is_partial_edge_chunk() */
7633
7634
/*-------------------------------------------------------------------------
7635
 * Function:    H5D__chunk_file_alloc()
7636
 *
7637
 * Purpose:     Chunk allocation:
7638
 *          Create the chunk if it doesn't exist, or reallocate the
7639
 *                chunk if its size changed.
7640
 *          The coding is moved and modified from each index structure.
7641
 *
7642
 * Return:      Non-negative on success/Negative on failure
7643
 *
7644
 *-------------------------------------------------------------------------
7645
 */
7646
herr_t
7647
H5D__chunk_file_alloc(const H5D_chk_idx_info_t *idx_info, const H5F_block_t *old_chunk,
7648
                      H5F_block_t *new_chunk, bool *need_insert, const hsize_t *scaled)
7649
0
{
7650
0
    bool   alloc_chunk = false;   /* Whether to allocate chunk */
7651
0
    herr_t ret_value   = SUCCEED; /* Return value         */
7652
7653
0
    FUNC_ENTER_PACKAGE
7654
7655
    /* Sanity check */
7656
0
    assert(idx_info);
7657
0
    assert(idx_info->f);
7658
0
    assert(idx_info->pline);
7659
0
    assert(idx_info->layout);
7660
0
    assert(new_chunk);
7661
0
    assert(need_insert);
7662
7663
0
    *need_insert = false;
7664
7665
    /* Check for filters on chunks */
7666
0
    if (idx_info->pline->nused > 0) {
7667
        /* The none index shouldn't be used with filtered datasets */
7668
0
        assert(idx_info->layout->storage.u.chunk.idx_type != H5D_CHUNK_IDX_NONE);
7669
7670
        /* Check for chunk size overflowing format limitations */
7671
        /* Only needed for filtered datasets because the unfiltered chunk size
7672
         * was already checked in H5D__chunk_construct() */
7673
0
        H5D_CHUNK_ENCODE_SIZE_CHECK(idx_info->layout, new_chunk->length, FAIL);
7674
7675
0
        if (old_chunk && H5_addr_defined(old_chunk->offset)) {
7676
            /* Sanity check */
7677
0
            assert(!H5_addr_defined(new_chunk->offset) || H5_addr_eq(new_chunk->offset, old_chunk->offset));
7678
7679
            /* Check for chunk being same size */
7680
0
            if (new_chunk->length != old_chunk->length) {
7681
                /* Release previous chunk */
7682
                /* Only free the old location if not doing SWMR writes - otherwise
7683
                 * we must keep the old chunk around in case a reader has an
7684
                 * outdated version of the B-tree node
7685
                 */
7686
0
                if (!(H5F_INTENT(idx_info->f) & H5F_ACC_SWMR_WRITE))
7687
0
                    if (H5MF_xfree(idx_info->f, H5FD_MEM_DRAW, old_chunk->offset, old_chunk->length) < 0)
7688
0
                        HGOTO_ERROR(H5E_DATASET, H5E_CANTFREE, FAIL, "unable to free chunk");
7689
0
                alloc_chunk = true;
7690
0
            } /* end if */
7691
0
            else {
7692
                /* Don't need to reallocate chunk, but send its address back up */
7693
0
                if (!H5_addr_defined(new_chunk->offset))
7694
0
                    new_chunk->offset = old_chunk->offset;
7695
0
            } /* end else */
7696
0
        }     /* end if */
7697
0
        else {
7698
0
            assert(!H5_addr_defined(new_chunk->offset));
7699
0
            alloc_chunk = true;
7700
0
        } /* end else */
7701
0
    }     /* end if */
7702
0
    else {
7703
0
        assert(!H5_addr_defined(new_chunk->offset));
7704
0
        assert(new_chunk->length == idx_info->layout->u.chunk.size);
7705
0
        alloc_chunk = true;
7706
0
    } /* end else */
7707
7708
    /* Actually allocate space for the chunk in the file */
7709
0
    if (alloc_chunk) {
7710
0
        switch (idx_info->layout->storage.u.chunk.idx_type) {
7711
0
            case H5D_CHUNK_IDX_NONE: {
7712
0
                H5D_chunk_ud_t udata;
7713
7714
0
                udata.common.scaled = scaled;
7715
0
                if ((idx_info->layout->storage.u.chunk.ops->get_addr)(idx_info, &udata) < 0)
7716
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't query chunk address");
7717
0
                new_chunk->offset = udata.chunk_block.offset;
7718
0
                assert(new_chunk->length == udata.chunk_block.length);
7719
0
                break;
7720
0
            }
7721
7722
0
            case H5D_CHUNK_IDX_EARRAY:
7723
0
            case H5D_CHUNK_IDX_FARRAY:
7724
0
            case H5D_CHUNK_IDX_BT2:
7725
0
            case H5D_CHUNK_IDX_BTREE:
7726
0
            case H5D_CHUNK_IDX_SINGLE:
7727
0
                assert(new_chunk->length > 0);
7728
0
                new_chunk->offset = H5MF_alloc(idx_info->f, H5FD_MEM_DRAW, new_chunk->length);
7729
0
                if (!H5_addr_defined(new_chunk->offset))
7730
0
                    HGOTO_ERROR(H5E_DATASET, H5E_CANTALLOC, FAIL, "file allocation failed");
7731
0
                *need_insert = true;
7732
0
                break;
7733
7734
0
            case H5D_CHUNK_IDX_NTYPES:
7735
0
            default:
7736
0
                assert(0 && "This should never be executed!");
7737
0
                break;
7738
0
        } /* end switch */
7739
0
    }     /* end if */
7740
7741
0
    assert(H5_addr_defined(new_chunk->offset));
7742
7743
0
done:
7744
0
    FUNC_LEAVE_NOAPI(ret_value)
7745
0
} /* H5D__chunk_file_alloc() */
7746
7747
/*-------------------------------------------------------------------------
7748
 * Function:    H5D__chunk_format_convert_cb
7749
 *
7750
 * Purpose:     Callback routine to insert chunk address into v1 B-tree
7751
 *              chunk index.
7752
 *
7753
 * Return:      Success:        Non-negative
7754
 *              Failure:        Negative
7755
 *
7756
 *-------------------------------------------------------------------------
7757
 */
7758
static int
7759
H5D__chunk_format_convert_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata)
7760
0
{
7761
0
    H5D_chunk_it_ud5_t *udata = (H5D_chunk_it_ud5_t *)_udata; /* User data */
7762
0
    H5D_chk_idx_info_t *new_idx_info;                         /* The new chunk index information */
7763
0
    H5D_chunk_ud_t      insert_udata;                         /* Chunk information to be inserted */
7764
0
    haddr_t             chunk_addr;                           /* Chunk address */
7765
0
    size_t              nbytes;                               /* Chunk size */
7766
0
    void               *buf       = NULL;                     /* Pointer to buffer of chunk data */
7767
0
    int                 ret_value = H5_ITER_CONT;             /* Return value */
7768
7769
0
    FUNC_ENTER_PACKAGE
7770
7771
    /* Set up */
7772
0
    new_idx_info = udata->new_idx_info;
7773
0
    H5_CHECKED_ASSIGN(nbytes, size_t, chunk_rec->nbytes, hsize_t);
7774
0
    chunk_addr = chunk_rec->chunk_addr;
7775
7776
0
    if (new_idx_info->pline->nused &&
7777
0
        (new_idx_info->layout->u.chunk.flags & H5O_LAYOUT_CHUNK_DONT_FILTER_PARTIAL_BOUND_CHUNKS) &&
7778
0
        (H5D__chunk_is_partial_edge_chunk(udata->dset_ndims, new_idx_info->layout->u.chunk.dim,
7779
0
                                          chunk_rec->scaled, udata->dset_dims))) {
7780
7781
        /* This is a partial non-filtered edge chunk */
7782
        /* Convert the chunk to a filtered edge chunk for v1 B-tree chunk index */
7783
7784
0
        unsigned filter_mask = chunk_rec->filter_mask;
7785
0
        H5Z_cb_t filter_cb;          /* Filter failure callback struct */
7786
0
        size_t   read_size = nbytes; /* Bytes to read */
7787
7788
0
        assert(read_size == new_idx_info->layout->u.chunk.size);
7789
7790
        /* Initialize the filter callback struct */
7791
0
        filter_cb.op_data = NULL;
7792
0
        filter_cb.func    = NULL; /* no callback function when failed */
7793
7794
        /* Allocate buffer for chunk data */
7795
0
        if (NULL == (buf = H5MM_malloc(read_size)))
7796
0
            HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, H5_ITER_ERROR,
7797
0
                        "memory allocation failed for raw data chunk");
7798
7799
        /* Read the non-filtered edge chunk */
7800
0
        if (H5F_block_read(new_idx_info->f, H5FD_MEM_DRAW, chunk_addr, read_size, buf) < 0)
7801
0
            HGOTO_ERROR(H5E_IO, H5E_READERROR, H5_ITER_ERROR, "unable to read raw data chunk");
7802
7803
        /* Pass the chunk through the pipeline */
7804
0
        if (H5Z_pipeline(new_idx_info->pline, 0, &filter_mask, H5Z_NO_EDC, filter_cb, &nbytes, &read_size,
7805
0
                         &buf) < 0)
7806
0
            HGOTO_ERROR(H5E_PLINE, H5E_CANTFILTER, H5_ITER_ERROR, "output pipeline failed");
7807
7808
0
#if H5_SIZEOF_SIZE_T > 4
7809
        /* Check for the chunk expanding too much to encode in a 32-bit value */
7810
0
        if (nbytes > ((size_t)0xffffffff))
7811
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADRANGE, H5_ITER_ERROR, "chunk too large for 32-bit length");
7812
0
#endif /* H5_SIZEOF_SIZE_T > 4 */
7813
7814
        /* Allocate space for the filtered chunk */
7815
0
        if ((chunk_addr = H5MF_alloc(new_idx_info->f, H5FD_MEM_DRAW, (hsize_t)nbytes)) == HADDR_UNDEF)
7816
0
            HGOTO_ERROR(H5E_DATASET, H5E_NOSPACE, H5_ITER_ERROR, "file allocation failed for filtered chunk");
7817
0
        assert(H5_addr_defined(chunk_addr));
7818
7819
        /* Write the filtered chunk to disk */
7820
0
        if (H5F_block_write(new_idx_info->f, H5FD_MEM_DRAW, chunk_addr, nbytes, buf) < 0)
7821
0
            HGOTO_ERROR(H5E_DATASET, H5E_WRITEERROR, H5_ITER_ERROR, "unable to write raw data to file");
7822
0
    } /* end if */
7823
7824
    /* Set up chunk information for insertion to chunk index */
7825
0
    insert_udata.chunk_block.offset = chunk_addr;
7826
0
    insert_udata.chunk_block.length = nbytes;
7827
0
    insert_udata.filter_mask        = chunk_rec->filter_mask;
7828
0
    insert_udata.common.scaled      = chunk_rec->scaled;
7829
0
    insert_udata.common.layout      = &new_idx_info->layout->u.chunk;
7830
0
    insert_udata.common.storage     = &new_idx_info->layout->storage.u.chunk;
7831
7832
    /* Insert chunk into the v1 B-tree chunk index */
7833
0
    if ((new_idx_info->layout->storage.u.chunk.ops->insert)(new_idx_info, &insert_udata, NULL) < 0)
7834
0
        HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, H5_ITER_ERROR, "unable to insert chunk addr into index");
7835
7836
0
done:
7837
0
    if (buf)
7838
0
        H5MM_xfree(buf);
7839
7840
0
    FUNC_LEAVE_NOAPI(ret_value)
7841
0
} /* H5D__chunk_format_convert_cb() */
7842
7843
/*-------------------------------------------------------------------------
7844
 * Function:    H5D__chunk_format_convert
7845
 *
7846
 * Purpose:     Iterate over the chunks for the current chunk index and insert the
7847
 *        the chunk addresses into v1 B-tree chunk index via callback.
7848
 *
7849
 * Return:      Non-negative on success/Negative on failure
7850
 *
7851
 *-------------------------------------------------------------------------
7852
 */
7853
herr_t
7854
H5D__chunk_format_convert(H5D_t *dset, H5D_chk_idx_info_t *idx_info, H5D_chk_idx_info_t *new_idx_info)
7855
0
{
7856
0
    H5D_chunk_it_ud5_t udata;               /* User data */
7857
0
    herr_t             ret_value = SUCCEED; /* Return value */
7858
7859
0
    FUNC_ENTER_PACKAGE
7860
7861
    /* Check args */
7862
0
    assert(dset);
7863
7864
    /* Set up user data */
7865
0
    udata.new_idx_info = new_idx_info;
7866
0
    udata.dset_ndims   = dset->shared->ndims;
7867
0
    udata.dset_dims    = dset->shared->curr_dims;
7868
7869
    /* Iterate over the chunks in the current index and insert the chunk addresses into version 1 B-tree index
7870
     */
7871
0
    if ((idx_info->layout->storage.u.chunk.ops->iterate)(idx_info, H5D__chunk_format_convert_cb, &udata) < 0)
7872
0
        HGOTO_ERROR(H5E_DATASET, H5E_BADITER, FAIL, "unable to iterate over chunk index to chunk info");
7873
7874
0
done:
7875
0
    FUNC_LEAVE_NOAPI(ret_value)
7876
0
} /* end H5D__chunk_format_convert() */
7877
7878
/*-------------------------------------------------------------------------
7879
 * Function:    H5D__chunk_index_empty_cb
7880
 *
7881
 * Purpose:     Callback function that simply stops iteration and sets the
7882
 *              `empty` parameter to false if called. If this callback is
7883
 *              entered, it means that the chunk index contains at least
7884
 *              one chunk, so is not empty.
7885
 *
7886
 * Return:      H5_ITER_STOP
7887
 *
7888
 *-------------------------------------------------------------------------
7889
 */
7890
static int
7891
H5D__chunk_index_empty_cb(const H5D_chunk_rec_t H5_ATTR_UNUSED *chunk_rec, void *_udata)
7892
0
{
7893
0
    bool *empty     = (bool *)_udata;
7894
0
    int   ret_value = H5_ITER_STOP;
7895
7896
0
    FUNC_ENTER_PACKAGE_NOERR
7897
7898
0
    *empty = false;
7899
7900
0
    FUNC_LEAVE_NOAPI(ret_value)
7901
0
} /* end H5D__chunk_index_empty_cb() */
7902
7903
/*-------------------------------------------------------------------------
7904
 * Function:    H5D__chunk_index_empty
7905
 *
7906
 * Purpose:     Determines whether a chunk index is empty (has no chunks
7907
 *              inserted into it yet).
7908
 *
7909
 * Note:        This routine is meant to be a little more performant than
7910
 *              just counting the number of chunks in the index. In the
7911
 *              future, this is probably a callback that the chunk index
7912
 *              ops structure should provide.
7913
 *
7914
 * Return:      Non-negative on Success/Negative on failure
7915
 *
7916
 *-------------------------------------------------------------------------
7917
 */
7918
herr_t
7919
H5D__chunk_index_empty(const H5D_t *dset, bool *empty)
7920
0
{
7921
0
    H5D_chk_idx_info_t idx_info;            /* Chunked index info */
7922
0
    H5D_rdcc_ent_t    *ent;                 /* Cache entry  */
7923
0
    const H5D_rdcc_t  *rdcc      = NULL;    /* Raw data chunk cache */
7924
0
    herr_t             ret_value = SUCCEED; /* Return value */
7925
7926
0
    FUNC_ENTER_PACKAGE_TAG(dset->oloc.addr)
7927
7928
0
    assert(dset);
7929
0
    assert(dset->shared);
7930
0
    assert(empty);
7931
7932
0
    rdcc = &(dset->shared->cache.chunk); /* raw data chunk cache */
7933
0
    assert(rdcc);
7934
7935
    /* Search for cached chunks that haven't been written out */
7936
0
    for (ent = rdcc->head; ent; ent = ent->next)
7937
        /* Flush the chunk out to disk, to make certain the size is correct later */
7938
0
        if (H5D__chunk_flush_entry(dset, ent, false) < 0)
7939
0
            HGOTO_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "cannot flush indexed storage buffer");
7940
7941
    /* Compose chunked index info struct */
7942
0
    idx_info.f      = dset->oloc.file;
7943
0
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
7944
0
    idx_info.layout = &dset->shared->layout;
7945
7946
0
    *empty = true;
7947
7948
0
    if (H5_addr_defined(idx_info.layout->storage.u.chunk.idx_addr)) {
7949
        /* Iterate over the allocated chunks */
7950
0
        if ((dset->shared->layout.storage.u.chunk.ops->iterate)(&idx_info, H5D__chunk_index_empty_cb, empty) <
7951
0
            0)
7952
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL,
7953
0
                        "unable to retrieve allocated chunk information from index");
7954
0
    }
7955
7956
0
done:
7957
0
    FUNC_LEAVE_NOAPI_TAG(ret_value)
7958
0
} /* end H5D__chunk_index_empty() */
7959
7960
/*-------------------------------------------------------------------------
7961
 * Function:    H5D__get_num_chunks_cb
7962
 *
7963
 * Purpose:     Callback function that increments the number of written
7964
 *              chunks in the dataset.
7965
 *
7966
 * Note:        Currently, this function only gets the number of all written
7967
 *              chunks, regardless the dataspace.
7968
 *
7969
 * Return:      H5_ITER_CONT
7970
 *
7971
 *-------------------------------------------------------------------------
7972
 */
7973
static int
7974
H5D__get_num_chunks_cb(const H5D_chunk_rec_t H5_ATTR_UNUSED *chunk_rec, void *_udata)
7975
0
{
7976
0
    hsize_t *num_chunks = (hsize_t *)_udata;
7977
0
    int      ret_value  = H5_ITER_CONT; /* Callback return value */
7978
7979
0
    FUNC_ENTER_PACKAGE_NOERR
7980
7981
0
    assert(num_chunks);
7982
7983
0
    (*num_chunks)++;
7984
7985
0
    FUNC_LEAVE_NOAPI(ret_value)
7986
0
} /* H5D__get_num_chunks_cb() */
7987
7988
/*-------------------------------------------------------------------------
7989
 * Function:    H5D__get_num_chunks
7990
 *
7991
 * Purpose:     Gets the number of written chunks in a dataset.
7992
 *
7993
 * Note:        Currently, this function only gets the number of all written
7994
 *              chunks, regardless the dataspace.
7995
 *
7996
 * Return:      Success:    Non-negative
7997
 *              Failure:    Negative
7998
 *
7999
 *-------------------------------------------------------------------------
8000
 */
8001
herr_t
8002
H5D__get_num_chunks(const H5D_t *dset, const H5S_t H5_ATTR_UNUSED *space, hsize_t *nchunks)
8003
0
{
8004
0
    H5D_chk_idx_info_t idx_info;            /* Chunked index info */
8005
0
    hsize_t            num_chunks = 0;      /* Number of written chunks */
8006
0
    H5D_rdcc_ent_t    *ent;                 /* Cache entry  */
8007
0
    const H5D_rdcc_t  *rdcc      = NULL;    /* Raw data chunk cache */
8008
0
    herr_t             ret_value = SUCCEED; /* Return value */
8009
8010
0
    FUNC_ENTER_PACKAGE_TAG(dset->oloc.addr)
8011
8012
0
    assert(dset);
8013
0
    assert(dset->shared);
8014
0
    assert(space);
8015
0
    assert(nchunks);
8016
8017
0
    rdcc = &(dset->shared->cache.chunk); /* raw data chunk cache */
8018
0
    assert(rdcc);
8019
8020
    /* Search for cached chunks that haven't been written out */
8021
0
    for (ent = rdcc->head; ent; ent = ent->next)
8022
        /* Flush the chunk out to disk, to make certain the size is correct later */
8023
0
        if (H5D__chunk_flush_entry(dset, ent, false) < 0)
8024
0
            HGOTO_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "cannot flush indexed storage buffer");
8025
8026
    /* Compose chunked index info struct */
8027
0
    idx_info.f      = dset->oloc.file;
8028
0
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
8029
0
    idx_info.layout = &dset->shared->layout;
8030
8031
    /* If the dataset is not written, number of chunks will be 0 */
8032
0
    if (!H5_addr_defined(idx_info.layout->storage.u.chunk.idx_addr))
8033
0
        *nchunks = 0;
8034
0
    else {
8035
        /* Iterate over the allocated chunks */
8036
0
        if ((dset->shared->layout.storage.u.chunk.ops->iterate)(&idx_info, H5D__get_num_chunks_cb,
8037
0
                                                                &num_chunks) < 0)
8038
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL,
8039
0
                        "unable to retrieve allocated chunk information from index");
8040
0
        *nchunks = num_chunks;
8041
0
    }
8042
8043
0
done:
8044
0
    FUNC_LEAVE_NOAPI_TAG(ret_value)
8045
0
} /* end H5D__get_num_chunks() */
8046
8047
/*-------------------------------------------------------------------------
8048
 * Function:    H5D__get_chunk_info_cb
8049
 *
8050
 * Purpose:     Get the chunk info of the queried chunk, given by its index
8051
 *
8052
 * Return:      Success:    H5_ITER_CONT or H5_ITER_STOP
8053
 *                          H5_ITER_STOP indicates the queried chunk is found
8054
 *              Failure:    Negative (H5_ITER_ERROR)
8055
 *
8056
 *-------------------------------------------------------------------------
8057
 */
8058
static int
8059
H5D__get_chunk_info_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata)
8060
0
{
8061
0
    H5D_chunk_info_iter_ud_t *chunk_info = (H5D_chunk_info_iter_ud_t *)_udata;
8062
0
    int                       ret_value  = H5_ITER_CONT; /* Callback return value */
8063
8064
0
    FUNC_ENTER_PACKAGE_NOERR
8065
8066
    /* Check args */
8067
0
    assert(chunk_rec);
8068
0
    assert(chunk_info);
8069
8070
    /* If this is the queried chunk, retrieve its info and stop iterating */
8071
0
    if (chunk_info->curr_idx == chunk_info->chunk_idx) {
8072
0
        hsize_t ii = 0; /* Dimension index */
8073
8074
        /* Copy info */
8075
0
        chunk_info->filter_mask = chunk_rec->filter_mask;
8076
0
        chunk_info->chunk_addr  = chunk_rec->chunk_addr;
8077
0
        chunk_info->nbytes      = chunk_rec->nbytes;
8078
0
        for (ii = 0; ii < chunk_info->ndims; ii++)
8079
0
            chunk_info->scaled[ii] = chunk_rec->scaled[ii];
8080
0
        chunk_info->found = true;
8081
8082
        /* Stop iterating */
8083
0
        ret_value = H5_ITER_STOP;
8084
0
    }
8085
    /* Go to the next chunk */
8086
0
    else
8087
0
        chunk_info->curr_idx++;
8088
8089
0
    FUNC_LEAVE_NOAPI(ret_value)
8090
0
} /* H5D__get_chunk_info_cb() */
8091
8092
/*-------------------------------------------------------------------------
8093
 * Function:    H5D__get_chunk_info
8094
 *
8095
 * Purpose:     Iterate over the chunks in the dataset to get the info
8096
 *              of the desired chunk.
8097
 *
8098
 * Note:        Currently, the domain of the index in this function is of all
8099
 *              the written chunks, regardless the dataspace.
8100
 *
8101
 * Return:      SUCCEED/FAIL
8102
 *-------------------------------------------------------------------------
8103
 */
8104
herr_t
8105
H5D__get_chunk_info(const H5D_t *dset, const H5S_t H5_ATTR_UNUSED *space, hsize_t chk_index, hsize_t *offset,
8106
                    unsigned *filter_mask, haddr_t *addr, hsize_t *size)
8107
0
{
8108
0
    H5D_chk_idx_info_t idx_info;            /* Chunked index info */
8109
0
    const H5D_rdcc_t  *rdcc = NULL;         /* Raw data chunk cache */
8110
0
    H5D_rdcc_ent_t    *ent;                 /* Cache entry index */
8111
0
    hsize_t            ii        = 0;       /* Dimension index */
8112
0
    herr_t             ret_value = SUCCEED; /* Return value */
8113
8114
0
    FUNC_ENTER_PACKAGE_TAG(dset->oloc.addr)
8115
8116
0
    assert(dset);
8117
0
    assert(dset->shared);
8118
0
    assert(space);
8119
8120
    /* Get the raw data chunk cache */
8121
0
    rdcc = &(dset->shared->cache.chunk);
8122
0
    assert(rdcc);
8123
8124
    /* Search for cached chunks that haven't been written out */
8125
0
    for (ent = rdcc->head; ent; ent = ent->next)
8126
        /* Flush the chunk out to disk, to make certain the size is correct later */
8127
0
        if (H5D__chunk_flush_entry(dset, ent, false) < 0)
8128
0
            HGOTO_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "cannot flush indexed storage buffer");
8129
8130
    /* Compose chunked index info struct */
8131
0
    idx_info.f      = dset->oloc.file;
8132
0
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
8133
0
    idx_info.layout = &dset->shared->layout;
8134
8135
    /* Set addr & size for when dset is not written or queried chunk is not found */
8136
0
    if (addr)
8137
0
        *addr = HADDR_UNDEF;
8138
0
    if (size)
8139
0
        *size = 0;
8140
8141
    /* If the chunk is written, get its info, otherwise, return without error */
8142
0
    if (H5_addr_defined(idx_info.layout->storage.u.chunk.idx_addr)) {
8143
8144
0
        H5D_chunk_info_iter_ud_t udata;
8145
8146
        /* Initialize before iteration */
8147
0
        udata.chunk_idx   = chk_index;
8148
0
        udata.curr_idx    = 0;
8149
0
        udata.ndims       = dset->shared->ndims;
8150
0
        udata.nbytes      = 0;
8151
0
        udata.filter_mask = 0;
8152
0
        udata.chunk_addr  = HADDR_UNDEF;
8153
0
        udata.found       = false;
8154
8155
        /* Iterate over the allocated chunks */
8156
0
        if ((dset->shared->layout.storage.u.chunk.ops->iterate)(&idx_info, H5D__get_chunk_info_cb, &udata) <
8157
0
            0)
8158
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL,
8159
0
                        "unable to retrieve allocated chunk information from index");
8160
8161
        /* Obtain requested info if the chunk is found */
8162
0
        if (udata.found) {
8163
0
            if (filter_mask)
8164
0
                *filter_mask = udata.filter_mask;
8165
0
            if (addr)
8166
0
                *addr = udata.chunk_addr + H5F_BASE_ADDR(dset->oloc.file);
8167
0
            if (size)
8168
0
                *size = udata.nbytes;
8169
0
            if (offset)
8170
0
                for (ii = 0; ii < udata.ndims; ii++)
8171
0
                    offset[ii] = udata.scaled[ii] * dset->shared->layout.u.chunk.dim[ii];
8172
0
        }
8173
0
    }
8174
8175
0
done:
8176
0
    FUNC_LEAVE_NOAPI_TAG(ret_value)
8177
0
} /* end H5D__get_chunk_info() */
8178
8179
/*-------------------------------------------------------------------------
8180
 * Function:    H5D__get_chunk_info_by_coord_cb
8181
 *
8182
 * Purpose:     Get the chunk info of the desired chunk, given its offset
8183
 *              coordinates.
8184
 *
8185
 * Return:      Success:    H5_ITER_CONT or H5_ITER_STOP
8186
 *              Failure:    Negative (H5_ITER_ERROR)
8187
 *
8188
 *-------------------------------------------------------------------------
8189
 */
8190
static int
8191
H5D__get_chunk_info_by_coord_cb(const H5D_chunk_rec_t *chunk_rec, void *_udata)
8192
0
{
8193
0
    H5D_chunk_info_iter_ud_t *chunk_info = (H5D_chunk_info_iter_ud_t *)_udata;
8194
0
    bool                      different  = false;       /* true when a scaled value pair mismatch */
8195
0
    hsize_t                   ii;                       /* Local index value */
8196
0
    int                       ret_value = H5_ITER_CONT; /* Callback return value */
8197
8198
0
    FUNC_ENTER_PACKAGE_NOERR
8199
8200
    /* Check args */
8201
0
    assert(chunk_rec);
8202
0
    assert(chunk_info);
8203
8204
    /* Going through the scaled, stop when a mismatch is found */
8205
0
    for (ii = 0; ii < chunk_info->ndims && !different; ii++)
8206
0
        if (chunk_info->scaled[ii] != chunk_rec->scaled[ii])
8207
0
            different = true;
8208
8209
    /* Same scaled coords means the chunk is found, copy the chunk info */
8210
0
    if (!different) {
8211
0
        chunk_info->nbytes      = chunk_rec->nbytes;
8212
0
        chunk_info->filter_mask = chunk_rec->filter_mask;
8213
0
        chunk_info->chunk_addr  = chunk_rec->chunk_addr;
8214
0
        chunk_info->found       = true;
8215
8216
        /* Stop iterating */
8217
0
        ret_value = H5_ITER_STOP;
8218
0
    }
8219
8220
0
    FUNC_LEAVE_NOAPI(ret_value)
8221
0
} /* H5D__get_chunk_info_by_coord_cb() */
8222
8223
/*-------------------------------------------------------------------------
8224
 * Function:    H5D__get_chunk_info_by_coord
8225
 *
8226
 * Purpose:     Iterate over the chunks in the dataset to get the info
8227
 *              of the desired chunk, given by its offset coordinates.
8228
 *
8229
 * Return:      Success:        Non-negative
8230
 *              Failure:        Negative
8231
 *
8232
 *-------------------------------------------------------------------------
8233
 */
8234
herr_t
8235
H5D__get_chunk_info_by_coord(const H5D_t *dset, const hsize_t *offset, unsigned *filter_mask, haddr_t *addr,
8236
                             hsize_t *size)
8237
0
{
8238
0
    const H5O_layout_t *layout = NULL;       /* Dataset layout */
8239
0
    const H5D_rdcc_t   *rdcc   = NULL;       /* Raw data chunk cache */
8240
0
    H5D_rdcc_ent_t     *ent;                 /* Cache entry index */
8241
0
    H5D_chk_idx_info_t  idx_info;            /* Chunked index info */
8242
0
    herr_t              ret_value = SUCCEED; /* Return value */
8243
8244
0
    FUNC_ENTER_PACKAGE_TAG(dset->oloc.addr)
8245
8246
    /* Check args */
8247
0
    assert(dset);
8248
0
    assert(dset->shared);
8249
0
    assert(offset);
8250
8251
    /* Get dataset layout and raw data chunk cache */
8252
0
    layout = &(dset->shared->layout);
8253
0
    rdcc   = &(dset->shared->cache.chunk);
8254
0
    assert(layout);
8255
0
    assert(rdcc);
8256
0
    assert(H5D_CHUNKED == layout->type);
8257
8258
    /* Search for cached chunks that haven't been written out */
8259
0
    for (ent = rdcc->head; ent; ent = ent->next)
8260
        /* Flush the chunk out to disk, to make certain the size is correct later */
8261
0
        if (H5D__chunk_flush_entry(dset, ent, false) < 0)
8262
0
            HGOTO_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "cannot flush indexed storage buffer");
8263
8264
    /* Set addr & size for when dset is not written or queried chunk is not found */
8265
0
    if (addr)
8266
0
        *addr = HADDR_UNDEF;
8267
0
    if (size)
8268
0
        *size = 0;
8269
8270
    /* Compose chunked index info struct */
8271
0
    idx_info.f      = dset->oloc.file;
8272
0
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
8273
0
    idx_info.layout = &dset->shared->layout;
8274
8275
    /* If the dataset is not written, return without errors */
8276
0
    if (H5_addr_defined(idx_info.layout->storage.u.chunk.idx_addr)) {
8277
8278
0
        H5D_chunk_info_iter_ud_t udata;
8279
8280
        /* Calculate the scaled of this chunk */
8281
0
        H5VM_chunk_scaled(dset->shared->ndims, offset, layout->u.chunk.dim, udata.scaled);
8282
0
        udata.scaled[dset->shared->ndims] = 0;
8283
8284
        /* Initialize before iteration */
8285
0
        udata.ndims       = dset->shared->ndims;
8286
0
        udata.nbytes      = 0;
8287
0
        udata.filter_mask = 0;
8288
0
        udata.chunk_addr  = HADDR_UNDEF;
8289
0
        udata.found       = false;
8290
8291
        /* Iterate over the allocated chunks to find the requested chunk */
8292
0
        if ((dset->shared->layout.storage.u.chunk.ops->iterate)(&idx_info, H5D__get_chunk_info_by_coord_cb,
8293
0
                                                                &udata) < 0)
8294
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL,
8295
0
                        "unable to retrieve information of the chunk by its scaled coordinates");
8296
8297
        /* Obtain requested info if the chunk is found */
8298
0
        if (udata.found) {
8299
0
            if (filter_mask)
8300
0
                *filter_mask = udata.filter_mask;
8301
0
            if (addr)
8302
0
                *addr = udata.chunk_addr + H5F_BASE_ADDR(dset->oloc.file);
8303
0
            if (size)
8304
0
                *size = udata.nbytes;
8305
0
        }
8306
0
    }
8307
8308
0
done:
8309
0
    FUNC_LEAVE_NOAPI_TAG(ret_value)
8310
0
} /* end H5D__get_chunk_info_by_coord() */
8311
8312
/*-------------------------------------------------------------------------
8313
 * Function:    H5D__chunk_iter_cb
8314
 *
8315
 * Purpose:     Call the user-defined function with the chunk data. The
8316
 *              iterator continues if the user-defined function returns
8317
 *              H5_ITER_CONT, and stops if H5_ITER_STOP is returned.
8318
 *
8319
 * Return:      Success:    H5_ITER_CONT or H5_ITER_STOP
8320
 *              Failure:    Negative (H5_ITER_ERROR)
8321
 *-------------------------------------------------------------------------
8322
 */
8323
static int
8324
H5D__chunk_iter_cb(const H5D_chunk_rec_t *chunk_rec, void *udata)
8325
0
{
8326
0
    const H5D_chunk_iter_ud_t *data  = (H5D_chunk_iter_ud_t *)udata;
8327
0
    const H5O_layout_chunk_t  *chunk = data->chunk;
8328
0
    hsize_t                    offset[H5O_LAYOUT_NDIMS];
8329
0
    int                        ret_value = H5_ITER_CONT;
8330
8331
0
    FUNC_ENTER_PACKAGE_NOERR
8332
8333
    /* Similar to H5D__get_chunk_info */
8334
0
    for (unsigned i = 0; i < chunk->ndims; i++)
8335
0
        offset[i] = chunk_rec->scaled[i] * chunk->dim[i];
8336
8337
    /* Prepare & restore library for user callback */
8338
0
    H5_BEFORE_USER_CB_NOERR(FAIL)
8339
0
        {
8340
0
            ret_value = (data->op)(offset, (unsigned)chunk_rec->filter_mask,
8341
0
                                   data->base_addr + chunk_rec->chunk_addr, chunk_rec->nbytes, data->op_data);
8342
0
        }
8343
0
    H5_AFTER_USER_CB_NOERR(FAIL)
8344
8345
    /* Check for callback failure and pass along return value */
8346
0
    if (ret_value < 0)
8347
0
        HERROR(H5E_DATASET, H5E_CANTNEXT, "iteration operator failed");
8348
8349
0
    FUNC_LEAVE_NOAPI(ret_value)
8350
0
} /* end H5D__chunk_iter_cb */
8351
8352
/*-------------------------------------------------------------------------
8353
 * Function:    H5D__chunk_iter
8354
 *
8355
 * Purpose:     Iterate over all the chunks in the dataset with given callback
8356
 *
8357
 * Return:      SUCCEED/FAIL
8358
 *-------------------------------------------------------------------------
8359
 */
8360
herr_t
8361
H5D__chunk_iter(H5D_t *dset, H5D_chunk_iter_op_t op, void *op_data)
8362
0
{
8363
0
    const H5D_rdcc_t  *rdcc   = NULL;       /* Raw data chunk cache */
8364
0
    H5O_layout_t      *layout = NULL;       /* Dataset layout */
8365
0
    H5D_rdcc_ent_t    *ent;                 /* Cache entry index */
8366
0
    H5D_chk_idx_info_t idx_info;            /* Chunked index info */
8367
0
    herr_t             ret_value = SUCCEED; /* Return value */
8368
8369
0
    FUNC_ENTER_PACKAGE_TAG(dset->oloc.addr)
8370
8371
    /* Check args */
8372
0
    assert(dset);
8373
0
    assert(dset->shared);
8374
8375
    /* Get dataset layout and raw data chunk cache */
8376
0
    layout = &(dset->shared->layout);
8377
0
    rdcc   = &(dset->shared->cache.chunk);
8378
0
    assert(layout);
8379
0
    assert(rdcc);
8380
0
    assert(H5D_CHUNKED == layout->type);
8381
8382
    /* Search for cached chunks that haven't been written out */
8383
0
    for (ent = rdcc->head; ent; ent = ent->next)
8384
        /* Flush the chunk out to disk, to make certain the size is correct later */
8385
0
        if (H5D__chunk_flush_entry(dset, ent, false) < 0)
8386
0
            HGOTO_ERROR(H5E_DATASET, H5E_CANTFLUSH, FAIL, "cannot flush indexed storage buffer");
8387
8388
    /* Compose chunked index info struct */
8389
0
    idx_info.f      = dset->oloc.file;
8390
0
    idx_info.pline  = &dset->shared->dcpl_cache.pline;
8391
0
    idx_info.layout = layout;
8392
8393
    /* If the dataset is not written, return without errors */
8394
0
    if (H5_addr_defined(idx_info.layout->storage.u.chunk.idx_addr)) {
8395
0
        H5D_chunk_iter_ud_t ud;
8396
8397
        /* Set up info for iteration callback */
8398
0
        ud.op        = op;
8399
0
        ud.op_data   = op_data;
8400
0
        ud.chunk     = &dset->shared->layout.u.chunk;
8401
0
        ud.base_addr = H5F_BASE_ADDR(dset->oloc.file);
8402
8403
        /* Iterate over the allocated chunks calling the iterator callback */
8404
0
        if ((ret_value = (layout->storage.u.chunk.ops->iterate)(&idx_info, H5D__chunk_iter_cb, &ud)) < 0)
8405
0
            HERROR(H5E_DATASET, H5E_CANTNEXT, "chunk iteration failed");
8406
0
    }
8407
8408
0
done:
8409
0
    FUNC_LEAVE_NOAPI_TAG(ret_value)
8410
0
} /* end H5D__chunk_iter() */
8411
8412
/*-------------------------------------------------------------------------
8413
 * Function:    H5D__chunk_get_offset_copy
8414
 *
8415
 * Purpose:     Copies an offset buffer and performs bounds checks on the
8416
 *              values.
8417
 *
8418
 *              This helper function ensures that the offset buffer given
8419
 *              by the user is suitable for use with the rest of the library.
8420
 *
8421
 * Return:      SUCCEED/FAIL
8422
 *
8423
 *-------------------------------------------------------------------------
8424
 */
8425
herr_t
8426
H5D__chunk_get_offset_copy(const H5D_t *dset, const hsize_t *offset, hsize_t *offset_copy)
8427
0
{
8428
0
    unsigned u;
8429
0
    herr_t   ret_value = SUCCEED; /* Return value */
8430
8431
0
    FUNC_ENTER_PACKAGE
8432
8433
0
    assert(dset);
8434
0
    assert(offset);
8435
0
    assert(offset_copy);
8436
8437
    /* The library's chunking code requires the offset to terminate with a zero.
8438
     * So transfer the offset array to an internal offset array that we
8439
     * can properly terminate (handled via the memset call).
8440
     */
8441
0
    memset(offset_copy, 0, H5O_LAYOUT_NDIMS * sizeof(hsize_t));
8442
8443
0
    for (u = 0; u < dset->shared->ndims; u++) {
8444
        /* Make sure the offset doesn't exceed the dataset's dimensions */
8445
0
        if (offset[u] > dset->shared->curr_dims[u])
8446
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "offset exceeds dimensions of dataset");
8447
8448
        /* Make sure the offset fall right on a chunk's boundary */
8449
0
        if (offset[u] % dset->shared->layout.u.chunk.dim[u])
8450
0
            HGOTO_ERROR(H5E_DATASET, H5E_BADVALUE, FAIL, "offset doesn't fall on chunks's boundary");
8451
8452
0
        offset_copy[u] = offset[u];
8453
0
    }
8454
8455
0
done:
8456
0
    FUNC_LEAVE_NOAPI(ret_value)
8457
0
} /* end H5D__chunk_get_offset_copy() */