/*-------------------------------------------------------------------------
|
* cfs.h
|
* Compressed File Store (CFS) — core constants, types, and on-disk
|
* structures for page-level transparent compression.
|
*
|
* Architecture overview
|
* ---------------------
|
* Shared buffers always hold *uncompressed* 8 kB pages — full compatibility
|
* with WAL, indices, locks, and every standard PostgreSQL mechanism is
|
* preserved.
|
*
|
* Compression happens at I/O boundaries:
|
* - Write path (FlushBuffer / smgrwrite): compress → append to .cfp file
|
* → update Page Map (.cfsmap)
|
* - Read path (smgrread) : look up Page Map → read compressed
|
* block → decompress → return 8 kB
|
*
|
* On-disk sidecar files (per relation fork):
|
* <relfileno>.cfp[.N] — append-only compressed data file, segmented
|
* at 1 GiB boundaries (see CFS_SEGMENT_SIZE)
|
* <relfileno>.cfsmap — Page Map: fixed-length array
|
* BlockNumber → CfsMapEntry
|
* <relfileno>.cfsjrn — journal for crash-safe Page Map updates
|
*
|
* This header is included by both backend server code and standalone
|
* utility programs (pg_cfs_check, etc.), so it must not pull in any
|
* server-only headers.
|
*
|
* Copyright (c) 2026, Kirillov Vyacheslav, QDB Development Group
|
*
|
* IDENTIFICATION
|
* src/include/storage/cfs/cfs.h
|
*
|
*-------------------------------------------------------------------------
|
*/
|
#ifndef CFS_H
|
#define CFS_H
|
|
#include <stdint.h>
|
#include <stddef.h>
|
|
#include "common/cfs_filename.h"
|
|
/* ----------------------------------------------------------------
|
* Fundamental constants
|
* ---------------------------------------------------------------- */
|
|
/*
|
* Magic number written in every CfsCompressedBlockHeader.
|
* Chosen so that an accidental read of a legacy file fails loudly.
|
*/
|
#define CFS_BLOCK_MAGIC UINT32_C(0xC0DEBA5E)
|
|
/* Current on-disk format version. Increment when the layout changes. */
|
#define CFS_FORMAT_VERSION UINT16_C(2)
|
|
/*
|
* Uncompressed PostgreSQL page size — must match BLCKSZ (8192 by default).
|
* We do not include pg_config.h here to keep this header self-contained;
|
* the C files that actually use BLCKSZ include postgres.h first.
|
*/
|
#define CFS_BLCKSZ 8192
|
|
/*
|
* Rows per shared block-map segment: the granularity of the shared map
|
* pool (defined here — the base header — because the journal's segment
|
* replay shares the constant with the pool).
|
*/
|
#define CFS_MAP_SEGMENT_BLOCKS 32768
|
|
/*
|
* Alignment of whole compressed records (header + payload) inside the
|
* .cfp file: like MAXALIGN'd WAL records, each record starts on an
|
* CFS_BLOCK_ALIGN boundary, so the tail padding of the previous record
|
* is always zero (see CFS_RECORD_SIZE).
|
*/
|
#define CFS_BLOCK_ALIGN 8
|
|
/*
|
* Reserved lead-in at the start of every .cfp file. Real compressed records
|
* are appended beginning at this offset, so a CfsMapEntry.physical_offset of 0
|
* unambiguously denotes an absent / never-written block (see
|
* CFS_ENTRY_INVALID_OFFSET). The storage layer must extend a freshly created
|
* .cfp to CFS_CFP_BASE_OFFSET bytes before appending the first record.
|
*/
|
#define CFS_CFP_BASE_OFFSET CFS_BLOCK_ALIGN
|
|
/*
|
* Content of the .cfp lead-in (exactly CFS_CFP_BASE_OFFSET bytes).
|
*
|
* 'epoch' is the file-creation timestamp (GetCurrentTimestamp()): it
|
* changes whenever the .cfp file is replaced — relation creation or a
|
* compaction swap — and never during append-only growth. Incremental
|
* backup uses it to prove that the .cfp listed in a prior backup manifest
|
* is the same append-only lifespan as the current file, so that the
|
* unchanged prefix needs not be copied again.
|
*
|
* A zero epoch means "unknown": a reader that cannot observe a meaningful
|
* epoch (unreadable or empty lead-in) must treat it as unknown and fall
|
* back to a full copy. The on-disk layout is unchanged by introducing
|
* this field: the lead-in was always reserved and never interpreted
|
* before.
|
*/
|
typedef struct CfsDataFileLeadIn
|
{
|
uint64 epoch; /* creation timestamp, 0 = unknown */
|
} CfsDataFileLeadIn;
|
|
/*
|
* .cfp segmentation.
|
*
|
* Like ordinary relation files, the .cfp data file is split into segments
|
* of RELSEG_SIZE * BLCKSZ bytes (1 GiB with the default 8 kB pages); the
|
* first segment is named "<relpath>.cfp", subsequent ones "<relpath>.cfp.N".
|
* This header must not include pg_config.h, so the segment size is stated
|
* as a literal and locked to RELSEG_SIZE * BLCKSZ by a StaticAssertDecl in
|
* cfs_storage.c.
|
*
|
* CfsMapEntry.physical_offset is a *global* byte offset across the whole
|
* segment chain: segment number = offset / CFS_SEGMENT_SIZE, in-segment
|
* offset = offset % CFS_SEGMENT_SIZE. Only segment 0 carries the
|
* CFS_CFP_BASE_OFFSET lead-in. A record never crosses a segment boundary:
|
* the append cursor is advanced to the next boundary when the record would
|
* not fit, leaving a short unwritten (zero) padding at the segment tail.
|
*
|
* Because offsets were always global, a .cfp written before segmentation
|
* was introduced needs no conversion: every offset in it is below
|
* CFS_SEGMENT_SIZE and therefore addresses segment 0.
|
*/
|
#define CFS_SEGMENT_SIZE UINT64_C(1073741824) /* 1 GiB */
|
#define CFS_CFP_SEGNO(off) ((uint32)((uint64)(off) / CFS_SEGMENT_SIZE))
|
#define CFS_CFP_SEG_OFF(off) ((off_t)((uint64)(off) % CFS_SEGMENT_SIZE))
|
|
/*
|
* Advance a .cfp append cursor past a segment boundary when a record of
|
* 'rec_size' bytes would not fit into the current segment. This is the
|
* single definition of the rollover rule, shared by the append path and
|
* by compaction (which rebuilds the chain with the same layout).
|
*/
|
static inline uint64
|
cfs_cfp_roll_offset(uint64 offset, uint64 rec_size)
|
{
|
if (offset % CFS_SEGMENT_SIZE + rec_size > CFS_SEGMENT_SIZE)
|
offset = (offset / CFS_SEGMENT_SIZE + 1) * CFS_SEGMENT_SIZE;
|
return offset;
|
}
|
|
/*
|
* Minimum gain in bytes that compression must achieve before we bother
|
* storing the compressed form. If (uncompressed_size - compressed_size)
|
* is less than this value, we store the page as RAW.
|
*
|
* Default: at least one 512-byte disk sector.
|
*/
|
#define CFS_MIN_GAIN_BYTES_DEFAULT 512
|
|
/*
|
* Compression level boundaries.
|
*
|
* The global maximum (22) covers the widest algorithm (Zstd). Each codec
|
* caps at its own native maximum; see CfsCodecMaxLevel() and the per-algorithm
|
* constants below. For Zstd the native maximum is a runtime value
|
* (ZSTD_maxCLevel()), so CFS_ZSTD_LEVEL_MAX is only the format's upper bound
|
* and CfsCodecMaxLevel() reports the actual library ceiling. The reloption
|
* "level" uses the global range, and the cross-field validator narrows it
|
* down per algorithm.
|
*/
|
/*
|
* Default compression level.
|
*
|
* A global fallback for the codecs' Assert-only paths; the levels users
|
* actually get come from the per-algorithm GUCs (cfs_default_lz4_level /
|
* cfs_default_zstd_level, see cfs_guc.c and guc_tables.c) and the
|
* per-algorithm constants below.
|
*/
|
#define CFS_COMPRESS_LEVEL_DEFAULT 3 /* global fallback level */
|
#define CFS_COMPRESS_LEVEL_MIN 1
|
#define CFS_COMPRESS_LEVEL_MAX 22 /* global maximum (Zstd) */
|
|
/*
|
* LZ4's usable level range: two fast levels (1..2, differing in
|
* acceleration) plus LZ4 HC levels 3..12 (10 settings) = 12 distinct
|
* levels. HC has no levels below 3, so the fast mode covers user levels
|
* 1..2; cfs_codec.c maps them to LZ4_compress_fast accelerations 2 and 1.
|
*/
|
#define CFS_LZ4_LEVEL_MAX 12
|
#define CFS_ZSTD_LEVEL_MAX 22 /* Zstd maximum */
|
|
/*
|
* Per-algorithm default compression levels, matching the backing
|
* libraries: LZ4_compress_default (= 1) and ZSTD_CLEVEL_DEFAULT (= 3).
|
* Kept in sync with the boot values of the cfs_default_lz4_level and
|
* cfs_default_zstd_level GUCs (see cfs_guc.c and guc_tables.c).
|
*/
|
#define CFS_LZ4_LEVEL_DEFAULT 1
|
#define CFS_ZSTD_LEVEL_DEFAULT 3
|
|
/*
|
* Magic for Page Map file header.
|
*
|
* CFS_MAP_MAGIC / CFS_MAP_VERSION and the .cfsmap prologue layout live in
|
* the frontend-safe common lexicon module (common/cfs_filename.h), shared
|
* with frontend tools; they are re-exported here through that include for
|
* the server-side code. The .cfsmap layout is the 8-byte CfsMapPrologue
|
* followed by positional rows (see the .cfsmap section below).
|
*/
|
|
/*
|
* Magic for Page Map Journal file header.
|
*/
|
#define CFS_JRN_MAGIC UINT32_C(0xCF5A4A00)
|
#define CFS_JRN_VERSION UINT16_C(2)
|
|
/* ----------------------------------------------------------------
|
* Compression algorithm identifiers
|
*
|
* Stored in CfsCompressedBlockHeader.algorithm (uint8) so values must
|
* fit in 0–255. Do NOT reuse or renumber existing values.
|
* ---------------------------------------------------------------- */
|
typedef enum CfsAlgorithm
|
{
|
CFS_ALGORITHM_RAW = 0, /* not compressed; stored verbatim */
|
CFS_ALGORITHM_LZ4 = 1, /* LZ4 frame-less block API */
|
CFS_ALGORITHM_ZSTD = 2, /* Zstd frame compression */
|
CFS_ALGORITHM_PGLZ = 3, /* PostgreSQL built-in PGLZ */
|
CFS_ALGORITHM_ZLIB = 4, /* zlib-wrapped DEFLATE */
|
|
/* sentinel — keep last */
|
CFS_ALGORITHM_COUNT
|
} CfsAlgorithm;
|
|
/* Human-readable algorithm names (index == CfsAlgorithm value). */
|
static const char *const CfsAlgorithmName[] =
|
{
|
"raw",
|
"lz4",
|
"zstd",
|
"pglz",
|
"zlib",
|
};
|
|
/* ----------------------------------------------------------------
|
* On-disk structure: CfsCompressedBlockHeader
|
*
|
* Written immediately before every payload stored in a .cfp file.
|
* The full on-disk record is:
|
*
|
* [ CfsCompressedBlockHeader ][ compressed_data ... ][ pad to CFS_BLOCK_ALIGN ]
|
*
|
* Offsets in the .cfp file always point to the *start* of the header.
|
*
|
* Every byte of the header is covered by hdr_crc. The record's tail
|
* padding — the 0..7 bytes between the end of the compressed payload and
|
* the CFS_BLOCK_ALIGN boundary of the whole record (header + payload) —
|
* is always zero and is verified to be zero on read; it is covered by no
|
* CRC. Like a MAXALIGN'd WAL record, alignment is applied to the total
|
* record length, not to the struct fields.
|
* ---------------------------------------------------------------- */
|
typedef struct CfsCompressedBlockHeader
|
{
|
uint32 magic; /* CFS_BLOCK_MAGIC */
|
uint16 version; /* CFS_FORMAT_VERSION */
|
uint8 algorithm; /* CfsAlgorithm */
|
|
uint32 compressed_size; /* size of payload following header */
|
uint32 original_size; /* size of original uncompressed data */
|
|
/*
|
* Checksums (CRC-32C): hdr_crc covers all fields above (header without
|
* hdr_crc itself) data_crc covers the compressed payload orig_crc
|
* covers the original uncompressed page
|
*/
|
uint32 orig_crc; /* CRC32C of the uncompressed page */
|
uint32 data_crc; /* CRC32C of the compressed payload */
|
uint32 hdr_crc; /* CRC32C of this header (must be last) */
|
} CfsCompressedBlockHeader;
|
|
/* ----------------------------------------------------------------
|
* On-disk structure: CfsMapEntry (one slot in .cfsmap)
|
*
|
* The .cfsmap file is a flat array of CfsMapEntry indexed by logical
|
* block number (BlockNumber). Entry at index N describes block N.
|
* The slot answers exactly "where does block N live and how many payload
|
* bytes does it have"; everything needed to *decode* the record
|
* (algorithm, sizes, checksums) lives in the record header itself
|
* (CfsCompressedBlockHeader) — the map deliberately does not duplicate it.
|
* A generation counter allows the crash-recovery journal to distinguish
|
* stale from current entries.
|
*
|
* The struct carries only role fields; the trailing alignment padding
|
* (bytes [20,24), forced by the uint64 alignment) is neither zeroed by
|
* convention nor covered by entry_crc — the same trade-off a MAXALIGN'd
|
* WAL record makes with its own tail padding.
|
* ---------------------------------------------------------------- */
|
/* ----------------------------------------------------------------
|
* Operation outcome codes
|
*
|
* The storage helpers return CFS_STORAGE_OK (0) on success. A negative
|
* value signals a problem; the caller decides whether to escalate via
|
* ereport(). Detailed diagnostics are emitted at DEBUG1/WARNING.
|
* ---------------------------------------------------------------- */
|
typedef enum CfsStorageStatus
|
{
|
CFS_STORAGE_OK = 0, /* success */
|
CFS_STORAGE_ERROR = -1, /* generic I/O or logic error */
|
CFS_STORAGE_CORRUPT = -2, /* checksum / format corruption detected */
|
CFS_STORAGE_NOENT = -3, /* block or file not found */
|
} CfsStorageStatus;
|
|
typedef struct CfsMapEntry
|
{
|
uint64 physical_offset; /* byte offset in .cfp; 0 = not present */
|
uint32 compressed_size; /* payload size (excl. header) */
|
uint32 generation; /* monotonically increasing per block */
|
uint32 entry_crc; /* CRC32C of this struct (excl. crc field) */
|
} CfsMapEntry;
|
|
/* Sentinel value: block has never been written via CFS. */
|
#define CFS_ENTRY_INVALID_OFFSET UINT64_C(0)
|
|
/* ----------------------------------------------------------------
|
* On-disk structure of .cfsmap: CfsMapPrologue + CfsMapEntry array
|
*
|
* The file starts with the static 8-byte prologue shared with frontend
|
* tools (common/cfs_filename.h) and continues with a flat array of
|
* CfsMapEntry indexed by logical block number. There is no server-side
|
* header: the number of rows is derived from the file size (a partial
|
* trailing row is a torn write and ignored), and every row is
|
* self-verifying via its entry_crc. An all-zero row is a sparse hole
|
* (the block was never written) and reads as INVALID; a row with a bad
|
* CRC that is not all-zero is corruption handled per the journal-repair
|
* contract (loaded as INVALID, healed by a covering journal record,
|
* reported otherwise). The mutable per-relation state (nblocks,
|
* cfp_size, max_generation) lives only in memory and in the journal
|
* header summary.
|
* ---------------------------------------------------------------- */
|
|
/*
|
* CfsMapState — the in-memory mutable state of one relation's map.
|
* Nothing here is stored in .cfsmap anymore: cfp_size follows the .cfp
|
* chain via EOF discovery and the generation watermark also travels in
|
* the .cfsjrn header summary (see CfsJournalFileHeader).
|
*/
|
typedef struct CfsMapState
|
{
|
uint64 nblocks; /* number of CfsMapEntry slots allocated */
|
uint64 cfp_size; /* current logical size of the .cfp chain */
|
uint32 max_generation; /* highest entry generation observed */
|
} CfsMapState;
|
|
/* ----------------------------------------------------------------
|
* On-disk structure: CfsJournalFileHeader (first bytes of .cfsjrn)
|
*
|
* The .cfsjrn file layout is:
|
*
|
* [ CfsJournalFileHeader ][ CfsJournalEntry ... ]
|
*
|
* The header lets utilities and recovery detect the file kind and version
|
* before touching any record, and — because it is rewritten by every
|
* reset — carries the one per-relation value that must survive truncation:
|
* the monotonic generation watermark.
|
* ---------------------------------------------------------------- */
|
typedef struct CfsJournalFileHeader
|
{
|
uint32 magic; /* CFS_JRN_MAGIC */
|
uint16 version; /* CFS_JRN_VERSION */
|
|
/*
|
* Journal incarnation. Bumped (mod 2^16) every time the journal is reset
|
* to a bare header - by a checkpoint truncate or by the compaction swap
|
* protocol. Backends compare it against the value observed when their
|
* in-memory map was last synced to detect a truncate-and-regrow (ABA)
|
* sequence that a pure file-size comparison cannot see.
|
*
|
* Accepted limitation: 16 bits alias after 2^16 resets, so a backend that
|
* misses exactly a multiple of 65536 journal resets between two refreshes
|
* would not notice the last one. This is considered unreachable in
|
* practice (a handle re-syncs on every cache miss and every write), and
|
* the file-size fallback still covers a plain truncate-without-regrowth
|
* in that window.
|
*/
|
uint16 incarnation;
|
|
/*
|
* Highest generation issued so far. Monotone: it survives table
|
* truncation, unlike the map rows themselves. The live-byte total was
|
* removed from the pre-release format: it had no production reader, and
|
* the checkpoint accounts dead space incrementally in the fold (the
|
* previous published value plus the superseded and truncated payloads),
|
* with compaction as the exact-recomputation point.
|
*/
|
uint32 max_generation;
|
uint32 hdr_crc; /* CRC32C of fields above */
|
} CfsJournalFileHeader;
|
|
/* ----------------------------------------------------------------
|
* On-disk structure: CfsJournalEntry (one record in .cfsjrn)
|
*
|
* The journal records every Page Map update atomically. On recovery,
|
* all journal entries are replayed in order against the last .cfsmap
|
* snapshot, and then the journal is truncated.
|
*
|
* The RESIZE operation records a change in the
|
* logical block count. The target nblocks is stored in je->blocknum.
|
* cfs_truncate() and cfs_zero_extend() append a RESIZE record so that
|
* journal replay restores nblocks deterministically after a crash.
|
* ---------------------------------------------------------------- */
|
typedef enum CfsJournalOp
|
{
|
CFS_JRN_OP_UPDATE = 1, /* block's mapping changed (write/overwrite) */
|
CFS_JRN_OP_DELETE = 2, /* block removed (truncation / vacuum) */
|
CFS_JRN_OP_RESIZE = 3, /* logical size changed (target in blocknum) */
|
} CfsJournalOp;
|
|
/*
|
* CfsJournalEntry intentionally omits a per-record lsn field: journal replay
|
* is strictly sequential (ordering is implicit). This keeps the on-disk
|
* format stable.
|
*/
|
typedef struct CfsJournalEntry
|
{
|
uint32 magic; /* CFS_JRN_MAGIC */
|
uint8 op; /* CfsJournalOp */
|
uint8 _reserved[3]; /* must be zero */
|
uint32 blocknum; /* logical block number */
|
CfsMapEntry new_entry; /* new map entry (op == UPDATE) */
|
uint32 entry_crc; /* CRC32C of fields above (excl. crc) */
|
} CfsJournalEntry;
|
|
/* ----------------------------------------------------------------
|
* File extension conventions
|
*
|
* The suffix macros and CfsFileKind live in the frontend-safe common
|
* lexicon module (common/cfs_filename.h), shared with frontend tools;
|
* they are re-exported here through the include below for the
|
* server-side code.
|
* ---------------------------------------------------------------- */
|
|
/* ----------------------------------------------------------------
|
* Helper macros
|
* ---------------------------------------------------------------- */
|
|
/*
|
* Fixed sizes of the on-disk structures. Used by the format layer
|
* (cfs_format.c), the integrity checker (cfs_fsck.c) and the storage
|
* layer to compute record offsets. Exact sizes are also checked at
|
* compile time by StaticAssertDecl in cfs_format.c.
|
*/
|
#define CFS_BLOCK_HEADER_SIZE sizeof(CfsCompressedBlockHeader)
|
#define CFS_MAP_HEADER_SIZE sizeof(CfsMapPrologue)
|
|
#define CFS_MAP_ENTRY_SIZE sizeof(CfsMapEntry)
|
|
/*
|
* Number of whole CfsMapEntry rows in a .cfsmap file of the given size.
|
* The row count derives from the file size (no server-side header); a
|
* partial trailing row is a torn write and is ignored by every loader.
|
*/
|
static inline uint64
|
cfs_map_rows_from_size(uint64 file_size)
|
{
|
if (file_size < (uint64) CFS_MAP_HEADER_SIZE)
|
return 0;
|
return (file_size - CFS_MAP_HEADER_SIZE) / CFS_MAP_ENTRY_SIZE;
|
}
|
|
/* Byte offset of one positional row in the .cfsmap file. */
|
static inline off_t
|
cfs_map_row_off(uint32 blocknum)
|
{
|
return (off_t) CFS_MAP_HEADER_SIZE +
|
(off_t) blocknum * CFS_MAP_ENTRY_SIZE;
|
}
|
|
/* Exact .cfsmap file size for 'nblocks' rows. */
|
static inline off_t
|
cfs_map_file_size(uint32 nblocks)
|
{
|
return (off_t) CFS_MAP_HEADER_SIZE +
|
(off_t) nblocks * CFS_MAP_ENTRY_SIZE;
|
}
|
#define CFS_JOURNAL_HEADER_SIZE sizeof(CfsJournalFileHeader)
|
#define CFS_JOURNAL_ENTRY_SIZE sizeof(CfsJournalEntry)
|
|
/*
|
* Round up 'sz' to the next multiple of CFS_BLOCK_ALIGN.
|
* Used to determine the physical space occupied by a compressed block.
|
*/
|
#define CFS_ALIGN_UP(sz) \
|
(((size_t)(sz) + (CFS_BLOCK_ALIGN) - 1) & ~((size_t)(CFS_BLOCK_ALIGN) - 1))
|
|
/*
|
* Total on-disk size of one compressed record (header + payload + tail
|
* padding). The whole record — not just the payload — is rounded up to
|
* CFS_BLOCK_ALIGN, mirroring how WAL MAXALIGNs each XLogRecord: with the
|
* 8-byte .cfp lead-in, every record start stays 8-aligned. The 0..7 tail
|
* bytes are always zero.
|
*/
|
#define CFS_RECORD_SIZE(compressed_payload_size) \
|
CFS_ALIGN_UP(CFS_BLOCK_HEADER_SIZE + (compressed_payload_size))
|
|
/*
|
* True when a CfsMapEntry refers to a valid, live, compressed block.
|
*/
|
#define CFS_MAP_ENTRY_VALID(e) \
|
((e)->physical_offset != CFS_ENTRY_INVALID_OFFSET)
|
|
/*
|
* True when algorithm value is within supported range.
|
*/
|
#define CFS_ALGORITHM_VALID(a) \
|
((unsigned)(a) < (unsigned)CFS_ALGORITHM_COUNT)
|
|
#endif /* CFS_H */
|