Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/*-------------------------------------------------------------------------
 * cfs_map_file.c
 *    Compressed File Store (CFS) — the .cfsmap file, one module.
 *
 * Every read and write of the .cfsmap sidecar goes through this file:
 * the 8-byte prologue (ensure / read), positional row reads with the
 * shared row-classification contract, the physical resize and the two
 * snapshot writers (raw descriptor and durable path variant).  See
 * cfs_map_file.h for the contracts; handle-level state (capacity,
 * watermark, cfp EOF) is assembled by cfs_storage.c on top of these
 * primitives.
 *
 * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
 *
 * IDENTIFICATION
 *    src/backend/storage/cfs/cfs_map_file.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"
 
#include <unistd.h>
 
#include "access/xlogutils.h"
#include "storage/cfs/cfs_format.h"
#include "storage/cfs/cfs_map_file.h"
#include "storage/cfs/cfs_recovery.h"
#include "storage/cfs/cfs_storage.h"
#include "storage/fd.h"
#include "utils/injection_point.h"
#include "utils/palloc.h"
#include "utils/wait_event.h"
 
int
cfs_map_file_prologue_ensure(int fd)
{
    CfsMapPrologue prologue;
    off_t       size;
 
    size = cfs_fd_size(fd);
    if (size < 0)
        return CFS_STORAGE_ERROR;
    if (size >= (off_t) sizeof(prologue))
        return CFS_STORAGE_OK;
    if (size > 0)
        return CFS_STORAGE_CORRUPT;
 
    cfs_map_prologue_init(&prologue);
    if (cfs_pwrite_all(fd, &prologue, sizeof(prologue), 0) != CFS_STORAGE_OK)
        return CFS_STORAGE_ERROR;
    return CFS_STORAGE_OK;
}
 
int
cfs_map_file_prologue_check(int fd, uint64 *nblocks)
{
    CfsMapPrologue prologue;
    off_t       map_size;
    int         rc;
 
    map_size = cfs_fd_size(fd);
    if (map_size < 0)
        return CFS_STORAGE_ERROR;
    if (map_size == 0)
    {
        *nblocks = 0;
        return CFS_STORAGE_NOENT;
    }
    if (map_size < (off_t) sizeof(prologue))
        return CFS_STORAGE_CORRUPT;
 
    rc = cfs_pread_all(fd, &prologue, sizeof(prologue), 0);
    if (rc != CFS_STORAGE_OK)
        return CFS_STORAGE_ERROR;
    if (cfs_map_prologue_validate(&prologue) != CFS_FORMAT_OK)
        return CFS_STORAGE_CORRUPT;
 
    *nblocks = cfs_map_rows_from_size((uint64) map_size);
    return CFS_STORAGE_OK;
}
 
int
cfs_map_file_prologue_read_fd(int fd, const char *path,
                              RelFileLocatorBackend rlocator,
                              ForkNumber forknum, uint64 *nblocks)
{
    int         rc;
 
    rc = cfs_map_file_prologue_check(fd, nblocks);
    if (rc != CFS_STORAGE_CORRUPT)
        return rc;
 
    /*
     * CFS_STORAGE_CORRUPT: the single corruption policy point every
     * loader shares (no fallback source exists).  Outside a normal
     * backend session (recovery, standby, auxiliary processes) a corrupt
     * prologue is a hard ERROR exactly as before: startup cannot even
     * size the map and must not come up on it.  In a normal backend the
     * damage goes through cfs_report_corruption(), so the
     * cfs_checksum_failure GUC decides ERROR or PANIC instead of the
     * hard-wired ERROR (see cfs_corruption_guc_applies()).
     */
    if (cfs_fd_size(fd) < (off_t) sizeof(CfsMapPrologue))
    {
        if (!cfs_corruption_guc_applies())
            ereport(ERROR,
                    (errcode(ERRCODE_DATA_CORRUPTED),
                     errmsg("CFS: corrupt page map snapshot"),
                     errdetail("File \"%s\" is shorter than its 8-byte "
                               "header.", path)));
        else
            cfs_report_corruption(rlocator, forknum, InvalidBlockNumber,
                                  psprintf("file \"%s\" is shorter than "
                                           "its 8-byte header", path),
                                  false);
    }
    else
    {
        if (!cfs_corruption_guc_applies())
            ereport(ERROR,
                    (errcode(ERRCODE_DATA_CORRUPTED),
                     errmsg("CFS: corrupt page map snapshot"),
                     errdetail("Invalid .cfsmap header in \"%s\".",
                               path)));
        else
            cfs_report_corruption(rlocator, forknum, InvalidBlockNumber,
                                  psprintf("invalid .cfsmap header in "
                                           "file \"%s\"", path),
                                  false);
    }
    return CFS_STORAGE_ERROR;   /* keep the compiler happy */
}
 
