Исходный код СУБД 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
/*-------------------------------------------------------------------------
 * cfs_smgr.h
 *    Compressed File Store (CFS) — Storage Manager integration layer
 *.
 *
 * This is the first integration layer between the autonomous CFS storage
 * engine  and PostgreSQL's storage manager (smgr.c / md.c).
 *
 * Responsibilities :
 *
 *   * Track per-SMgrRelation CFS state: is the relation fork compressed,
 *     and, if so, the resolved effective policy plus a lazily-opened
 *     CfsRelation handle.
 *
 *   * Provide a locator-level predicate RelFileLocatorUsesCfs() so that
 *     auxiliary processes (checkpointer, bgwriter) — which obtain an
 *     SMgrRelation via smgropen() rather than the relcache — can decide
 *     whether a fork is compressed.  The effective policy is published
 *     into shared memory by RelationGetSmgr() and read back here.
 *
 *   * Bridge every relevant smgr operation to the CFS storage layer
 *     table: read, write, extend, zero-extend, truncate, nblocks, create,
 *     unlink, immedsync.
 *
 * Only MAIN_FORKNUM is ever compressed; FSM, visibility-map and init forks
 * keep using the regular md path unchanged.
 *
 * Copyright (c) 2026, Kirillov Vyacheslav, QDB Development Group
 *
 * IDENTIFICATION
 *    src/include/storage/cfs/cfs_smgr.h
 *
 *-------------------------------------------------------------------------
 */
#ifndef CFS_SMGR_H
#define CFS_SMGR_H
 
#include "postgres.h"
 
#include "catalog/storage_xlog.h"
#include "common/relpath.h"
#include "storage/aio_types.h"
#include "storage/block.h"
#include "storage/cfs/cfs_rel.h"
#include "storage/cfs/cfs_storage.h"
#include "storage/relfilelocator.h"
#include "storage/smgr.h"
#include "storage/sync.h"
 
/* The file-tag helpers and the sync-queue API moved to cfs_sync.h. */
#include "storage/cfs/cfs_sync.h"
 
/* ----------------------------------------------------------------
 * CfsSmgrState — backend-local CFS state attached to an SMgrRelation.
 *
 * One SMgrRelation needs at most a single state because CFS only ever
 * applies to MAIN_FORKNUM.  The state is allocated lazily on first
 * resolution and freed when the SMgrRelation is destroyed.
 * ---------------------------------------------------------------- */
typedef struct CfsSmgrState
{
    RelFileLocatorBackend rlocator; /* copied from the owning SMgrRelation  */
    CfsEffectiveOptions opts;   /* resolved effective policy                */
    bool        is_cfs;         /* fork is served by CFS                    */
    bool        opts_valid;     /* 'opts' has been resolved                 */
    bool        cfs_resolved;   /* is_cfs decision is final (see below)     */
    bool        cfs_pinned;     /* metadata slot is pinned (append lock)    */
    bool        fallback_warned;    /* fallback-codec WARNING raised once per
                                     * SMgrRelation (see
                                     * cfs_warn_fallback_codec)         */
    uint64      policy_gen;     /* shared-memory policy generation that 'opts'
                                 * reflects; re-checked on every resolve so
                                 * that an ALTER ... SET (level /
                                 * min_gain_bytes) propagates to processes
                                 * that never re-open the relation through the
                                 * relcache (checkpointer, bgwriter)    */
    CfsRelation *cfs;           /* lazily-opened sidecar handle (or NULL)   */
} CfsSmgrState;
 
