/*------------------------------------------------------------------------- * * cfs_codec.c * Compressed File Store (CFS) codec dispatch table implementation. * * Provides concrete implementations of the CfsCodec vtable for: * - RAW (identity pass-through, no library required) * - LZ4 (requires liblz4, guarded by USE_LZ4) * - Zstd (requires libzstd, guarded by USE_ZSTD) * * Per-backend state (Zstd contexts) is cached in a static array indexed * by CfsAlgorithm so that we avoid repeated allocation on the I/O hot path. * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_codec.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include #ifdef USE_LZ4 #include #include #endif #ifdef USE_ZSTD #include #include #endif #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_codec.h" #include "storage/cfs/cfs_guc.h" #include "utils/memutils.h" StaticAssertDecl(CFS_BLCKSZ == BLCKSZ, "CFS_BLCKSZ must match PostgreSQL BLCKSZ"); /* ---------------------------------------------------------------- * Opaque per-backend state * ---------------------------------------------------------------- */ struct CfsCodecState { #ifdef USE_ZSTD ZSTD_CCtx *zstd_cctx; /* compression context */ ZSTD_DCtx *zstd_dctx; /* decompression context */ #endif /* LZ4 block API is stateless, so no context is needed. */ int _dummy; /* keep struct non-empty if no libs */ }; /* * One cached state per algorithm per backend. * Initialised lazily by CfsCodecStateCreate(). */ static CfsCodecState *backend_states[CFS_ALGORITHM_COUNT]; /* ================================================================ * RAW codec (identity, no compression) * ================================================================ */ static CfsCodecState * raw_state_create(void) { CfsCodecState *s = palloc0(sizeof(CfsCodecState)); ereport(DEBUG1, (errmsg(("CFS: initialized RAW codec state")))); return s; } static void raw_state_destroy(CfsCodecState *state) { if (state) pfree(state); } static CfsCodecResult raw_compress(CfsCodecState *state, const void *src, size_t src_size, void *dst, size_t dst_size, int level, size_t *out_size) { if (dst_size < src_size) return CFS_CODEC_OVERFLOW; memcpy(dst, src, src_size); *out_size = src_size; return CFS_CODEC_OK; } static CfsCodecResult raw_decompress(CfsCodecState *state, const void *src, size_t src_size, void *dst, size_t dst_size, size_t expected_size, size_t *out_size) { if (src_size > dst_size) return CFS_CODEC_CORRUPT; memcpy(dst, src, src_size); *out_size = src_size; return CFS_CODEC_OK; } static size_t raw_compress_bound(size_t src_size) { return src_size; } static bool raw_available(void) { return true; } static const CfsCodec cfs_codec_raw = { .algorithm = CFS_ALGORITHM_RAW, .state_create = raw_state_create, .state_destroy = raw_state_destroy, .compress = raw_compress, .decompress = raw_decompress, .compress_bound = raw_compress_bound, .available = raw_available, }; /* ================================================================ * LZ4 codec * ================================================================ */ static CfsCodecState * lz4_state_create(void) { #ifndef USE_LZ4 ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("CFS compression algorithm \"lz4\" is not available in this build"), errhint("Rebuild the server with --with-lz4."))); return NULL; #else CfsCodecState *s = palloc0(sizeof(CfsCodecState)); /* LZ4 block API is stateless, so nothing else is initialized. */ ereport(DEBUG1, (errmsg(("CFS: initialized LZ4 codec state")))); return s; #endif } static void lz4_state_destroy(CfsCodecState *state) { if (state) pfree(state); } static CfsCodecResult lz4_compress(CfsCodecState *state, const void *src, size_t src_size, void *dst, size_t dst_size, int level, size_t *out_size) { #ifndef USE_LZ4 return CFS_CODEC_UNAVAIL; #else int compressed; int dst_capacity; /* * LZ4 API uses int for sizes; guard against overflow on hypothetical huge * pages (BLCKSZ is 8 kB, so this is just future-proofing). */ if (dst_size > (size_t) PG_INT32_MAX) return CFS_CODEC_OVERFLOW; dst_capacity = (int) dst_size; Assert(level >= CFS_COMPRESS_LEVEL_MIN && level <= CFS_LZ4_LEVEL_MAX); /* * Clamp defensively, mirroring zstd_compress(): release builds have no * Assert, and liblz4 silently treats any level above LZ4HC_CLEVEL_MAX as * that maximum. The Assert stays above the clamp so a debug build still * flags a caller that violates the contract. */ if (level > CFS_LZ4_LEVEL_MAX) level = CFS_LZ4_LEVEL_MAX; if (level <= 2) { /* * Fast mode: levels 1..2 select two accelerations (2 and 1), so level * 2 is a touch slower and compresses a touch better. */ compressed = LZ4_compress_fast((const char *) src, (char *) dst, (int) src_size, dst_capacity, 3 - level); } else { /* * LZ4_compress_HC offers better ratio at the cost of speed; levels * 3..12 map 1:1 to the LZ4 HC levels. */ compressed = LZ4_compress_HC((const char *) src, (char *) dst, (int) src_size, dst_capacity, level); } if (compressed <= 0) return CFS_CODEC_OVERFLOW; /* output didn't fit or library error */ *out_size = (size_t) compressed; return CFS_CODEC_OK; #endif } static CfsCodecResult lz4_decompress(CfsCodecState *state, const void *src, size_t src_size, void *dst, size_t dst_size, size_t expected_size, size_t *out_size) { #ifndef USE_LZ4 return CFS_CODEC_UNAVAIL; #else int decompressed; if (expected_size > dst_size) return CFS_CODEC_CORRUPT; decompressed = LZ4_decompress_safe((const char *) src, (char *) dst, (int) src_size, (int) expected_size); if (decompressed < 0) return CFS_CODEC_CORRUPT; if ((size_t) decompressed != expected_size) return CFS_CODEC_CORRUPT; *out_size = (size_t) decompressed; return CFS_CODEC_OK; #endif } static size_t lz4_compress_bound(size_t src_size) { #ifndef USE_LZ4 return src_size + src_size / 4 + 16; /* conservative fallback */ #else return (size_t) LZ4_compressBound((int) src_size); #endif } static bool lz4_available(void) { #ifdef USE_LZ4 /* Debug fault injection: pretend the library was not compiled in. */ if (cfs_debug_disable_codecs & (1 << CFS_ALGORITHM_LZ4)) return false; return true; #else return false; #endif } static const CfsCodec cfs_codec_lz4 = { .algorithm = CFS_ALGORITHM_LZ4, .state_create = lz4_state_create, .state_destroy = lz4_state_destroy, .compress = lz4_compress, .decompress = lz4_decompress, .compress_bound = lz4_compress_bound, .available = lz4_available, }; /* ================================================================ * Zstd codec * ================================================================ */ static CfsCodecState * zstd_state_create(void) { #ifndef USE_ZSTD ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("CFS compression algorithm \"zstd\" is not available in this build"), errhint("Rebuild the server with --with-zstd."))); return NULL; #else CfsCodecState *s = palloc0(sizeof(CfsCodecState)); s->zstd_cctx = ZSTD_createCCtx(); if (s->zstd_cctx == NULL) { pfree(s); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("could not create Zstd compression context"))); } s->zstd_dctx = ZSTD_createDCtx(); if (s->zstd_dctx == NULL) { ZSTD_freeCCtx(s->zstd_cctx); pfree(s); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("could not create Zstd decompression context"))); } ereport(DEBUG1, (errmsg(("CFS: initialized Zstd codec state")))); return s; #endif } static void zstd_state_destroy(CfsCodecState *state) { if (!state) return; #ifdef USE_ZSTD if (state->zstd_cctx) ZSTD_freeCCtx(state->zstd_cctx); if (state->zstd_dctx) ZSTD_freeDCtx(state->zstd_dctx); #endif pfree(state); } static CfsCodecResult zstd_compress(CfsCodecState *state, const void *src, size_t src_size, void *dst, size_t dst_size, int level, size_t *out_size) { #ifndef USE_ZSTD return CFS_CODEC_UNAVAIL; #else size_t result; int zstd_level; /* Clamp to Zstd's [1, ZSTD_maxCLevel()] range */ zstd_level = (level < 1) ? 1 : level; if (zstd_level > ZSTD_maxCLevel()) zstd_level = ZSTD_maxCLevel(); result = ZSTD_compressCCtx(state->zstd_cctx, dst, dst_size, src, src_size, zstd_level); if (ZSTD_isError(result)) { if (ZSTD_getErrorCode(result) == ZSTD_error_dstSize_tooSmall) return CFS_CODEC_OVERFLOW; ereport(WARNING, (errmsg("Zstd compression error: %s", ZSTD_getErrorName(result)))); return CFS_CODEC_ERROR; } *out_size = result; return CFS_CODEC_OK; #endif } static CfsCodecResult zstd_decompress(CfsCodecState *state, const void *src, size_t src_size, void *dst, size_t dst_size, size_t expected_size, size_t *out_size) { #ifndef USE_ZSTD return CFS_CODEC_UNAVAIL; #else size_t result; result = ZSTD_decompressDCtx(state->zstd_dctx, dst, dst_size, src, src_size); if (ZSTD_isError(result)) { ereport(WARNING, (errmsg("Zstd decompression error: %s", ZSTD_getErrorName(result)))); return CFS_CODEC_CORRUPT; } if (result != expected_size) { ereport(WARNING, (errmsg("Zstd decompressed %zu bytes, expected %zu", result, expected_size))); return CFS_CODEC_CORRUPT; } *out_size = result; return CFS_CODEC_OK; #endif } static size_t zstd_compress_bound(size_t src_size) { #ifndef USE_ZSTD return src_size + src_size / 4 + 128; /* conservative fallback */ #else return ZSTD_compressBound(src_size); #endif } static bool zstd_available(void) { #ifdef USE_ZSTD /* Debug fault injection: pretend the library was not compiled in. */ if (cfs_debug_disable_codecs & (1 << CFS_ALGORITHM_ZSTD)) return false; return true; #else return false; #endif } static const CfsCodec cfs_codec_zstd = { .algorithm = CFS_ALGORITHM_ZSTD, .state_create = zstd_state_create, .state_destroy = zstd_state_destroy, .compress = zstd_compress, .decompress = zstd_decompress, .compress_bound = zstd_compress_bound, .available = zstd_available, }; /* ================================================================ * Global dispatch table * ================================================================ */ /* * Demo compatibility adapters for the independently implemented codecs. * PGLZ is stateless; ZLIB owns pre-warmed backend-local streams. * Do not change existing RAW/LZ4/ZSTD on-disk algorithm values. */ extern bool cfs_codec_pglz_available(void); extern Size cfs_codec_pglz_bound(Size); extern CfsCodecResult cfs_codec_pglz_compress(const char *, Size, char *, Size, int, Size *); extern CfsCodecResult cfs_codec_pglz_decompress(const char *, Size, char *, Size); extern bool cfs_codec_zlib_available(void); extern bool cfs_codec_zlib_prepare(void); extern void cfs_codec_zlib_release(void); extern Size cfs_codec_zlib_bound(Size); extern CfsCodecResult cfs_codec_zlib_compress(const char *, Size, char *, Size, int, Size *); extern CfsCodecResult cfs_codec_zlib_decompress(const char *, Size, char *, Size); static CfsCodecResult pglz_demo_compress(CfsCodecState *state, const void *src, size_t src_size, void *dst, size_t dst_size, int level, size_t *out_size) { (void) state; return cfs_codec_pglz_compress((const char *) src, src_size, (char *) dst, dst_size, level, out_size); } static CfsCodecResult pglz_demo_decompress(CfsCodecState *state, const void *src, size_t src_size, void *dst, size_t dst_size, size_t expected_size, size_t *out_size) { CfsCodecResult rc; (void) state; if (expected_size > dst_size) return CFS_CODEC_CORRUPT; rc = cfs_codec_pglz_decompress((const char *) src, src_size, (char *) dst, expected_size); if (rc == CFS_CODEC_OK) *out_size = expected_size; return rc; } static CfsCodecState * zlib_demo_state_create(void) { if (!cfs_codec_zlib_prepare()) return NULL; return raw_state_create(); } static void zlib_demo_state_destroy(CfsCodecState *state) { cfs_codec_zlib_release(); raw_state_destroy(state); } static CfsCodecResult zlib_demo_compress(CfsCodecState *state, const void *src, size_t src_size, void *dst, size_t dst_size, int level, size_t *out_size) { (void) state; return cfs_codec_zlib_compress((const char *) src, src_size, (char *) dst, dst_size, level, out_size); } static CfsCodecResult zlib_demo_decompress(CfsCodecState *state, const void *src, size_t src_size, void *dst, size_t dst_size, size_t expected_size, size_t *out_size) { CfsCodecResult rc; (void) state; if (expected_size > dst_size) return CFS_CODEC_CORRUPT; rc = cfs_codec_zlib_decompress((const char *) src, src_size, (char *) dst, expected_size); if (rc == CFS_CODEC_OK) *out_size = expected_size; return rc; } static const CfsCodec cfs_codec_pglz_demo = { .algorithm = CFS_ALGORITHM_PGLZ, .state_create = raw_state_create, .state_destroy = raw_state_destroy, .compress = pglz_demo_compress, .decompress = pglz_demo_decompress, .compress_bound = cfs_codec_pglz_bound, .available = cfs_codec_pglz_available, }; static const CfsCodec cfs_codec_zlib_demo = { .algorithm = CFS_ALGORITHM_ZLIB, .state_create = zlib_demo_state_create, .state_destroy = zlib_demo_state_destroy, .compress = zlib_demo_compress, .decompress = zlib_demo_decompress, .compress_bound = cfs_codec_zlib_bound, .available = cfs_codec_zlib_available, }; const CfsCodec *CfsCodecTable[CFS_ALGORITHM_COUNT] = { [CFS_ALGORITHM_RAW] = &cfs_codec_raw, [CFS_ALGORITHM_LZ4] = &cfs_codec_lz4, [CFS_ALGORITHM_ZSTD] = &cfs_codec_zstd, [CFS_ALGORITHM_PGLZ] = &cfs_codec_pglz_demo, [CFS_ALGORITHM_ZLIB] = &cfs_codec_zlib_demo, }; /* ================================================================ * Per-algorithm native level ceiling * ================================================================ */ /* * CfsCodecMaxLevel * Return the native maximum compression level of the given algorithm. * See the declaration in cfs_codec.h. */ int CfsCodecMaxLevel(CfsAlgorithm algorithm) { switch (algorithm) { case CFS_ALGORITHM_LZ4: return CFS_LZ4_LEVEL_MAX; case CFS_ALGORITHM_PGLZ: return 1; case CFS_ALGORITHM_ZLIB: return 9; case CFS_ALGORITHM_ZSTD: #ifdef USE_ZSTD /* * The library's ceiling is a runtime value (ZSTD_maxCLevel()); * CFS_ZSTD_LEVEL_MAX is only the format's upper bound. Clamp * here so DDL validation and the resolvers' defense check reject * a level the codec could never honour, instead of silently * clamping it on the write path. */ return Min(CFS_ZSTD_LEVEL_MAX, ZSTD_maxCLevel()); #else return CFS_ZSTD_LEVEL_MAX; #endif default: return CFS_COMPRESS_LEVEL_MAX; } } /* ================================================================ * Initialisation * ================================================================ */ /* * CfsCodecInit * Called once at subsystem startup (from CfsSubsystemInit) to verify * the codec dispatch table is consistent. A broken table is a coding * error and PANICs. */ void CfsCodecInit(void) { int i; ereport(DEBUG1, (errmsg(("CFS: initializing codec dispatch table")))); /* Verify table consistency, every slot must be non-NULL. */ for (i = 0; i < CFS_ALGORITHM_COUNT; i++) { if (CfsCodecTable[i] == NULL) ereport(PANIC, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CfsCodecTable[%d] is NULL", i), errdetail("CFS codec dispatch table was not initialised."), errhint("This is a coding error, please report it."))); if ((int) CfsCodecTable[i]->algorithm != i) ereport(PANIC, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CfsCodecTable[%d] has wrong algorithm %d", i, (int) CfsCodecTable[i]->algorithm), errdetail("CFS codec dispatch table is inconsistent."), errhint("This is a coding error, please report it."))); } } /* ================================================================ * Per-backend state cache * ================================================================ */ /* * CfsCodecStateCreate(algorithm) * Return (creating if necessary) a per-backend CfsCodecState for * the requested algorithm. Returns NULL if the algorithm is not * available in this build. * * The state is allocated in TopMemoryContext so that it survives for * the lifetime of the backend. This is critical: backend_states[] is * a plain static array whose pointers persist across queries, but the * first compress/decompress call can happen while CurrentMemoryContext * is a short-lived query/portal context (e.g. MessageContext, which is * reset at the top of every query cycle). Allocating the state in that * transient context and then dereferencing the cached pointer from a * later query is a use-after-free. * * The use-after-free is silent for the RAW and LZ4 codecs (their * compress/decompress entry points do not dereference the state * struct — LZ4's block API is stateless), but ZSTD stores live * ZSTD_CCtx / ZSTD_DCtx pointers inside CfsCodecState, and * ZSTD_decompressDCtx(state->zstd_dctx, ...) dereferences them. Once * the freed CfsCodecState slot is reused by an unrelated allocation, * the dangling zstd_dctx read yields a garbage pointer and the library * dereferences it -> SIGSEGV. This is the C5 defect. */ CfsCodecState * CfsCodecStateCreate(CfsAlgorithm algorithm) { const CfsCodec *codec; if (!CFS_ALGORITHM_VALID(algorithm)) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid CFS algorithm %d", (int) algorithm))); } codec = CfsCodecTable[(int) algorithm]; Assert(codec != NULL); if (!codec->available()) return NULL; if (backend_states[(int) algorithm] == NULL) { MemoryContext oldcontext; /* * Allocate the cached state (and any subordinate pallocs done by * state_create) in TopMemoryContext so it outlives query/portal * resets. ZSTD_createCCtx/DCtx use malloc internally and are * unaffected by the MemoryContext choice; only the CfsCodecState * struct itself (which holds the pointers the hot path reads) must * live in a context that is not reset between queries. */ oldcontext = MemoryContextSwitchTo(TopMemoryContext); backend_states[(int) algorithm] = codec->state_create(); MemoryContextSwitchTo(oldcontext); } return backend_states[(int) algorithm]; } /* * CfsCodecStateDestroy(algorithm) * Release cached per-backend state for one algorithm. */ void CfsCodecStateDestroy(CfsAlgorithm algorithm) { if (!CFS_ALGORITHM_VALID(algorithm)) return; if (backend_states[(int) algorithm] != NULL) { const CfsCodec *codec = CfsCodecTable[(int) algorithm]; codec->state_destroy(backend_states[(int) algorithm]); backend_states[(int) algorithm] = NULL; } } /* * CfsCodecStateDestroyAll() * Release all cached per-backend states. Called from CfsAtProcExit at * backend exit. */ void CfsCodecStateDestroyAll(void) { int i; for (i = 0; i < CFS_ALGORITHM_COUNT; i++) CfsCodecStateDestroy((CfsAlgorithm) i); }