int
cfs_map_file_prologue_read(CfsRelation *cfs, uint64 *nblocks)
{
    return cfs_map_file_prologue_read_fd(cfs->map_fd, cfs->map_path,
                                         cfs->rlocator, cfs->forknum,
                                         nblocks);
}
 
int
cfs_map_file_read_range(int fd, uint64 first_block, uint64 nblocks,
                        CfsMapEntry *rows, char **corrupt_mask,
                        uint64 corrupt_mask_len)
{
    uint64      i;
 
    if (nblocks == 0)
        return CFS_STORAGE_OK;
 
    if (cfs_pread_all(fd, rows, (size_t) nblocks * CFS_MAP_ENTRY_SIZE,
                      cfs_map_row_off(first_block)) != CFS_STORAGE_OK)
        return CFS_STORAGE_ERROR;
 
    for (i = 0; i < nblocks; i++)
    {
        CfsMapEntry *e = &rows[i];
 
        switch (cfs_map_row_classify(e, false, NULL))
        {
            case CFS_MAP_ROW_VALID:
                break;
            case CFS_MAP_ROW_HOLE:
 
                /*
                 * A sparse hole of a never-written block reads as INVALID: a
                 * CRC-valid entry with the invalid offset.
                 */
                cfs_map_entry_init(e);
                break;
            case CFS_MAP_ROW_CORRUPT:
 
                /*
                 * INVALID now, healed by a covering journal record; the mask
                 * remembers the block for that check.  It is allocated only
                 * when there is something to remember: a healthy load of a
                 * terabyte map must not palloc a hundred megabytes for a mask
                 * it never touches.
                 */
                cfs_map_entry_init(e);
                if (i < corrupt_mask_len)
                {
                    if (*corrupt_mask == NULL)
                        *corrupt_mask = palloc0(corrupt_mask_len);
                    (*corrupt_mask)[i] = 1;
                }
                break;
        }
    }
    return CFS_STORAGE_OK;
}
 
/*
 * Chunk of rows read per pread.  Stack-sized and fixed: the truncate path
 * calls this inside the smgr critical section, where palloc is forbidden
 * (and a VLA would be illegal C for this tree anyway).
 */
#define CFS_MAP_RANGE_LIVE_CHUNK 256
 
int
cfs_map_file_range_live_bytes(int fd, uint64 first_block,
                              uint64 nblocks, uint64 *live_bytes,
                              uint64 *live_pages)
{
    CfsMapEntry rows[CFS_MAP_RANGE_LIVE_CHUNK];
    uint64      bytes = 0;
    uint64      pages = 0;
    uint64      done = 0;
 
    if (nblocks == 0)
    {
        if (live_bytes != NULL)
            *live_bytes = 0;
        if (live_pages != NULL)
            *live_pages = 0;
        return CFS_STORAGE_OK;
    }
 
    while (done < nblocks)
    {
        uint64      chunk = Min(nblocks - done,
                                (uint64) CFS_MAP_RANGE_LIVE_CHUNK);
        uint64      i;
 
        if (cfs_map_file_read_range(fd, first_block + done, chunk, rows,
                                    NULL, 0) != CFS_STORAGE_OK)
            return CFS_STORAGE_ERROR;
        for (i = 0; i < chunk; i++)
        {
            if (CFS_MAP_ENTRY_VALID(&rows[i]))
            {
                bytes += CFS_RECORD_SIZE(rows[i].compressed_size);
                pages++;
            }
        }
        done += chunk;
    }
    if (live_bytes != NULL)
        *live_bytes = bytes;
    if (live_pages != NULL)
        *live_pages = pages;
    return CFS_STORAGE_OK;
}
 
void
cfs_map_range_iter_init(CfsMapRangeIter *it, int fd, uint64 nblocks)
{
    it->fd = fd;
    it->nblocks = nblocks;
    it->next_block = 0;
    it->buf = palloc(CFS_MAP_RANGE_CHUNK_ENTRIES * CFS_MAP_ENTRY_SIZE);
    it->buflen = 0;
    it->bufpos = 0;
    it->truncated = false;
}
 
bool
cfs_map_range_iter_next(CfsMapRangeIter *it, uint64 *blocknum,
                        const CfsMapEntry **row)
{
    if (it->bufpos >= it->buflen)
    {
        uint64      remaining;
        size_t      want;
        off_t       off;
        ssize_t     got;
 
        if (it->truncated || it->next_block >= it->nblocks)
            return false;
 
        remaining = it->nblocks - it->next_block;
        want = (size_t) Min(remaining, CFS_MAP_RANGE_CHUNK_ENTRIES) *
            CFS_MAP_ENTRY_SIZE;
        off = cfs_map_row_off(it->next_block);
        do
        {
            got = pg_pread(it->fd, it->buf, want, off);
        } while (got < 0 && errno == EINTR);
 
        if (got < 0 || (size_t) got % CFS_MAP_ENTRY_SIZE != 0 ||
            got == 0)
        {
            it->truncated = true;
            return false;
        }
        it->buflen = (size_t) got / CFS_MAP_ENTRY_SIZE;
        it->bufpos = 0;
    }
 
    *blocknum = it->next_block++;
    *row = (const CfsMapEntry *) (it->buf + it->bufpos * CFS_MAP_ENTRY_SIZE);
    it->bufpos++;
    return true;
}
 