/*
 * cfs_resolved vs opts_valid
 *
 *   opts_valid     — the full effective policy (algorithm / level /
 *                    min_gain_bytes) is known, either from the relcache
 *                    (cfs_open_relation_smgr) or from the shared-memory policy cache.
 *                    The write path uses opts.algorithm when this is true;
 *                    otherwise it falls back to a built-in default codec
 *                    (see cfs_smgr_write_opts).
 *
 *   cfs_resolved   — the is_cfs decision itself has been made and will not
 *                    change for the lifetime of this SMgrRelation.  This is
 *                    a strictly weaker condition than opts_valid: during
 *                    crash recovery / hot standby replay the relcache is not
 *                    available, so the effective algorithm/level cannot be
 *                    resolved, but is_cfs CAN be decided (from shared memory
 *                    or from sidecar file existence) and — crucially — must
 *                    be decided only ONCE.
 *
 * cfs_smgr_ensure_state() uses cfs_resolved as its idempotency guard so that
 * subsequent calls (including those reaching it from inside a WAL-redo
 * critical section via smgriscfsenabled()) do not re-run the sidecar
 * existence check and its pallocs (cfs_make_filename / psprintf).  Re-running
 * that work inside START_CRIT_SECTION() trips the palloc assertion
 * (CritSectionCount == 0) — the C6 defect.
 *
 * Note that only the is_cfs decision is frozen: the effective policy
 * (level / min_gain_bytes) is REFRESHED whenever the shared-memory policy
 * generation moves past state->policy_gen.  The refresh is palloc-free
 * (a shared-memory read), so it is safe inside critical sections.
 */
 
 
/* ----------------------------------------------------------------
 * Lifecycle
 * ---------------------------------------------------------------- */
 
extern void CfsSmgrInit(void);
 
/* Ensure 'reln' has a CfsSmgrState and that is_cfs / opts are resolved. */
extern void cfs_smgr_ensure_state(SMgrRelation reln);
 
/* Close the CfsRelation handle (if any) for a fork. */
extern void cfs_smgr_close(SMgrRelation reln, ForkNumber forknum);
 
/* Close all CFS handles and free the state attached to 'reln'. */
extern void cfs_smgr_release(SMgrRelation reln);
 
/*
 * cfs_default_write_opts — fill 'opts' with the built-in default write
 * policy: the first available codec, with level and minimum gain left
 * unset (0 sentinel, set-flags cleared).  This is the single source of
 * the fallback used when no effective relation policy has been published
 * (recovery, database copy with a cold policy cache); consumers resolve
 * the unset fields from their own GUCs at write time.  Exposed so the
 * test module can assert that a fallback carries no GUC-derived values.
 */
extern void cfs_default_write_opts(CfsEffectiveOptions *opts);
 
/* Resolve policy before attaching a relation's SMgr handle. */
extern SMgrRelation cfs_open_relation_smgr(Relation rel);
 
/* Resolve the source snapshot before creating destination storage. */
extern SMgrRelation cfs_prepare_copy_policy(Relation rel,
                                          CfsEffectiveOptions *opts);
 
/*
 * cfs_wal_log_new_relation_policy — emit an XLOG_SMGR_CFS_POLICY record for
 * a freshly created relation, so that WAL redo learns the relation's CFS
 * policy before the first data record for it replays (during redo there is
 * no relcache entry to resolve reloptions from).
 */
extern void cfs_wal_log_new_relation_policy(Relation rel,
                                            const CfsEffectiveOptions *opts);
 
/*
 * cfs_wal_log_new_table_policy / cfs_wal_log_new_index_policy — resolve the
 * effective CFS policy from the raw reloptions datum of a freshly created
 * heap-like relation / index (the local relcache entry has no rd_options
 * yet) and WAL-log it.  Called from heap_create_with_catalog() and
 * index_create() respectively.
 */
extern void cfs_wal_log_new_table_policy(Relation rel, Datum reloptions);
extern void cfs_wal_log_new_index_policy(Relation heapRel, Relation indexRel,
                                         Datum reloptions);
 
/*
 * cfs_wal_log_rewrite_policy — emit an XLOG_SMGR_CFS_POLICY record for the
 * new relfilenumber of an in-place rewrite (TRUNCATE, REINDEX, VACUUM FULL /
 * CLUSTER index rebuild), which bypasses the relation-creation paths that
 * otherwise WAL-log the policy.  Called from RelationSetNewRelfilenumber().
 */
extern void cfs_wal_log_rewrite_policy(Relation rel,
                                       const RelFileLocator *newrlocator);
 
