/*------------------------------------------------------------------------- * cfs_compress.c * Compressed File Store (CFS) page-level compress/decompress helpers. * * Implements CfsCompressPage() and CfsDecompressPage(), which form the * core of the CFS I/O layer. All CRC-32C checksums are computed with * PostgreSQL's standard pg_crc32c machinery. * * Scratch buffer layout used by CfsCompressPage(): * * [ CfsCompressedBlockHeader (fixed, CFS_BLOCK_HEADER_SIZE bytes) ] * [ compressed payload (variable, up to compress_bound) ] * [ alignment padding (0–7 bytes, to reach CFS_BLOCK_ALIGN)] * * The header is filled last so that data_crc and hdr_crc can be * computed after compression completes. * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_compress.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include #include "port/pg_crc32c.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_codec.h" #include "storage/cfs/cfs_compress.h" /* ---------------------------------------------------------------- * Internal helpers * ---------------------------------------------------------------- */ /* * cfs_crc32c_of * Compute CRC-32C over a byte range. */ static inline pg_crc32c cfs_crc32c_of(const void *data, size_t len) { pg_crc32c crc; INIT_CRC32C(crc); COMP_CRC32C(crc, data, len); FIN_CRC32C(crc); return crc; } uint32 CfsCrc32cPayload(const void *payload, size_t payload_size) { return (uint32) cfs_crc32c_of(payload, payload_size); } /* * cfs_header_crc * Compute the CRC-32C over all fields of *hdr* except hdr_crc itself. * The hdr_crc field must be the last member of CfsCompressedBlockHeader. */ static inline pg_crc32c cfs_header_crc(const CfsCompressedBlockHeader *hdr) { /* * Cover everything up to (but not including) the hdr_crc field. * StaticAssertStmt would be cleaner but offsetof is available here. */ size_t covered = offsetof(CfsCompressedBlockHeader, hdr_crc); return cfs_crc32c_of(hdr, covered); } uint32 CfsCrc32cHeader(const CfsCompressedBlockHeader *hdr) { return (uint32) cfs_header_crc(hdr); } /* * cfs_bytes_all_zero * Return true when every byte in the range [p, p + len) is zero. * Used to validate on-disk padding that no CRC covers. */ static bool cfs_bytes_all_zero(const unsigned char *p, size_t len) { size_t i; for (i = 0; i < len; i++) { if (p[i] != 0) return false; } return true; } /* * CfsFillBlockHeader * Populate a CfsCompressedBlockHeader and compute all three CRCs. * * Parameters: * hdr - destination header (caller-supplied) * algorithm - compression algorithm used * compressed_data - pointer to the compressed payload * compressed_size - byte count of the compressed payload * original_data - pointer to the original uncompressed page * original_size - byte count of the original page */ void CfsFillBlockHeader(CfsCompressedBlockHeader *hdr, CfsAlgorithm algorithm, const void *compressed_data, uint32 compressed_size, const void *original_data, uint32 original_size) { hdr->magic = CFS_BLOCK_MAGIC; hdr->version = CFS_FORMAT_VERSION; hdr->algorithm = (uint8) algorithm; hdr->compressed_size = compressed_size; hdr->original_size = original_size; /* Compute CRC over the original uncompressed page. */ hdr->orig_crc = CfsCrc32cPayload(original_data, original_size); hdr->data_crc = CfsCrc32cPayload(compressed_data, compressed_size); hdr->hdr_crc = CfsCrc32cHeader(hdr); } /* ---------------------------------------------------------------- * Public API: CfsCompressPage. * ---------------------------------------------------------------- */ /* * CfsCompressScratchSize * Return the minimum scratch buffer size needed by CfsCompressPage(). * * We need room for: * - one CfsCompressedBlockHeader * - the maximum possible compressed output for any supported algorithm * (worst case is LZ4CompressBound, which exceeds ZstdCompressBound * for typical page sizes) * - CFS_BLOCK_ALIGN bytes of padding */ size_t CfsCompressScratchSize(size_t page_size) { size_t max_bound = 0; size_t bound; int i; for (i = 0; i < CFS_ALGORITHM_COUNT; i++) { const CfsCodec *codec = CfsCodecTable[i]; if (codec == NULL || codec->compress_bound == NULL) continue; bound = codec->compress_bound(page_size); if (bound > max_bound) max_bound = bound; } /* * Header + worst-case payload + alignment slop. */ return CFS_BLOCK_HEADER_SIZE + max_bound + CFS_BLOCK_ALIGN; } /* * CfsCompressPage / CfsCompressPageNoCopy — compress one PostgreSQL page * and format the result as a CfsCompressedBlockHeader + payload blob in * the caller's scratch buffer. * * If the chosen algorithm fails to shrink the data by at least * opts->min_gain_bytes, the page is stored RAW (verbatim copy) and * result->is_raw is set to true. * * The two entry points share one decision core and differ only in how a * RAW result is presented: * * CfsCompressPage — the contiguous contract every pre-D4 consumer * relies on: the payload is copied into the * scratch buffer and result_data spans the whole * record (payload_external stays false). * * CfsCompressPageNoCopy — the D4 write-path form: a RAW result is NOT * copied; only the 28-byte header is built in * the scratch buffer, payload_data points at the * caller's original page and the append path * writes [header][page][zero padding] with * cfs_pwritev_all(). The on-disk record is * byte-identical to the copied form. Compressed * results are always contiguous in both forms. */ static void compress_page_core(const void *page, size_t page_size, const CfsCompressOptions *opts, void *scratch, size_t scratch_sz, bool raw_nocopy, CfsCompressResult *result) { const CfsCodec *codec; CfsCodecState *state; CfsCompressedBlockHeader *hdr; void *payload_buf; size_t payload_capacity; size_t compressed_size; CfsCodecResult codec_rc; bool store_raw; bool payload_verbatim; bool allow_raw_fallback; CfsAlgorithm actual_algorithm; Assert(page != NULL); Assert(opts != NULL); Assert(scratch != NULL); Assert(result != NULL); if (page_size != CFS_BLCKSZ) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: page_size %zu is not CFS_BLCKSZ %d", page_size, CFS_BLCKSZ))); } /* Verify scratch buffer is large enough. */ if (scratch_sz < CfsCompressScratchSize(page_size)) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: scratch buffer too small: need %zu, got %zu", CfsCompressScratchSize(page_size), scratch_sz))); } /* Layout: [header][payload ...] inside scratch */ hdr = (CfsCompressedBlockHeader *) scratch; payload_buf = (char *) scratch + CFS_BLOCK_HEADER_SIZE; payload_capacity = scratch_sz - CFS_BLOCK_HEADER_SIZE - CFS_BLOCK_ALIGN; store_raw = false; payload_verbatim = false; allow_raw_fallback = opts->allow_raw_fallback || !opts->explicit_algorithm; actual_algorithm = opts->algorithm; codec_rc = CFS_CODEC_NOOP; /* assume no compression initially */ /* * The no-copy form never runs the RAW codec (whose whole job is to * memcpy the page into the payload): the record is written straight * from the caller's page below, byte-identical to the copied form. */ if (raw_nocopy && opts->algorithm == CFS_ALGORITHM_RAW) store_raw = true; codec = CfsCodecLookup(opts->algorithm); if (codec == NULL || !codec->available()) { if (opts->explicit_algorithm || !allow_raw_fallback) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("CFS: algorithm %d not available", (int) opts->algorithm), errhint("Select an available algorithm or enable RAW fallback."))); ereport(DEBUG1, (errmsg("CFS: algorithm %d not available, falling back to RAW", (int) opts->algorithm))); store_raw = true; } else if (!store_raw) { state = CfsCodecStateCreate(opts->algorithm); if (state == NULL) { if (opts->explicit_algorithm || !allow_raw_fallback) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("CFS: could not create codec state for algorithm %d", (int) opts->algorithm))); ereport(DEBUG1, (errmsg("CFS: could not create codec state for algorithm %d, falling back to RAW", (int) opts->algorithm))); store_raw = true; } else { codec_rc = codec->compress(state, page, page_size, payload_buf, payload_capacity, opts->level, &compressed_size); /* * A successful RAW compression already left the verbatim page in * the payload, so the store_raw path below must not copy again. */ if (codec_rc == CFS_CODEC_OK && opts->algorithm == CFS_ALGORITHM_RAW) payload_verbatim = true; } } /* * Decide whether to accept the compressed form or fall back to RAW. * Conditions for RAW: (a) codec is unavailable, or (b) codec returned * OVERFLOW / NOOP, or (c) compressed output is not small enough * (min_gain_bytes). A RAW page always lands here because its gain is * zero. */ if (!store_raw) { if (codec_rc == CFS_CODEC_OK) { /* Check minimum gain requirement */ if (page_size > compressed_size && (page_size - compressed_size) >= opts->min_gain_bytes) { /* Accept compressed form, nothing more to do. */ } else { /* Not worth compressing */ store_raw = true; } } else if (codec_rc == CFS_CODEC_NOOP || codec_rc == CFS_CODEC_OVERFLOW) { if (!allow_raw_fallback) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: compression did not produce a storable compressed block"))); store_raw = true; } else { /* Unexpected codec error */ if (!allow_raw_fallback) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: compression failed (algorithm=%d, rc=%d)", (int) opts->algorithm, (int) codec_rc))); ereport(DEBUG1, (errmsg("CFS: compression error (algorithm=%d, rc=%d), falling back to RAW", (int) opts->algorithm, (int) codec_rc))); store_raw = true; } } if (store_raw) { compressed_size = (uint32) page_size; actual_algorithm = CFS_ALGORITHM_RAW; /* * Contiguous form: copy the page verbatim into the payload region * of the scratch buffer (the pre-D4 contract every consumer of * result_data relies on), unless a successful RAW codec already * left the verbatim page there. */ if (!raw_nocopy && !payload_verbatim) memcpy(payload_buf, page, page_size); /* * The no-copy form leaves the payload at the caller's page — no * 8 KiB memcpy into the scratch buffer. Only the 28-byte header * is built here; the record is written as [header][page][zero * padding] by cfs_pwritev_all(), byte-identical to the copied * form (the payload CRC below runs over the original page). */ } /* * Make every on-disk byte of this record deterministic. The scratch * buffer is allocated with palloc() (not palloc0) and reused across * writes, so any byte that is neither explicitly assigned nor covered by * a CRC would otherwise carry stale backend memory to disk -- a silent * leak, since none of these bytes are covered by any CRC. The header * MemSet also zeroes the two trailing alignment bytes of the header * struct that no field assigns; the scratch record tail below covers the * contiguous forms, while the external RAW tail is written from the * append path's zero buffer. */ MemSet(hdr, 0, sizeof(CfsCompressedBlockHeader)); { size_t rec_size = CFS_RECORD_SIZE(compressed_size); size_t rec_tail = rec_size - CFS_BLOCK_HEADER_SIZE - compressed_size; bool payload_in_scratch = !(store_raw && raw_nocopy); if (payload_in_scratch && rec_tail > 0) MemSet((char *) payload_buf + compressed_size, 0, rec_tail); } /* Fill and checksum the header */ CfsFillBlockHeader(hdr, actual_algorithm, (store_raw && raw_nocopy) ? page : payload_buf, (uint32) compressed_size, page, (uint32) page_size); /* Build result descriptor */ result->result_data = scratch; result->total_size = CFS_RECORD_SIZE(compressed_size); result->compressed_size = (uint32) compressed_size; result->algorithm_used = actual_algorithm; result->is_raw = store_raw; result->payload_external = (store_raw && raw_nocopy); result->payload_data = result->payload_external ? (void *) page : payload_buf; result->padding_bytes = result->total_size - CFS_BLOCK_HEADER_SIZE - compressed_size; Assert(result->total_size <= scratch_sz); Assert(!result->payload_external || result->padding_bytes < CFS_BLOCK_ALIGN); } /* * The two public entry points (see the contract comment above the core). */ void CfsCompressPage(const void *page, size_t page_size, const CfsCompressOptions *opts, void *scratch, size_t scratch_sz, CfsCompressResult *result) { compress_page_core(page, page_size, opts, scratch, scratch_sz, false, result); } void CfsCompressPageNoCopy(const void *page, size_t page_size, const CfsCompressOptions *opts, void *scratch, size_t scratch_sz, CfsCompressResult *result) { compress_page_core(page, page_size, opts, scratch, scratch_sz, true, result); } /* ---------------------------------------------------------------- * Public API: CfsDecompressPage. * ---------------------------------------------------------------- */ /* * CfsVerifyBlockHeader * Validate magic, version, and CRC of a CfsCompressedBlockHeader. * Returns true on success, false on any mismatch. */ bool CfsVerifyBlockHeader(const CfsCompressedBlockHeader *hdr) { pg_crc32c expected_crc; if (hdr->magic != CFS_BLOCK_MAGIC) { ereport(WARNING, (errmsg("CFS: bad magic in block header: 0x%08X (expected 0x%08X)", hdr->magic, CFS_BLOCK_MAGIC))); return false; } if (hdr->version != CFS_FORMAT_VERSION) { ereport(WARNING, (errmsg("CFS: unsupported block header version %u (expected %u)", (unsigned) hdr->version, (unsigned) CFS_FORMAT_VERSION))); return false; } if (!CFS_ALGORITHM_VALID((CfsAlgorithm) hdr->algorithm)) { ereport(WARNING, (errmsg("CFS: unknown algorithm %u in block header", (unsigned) hdr->algorithm))); return false; } expected_crc = (pg_crc32c) cfs_header_crc(hdr); if (!EQ_CRC32C(expected_crc, (pg_crc32c) hdr->hdr_crc)) { ereport(WARNING, (errmsg("CFS: header CRC mismatch: computed 0x%08X, stored 0x%08X", (unsigned) expected_crc, (unsigned) hdr->hdr_crc))); return false; } return true; } /* * CfsDecompressPage * Decompress a .cfp record back into a full uncompressed page, * verifying all three CRC-32C checksums. */ CfsDecompressStatus CfsDecompressPage(const void *compressed_data, size_t data_size, void *out_page, size_t out_page_size, CfsDecompressResult *result) { const CfsCompressedBlockHeader *hdr; const void *payload; size_t payload_size; const CfsCodec *codec; CfsCodecState *state; pg_crc32c computed_crc; CfsCodecResult codec_rc; size_t decompressed_size; Assert(compressed_data != NULL); Assert(out_page != NULL); if (data_size < CFS_BLOCK_HEADER_SIZE) { ereport(WARNING, (errmsg("CFS: compressed_data too small for header: %zu bytes", data_size))); return CFS_DECOMPRESS_BAD_HDR; } hdr = (const CfsCompressedBlockHeader *) compressed_data; /* Validate header magic, version, and checksum. */ if (!CfsVerifyBlockHeader(hdr)) return CFS_DECOMPRESS_BAD_HDR; /* Every record stores a full 8 kB page. */ if (hdr->original_size != CFS_BLCKSZ) { ereport(WARNING, (errmsg("CFS: original_size %u is not CFS_BLCKSZ %d", (unsigned) hdr->original_size, CFS_BLCKSZ))); return CFS_DECOMPRESS_BAD_HDR; } payload = (const char *) compressed_data + CFS_BLOCK_HEADER_SIZE; payload_size = hdr->compressed_size; /* Check that payload fits within data_size. */ if (CFS_BLOCK_HEADER_SIZE + payload_size > data_size) { ereport(WARNING, (errmsg("CFS: payload_size %u exceeds available data %zu", hdr->compressed_size, data_size - CFS_BLOCK_HEADER_SIZE))); return CFS_DECOMPRESS_BAD_HDR; } /* Verify payload (compressed data) CRC. */ computed_crc = (pg_crc32c) cfs_crc32c_of(payload, payload_size); if (!EQ_CRC32C(computed_crc, (pg_crc32c) hdr->data_crc)) { ereport(WARNING, (errmsg("CFS: payload CRC mismatch: computed 0x%08X, stored 0x%08X", (unsigned) computed_crc, (unsigned) hdr->data_crc))); return CFS_DECOMPRESS_BAD_DATA; } /* * Record tail padding ([header + compressed_size, * CFS_RECORD_SIZE(compressed_size))) is written to disk but covered by no * CRC; it must always be zero. Only bytes actually present within * data_size are checked. */ { size_t rec_size = CFS_RECORD_SIZE(payload_size); size_t available = data_size - CFS_BLOCK_HEADER_SIZE; size_t pad_end = Min(rec_size - CFS_BLOCK_HEADER_SIZE, available); if (pad_end > payload_size && !cfs_bytes_all_zero((const unsigned char *) payload + payload_size, pad_end - payload_size)) { ereport(WARNING, (errmsg("CFS: nonzero byte in record tail padding"))); return CFS_DECOMPRESS_BAD_DATA; } } /* Ensure output buffer is large enough. */ if (out_page_size < hdr->original_size) { ereport(WARNING, (errmsg("CFS: output buffer too small: need %u, got %zu", hdr->original_size, out_page_size))); return CFS_DECOMPRESS_ERROR; } /* Decompress through the codec table (RAW is a codec too). */ codec = CfsCodecLookup((CfsAlgorithm) hdr->algorithm); if (codec == NULL || !codec->available()) { ereport(WARNING, (errmsg("CFS: algorithm %u not available in this build, cannot decompress page", (unsigned) hdr->algorithm), errhint("Rebuild with --with-lz4 or --with-zstd to enable this codec."))); return CFS_DECOMPRESS_ERROR; } state = CfsCodecStateCreate((CfsAlgorithm) hdr->algorithm); if (state == NULL) { ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("CFS: could not create codec state for algorithm %u", (unsigned) hdr->algorithm))); return CFS_DECOMPRESS_ERROR; /* unreachable */ } codec_rc = codec->decompress(state, payload, payload_size, out_page, out_page_size, hdr->original_size, &decompressed_size); if (codec_rc != CFS_CODEC_OK) { ereport(WARNING, (errmsg("CFS: decompression failed (algorithm=%u, rc=%d)", (unsigned) hdr->algorithm, (int) codec_rc))); return CFS_DECOMPRESS_CORRUPT; } /* The codec must reproduce exactly the original page size. */ if (decompressed_size != hdr->original_size) { ereport(WARNING, (errmsg("CFS: decompressed size %zu != original_size %u", decompressed_size, hdr->original_size))); return CFS_DECOMPRESS_CORRUPT; } /* Verify original page CRC after decompression. */ computed_crc = (pg_crc32c) cfs_crc32c_of(out_page, decompressed_size); if (!EQ_CRC32C(computed_crc, (pg_crc32c) hdr->orig_crc)) { ereport(WARNING, (errmsg("CFS: original page CRC mismatch after decompression: computed 0x%08X, stored 0x%08X", (unsigned) computed_crc, (unsigned) hdr->orig_crc))); return CFS_DECOMPRESS_BAD_ORIG; } if (result != NULL) { result->decompressed_size = decompressed_size; result->algorithm_used = (CfsAlgorithm) hdr->algorithm; result->is_raw = (hdr->algorithm == CFS_ALGORITHM_RAW); } return CFS_DECOMPRESS_OK; } CfsAlgorithm CfsAlgorithmFromName(const char *name) { int i; if (name == NULL) return CFS_ALGORITHM_COUNT; for (i = 0; i < CFS_ALGORITHM_COUNT; i++) { if (pg_strcasecmp(name, CfsAlgorithmName[i]) == 0) return (CfsAlgorithm) i; } return CFS_ALGORITHM_COUNT; } const char * CfsAlgorithmGetName(CfsAlgorithm algorithm) { if (!CFS_ALGORITHM_VALID(algorithm)) return "unknown"; return CfsAlgorithmName[algorithm]; } /* ---------------------------------------------------------------- * Status string helpers * ---------------------------------------------------------------- */ const char * CfsDecompressStatusString(CfsDecompressStatus status) { switch (status) { case CFS_DECOMPRESS_OK: return "ok"; case CFS_DECOMPRESS_BAD_HDR: return "bad header (magic/version/CRC mismatch)"; case CFS_DECOMPRESS_BAD_DATA: return "compressed payload CRC mismatch"; case CFS_DECOMPRESS_CORRUPT: return "decompression reported corrupt data"; case CFS_DECOMPRESS_BAD_ORIG: return "original page CRC mismatch after decompression"; case CFS_DECOMPRESS_ERROR: return "internal error"; default: return "unknown"; } }