void
cfs_map_range_iter_free(CfsMapRangeIter *it)
{
    pfree(it->buf);
}
 
void
cfs_map_file_resize(CfsRelation *cfs, BlockNumber nblocks)
{
    off_t       map_size = cfs_map_file_size(nblocks);
    bool        resize_failed;
 
    Assert(cfs != NULL && !cfs->read_only);
    Assert(cfs->map_fd >= 0);
 
    /*
     * Test seam: cfs-fail-map-truncate simulates the ftruncate failure of the
     * checkpoint's RESIZE application, so t/500 can replay the crash-retry
     * window (the journal is preserved; the next checkpoint applies the
     * record again).  Without --enable-injection-points the check is a
     * compile-time false.
     */
    if (IS_INJECTION_POINT_ATTACHED("cfs-fail-map-truncate"))
    {
        errno = EIO;
        resize_failed = true;
    }
    else
        resize_failed = (ftruncate(cfs->map_fd, map_size) != 0);
 
    if (resize_failed)
        ereport(data_sync_elevel(ERROR),
                (errcode_for_file_access(),
                 errmsg("CFS: could not resize page map \"%s\": %m",
                        cfs->map_path)));
 
    pgstat_report_wait_start(WAIT_EVENT_CFS_FSYNC);
    if (pg_fsync(cfs->map_fd) != 0)
    {
        pgstat_report_wait_end();
        ereport(data_sync_elevel(ERROR),
                (errcode_for_file_access(),
                 errmsg("CFS: could not fsync page map \"%s\": %m",
                        cfs->map_path)));
    }
    pgstat_report_wait_end();
}
 
int
cfs_map_file_write_snapshot_fd(int fd, const char *path,
                               const CfsMapEntry *map, uint64 nblocks)
{
    CfsMapPrologue prologue;
 
    cfs_map_prologue_init(&prologue);
    if (cfs_pwrite_all(fd, &prologue, sizeof(prologue), 0) != CFS_STORAGE_OK)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not write page map snapshot header \"%s\"",
                        path)));
 
    if (nblocks > 0 &&
        cfs_pwrite_all(fd, map, (size_t) nblocks * CFS_MAP_ENTRY_SIZE,
                       CFS_MAP_HEADER_SIZE) != CFS_STORAGE_OK)
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not write page map snapshot entries \"%s\"",
                        path)));
 
    return CFS_STORAGE_OK;
}
 
int
cfs_map_file_write_snapshot_path(const char *path, const CfsMapEntry *map,
                                 uint64 nblocks)
{
    char       *tmp_path;
    int         fd;
 
    /*
     * Snapshot temps live in their own ".tmp" namespace: the compaction
     * candidate .cfsmap uses the distinct CFS_MAP_CANDIDATE_TMP_SUFFIX, so
     * a snapshot writer and a lock-free compaction copy phase can never
     * truncate or rename away each other's temp file (QDB-1514).  Every
     * caller of this helper holds the relation's append lock exclusively
     * around the write+rename; keep that contract when adding new ones.
     */
    tmp_path = psprintf("%s.tmp", path);
 
    ereport(DEBUG1,
            (errmsg("CFS: saving map snapshot: %llu blocks -> \"%s\"",
                    (unsigned long long) nblocks, tmp_path)));
 
    fd = BasicOpenFile(tmp_path, O_CREAT | O_RDWR | O_TRUNC | PG_BINARY);
    if (fd < 0)
    {
        pfree(tmp_path);
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not create snapshot temp file \"%s\": %m",
                        tmp_path)));
    }
 
    PG_TRY();
    {
        (void) cfs_map_file_write_snapshot_fd(fd, tmp_path, map, nblocks);
 
        if (pg_fsync(fd) != 0)
            ereport(data_sync_elevel(ERROR),
                    (errcode_for_file_access(),
                     errmsg("CFS: could not fsync snapshot temp file")));
    }
    PG_CATCH();
    {
        /* The temp file is garbage: drop it before propagating. */
        close(fd);
        unlink(tmp_path);
        pfree(tmp_path);
        PG_RE_THROW();
    }
    PG_END_TRY();
    close(fd);
 
    /* Atomic rename into place. */
    if (durable_rename(tmp_path, path, ERROR) != 0)
    {
        unlink(tmp_path);
        pfree(tmp_path);
        ereport(ERROR,
                (errcode_for_file_access(),
                 errmsg("CFS: could not rename snapshot to \"%s\"",
                        path)));
    }
 
    pfree(tmp_path);
    return CFS_STORAGE_OK;
}