/*
 * cfs_smgr_publish_copy_policy — re-publish the relation's effective CFS
 * policy for the destination storage of the ALTER ... SET TABLESPACE copy
 * paths (heapam_relation_copy_data() / index_copy_data()), and WAL-log it
 * for redo.  Without this the copy would be written raw while reloptions
 * keep claiming the relation is compressed.
 */
extern void cfs_smgr_publish_copy_policy(SMgrRelation dstrel,
                                         const CfsEffectiveOptions *opts,
                                         char relpersistence);
 
/*
 * cfs_smgr_publish_db_copy_policy — publish the source relation's effective
 * CFS policy for the destination storage of the CREATE DATABASE ...
 * STRATEGY WAL_LOG copy path (no relcache entry is available for either
 * database there), and WAL-log it for redo.  Without this the copy would be
 * written into the raw base file while pg_class.reloptions keep claiming
 * the relation is compressed, making the copy read as empty until a
 * checkpoint.
 */
extern void cfs_smgr_publish_db_copy_policy(SMgrRelation srcrel,
                                            SMgrRelation dstrel);
 
/*
 * cfs_smgr_wal_policy_redo — redo of an XLOG_SMGR_CFS_POLICY record:
 * publish the relation's CFS policy into shared memory, create the sidecar
 * files eagerly (a durable CFS marker that survives standby restarts) and
 * correct the CfsSmgrState of the SMgrRelation if it is already open in
 * this process (the WAL prefetcher may have frozen an is_cfs=false
 * decision before this record replayed).
 */
extern void cfs_smgr_wal_policy_redo(const xl_smgr_cfs_policy *xlrec);
 
 
/* ----------------------------------------------------------------
 * Predicates
 * ---------------------------------------------------------------- */
 
/*
 * smgriscfsenabled — true when the fork of 'reln' is stored compressed.
 * Resolves the CfsSmgrState on demand.  Never errors: returns false for any
 * non-CFS or unsupported fork.
 */
extern bool smgriscfsenabled(SMgrRelation reln, ForkNumber forknum);
 
/*
 * RelFileLocatorUsesCfs — locator-level predicate usable without an
 * SMgrRelation (e.g. during unlink).  Consults shared memory and, as a
 * fall-back, sidecar file existence.
 */
extern bool RelFileLocatorUsesCfs(RelFileLocatorBackend rlocator,
                                  ForkNumber forknum);
 
/*
 * cfs_smgr_get_handle — return the lazily-opened CfsRelation for 'reln',
 * opening the sidecars (with journal replay) on first access.  The handle is
 * cached in the CfsSmgrState and closed by cfs_smgr_close().
 */
extern CfsRelation *cfs_smgr_get_handle(SMgrRelation reln);
 
/*
 * cfs_smgr_resolve_physical — override the SMgrRelation's CFS-ness to match
 * the physical reality (sidecar file existence), ignoring the current
 * reloptions.  Used during table rewrite (VACUUM FULL / CLUSTER / ALTER
 * TABLE SET algorithm) where the old heap's reloptions have already been
 * updated but its physical storage is still in the old format.
 */
extern void cfs_smgr_resolve_physical(SMgrRelation reln);
 
 
/* ----------------------------------------------------------------
 * smgr operation bridges
 *
 * Each bridge is invoked by the corresponding smgr.c public function when
 * CFS is enabled for the fork.  They call the cfs_* functions directly
 * the storage layer directly) so the implementation stays swappable.
 * ---------------------------------------------------------------- */
 
/* Create the sidecar files for a relation fork (after md created the base). */
extern void cfs_smgr_create(SMgrRelation reln, ForkNumber forknum, bool isRedo);
 
/* Remove the sidecar files for a relation fork. */
extern void cfs_smgr_unlink(RelFileLocatorBackend rlocator,
                            ForkNumber forknum, bool isRedo);
 
/* Append one compressed page to the .cfp and update the map (extension). */
extern void cfs_smgr_extend(SMgrRelation reln, ForkNumber forknum,
                            BlockNumber blocknum, const void *buffer,
                            bool skipFsync);
 
/* Extend the logical map by zero blocks. */
extern void cfs_smgr_zeroextend(SMgrRelation reln, ForkNumber forknum,
                                BlockNumber blocknum, int nblocks,
                                bool skipFsync);
 
