/*------------------------------------------------------------------------- * cfs_smgr.c * Compressed File Store (CFS) — Storage Manager integration layer *. * * Implements the bridge declared in cfs_smgr.h. It attaches CFS state to an * SMgrRelation, resolves whether a fork is compressed, opens the sidecar * handle lazily and routes every relevant smgr operation through the * the CFS storage functions. * * Determining "is this fork compressed?" without a relcache entry: * * 1. The effective policy is published into shared memory by * RelationGetSmgr() (cfs_open_relation_smgr()). Auxiliary processes — the * checkpointer / bgwriter, which obtain an SMgrRelation via smgropen() * rather than the relcache — read it back with cfs_get_options(). * During WAL redo the policy arrives through the XLOG_SMGR_CFS_POLICY * record, replayed by cfs_smgr_wal_policy_redo() into the same * shared-memory cache before the first data record for the relation. * * 2. As a fall-back (e.g. crash recovery before the relcache is * available), sidecar file existence is checked: if a .cfp/.cfsmap/ * .cfsjrn file exists, the fork is treated as a CFS fork. The policy * redo also creates the sidecars eagerly, so this marker is durable * across standby restarts even before the first data write. * * Locking discipline: compression, decompression, file I/O and fsync are * never performed while a CFS shared-memory partition lock is held — those * happen inside the storage layer, which is lock-free with respect * to the CFS partition locks. * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_smgr.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/reloptions.h" #include "access/xlog.h" #include "access/xlogdefs.h" #include "access/xloginsert.h" #include "access/xlogutils.h" #include "common/relpath.h" #include "miscadmin.h" #include "storage/aio.h" #include "storage/aio_internal.h" #include "storage/bufmgr.h" #include "storage/bufpage.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_cfp.h" #include "storage/cfs/cfs_codec.h" #include "storage/cfs/cfs_compress.h" #include "storage/cfs/cfs_guc.h" #include "storage/cfs/cfs_journal.h" #include "storage/cfs/cfs_map_file.h" #include "storage/cfs/cfs_path.h" #include "storage/cfs/cfs_recovery.h" #include "storage/cfs/cfs_shmem.h" #include "storage/cfs/cfs_smgr.h" #include "storage/cfs/cfs_state.h" #include "storage/cfs/cfs_storage.h" #include "storage/fd.h" #include "storage/md.h" #include "storage/smgr.h" #include "utils/memutils.h" #include "utils/palloc.h" #include "utils/rel.h" #include "utils/wait_event.h" /* ================================================================ * Lifecycle * ================================================================ */ void CfsSmgrInit(void) { ereport(DEBUG1, (errmsg("CFS: storage manager integration layer initialised"))); } /* * Allocate (in TopMemoryContext) a fresh CfsSmgrState for 'reln' and resolve * is_cfs / opts. Called lazily from smgriscfsenabled() and the bridges. */ static CfsSmgrState * cfs_smgr_alloc(SMgrRelation reln) { CfsSmgrState *state; MemoryContext oldcontext; oldcontext = MemoryContextSwitchTo(TopMemoryContext); state = palloc0(sizeof(CfsSmgrState)); MemoryContextSwitchTo(oldcontext); state->rlocator = reln->smgr_rlocator; state->cfs = NULL; state->is_cfs = false; state->opts_valid = false; reln->cfs_smgr = state; return state; } /* * cfs_warn_fallback_codec — complain, once per SMgrRelation, that new pages * are being written with the built-in default codec because the relation's * real compression policy is not published. This happens when WAL recovery * replays data records of a relation whose policy record predates the redo * point, and when an auxiliary process writes through a cold policy cache * after a restart; the mismatch (e.g. a zstd primary and LZ4-writing * standby) would otherwise be visible only at DEBUG1. * * The real policy cannot be compared here — that is the point of the * fallback, it is unknown — so the WARNING deliberately fires on the fact of * the fallback, which also means it can fire when the real policy happens * to equal the default: an accepted price for operator visibility. */ static void cfs_warn_fallback_codec(CfsSmgrState *state, CfsAlgorithm algo, const char *via) { if (state->fallback_warned) return; state->fallback_warned = true; ereport(WARNING, (errmsg("CFS: compression policy of relation %u/%u/%u is not " "published yet (%s); new pages are written with the " "built-in default algorithm \"%s\"", state->rlocator.locator.spcOid, state->rlocator.locator.dbOid, state->rlocator.locator.relNumber, via, CfsAlgorithmName[algo]), errdetail("Records written with the default codec are " "self-describing and stay readable; the real policy " "is re-published after recovery or at the relation's " "first relcache access."))); } /* * Resolve the effective policy for 'reln'. Idempotent: once the is_cfs * decision has been made (cfs_resolved), subsequent calls return immediately * without re-running the sidecar existence check. * * This idempotency is required because smgriscfsenabled() may be called from * inside a WAL-redo critical section (e.g. XLOG_SMGR_TRUNCATE redo), where * palloc is forbidden. The first resolution happens outside the critical * section (via smgrcreate() / smgrnblocks()); cfs_resolved ensures that the * in-critical-section call short-circuits instead of redoing cfs_exists(), * which pallocs via cfs_make_filename()/psprintf(). * * The is_cfs decision is frozen, but the effective policy is not: every * call compares the shared-memory policy generation against the locally * cached one and re-reads the policy when it changed (ALTER TABLE ... * SET (level/min_gain_bytes) without a rewrite). The check and the * re-read are plain shared-memory lookups — no palloc — so they are safe * inside critical sections. This closes the staleness window for the * auxiliary processes (checkpointer / bgwriter), which obtain an * SMgrRelation via smgropen() and otherwise would keep the pre-ALTER * policy until the SMgrRelation is destroyed. */ void cfs_smgr_ensure_state(SMgrRelation reln) { CfsSmgrState *state; /* * Fast path: the is_cfs decision is final. Refresh the effective policy * when the shared-memory generation moved on (see above). */ if (reln->cfs_smgr != NULL && reln->cfs_smgr->cfs_resolved) { uint64 gen; state = reln->cfs_smgr; gen = cfs_policy_generation(state->rlocator, MAIN_FORKNUM); if (gen != state->policy_gen) { CfsEffectiveOptions newopts; /* * On a lookup miss (slot evicted or policy forgotten) keep the * previously resolved options: the is_cfs decision is physical * (sidecar files), so it cannot have changed underneath us. Only * the tunables are refreshed — is_cfs is deliberately NOT * re-decided here: a published policy alone does not mean the * sidecar files exist yet (ALTER ... SET (algorithm) publishes * before the rewrite creates the new storage). */ if (cfs_get_options(state->rlocator, MAIN_FORKNUM, &newopts)) { state->opts = newopts; state->opts_valid = true; ereport(DEBUG1, (errmsg("CFS: smgr policy refreshed from shared cache " "for relation %u/%u/%u: is_cfs=%d algo=%d", state->rlocator.locator.spcOid, state->rlocator.locator.dbOid, state->rlocator.locator.relNumber, (int) state->is_cfs, (int) state->opts.algorithm))); } state->policy_gen = gen; } return; } if (reln->cfs_smgr == NULL) state = cfs_smgr_alloc(reln); else state = reln->cfs_smgr; if (state->cfs_resolved) return; /* * A temp locator is never CFS: no policy is published for it (see the * guard in CfsEffectiveOptionsFromRelation) and no sidecar files may * exist, so resolve without taking the shared-memory partition lock or touching the * file system, even from callers that may run inside a WAL-redo * critical section. */ if (state->rlocator.backend != INVALID_PROC_NUMBER) { state->is_cfs = false; state->opts_valid = true; state->cfs_resolved = true; state->opts.is_cfs = false; state->opts.algorithm = CFS_ALGORITHM_RAW; return; } /* * Primary source: the shared-memory policy published by RelationGetSmgr. */ if (cfs_get_options(state->rlocator, MAIN_FORKNUM, &state->opts)) { state->is_cfs = state->opts.is_cfs; state->opts_valid = true; state->cfs_resolved = true; state->policy_gen = cfs_policy_generation(state->rlocator, MAIN_FORKNUM); ereport(DEBUG1, (errmsg("CFS: smgr policy resolved from shared cache for " "relation %u/%u/%u: is_cfs=%d algo=%d", state->rlocator.locator.spcOid, state->rlocator.locator.dbOid, state->rlocator.locator.relNumber, (int) state->is_cfs, (int) state->opts.algorithm))); return; } /* * Fall-back: no policy published yet. Decide CFS-ness purely from the * existence of sidecar files. This keeps crash recovery safe (the * startup process has no relcache) and lets the read path decompress * existing records. * * cfs_exists() pallocs (cfs_make_filename -> psprintf); this is only ever * reached once per SMgrRelation because cfs_resolved is set below, so the * caller must ensure the first call happens outside any critical section * (smgrcreate() does this for the WAL-redo path). */ if (cfs_exists(state->rlocator, MAIN_FORKNUM)) { state->is_cfs = true; if (InRecovery) { CfsEffectiveOptions defopts; /* * During recovery the relcache has no resolved policy, and the * XLOG_SMGR_CFS_POLICY record is only replayed for policies that * were created or changed after the redo point. A relation that * already existed at the redo point therefore has no policy * record in the replayed WAL, so publish the built-in default * here: the metadata slot then carries is_cfs, which * cfs_map_cache_set_meta() requires to set dirty_checkpoint, so * the end-of-recovery checkpoint enumerates the relation, * snapshots its map and truncates its journal. On a codec-less * build the default itself is RAW (cfs_algo == 0) — that is * fine, is_cfs no longer derives from the algorithm value. The * published default may also differ from the relation's real * policy; that is safe because every .cfp record is * self-describing, and the real policy is re-published through * the relcache once recovery ends. Outside recovery the relcache * publishes the policy via cfs_open_relation_smgr(); we do not * publish here, keeping the normal path unchanged. */ cfs_default_write_opts(&defopts); state->policy_gen = cfs_publish_options(state->rlocator, MAIN_FORKNUM, &defopts); state->opts = defopts; state->opts_valid = true; cfs_warn_fallback_codec(state, state->opts.algorithm, "during recovery"); } else { /* * Effective options unknown here; the write path supplies a * sensible default when opts_valid is false (see * cfs_smgr_write_opts()). */ state->opts.is_cfs = true; state->opts_valid = false; ereport(DEBUG1, (errmsg("CFS: smgr detected sidecar files for relation " "%u/%u/%u (policy not yet published)", state->rlocator.locator.spcOid, state->rlocator.locator.dbOid, state->rlocator.locator.relNumber))); } state->cfs_resolved = true; } else { state->is_cfs = false; state->opts_valid = true; state->cfs_resolved = true; state->opts.is_cfs = false; state->opts.algorithm = CFS_ALGORITHM_RAW; } } /* * cfs_default_write_opts * Fill 'opts' with the built-in default write policy: the first * available codec, with every tunable field left unset. * * 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) — previously the ladder was spelled out in both * cfs_smgr_write_opts() and cfs_smgr_publish_db_copy_policy(). Only * the codec choice is a physical fact here: level and minimum gain * keep the 0 sentinel with their set-flags cleared, because a fallback * is not an explicit user choice. Publishing it (shmem/WAL) therefore * carries nothing computed from a session GUC, and consumers re-resolve * those fields from their own GUCs at write time — the same "session * GUCs don't stick" contract as everywhere else. */ void cfs_default_write_opts(CfsEffectiveOptions *opts) { memset(opts, 0, sizeof(*opts)); opts->is_cfs = true; if (CfsCodecAvailable(CFS_ALGORITHM_LZ4)) opts->algorithm = CFS_ALGORITHM_LZ4; else if (CfsCodecAvailable(CFS_ALGORITHM_ZSTD)) opts->algorithm = CFS_ALGORITHM_ZSTD; else opts->algorithm = CFS_ALGORITHM_RAW; } /* * cfs_smgr_install_policy * Install a freshly resolved/published policy into the SMgrRelation's * local state, so the very next operation takes the fast path instead * of re-resolving from shared memory. The policy generation is stored * so that the generation check in cfs_smgr_ensure_state() does not * fire spuriously on the next call. */ static void cfs_smgr_install_policy(SMgrRelation reln, const CfsEffectiveOptions *opts, uint64 policy_gen) { if (reln->cfs_smgr == NULL) cfs_smgr_alloc(reln); reln->cfs_smgr->opts = *opts; reln->cfs_smgr->is_cfs = opts->is_cfs; reln->cfs_smgr->opts_valid = true; reln->cfs_smgr->cfs_resolved = true; reln->cfs_smgr->policy_gen = policy_gen; } /* * cfs_warn_unavailable_algo * Warn that a policy naming a codec that is not compiled into this * binary is being applied on a node that cannot honour it. * * DDL on the primary validates the algorithm against the primary's * own build, but the redo / standby paths apply a policy that was * validated on a different binary: the set of compiled-in codecs is * a per-build property and may legitimately differ between primary * and standby. The policy itself is published faithfully — the * shared-memory policy cache can represent a RAW policy (is_cfs set, * cfs_algo == 0) — but the actual degrade to RAW still happens at * the consumption point, cfs_smgr_write_opts(), which is where this * warning is issued. */ static void cfs_warn_unavailable_algo(RelFileLocator rlocator, CfsAlgorithm algo) { if (algo == CFS_ALGORITHM_RAW || CfsCodecAvailable(algo)) return; ereport(WARNING, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("CFS compression algorithm \"%s\" is not available in this build", CfsAlgorithmGetName(algo)), errdetail("New pages of relation %u/%u/%u will be stored as RAW until the relation is rewritten with an available algorithm.", rlocator.spcOid, rlocator.dbOid, rlocator.relNumber), errhint("Rebuild the server with the corresponding compression library to enable it."))); } /* * Install an already resolved policy. No catalog access is allowed here: * relcache invalidation can release borrowed SMgrRelation handles. */ static void cfs_smgr_set_resolved_policy(SMgrRelation reln, const CfsEffectiveOptions *opts) { uint64 gen = 0; bool published = false; /* Allocate local state before publishing the policy. */ if (reln->cfs_smgr == NULL) cfs_smgr_alloc(reln); Assert(!opts->is_cfs || !RelFileLocatorBackendIsTemp(reln->smgr_rlocator)); if (opts->is_cfs) { /* * Publish into shared memory so that auxiliary processes can resolve * the policy. This is the authoritative cross-process channel. The * returned generation is captured under the publication lock, so a * concurrent policy change cannot be missed by the local state. * * Skip the publication when this relation has a deferred policy * publication queued in the current transaction: the policy read from * the relcache comes from an uncommitted catalog change, and the * flush at commit (or the first reopen after abort) publishes the * surviving policy. */ if (!cfs_publish_is_pending(reln->smgr_rlocator, MAIN_FORKNUM)) { gen = cfs_publish_options(reln->smgr_rlocator, MAIN_FORKNUM, opts); published = true; } } /* Refresh the local state to match the published policy. */ cfs_smgr_install_policy(reln, opts, published ? gen : cfs_policy_generation(reln->smgr_rlocator, MAIN_FORKNUM)); } /* * Resolve under the caller's relation reference and locks. Changes to * CFS reloptions require AccessExclusiveLock, including on the TOAST * relation. A forced cache flush is not itself a policy change. */ static void cfs_resolve_smgr_policy(Relation rel, CfsEffectiveOptions *opts) { Oid relid = RelationGetRelid(rel); RelFileLocator locator = rel->rd_locator; ProcNumber backend = rel->rd_backend; CfsEffectiveOptionsFromRelation(rel, opts); if (relid != RelationGetRelid(rel) || !RelFileLocatorEquals(locator, rel->rd_locator) || backend != rel->rd_backend) elog(ERROR, "relation identity changed during CFS policy resolution"); } /* * A recursive lookup may have attached a handle already. Do not pin * it twice. Install policy before publishing rd_smgr; on ERROR the raw * unattached handle retains its normal transaction lifetime. */ static SMgrRelation cfs_open_resolved_smgr(Relation rel, const CfsEffectiveOptions *opts) { SMgrRelation reln = rel->rd_smgr; if (reln != NULL) { Assert(RelFileLocatorEquals(reln->smgr_rlocator.locator, rel->rd_locator)); Assert(reln->smgr_rlocator.backend == rel->rd_backend); return reln; } reln = smgropen(rel->rd_locator, rel->rd_backend); cfs_smgr_set_resolved_policy(reln, opts); smgrpin(reln); rel->rd_smgr = reln; return reln; } SMgrRelation cfs_open_relation_smgr(Relation rel) { CfsEffectiveOptions opts; cfs_resolve_smgr_policy(rel, &opts); return cfs_open_resolved_smgr(rel, &opts); } /* * Resolve before acquiring storage handles. The copy callers hold an * exclusive relation lock; use the same snapshot for destination local * state, shared publication and WAL. */ SMgrRelation cfs_prepare_copy_policy(Relation rel, CfsEffectiveOptions *opts) { cfs_resolve_smgr_policy(rel, opts); return cfs_open_resolved_smgr(rel, opts); } /* * cfs_materialize_sidecars * Create the sidecar files of a relation whose policy is being * published, unless they exist already (idempotent). * * This mirrors the policy redo (cfs_smgr_wal_policy_redo) and upholds * the mdcreate() contract for the base file: the sidecars exist from * the moment the policy is known, so no later operation ever has to * create them as a side effect. In particular the smgrtruncate() * bridge runs inside a critical section, where cfs_create()'s path * building and file initialization would turn any failure into a * PANIC of the whole server. fsync requests are registered * the same way the redo path registers them, so the next checkpoint * makes the created files durable. */ static void cfs_materialize_sidecars(RelFileLocator rlocator) { RelFileLocatorBackend rlb; CfsRelation *cfs; rlb.locator = rlocator; rlb.backend = INVALID_PROC_NUMBER; if (cfs_exists(rlb, MAIN_FORKNUM)) return; ereport(DEBUG1, (errmsg("CFS: creating sidecar files for relation %u/%u/%u", rlocator.spcOid, rlocator.dbOid, rlocator.relNumber))); cfs = cfs_create(rlb, MAIN_FORKNUM); cfs_close(cfs); cfs_register_dirty_file(rlb, MAIN_FORKNUM, CFS_FILE_DATA); cfs_register_dirty_file(rlb, MAIN_FORKNUM, CFS_FILE_MAP); cfs_register_dirty_file(rlb, MAIN_FORKNUM, CFS_FILE_JOURNAL); } /* * cfs_wal_log_policy_record * Emit the XLOG_SMGR_CFS_POLICY record for 'rlocator'. * * Every primary-side policy publication converges here (fresh * relations, relfilenode rewrites, tablespace / database copies), so * this is also where the sidecars are materialized on the primary — * the redo of this record does the same on a standby, and the files * must exist before the record that describes them hits the WAL. */ static void cfs_wal_log_policy_record(RelFileLocator rlocator, const CfsEffectiveOptions *opts) { xl_smgr_cfs_policy xlrec = {0}; cfs_materialize_sidecars(rlocator); xlrec.rlocator = rlocator; xlrec.level = opts->level; xlrec.min_gain_bytes = opts->min_gain_bytes; xlrec.algorithm = (uint8) opts->algorithm; xlrec.level_set = (uint8) opts->level_set; xlrec.min_gain_bytes_set = (uint8) opts->min_gain_bytes_set; XLogBeginInsert(); XLogRegisterData((char *) &xlrec, sizeof(xlrec)); XLogInsert(RM_SMGR_ID, XLOG_SMGR_CFS_POLICY | XLR_SPECIAL_REL_UPDATE); ereport(DEBUG1, (errmsg("CFS: WAL-logged policy for relation %u/%u/%u (algo=%d)", rlocator.spcOid, rlocator.dbOid, rlocator.relNumber, (int) opts->algorithm))); } /* * cfs_wal_log_new_relation_policy * Emit an XLOG_SMGR_CFS_POLICY record for a freshly created relation. * * Called right after the relation's storage was created (so the final * RelFileLocator is known) but still inside the creating transaction, * before any data-bearing WAL record for the relation can be written. * During redo the startup process has no relcache entry, so this record * is the only channel through which a standby (or crash recovery) * learns that the new relation is compressed *before* the first data * record for it replays. Without it, redo resolves is_cfs=false and * writes the replayed pages raw into the base file, making them * unreachable through the CFS read path forever. * * Only permanent relations are logged: CFS reloptions are rejected for * TEMP/UNLOGGED relations (cfs_check_persistence), and non-permanent * storage creation is not WAL-logged either. */ void cfs_wal_log_new_relation_policy(Relation rel, const CfsEffectiveOptions *opts) { if (!opts->is_cfs) return; /* Relations without physical storage have no fork to compress. */ if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind)) return; if (rel->rd_rel->relpersistence != RELPERSISTENCE_PERMANENT) return; cfs_wal_log_policy_record(rel->rd_locator, opts); } /* * cfs_wal_log_rewrite_policy * Emit an XLOG_SMGR_CFS_POLICY record for the new physical storage of * an in-place rewrite, carrying the *new* relfilelocator. * * TRUNCATE, REINDEX and the VACUUM FULL / CLUSTER index rebuild assign * a new relfilenumber to an existing relation via * RelationSetNewRelfilenumber(), which does not pass through * heap_create_with_catalog() / index_create() — the two places that * otherwise WAL-log the policy. Without this record redo would * resolve the rewritten storage as uncompressed (no relcache, no * shared-memory policy, no sidecar files at that point) and replay the * data pages raw into the base file, making them unreachable through * the CFS read path — the same contract as for a freshly created * relation. */ void cfs_wal_log_rewrite_policy(Relation rel, const RelFileLocator *newrlocator) { CfsEffectiveOptions opts; CfsEffectiveOptionsFromRelation(rel, &opts); if (!opts.is_cfs) return; /* Relations without physical storage have no fork to compress. */ if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind)) return; cfs_wal_log_policy_record(*newrlocator, &opts); } /* * cfs_smgr_publish_copy_policy * Publish the already resolved source policy for the freshly created * destination storage 'dstrel' of the ALTER ... SET TABLESPACE copy * paths (heapam_relation_copy_data() and index_copy_data()). * * RelationCreateStorage() resolves the destination's CFS-ness before * any policy exists for the new relfilelocator and therefore freezes * is_cfs=false: without this call the subsequent RelationCopyStorage() * would write the data raw and create no sidecar files, while * pg_class.reloptions would keep claiming the relation is compressed. * Publish the policy for the new locator (shared memory plus dstrel's * local state) so the copy goes through the CFS write path, and WAL-log * it so that redo learns the policy before the first copied page * replays — the same contract as for a freshly created relation. */ void cfs_smgr_publish_copy_policy(SMgrRelation dstrel, const CfsEffectiveOptions *opts, char relpersistence) { if (!opts->is_cfs) return; cfs_smgr_set_resolved_policy(dstrel, opts); if (relpersistence == RELPERSISTENCE_PERMANENT) cfs_wal_log_policy_record(dstrel->smgr_rlocator.locator, opts); } /* * cfs_smgr_publish_db_copy_policy * Publish the source relation's effective CFS policy for the freshly * created destination storage of the CREATE DATABASE ... STRATEGY * WAL_LOG copy path (CreateAndCopyRelationData()), and WAL-log it for * redo. * * The copying backend is connected to neither the source nor the * destination database, so there is no relcache entry to resolve the * policy from: the destination resolves is_cfs=false (no shared-memory * policy, no sidecar files yet) and RelationCreateStorage() has already * frozen that decision in dstrel's local state. Without this call the * bulk extend would physically lengthen the destination's base file and * the copied pages would be staged as plain buffers, while the copied * pg_class.reloptions keep claiming the relation is compressed: every * session opening the new database would consult the empty CFS map and * read 0 blocks until a checkpoint happened to flush the buffers * through the CFS write path (or forever, if the checkpoint came * first), and an extension in that window would trip over the mismatch * between the map (0 blocks) and the raw base file. * * The effective options are taken from the shared-memory policy cache * when the source's policy is published there, else from the source's * resolved SMgrRelation state, else the built-in default policy * (cfs_default_write_opts(), shared with the write path). Only the * compression of the copied blocks depends on the choice: * reads always honor the per-block algorithm recorded in the map. */ void cfs_smgr_publish_db_copy_policy(SMgrRelation srcrel, SMgrRelation dstrel) { CfsEffectiveOptions opts; uint64 policy_gen; const char *opts_source; if (!smgriscfsenabled(srcrel, MAIN_FORKNUM)) return; if (cfs_get_options(srcrel->smgr_rlocator, MAIN_FORKNUM, &opts)) opts_source = "shared cache"; else if (srcrel->cfs_smgr->opts_valid) { opts = srcrel->cfs_smgr->opts; opts_source = "source smgr state"; } else { cfs_default_write_opts(&opts); opts_source = "built-in default"; } opts.is_cfs = true; ereport(DEBUG1, (errmsg("CFS: database copy detected compressed relation %u/%u/%u, publishing policy for destination %u/%u/%u (algo=%d, source: %s)", srcrel->smgr_rlocator.locator.spcOid, srcrel->smgr_rlocator.locator.dbOid, srcrel->smgr_rlocator.locator.relNumber, dstrel->smgr_rlocator.locator.spcOid, dstrel->smgr_rlocator.locator.dbOid, dstrel->smgr_rlocator.locator.relNumber, (int) opts.algorithm, opts_source))); /* * Publish into shared memory so that every process — the checkpointer * flushing the copied buffers included — resolves the destination as * compressed from now on. */ policy_gen = cfs_publish_options(dstrel->smgr_rlocator, MAIN_FORKNUM, &opts); /* Undo the is_cfs=false decision RelationCreateStorage() froze. */ cfs_smgr_install_policy(dstrel, &opts, policy_gen); /* * WAL-log the policy so that redo learns it before the first copied page * replays — the same contract as for a freshly created relation (the * record lands right after the destination's XLOG_SMGR_CREATE). CFS * reloptions are rejected for TEMP/UNLOGGED relations, so a CFS source is * always permanent. Like log_smgrcreate() upstream, the record is not * gated on the WAL level: at wal_level=minimal the copy skips WAL, but * the sidecar materialization inside cfs_wal_log_policy_record() must * still happen, or a never-written source relation would leave the * destination without sidecars — reviving the first-touch creation race * the eager-creation contract removed. */ cfs_wal_log_policy_record(dstrel->smgr_rlocator.locator, &opts); } /* * cfs_wal_log_new_table_policy * Resolve the effective CFS policy of a freshly created heap-like * relation (table / matview / TOAST / sequence) from its raw reloptions * datum and WAL-log it. Called from heap_create_with_catalog(): at * this point the local relcache entry has no rd_options yet (they are * only stored into pg_class by AddNewRelationTuple), so the policy must * be resolved from the datum directly. */ void cfs_wal_log_new_table_policy(Relation rel, Datum reloptions) { CfsEffectiveOptions opts; StdRdOptions *stdopts; stdopts = (StdRdOptions *) heap_reloptions(rel->rd_rel->relkind, reloptions, false); CfsEffectiveOptionsFromStdRdOptions(stdopts, &opts); cfs_wal_log_new_relation_policy(rel, &opts); } /* * cfs_wal_log_new_index_policy * Same as cfs_wal_log_new_table_policy() for an index: the policy is * resolved from the index's own reloptions only (see * CfsEffectiveOptionsFromIndexReloptions) — an index without an * explicit algorithm logs no CFS policy and stays plain. */ void cfs_wal_log_new_index_policy(Relation heapRel, Relation indexRel, Datum reloptions) { CfsEffectiveOptions opts; if (!RELKIND_HAS_STORAGE(indexRel->rd_rel->relkind)) return; CfsEffectiveOptionsFromIndexReloptions(heapRel, indexRel->rd_rel->relam, reloptions, &opts); cfs_wal_log_new_relation_policy(indexRel, &opts); } /* * Redo of an XLOG_SMGR_CFS_POLICY record (see smgr_redo()). * * The record replays right after the relation's XLOG_SMGR_CREATE record, * whose cfs_smgr_create() may already have frozen a wrong is_cfs=false * decision (no relcache, no sidecars, no shared-memory policy at that * point); the SMgrRelation state correction below undoes that, so the * first data record for the relation replays through the CFS write path. * * The sidecar files are created eagerly (not lazily on first I/O as on the * primary): they double as the durable CFS marker for redo. If the standby * restarts from a checkpoint taken after this record but before the first * data write, shared memory is empty and only sidecar existence tells redo * that the relation is compressed. fsync requests are registered exactly * like mdcreate() does for redo-created base files, so the next * restartpoint makes the files durable. */ void cfs_smgr_wal_policy_redo(const xl_smgr_cfs_policy *xlrec) { RelFileLocatorBackend rlb; CfsEffectiveOptions opts; SMgrRelation reln; uint64 policy_gen; rlb.locator = xlrec->rlocator; rlb.backend = INVALID_PROC_NUMBER; opts.is_cfs = true; opts.algorithm = (CfsAlgorithm) xlrec->algorithm; opts.level = xlrec->level; opts.min_gain_bytes = xlrec->min_gain_bytes; opts.level_set = (bool) xlrec->level_set; opts.min_gain_bytes_set = (bool) xlrec->min_gain_bytes_set; /* * The replayed policy was validated against the primary's build; this * binary may lack the codec. Warn here; cfs_smgr_write_opts() stores new * pages as RAW during recovery so that redo-time page flushes cannot fail * fatally. */ cfs_warn_unavailable_algo(rlb.locator, opts.algorithm); /* Publish into shared memory for this and the auxiliary processes. */ policy_gen = cfs_publish_options(rlb, MAIN_FORKNUM, &opts); /* * Materialize the sidecars if they do not exist yet (idempotent replay): * they double as the durable CFS marker for redo. If the standby * restarts from a checkpoint taken after this record but before the first * data write, shared memory is empty and only sidecar existence tells * redo that the relation is compressed. */ cfs_materialize_sidecars(xlrec->rlocator); /* * If the SMgrRelation is already open in this process — the WAL * prefetcher may have resolved (and frozen) is_cfs=false while looking * ahead of the replay position — correct its state to match the policy. * smgropen() creates the entry if it does not exist yet; that is what * smgr_redo() does for XLOG_SMGR_CREATE as well. */ reln = smgropen(xlrec->rlocator, INVALID_PROC_NUMBER); cfs_smgr_install_policy(reln, &opts, policy_gen); ereport(DEBUG1, (errmsg("CFS: redo applied policy for relation %u/%u/%u (algo=%d)", rlb.locator.spcOid, rlb.locator.dbOid, rlb.locator.relNumber, (int) opts.algorithm))); } void cfs_smgr_close(SMgrRelation reln, ForkNumber forknum) { CfsSmgrState *state = reln->cfs_smgr; if (state == NULL || state->cfs == NULL) return; /* CFS only owns a handle for MAIN_FORKNUM. */ if (forknum == MAIN_FORKNUM) { ereport(DEBUG1, (errmsg("CFS: closing sidecar handle for relation %u/%u/%u", state->rlocator.locator.spcOid, state->rlocator.locator.dbOid, state->rlocator.locator.relNumber))); cfs_close(state->cfs); state->cfs = NULL; } } void cfs_smgr_release(SMgrRelation reln) { CfsSmgrState *state = reln->cfs_smgr; if (state == NULL) return; if (state->cfs != NULL) { ereport(DEBUG1, (errmsg("CFS: releasing sidecar handle for relation %u/%u/%u", state->rlocator.locator.spcOid, state->rlocator.locator.dbOid, state->rlocator.locator.relNumber))); cfs_close(state->cfs); state->cfs = NULL; } /* * Drop the metadata-slot pin so the slot (and its append lock) can be * reclaimed by LRU when no longer needed. */ if (state->cfs_pinned) cfs_map_cache_unpin(state->rlocator, MAIN_FORKNUM); pfree(state); reln->cfs_smgr = NULL; } /* ================================================================ * Predicates * ================================================================ */ bool smgriscfsenabled(SMgrRelation reln, ForkNumber forknum) { /* Only the main fork is ever compressed. */ if (forknum != MAIN_FORKNUM) return false; cfs_smgr_ensure_state(reln); return reln->cfs_smgr->is_cfs; } bool RelFileLocatorUsesCfs(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsEffectiveOptions opts; if (forknum != MAIN_FORKNUM) return false; /* TEMP locators are never CFS. */ if (RelFileLocatorBackendIsTemp(rlocator)) return false; if (cfs_get_options(rlocator, forknum, &opts)) return opts.is_cfs; return cfs_exists(rlocator, forknum); } /* ================================================================ * Handle management * ================================================================ */ /* * Return the sidecar handle, opening it on first use. On first access the * in-memory map is rebuilt from the .cfsmap snapshot + .cfsjrn replay, so the * returned handle reflects the last durable state. */ CfsRelation * cfs_smgr_get_handle(SMgrRelation reln) { CfsSmgrState *state; cfs_smgr_ensure_state(reln); state = reln->cfs_smgr; if (!state->is_cfs) return NULL; if (state->cfs == NULL) { MemoryContext oldcontext; ereport(DEBUG1, (errmsg("CFS: opening sidecar handle for relation %u/%u/%u", state->rlocator.locator.spcOid, state->rlocator.locator.dbOid, state->rlocator.locator.relNumber))); /* * The sidecars of a CFS relation are materialized when its policy is * published (cfs_materialize_sidecars), so the common case below is * opening existing files, which never creates anything. The * cfs_create() branch is a real fallback: cfs_open_relation_smgr() publishes the * policy into shared memory without materializing anything, so a * relation published only through it (created by an older binary, or * turned into CFS by reloptions before its first rewrite) can arrive * here with the sidecars still absent. This is safe: smgrnblocks() * runs before the truncation critical section, and a concurrent first * measure of such an empty relation can at worst race two * cfs_create()s without losing data. * * The handle (and all memory it allocates internally: paths, map, * scratch) must survive as long as the SMgrRelation, i.e. across * statement boundaries, so allocate it in TopMemoryContext. */ oldcontext = MemoryContextSwitchTo(TopMemoryContext); if (cfs_exists(state->rlocator, MAIN_FORKNUM)) { /* * Lazy handle (shared segment pool) only when the pool is on; * with cfs_map_memory=0 there are no segments to resolve entries * through, so the handle must carry its own full map (the * pre-pool behaviour). */ if (cfs_map_memory_effective()) state->cfs = cfs_open(state->rlocator, MAIN_FORKNUM, CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP); else state->cfs = cfs_open(state->rlocator, MAIN_FORKNUM, CFS_OPEN_RDWR); } else { ereport(DEBUG1, (errmsg("CFS: creating sidecar files for relation %u/%u/%u", state->rlocator.locator.spcOid, state->rlocator.locator.dbOid, state->rlocator.locator.relNumber))); state->cfs = cfs_create(state->rlocator, MAIN_FORKNUM); } MemoryContextSwitchTo(oldcontext); if (state->cfs == NULL) { /* * cfs_open returns NULL only for unsupported (temp) locators, * which cannot happen here because is_cfs was already resolved. */ ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not open sidecar files for relation %u/%u/%u", state->rlocator.locator.spcOid, state->rlocator.locator.dbOid, state->rlocator.locator.relNumber))); } /* * Pin the metadata slot so it — and the per-relation append lock * embedded in it — survives until the SMgrRelation is released. * cfs_map_cache_pin() raises ERROR if no slot can be allocated * (capacity exhausted), which is preferable to a later surprise * failure from cfs_append_lock_acquire() mid-write. */ if (!state->cfs_pinned) { cfs_map_cache_pin(state->rlocator, MAIN_FORKNUM); state->cfs_pinned = true; } /* * Warm the shared cache with the freshly-loaded disk state, but never * let this handle's local map shrink the authoritative cached size. * The local map reflects a point-in-time snapshot+journal read and * may lag behind a concurrent extension done by another backend * (whose journal record may not have been visible at open time); a * stale value published here would make a later cfs_smgr_nblocks() * reader extend at an already-occupied block. Only publish when the * cache is cold or the local value is at least as large. * * A lazy handle must not publish at all: its map_hdr.nblocks comes * from the .cfsmap snapshot alone and does not include journal-only * extensions. A cold slot is resolved by cfs_smgr_nblocks() through * a throwaway full handle, which publishes a verified value. */ if ((state->cfs->flags & CFS_OPEN_LAZY_MAP) == 0) { uint64 local_nb = (uint64) cfs_map_nblocks(state->cfs); uint64 cached_nb; if (!cfs_map_cache_get_nblocks(state->rlocator, MAIN_FORKNUM, &cached_nb) || local_nb >= cached_nb) cfs_map_cache_set_meta(state->rlocator, MAIN_FORKNUM, local_nb); } /* * open_generation was set by cfs_open_paths() when the handle was * created; nothing to refresh here. */ } return state->cfs; } /* * cfs_smgr_check_cfs — verify the dispatcher invariant without opening * anything. An operation reaches the CFS bridges only after * smgriscfsenabled() returned true for this SMgrRelation, and by then * is_cfs is frozen for its lifetime (cfs_resolved). A false verdict here * therefore means the dispatcher's invariant is broken; skipping the * operation silently would drop data (reads would return zeroed pages, * writes would vanish), so raise an internal error instead. The branch * is unreachable today — this is a defensive check with no direct test. */ static void cfs_smgr_check_cfs(SMgrRelation reln, const char *opname) { cfs_smgr_ensure_state(reln); if (!reln->cfs_smgr->is_cfs) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: %s dispatched for non-CFS relation %u/%u/%u", opname, reln->smgr_rlocator.locator.spcOid, reln->smgr_rlocator.locator.dbOid, reln->smgr_rlocator.locator.relNumber))); } /* * cfs_smgr_require_handle — fetch the sidecar handle or fail loudly via * cfs_smgr_check_cfs(). For a legitimate CFS relation the sidecars exist * since its policy was published, so opening never creates anything here; * only the defensive fallback inside cfs_smgr_get_handle() can create, see * the comment there. */ static CfsRelation * cfs_smgr_require_handle(SMgrRelation reln, const char *opname) { CfsRelation *cfs = cfs_smgr_get_handle(reln); if (cfs == NULL) cfs_smgr_check_cfs(reln, opname); /* raises ERROR */ return cfs; } /* * Reopen a cached handle whose sidecars were replaced by immedsync (which * does not bump the shared generation) or by compaction (which does). Both * TRUNCATE and zero-extend journal a RESIZE and must not do it through a * descriptor that names a replaced map inode. */ static void cfs_reopen_if_handle_stale(CfsRelation *cfs) { cfs_handle_refresh_if_stale(cfs); (void) cfs_reopen_if_map_swapped(cfs); } void cfs_smgr_resolve_physical(SMgrRelation reln) { CfsSmgrState *state; bool has_sidecars; /* * Ensure the CfsSmgrState exists and is populated (this calls * resolved-policy-equivalent logic), then override is_cfs / opts to match the * physical on-disk reality rather than the possibly-stale reloptions. */ cfs_smgr_ensure_state(reln); state = reln->cfs_smgr; has_sidecars = cfs_exists(reln->smgr_rlocator, MAIN_FORKNUM); state->is_cfs = has_sidecars; state->opts_valid = true; state->opts.is_cfs = has_sidecars; if (!has_sidecars) state->opts.algorithm = CFS_ALGORITHM_RAW; /* * Publish or forget the shared-memory policy so other backends and * auxiliary processes see the same reality. */ if (has_sidecars) state->policy_gen = cfs_publish_options(reln->smgr_rlocator, MAIN_FORKNUM, &state->opts); else { cfs_forget_options(reln->smgr_rlocator, MAIN_FORKNUM); state->policy_gen = cfs_policy_generation(reln->smgr_rlocator, MAIN_FORKNUM); } ereport(DEBUG1, (errmsg("CFS: resolve_physical for relation %u/%u/%u: " "has_sidecars=%d, is_cfs=%d", reln->smgr_rlocator.locator.spcOid, reln->smgr_rlocator.locator.dbOid, reln->smgr_rlocator.locator.relNumber, (int) has_sidecars, (int) state->is_cfs))); } /* * Build CfsWriteOptions for a write. When the effective policy was not * published yet (e.g. recovery), fall back to the first available codec at * the GUC default level. */ static void cfs_smgr_write_opts(SMgrRelation reln, CfsWriteOptions *wopts) { CfsSmgrState *state = reln->cfs_smgr; CfsAlgorithm algo; MemSet(wopts, 0, sizeof(CfsWriteOptions)); if (state->opts_valid && state->opts.is_cfs) algo = state->opts.algorithm; else { /* * Recovery / not-yet-published path: fall back to the built-in * default policy. Warn so administrators notice a codec mismatch * between primary and standby. */ CfsEffectiveOptions defopts; cfs_default_write_opts(&defopts); algo = defopts.algorithm; cfs_warn_fallback_codec(state, algo, "cold policy cache"); } /* * WAL redo / standby: the resolved policy may name a codec that is not * compiled into this binary (it was validated against the primary's * build, and the compiled-in codec set may legitimately differ). With * explicit_algorithm set below, an unavailable codec would make * CfsCompressPage() raise ERROR, which is fatal during WAL redo — so * during recovery store new pages as RAW instead; the per-record format * markers keep every page readable, and the policy record's redo has * already warned (cfs_warn_unavailable_algo()). On a writer node the * codec is guaranteed available by the DDL-time check, and after * promotion an unavailable explicit algorithm keeps failing loudly. */ if (RecoveryInProgress() && algo != CFS_ALGORITHM_RAW && !CfsCodecAvailable(algo)) { ereport(DEBUG1, (errmsg("CFS: algorithm \"%s\" is not available in this build, " "storing page as RAW during recovery", CfsAlgorithmGetName(algo)))); algo = CFS_ALGORITHM_RAW; } wopts->algorithm = algo; /* * Resolve the level: an explicitly stored value is used as-is; an unset * one is read from the session's per-algorithm GUC at the moment of this * write (vanilla default_toast_compression pattern), so a GUC change * affects the very next record and nothing is cached in the SMgrRelation * state. The cold-cache branch resolves through the same helper for the * fallback algorithm; RAW has no level. */ if (state->opts_valid && state->opts.is_cfs && state->opts.level_set) wopts->level = state->opts.level; else if (algo != CFS_ALGORITHM_RAW) wopts->level = cfs_default_level_for(algo); else wopts->level = CFS_COMPRESS_LEVEL_DEFAULT; /* * Narrow the level to the final algorithm's native ceiling: the GUC range * is per-algorithm, but a published policy may carry a level out of * range, so clamp defensively here too (and the installed libzstd ceiling * may be lower than the format bound). */ wopts->level = Min(wopts->level, CfsCodecMaxLevel(algo)); /* min_gain_bytes: explicit value or the session GUC, per write. */ if (state->opts_valid && state->opts.is_cfs && state->opts.min_gain_bytes_set) wopts->min_gain_bytes = state->opts.min_gain_bytes; else wopts->min_gain_bytes = cfs_default_min_gain_bytes; wopts->explicit_algorithm = true; wopts->allow_raw_fallback = true; } /* ================================================================ * smgr operation bridges * ================================================================ */ /* * cfs_smgr_create — the base main fork has just been created by md as a * zero-size compatibility marker. At this point the relation's effective * policy is not known yet (the reloptions reach the catalog after the * storage is created, and the WAL order is XLOG_SMGR_CREATE then * XLOG_SMGR_CFS_POLICY), so the CFS sidecars are materialized slightly * later, when the policy is published (cfs_materialize_sidecars): the * sidecars exist from then on, the same contract mdcreate() upholds for * the base file. cfs_smgr_get_handle()'s create path remains only as a * defensive fallback, unreachable by any of the four publication paths. */ void cfs_smgr_create(SMgrRelation reln, ForkNumber forknum, bool isRedo) { if (forknum != MAIN_FORKNUM) return; /* Resolve CFS-ness so later operations take the fast path. */ cfs_smgr_ensure_state(reln); ereport(DEBUG1, (errmsg("CFS: smgr_create for relation %u/%u/%u (isRedo=%d, is_cfs=%d)", reln->smgr_rlocator.locator.spcOid, reln->smgr_rlocator.locator.dbOid, reln->smgr_rlocator.locator.relNumber, (int) isRedo, (int) reln->cfs_smgr->is_cfs))); } void cfs_smgr_unlink(RelFileLocatorBackend rlocator, ForkNumber forknum, bool isRedo) { bool have_sidecars; if (forknum != MAIN_FORKNUM) return; /* * Physical predicate, like mdunlink(): the decision to remove the sidecar * files is taken from the files themselves, never from the policy cache — * a stale or garbage slot claiming is_cfs=false for a node whose sidecar * files are still on disk must not leak them. The cached slot is dropped * below whatever it says. */ have_sidecars = cfs_exists(rlocator, forknum); if (have_sidecars) { /* * For permanent relations the sidecar files must not be removed * before a checkpoint completes (mdunlink() follows this policy for * the base file). We register the unlinks with the sync queue so the * checkpointer performs them after fsync'ing the base relation. In * the redo / temp / binary-upgrade paths we remove the sidecars * immediately and forget any pending sync requests for them. */ if (isRedo || RelFileLocatorBackendIsTemp(rlocator)) { cfs_forget_sync_requests(rlocator, forknum); cfs_unlink(rlocator, forknum); } else { cfs_register_unlink_file(rlocator, forknum, CFS_FILE_DATA); cfs_register_unlink_file(rlocator, forknum, CFS_FILE_MAP); cfs_register_unlink_file(rlocator, forknum, CFS_FILE_JOURNAL); } } /* Drop any cached metadata / options for this relation. */ cfs_map_cache_invalidate(rlocator, forknum); cfs_shared_map_invalidate_relation(rlocator, forknum); cfs_forget_options(rlocator, forknum); if (have_sidecars) ereport(DEBUG1, (errmsg("CFS: unlinked sidecar files for relation %u/%u/%u (isRedo=%d)", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber, (int) isRedo))); } void cfs_smgr_extend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, const void *buffer, bool skipFsync) { CfsRelation *cfs; CfsWriteOptions wopts; int rc; cfs = cfs_smgr_require_handle(reln, "extend"); cfs_smgr_write_opts(reln, &wopts); wopts.skip_fsync = skipFsync; wopts.is_extend = true; rc = cfs_write_page_cached(cfs, blocknum, (const char *) buffer, &wopts); if (rc != CFS_STORAGE_OK) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not extend relation %u/%u/%u to block %u", reln->smgr_rlocator.locator.spcOid, reln->smgr_rlocator.locator.dbOid, reln->smgr_rlocator.locator.relNumber, blocknum))); } void cfs_smgr_zeroextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, int nblocks, bool skipFsync) { CfsRelation *cfs; int rc; cfs = cfs_smgr_require_handle(reln, "zeroextend"); cfs_append_lock_acquire(reln->smgr_rlocator, forknum, LW_EXCLUSIVE); /* * A compaction may have swapped the sidecar files while we waited for the * append lock, and an immedsync may have replaced the .cfsmap inode * without bumping the shared generation. Journaling the RESIZE through a * stale handle would use its stale map and cursors (and publish a stale * cfp EOF into the shared cache), so reopen the handle if its generation * is stale or its map descriptor names a replaced inode, the same * invariant the write path already upholds. */ cfs_reopen_if_handle_stale(cfs); rc = cfs_zero_extend(cfs, blocknum, nblocks); cfs_append_lock_release(reln->smgr_rlocator, forknum); if (rc != CFS_STORAGE_OK) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not zero-extend relation %u/%u/%u", reln->smgr_rlocator.locator.spcOid, reln->smgr_rlocator.locator.dbOid, reln->smgr_rlocator.locator.relNumber))); /* * Register the journal dirtied by the RESIZE record outside the append * lock, before the metadata refresh below — the same placement (and for * the same reason) as in cfs_write_page_cached(): when the sync queue is * full, cfs_register_dirty_file() falls back to a synchronous fsync, and * holding the lock through it would park every writer of the relation * behind that fsync. md.c makes the same choice: its * register_dirty_segment() fallback runs without any relation-level lock. */ if (!skipFsync) cfs_register_dirty_file(reln->smgr_rlocator, forknum, CFS_FILE_JOURNAL); /* * Publish the new logical size so cfs_smgr_nblocks() stays consistent * without re-opening the handle. */ cfs_map_cache_set_meta(reln->smgr_rlocator, forknum, (uint64) (blocknum + nblocks)); } /* * Failure codes encoded (negated) into the inline AIO result by * cfs_smgr_startreadv() and decoded by the aio_cfs_readv_cb callbacks. * Since QDB-1513 an IO may cover several blocks (a contiguous .cfp run); * the inline result carries only the code, so the report callback names * td->smgr.blockNum — the FIRST block of the IO — while the synchronous * entry point reports the exact failing block. The codes also land in the * error_data field of a PGAIO result with the id PGAIO_HCB_CFS_READV, * where they pass through the bit layout of buffer_readv_decode_error() * in bufmgr.c (shared_buffer_readv_complete_local decodes any * PGAIO_RS_ERROR regardless of the id): bits 0-1 select the zeroed/ignored * flags and bit 2 starts the checksum-failure count, so a value >= 4 would * be misread as a bogus checksum-failure report. Keep the codes below 4 — * asserted below; a new code must not cross that boundary without * adjusting the bufmgr decoder first. */ #define CFS_AIO_FAIL_CORRUPT 1 #define CFS_AIO_FAIL_IO 2 StaticAssertDecl(CFS_AIO_FAIL_CORRUPT < 4 && CFS_AIO_FAIL_IO < 4, "CFS AIO failure codes must stay below 4 " "(buffer_readv_decode_error bit layout)"); /* * cfs_read_blocks_status — decompress nblocks pages into the caller's * buffers WITHOUT throwing. Returns CFS_STORAGE_OK when every page was * read; otherwise returns the CfsStorageStatus of the first failure and, * for non-NULL out parameters, stores that code and the failing block * number. Used by both read entry points: the synchronous one raises the * error itself (parity with mdreadv), the AIO one encodes it into the IO * result. * * Since QDB-1513 the body batches physically contiguous runs of records * into single preads (cfs_read_pages_batch); blocks that cannot join a run * keep flowing through the per-block path, so the no-throw contract and * the failure semantics below are unchanged. Reads beyond the relation's * size (blocknum >= the map's nblocks) still raise ERROR from * cfs_read_page(), and a map refresh inside cfs_read_page_cached() can * raise on a corrupt .cfsmap prologue or journal header (and allocate). * cfs_smgr_startreadv() wraps this call and converts an escaping ERROR into * its inline failure code, so the AIO consumer still gets the failure * through the normal result channel; the synchronous entry point lets the * ERROR propagate. */ static int cfs_read_blocks_status(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, void **buffers, BlockNumber nblocks, int *fail_code, BlockNumber *fail_block) { CfsRelation *cfs = cfs_smgr_require_handle(reln, "readv"); return cfs_read_pages_batch(cfs, blocknum, buffers, nblocks, fail_code, fail_block); } void cfs_smgr_readv(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, void **buffers, BlockNumber nblocks) { int fail_code; BlockNumber fail_block; if (cfs_read_blocks_status(reln, forknum, blocknum, buffers, nblocks, &fail_code, &fail_block) == CFS_STORAGE_OK) return; if (fail_code == CFS_STORAGE_CORRUPT) { /* * Report corruption through the centralised handler which respects * the cfs_checksum_failure GUC (PGC_SUSET). The handler always * raises ERROR or PANIC — we never substitute a fabricated zero * page, because doing so would cause silent data divergence between * primary and standby . */ cfs_report_corruption(reln->smgr_rlocator, forknum, fail_block, "checksum or format error in compressed page", false); /* cfs_report_corruption always longjmps; not reached */ } else ereport(ERROR, (errcode(ERRCODE_IO_ERROR), errmsg("CFS: could not read block %u of relation %u/%u/%u", fail_block, reln->smgr_rlocator.locator.spcOid, reln->smgr_rlocator.locator.dbOid, reln->smgr_rlocator.locator.relNumber))); } /* * AIO target for a CFS span readv (P4-2): an IO worker reopens the .cfp * segment by identity (no cross-process fd); the span plan and the raw * span live in the shared scratch arena, so the vanilla preadv can run * in the worker and the validate+decompress phase runs in the executor's * completion callback. The fd comes from the vfd LRU cache (raw * descriptor via FileGetRawDesc), so the worker does not close it * explicitly - the same contract smgr_aio_reopen() follows. */ static void cfs_aio_reopen(PgAioHandle *ioh); static char *cfs_aio_describe_identity(const PgAioTargetData *sd); const PgAioTargetInfo aio_cfs_target_info = { .name = "cfs", .reopen = cfs_aio_reopen, .describe_identity = cfs_aio_describe_identity, }; static void cfs_aio_reopen(PgAioHandle *ioh) { PgAioTargetData *sd = pgaio_io_get_target_data(ioh); PgAioOpData *od = pgaio_io_get_op_data(ioh); RelFileLocatorBackend rl; char *fname; File file; /* * The caller prevents interrupts, otherwise the fd could be closed * again before the IO is executed (same contract as smgr_aio_reopen). */ Assert(!INTERRUPTS_CAN_BE_PROCESSED()); switch (pgaio_io_get_op(ioh)) { case PGAIO_OP_READV: break; default: pg_unreachable(); break; } rl.locator = sd->cfs.rlocator; rl.backend = INVALID_PROC_NUMBER; /* CFS relations are never temp */ /* * Generation gate: the plan's offsets belong to the sidecar-pair * epoch 'generation'. A compaction bumps the relation's map * generation when it swaps the files, so a mismatch means the name * below now resolves to a file the plan cannot describe. Fail the * IO transiently instead of reading wrong bytes and reporting a * bogus corruption: the next read re-plans against the new files. * The slot generation is compared, never trusted, below: a reader * whose backend died keeps its pin only until the AIO machinery * finishes this IO, and the handle is pinned for its lifetime. */ if (cfs_state_relation_generation(rl, sd->cfs.forkNum) != sd->cfs.generation) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: .cfp segment %u of relation %u/%u/%u was " "replaced while a read was in flight", sd->cfs.segment, sd->cfs.rlocator.spcOid, sd->cfs.rlocator.dbOid, sd->cfs.rlocator.relNumber))); } fname = cfs_make_segment_filename(rl, sd->cfs.forkNum, CFS_FILE_DATA, sd->cfs.segment); file = PathNameOpenFile(fname, O_RDONLY | PG_BINARY); if (file < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not reopen .cfp segment \"%s\" " "for an IO worker read", fname))); od->read.fd = FileGetRawDesc(file); pfree(fname); /* * Warm the codec states outside the completion critical section: the * executor's CfsDecompressPage() would otherwise allocate them * (TopMemoryContext) inside pgaio_io_process_completion(), where an * allocation failure escalates to PANIC. Results are ignored - a * codec missing from this build fails exactly like it does in the * backend when a record names it. */ for (int algo = 0; algo < CFS_ALGORITHM_COUNT; algo++) (void) CfsCodecStateCreate((CfsAlgorithm) algo); } static char * cfs_aio_describe_identity(const PgAioTargetData *sd) { return psprintf("CFS .cfp segment %u of relation %u/%u/%u fork %u, " "blocks %u..%u", sd->cfs.segment, sd->cfs.rlocator.spcOid, sd->cfs.rlocator.dbOid, sd->cfs.rlocator.relNumber, (ForkNumber) sd->cfs.forkNum, sd->cfs.blockNum, sd->cfs.blockNum + sd->cfs.nblocks - 1); } /* * AIO completion callback for cfs_smgr_startreadv(). Mirrors * md_readv_complete(): a negative result encodes a failure code; turn it * into PGAIO_RS_ERROR, keep the code in error_data and immediately report * it to the server log only. This runs inside the IO-completion critical * section, so nothing here may raise above LOG. A non-negative result is * already a block count (CFS never combines and never short-reads: the * transfer either produced every requested block or failed with a code), * so it is passed through unchanged for the SHARED_BUFFER_READV consumer. */ static PgAioResult aio_cfs_readv_complete(PgAioHandle *ioh, PgAioResult prior_result, uint8 cb_data) { PgAioTargetData *td = pgaio_io_get_target_data(ioh); PgAioResult result = prior_result; if (prior_result.result < 0) { result.status = PGAIO_RS_ERROR; result.id = PGAIO_HCB_CFS_READV; result.error_data = -prior_result.result; result.result = 0; /* * Immediately log a message about the IO error, but only to the * server log: the originator might not process the query result at * all (cancelled, or failed by another IO), and the definer of the IO * will raise the ERROR when processing the results. */ pgaio_result_report(result, td, LOG_SERVER_ONLY); return result; } Assert(result.result > 0); Assert(result.result <= td->smgr.nblocks); return result; } /* * AIO error reporting callback for cfs_smgr_startreadv(). Called with * elevel == ERROR by the consumer of a failed IO, and with a lower elevel * (e.g. LOG_SERVER_ONLY from aio_cfs_readv_complete) for immediate * logging; only the ERROR path raises. */ static void aio_cfs_readv_report(PgAioResult result, const PgAioTargetData *td, int elevel) { /* * Corruption keeps the centralised reporting path so the * cfs_checksum_failure GUC semantics (ERROR vs PANIC) and the usual * message text are preserved. CFS relations are never temp. The * during_recovery argument is deliberately false even though WAL redo * also goes through read_stream / StartReadBuffer(): the historic * synchronous path always reported corruption with during_recovery = * false, and cfs_report_corruption()'s recovery branch (which honours * cfs_recovery_strict) is reserved for the redo-time map/journal readers, * not for page reads. Keeping the AIO path identical preserves those GUC * semantics; whether redo-time page corruption should be governed by * cfs_recovery_strict as well is a separate question. */ if (result.error_data == CFS_AIO_FAIL_CORRUPT) { if (elevel >= ERROR) { RelFileLocatorBackend rlocator; rlocator.locator = td->smgr.rlocator; rlocator.backend = td->smgr.is_temp ? MyProcNumber : INVALID_PROC_NUMBER; cfs_report_corruption(rlocator, td->smgr.forkNum, td->smgr.blockNum, "checksum or format error in compressed page", false); } else ereport(elevel, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: could not read block %u of relation %u/%u/%u", td->smgr.blockNum, td->smgr.rlocator.spcOid, td->smgr.rlocator.dbOid, td->smgr.rlocator.relNumber))); } else ereport(elevel, (errcode(ERRCODE_IO_ERROR), errmsg("CFS: could not read block %u of relation %u/%u/%u", td->smgr.blockNum, td->smgr.rlocator.spcOid, td->smgr.rlocator.dbOid, td->smgr.rlocator.relNumber))); } const PgAioHandleCallbacks aio_cfs_readv_cb = { .complete_shared = aio_cfs_readv_complete, .report = aio_cfs_readv_report, }; /* * AIO completion callback for an OFFLOADED CFS span readv (P4-2). The * vanilla preadv (run by the IO worker, or inline when the method * executes the IO in the owner backend) has filled the scratch slot's * span buffer; this callback validates and decompresses every record of * the plan straight into the pinned target buffers and releases the * slot. It runs inside pgaio_io_process_completion()'s critical * section and possibly inside an IO worker: nothing here may raise * above LOG, and every failure is encoded into the result for * aio_cfs_span_readv_report() to raise in the owner backend - the * md_readv_complete()/buffer_readv_complete() contract. * * Registered after the buffer callback, so it executes FIRST * (last-registered-first): the pages it produces are exactly what the * buffer callback then verifies (PageIsVerified) and marks BM_VALID. * * The success result is the block count, the same currency the inline * path reports, so the buffer callback's short-read logic is unchanged. * * LWLocks inside the critical section: cfs_stats_count_*(), * cfs_read_span_corrupt_bookkeeping() and the pool invalidation take * partition/map lwlocks. This is a deliberate, bounded deviation from * the vanilla "no lwlocks in AIO callbacks" guidance, for three * reasons: (1) moving them to a complete_local callback does not leave * the critical section either (pgaio_io_call_complete_local() also * runs under START_CRIT_SECTION, see aio_callback.c); (2) every one of * these functions is guaranteed non-throwing (no ereport path reaches * them from here), so the critical section can never unwind through * them; (3) the held locks are leaf locks (stats partition or one map * segment lock) that are never acquired in the opposite order by * anything else holding them, so a worker cannot deadlock or block * longer than a single short critical region. The inline path takes * the same locks outside any critical section; the observable counter * and invalidation behaviour is required to stay identical between * the two paths, which pins the accounting here. */ static PgAioResult aio_cfs_span_readv_complete(PgAioHandle *ioh, PgAioResult prior_result, uint8 cb_data) { PgAioTargetData *td = pgaio_io_get_target_data(ioh); CfsReadScratchSlot *slot = cfs_read_scratch_slot(td->cfs.plan_slot); char *span = cfs_read_scratch_span(slot); PgAioResult result = prior_result; RelFileLocatorBackend rl; uint64 *io_data; uint8 handle_data_len; BlockNumber b; rl.locator = td->cfs.rlocator; rl.backend = INVALID_PROC_NUMBER; /* CFS relations are never temp */ /* Pairs with cfs_read_scratch_publish() in the planning backend. */ pg_read_barrier(); if (prior_result.result != (int32) slot->span_len) { /* * The transfer either produced every requested byte or failed. * Error currency mirrors the inline span path byte for byte: a * preadv error (negative errno) is a plain IO failure, while a * short read is the unexpected EOF that cfs_pread_all() reports * as NOENT and cfs_read_records_span() maps to CORRUPT — a * truncated .cfp tail is corruption, and the report must take * the cfs_report_corruption() route, not an internal error. * * A short read is the offloaded twin of a failing inline span, * so the pool bookkeeping must run here too (exactly what * cfs_read_pages_batch() does when cfs_read_records_span() * fails on pool-sourced rows): the crc failure is counted and * the pool row is invalidated, so a retry re-resolves the * block from the journal instead of deterministically * repeating the short read against the stale pooled offset. * An IO error (negative errno) keeps the inline semantics and * invalidates nothing. */ if (prior_result.result >= 0) cfs_read_span_corrupt_bookkeeping(rl, td->cfs.forkNum, td->cfs.blockNum, slot->pooled); result.status = PGAIO_RS_ERROR; result.id = PGAIO_HCB_CFS_SPAN_READV; result.error_data = (prior_result.result < 0) ? CFS_AIO_FAIL_IO : CFS_AIO_FAIL_CORRUPT; result.result = 0; pgaio_result_report(result, td, LOG_SERVER_ONLY); cfs_read_scratch_release(slot); return result; } io_data = pgaio_io_get_handle_data(ioh, &handle_data_len); Assert((uint32) handle_data_len == td->cfs.nblocks); Assert((uint32) handle_data_len == slot->plan_len); pgstat_report_wait_start(WAIT_EVENT_CFS_DECOMPRESS); for (b = 0; b < slot->plan_len; b++) { CfsReadPlanEntry *e = &slot->entries[b]; char *dst = BufferGetBlock((Buffer) io_data[e->buf_off]); CfsDecompressStatus dstatus; dstatus = CfsDecompressPage(span + e->rec_off, CFS_RECORD_SIZE(e->payload), dst, CFS_BLCKSZ, NULL); if (dstatus != CFS_DECOMPRESS_OK) { pgstat_report_wait_end(); /* * Partial-batch accounting mirrors cfs_read_records_span(): * records 0..b-1 were served per page; the still-uncounted * span summary is settled here so the read_batched_pages * balance survives this error path too. */ if (b > 0) cfs_stats_count_read_span(rl, td->cfs.forkNum, b); cfs_read_span_corrupt_bookkeeping(rl, td->cfs.forkNum, td->cfs.blockNum + b, slot->pooled); /* * Blocks before b keep their decompressed content, but the * IO fails as a whole with the whole-IO result 0 - bitwise * the inline path's failure semantics (the consumer never * observes a partially valid batch). */ result.status = PGAIO_RS_ERROR; result.id = PGAIO_HCB_CFS_SPAN_READV; result.error_data = CFS_AIO_FAIL_CORRUPT; result.result = 0; pgaio_result_report(result, td, LOG_SERVER_ONLY); cfs_read_scratch_release(slot); return result; } cfs_stats_count_read(rl, td->cfs.forkNum, e->payload); } pgstat_report_wait_end(); cfs_stats_count_read_span(rl, td->cfs.forkNum, slot->plan_len); /* Success: the result is the number of blocks the read produced. */ result.status = PGAIO_RS_OK; result.result = td->cfs.nblocks; cfs_read_scratch_release(slot); return result; } /* * AIO error reporting callback for an offloaded CFS span readv: the * owner-backend twin of aio_cfs_readv_report(), reading the CFS target * data instead of the smgr one (the report callback only receives the * union, hence the separate callback id). The first-block naming and * the cfs_checksum_failure routing are the inline path's contract. */ static void aio_cfs_span_readv_report(PgAioResult result, const PgAioTargetData *td, int elevel) { RelFileLocatorBackend rlocator; rlocator.locator = td->cfs.rlocator; rlocator.backend = INVALID_PROC_NUMBER; if (result.error_data == CFS_AIO_FAIL_CORRUPT) { if (elevel >= ERROR) cfs_report_corruption(rlocator, (ForkNumber) td->cfs.forkNum, td->cfs.blockNum, "checksum or format error in compressed page", false); else ereport(elevel, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: could not read block %u of relation %u/%u/%u", td->cfs.blockNum, td->cfs.rlocator.spcOid, td->cfs.rlocator.dbOid, td->cfs.rlocator.relNumber))); } else ereport(elevel, (errcode(ERRCODE_IO_ERROR), errmsg("CFS: could not read block %u of relation %u/%u/%u", td->cfs.blockNum, td->cfs.rlocator.spcOid, td->cfs.rlocator.dbOid, td->cfs.rlocator.relNumber))); } const PgAioHandleCallbacks aio_cfs_span_readv_cb = { .complete_shared = aio_cfs_span_readv_complete, .report = aio_cfs_span_readv_report, }; /* * cfs_span_offload_possible — gate for the offloaded read path (P4-2): * the arena must have bought slots, the method must be io_method=worker * (the design's degradation decision: sync stays inline, io_uring * reaps completions in the backend), IO_DIRECT_DATA must be off (the * arena pages are ordinary shared memory, not O_DIRECT-aligned) and the * request must be a multi-block read (a single block never pays for the * handoff) of a non-temporary relation (CFS relations are never temp; * the guard keeps the invariant cheap if that ever changes). */ static bool cfs_span_offload_possible(SMgrRelation reln, BlockNumber nblocks) { return cfs_read_scratch_effective() && io_method == IOMETHOD_WORKER && !(io_direct_flags & IO_DIRECT_DATA) && reln->smgr_rlocator.backend == INVALID_PROC_NUMBER && nblocks >= 2; } /* * cfs_aio_submit_span — plan and submit one offloaded span readv. * Returns the plan status: OK (the IO is staged, nothing left to do), * DEGRADE (the caller serves the whole request inline) or FAIL (the * caller registers the inline target and completes the handle with the * encoded failure code, exactly as a failed inline read would). */ static CfsReadPlanStatus cfs_aio_submit_span(PgAioHandle *ioh, SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, BlockNumber nblocks, int *fail_code, BlockNumber *fail_block, bool *out_published) { CfsRelation *cfs = cfs_smgr_require_handle(reln, "readv"); CfsReadScratchSlot *slot; PgAioTargetData *sd; struct iovec *iov; uint64 span_off; int fd; CfsReadPlanStatus prc; if (!(io_direct_flags & IO_DIRECT_DATA)) pgaio_io_set_flag(ioh, PGAIO_HF_BUFFERED); /* * Warm the codec states in the planning process: when the method * executes the IO synchronously in the owner (e.g. !IsUnderPostmaster, * the standalone/startup case), complete_shared - and with it the * first codec allocation - runs inside * pgaio_io_perform_synchronously()'s critical section, where an * allocation failure would escalate to PANIC. The worker side is * warmed at reopen for the same reason. Done BEFORE the plan is * built: after the slot is acquired nothing between acquire and * publish may throw, or the slot would be lost in BUILDING (the * adversarial-review fix). */ for (int algo = 0; algo < CFS_ALGORITHM_COUNT; algo++) (void) CfsCodecStateCreate((CfsAlgorithm) algo); prc = cfs_read_span_plan(cfs, blocknum, nblocks, &slot, &fd, &span_off, fail_code, fail_block); if (prc != CFS_READ_PLAN_OK) return prc; /* * Target and callbacks: the CFS target lets the worker reopen the * .cfp segment by identity; the span callback runs before the buffer * callback (registration order) and feeds it the block-count result. * * The union is zeroed first: the buffer completion's report callback * reads the target data with its own smgr lens (buffer_readv_report: * td->smgr.is_temp for the error path), and a zeroed union keeps * those aliasing reads defined (is_temp false, sane relpath) instead * of exposing bytes of this struct's padding. */ sd = pgaio_io_get_target_data(ioh); MemSet(sd, 0, sizeof(PgAioTargetData)); pgaio_io_set_target(ioh, PGAIO_TID_CFS); sd->cfs.rlocator = reln->smgr_rlocator.locator; sd->cfs.forkNum = forknum; sd->cfs.blockNum = blocknum; sd->cfs.nblocks = nblocks; sd->cfs.generation = cfs->open_generation; sd->cfs.plan_slot = cfs_read_scratch_slot_index(slot); sd->cfs.segment = CFS_CFP_SEGNO(span_off); /* * QDB-1569: bind the page-checksum skip decision here, in the owner * backend where the session GUC applies. The bit lives in the smgr * bitfield unit inside this member's zeroed padding (the aliasing * contract in aio_types.h), so it is written through the smgr lens * AFTER the cfs fields are filled. The buffer completion may run * in an IO worker with its own GUC copy, so the decision cannot be * re-read there. */ sd->smgr.cfs_skip_checksum = cfs_skip_page_checksum; /* * The plan becomes visible to the executor BEFORE the callbacks are * registered: with the slot published first, every remaining step * (registration, iovec setup, staging) that could ever throw leaves * a completable handle behind - the catch in cfs_smgr_startreadv() * finishes it through the already-registered span callback with a * plain IO failure code instead of re-registering the inline * callbacks on top (a second callback set would run the span * callback against an overwritten smgr-shaped union). */ cfs_read_scratch_publish(slot); *out_published = true; pgaio_io_register_callbacks(ioh, PGAIO_HCB_CFS_SPAN_READV, 0); /* One contiguous span buffer: a single iovec entry. */ (void) pgaio_io_get_iovec(ioh, &iov); Assert(iov != NULL); iov[0].iov_base = cfs_read_scratch_span(slot); iov[0].iov_len = slot->span_len; pgaio_io_start_readv(ioh, fd, 1, CFS_CFP_SEG_OFF((off_t) span_off)); return CFS_READ_PLAN_OK; } /* * cfs_aio_caught_error_code — shared catch-handling for both inline * paths: restore the error state and interrupt accounting of the * enclosing cfs_smgr_startreadv(), keep the original message at DEBUG1, * and map the SQLSTATE onto the inline failure code (DATA_CORRUPTED * keeps the corruption routing, everything else is a plain IO failure). */ static int cfs_aio_caught_error_code(MemoryContext oldcontext, uint32 save_holdoff, uint32 save_cancel_holdoff, uint32 save_crit_section) { ErrorData *edata; int fail_code; MemoryContextSwitchTo(oldcontext); edata = CopyErrorData(); FlushErrorState(); /* * errfinish() zeroes InterruptHoldoffCount, QueryCancelHoldoffCount * and CritSectionCount on the way into the handler. Restore what the * caller (smgrstartreadv) held, so its RESUME_INTERRUPTS() after this * function returns stays balanced and its critical-section accounting * is unchanged. */ InterruptHoldoffCount = save_holdoff; QueryCancelHoldoffCount = save_cancel_holdoff; CritSectionCount = save_crit_section; if (edata->detail != NULL) elog(DEBUG1, "CFS: synchronous AIO read failed: %s (%s)", edata->message, edata->detail); else elog(DEBUG1, "CFS: synchronous AIO read failed: %s", edata->message); fail_code = (edata->sqlerrcode == ERRCODE_DATA_CORRUPTED) ? CFS_STORAGE_CORRUPT : CFS_STORAGE_ERROR; FreeErrorData(edata); return fail_code; } void cfs_smgr_startreadv(PgAioHandle *ioh, SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, void **buffers, BlockNumber nblocks) { int fail_code = 0; volatile int result; volatile uint32 save_holdoff = InterruptHoldoffCount; volatile uint32 save_cancel_holdoff = QueryCancelHoldoffCount; volatile uint32 save_crit_section = CritSectionCount; MemoryContext oldcontext = CurrentMemoryContext; /* * CFS pages are stored compressed: a raw pread() cannot produce them. * The default path therefore decompresses the requested blocks * synchronously into the caller's buffers and completes the AIO * handle inline. Since P4-2, the io_method=worker configuration can * instead offload the raw preadv into a shared scratch slot and let * the executor (IO worker) validate+decompress, see * cfs_aio_submit_span() above. * * Unlike the synchronous entry point, a read failure must NOT be raised * here: the target and callbacks are registered first, the failure is * encoded into the inline result (negated failure code, like md encodes * errno), and the consumer of the IO result raises the ERROR through * aio_cfs_readv_report — the same contract mdstartreadv() follows. * * cfs_read_blocks_status() itself can still throw: a map reload inside * cfs_read_page_cached() raises on a corrupt .cfsmap prologue or journal * header. An escaping ERROR would leave the registered handle * uncompleted (and the caller would never see its result), so the * synchronous read is wrapped: the catch maps the SQLSTATE onto the same * inline failure code, keeps the original error at DEBUG1 for * diagnostics, and the handle is completed exactly once after the * PG_TRY/PG_CATCH block. The consumer still raises the ERROR through * aio_cfs_readv_report, so from the caller's point of view the failure * arrives via the normal AIO result path. * * A DATA_CORRUPTED state becomes CFS_AIO_FAIL_CORRUPT, so the later * report goes through cfs_report_corruption() and honours * cfs_checksum_failure (including panic) — unlike the plain ERROR the * structural readers used to raise on this path. */ /* * Offload attempt (P4-2): plan the request as one contiguous span and * hand it to the executor. The plan phase can throw exactly where * the inline path can (a corrupt .cfsmap prologue or journal header * during the refresh); the same catch converts the error into the * inline failure code below. The submit phase after a successful * plan is pure state machine work and cannot throw, so the catch * can never see a staged IO. */ if (cfs_span_offload_possible(reln, nblocks)) { BlockNumber fail_block = InvalidBlockNumber; volatile CfsReadPlanStatus prc = CFS_READ_PLAN_DEGRADE; volatile bool published = false; PG_TRY(); { prc = cfs_aio_submit_span(ioh, reln, forknum, blocknum, nblocks, &fail_code, &fail_block, (bool *) &published); } PG_CATCH(); { fail_code = cfs_aio_caught_error_code(oldcontext, save_holdoff, save_cancel_holdoff, save_crit_section); if (published) { /* * The plan was made visible and the span callback is * already registered on the handle. Finish the IO * through that callback with a plain IO failure: the * span completion takes the short-read branch, reports * through the AIO result and releases the slot. The * inline FAIL path below must NOT run here - it would * register a second callback set and overwrite the * union through pgaio_io_set_target_smgr(). */ pgaio_io_complete_inline(ioh, PGAIO_OP_READV, -CFS_AIO_FAIL_IO); return; } prc = CFS_READ_PLAN_FAIL; } PG_END_TRY(); if (prc == CFS_READ_PLAN_OK) return; if (prc == CFS_READ_PLAN_FAIL) { if (!(io_direct_flags & IO_DIRECT_DATA)) pgaio_io_set_flag(ioh, PGAIO_HF_BUFFERED); pgaio_io_set_target_smgr(ioh, reln, forknum, blocknum, nblocks, false); /* * QDB-1569: bind the checksum-skip decision at submit time * in the owner backend (the buffer completion may run in * an IO worker with its own GUC copy). Harmless on this * failure path — failed reads skip verification anyway — * and the same assignment is repeated on the inline * degrade path below. */ pgaio_io_get_target_data(ioh)->smgr.cfs_skip_checksum = cfs_skip_page_checksum; pgaio_io_register_callbacks(ioh, PGAIO_HCB_CFS_READV, 0); pgaio_io_complete_inline(ioh, PGAIO_OP_READV, (fail_code == CFS_STORAGE_CORRUPT) ? -CFS_AIO_FAIL_CORRUPT : -CFS_AIO_FAIL_IO); return; } /* CFS_READ_PLAN_DEGRADE: serve the whole request inline. */ } if (!(io_direct_flags & IO_DIRECT_DATA)) pgaio_io_set_flag(ioh, PGAIO_HF_BUFFERED); pgaio_io_set_target_smgr(ioh, reln, forknum, blocknum, nblocks, false); /* QDB-1569: checksum-skip bit, see the assignment above. */ pgaio_io_get_target_data(ioh)->smgr.cfs_skip_checksum = cfs_skip_page_checksum; pgaio_io_register_callbacks(ioh, PGAIO_HCB_CFS_READV, 0); /* The success result is the number of blocks the read produced. */ result = (int) nblocks; PG_TRY(); { if (cfs_read_blocks_status(reln, forknum, blocknum, buffers, nblocks, &fail_code, NULL) != CFS_STORAGE_OK) result = (fail_code == CFS_STORAGE_CORRUPT) ? -CFS_AIO_FAIL_CORRUPT : -CFS_AIO_FAIL_IO; } PG_CATCH(); { fail_code = cfs_aio_caught_error_code(oldcontext, save_holdoff, save_cancel_holdoff, save_crit_section); result = (fail_code == CFS_STORAGE_CORRUPT) ? -CFS_AIO_FAIL_CORRUPT : -CFS_AIO_FAIL_IO; } PG_END_TRY(); /* * Exactly one completion for every path: success, an inline failure code * from the status read, or a caught ERROR. Kept outside PG_TRY so a * throw from the completion machinery could never be completed twice. */ pgaio_io_complete_inline(ioh, PGAIO_OP_READV, result); } uint32 cfs_smgr_maxcombine(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum) { CfsRelation *cfs = cfs_smgr_require_handle(reln, "maxcombine"); /* * QDB-1513: combine as many blocks as form a physically contiguous run * of records in .cfp (compacted or freshly loaded relations store * logical neighbours back-to-back). The value is advisory: the read * entry points re-derive the grouping at read time and degrade any * block that no longer fits a run to the per-block path, so a race with * compaction or eviction merely shrinks the batches. The walk reads * only already-resident map state — no I/O, no pool residency — and * bufmgr additionally clamps the answer by io_combine_limit. */ return (uint32) cfs_map_contiguous_run(cfs, blocknum, (BlockNumber) io_combine_limit); } /* * cfs_smgr_advise_segment — issue one prefetch or writeback advice for * [off, off + len) of .cfp segment 'segno'. The descriptor comes from the * handle's read cache (cfs_cfp_read_segment_fd); it stays owned by the * handle and is never closed here. A segment that cannot be opened is * skipped: the advice is best-effort, the regular read path re-resolves * everything. Failures of the advice itself are ignored exactly like * mdprefetch() ignores FilePrefetch() results (md.c): a failed hint costs * at most a cold read or a later writeback, never correctness. No wait * event is registered around posix_fadvise(), which only queues kernel * advice and never blocks; sync_file_range() may block when too much * dirty data is queued (the pg_flush_data() note), so it reports under * the data-file flush wait event, like mdwriteback(). */ static void cfs_smgr_advise_segment(CfsRelation *cfs, uint32 segno, uint64 off, uint64 len, bool for_write) { int fd; fd = cfs_cfp_read_segment_fd(cfs, segno); if (fd < 0) return; if (for_write) { #if defined(HAVE_SYNC_FILE_RANGE) int rc; pgstat_report_wait_start(WAIT_EVENT_DATA_FILE_FLUSH); retry: rc = sync_file_range(fd, (off_t) off, (off_t) len, SYNC_FILE_RANGE_WRITE); if (rc != 0 && errno == EINTR) goto retry; pgstat_report_wait_end(); /* * Other errors are ignored: this is a scheduling hint and the * buffer manager requires writeback to never error out. */ #endif } else { #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED) int rc; retry_prefetch: rc = posix_fadvise(fd, (off_t) off, (off_t) len, POSIX_FADV_WILLNEED); if (rc == EINTR) goto retry_prefetch; /* * posix_fadvise() returns the error code directly; other errors * (EINVAL, EBADF, ...) are ignored like mdprefetch() does. */ #endif } } /* * cfs_smgr_advise_range — walk the map entries of [blocknum, blocknum + * nblocks) and hand each run of physically contiguous records inside one * .cfp segment to cfs_smgr_advise_segment() (records are merged while * off == prev_off + prev_len, so the advice is one per run, not one per * record). Purely advisory, mirroring cfs_map_contiguous_run() / * cfs_gather_contiguous_run(): only already-resident map state is * consulted (the private map array or resident pool segments, * tag-checked), with no residency work and no journal replay — a miss, * INVALID slot or stale generation after compaction is simply skipped, * so races with compaction or eviction at most drop advice, never * correctness. Skipped blocks merely end the current run. */ static void cfs_smgr_advise_range(CfsRelation *cfs, BlockNumber blocknum, BlockNumber nblocks, bool for_write) { RelFileLocatorBackend rl = cfs->rlocator; ForkNumber forknum = cfs->forknum; bool have_run = false; uint32 run_segno = 0; uint64 run_off = 0; uint64 run_len = 0; BlockNumber b; if (nblocks == 0) return; /* * Clamp the walk to MaxBlockNumber rather than failing the call the * way mdprefetch() does (it returns false past EOF): for a hint there * is nothing to report, and no entry past the last real block can be * in the map anyway. */ if ((uint64) blocknum + nblocks > (uint64) MaxBlockNumber + 1) nblocks = (BlockNumber) ((uint64) MaxBlockNumber + 1 - blocknum); for (b = 0; b < nblocks; b++) { CfsMapEntry entry; uint64 seg_gen = 0; uint64 rec_off = 0; uint64 rec_len = 0; uint32 segno = 0; bool have = false; bool extends_run = false; if (cfs->map != NULL) { /* * Private map (cfs_map_memory=0): the array is this handle's * own snapshot, so no generation tag applies; it may lag the * logical size, hence the double bound. */ if ((uint64) (blocknum + b) < cfs->map_hdr.nblocks && (uint64) (blocknum + b) < cfs->map_capacity) { entry = cfs->map[blocknum + b]; have = true; } } else { have = cfs_shared_map_lookup(rl, forknum, blocknum + b, &entry, &seg_gen) && cfs_seg_tag_matches(seg_gen, cfs); } if (have && CFS_MAP_ENTRY_VALID(&entry)) { segno = CFS_CFP_SEGNO(entry.physical_offset); rec_off = (uint64) CFS_CFP_SEG_OFF(entry.physical_offset); rec_len = (uint64) CFS_RECORD_SIZE(entry.compressed_size); extends_run = have_run && segno == run_segno && rec_off == run_off + run_len; } if (extends_run) { run_len += rec_len; continue; } /* The run ended (hole, miss, stale tag, gap or new segment). */ if (have_run) { cfs_smgr_advise_segment(cfs, run_segno, run_off, run_len, for_write); have_run = false; } if (have && CFS_MAP_ENTRY_VALID(&entry)) { run_segno = segno; run_off = rec_off; run_len = rec_len; have_run = true; } } if (have_run) cfs_smgr_advise_segment(cfs, run_segno, run_off, run_len, for_write); } /* * cfs_smgr_open_advisory — open a throwaway read-only sidecar handle for * the advisory smgr paths (prefetch / writeback). Both are issued from * the bgwriter / checkpointer / an arbitrary backend inside the smgr.c * dispatcher's HOLD_INTERRUPTS, and a hint must never break its caller * (the mdwriteback "never error out" contract): cfs_open() can raise on * a partially-present sidecar pair left by a concurrent drop, on a * corrupted prologue, on metadata-slot exhaustion inside the open guard * or on a plain EMFILE. Every such ERROR is therefore caught here and * quietly turned into NULL: a damaged pair is surfaced by the next real * I/O anyway, and the hint only loses one round of advice. The caught * error is not reported (no EmitErrorReport) to keep a permanently * damaged pair from spamming the log out of a background process. * * CFS_OPEN_RDONLY keeps the open side-effect free: the lead-in / prologue * / journal-header creation branches are gated on !read_only, and no * CFS_OPEN_CREATE means cfs_open_sidecar() never creates a file. The * quiet CFS_OPEN_MISSING_OK contract returns NULL for a fully missing * sidecar triple (a dropped relation) without an error. The LAZY_MAP * choice mirrors cfs_smgr_get_handle(): with the segment pool on (the * default) the advice resolves blocks through the pool and must not pay * a full map load for a hint; with the pool off the private map array * is the only resolver. * * The returned handle is unpinned (no metadata slot, no append lock): * cfs_smgr_advise_range() only reads the pool and the handle's own fd * cache, neither of which needs the slot alive. Close it with * cfs_close() — its memory is TopMemoryContext, so a caller that keeps * running after the advice must not leak one per call. * * errfinish() zeroes InterruptHoldoffCount / QueryCancelHoldoffCount / * CritSectionCount on the way into the handler, which would unbalance * the caller's RESUME_INTERRUPTS() (the dispatcher holds interrupts * around this hint). Restore them the way cfs_aio_caught_error_code() * does for the inline AIO read paths. */ static CfsRelation * cfs_smgr_open_advisory(SMgrRelation reln, ForkNumber forknum) { MemoryContext oldcontext = CurrentMemoryContext; volatile uint32 save_holdoff = InterruptHoldoffCount; volatile uint32 save_cancel_holdoff = QueryCancelHoldoffCount; volatile uint32 save_crit_section = CritSectionCount; int flags = CFS_OPEN_RDONLY | CFS_OPEN_MISSING_OK; CfsRelation *cfs = NULL; if (cfs_map_memory_effective()) flags |= CFS_OPEN_LAZY_MAP; PG_TRY(); { cfs = cfs_open(reln->smgr_rlocator, forknum, flags); } PG_CATCH(); { MemoryContextSwitchTo(oldcontext); FlushErrorState(); InterruptHoldoffCount = save_holdoff; QueryCancelHoldoffCount = save_cancel_holdoff; CritSectionCount = save_crit_section; cfs = NULL; } PG_END_TRY(); return cfs; } /* * cfs_smgr_prefetch — the smgr_prefetch bridge for CFS relations (see the * contract in cfs_smgr.h). POSIX_FADV_WILLNEED is issued per contiguous * .cfp run resolved through the block map, warming the page cache the * synchronous CFS reads later read from; CFS reads themselves stay * synchronous, this changes no read route. The sidecar pair is opened * through the quiet throwaway cfs_smgr_open_advisory() above: the hint * never raises and never materializes anything on disk. */ bool cfs_smgr_prefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, int nblocks) { #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED) { CfsRelation *cfs = cfs_smgr_open_advisory(reln, forknum); if (cfs == NULL) { /* * No sidecar pair: fully missing (a dropped relation, or one * whose policy was published without materializing sidecars) * or unopenable as a whole (the quiet catch above). In * recovery report the relation missing — the smgrprefetch * contract lets the WAL redo machinery treat it as dropped by * a later record; outside recovery the hint is simply not * applicable. */ return InRecovery ? false : true; } cfs_smgr_advise_range(cfs, blocknum, (BlockNumber) nblocks, false); cfs_close(cfs); } #else /* * Platform without posix_fadvise(POSIX_FADV_WILLNEED): nothing to * initiate. Claim success so callers never treat the relation as * missing. */ #endif return true; } /* * cfs_smgr_writeback — the smgr_writeback bridge for CFS relations (see * the contract in cfs_smgr.h): start kernel writeback of the .cfp ranges * the blocks live in. This must never raise and never create anything: * the buffer manager may issue writeback for a relation that was dropped * after its buffers were scheduled (mdwriteback tolerates the same race), * so the pair is opened through the quiet read-only * cfs_smgr_open_advisory(), whose MISSING_OK contract returns NULL for a * fully missing triple and whose catch swallows the partially-present * window of a concurrent drop without recreating the files. */ void cfs_smgr_writeback(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, BlockNumber nblocks) { #ifdef HAVE_SYNC_FILE_RANGE { CfsRelation *cfs = cfs_smgr_open_advisory(reln, forknum); if (cfs == NULL) return; cfs_smgr_advise_range(cfs, blocknum, nblocks, true); cfs_close(cfs); } #else /* * sync_file_range() is Linux-only; writeback stays a no-op elsewhere * (the checkpoint's CFS fsync path provides durability regardless). */ #endif } void cfs_smgr_writev(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, const void **buffers, BlockNumber nblocks, bool skipFsync) { BlockNumber b; CfsWriteOptions wopts; CfsRelation *cfs; cfs_smgr_write_opts(reln, &wopts); wopts.skip_fsync = skipFsync; /* * WAL compatibility: the buffers arriving here are always full * uncompressed BLCKSZ pages that have already passed through the standard * FlushBuffer() -> XLogFlush() path. CFS never writes compressed bytes * into WAL; compression happens only at this smgr write boundary. */ /* * One descriptor per call (the D3 hygiene item): the handle is per * SMgrRelation and valid for every block of this writev, so resolve it * once instead of per block. In the current tree nblocks is always 1, * which makes this a pure code-hygiene change with no measurable * effect; it prepares the path for real multi-block callers. */ cfs = cfs_smgr_require_handle(reln, "writev"); for (b = 0; b < nblocks; b++) { int rc; /* The buffer is always a full uncompressed page (WAL compatibility). */ Assert(buffers[b] != NULL); rc = cfs_write_page_cached(cfs, blocknum + b, (const char *) buffers[b], &wopts); if (rc != CFS_STORAGE_OK) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not write block %u of relation %u/%u/%u", blocknum + b, reln->smgr_rlocator.locator.spcOid, reln->smgr_rlocator.locator.dbOid, reln->smgr_rlocator.locator.relNumber))); } } /* * Throwaway full-map handles: a shared counter (the checkpoint opens its * handle in the checkpointer process, so a per-process count could not be * observed from a backend). Test observability for the cfs_map_memory=0 * path and for the checkpoint's lazy-handle contract: with the pool * disabled the persistent handle already owns a full map, so a size/sync * path must not build a second one, and a checkpoint must not build one * at all - its cost tracks the journal, not the table. */ /* * The shared body of the throwaway pinned openers below: open the * sidecars with 'open_flags', count a full-map open when asked, and pin * the relation's metadata slot so the slot and its append lock stay * addressable while the handle lives. * * 'required' selects the failure contract: a caller that may legitimately * find the sidecars gone between listing a dirty slot and opening them * passes false and handles the NULL; everyone else raises. The pin runs * under PG_TRY protection: cfs_map_cache_pin() raises ERROR when the * partition is exhausted, and the descriptors opened just above must not * leak past it. Every successful open is paired with * cfs_close_full_unpinned() in PG_FINALLY; pinning only after a * successful open keeps the two halves symmetric. */ static CfsRelation * cfs_open_pinned(RelFileLocatorBackend rl, ForkNumber forknum, bool required, int open_flags, bool count_full_map_open) { CfsRelation *cfs; cfs = cfs_open(rl, forknum, open_flags); if (cfs == NULL) { if (!required) return NULL; ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not open sidecar files for relation %u/%u/%u", rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber))); } if (count_full_map_open) cfs_shared_note_full_map_open(rl, forknum); PG_TRY(); { cfs_map_cache_pin(rl, forknum); } PG_CATCH(); { cfs_close(cfs); PG_RE_THROW(); } PG_END_TRY(); return cfs; } /* * Open a throwaway FULL handle (one with its own private map). Used by * the paths that must assemble or persist the complete map: sizing and * immediate sync. */ CfsRelation * cfs_open_full_pinned(RelFileLocatorBackend rl, ForkNumber forknum, bool required) { return cfs_open_pinned(rl, forknum, required, CFS_OPEN_RDWR, true); } uint64 cfs_smgr_full_map_open_count(void) { return cfs_shared_full_map_opens(); } /* * Open a throwaway LAZY handle (descriptors and the map prologue only, no * private map array). The checkpoint fold works straight off the sidecar * files, so it never pays a full-map load; see cfs_smgr.h. * * The open is serialised against an in-flight compaction or immedsync: * the metadata slot is pinned and the append lock taken BEFORE cfs_open() * runs the interrupted-swap recovery. Compaction holds this same lock * across its whole copy + swap window, so an open under the lock can * never observe a half-staged candidate pair: the "a lock-free path * opener must not be added without revisiting this" invariant of * cfs_swap.c is upheld by taking the lock instead. The lock discipline * follows 'required': the checkpoint's dirty-slot sweep passes false and * stays conditional - a taken lock means one of those long holders is at * work and the relation is skipped for one round rather than stalled * behind it (the dirty mark is untouched, so the next checkpoint * retries) - while every other caller blocks, so a busy lock can never * surface as its NULL. * * 'required' selects the failure contract too: a caller that may * legitimately find the sidecars gone between listing a dirty slot and * opening them passes false and handles the NULL - the unsupported * locator, the vanished sidecar pair (CFS_OPEN_MISSING_OK) and the busy * append lock of the conditional acquisition above; everyone else * raises. */ CfsRelation * cfs_open_lazy_pinned(RelFileLocatorBackend rl, ForkNumber forknum, bool required) { CfsRelation *cfs; int flags = CFS_OPEN_RDWR | CFS_OPEN_LAZY_MAP; if (!required) flags |= CFS_OPEN_MISSING_OK; /* The slot must outlive the lock: pin before acquiring it. */ cfs_map_cache_pin(rl, forknum); if (required) cfs_append_lock_acquire(rl, forknum, LW_EXCLUSIVE); else if (!cfs_append_lock_try_acquire(rl, forknum)) { cfs_map_cache_unpin(rl, forknum); return NULL; } PG_TRY(); { cfs = cfs_open(rl, forknum, flags); } PG_CATCH(); { cfs_append_lock_release_after_error(rl, forknum); cfs_map_cache_unpin(rl, forknum); PG_RE_THROW(); } PG_END_TRY(); cfs_append_lock_release(rl, forknum); if (cfs == NULL) { cfs_map_cache_unpin(rl, forknum); if (required) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not open sidecar files for relation %u/%u/%u", rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber))); return NULL; } return cfs; } /* * Close a handle opened by cfs_open_full_pinned() or cfs_open_lazy_pinned() * and release its pin. */ void cfs_close_full_unpinned(CfsRelation *cfs, RelFileLocatorBackend rl, ForkNumber forknum) { cfs_close(cfs); cfs_map_cache_unpin(rl, forknum); } /* * Return a handle owning a private full map for a path that must replay the * journal. With the pool enabled the persistent smgr handle is lazy (no * private map), so a throwaway full handle is opened. With the pool * disabled (cfs_map_memory=0) the persistent handle already carries a full * map; reusing it avoids a second copy of the whole map and a duplicate * .cfsmap read on every such call. * * 'ensure_persistent' opens the persistent smgr handle when it is not open * yet; callers that need it for a later critical section pass true. With * false only an already-open handle is reused. * * '*throwaway' tells the caller whether the result must be closed with * cfs_close_full_unpinned(); the persistent handle stays owned by the * SMgrRelation. */ static CfsRelation * cfs_smgr_full_map_handle(SMgrRelation reln, ForkNumber forknum, const char *opname, bool ensure_persistent, bool *throwaway) { CfsRelation *cfs = (reln->cfs_smgr != NULL) ? reln->cfs_smgr->cfs : NULL; if (cfs == NULL && ensure_persistent) cfs = cfs_smgr_require_handle(reln, opname); if (cfs != NULL && cfs->map != NULL) { *throwaway = false; return cfs; } *throwaway = true; return cfs_open_full_pinned(reln->smgr_rlocator, forknum, true); } BlockNumber cfs_smgr_nblocks(SMgrRelation reln, ForkNumber forknum) { uint64 nblocks; volatile bool append_held = false; /* * Check the dispatcher invariant without opening the handle first: the * fast path below answers from the shared metadata cache alone, and the * slow path measures the size from the sidecar files, so the size * itself never requires a handle's map. The persistent handle is * opened below at most once, solely to serve the later smgrtruncate() * critical section; see the path comments below. */ cfs_smgr_check_cfs(reln, "nblocks"); /* * The shared-memory metadata slot is the authoritative cross-backend * source of the logical size: every extend / write / truncate publishes * the current nblocks into it under the relation extension lock (and the * per-relation append lock for the physical append). Read it first so a * concurrent extension done by another backend is visible here. The * buffer manager calls smgrnblocks() under LockRelationForExtension to * learn the up-to-date size; a value read from this backend's private * handle map instead would reflect only this backend's own writes and lag * behind the other backend's extension, making the buffer manager extend * at an already-occupied block (the "unexpected data beyond EOF" failure) * or journal a RESIZE below the real size, which on recovery (last RESIZE * wins) silently loses the blocks the other backend wrote. * * A cached 0 is NOT trusted on its own: a freshly published policy slot * carries nblocks == 0 without the size ever having been measured (the * startup process publishes the default policy during recovery before any * data page is replayed), and answering 0 for a relation that does hold * data would make WAL replay overwrite existing blocks from scratch. */ if (cfs_map_cache_get_nblocks(reln->smgr_rlocator, forknum, &nblocks) && nblocks > 0) { /* * RelationTruncate() -> smgrtruncate() runs inside a critical section * and must not allocate, so it cannot open the sidecar handle there * (opening pallocs the paths and replays the journal). It relies on * this call — which precedes the critical section — leaving the * handle open. The sidecars are materialized when the policy is * published (cfs_materialize_sidecars), so opening them here can * never create anything. */ if (reln->cfs_smgr->cfs == NULL) (void) cfs_smgr_require_handle(reln, "nblocks"); return (BlockNumber) nblocks; } /* * Cache miss, or a cached 0 that needs confirmation. The sidecars always * exist for a CFS relation — they are materialized when the policy is * published (cfs_materialize_sidecars), whatever the WAL level, the same * contract mdcreate() upholds for the base file — so the measurement * below never opens a half-created pair. A cache miss means the shared * metadata slot was evicted under LRU pressure (or only a policy has * been published so far): measure the current size from the sidecar * pair WITHOUT building a private full map (an O(map) read that, with * the segment pool enabled, opened and pinned a throwaway full handle * per miss) — the .cfsmap row count plus the journal's last RESIZE * target is the same size the full-map replay would compute, at * O(journal) cost. The one exception is a mid-file-torn journal in * the non-strict startup process, which falls back to that full-map * measurement below instead of trusting any journal-derived size. */ { RelFileLocatorBackend rl = reln->smgr_rlocator; BlockNumber measured; off_t torn_off = 0; bool fallback = false; /* * No sidecars (dropped / rewritten relation whose slot is still * around): the size is genuinely zero. */ if (!cfs_exists(rl, forknum)) { cfs_map_cache_set_meta(rl, forknum, 0); return 0; } /* * RelationTruncate() -> smgrtruncate() runs inside a critical section * and must not allocate, so it cannot open the sidecar handle there * (opening pallocs the paths and replays the journal). It relies on * this call — which precedes the critical section — leaving the * handle open, exactly like the fast path above. The size itself is * not taken from the handle: it is measured from the files below, * which is why a lazy pool handle (no private map) suffices. */ if (reln->cfs_smgr->cfs == NULL) (void) cfs_smgr_require_handle(reln, "nblocks"); /* * Measure under the SHARED append lock (the same lock the old * full-map path took): every writer that changes the size journals * a RESIZE under the EXCLUSIVE append lock, and the folds / swaps * that rewrite the .cfsmap hold it EXCLUSIVE too, so the stat and * the journal scan inside see one consistent pair and cannot race * a size change. */ PG_TRY(); { CfsJournalMeasureStatus mstat; bool in_startup = AmStartupProcess(); cfs_append_lock_acquire(rl, forknum, LW_SHARED); append_held = true; mstat = cfs_journal_measure_nblocks(rl, forknum, &measured, &torn_off); cfs_append_lock_release(rl, forknum); append_held = false; if (mstat != CFS_JOURNAL_MEASURE_MIDFILE) { nblocks = (uint64) measured; } else { /* * Mid-file journal damage: the records past the torn one * may hold the real last RESIZE, so no journal-derived size * can be answered. The severity is the CALLER's context, * mirroring the recovery fold's contract (a backend's * delta replay there picks the recovery severity on * purpose, so the checksum-failure channel must not take * the session down during WAL redo): * * - a normal backend escalates through the centralised * channel (cfs_checksum_failure: ERROR or PANIC); * - the startup process (AmStartupProcess(), the standard * miscadmin.h context probe; the smgr dispatch carries * no load context here) follows cfs_recovery_strict: * strict is parity with the fold (an ERROR aborts the * startup), non-strict WARNINGs and falls back to the * full-map measurement below, so a damaged journal can * never make the cluster refuse to boot. */ if (!in_startup || cfs_recovery_strict) { char *jrn_path; jrn_path = cfs_make_filename(rl, forknum, CFS_FILE_JOURNAL); cfs_report_corruption(rl, forknum, InvalidBlockNumber, psprintf("journal scan for the " "size stopped at a torn " "record at offset %lld " "with valid records " "behind it " "(journal \"%s\")", (long long) torn_off, jrn_path), in_startup); } ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: size measurement for relation " "%u/%u/%u stopped at a torn journal " "record, falling back to the full map", rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber))); fallback = true; } } PG_FINALLY(); { /* Release the append lock even when the measurement raises. */ if (append_held) cfs_append_lock_release_after_error(rl, forknum); } PG_END_TRY(); if (fallback) { CfsRelation *cfs; bool throwaway = false; /* * The non-strict startup fallback: answer the size the way the * pre-QDB-1516 path did, from a handle with a full private map * refreshed under this same SHARED append lock. Its delta * replay stops at the torn record too, but as WARNING-only * damage on a non-strict handle, so recovery never gets more * than a WARNING from the size path - the pre-regression * behaviour. The throwaway open is counted by * cfs_open_full_pinned(), keeping the rare fallback honest in * the full_map_opens stat. */ cfs = cfs_smgr_full_map_handle(reln, forknum, "nblocks", true, &throwaway); PG_TRY(); { cfs_append_lock_acquire(rl, forknum, LW_SHARED); append_held = true; cfs_handle_refresh_if_stale(cfs); if (cfs_refresh_map(cfs, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not refresh map to " "determine size of relation " "%u/%u/%u", rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber))); cfs_append_lock_release(rl, forknum); append_held = false; nblocks = (uint64) cfs_map_nblocks(cfs); } PG_FINALLY(); { /* * Release the append lock before unpinning the metadata * slot: the unpin may let another backend evict and reuse * it, which must not happen while this backend still * holds its lock. */ if (append_held) cfs_append_lock_release_after_error(rl, forknum); if (throwaway) cfs_close_full_unpinned(cfs, rl, forknum); } PG_END_TRY(); } } /* Republish so the next caller gets a cheap shared-cache hit. */ cfs_map_cache_set_meta(reln->smgr_rlocator, forknum, nblocks); return (BlockNumber) nblocks; } void cfs_smgr_truncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks) { CfsRelation *cfs; int rc; cfs = cfs_smgr_require_handle(reln, "truncate"); cfs_append_lock_acquire(reln->smgr_rlocator, forknum, LW_EXCLUSIVE); /* * A compaction may have swapped the sidecar files while we waited for the * append lock, and an immedsync may have replaced the .cfsmap inode * without bumping the shared generation. Journaling the RESIZE through a * stale handle would use its stale map and cursors (and publish a stale * cfp EOF into the shared cache), so reopen the handle if its generation * is stale or its map descriptor names a replaced inode, the same * invariant the write path already upholds. * * ponytail: this reopen pallocs and may raise ERROR, while * RelationTruncate() calls us inside START_CRIT_SECTION (an ERROR there * becomes a PANIC). The handle is warmed before that section but NOT * revalidated: RelationTruncate() samples the size with smgrnblocks() * first, whose branches only open a missing persistent handle (the * size itself is measured from the sidecar files, not from the * handle's map) -- nothing checks the map inode. So a map replaced * by a concurrent immedsync still makes this reopen allocate inside * the critical section, and an I/O failure there panics. VACUUM * normally escapes that, because resolving every page through the * segment pool reopens a swapped handle first. The physical map * truncation (and its O(dropped rows) tail read) moved OUT of this * path into the checkpoint's RESIZE application, so the critical * section below only journals the RESIZE record; the reopen hazard * above is what remains. Upgrade path: revalidate the handle in the * caller before the critical section, not allocation-free reopen * machinery here. */ cfs_reopen_if_handle_stale(cfs); rc = cfs_truncate(cfs, nblocks); if (rc == CFS_STORAGE_OK) { /* * Publish the new generation and size under the append lock: the * truncate bump and the RESIZE record must become visible together, * or a reader could see the new generation while the journal still * describes the old extent (and vice versa). */ cfs_map_cache_truncate(reln->smgr_rlocator, forknum, nblocks); cfs_map_cache_set_meta(reln->smgr_rlocator, forknum, (uint64) nblocks); } cfs_append_lock_release(reln->smgr_rlocator, forknum); if (rc != CFS_STORAGE_OK) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not truncate relation %u/%u/%u to %u blocks", reln->smgr_rlocator.locator.spcOid, reln->smgr_rlocator.locator.dbOid, reln->smgr_rlocator.locator.relNumber, nblocks))); /* * Register the journal dirtied by the RESIZE record outside the append * lock (same placement and reason as in cfs_smgr_zeroextend above): the * fallback fsync of a full sync queue must not park the relation's * writers behind it. */ cfs_register_dirty_file(reln->smgr_rlocator, forknum, CFS_FILE_JOURNAL); /* * Keep the shared cache consistent. The map-cache truncate above bumped * the relation generation, and every block-map segment of the relation * still carries offsets tagged with the OLD generation — a reader would * reject every hit. Dropping the segments entirely is the safe * equivalent: they reload from the .cfsmap snapshot on the next access, * tagged with the new generation. This is an O(N) descriptor scan and * deliberately stays outside the append lock; the generation gate makes a * reader that races it retry instead of serving a zero page. */ cfs_shared_map_invalidate_relation(reln->smgr_rlocator, forknum); } /* * cfs_smgr_register_sync — counterpart of smgrregistersync() for the CFS * sidecar files. Bulk operations (smgr_bulk_flush(), RelationCopyStorage()) * write pages with skipFsync=true and then register the skipped fsyncs for * the whole relation at once; mdregistersync() covers only the base fork, * so the sidecars are registered here. */ void cfs_smgr_register_sync(SMgrRelation reln, ForkNumber forknum) { if (forknum != MAIN_FORKNUM) return; if (!smgriscfsenabled(reln, forknum)) return; cfs_register_dirty_file(reln->smgr_rlocator, forknum, CFS_FILE_DATA); cfs_register_dirty_file(reln->smgr_rlocator, forknum, CFS_FILE_MAP); cfs_register_dirty_file(reln->smgr_rlocator, forknum, CFS_FILE_JOURNAL); ereport(DEBUG1, (errmsg("CFS: registered sidecar files of relation %u/%u/%u " "for the next checkpoint sync", reln->smgr_rlocator.locator.spcOid, reln->smgr_rlocator.locator.dbOid, reln->smgr_rlocator.locator.relNumber))); } void cfs_smgr_immedsync(SMgrRelation reln, ForkNumber forknum) { RelFileLocatorBackend rl = reln->smgr_rlocator; CfsRelation *cfs; volatile bool append_held = false; bool throwaway = false; /* * This path must refresh a full map and persist it as a snapshot. With * the pool enabled the regular smgr handle is lazy, so a throwaway full * handle is opened, pinned like the compactor pins its own; with the pool * disabled the persistent handle already owns a full map and is reused. * The sidecars may already be gone (drop / rewrite): nothing to sync * then. */ if (!cfs_exists(rl, forknum)) return; cfs = cfs_smgr_full_map_handle(reln, forknum, "immedsync", false, &throwaway); PG_TRY(); { /* * Durability order for a checkpoint-like sync: data first, then * journal, then the map snapshot. Persisting the map snapshot here * makes this handle's current in-memory map durable; the journal * reset below then turns this point into a reset point, so records * other backends append afterwards are simply replayed on top of this * snapshot at the next open or crash recovery. * * The append lock serialises this sequence against concurrent * writers: without it a backend could append journal records while * the snapshot is being written, leaving a durable snapshot that does * not agree with the journal tail. */ cfs_append_lock_acquire(rl, forknum, LW_EXCLUSIVE); append_held = true; /* * A compaction may have swapped the sidecar files while we waited for * the append lock; snapshotting the stale in-memory map would undo * the swap, so reopen the handle if its generation is stale. */ cfs_handle_refresh_if_stale(cfs); /* * Same durability order and error discipline as the checkpoint path: * an fsync failure escalates to PANIC via data_sync_elevel(), * matching mdimmedsync() in md.c. */ if (cfs_fsync_kind(cfs, CFS_FILE_DATA) != CFS_STORAGE_OK) ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: could not fsync data file for relation %u/%u/%u", rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber))); if (cfs_fsync_kind(cfs, CFS_FILE_JOURNAL) != CFS_STORAGE_OK) ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: could not fsync journal file for relation %u/%u/%u", rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber))); /* * Bring the handle's in-memory map up to date with the journal before * snapshotting it, exactly like cfs_checkpoint_one() does. */ if (cfs_refresh_map(cfs, true, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not refresh map for immediate sync of relation %u/%u/%u", rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber))); /* Raises ERROR on failure. */ cfs_map_save_snapshot(cfs); /* * The snapshot just carried every journal record (the append lock * excludes concurrent writers), so this is a reset point: the shared * core stamps the fresh map summary and bumps the incarnation. * Before, the journal was deliberately left untouched and the next * checkpoint truncated it; resetting here keeps the contract uniform * across every full-snapshot writer. */ cfs_journal_reset_point(cfs, cfs_map_live_summary(cfs), data_sync_elevel(ERROR)); /* * Clear the dirty-checkpoint flag while the append lock is still * held, for the same reason as in cfs_checkpoint_one(). */ cfs_map_cache_clear_dirty(rl, forknum); cfs_append_lock_release(rl, forknum); append_held = false; ereport(DEBUG1, (errmsg("CFS: immediate sync completed for relation %u/%u/%u", rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber))); } PG_FINALLY(); { /* * Release the append lock before unpinning the metadata slot: the * unpin may let another backend evict and reuse it, which must not * happen while this backend still holds its lock. An ERROR from the * fsync/refresh/snapshot path unwinds through here with the lock * still held (FATAL does not, but the backend is gone then). */ if (append_held) cfs_append_lock_release_after_error(rl, forknum); if (throwaway) cfs_close_full_unpinned(cfs, rl, forknum); } PG_END_TRY(); }