/* Read one or more logical blocks, decompressing each from the .cfp. */
extern void cfs_smgr_readv(SMgrRelation reln, ForkNumber forknum,
                           BlockNumber blocknum, void **buffers,
                           BlockNumber nblocks);
 
/*
 * cfs_smgr_startreadv — AIO-compatible read entry point.  CFS pages cannot be
 * served by a raw pread() into the target buffers (they must be
 * decompressed), so by default the requested blocks are read
 * synchronously and the AIO handle is completed inline, guaranteeing
 * decompression happens in the originating backend.
 *
 * Since P4-2, an io_method=worker server with the read scratch arena
 * enabled (cfs_read_scratch_mb > 0) can instead offload the request: the
 * raw compressed span is preadv'd into a shared scratch slot by an IO
 * worker and the validate+decompress phase runs in the executor's
 * completion callback (aio_cfs_span_readv_cb).  The offload only covers
 * a request that is one whole contiguous span; everything else degrades
 * to the inline path, and the failure contract is identical on both.
 *
 * Read failures are NOT raised here: they are encoded into the inline IO
 * result (negative failure code, like md encodes errno) and the callbacks
 * below decode and report them, so the error reaches the consumer through
 * the standard AIO result path (see aio_cfs_readv_cb).
 */
extern void cfs_smgr_startreadv(PgAioHandle *ioh, SMgrRelation reln,
                                ForkNumber forknum, BlockNumber blocknum,
                                void **buffers, BlockNumber nblocks);
 
/*
 * AIO completion callbacks for cfs_smgr_startreadv().  complete_shared
 * mirrors aio_md_readv_cb: a negative result is turned into PGAIO_RS_ERROR
 * with the failure code in error_data and is immediately logged
 * (LOG_SERVER_ONLY); the ERROR itself is raised by the report callback,
 * which routes corruption through cfs_report_corruption (preserving the
 * cfs_checksum_failure GUC semantics) and other failures through a plain
 * "could not read block" error.
 */
extern const PgAioHandleCallbacks aio_cfs_readv_cb;
 
/*
 * AIO completion callbacks for the OFFLOADED span variant (P4-2): the
 * raw preadv ran in the executor (usually an IO worker) and filled the
 * shared scratch slot, so complete_shared validates+decompresses every
 * planned record into its target buffer and releases the slot; the
 * report callback is the owner-backend twin of aio_cfs_readv_cb's.
 * Separate from aio_cfs_readv_cb because the report callback receives
 * only the target data union and must know which member is live.
 */
extern const PgAioHandleCallbacks aio_cfs_span_readv_cb;
 
/*
 * cfs_smgr_maxcombine — the advisory length of the physically contiguous
 * .cfp run starting at blocknum (see cfs_map_contiguous_run): neighbouring
 * logical blocks are combined into one IO only when their compressed
 * records are physically adjacent in one segment (compacted or freshly
 * loaded relations); otherwise the answer is 1 and every block is read
 * individually.  The read entry points never rely on the exact value.
 */
extern uint32 cfs_smgr_maxcombine(SMgrRelation reln, ForkNumber forknum,
                                  BlockNumber blocknum);
 
/*
 * cfs_smgr_prefetch — advise the OS to read the .cfp ranges backing
 * [blocknum, blocknum + nblocks) into the page cache
 * (posix_fadvise(POSIX_FADV_WILLNEED); a no-op that just returns true on
 * platforms without it).  Purely advisory: it changes neither the read nor
 * the write route and never fails the caller — CFS reads stay synchronous
 * (decompression cannot be deferred), the advice only warms the page cache
 * they read from.  The sidecar pair is opened read-only through a quiet
 * catch, so the hint never raises (it runs from background processes
 * inside the smgr dispatcher's HOLD_INTERRUPTS) and never materializes
 * anything on disk.  Returns false only while in recovery when no sidecar
 * pair can be opened (the smgrprefetch contract: a missing file presumed
 * dropped by a later WAL record); every other miss (non-resident map
 * segment, stale generation after compaction, unopenable segment, failed
 * advice) is silently skipped.
 */
extern bool cfs_smgr_prefetch(SMgrRelation reln, ForkNumber forknum,
                              BlockNumber blocknum, int nblocks);
 
/*
 * cfs_smgr_writeback — ask the kernel to start writeback of the dirty .cfp
 * ranges backing [blocknum, blocknum + nblocks)
 * (sync_file_range(SYNC_FILE_RANGE_WRITE); a no-op outside Linux).  The
 * .cfp counterpart of mdwriteback: a scheduling hint without any fsync
 * semantics — the durability contract stays with the checkpoint's CFS sync
 * path — and it never errors out (the buffer manager issues it as a
 * best-effort hint; the sidecar pair is opened read-only through the same
 * quiet catch as cfs_smgr_prefetch).  A missing or unopenable sidecar pair
 * — e.g. a relation dropped after its buffers were scheduled — is quietly
 * skipped, and no file is ever created.
 */
extern void cfs_smgr_writeback(SMgrRelation reln, ForkNumber forknum,
                               BlockNumber blocknum, BlockNumber nblocks);
 
/* Write (overwrite) one or more logical blocks, compressing each. */
extern void cfs_smgr_writev(SMgrRelation reln, ForkNumber forknum,
                            BlockNumber blocknum, const void **buffers,
                            BlockNumber nblocks, bool skipFsync);
 
/* Return the logical block count (from the map / shared cache). */
extern BlockNumber cfs_smgr_nblocks(SMgrRelation reln, ForkNumber forknum);
 
/* Truncate the relation to 'nblocks' logical blocks. */
extern void cfs_smgr_truncate(SMgrRelation reln, ForkNumber forknum,
                              BlockNumber nblocks);
 
/*
 * cfs_smgr_register_sync — register the sidecar files for the next
 * checkpoint sync (used by smgrregistersync, the end-of-bulk-write
 * counterpart of the skipFsync writes).
 */
extern void cfs_smgr_register_sync(SMgrRelation reln, ForkNumber forknum);
 
/* fsync the sidecar files (used by smgrimmedsync). */
extern void cfs_smgr_immedsync(SMgrRelation reln, ForkNumber forknum);
 
 
/*
 * Test observability: number of throwaway full-map handles opened
 * cluster-wide (the checkpoint opens its handle in the checkpointer, so a
 * per-process count could not be observed from a backend).  With
 * cfs_map_memory=0 the size and immediate-sync paths reuse the persistent
 * smgr handle, so the counter must not advance.
 */
extern uint64 cfs_smgr_full_map_open_count(void);
 
/*
 * The throwaway pinned-handle pairs: open a handle (full or lazy, see
 * below) and pin it in the shared map cache; cfs_close_full_unpinned()
 * closes either and drops the pin.  'required' selects the failure
 * contract - the sizing and immediate-sync users of the full variant
 * raise (the relation must be readable); the checkpoint (the lazy
 * variant) may find the sidecars gone between listing a dirty slot and
 * opening them, passes false and skips the relation on NULL.  Always
 * paired in PG_FINALLY.
 */
extern CfsRelation *cfs_open_full_pinned(RelFileLocatorBackend rl,
                                         ForkNumber forknum, bool required);
 
/*
 * The lazy variant: descriptors and the map prologue only, no private
 * map array.  The checkpoint uses it: its fold reads the journal and
 * rewrites exactly the rows the journal names, straight through the
 * file descriptor, so it must not pay a full-map load whose cost tracks
 * the table instead of the journal.  CFS_OPEN_LAZY_MAP is safe here even
 * with the segment pool off (cfs_map_memory=0), because nothing on the
 * checkpoint path ever resolves a block through the map.
 */
extern CfsRelation *cfs_open_lazy_pinned(RelFileLocatorBackend rl,
                                         ForkNumber forknum, bool required);
extern void cfs_close_full_unpinned(CfsRelation *cfs,
                                    RelFileLocatorBackend rl,
                                    ForkNumber forknum);
 
#endif                          /* CFS_SMGR_H */