/*------------------------------------------------------------------------- * cfs_shmem.c * Compressed File Store (CFS) - shared-memory map cache, statistics * and synchronisation. * * Implements the partitioned shared-memory page-map cache, per-relation * statistics and the cached read/write helpers declared in cfs_shmem.h. * * Locking discipline: * * * The map cache and relation metadata share one set of partition locks * (cfs_map_locks); statistics has its own (cfs_stats_locks). * * Lookups take LW_SHARED; insertions / updates take LW_EXCLUSIVE. * * Compression, decompression, FileRead/FileWrite, fsync and XLogFlush * are never performed while a CFS partition lock is held - only the * (cheap) CfsMapEntry copy / slot update happens inside the lock. * * The only nested lock ordering that may occur is map-lock -> stats-lock * (e.g. while accounting dead bytes); the reverse never happens, so the * ordering is deadlock-free. * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_shmem.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/twophase_rmgr.h" #include "access/xact.h" #include "catalog/storage.h" #include "common/hashfn.h" #include "common/relpath.h" #include "miscadmin.h" #include "storage/aio.h" #include "storage/cfs/cfs_cfp.h" #include "storage/cfs/cfs_format.h" #include "storage/cfs/cfs_guc.h" #include "storage/cfs/cfs_journal.h" #include "storage/cfs/cfs_map_file.h" #include "storage/cfs/cfs_recovery.h" #include "storage/cfs/cfs_rel.h" #include "storage/cfs/cfs_shmem.h" #include "storage/cfs/cfs_shmem_internal.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/lwlock.h" #include "storage/proc.h" #include "storage/procarray.h" #include "storage/shmem.h" #include "utils/hsearch.h" #include "utils/memutils.h" #include "utils/palloc.h" #include "utils/timestamp.h" /* Mask for selecting a partition from a hash (NUM_PARTITIONS is a power of 2). */ /* * Retry interval for the dead-pin reaper after a sweep that reaped * nothing: a fresh dead owner can only appear when some backend dies, so * a short TTL delays the rescue but never loses it. */ #define CFS_PIN_REAP_EMPTY_RETRY_USECS (10 * USECS_PER_SEC) /* ================================================================ * Shared-memory pointers (initialised by CfsShmemInit) * ================================================================ */ CfsShmemControl *cfs_control = NULL; static LWLockPadded *cfs_map_locks = NULL; /* * Sidecar-open guard implementation (QDB-1514), installed into the state * judge by CfsShmemInit(); defined near the compaction mark helpers below. */ static bool cfs_open_guard_acquire_impl(RelFileLocatorBackend rlocator, ForkNumber forknum); static void cfs_open_guard_release_impl(RelFileLocatorBackend rlocator, ForkNumber forknum, bool after_error); /* * Relation-metadata slots, stored as a flat array of NUM_PARTITIONS * * cfs_map_cache_rels_per_partition entries (the per-partition count is a * PGC_POSTMASTER GUC, so the second dimension is not a compile-time * constant). Use cfs_rel_meta_slot() to index it. */ static CfsRelMetaSlot *cfs_rel_meta = NULL; /* Map-domain per-partition access clock (see cfs_shmem_internal.h). */ uint64 *cfs_map_clocks = NULL; /* * Per-partition bucket heads for the metadata hash chains (QDB-1516 Д2): * a flat array of NUM_PARTITIONS * cfs_map_cache_rels_per_partition * entries, -1 = empty head / end of chain. Use cfs_meta_head() to index. */ static int32 *cfs_map_bucket_heads = NULL; /* cfs_stats_locks / cfs_stats_slots moved to cfs_stats.c. */ /* Background compaction worker control block + its dedicated lock. */ static CfsBgControl *cfs_bg_control = NULL; static LWLockPadded *cfs_bg_lock = NULL; /* * Shared block-map segment pool. NULL (and cfs_map_seg_count == 0) when * cfs_map_memory is 0: the pool is simply absent and every consumer must * fall back to the authoritative miss path. * * Lock ordering invariant (deadlock-free by construction, the buffer * mapping model): * * append_lock -> index lock -> mapping partition lock -> segment lock * * A mapping (hash-table) partition lock may be held together with a segment * lock — acquire reserves the descriptor and inserts the mapping under both * — but only in that order: partition lock first, segment lock second, * never the reverse. The hash lookup/insert runs under the partition lock, * and the segment key is re-validated under the segment lock to catch a * concurrent eviction. The append lock precedes all three on every writing * path, and nothing takes the append lock while holding a mapping or * segment lock. Compression, decompression, disk I/O and journal replay * are never performed while a segment lock is held: under it only * single-entry copies/stores happen (segment loads read .cfsmap into a * private buffer first, and the journal incarnation is sampled before the * locks for the same reason). * * Pinning is relation-level for the metadata slot: an open CFS handle * pins the slot (refcount), which keeps the slot's identity, nblocks * and append lock alive — but it deliberately does NOT protect the * slot's resident pool segments from eviction. A per-segment pin (the * bufmgr BufferDesc.refcount model) would remove the reservation table * and part of the epoch/ghost logic, but the working set does not need * it: usage_count is bumped by every lookup and store, so the segments * under an active scan stay hot and survive the clock sweep, while cold * segments — even of an open relation — are evictable. Skipping the * segments of open relations instead (the earlier policy) let a single * relation larger than the pool exhaust it forever: no victim could be * found, evictions stayed zero and every further read paid the * authoritative fallback on every scan. */ static CfsMapSegmentDesc *cfs_map_seg_descs = NULL; static CfsMapEntry (*cfs_map_seg_data)[CFS_MAP_SEGMENT_BLOCKS] = NULL; static LWLockPadded *cfs_map_seg_locks = NULL; static int cfs_map_seg_count = 0; /* * Process-local clock-sweep hand. A plain uint32 is enough: a torn advance * only re-scans, never misassigns (the bufmgr nextVictimBuffer model). */ static uint32 cfs_map_seg_hand = 0; /* * Process-local memo of a failed pool attempt: while the shared churn * counter stays where the failure left it, nothing has been published, * evicted or unpinned, so the pool cannot have become usable again. The * read path then skips the sweep entirely and takes the authoritative * scratch fallback, instead of paying a locked clock-sweep revolution per * page while every segment stays reserved or hot (the only states that * can keep a full pool without a victim now that pinned relations no * longer protect their segments). */ static bool cfs_map_pool_exhausted = false; static uint64 cfs_map_pool_exhausted_churn = 0; /* * The (key -> segment id) lookup table: a shared partitioned dynahash, * guarded by the same cfs_map_locks partition array as the map cache * (the vanilla SharedBufHash pattern; one tranche serves both, the * critical sections never overlap). */ static HTAB *cfs_map_seg_hash = NULL; /* (key -> reserved descriptor) for in-flight acquisitions. */ static HTAB *cfs_map_seg_live = NULL; /* * Per-relation index over the pool: (relation, fork) -> list of segment * descriptors. Publishing a segment links it here, eviction unlinks it, * and cfs_shared_map_invalidate_relation() walks only the segments of the * requested relation instead of scanning the whole pool (the pool may hold * more than a million descriptors at the documented sizing limit). * * Lock order: relation index -> mapping partition -> segment. The index * lock is only ever held together with a segment lock (to sample or move a * node); eviction never takes it while the mapping lock is held. */ typedef struct CfsMapSegmentRelKey { RelFileLocatorBackend rlocator; ForkNumber forknum; } CfsMapSegmentRelKey; typedef struct CfsMapSegmentRelEnt { CfsMapSegmentRelKey key; dlist_head head; int count; } CfsMapSegmentRelEnt; static HTAB *cfs_map_rel_index = NULL; static LWLockPadded *cfs_map_rel_index_lock = NULL; /* * Pin-owner registry for metadata slots. A hard process * death (kill -9, FATAL) skips every unpin this backend owed, so a slot's * refcount would stay elevated forever and a series of such deaths could * exhaust a partition. Every pin is therefore also recorded here under * the pinning process's (procno, pid, epoch) identity; when a partition * runs out of reclaimable slots, dead owners are reaped exactly like * dead segment reservations. Guarded by the same cfs_map_locks * partition as the slot itself, which cfs_map_pin_hash() makes safe for * the shared dynahash: keys in one bucket always share that lock. */ typedef struct CfsMapPinKey { RelFileLocatorBackend rlocator; ForkNumber forknum; int procno; } CfsMapPinKey; typedef struct CfsMapPinOwner { CfsMapPinKey key; int owner_pid; uint64 owner_epoch; int pin_count; } CfsMapPinOwner; static HTAB *cfs_map_pin_live = NULL; /* One-shot log flag for a full pin-owner registry (see cfs_map_pin_track). */ static bool cfs_pin_registry_overflow_logged = false; /* * Per-process epochs used by segment reservations. A ProcNumber is * recycled by a new backend, so (pid, ProcNumber) alone could look alive * after PID reuse; the epoch in the process's slot changes on first CFS * use by the new owner and makes the old reservation provably stale. */ static pg_atomic_uint64 *cfs_proc_epochs = NULL; static int cfs_proc_epochs_count = 0; static uint64 cfs_owner_epoch = 0; /* * Test-only switch for the I4 merge race, consumed by * cfs_shared_map_ensure(). Compiled only in assert-enabled builds. */ #ifdef USE_ASSERT_CHECKING static bool cfs_test_merge_race_pending = false; #endif /* * Test-only switch (always compiled; see cfs_shmem.h): forces victim * selection to report an exhausted pool so the authoritative fallback * stays deterministically coverable in every build. */ bool cfs_test_pool_block_victim = false; /* Shared dynahash of the per-relation compaction history. */ static HTAB *cfs_bg_history_hash = NULL; /* One-time-per-process overflow notice for the history hash. */ static bool cfs_bg_history_overflow_logged = false; /* * Read scratch arena (QDB-1513 P4-2). Slot descriptors, span buffers * and the control block live in one contiguous pair of arrays plus a * small header; see cfs_shmem.h for the state machine. All pointers * stay NULL with cfs_read_scratch_slots_count == 0 when the GUCs buy no * slot, and every consumer then takes the inline read path. */ static CfsReadScratchSlot *cfs_read_scratch_slots = NULL; static int cfs_read_scratch_slots_count = 0; static Size cfs_read_scratch_span_bytes = 0; static char *cfs_read_scratch_spans = NULL; typedef struct CfsReadScratchCtl { pg_atomic_uint32 cursor; /* round-robin acquisition hint */ pg_atomic_uint64 exhaustions; /* acquisitions that found no free * slot and degraded to inline */ } CfsReadScratchCtl; static CfsReadScratchCtl *cfs_read_scratch_ctl = NULL; /* ================================================================ * Internal helpers * ================================================================ */ /* Index the flat relation-metadata array by (partition, slot). */ static inline CfsRelMetaSlot * cfs_rel_meta_slot(int part, int i) { return &cfs_rel_meta[part * cfs_map_cache_rels_per_partition + i]; } /* * Forward declaration: cfs_meta_find is used by cfs_append_lock_find_slot * (append serialization section) and defined in the relation-metadata * section. cfs_stats_get_or_create moved to cfs_stats.c. */ static CfsRelMetaSlot *cfs_meta_find(uint32 rel_hash, RelFileLocatorBackend rlocator, ForkNumber forknum); /* * Hash of a pin-owner registry key. The lock-manager pattern (see * LockTagHashCode / LockHashPartitionLock): the partition lock a caller * holds while touching the registry is cfs_map_locks[rel part], and any * two keys dynahash places in one bucket must always share that lock. * Keep tag_hash's bits but force the low CFS_PART_MASK bits to the * relation's metadata partition - nbuckets is never below the partition * count (dynahash.c), so the bucket address bits always include these. * Every registry access must go through this function - never a plain * hash_search(), which computes a different value for the same key and * would miss the record. */ static inline uint32 cfs_map_pin_hash(const CfsMapPinKey * key, uint32 rel_hash) { uint32 h; h = (tag_hash(key, sizeof(*key)) & ~CFS_PART_MASK) | (rel_hash & CFS_PART_MASK); /* * A zero hashvalue is not special to dynahash, but 0 is kept out of the * table for symmetry with cfs_map_segment_hash(). The fixup bit is above * every bucket address bit, so the forced partition bits survive it. */ return h ? h : 0x80000000; } /* * Fill *key and return the hash value for one registry access. track, * untrack and the test hook must all build the key and the hash through * this single helper: drifting copies would look in different buckets and * silently miss each other's records. */ static inline uint32 cfs_map_pin_key_hash(RelFileLocatorBackend rlocator, ForkNumber forknum, int procno, CfsMapPinKey * key, uint32 rel_hash) { key->rlocator = rlocator; key->forknum = forknum; key->procno = procno; return cfs_map_pin_hash(key, rel_hash); } /* ================================================================ * Shared-memory lifecycle * ================================================================ */ /* * Number of block-map segments the cfs_map_memory GUC buys. One segment * is CFS_MAP_SEGMENT_BLOCKS entries (768 KiB today). 1 MB already covers * one segment, so any positive GUC yields at least one segment. */ int cfs_map_pool_segments(void) { uint64 seg_bytes = (uint64) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry); uint64 nsegs; if (cfs_map_memory <= 0) return 0; nsegs = ((uint64) cfs_map_memory * 1024 * 1024) / seg_bytes; if (nsegs > INT_MAX) nsegs = INT_MAX; return (int) nsegs; } /* * Capacity of the pin-owner registry: the same relation budget the * metadata-slot pool offers (one row per pinned relation, fork and * process), so the registry cannot run out before the slots it protects. */ static int cfs_map_pin_registry_size(void) { return CFS_MAP_CACHE_NUM_PARTITIONS * cfs_map_cache_rels_per_partition; } bool cfs_map_memory_effective(void) { return cfs_map_pool_segments() > 0; } /* * Read scratch arena sizing (QDB-1513 P4-2). * * The slot budget covers one in-flight offloaded read per AIO handle the * backend may hold, doubled so completed-but-not-yet-reclaimed IOs never * starve new submissions (the handles themselves allow the same overlap). * The cfs_read_scratch_mb GUC caps the total arena memory; whichever * bound is smaller wins, and a budget below one slot disables the arena * entirely (0 included) — reads then stay on the inline path. */ int cfs_read_scratch_slot_count(void) { uint64 slot_bytes; uint64 by_concurrency; uint64 by_budget; uint64 nslots; if (cfs_read_scratch_mb <= 0 || io_max_concurrency <= 0) return 0; slot_bytes = sizeof(CfsReadScratchSlot) + cfs_read_span_capacity(); by_concurrency = 2 * (uint64) io_max_concurrency; by_budget = ((uint64) cfs_read_scratch_mb * 1024 * 1024) / slot_bytes; nslots = Min(by_concurrency, by_budget); if (nslots > INT_MAX) nslots = INT_MAX; return (int) nslots; } bool cfs_read_scratch_effective(void) { /* * The slot count depends only on postmaster-time GUCs, so the value * computed once in the shmem startup is authoritative for the whole * cluster lifetime; avoid re-doing the budget arithmetic on every * readv gate check. */ return cfs_read_scratch_slots_count > 0; } Size cfs_read_span_capacity(void) { /* * No IO carries more than io_max_combine_limit blocks, and no valid * record is longer than a stored-raw page plus its header * (CFS_RECORD_SIZE aligned; the read path rejects a larger * compressed_size as corruption), so the product bounds every * offloadable span. Degradation to the inline path is therefore * driven by arena exhaustion and span contiguity, never by capacity. */ return (Size) io_max_combine_limit * CFS_RECORD_SIZE(CFS_BLCKSZ); } /* * cfs_read_scratch_acquire — claim a slot with a single CAS and reset its * bookkeeping. The round-robin hint spreads the search start so that * concurrent backends do not all hammer slot 0; a full failed sweep * counts one exhaustion and returns NULL — the caller must degrade to * the inline path, never wait. */ CfsReadScratchSlot * cfs_read_scratch_acquire(void) { int nslots = cfs_read_scratch_slots_count; uint32 hint; if (nslots <= 0) return NULL; hint = pg_atomic_fetch_add_u32(&cfs_read_scratch_ctl->cursor, 1); for (int k = 0; k < nslots; k++) { int i = (int) ((hint + k) % (uint32) nslots); CfsReadScratchSlot *slot = &cfs_read_scratch_slots[i]; uint32 expected = CFS_READ_SCRATCH_FREE; if (pg_atomic_compare_exchange_u32(&slot->state, &expected, CFS_READ_SCRATCH_BUILDING)) { slot->owner_procno = MyProcNumber; slot->plan_len = 0; slot->span_len = 0; return slot; } } pg_atomic_fetch_add_u64(&cfs_read_scratch_ctl->exhaustions, 1); return NULL; } void cfs_read_scratch_publish(CfsReadScratchSlot *slot) { Assert(pg_atomic_read_u32(&slot->state) == CFS_READ_SCRATCH_BUILDING); Assert(slot->plan_len <= CFS_READ_PLAN_MAX); /* * The plan and the span bookkeeping must be visible before the state * transition: once the executor observes INFLIGHT it is entitled to * read both without further synchronisation of its own with this * backend. */ pg_write_barrier(); pg_atomic_write_u32(&slot->state, CFS_READ_SCRATCH_INFLIGHT); } void cfs_read_scratch_release(CfsReadScratchSlot *slot) { Assert(pg_atomic_read_u32(&slot->state) != CFS_READ_SCRATCH_FREE); /* * Order the diagnostics reset before the FREE transition so the next * acquirer never observes a stale owner once the slot looks free. */ pg_write_barrier(); slot->owner_procno = INVALID_PROC_NUMBER; pg_atomic_write_u32(&slot->state, CFS_READ_SCRATCH_FREE); } char * cfs_read_scratch_span(const CfsReadScratchSlot *slot) { int idx = slot - cfs_read_scratch_slots; Assert(idx >= 0 && idx < cfs_read_scratch_slots_count); return cfs_read_scratch_spans + (Size) idx * cfs_read_scratch_span_bytes; } uint32 cfs_read_scratch_slot_index(const CfsReadScratchSlot *slot) { int idx = slot - cfs_read_scratch_slots; Assert(idx >= 0 && idx < cfs_read_scratch_slots_count); return (uint32) idx; } CfsReadScratchSlot * cfs_read_scratch_slot(uint32 slot_id) { Assert(slot_id < (uint32) cfs_read_scratch_slots_count); return &cfs_read_scratch_slots[slot_id]; } uint64 cfs_read_scratch_exhaustions(void) { if (cfs_read_scratch_ctl == NULL) return 0; return pg_atomic_read_u64(&cfs_read_scratch_ctl->exhaustions); } Size CfsShmemSize(void) { Size size = 0; size = add_size(size, sizeof(CfsShmemControl)); size = add_size(size, mul_size(sizeof(LWLockPadded), CFS_MAP_CACHE_NUM_PARTITIONS)); size = add_size(size, mul_size(sizeof(CfsRelMetaSlot), mul_size(CFS_MAP_CACHE_NUM_PARTITIONS, cfs_map_cache_rels_per_partition))); size = add_size(size, mul_size(sizeof(LWLockPadded), CFS_MAP_CACHE_NUM_PARTITIONS)); size = add_size(size, mul_size(sizeof(CfsRelationStats), mul_size(CFS_MAP_CACHE_NUM_PARTITIONS, cfs_stats_slots_per_partition))); /* * Per-partition access clocks (QDB-1516 Д1), one per domain. Each * array is cacheline-padded so it shares no cache line with the lock * arrays or with the other domain's clocks. */ size = add_size(size, CACHELINEALIGN((Size) CFS_MAP_CACHE_NUM_PARTITIONS * sizeof(uint64))); size = add_size(size, CACHELINEALIGN((Size) CFS_MAP_CACHE_NUM_PARTITIONS * sizeof(pg_atomic_uint64))); /* * Per-partition hash-chain bucket heads (QDB-1516 Д2), one entry per * slot of each domain's table. */ size = add_size(size, mul_size(sizeof(int32), mul_size(CFS_MAP_CACHE_NUM_PARTITIONS, cfs_map_cache_rels_per_partition))); size = add_size(size, mul_size(sizeof(int32), mul_size(CFS_MAP_CACHE_NUM_PARTITIONS, cfs_stats_slots_per_partition))); size = add_size(size, sizeof(CfsBgControl)); size = add_size(size, sizeof(LWLockPadded)); /* bgworker control lock */ size = add_size(size, hash_estimate_size(CFS_BG_HISTORY_MAX, sizeof(CfsBgHistoryEntry))); /* Block-map segment pool (descriptors + data + one lock per segment). */ { int nsegs = cfs_map_pool_segments(); if (nsegs > 0) { size = add_size(size, mul_size(sizeof(CfsMapSegmentDesc), nsegs)); size = add_size(size, mul_size((Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry), nsegs)); size = add_size(size, mul_size(sizeof(LWLockPadded), nsegs)); size = add_size(size, hash_estimate_size(nsegs, sizeof(CfsMapSegmentHashEnt))); size = add_size(size, hash_estimate_size(nsegs, sizeof(CfsMapSegmentReservation))); size = add_size(size, mul_size(sizeof(pg_atomic_uint64), MaxBackends + NUM_AUXILIARY_PROCS)); /* Per-relation segment index and its single lock. */ size = add_size(size, sizeof(LWLockPadded)); size = add_size(size, hash_estimate_size(nsegs, sizeof(CfsMapSegmentRelEnt))); } } /* * Pin-owner registry for metadata slots: needed for every pool size * (cfs_map_memory = 0 included), one row per (relation, fork, process) * pin owner. */ size = add_size(size, hash_estimate_size(cfs_map_pin_registry_size(), sizeof(CfsMapPinOwner))); /* Read scratch arena (QDB-1513 P4-2): control, descriptors, spans. */ { int nscratch = cfs_read_scratch_slot_count(); if (nscratch > 0) { size = add_size(size, sizeof(CfsReadScratchCtl)); size = add_size(size, mul_size(sizeof(CfsReadScratchSlot), nscratch)); size = add_size(size, mul_size(cfs_read_span_capacity(), nscratch)); } } return size; } void CfsShmemInit(void) { bool found; int i; /* Control block. */ cfs_control = ShmemInitStruct("CFS Control", sizeof(CfsShmemControl), &found); if (!found) { /* * Postmaster: assign dynamic tranche ids for our lock families. The * counter lives just before MainLWLockArray and is already * initialised by CreateLWLocks(), which runs earlier in this path. */ cfs_control->map_tranche_id = LWLockNewTrancheId("cfs_map"); cfs_control->stats_tranche_id = LWLockNewTrancheId("cfs_stats"); cfs_control->append_tranche_id = LWLockNewTrancheId("cfs_append"); cfs_control->bg_tranche_id = LWLockNewTrancheId("cfs_bg"); cfs_control->map_seg_tranche_id = LWLockNewTrancheId("cfs_map_seg"); /* * Freeze the statistics slot count (the cfs_stats_slots_per_partition * GUC) for the attach-time consistency check in * cfs_stats_shmem_init(): EXEC_BACKEND children re-parse their own * configuration, and a different value would index the shared arrays * out of their layout. */ cfs_control->stats_slots_per_part = cfs_stats_slots_per_partition; pg_atomic_init_u64(&cfs_control->evictions, 0); pg_atomic_init_u64(&cfs_control->map_segment_loads, 0); pg_atomic_init_u64(&cfs_control->map_segment_evictions, 0); pg_atomic_init_u64(&cfs_control->map_segments_in_use, 0); pg_atomic_init_u64(&cfs_control->map_fallback_reads, 0); pg_atomic_init_u64(&cfs_control->map_pool_churn, 0); pg_atomic_init_u64(&cfs_control->map_pin_reap_empty_at, 0); pg_atomic_init_u64(&cfs_control->owner_epoch_next, 0); pg_atomic_init_u64(&cfs_control->full_map_opens, 0); } /* * [PG19 adaptation] Tranche names are registered for wait-event display * by LWLockNewTrancheId(name) at id assignment time above; PG19 removed * the separate LWLockRegisterTranche() registration pass. */ /* * Publish the generation lookup to the ownership-state judge: the storage * layer tags freshly opened handles through the provider instead of * calling into this layer (the storage -> shmem edge the review cycle was * feeding on; see cfs_state.h). */ cfs_state_set_generation_provider(cfs_map_cache_get_generation); /* * Publish the authoritative .cfp tail operations the same way: the * storage layer's append path consults and maintains the shared tail * through the state judge's hooks (see cfs_shmem.h for the protocol). */ { static const CfsCfpTailOps cfp_tail_ops = { .tail_fetch = cfs_cfp_tail_fetch, .tail_begin = cfs_cfp_tail_begin, .tail_commit = cfs_cfp_tail_commit, .tail_dirty = cfs_cfp_tail_dirty, }; cfs_state_set_cfp_tail_ops(&cfp_tail_ops); } /* * Publish the online-compaction liveness answer the same way: the open * path consults it to decide whether the interrupted-swap recovery may * run over this relation's candidate files (QDB-1514; see cfs_swap.c * for the invariant). */ cfs_state_set_compaction_provider(cfs_map_cache_compaction_active); /* * Publish the sidecar-open guard the same way: the lock-free opens * take a shared hold of the append lock so an online compaction's swap * phase cannot interleave with the descriptor resolution and the * generation tagging (QDB-1514). */ { static const CfsOpenGuardOps open_guard_ops = { .open_guard_acquire = cfs_open_guard_acquire_impl, .open_guard_release = cfs_open_guard_release_impl, }; cfs_state_set_open_guard_ops(&open_guard_ops); } ereport(DEBUG1, (errmsg("CFS: shared memory initialised (map tranche=%d, stats tranche=%d, append tranche=%d)", cfs_control->map_tranche_id, cfs_control->stats_tranche_id, cfs_control->append_tranche_id))); /* Map-cache / metadata partition locks. */ cfs_map_locks = ShmemInitStruct("CFS Map Locks", mul_size(sizeof(LWLockPadded), CFS_MAP_CACHE_NUM_PARTITIONS), &found); if (!found) { for (i = 0; i < CFS_MAP_CACHE_NUM_PARTITIONS; i++) LWLockInitialize(&cfs_map_locks[i].lock, cfs_control->map_tranche_id); } /* * Map-domain per-partition access clock (QDB-1516 Д1). Its own * CACHELINEALIGN-ed allocation keeps the clock off the partition locks' * cache lines; the plain uint64 cells are updated only under the * partition lock held exclusively (see cfs_map_clock_tick). */ cfs_map_clocks = ShmemInitStruct("CFS Map Clocks", CACHELINEALIGN((Size) CFS_MAP_CACHE_NUM_PARTITIONS * sizeof(uint64)), &found); if (!found) MemSet(cfs_map_clocks, 0, CACHELINEALIGN((Size) CFS_MAP_CACHE_NUM_PARTITIONS * sizeof(uint64))); /* Relation-metadata slots (flat array, see cfs_rel_meta_slot()). */ cfs_rel_meta = ShmemInitStruct("CFS Rel Meta", mul_size(sizeof(CfsRelMetaSlot), mul_size(CFS_MAP_CACHE_NUM_PARTITIONS, cfs_map_cache_rels_per_partition)), &found); if (!found) MemSet(cfs_rel_meta, 0, mul_size(sizeof(CfsRelMetaSlot), mul_size(CFS_MAP_CACHE_NUM_PARTITIONS, cfs_map_cache_rels_per_partition))); /* * Bucket heads of the metadata hash chains (QDB-1516 Д2): all heads * start empty (-1), matching the zeroed (all-free) slot array. */ cfs_map_bucket_heads = ShmemInitStruct("CFS Map Buckets", mul_size(sizeof(int32), mul_size(CFS_MAP_CACHE_NUM_PARTITIONS, cfs_map_cache_rels_per_partition)), &found); if (!found) MemSet(cfs_map_bucket_heads, 0xFF, mul_size(sizeof(int32), mul_size(CFS_MAP_CACHE_NUM_PARTITIONS, cfs_map_cache_rels_per_partition))); /* Statistics locks and slots: allocated by the stats module. */ cfs_stats_shmem_init(); /* Background compaction worker control block. */ cfs_bg_control = ShmemInitStruct("CFS BgWorker Control", sizeof(CfsBgControl), &found); if (!found) MemSet(cfs_bg_control, 0, sizeof(CfsBgControl)); cfs_bg_lock = ShmemInitStruct("CFS BgWorker Lock", sizeof(LWLockPadded), &found); if (!found) LWLockInitialize(&cfs_bg_lock->lock, cfs_control->bg_tranche_id); /* * Per-relation compaction history: a shared dynahash sized for * CFS_BG_HISTORY_MAX fixed-size entries, grown once here (the * lock-manager pattern: shared hashes in vanilla are created once with * their full capacity). Entries expire by age, not by count. */ { HASHCTL ctl; MemSet(&ctl, 0, sizeof(ctl)); ctl.keysize = sizeof(CfsBgHistoryKey); ctl.entrysize = sizeof(CfsBgHistoryEntry); cfs_bg_history_hash = ShmemInitHash("CFS BgWorker History", CFS_BG_HISTORY_MAX, &ctl, HASH_ELEM | HASH_BLOBS); } /* * Restore the persisted per-relation statistics. This runs in the * postmaster before any child exists (EXEC builds attach to already * initialised memory with IsUnderPostmaster set and skip it). */ if (!IsUnderPostmaster) cfs_stats_restore_statsfile(); /* * QDB-1507 U1: consume the persistent resync marker written by a * clean shutdown that overtook the crash-boot sweep - the restored * values are still unresynced, so this boot must keep the sweep * armed. Must run before StartupXLOG's crash/clean decision. */ if (!IsUnderPostmaster) cfs_stats_boot_restore_marker(); /* * Block-map segment pool: descriptors, data and one lock per segment. * Allocated only when cfs_map_memory > 0; otherwise the pointers stay * NULL and cfs_map_seg_count 0, and all consumers take the fallback. */ cfs_map_seg_count = cfs_map_pool_segments(); /* * Per-process epochs are needed for segment reservations (pool > 0) and * for metadata-slot pin reaping (always) - allocate both unconditionally. */ cfs_proc_epochs_count = MaxBackends + NUM_AUXILIARY_PROCS; cfs_proc_epochs = ShmemInitStruct("CFS Proc Epochs", mul_size(sizeof(pg_atomic_uint64), cfs_proc_epochs_count), &found); if (!found) { for (i = 0; i < cfs_proc_epochs_count; i++) pg_atomic_init_u64(&cfs_proc_epochs[i], 0); } /* * Pin-owner registry for metadata slots. Created for every pool size: * metadata slots (and their pins) exist even when the segment pool is * off, and the reaper must be able to return a dead process's pins then * too. The lock-manager pattern: every access goes through * cfs_map_pin_hash() under the relation's cfs_map_locks partition. */ { HASHCTL pin_ctl; MemSet(&pin_ctl, 0, sizeof(pin_ctl)); pin_ctl.keysize = sizeof(CfsMapPinKey); pin_ctl.entrysize = sizeof(CfsMapPinOwner); pin_ctl.num_partitions = CFS_MAP_CACHE_NUM_PARTITIONS; cfs_map_pin_live = ShmemInitHash("CFS Map Pin Live", cfs_map_pin_registry_size(), &pin_ctl, HASH_ELEM | HASH_BLOBS | HASH_PARTITION); } if (cfs_map_seg_count > 0) { cfs_map_seg_descs = ShmemInitStruct("CFS Map Pool Descs", mul_size(sizeof(CfsMapSegmentDesc), cfs_map_seg_count), &found); if (!found) { MemSet(cfs_map_seg_descs, 0, mul_size(sizeof(CfsMapSegmentDesc), cfs_map_seg_count)); for (i = 0; i < cfs_map_seg_count; i++) pg_atomic_init_u32(&cfs_map_seg_descs[i].usage_count, 0); } cfs_map_seg_data = ShmemInitStruct("CFS Map Pool Data", mul_size((Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry), cfs_map_seg_count), &found); if (!found) MemSet(cfs_map_seg_data, 0, mul_size((Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry), cfs_map_seg_count)); cfs_map_seg_locks = ShmemInitStruct("CFS Map Pool Locks", mul_size(sizeof(LWLockPadded), cfs_map_seg_count), &found); if (!found) { for (i = 0; i < cfs_map_seg_count; i++) LWLockInitialize(&cfs_map_seg_locks[i].lock, cfs_control->map_seg_tranche_id); } /* The (key -> segment id) lookup table over the pool. */ { HASHCTL ctl; MemSet(&ctl, 0, sizeof(ctl)); ctl.keysize = sizeof(CfsMapSegmentKey); ctl.entrysize = sizeof(CfsMapSegmentHashEnt); ctl.num_partitions = CFS_MAP_CACHE_NUM_PARTITIONS; cfs_map_seg_hash = ShmemInitHash("CFS Map Segment Hash", cfs_map_seg_count, &ctl, HASH_ELEM | HASH_BLOBS | HASH_PARTITION); MemSet(&ctl, 0, sizeof(ctl)); ctl.keysize = sizeof(CfsMapSegmentKey); ctl.entrysize = sizeof(CfsMapSegmentReservation); ctl.num_partitions = CFS_MAP_CACHE_NUM_PARTITIONS; cfs_map_seg_live = ShmemInitHash("CFS Map Segment Live", cfs_map_seg_count, &ctl, HASH_ELEM | HASH_BLOBS | HASH_PARTITION); } /* Per-relation segment index: one list head per (relation, fork). */ cfs_map_rel_index_lock = ShmemInitStruct("CFS Map Rel Index Lock", sizeof(LWLockPadded), &found); if (!found) LWLockInitialize(&cfs_map_rel_index_lock->lock, cfs_control->map_seg_tranche_id); { HASHCTL ctl; MemSet(&ctl, 0, sizeof(ctl)); ctl.keysize = sizeof(CfsMapSegmentRelKey); ctl.entrysize = sizeof(CfsMapSegmentRelEnt); cfs_map_rel_index = ShmemInitHash("CFS Map Rel Index", cfs_map_seg_count, &ctl, HASH_ELEM | HASH_BLOBS); } } /* * Read scratch arena (QDB-1513 P4-2): control block, slot descriptors * and span buffers. Allocated only when the GUCs buy at least one * slot; otherwise the pointers stay NULL, the count 0, and every read * takes the inline path. */ cfs_read_scratch_slots_count = cfs_read_scratch_slot_count(); if (cfs_read_scratch_slots_count > 0) { cfs_read_scratch_span_bytes = cfs_read_span_capacity(); cfs_read_scratch_ctl = ShmemInitStruct("CFS Read Scratch Ctl", sizeof(CfsReadScratchCtl), &found); if (!found) { pg_atomic_init_u32(&cfs_read_scratch_ctl->cursor, 0); pg_atomic_init_u64(&cfs_read_scratch_ctl->exhaustions, 0); } cfs_read_scratch_slots = ShmemInitStruct("CFS Read Scratch Descs", mul_size(sizeof(CfsReadScratchSlot), cfs_read_scratch_slots_count), &found); if (!found) { MemSet(cfs_read_scratch_slots, 0, mul_size(sizeof(CfsReadScratchSlot), cfs_read_scratch_slots_count)); for (i = 0; i < cfs_read_scratch_slots_count; i++) pg_atomic_init_u32(&cfs_read_scratch_slots[i].state, CFS_READ_SCRATCH_FREE); } cfs_read_scratch_spans = ShmemInitStruct("CFS Read Scratch Spans", mul_size(cfs_read_scratch_span_bytes, cfs_read_scratch_slots_count), &found); /* Raw pread destination: no initialisation needed. */ ereport(DEBUG1, (errmsg("CFS: read scratch arena: %d slots of %zu bytes " "(%d MB budget)", cfs_read_scratch_slots_count, (Size) sizeof(CfsReadScratchSlot) + cfs_read_scratch_span_bytes, cfs_read_scratch_mb))); } ereport(DEBUG1, (errmsg("CFS: block-map segment pool: %d segments (%d MB)", cfs_map_seg_count, cfs_map_memory))); } /* * cfs_map_clock_tick — advance and return the map-domain access clock of a * partition (QDB-1516 Д1). Every map-domain touch point holds * cfs_map_locks[part] in LW_EXCLUSIVE mode, so a plain increment is * race-free and the tick is strictly increasing within the partition; * no atomic RMW is needed on the hot path. */ uint64 cfs_map_clock_tick(int part) { Assert(cfs_map_clocks != NULL); Assert(LWLockHeldByMeInMode(&cfs_map_locks[part].lock, LW_EXCLUSIVE)); return ++cfs_map_clocks[part]; } /* ================================================================ * Shared block-map segment pool API * ================================================================ */ /* Hash of a segment key; 0 is reserved for "free segment". */ static inline uint32 cfs_map_segment_hash(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber first_block) { CfsMapSegmentKey key; uint32 h; key.rlocator = rlocator; key.forknum = forknum; key.first_block = first_block; h = tag_hash(&key, sizeof(key)); return (h == 0) ? 1 : h; } /* Does the descriptor still describe this key (it may have been evicted)? */ static inline bool cfs_map_segment_valid(const CfsMapSegmentDesc *desc, uint32 hash, RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber first_block) { return desc->hash == hash && cfs_rlbe_eq(desc->rlocator, rlocator) && desc->forknum == forknum && desc->first_block == first_block; } /* * cfs_seg_tag_matches — does a map-generation tag (a segment descriptor's * or the one a lookup returns) still name the sidecar-pair epoch this * handle works on? This is the single definition of segment-vs-handle * epoch agreement: no call site compares the generation fields by hand * (the CFS review rules (README.md, "Review rules") reject a new one). * Exported (cfs_shmem.h) for the smgr bridges that resolve pool entries * outside this module (cfs_smgr.c). */ bool cfs_seg_tag_matches(uint64 seg_generation, const CfsRelation *cfs) { return seg_generation == cfs->open_generation; } /* * cfs_seg_matches — the cached segment still describes this key AND still * belongs to this handle's file-pair epoch. */ static inline bool cfs_seg_matches(const CfsMapSegmentDesc *desc, uint32 hash, RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber first_block, const CfsRelation *cfs) { return cfs_map_segment_valid(desc, hash, rlocator, forknum, first_block) && cfs_seg_tag_matches(desc->rel_generation, cfs); } static void cfs_map_segment_evict_one(int id, uint32 hash, BlockNumber first_block, uint64 epoch, bool unlink_rel); static void cfs_map_segment_rel_link_locked(int id); static void cfs_seg_unhealed_clear(CfsMapSegmentDesc *desc, uint32 off); static bool cfs_map_segment_unhealed_at(int id, uint32 hash, RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber first_block, BlockNumber blocknum); static int cfs_shared_map_sync_segment(CfsRelation *cfs, BlockNumber blocknum, char *corrupt_mask); static bool cfs_map_segment_acquire(const CfsMapSegmentKey *key, uint32 hash, uint64 generation, int *id_out, bool *fresh_out); static void cfs_map_segment_clear_reservation(const CfsMapSegmentKey *key, uint32 hash); static void cfs_map_pin_track(RelFileLocatorBackend rlocator, ForkNumber forknum, uint32 rel_hash); static void cfs_map_pin_untrack(RelFileLocatorBackend rlocator, ForkNumber forknum, uint32 rel_hash); static bool cfs_map_slot_reap_dead_pins(bool force); /* * Per-process scratch buffer for one segment's worth of .cfsmap entries * (768 kB), allocated lazily in TopMemoryContext and reused across loads * (the XLogReader model). The callers use it strictly sequentially — * segment loading never nests within itself in one backend — and re-zero * it before each load, since the loader only overwrites the blocks the * snapshot covers. */ static CfsMapEntry *cfs_map_seg_scratch = NULL; static CfsMapEntry * cfs_map_segment_scratch(void) { if (cfs_map_seg_scratch == NULL) cfs_map_seg_scratch = (CfsMapEntry *) MemoryContextAllocZero(TopMemoryContext, (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry)); return cfs_map_seg_scratch; } /* * Fill the INVALID slots of a segment from a loaded .cfsmap range. Entries * the segment already holds came from the journal (store) and are newer * than the snapshot, so they win. The caller holds the segment lock. */ static void cfs_map_segment_merge_invalid_locked(int id, const CfsMapEntry *buf) { int off; for (off = 0; off < CFS_MAP_SEGMENT_BLOCKS; off++) { if (cfs_map_seg_data[id][off].physical_offset == CFS_ENTRY_INVALID_OFFSET && buf[off].physical_offset != CFS_ENTRY_INVALID_OFFSET) cfs_map_seg_data[id][off] = buf[off]; } } /* * Load the .cfsmap snapshot entries of one segment range into 'buf' * (pre-zeroed by the caller, so blocks the snapshot does not cover stay * INVALID). A missing/empty snapshot (a young relation before its first * checkpoint) leaves the buffer all-INVALID: an empty snapshot is the whole * truth from the .cfsmap side. A corrupt prologue raises the shared hard * ERROR of cfs_map_file_prologue_read() directly - the single policy point * for every loader. 'corrupt_mask' is mandatory (one byte per block of the * range) and records the rows whose entry_crc failed. Returns -2 on an I/O * failure of the snapshot read; 0 otherwise. */ static int cfs_map_segment_load_buf(CfsRelation *cfs, BlockNumber first_block, CfsMapEntry *buf, Size seg_bytes, char *corrupt_mask) { uint64 nblocks; uint64 end_block; int rc; Assert(corrupt_mask != NULL); /* * A checkpoint (or a compaction that did not bump the generation this * caller observed) may have replaced the .cfsmap inode. Reading the * range through the old descriptor would mix the old snapshot with the * new, already truncated journal and publish an incomplete segment as * authoritative. The caller holds the append lock, so the identity is * stable between this check and the read. */ (void) cfs_reopen_if_map_swapped(cfs); rc = cfs_map_file_prologue_read(cfs, &nblocks); if (rc == CFS_STORAGE_ERROR) return -2; if (rc == CFS_STORAGE_NOENT) return 0; /* empty snapshot */ end_block = Min(first_block + CFS_MAP_SEGMENT_BLOCKS, nblocks); if (end_block > first_block) { /* * A short range means the snapshot is unreadable, not that the * uncovered blocks are unwritten: publishing zeroed entries would * silently fabricate a map. The caller turns this into an ERROR. * Rows are classified by the shared range reader: a corrupt row * plants INVALID and is remembered in the mask so the caller's * journal replay can heal it; a hole stays INVALID. */ rc = cfs_map_file_read_range(cfs->map_fd, first_block, end_block - first_block, buf, &corrupt_mask, CFS_MAP_SEGMENT_BLOCKS); if (rc != CFS_STORAGE_OK) return -2; } return 0; } /* * Merge the .cfsmap snapshot into a RESIDENT segment: load the range into a * private buffer (outside every lock) and fill only the INVALID slots under * the segment lock, then mark the snapshot part loaded. Used by the * authoritative resync of cfs_shared_map_sync_segment after a journal reset * invalidated the segment's merge state. Returns false when the segment * vanished (eviction race) — the caller treats that as "nothing more to do". */ static bool cfs_map_segment_merge_snapshot(CfsRelation *cfs, int id, uint32 hash, RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber first_block, char *corrupt_mask) { CfsMapEntry *buf; Size seg_bytes = (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry); bool merged = false; buf = cfs_map_segment_scratch(); MemSet(buf, 0, seg_bytes); { int load_rc; load_rc = cfs_map_segment_load_buf(cfs, first_block, buf, seg_bytes, corrupt_mask); if (load_rc == -2) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not read map segment from \"%s\"", cfs->map_path))); } LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); if (cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator, forknum, first_block)) { if (!cfs_map_seg_descs[id].snapshot_loaded) { /* * The freshly loaded snapshot is the new authority: drop bits * derived from the previous residency before the caller's sync * re-detects the rows that are still torn. */ MemSet(cfs_map_seg_descs[id].unhealed_mask, 0, sizeof(cfs_map_seg_descs[id].unhealed_mask)); cfs_map_segment_merge_invalid_locked(id, buf); cfs_map_seg_descs[id].snapshot_loaded = true; cfs_map_seg_descs[id].journal_synced = false; pg_atomic_fetch_add_u64(&cfs_control->map_segment_loads, 1); } merged = true; } LWLockRelease(&cfs_map_seg_locks[id].lock); return merged; } /* * Current on-disk journal incarnation of 'cfs'. 0 when the header is * momentarily unreadable; a segment stamped 0 never matches a real * incarnation (they start at 1), so its first sync resyncs once — fail * safe. */ static uint16 cfs_map_segment_journal_incarnation(CfsRelation *cfs) { CfsJournalFileHeader jhdr; if (cfs_journal_read_header(cfs->jrn_fd, &jhdr)) return jhdr.incarnation; return 0; } /* * Roll back a fresh acquire that could not load its data: drop the mapping * entry and leave the descriptor hash == 0 (free), so no reader can ever * observe a published-but-empty segment. */ static void cfs_map_segment_release_reservation(const CfsMapSegmentKey *key, uint32 hash, int id) { int part = hash & CFS_PART_MASK; CfsMapSegmentHashEnt *ent; /* * Remove the mapping first, then clear 'reserved'. The reverse order * exposed a ghost (hash == 0 && !reserved) to a competitor, which could * recreate the mapping and then have it removed by our HASH_REMOVE. */ LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); ent = (CfsMapSegmentHashEnt *) hash_search_with_hash_value(cfs_map_seg_hash, key, hash, HASH_FIND, NULL); if (ent != NULL && ent->segment_id == id) hash_search_with_hash_value(cfs_map_seg_hash, key, hash, HASH_REMOVE, NULL); LWLockRelease(&cfs_map_locks[part].lock); cfs_map_segment_clear_reservation(key, hash); LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); if (cfs_map_seg_descs[id].hash == 0 && cfs_map_seg_descs[id].reserved) cfs_map_seg_descs[id].reserved = false; LWLockRelease(&cfs_map_seg_locks[id].lock); } static void cfs_map_segment_invalidate_block(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum); static void cfs_map_segment_rel_link_locked(int id); /* * Publish a segment: copy in the snapshot range (or zero it for a store * publication), stamp the descriptor and link it into the relation index. * The caller holds the index lock and the segment lock, has checked that * the descriptor is free (or, for the test hook, is ours), and has already * retired the in-flight reservation. * * 'snapshot' is the loaded .cfsmap range; NULL publishes a segment that * holds only journaled (store) entries and must still merge the snapshot * on its first read. 'journal_synced' states whether the published * contents already include the journal delta. 'jrn_incarnation' is the * value sampled by the caller before taking any pool lock; a store * publication passes 0 so the first sync sees a mismatching incarnation * and re-baselines the segment (snapshot merge + full replay). * * Having one function for all publications keeps the invariants (epoch, * reservation flag, index link, in-use counter) in one place: the three * call sites used to duplicate them with subtly different flags. */ static void cfs_map_segment_publish_locked(int id, uint32 hash, RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber first_block, uint64 rel_generation, const CfsMapEntry *snapshot, bool journal_synced, uint16 jrn_incarnation) { CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id]; Size seg_bytes = (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry); bool newly_used = (desc->hash == 0); if (snapshot != NULL) memcpy(cfs_map_seg_data[id], snapshot, seg_bytes); else MemSet(cfs_map_seg_data[id], 0, seg_bytes); desc->hash = hash; desc->rlocator = rlocator; desc->forknum = forknum; desc->first_block = first_block; desc->rel_generation = rel_generation; desc->snapshot_loaded = (snapshot != NULL); desc->journal_synced = journal_synced; MemSet(desc->unhealed_mask, 0, sizeof(desc->unhealed_mask)); desc->jrn_synced_off = 0; desc->jrn_incarnation = jrn_incarnation; desc->seg_epoch++; desc->reserved = false; if (newly_used) { pg_atomic_write_u32(&desc->usage_count, 0); cfs_map_segment_rel_link_locked(id); pg_atomic_fetch_add_u64(&cfs_control->map_segments_in_use, 1); pg_atomic_fetch_add_u64(&cfs_control->map_pool_churn, 1); } } /* * Find the id of the pool segment mapped to 'key' and validate the range. * Takes the mapping partition lock in the requested mode, copies the id out * under the lock (the hash entry may be freed as soon as it is released) * and reports an out-of-range id as a plain miss: a mapping entry can * outlive its descriptor (a ghost), and an id outside the pool is never * usable. The caller must still validate the descriptor under the segment * lock — the id may be recycled between the two steps. */ static int cfs_map_segment_find(const CfsMapSegmentKey *key, uint32 hash, LWLockMode mode) { CfsMapSegmentHashEnt *ent; int part = hash & CFS_PART_MASK; int id; LWLockAcquire(&cfs_map_locks[part].lock, mode); ent = (CfsMapSegmentHashEnt *) hash_search_with_hash_value(cfs_map_seg_hash, key, hash, HASH_FIND, NULL); id = (ent != NULL) ? ent->segment_id : -1; LWLockRelease(&cfs_map_locks[part].lock); if (id < 0 || id >= cfs_map_seg_count) return -1; return id; } /* * Per-process epoch for segment reservations. The epoch is taken lazily on * first use and written into this process's ProcNumber slot; a recycled * ProcNumber gets a new value when its new owner first touches CFS. */ static uint64 cfs_map_owner_epoch_get(void) { if (cfs_owner_epoch == 0) { cfs_owner_epoch = pg_atomic_add_fetch_u64(&cfs_control->owner_epoch_next, 1); if (cfs_proc_epochs != NULL && MyProcNumber >= 0 && MyProcNumber < cfs_proc_epochs_count) pg_atomic_write_u64(&cfs_proc_epochs[MyProcNumber], cfs_owner_epoch); } return cfs_owner_epoch; } /* Is (procno, pid, epoch) still the same live process? */ static bool cfs_map_owner_alive(int procno, int pid, uint64 epoch) { PGPROC *proc; if (cfs_proc_epochs == NULL || procno < 0 || procno >= cfs_proc_epochs_count) return false; proc = ProcNumberGetProc(procno); if (proc == NULL || proc->pid != pid) return false; return pg_atomic_read_u64(&cfs_proc_epochs[procno]) == epoch; } /* Is the owner recorded in a reservation still the same live process? */ static bool cfs_map_reservation_owner_alive(const CfsMapSegmentReservation *live) { return cfs_map_owner_alive(live->owner_procno, live->owner_pid, live->owner_epoch); } /* * Classify the in-flight reservation for this key/id pair: missing, live * or dead. A missing entry means either no reservation at all or the short * window between clear_reservation() and publication; both must not be * reaped. */ #define CFS_RESERVATION_MISSING 0 #define CFS_RESERVATION_LIVE 1 #define CFS_RESERVATION_DEAD 2 static int cfs_map_segment_reservation_state(const CfsMapSegmentKey *key, int id) { int part = cfs_map_segment_hash(key->rlocator, key->forknum, key->first_block) & CFS_PART_MASK; CfsMapSegmentReservation *live; int state; if (cfs_map_seg_live == NULL) return CFS_RESERVATION_MISSING; LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED); live = (CfsMapSegmentReservation *) hash_search(cfs_map_seg_live, key, HASH_FIND, NULL); if (live == NULL || live->segment_id != id) state = CFS_RESERVATION_MISSING; else if (cfs_map_reservation_owner_alive(live)) state = CFS_RESERVATION_LIVE; else state = CFS_RESERVATION_DEAD; LWLockRelease(&cfs_map_locks[part].lock); return state; } /* * Reap a reservation whose owner died before publishing. The descriptor * still has 'reserved' set and a ghost mapping may exist, so reuse the * normal rollback path. A live owner is never touched. */ static bool cfs_map_segment_reap_if_dead(const CfsMapSegmentKey *key, uint32 hash, int id) { if (cfs_map_segment_reservation_state(key, id) != CFS_RESERVATION_DEAD) return false; cfs_map_segment_release_reservation(key, hash, id); return true; } /* Drop an in-flight reservation after publication or on failure. */ static void cfs_map_segment_clear_reservation(const CfsMapSegmentKey *key, uint32 hash) { int part = hash & CFS_PART_MASK; if (cfs_map_seg_live == NULL) return; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); hash_search_with_hash_value(cfs_map_seg_live, key, hash, HASH_REMOVE, NULL); LWLockRelease(&cfs_map_locks[part].lock); } /* * Bump the clock-sweep usage counter with saturation. Called on a lookup * hit and on a successful store, while the segment lock is held. */ static inline void cfs_map_segment_bump_usage(CfsMapSegmentDesc *desc) { uint32 old; old = pg_atomic_fetch_add_u32(&desc->usage_count, 1); if (old >= CFS_MAP_SEG_USAGE_MAX) pg_atomic_write_u32(&desc->usage_count, CFS_MAP_SEG_USAGE_MAX); } /* * Decrement the clock-sweep usage counter only when it is positive. A plain * fetch_sub after a shared-lock read of 1 lets two sweepers underflow the * counter to UINT32_MAX, which makes the segment effectively unevictable; * the CAS loop is the bufmgr-style "decrement if nonzero" rule. */ static bool cfs_map_segment_dec_usage(CfsMapSegmentDesc *desc) { for (;;) { uint32 old = pg_atomic_read_u32(&desc->usage_count); if (old == 0) return false; if (pg_atomic_compare_exchange_u32(&desc->usage_count, &old, old - 1)) return true; } } /* * Clock-sweep victim selection, modelled on bufmgr's ClockSweepTick: * advance the shared hand one segment per tick, decrement a nonzero usage * count and move on, and choose the first segment whose count reached zero. * A free segment wins immediately. Reserved segments and segments whose * relation is still pinned are skipped. The key and epoch are sampled under * the segment lock and re-validated by cfs_map_segment_evict_one(), so a * recycle of the same id/key cannot be evicted by mistake. * * Returns the victim id (or -1 when a full sweep found no candidate); * out_free tells the caller whether it must evict or may insert directly. */ static int cfs_map_segment_select_victim(uint32 *out_hash, BlockNumber *out_first, uint64 *out_epoch, bool *out_free) { int ticks; int max_ticks = cfs_map_seg_count * (CFS_MAP_SEG_USAGE_MAX + 1); int since_progress = 0; /* Test-only: simulate a pool with no allocatable victim. */ if (cfs_test_pool_block_victim) return -1; for (ticks = 0; ticks < max_ticks; ticks++) { uint32 tick = cfs_map_seg_hand++; int id = tick % cfs_map_seg_count; CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id]; uint32 hash; uint32 usage; bool reserved; RelFileLocatorBackend rlocator; ForkNumber forknum; BlockNumber first_block; uint64 epoch; CfsMapSegmentKey key; LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED); hash = desc->hash; reserved = desc->reserved; rlocator = desc->rlocator; forknum = desc->forknum; first_block = desc->first_block; epoch = desc->seg_epoch; usage = pg_atomic_read_u32(&desc->usage_count); LWLockRelease(&cfs_map_seg_locks[id].lock); key.rlocator = rlocator; key.forknum = forknum; key.first_block = first_block; /* * A skipped tick is no progress: a full revolution without a single * usage decrement (or a free hit) means every segment is reserved, * mid-acquisition or pinned, so no number of further passes can find * a victim. Bail out after that revolution instead of sweeping * CFS_MAP_SEG_USAGE_MAX + 1 times, each tick taking a segment lock. */ if (reserved) { uint32 key_hash; key_hash = cfs_map_segment_hash(rlocator, forknum, first_block); if (cfs_map_segment_reap_if_dead(&key, key_hash, id)) { since_progress = 0; continue; } if (++since_progress >= cfs_map_seg_count) return -1; continue; } if (hash == 0) { int res_state; res_state = cfs_map_segment_reservation_state(&key, id); if (res_state == CFS_RESERVATION_DEAD) { uint32 key_hash; key_hash = cfs_map_segment_hash(rlocator, forknum, first_block); (void) cfs_map_segment_reap_if_dead(&key, key_hash, id); since_progress = 0; } else if (res_state == CFS_RESERVATION_LIVE) { if (++since_progress >= cfs_map_seg_count) return -1; continue; } *out_hash = 0; *out_first = 0; *out_epoch = epoch; *out_free = true; return id; } /* * A pinned relation does not protect its segments here: the slot pin * guards the metadata slot, and the working set is protected by * usage_count alone (bumped by every lookup/store). Skipping the * segments of open relations would let one relation larger than the * pool keep it exhausted forever, with every further read paying the * authoritative fallback (measured: a 12x oversize degraded every * scan linearly, evictions stayed 0). */ if (usage > 0) { (void) cfs_map_segment_dec_usage(desc); since_progress = 0; continue; } *out_hash = hash; *out_first = first_block; *out_epoch = epoch; *out_free = false; return id; } return -1; } int cfs_shared_map_ensure(CfsRelation *cfs, BlockNumber blocknum) { RelFileLocatorBackend rlocator = cfs->rlocator; ForkNumber forknum = cfs->forknum; CfsMapSegmentKey key; uint32 hash; int id; int attempt; bool fresh_segment = false; CfsMapEntry *buf = NULL; Size seg_bytes = (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry); bool merge_only = false; uint16 jrn_incarnation = 0; volatile bool reservation_held = false; char *corrupt_mask = NULL; int sync_rc; if (cfs_map_seg_count == 0) return CFS_STORAGE_ERROR; if (cfs_map_pool_exhausted && pg_atomic_read_u64(&cfs_control->map_pool_churn) == cfs_map_pool_exhausted_churn) return CFS_STORAGE_ERROR; key.rlocator = rlocator; key.forknum = forknum; key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1); hash = cfs_map_segment_hash(rlocator, forknum, key.first_block); /* * A segment of an older relation generation may hold offsets tagged with * the pre-truncate/pre-compaction sidecar pair; it must never satisfy a * read through the new handle. Evict it and try again: the retry either * reloads the segment under the current generation or loses the race and * reports a miss to the caller, which then falls back to the * authoritative path. */ for (attempt = 0; attempt < 2; attempt++) { bool stale_generation = false; uint64 stale_epoch = 0; merge_only = false; fresh_segment = false; buf = NULL; /* Fast path: the segment is resident AND snapshot-complete. */ id = cfs_map_segment_find(&key, hash, LW_SHARED); if (id >= 0) { int lock_id = id; LWLockAcquire(&cfs_map_seg_locks[lock_id].lock, LW_SHARED); if (cfs_map_segment_valid(&cfs_map_seg_descs[lock_id], hash, rlocator, forknum, key.first_block)) { if (!cfs_seg_tag_matches(cfs_map_seg_descs[lock_id].rel_generation, cfs)) { stale_generation = true; stale_epoch = cfs_map_seg_descs[lock_id].seg_epoch; } else { merge_only = !cfs_map_seg_descs[lock_id].snapshot_loaded; if (!merge_only) { bool unhealed = cfs_map_segment_unhealed_at(lock_id, hash, rlocator, forknum, key.first_block, blocknum); LWLockRelease(&cfs_map_seg_locks[lock_id].lock); /* * Only the requested block decides this call: other * torn blocks of the same segment stay in the bitmap * and fail their own reads through the corruption * report. */ return unhealed ? CFS_STORAGE_CORRUPT : CFS_STORAGE_OK; } } } else id = -1; LWLockRelease(&cfs_map_seg_locks[lock_id].lock); } if (stale_generation) { cfs_map_segment_evict_one(id, hash, key.first_block, stale_epoch, true); continue; } /* * A resident segment that only holds journaled (store) entries needs * the .cfsmap snapshot merged into its INVALID slots before its * entries can be trusted by lookups; take the acquire path, which * re-recognises the resident segment, and merge below (never * overwriting the fresher journaled entries). */ if (merge_only) { /* * Re-lookup only: a shared lock suffices — the search modifies * nothing, and a vanished entry is caught by the acquire/validate * steps below. */ id = cfs_map_segment_find(&key, hash, LW_SHARED); if (id < 0) merge_only = false; /* vanished: full ensure below */ } /* * Allocate (or find) the segment, evicting a clock-sweep victim when * the pool is full. A competitor may be allocating the same segment * right now: its mapping entry exists while desc->hash is still 0 * until the loader publishes the data, and a shared acquisition does * not wait for that load (the I/O happens outside the lock). The * validation below therefore sees an unpublished descriptor and * reports a miss, which the caller retries or resolves through the * authoritative path — it never accepts an "ensured" segment whose * entries are not there yet. */ if (!merge_only) { if (!cfs_map_segment_acquire(&key, hash, cfs->open_generation, &id, &fresh_segment)) continue; if (!fresh_segment) { LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED); if (!cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator, forknum, key.first_block)) { /* The id was re-used by another key meanwhile: miss. */ LWLockRelease(&cfs_map_seg_locks[id].lock); continue; } if (!cfs_seg_tag_matches(cfs_map_seg_descs[id].rel_generation, cfs)) { stale_epoch = cfs_map_seg_descs[id].seg_epoch; LWLockRelease(&cfs_map_seg_locks[id].lock); cfs_map_segment_evict_one(id, hash, key.first_block, stale_epoch, true); continue; } merge_only = !cfs_map_seg_descs[id].snapshot_loaded; if (!merge_only) { bool unhealed = cfs_map_segment_unhealed_at(id, hash, rlocator, forknum, key.first_block, blocknum); LWLockRelease(&cfs_map_seg_locks[id].lock); return unhealed ? CFS_STORAGE_CORRUPT : CFS_STORAGE_OK; } LWLockRelease(&cfs_map_seg_locks[id].lock); } } /* * Load the segment from the .cfsmap snapshot into a private buffer, * outside every lock. Blocks the snapshot does not cover yet stay * zeroed (the INVALID sentinel) — the journal delta replay of the * authoritative miss path fills them in and advances jrn_synced_off. * The load starts at journal offset 0 on purpose: a snapshot written * by smgrimmedsync() does not truncate the journal, so replaying from * the journal header after every snapshot load is the norm, not a * corner case (the offset is not worth optimising: immedsync is * rare). * * A missing/empty snapshot (a young relation before its first * checkpoint) means an empty snapshot is the whole truth from the * .cfsmap side: the zeroed buffer is published/merged as-is and the * journal replay that the authoritative miss path always runs right * after ensure fills in the written blocks from the journal header. */ if (fresh_segment) reservation_held = true; PG_TRY(); { buf = cfs_map_segment_scratch(); MemSet(buf, 0, seg_bytes); if (corrupt_mask != NULL) pfree(corrupt_mask); corrupt_mask = palloc0(CFS_MAP_SEGMENT_BLOCKS); { int load_rc; load_rc = cfs_map_segment_load_buf(cfs, key.first_block, buf, seg_bytes, corrupt_mask); if (load_rc < 0) { /* * The snapshot is a synchronisation point (see * cfs_map_file_prologue_read): no fallback source exists. * PG_FINALLY releases the reservation, or the reserved * descriptor stays unpublished forever. */ ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not read map segment from \"%s\"", cfs->map_path))); } } /* * Sample the journal incarnation before any pool lock is taken: * it costs a pread of the journal header, and performing that * under the index/segment locks would stall every publisher for * the duration of the disk read. Under the append lock (which * every production caller of ensure holds) the journal header is * stable, so the early sample equals what a later read would * return; a caller without the lock can only race a checkpoint * into an incarnation mismatch, which the segment's first sync * turns into a harmless resync. */ jrn_incarnation = cfs_map_segment_journal_incarnation(cfs); #ifdef USE_ASSERT_CHECKING /* * Test-only I4 race: a competitor merged the snapshot between our * load above and the segment phase below. The merge helper * reloads the same per-backend scratch buffer, so 'buf' is no * longer ours; the segment phase then takes the "already merged" * branch anyway, which is exactly the behaviour under test. */ if (cfs_test_merge_race_pending) { cfs_test_merge_race_pending = false; if (!fresh_segment) { char *race_mask = palloc0(CFS_MAP_SEGMENT_BLOCKS); (void) cfs_map_segment_merge_snapshot(cfs, id, hash, rlocator, forknum, key.first_block, race_mask); pfree(race_mask); } } #endif if (fresh_segment) { cfs_map_segment_clear_reservation(&key, hash); reservation_held = false; } } PG_FINALLY(); { if (reservation_held) cfs_map_segment_release_reservation(&key, hash, id); } PG_END_TRY(); /* * Segment phase: publish the loaded data under the segment lock. A * concurrent eviction may have freed the id while we were reading: * for a fresh allocation the hash == 0 re-check turns that into a * plain miss; a concurrent eviction/re-use of an existing id is * caught by the key re-validation. Fresh allocation: publish the * loaded snapshot wholesale (desc->hash == 0 still marks our * reservation). Merge into a store-created segment: fill only the * INVALID slots — the journaled entries it already holds are newer * than the snapshot — and mark the snapshot part loaded. */ LWLockAcquire(&cfs_map_rel_index_lock->lock, LW_EXCLUSIVE); LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); if (cfs_map_seg_descs[id].hash == 0) { cfs_map_segment_publish_locked(id, hash, rlocator, forknum, key.first_block, cfs->open_generation, buf, false, jrn_incarnation); pg_atomic_fetch_add_u64(&cfs_control->map_segment_loads, 1); LWLockRelease(&cfs_map_seg_locks[id].lock); LWLockRelease(&cfs_map_rel_index_lock->lock); /* * The published snapshot may be staler than the journal (a * truncate journals RESIZE long before the next checkpoint * rewrites .cfsmap): replay the journal into the segment now, so * no reader can hit an entry the journal has since deleted. The * replay also decides the freshly loaded corrupt rows: a row the * journal does not heal fails the read (CORRUPT) instead of ever * serving as a zero page. */ sync_rc = cfs_shared_map_sync_segment(cfs, blocknum, corrupt_mask); pfree(corrupt_mask); /* * CORRUPT propagates; a transient sync failure (0) must not read * as ensured - the follow-up sync of the read path runs without a * mask and would grant journal_synced unchecked. The caller's * authoritative fallback re-validates instead. */ return (sync_rc == 1) ? CFS_STORAGE_OK : (sync_rc == CFS_STORAGE_CORRUPT ? CFS_STORAGE_CORRUPT : CFS_STORAGE_ERROR); } if (cfs_seg_matches(&cfs_map_seg_descs[id], hash, rlocator, forknum, key.first_block, cfs)) { if (!cfs_map_seg_descs[id].snapshot_loaded) { cfs_map_segment_merge_invalid_locked(id, buf); cfs_map_seg_descs[id].snapshot_loaded = true; cfs_map_seg_descs[id].journal_synced = false; MemSet(cfs_map_seg_descs[id].unhealed_mask, 0, sizeof(cfs_map_seg_descs[id].unhealed_mask)); cfs_map_seg_descs[id].jrn_incarnation = jrn_incarnation; /* * The merged snapshot may predate journal records * (RESIZE/DELETE) the segment has not consumed; rebaseline * the replay cursor so the full journal replay below * re-applies them AFTER the merge, clearing whatever the * stale snapshot resurrected. */ cfs_map_seg_descs[id].jrn_synced_off = 0; pg_atomic_fetch_add_u64(&cfs_control->map_segment_loads, 1); LWLockRelease(&cfs_map_seg_locks[id].lock); LWLockRelease(&cfs_map_rel_index_lock->lock); sync_rc = cfs_shared_map_sync_segment(cfs, blocknum, corrupt_mask); pfree(corrupt_mask); return (sync_rc == 1) ? CFS_STORAGE_OK : (sync_rc == CFS_STORAGE_CORRUPT ? CFS_STORAGE_CORRUPT : CFS_STORAGE_ERROR); } { bool unhealed = cfs_map_segment_unhealed_at(id, hash, rlocator, forknum, key.first_block, blocknum); LWLockRelease(&cfs_map_seg_locks[id].lock); LWLockRelease(&cfs_map_rel_index_lock->lock); pfree(corrupt_mask); return unhealed ? CFS_STORAGE_CORRUPT : CFS_STORAGE_OK; } } LWLockRelease(&cfs_map_seg_locks[id].lock); LWLockRelease(&cfs_map_rel_index_lock->lock); } /* * The pool could not serve us: remember the churn value so the next miss * of this backend goes straight to the authoritative fallback until * something changes. The fallback is always correct, so a stale memo * only costs a scratch load, never data. */ cfs_map_pool_exhausted = true; cfs_map_pool_exhausted_churn = pg_atomic_read_u64(&cfs_control->map_pool_churn); if (corrupt_mask != NULL) pfree(corrupt_mask); return CFS_STORAGE_ERROR; } bool cfs_shared_map_lookup(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum, CfsMapEntry *out_entry, uint64 *out_generation) { CfsMapSegmentKey key; uint32 hash; int id; bool found = false; uint64 nblocks; if (cfs_map_seg_count == 0) return false; /* * Serve only blocks below the metadata slot's current logical size . * Today the .cfsmap file is always exactly nblocks rows, so resident rows * beyond nblocks can only appear transiently - a truncate shrinks the * slot (and journals RESIZE) under the append lock but drops the segments * outside it. With deferred truncation and sparse maps this gate becomes * load-bearing. An absent or zero-size slot imposes no restriction: its * size is simply not published yet. */ if (cfs_map_cache_get_nblocks(rlocator, forknum, &nblocks) && nblocks > 0 && (uint64) blocknum >= nblocks) return false; key.rlocator = rlocator; key.forknum = forknum; key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1); hash = cfs_map_segment_hash(rlocator, forknum, key.first_block); id = cfs_map_segment_find(&key, hash, LW_SHARED); if (id < 0) return false; /* * The segment may have been evicted and its id re-used between the hash * lookup and here; the descriptor check under the segment lock catches * that and turns it into a plain miss. */ LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED); if (cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator, forknum, key.first_block) && cfs_map_seg_descs[id].journal_synced && !cfs_map_segment_unhealed_at(id, hash, rlocator, forknum, key.first_block, blocknum)) { CfsMapEntry *entry; entry = &cfs_map_seg_data[id][blocknum - key.first_block]; if (entry->physical_offset != CFS_ENTRY_INVALID_OFFSET) { *out_entry = *entry; if (out_generation != NULL) *out_generation = cfs_map_seg_descs[id].rel_generation; cfs_map_segment_bump_usage(&cfs_map_seg_descs[id]); found = true; } } LWLockRelease(&cfs_map_seg_locks[id].lock); return found; } /* * cfs_map_segment_acquire — make sure the pool holds a (possibly fresh, * still invisible) segment for 'key', evicting a clock-sweep victim when * the pool is full. 'generation' tags the allocation with the relation map * generation its offsets will belong to (captured by the caller before * any locks: a stale tag costs one extra handle reopen, never incorrect * data). On success *id_out is the segment id and *fresh_out tells * whether WE allocated it (and must zero its data and publish desc->hash * in the segment phase). Returns false when no victim can be found * (every segment pinned) or a race lost three times in a row — the * caller then degrades to the authoritative path, which is always * correct without a resident segment. */ static bool cfs_map_segment_acquire(const CfsMapSegmentKey *key, uint32 hash, uint64 generation, int *id_out, bool *fresh_out) { int part = hash & CFS_PART_MASK; CfsMapSegmentHashEnt *ent; int id; int candidate; int tries; *fresh_out = false; for (tries = 0; tries < 3; tries++) { bool candidate_ready = false; /* * Look the key up before choosing a victim. A repeated store of an * already resident segment is a plain update: scanning for (and * evicting) a victim first threw an unrelated resident segment out of * a full pool for no reason. */ id = cfs_map_segment_find(key, hash, LW_SHARED); if (id >= 0) { bool ghost; bool reserved; /* * A mapping entry may point at a descriptor an invalidation has * meanwhile freed (a "ghost" mapping); an entry whose descriptor * is reserved belongs to an acquirer still publishing it and is * returned so the caller can wait for/validate the publication. A * reserved descriptor whose owner died is reaped here: the * segment lock is released first because the reaper needs the * mapping lock. */ LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED); ghost = (cfs_map_seg_descs[id].hash == 0 && !cfs_map_seg_descs[id].reserved); reserved = cfs_map_seg_descs[id].reserved; LWLockRelease(&cfs_map_seg_locks[id].lock); if (reserved) { if (cfs_map_segment_reap_if_dead(key, hash, id)) { /* * The reaped descriptor is free again: reuse exactly this * id instead of sweeping for another one. */ candidate = id; candidate_ready = true; } else { *id_out = id; return true; } } if (!reserved && !ghost) { *id_out = id; return true; } } /* * Pick a segment with the clock sweep. Both the sweep and the * eviction take segment/mapping locks themselves, so they run before * we take the mapping partition lock below. */ if (!candidate_ready) { uint32 victim_hash; BlockNumber victim_first; uint64 victim_epoch; bool victim_free; candidate = cfs_map_segment_select_victim(&victim_hash, &victim_first, &victim_epoch, &victim_free); if (candidate < 0) return false; /* every segment is pinned */ if (!victim_free) cfs_map_segment_evict_one(candidate, victim_hash, victim_first, victim_epoch, true); } LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); ent = (CfsMapSegmentHashEnt *) hash_search_with_hash_value(cfs_map_seg_hash, key, hash, HASH_FIND, NULL); id = (ent != NULL) ? ent->segment_id : -1; /* * A concurrent eviction can leave a ghost mapping between the lookup * above and this exclusive re-check; drop it before allocating. */ if (id >= 0 && id < cfs_map_seg_count) { bool ghost; LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED); ghost = (cfs_map_seg_descs[id].hash == 0 && !cfs_map_seg_descs[id].reserved); LWLockRelease(&cfs_map_seg_locks[id].lock); if (ghost) { hash_search_with_hash_value(cfs_map_seg_hash, key, hash, HASH_REMOVE, NULL); id = -1; } } if (id >= 0 && id < cfs_map_seg_count) { /* Resident (or a competitor's fresh allocation). */ LWLockRelease(&cfs_map_locks[part].lock); *id_out = id; return true; } /* * The exclusive re-lookup above overwrote 'id'; go back to the * candidate the clock sweep chose (free or just evicted). */ id = candidate; /* * Reserve the descriptor under the segment lock: 'reserved' makes the * sweep skip the id while we initialise its fields and publish the * mapping entry (the buffer-manager pin-before-publish model — * without it a competitor could allocate the same "free" descriptor * and leave two mapping entries pointing at one descriptor). * desc->hash stays 0: the descriptor remains invisible to readers * until the owner's segment phase publishes initialised data. */ { CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id]; bool found; LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); if (desc->hash != 0 || desc->reserved) { /* Lost the candidate between the sweep and here; retry. */ LWLockRelease(&cfs_map_seg_locks[id].lock); LWLockRelease(&cfs_map_locks[part].lock); continue; } desc->rlocator = key->rlocator; desc->forknum = key->forknum; desc->first_block = key->first_block; desc->jrn_synced_off = 0; desc->jrn_incarnation = 0; desc->rel_generation = generation; desc->snapshot_loaded = false; desc->journal_synced = false; desc->seg_epoch++; desc->reserved = true; LWLockRelease(&cfs_map_seg_locks[id].lock); ent = (CfsMapSegmentHashEnt *) hash_search_with_hash_value(cfs_map_seg_hash, key, hash, HASH_ENTER, &found); if (!found) { CfsMapSegmentReservation *live; ent->segment_id = id; live = (CfsMapSegmentReservation *) hash_search_with_hash_value(cfs_map_seg_live, key, hash, HASH_ENTER, NULL); live->segment_id = id; live->owner_pid = MyProcPid; live->owner_procno = MyProcNumber; live->owner_epoch = cfs_map_owner_epoch_get(); *id_out = id; *fresh_out = true; LWLockRelease(&cfs_map_locks[part].lock); return true; } /* * A concurrent insert won the race; its segment is ours. Copy * the id while the partition lock is still held: 'ent' may be * freed as soon as the lock is released. */ { int winner_id = ent->segment_id; LWLockRelease(&cfs_map_locks[part].lock); LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); desc->reserved = false; LWLockRelease(&cfs_map_seg_locks[id].lock); *id_out = winner_id; return true; } } } return false; } bool cfs_shared_map_store(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum, const CfsMapEntry *entry, uint64 generation) { CfsMapSegmentKey key; uint32 hash; int id; bool fresh_segment = false; if (cfs_map_seg_count == 0) return false; key.rlocator = rlocator; key.forknum = forknum; key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1); hash = cfs_map_segment_hash(rlocator, forknum, key.first_block); /* * The caller (cfs_write_page_cached) holds the append lock and has just * refreshed a stale handle, so the generation it passes is its open * generation, naming the sidecar pair the new entry's offset belongs to. * A racing compaction is excluded by that same lock. */ if (!cfs_map_segment_acquire(&key, hash, generation, &id, &fresh_segment)) return false; /* * Segment phase: for a fresh allocation zero the data first and only then * publish desc->hash; for an existing segment validate the key (the id * may have been evicted and re-used while we waited). The in-flight * reservation is retired just before publication, while 'reserved' still * keeps the victim sweep away from the descriptor. */ if (fresh_segment) cfs_map_segment_clear_reservation(&key, hash); /* * A fresh publication must also be linked into the per-relation index, * which requires the index lock outside the segment lock. Updates of an * already resident segment (the common per-block case) skip it. */ if (fresh_segment) LWLockAcquire(&cfs_map_rel_index_lock->lock, LW_EXCLUSIVE); LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); if (fresh_segment && cfs_map_seg_descs[id].hash == 0) cfs_map_segment_publish_locked(id, hash, rlocator, forknum, key.first_block, generation, NULL, true, 0); if (cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator, forknum, key.first_block)) { uint32 off = blocknum - key.first_block; cfs_map_seg_data[id][off] = *entry; /* * A freshly written version resolves the block: any earlier torn * snapshot row for it is superseded, so the block may serve again. */ cfs_seg_unhealed_clear(&cfs_map_seg_descs[id], off); cfs_map_segment_bump_usage(&cfs_map_seg_descs[id]); LWLockRelease(&cfs_map_seg_locks[id].lock); if (fresh_segment) LWLockRelease(&cfs_map_rel_index_lock->lock); return true; } LWLockRelease(&cfs_map_seg_locks[id].lock); if (fresh_segment) LWLockRelease(&cfs_map_rel_index_lock->lock); return false; } /* * The index key is compared bytewise (HASH_BLOBS), so clear the tail * padding that a struct assignment would leave uninitialised. */ static void cfs_map_segment_rel_key(CfsMapSegmentRelKey *key, RelFileLocatorBackend rlocator, ForkNumber forknum) { MemSet(key, 0, sizeof(*key)); key->rlocator = rlocator; key->forknum = forknum; } /* * Link a freshly published descriptor into its relation's segment list. * The caller holds the index lock and the segment lock (so the descriptor's * key fields cannot change underneath). */ static void cfs_map_segment_rel_link_locked(int id) { CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id]; CfsMapSegmentRelKey key; CfsMapSegmentRelEnt *ent; bool found; Assert(!desc->rel_linked); cfs_map_segment_rel_key(&key, desc->rlocator, desc->forknum); ent = hash_search(cfs_map_rel_index, &key, HASH_ENTER, &found); if (!found) { dlist_init(&ent->head); ent->count = 0; } dlist_push_head(&ent->head, &desc->rel_node); desc->rel_linked = true; ent->count++; } /* * Unlink a published descriptor from its relation's segment list. The * caller holds the index lock and the segment lock. A descriptor that is * already detached (the invalidation path detaches before it evicts) is * left alone, which keeps the call idempotent. */ static void cfs_map_segment_rel_unlink_locked(int id) { CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id]; CfsMapSegmentRelKey key; CfsMapSegmentRelEnt *ent; if (!desc->rel_linked) return; cfs_map_segment_rel_key(&key, desc->rlocator, desc->forknum); ent = hash_search(cfs_map_rel_index, &key, HASH_FIND, NULL); Assert(ent != NULL); dlist_delete_thoroughly(&desc->rel_node); desc->rel_linked = false; ent->count--; Assert(desc->rel_node.prev == NULL && desc->rel_node.next == NULL); if (ent->count == 0) { Assert(dlist_is_empty(&ent->head)); hash_search(cfs_map_rel_index, &key, HASH_REMOVE, NULL); } } /* * Drop the hash-table entry and free the descriptor of one segment. The * caller has verified under the segment lock that the descriptor matches * 'hash'/'first_block'; we re-check under the segment lock after the hash * removal so that a concurrent re-use of the id by another key is never * freed by mistake. 'unlink_rel' tells whether the descriptor still sits * in the per-relation index (the invalidation path detaches its nodes * itself, under the index lock, before calling here). */ static void cfs_map_segment_evict_one(int id, uint32 hash, BlockNumber first_block, uint64 epoch, bool unlink_rel) { CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id]; int part = hash & CFS_PART_MASK; CfsMapSegmentKey key; bool still_victim = false; /* * Sample the victim key under the segment lock: reading the descriptor * fields before taking it could race a re-use of the id for another * relation and remove the wrong mapping entry. hash + first_block + * epoch are enough to identify the victim exactly: every publication and * every release bumps the epoch in the same critical section that * rewrites the key fields, so a descriptor recycled for another * rlocator/forknum must carry a different epoch even if the id, hash and * first_block happen to repeat (the rlocator/forknum fields are therefore * not compared separately). The index lock is the outer one (index -> * segment), and the node is detached in the same critical section that * samples it. */ if (unlink_rel) LWLockAcquire(&cfs_map_rel_index_lock->lock, LW_EXCLUSIVE); LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED); if (desc->hash == hash && desc->first_block == first_block && desc->seg_epoch == epoch && !desc->reserved) { key.rlocator = desc->rlocator; key.forknum = desc->forknum; key.first_block = first_block; still_victim = true; if (unlink_rel) cfs_map_segment_rel_unlink_locked(id); } LWLockRelease(&cfs_map_seg_locks[id].lock); if (unlink_rel) LWLockRelease(&cfs_map_rel_index_lock->lock); if (!still_victim) return; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); hash_search_with_hash_value(cfs_map_seg_hash, &key, hash, HASH_REMOVE, NULL); LWLockRelease(&cfs_map_locks[part].lock); LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); if (desc->hash == hash && desc->first_block == first_block && desc->seg_epoch == epoch) { desc->hash = 0; pg_atomic_write_u32(&desc->usage_count, 0); desc->snapshot_loaded = false; desc->journal_synced = false; desc->seg_epoch++; pg_atomic_fetch_sub_u64(&cfs_control->map_segments_in_use, 1); pg_atomic_fetch_add_u64(&cfs_control->map_segment_evictions, 1); pg_atomic_fetch_add_u64(&cfs_control->map_pool_churn, 1); } LWLockRelease(&cfs_map_seg_locks[id].lock); } void cfs_shared_map_invalidate_relation(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsMapSegmentRelKey relkey; if (cfs_map_seg_count == 0) return; /* * Walk the relation's segment list instead of the whole pool. Each * iteration detaches one node under the index lock (together with a * sample of the descriptor key and epoch), then evicts outside it. The * sampled epoch makes eviction a no-op if the id was recycled meanwhile; * the node is detached exactly once even with concurrent invalidations. */ cfs_map_segment_rel_key(&relkey, rlocator, forknum); for (;;) { CfsMapSegmentRelEnt *ent; CfsMapSegmentDesc *desc; uint32 hash; BlockNumber first_block; uint64 epoch; int id; LWLockAcquire(&cfs_map_rel_index_lock->lock, LW_EXCLUSIVE); ent = hash_search(cfs_map_rel_index, &relkey, HASH_FIND, NULL); if (ent == NULL || dlist_is_empty(&ent->head)) { LWLockRelease(&cfs_map_rel_index_lock->lock); break; } desc = dlist_container(CfsMapSegmentDesc, rel_node, dlist_head_node(&ent->head)); id = desc - cfs_map_seg_descs; LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED); hash = desc->hash; first_block = desc->first_block; epoch = desc->seg_epoch; cfs_map_segment_rel_unlink_locked(id); LWLockRelease(&cfs_map_seg_locks[id].lock); LWLockRelease(&cfs_map_rel_index_lock->lock); if (hash != 0) cfs_map_segment_evict_one(id, hash, first_block, epoch, false); } } void cfs_shared_map_invalidate_db(Oid dbid) { int id; if (cfs_map_seg_count == 0) return; for (id = 0; id < cfs_map_seg_count; id++) { CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id]; uint32 hash; BlockNumber first_block; uint64 epoch; LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED); hash = desc->hash; first_block = desc->first_block; epoch = desc->seg_epoch; if (hash == 0 || desc->rlocator.locator.dbOid != dbid) { LWLockRelease(&cfs_map_seg_locks[id].lock); continue; } LWLockRelease(&cfs_map_seg_locks[id].lock); cfs_map_segment_evict_one(id, hash, first_block, epoch, true); } } void cfs_shared_map_stats(uint64 *segments_in_use, uint64 *segment_loads, uint64 *segment_evictions, uint64 *pool_segments) { uint64 dummy; if (segments_in_use == NULL) segments_in_use = &dummy; if (segment_loads == NULL) segment_loads = &dummy; if (segment_evictions == NULL) segment_evictions = &dummy; if (pool_segments == NULL) pool_segments = &dummy; if (cfs_control == NULL) { *segments_in_use = *segment_loads = 0; *segment_evictions = *pool_segments = 0; return; } *segments_in_use = pg_atomic_read_u64(&cfs_control->map_segments_in_use); *segment_loads = pg_atomic_read_u64(&cfs_control->map_segment_loads); *segment_evictions = pg_atomic_read_u64(&cfs_control->map_segment_evictions); *pool_segments = (uint64) cfs_map_seg_count; } uint64 cfs_shared_map_fallback_reads(void) { if (cfs_control == NULL) return 0; return pg_atomic_read_u64(&cfs_control->map_fallback_reads); } uint64 cfs_shared_full_map_opens(void) { if (cfs_control == NULL) return 0; return pg_atomic_read_u64(&cfs_control->full_map_opens); } #ifdef USE_ASSERT_CHECKING /* * Test-only: publish the segment covering 'blocknum' straight from the * .cfsmap snapshot with journal_synced == false, i.e. exactly the state a * fresh publication has before the first replay. A lookup must treat that * segment as a miss until cfs_shared_map_sync_segment() catches it up with * the journal (C2). */ bool cfs_shared_map_test_publish_unsynced(CfsRelation *cfs, BlockNumber blocknum) { RelFileLocatorBackend rlocator = cfs->rlocator; ForkNumber forknum = cfs->forknum; CfsMapSegmentKey key; uint32 hash; CfsMapEntry *buf; Size seg_bytes = (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry); uint16 jrn_incarnation; int id; bool fresh = false; bool ok = false; if (cfs_map_seg_count == 0) return false; key.rlocator = rlocator; key.forknum = forknum; key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1); hash = cfs_map_segment_hash(rlocator, forknum, key.first_block); if (!cfs_map_segment_acquire(&key, hash, cfs->open_generation, &id, &fresh)) return false; buf = cfs_map_segment_scratch(); MemSet(buf, 0, seg_bytes); { char *corrupt_mask = palloc0(CFS_MAP_SEGMENT_BLOCKS); if (cfs_map_segment_load_buf(cfs, key.first_block, buf, seg_bytes, corrupt_mask) < 0) { pfree(corrupt_mask); if (fresh) cfs_map_segment_release_reservation(&key, hash, id); return false; } pfree(corrupt_mask); } /* * Sampled before the locks, like cfs_shared_map_ensure(): no journal * header I/O under the index/segment locks. */ jrn_incarnation = cfs_map_segment_journal_incarnation(cfs); if (fresh) cfs_map_segment_clear_reservation(&key, hash); LWLockAcquire(&cfs_map_rel_index_lock->lock, LW_EXCLUSIVE); LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); if (cfs_map_seg_descs[id].hash == 0 || cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator, forknum, key.first_block)) { bool newly_used = (cfs_map_seg_descs[id].hash == 0); cfs_map_segment_publish_locked(id, hash, rlocator, forknum, key.first_block, cfs->open_generation, buf, false, jrn_incarnation); if (newly_used) pg_atomic_fetch_add_u64(&cfs_control->map_segment_loads, 1); ok = true; } LWLockRelease(&cfs_map_seg_locks[id].lock); LWLockRelease(&cfs_map_rel_index_lock->lock); return ok; } /* * Test-only: leave an in-flight reservation for a free segment id, as a * backend that died between claiming the descriptor and publishing it * would. Unlike a real acquirer this one marks the descriptor reserved and * records a provably dead owner (pid 0, invalid ProcNumber, epoch 0), so a * competitor must reap it and reuse the same id. */ int cfs_shared_map_test_reserve_orphan(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum) { CfsMapSegmentKey key; CfsMapSegmentReservation *live; CfsMapSegmentHashEnt *ent; uint32 hash; int part; int id = -1; int i; bool found; if (cfs_map_seg_count == 0 || cfs_map_seg_live == NULL) return -1; for (i = 0; i < cfs_map_seg_count; i++) { bool free; LWLockAcquire(&cfs_map_seg_locks[i].lock, LW_SHARED); free = (cfs_map_seg_descs[i].hash == 0 && !cfs_map_seg_descs[i].reserved); LWLockRelease(&cfs_map_seg_locks[i].lock); if (free) { id = i; break; } } if (id < 0) return -1; key.rlocator = rlocator; key.forknum = forknum; key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1); hash = cfs_map_segment_hash(rlocator, forknum, key.first_block); part = hash & CFS_PART_MASK; LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); if (cfs_map_seg_descs[id].hash != 0 || cfs_map_seg_descs[id].reserved) { LWLockRelease(&cfs_map_seg_locks[id].lock); return -1; } cfs_map_seg_descs[id].rlocator = rlocator; cfs_map_seg_descs[id].forknum = forknum; cfs_map_seg_descs[id].first_block = key.first_block; cfs_map_seg_descs[id].seg_epoch++; cfs_map_seg_descs[id].reserved = true; LWLockRelease(&cfs_map_seg_locks[id].lock); LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); ent = (CfsMapSegmentHashEnt *) hash_search_with_hash_value(cfs_map_seg_hash, &key, hash, HASH_ENTER, &found); if (found) { LWLockRelease(&cfs_map_locks[part].lock); LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); cfs_map_seg_descs[id].reserved = false; LWLockRelease(&cfs_map_seg_locks[id].lock); return -1; } ent->segment_id = id; live = (CfsMapSegmentReservation *) hash_search_with_hash_value(cfs_map_seg_live, &key, hash, HASH_ENTER, NULL); live->segment_id = id; live->owner_pid = 0; live->owner_procno = INVALID_PROC_NUMBER; live->owner_epoch = 0; LWLockRelease(&cfs_map_locks[part].lock); return id; } /* Test-only: clock-sweep usage counter of a descriptor (0 if out of range). */ uint32 cfs_shared_map_test_desc_usage(int id) { if (id < 0 || id >= cfs_map_seg_count) return 0; return pg_atomic_read_u32(&cfs_map_seg_descs[id].usage_count); } /* Test-only: force a usage value, to exercise the decrement edge cases. */ void cfs_shared_map_test_set_desc_usage(int id, uint32 value) { if (id < 0 || id >= cfs_map_seg_count) return; pg_atomic_write_u32(&cfs_map_seg_descs[id].usage_count, value); } /* Test-only: run the production decrement helper on one descriptor. */ void cfs_shared_map_test_dec_desc_usage(int id) { if (id < 0 || id >= cfs_map_seg_count) return; (void) cfs_map_segment_dec_usage(&cfs_map_seg_descs[id]); } /* Test-only: current segment id of a key (or -1 when not mapped). */ int cfs_shared_map_test_segment_id(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum) { CfsMapSegmentKey key; uint32 hash; if (cfs_map_seg_count == 0) return -1; key.rlocator = rlocator; key.forknum = forknum; key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1); hash = cfs_map_segment_hash(rlocator, forknum, key.first_block); return cfs_map_segment_find(&key, hash, LW_SHARED); } /* * Test-only switch for the I4 race: cfs_shared_map_ensure() consumes it * between the snapshot load and the segment phase and merges the snapshot * the way a competing backend already would have. */ bool cfs_shared_map_test_merge_race(CfsRelation *cfs, BlockNumber blocknum) { (void) blocknum; if (cfs_map_seg_count == 0) return false; cfs_test_merge_race_pending = true; return true; } #endif /* USE_ASSERT_CHECKING */ /* ================================================================ * Append serialization * ================================================================ */ /* * Locate the metadata slot for a relation without holding any lock; returns * a stable pointer because the slot array is a fixed shared-memory * allocation. The caller must have pinned the slot (so it cannot be * evicted) before relying on the returned pointer for lock operations. */ static CfsRelMetaSlot * cfs_append_lock_find_slot(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED); m = cfs_meta_find(rel_hash, rlocator, forknum); LWLockRelease(&cfs_map_locks[part].lock); return m; } void cfs_append_lock_acquire(RelFileLocatorBackend rlocator, ForkNumber forknum, LWLockMode mode) { CfsRelMetaSlot *m; m = cfs_append_lock_find_slot(rlocator, forknum); if (m == NULL) ereport(ERROR, (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED), errmsg("CFS: could not acquire append lock for relation %u/%u/%u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber), errdetail("The relation has no metadata slot in shared memory."), errhint("Increase the configuration parameter " "\"cfs_map_cache_rels_per_partition\" and restart " "the server."))); LWLockAcquire(&m->append_lock, mode); } /* * The non-blocking form for callers that must not wait out a long holder: * the checkpoint's handle open races an in-flight compaction (which holds * this lock across its whole copy + swap window), so it skips the * relation for one round instead of stalling behind it. Returns false * without blocking when the lock is taken; the caller must hold a pin so * the slot outlives the call. */ bool cfs_append_lock_try_acquire(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m; m = cfs_append_lock_find_slot(rlocator, forknum); if (m == NULL) ereport(ERROR, (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED), errmsg("CFS: could not acquire append lock for relation %u/%u/%u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber), errdetail("The relation has no metadata slot in shared memory."), errhint("Increase the configuration parameter " "\"cfs_map_cache_rels_per_partition\" and restart " "the server."))); return LWLockConditionalAcquire(&m->append_lock, LW_EXCLUSIVE); } void cfs_shared_note_full_map_open(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m; if (cfs_control == NULL) return; pg_atomic_add_fetch_u64(&cfs_control->full_map_opens, 1); /* * The per-relation half (a slot may legitimately not exist yet for a * relation whose full handle is being opened for the very first time - * the global counter above already accounts for it). */ m = cfs_append_lock_find_slot(rlocator, forknum); if (m != NULL) pg_atomic_add_fetch_u64(&m->full_map_opens, 1); } uint64 cfs_shared_full_map_opens_rel(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m; if (cfs_control == NULL) return 0; m = cfs_append_lock_find_slot(rlocator, forknum); if (m == NULL) return 0; return pg_atomic_read_u64(&m->full_map_opens); } void cfs_append_lock_release(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m; m = cfs_append_lock_find_slot(rlocator, forknum); /* * The slot must exist: the caller holds a pin (acquired when the * SMgrRelation handle was opened, or explicitly for compaction), so the * slot cannot have been evicted between acquire and release. A missing * slot here is a logic bug, not a capacity issue — fail loudly instead * of silently leaving the append lock held. */ Assert(m != NULL); /* The normal path consumes the holdoff credit from LWLockAcquire. */ if (LWLockHeldByMe(&m->append_lock)) LWLockRelease(&m->append_lock); } /* * Local ERROR unwinding happens before transaction abort. errfinish has * reset InterruptHoldoffCount, even if this lock is still held. As in * LWLockReleaseAll, preserve the current holdoff count while releasing the * owned lock. Call only on error paths that propagate the exception. */ void cfs_append_lock_release_after_error(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum); Assert(m != NULL); if (m != NULL && LWLockHeldByMe(&m->append_lock)) { HOLD_INTERRUPTS(); LWLockRelease(&m->append_lock); } } /* ================================================================ * Authoritative .cfp tail (shared append cursor) * ================================================================ */ /* * Fetch the slot's authoritative .cfp tail. Every non-IDLE state answers * false, so a crashed appender (IN_PROGRESS left behind), a failed pwrite * and a freshly created slot all send the caller down the * cfs_cfp_discover_eof() walk instead of a possibly-wrong offset. */ bool cfs_cfp_tail_fetch(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 *out_tail) { CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum); if (m == NULL || m->cfp_append_state != CFS_CFP_APPEND_IDLE) return false; *out_tail = m->cfp_tail; return true; } /* * Mark the append in progress under the append lock. The owner is * recorded for diagnostics only: a recycled ProcNumber never validates a * stale IN_PROGRESS, the state itself is what the next writer checks. */ void cfs_cfp_tail_begin(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum); if (m == NULL) return; m->cfp_append_state = CFS_CFP_APPEND_IN_PROGRESS; m->cfp_append_proc = MyProcNumber; } /* * Publish the authoritative tail after a successful pwrite. Must be * called under the append lock; the value is the aligned offset just past * the record the caller wrote. */ void cfs_cfp_tail_commit(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 new_tail) { CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum); if (m == NULL) return; m->cfp_tail = new_tail; m->cfp_append_state = CFS_CFP_APPEND_IDLE; m->cfp_append_proc = INVALID_PROC_NUMBER; } /* * Drop trust in the stored tail. Used after a failed pwrite (the file end * is then whatever the failed write left behind) and whenever the sidecar * pair was replaced out from under the slot (compaction swap). */ void cfs_cfp_tail_dirty(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum); if (m == NULL) return; m->cfp_append_state = CFS_CFP_APPEND_DIRTY; m->cfp_append_proc = INVALID_PROC_NUMBER; } /* * Online-compaction ownership mark (QDB-1514). The pair (ProcNumber, pid) * is the liveness identity: a recycled ProcNumber points at some other * backend's PGPROC whose pid differs, and a dead backend's slot either is * free (pid 0) or belongs to a successor. Both read as "not active", which * is exactly how a compaction whose backend died mid-copy must look to the * interrupted-swap recovery below the storage layer. */ void cfs_compact_mark_active(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum); if (m == NULL) return; m->compact_proc = MyProcNumber; m->compact_pid = MyProcPid; } /* * Clear the mark. Called on every completion path of the compaction that * set it; a leftover mark from a dead backend needs no cleanup (see above), * so a missed clear is safe, merely delaying orphan cleanup until the next * open after the backend exits. */ void cfs_compact_mark_inactive(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum); if (m == NULL) return; m->compact_proc = INVALID_PROC_NUMBER; m->compact_pid = 0; } /* * The compaction provider of the ownership-state judge: is an online * compaction with a live owner running for this relation fork? Reads the * mark without taking the append lock: the answer only gates the * interrupted-swap recovery, where a momentary stale "active" is harmless * (the real owner is still holding or about to take the append lock for the * swap) and a stale "inactive" is impossible while the owner lives. */ bool cfs_map_cache_compaction_active(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum); PGPROC *owner; if (m == NULL || m->compact_proc == INVALID_PROC_NUMBER) return false; owner = GetPGProcByNumber(m->compact_proc); return owner->pid != 0 && owner->pid == m->compact_pid; } /* * Sidecar-open guard (QDB-1514), the shmem side of the state judge's hook: * a shared hold of the relation's append lock around lock-free sidecar * opens. Skipped when this backend already holds the lock (any mode) — * checkpoint, fsck and the compactor itself serialize through their own * holds, and an LWLock must never be re-acquired by its holder. * * The slot is PINNED for the duration of the hold: the append lock lives * inside the slot, and the pin-before-lock contract of * cfs_append_lock_find_slot() is what keeps an evictable (refcount 0) slot * from being wiped — and its lock re-initialized — while we hold it. The * caller of cfs_open_paths() pins the slot again after the open; the pair * of refcounts here is balanced by cfs_open_guard_release_impl(). */ static bool cfs_open_guard_acquire_impl(RelFileLocatorBackend rlocator, ForkNumber forknum) { CfsRelMetaSlot *m; /* * May raise ERROR when the slot pool is exhausted — nothing is held * yet, and the smgr-level pin after the open would fail the same way * a moment later. */ cfs_map_cache_pin(rlocator, forknum); m = cfs_append_lock_find_slot(rlocator, forknum); if (m == NULL) { cfs_map_cache_unpin(rlocator, forknum); return false; } if (LWLockHeldByMe(&m->append_lock)) { cfs_map_cache_unpin(rlocator, forknum); return false; } LWLockAcquire(&m->append_lock, LW_SHARED); return true; } static void cfs_open_guard_release_impl(RelFileLocatorBackend rlocator, ForkNumber forknum, bool after_error) { if (after_error) cfs_append_lock_release_after_error(rlocator, forknum); else cfs_append_lock_release(rlocator, forknum); /* The pin must outlive the lock, including on ERROR. */ cfs_map_cache_unpin(rlocator, forknum); } /* ================================================================ * Background worker control * ================================================================ */ void cfs_bg_pause(int64 paused_until) { Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL); LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE); cfs_bg_control->paused = true; cfs_bg_control->paused_until = paused_until; LWLockRelease(&cfs_bg_lock->lock); ereport(DEBUG1, (errmsg("CFS bgworker paused%s", paused_until != 0 ? " until expiry" : " indefinitely"))); } void cfs_bg_resume(void) { Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL); LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE); cfs_bg_control->paused = false; cfs_bg_control->paused_until = 0; LWLockRelease(&cfs_bg_lock->lock); ereport(DEBUG1, (errmsg("CFS bgworker resumed"))); } /* * cfs_bg_expire_if_due — clear a timed pause whose deadline has passed. * * Writes the cleared pause state, so the caller must hold the bgworker lock * in LW_EXCLUSIVE mode. */ static void cfs_bg_expire_if_due(void) { if (cfs_bg_control->paused && cfs_bg_control->paused_until != 0 && (int64) GetCurrentTimestamp() >= cfs_bg_control->paused_until) { cfs_bg_control->paused = false; cfs_bg_control->paused_until = 0; } } bool cfs_bg_is_paused(void) { bool result; Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL); LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE); cfs_bg_expire_if_due(); result = cfs_bg_control->paused; LWLockRelease(&cfs_bg_lock->lock); return result; } void cfs_bg_set_cycle_started(void) { Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL); LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE); cfs_bg_control->last_cycle_started_at = (int64) GetCurrentTimestamp(); LWLockRelease(&cfs_bg_lock->lock); } void cfs_bg_set_cycle_finished(void) { Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL); LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE); cfs_bg_control->last_cycle_finished_at = (int64) GetCurrentTimestamp(); LWLockRelease(&cfs_bg_lock->lock); } void cfs_bg_history_set(Oid relid, TimestampTz ts) { CfsBgHistoryKey key; CfsBgHistoryEntry *h; bool found; Assert(cfs_bg_history_hash != NULL && cfs_bg_lock != NULL); /* * The entries are keyed by (database, relation): relids are unique only * within a database. Both callers (the per-database worker and manual * pg_cfs_compact) always run with MyDatabaseId set. */ key.dboid = MyDatabaseId; key.relid = relid; LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE); h = hash_search(cfs_bg_history_hash, &key, HASH_ENTER_NULL, &found); if (h == NULL) { /* * ponytail: more relations compacted within cfs_bg_min_interval_s * than CFS_BG_HISTORY_MAX. Skipping the record costs this one * relation its throttle until the sweep frees space -- extra * background work, not a correctness problem. Ceiling and upgrade * path: a GUC-sized hash. */ if (!cfs_bg_history_overflow_logged) { cfs_bg_history_overflow_logged = true; ereport(LOG, (errmsg("CFS: compaction history is full (%d entries); the minimum interval cannot be enforced for further relations until older entries expire", CFS_BG_HISTORY_MAX))); } } else h->last_compact = (int64) ts; LWLockRelease(&cfs_bg_lock->lock); } TimestampTz cfs_bg_history_get(Oid relid) { CfsBgHistoryKey key; CfsBgHistoryEntry *h; TimestampTz result = 0; Assert(cfs_bg_history_hash != NULL && cfs_bg_lock != NULL); key.dboid = MyDatabaseId; key.relid = relid; LWLockAcquire(&cfs_bg_lock->lock, LW_SHARED); h = hash_search(cfs_bg_history_hash, &key, HASH_FIND, NULL); if (h != NULL) result = (TimestampTz) h->last_compact; LWLockRelease(&cfs_bg_lock->lock); return result; } void cfs_bg_history_sweep(void) { HASH_SEQ_STATUS status; CfsBgHistoryEntry *h; int64 horizon; if (cfs_bg_history_hash == NULL) return; /* * An entry older than the throttle window cannot matter: the interval it * exists to enforce has expired. Retiring expired entries also retires * the entries of dropped relations without any catalog cross-check * (pgstat needs one for its persistent statistics; the history is * volatile, so ageing out is enough). Increasing cfs_bg_min_interval_s * after a sweep may find earlier entries gone: one relation then risks a * single premature compaction, which is safe. */ horizon = (int64) GetCurrentTimestamp() - (int64) cfs_bg_min_interval_s * USECS_PER_SEC; LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE); /* * The scan always runs to completion (hash_seq_search returns NULL), so * no hash_seq_term() is needed: per dynahash, terminating is only for * scans abandoned before completion, and removing entries along the way * is explicitly supported. */ hash_seq_init(&status, cfs_bg_history_hash); while ((h = hash_seq_search(&status)) != NULL) { if (h->last_compact < horizon) hash_search(cfs_bg_history_hash, &h->key, HASH_REMOVE, NULL); } LWLockRelease(&cfs_bg_lock->lock); /* Room may have been freed: re-arm the overflow notice. */ cfs_bg_history_overflow_logged = false; } void cfs_bg_get_status(CfsBgStatus *out) { Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL && out != NULL); LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE); cfs_bg_expire_if_due(); out->paused = cfs_bg_control->paused; out->paused_until = cfs_bg_control->paused_until; out->last_cycle_started_at = cfs_bg_control->last_cycle_started_at; out->last_cycle_finished_at = cfs_bg_control->last_cycle_finished_at; LWLockRelease(&cfs_bg_lock->lock); } /* ================================================================ * Relation metadata (helpers for the map cache) * ================================================================ */ /* * Per-partition hash chains over the metadata slots (QDB-1516 Д2). The * invariants I1-I3 are stated in cfs_shmem_internal.h; all helpers below * mutate chains only under LW_EXCLUSIVE of the partition. */ /* * Bucket of a key inside its partition: the hash bits that do not select * the partition, run through a multiplicative mix (Knuth's 2654435761). * The partition is selected by the low CFS_PART_BITS bits; the multiply * folds those (and every other input bit) back into the bits the modulo * keeps, so the choice of partition and the choice of chain do not * correlate even though the underlying hash is a simple polynomial. */ static inline int cfs_meta_bucket(uint32 rel_hash) { uint32 b = rel_hash * 2654435761U; return (int) ((b >> CFS_PART_BITS) % (uint32) cfs_map_cache_rels_per_partition); } /* The bucket-head cell (part, bucket) of the metadata chains. */ static inline int32 * cfs_meta_head(int part, int bucket) { return &cfs_map_bucket_heads[part * cfs_map_cache_rels_per_partition + bucket]; } /* Partition-relative index of a metadata slot. */ static inline int cfs_meta_slot_index(int part, const CfsRelMetaSlot *slot) { return (int) (slot - &cfs_rel_meta[part * cfs_map_cache_rels_per_partition]); } /* * Link an occupied slot at the head of its bucket chain. The caller holds * the partition lock exclusively; the slot is populated (hash set) and not * in any chain yet. */ static void cfs_meta_chain_link(int part, CfsRelMetaSlot *slot) { int bucket = cfs_meta_bucket(slot->hash); int32 *head = cfs_meta_head(part, bucket); slot->chain_next = *head; *head = cfs_meta_slot_index(part, slot); } /* * Unlink an occupied slot from its chain. The caller holds the partition * lock exclusively. Must run BEFORE the slot is cleared (invariant I3): * it walks the slot's own chain to find the predecessor. */ static void cfs_meta_chain_unlink(int part, CfsRelMetaSlot *slot) { int idx = cfs_meta_slot_index(part, slot); int bucket = cfs_meta_bucket(slot->hash); int32 *head = cfs_meta_head(part, bucket); int cur = *head; int prev = -1; Assert(slot->hash != 0); Assert(cur != -1); /* an occupied slot is always chained (I1) */ while (cur != idx) { /* A broken I1 must error out, not read slot(part, -1). */ if (cur == -1) elog(ERROR, "CFS: relation metadata slot %d not found in its " "hash chain", idx); prev = cur; cur = cfs_rel_meta_slot(part, cur)->chain_next; } if (prev == -1) *head = slot->chain_next; else cfs_rel_meta_slot(part, prev)->chain_next = slot->chain_next; } /* * Rebuild one partition's bucket heads from its occupied slots. The * caller holds the partition lock exclusively. Used after bulk clears * (DROP DATABASE) that clear slots without unlinking them one by one; * surviving occupied slots are re-linked at their buckets' heads, and the * cleared slots stay free (I1). */ static void cfs_meta_heads_rebuild(int part) { int nslots = cfs_map_cache_rels_per_partition; int i; MemSet(cfs_meta_head(part, 0), 0xFF, mul_size(sizeof(int32), nslots)); for (i = 0; i < nslots; i++) { CfsRelMetaSlot *m = cfs_rel_meta_slot(part, i); if (m->hash != 0) { int bucket = cfs_meta_bucket(m->hash); int32 *head = cfs_meta_head(part, bucket); m->chain_next = *head; *head = i; } } } /* * Locate the metadata slot for a relation by walking its hash chain. The * caller must hold the lock of the partition selected by rel_hash (in * LW_SHARED or LW_EXCLUSIVE mode); touching the slot without that lock is * a data race. Returns NULL when none exists. */ static CfsRelMetaSlot * cfs_meta_find(uint32 rel_hash, RelFileLocatorBackend rlocator, ForkNumber forknum) { int part = rel_hash & CFS_PART_MASK; int bucket = cfs_meta_bucket(rel_hash); int cur; Assert(LWLockHeldByMe(&cfs_map_locks[part].lock)); for (cur = *cfs_meta_head(part, bucket); cur != -1;) { CfsRelMetaSlot *m = cfs_rel_meta_slot(part, cur); int next = m->chain_next; if (m->hash == rel_hash && cfs_rlbe_eq(m->rlocator, rlocator) && m->forknum == forknum) return m; cur = next; } return NULL; } /* * Find or create a metadata slot. The caller must hold the lock of the * partition selected by rel_hash in LW_EXCLUSIVE mode. * * Creation order (QDB-1516 Д2): the key's own chain is searched first; * on a miss the first free slot (hash == 0) of the partition is taken by * a plain scan — a per-partition LIFO free list was judged not worth the * extra shared state at <= CFS_MAP_CACHE_MAX_RELS_PER_PART slots — and * only when no free slot remains is an LRU victim chosen by a full * partition scan and unlinked from ITS chain before being cleared (I3). * A newly claimed slot is linked at the head of its bucket. * * Returns NULL when every slot of the partition is pinned or dirty for * checkpoint. The caller MUST check for NULL and raise ERROR (via * cfs_meta_overflow_error) AFTER releasing the partition lock — raising * ERROR from here would longjmp past the caller's LWLockRelease and leak * the partition lock. */ static CfsRelMetaSlot * cfs_meta_get_or_create(uint32 rel_hash, RelFileLocatorBackend rlocator, ForkNumber forknum) { int part = rel_hash & CFS_PART_MASK; int bucket = cfs_meta_bucket(rel_hash); CfsRelMetaSlot *free_slot = NULL; CfsRelMetaSlot *victim = NULL; uint64 min_clock = PG_UINT64_MAX; int i; int cur; Assert(LWLockHeldByMeInMode(&cfs_map_locks[part].lock, LW_EXCLUSIVE)); /* Search the key's own chain (the hit path of the partition). */ for (cur = *cfs_meta_head(part, bucket); cur != -1;) { CfsRelMetaSlot *m = cfs_rel_meta_slot(part, cur); int next = m->chain_next; if (m->hash == rel_hash && cfs_rlbe_eq(m->rlocator, rlocator) && m->forknum == forknum) return m; cur = next; } /* Miss: take the first free slot of the partition. */ for (i = 0; i < cfs_map_cache_rels_per_partition; i++) { CfsRelMetaSlot *m = cfs_rel_meta_slot(part, i); if (m->hash == 0) { free_slot = m; break; } } /* * No free slot: LRU victim among all occupied slots (a full partition * scan, as before the chains). Never evict a dirty-checkpoint slot - * a relation that was written since the last checkpoint must survive * until the checkpointer has fsync'd its sidecars - and never a pinned * one. The victim is unlinked from its own chain BEFORE the clear * (invariant I3). */ if (free_slot == NULL) { for (i = 0; i < cfs_map_cache_rels_per_partition; i++) { CfsRelMetaSlot *m = cfs_rel_meta_slot(part, i); if (m->hash != 0 && m->refcount == 0 && !m->dirty_checkpoint && m->access_clock < min_clock) { min_clock = m->access_clock; victim = m; } } free_slot = victim; if (free_slot != NULL) { pg_atomic_fetch_add_u64(&cfs_control->evictions, 1); cfs_meta_chain_unlink(part, free_slot); MemSet(free_slot, 0, sizeof(CfsRelMetaSlot)); } } if (free_slot == NULL) return NULL; /* partition full of pinned/dirty relations */ free_slot->hash = rel_hash; free_slot->rlocator = rlocator; free_slot->forknum = forknum; free_slot->generation = 0; free_slot->refcount = 0; free_slot->access_clock = cfs_map_clock_tick(part); /* * A freshly claimed slot knows nothing about the .cfp chain end: start * untrusted so the first writer re-discovers it (the D1 tail protocol; * cfp_tail stays zero and is never read while the state is DIRTY). */ free_slot->cfp_tail = 0; free_slot->cfp_append_state = CFS_CFP_APPEND_DIRTY; free_slot->cfp_append_proc = INVALID_PROC_NUMBER; free_slot->compact_proc = INVALID_PROC_NUMBER; free_slot->compact_pid = 0; pg_atomic_init_u32(&free_slot->next_generation, 0); pg_atomic_init_u64(&free_slot->full_map_opens, 0); free_slot->generation_initialized = false; /* * Initialise the embedded per-relation append lock. The slot was just * claimed (fresh or evicted-and-zeroed), so the lock state is undefined; * LWLockInitialize() resets it to the unlocked state with the correct * tranche id for wait-event display. */ LWLockInitialize(&free_slot->append_lock, cfs_control->append_tranche_id); /* Insert the claimed slot at the head of its bucket chain (I2). */ cfs_meta_chain_link(part, free_slot); return free_slot; } /* * Raise the slot-exhaustion ERROR. Must be called AFTER releasing the * partition lock so the longjmp does not leak it. */ static void cfs_meta_overflow_error(RelFileLocatorBackend rlocator, int part) { ereport(ERROR, (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED), errmsg("CFS: out of relation metadata slots for relation %u/%u/%u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber), errdetail("All %d slots in cache partition %d are pinned or dirty " "for checkpoint.", cfs_map_cache_rels_per_partition, part), errhint("Increase the configuration parameter " "\"cfs_map_cache_rels_per_partition\" and restart the server."))); } /* * Warn about slot exhaustion on a post-commit path, where raising ERROR is * no longer safe: the commit is already durable and cannot be rolled back * (a vanilla post-commit step degrades instead of failing). The policy * stays in the catalog; the next open of the relation republishes it * through cfs_open_relation_smgr(). */ static void cfs_meta_overflow_warning(RelFileLocatorBackend rlocator, int part) { ereport(WARNING, (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED), errmsg("CFS: could not publish the policy for relation %u/%u/%u after commit", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber), errdetail("All %d slots in cache partition %d are pinned or dirty " "for checkpoint.", cfs_map_cache_rels_per_partition, part), errhint("The policy will be republished the next time the relation is " "opened. To avoid this, increase the configuration parameter " "\"cfs_map_cache_rels_per_partition\" and restart the server."))); } /* ================================================================ * Relation metadata cache * ================================================================ */ void cfs_map_cache_invalidate(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); Assert(cfs_control != NULL); /* * Drop the metadata slot under its own partition lock. Block entries * live in the shared segment pool and are dropped by the caller through * cfs_shared_map_invalidate_relation(). */ { int mpart = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; LWLockAcquire(&cfs_map_locks[mpart].lock, LW_EXCLUSIVE); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL) { /* Unlink from the chain before the clear (invariant I3). */ cfs_meta_chain_unlink(mpart, m); MemSet(m, 0, sizeof(CfsRelMetaSlot)); } LWLockRelease(&cfs_map_locks[mpart].lock); } /* * Statistics are deliberately NOT reset here: wiping the counters would * destroy the pg_stat_cfs signal (including crc_failures) without the * user asking for it. Counters survive until an explicit * pg_cfs_reset_stats() (or slot eviction); a stale row for a dropped * relation is reclaimed by the statistics LRU. */ ereport(DEBUG1, (errmsg("CFS: invalidated cache entries for relation %u/%u/%u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); } /* * cfs_drop_database_caches — drop every shared-memory cache entry that * belongs to a database being dropped: cached page-map entries, per-relation * metadata and published policies. Called from DROP DATABASE (and its WAL * redo) alongside DropDatabaseBuffers()/ForgetDatabaseSyncRequests(): the * database directory is removed wholesale, without per-relation smgr unlink * processing, so without this sweep the entries would survive and confuse a * relation that later reuses the same (tablespace, database, relfilenumber) * key — a stale block mapping would then read a foreign .cfp offset. * * Statistics slots are deliberately kept (see cfs_map_cache_invalidate). */ void cfs_drop_database_caches(Oid dbid) { int part; int i; Assert(cfs_control != NULL); /* * Relation-metadata slots are spread across every partition, so sweep * them all under each partition lock. This is O(NUM_PARTITIONS * * RELS_PER_PART) but runs only on DROP DATABASE. Block entries live in * the shared segment pool and are dropped through * cfs_shared_map_invalidate_relation() per relation. */ for (part = 0; part < CFS_MAP_CACHE_NUM_PARTITIONS; part++) { LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); for (i = 0; i < cfs_map_cache_rels_per_partition; i++) { CfsRelMetaSlot *m = cfs_rel_meta_slot(part, i); if (m->hash != 0 && m->rlocator.locator.dbOid == dbid) MemSet(m, 0, sizeof(CfsRelMetaSlot)); } /* * The clears above broke the chains: rebuild the partition's * bucket heads wholesale (simpler than unlinking every dropped * slot, and DROP DATABASE is rare). Surviving occupied slots are * re-linked; the cleared slots stay free (I1). */ cfs_meta_heads_rebuild(part); LWLockRelease(&cfs_map_locks[part].lock); } /* * Drop only this database's segments. Segment keys carry dbOid, so a * relation of another database can never share them; resetting the whole * pool would throw away every other database's warm segments (and, in WAL * redo, make the startup process sweep a large pool). */ cfs_shared_map_invalidate_db(dbid); ereport(DEBUG1, (errmsg("CFS: invalidated cache entries for dropped database %u", dbid))); } void cfs_map_cache_compact_reset(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); Assert(cfs_control != NULL); /* * Compaction rewrote the .cfp (every physical offset changed) and the * caller drops the relation's pool segments separately. What remains * here is the metadata slot: bump the generation (so any in-flight * readers notice the offset change) and, crucially, mark dirty_checkpoint * so the next CfsCheckpoint() still finds this relation (the policy * fields are preserved) and snapshots the freshly compacted map. Unlike * cfs_map_cache_invalidate(), the slot is kept alive. */ { int mpart = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; LWLockAcquire(&cfs_map_locks[mpart].lock, LW_EXCLUSIVE); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL) { m->generation++; m->access_clock = cfs_map_clock_tick(mpart); m->dirty_checkpoint = true; /* * The compaction replaced the whole .cfp chain: the stored tail * describes the replaced inode pair and must not be trusted. */ m->cfp_append_state = CFS_CFP_APPEND_DIRTY; m->cfp_append_proc = INVALID_PROC_NUMBER; } LWLockRelease(&cfs_map_locks[mpart].lock); } ereport(DEBUG1, (errmsg("CFS: reset cache after compaction for relation %u/%u/%u", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber))); } uint64 cfs_map_cache_get_generation(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; uint64 generation = 0; Assert(cfs_control != NULL); LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL) generation = m->generation; LWLockRelease(&cfs_map_locks[part].lock); return generation; } uint32 cfs_map_cache_next_generation(CfsRelation *cfs) { CfsRelMetaSlot *m; m = cfs_append_lock_find_slot(cfs->rlocator, cfs->forknum); Assert(m != NULL); Assert(LWLockHeldByMe(&m->append_lock)); if (!m->generation_initialized) { uint32 max_gen; /* * cfs_generation_summary() seeds from the in-memory map, the journal * header watermark (stamped by every journal reset, so it survives * map truncation) and every UPDATE the journal still holds beyond its * last reset (the header may predate the journal tail). Durability of * the referenced .cfp bytes is not checked here: a generation is * occupied once its journal record exists, even when replay would * later skip the record. * * The scan reads the whole journal of the relation under the * exclusive append lock. It is a one-time cost per metadata slot: * m->generation_initialized stays set until the slot is evicted * (which needs the relation to be closed), so steady-state writes * only consume the atomic counter. */ if (cfs_generation_summary(cfs, &max_gen) != CFS_STORAGE_OK) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not scan journal for relation %u/%u/%u", cfs->rlocator.locator.spcOid, cfs->rlocator.locator.dbOid, cfs->rlocator.locator.relNumber))); pg_atomic_write_u32(&m->next_generation, max_gen); m->generation_initialized = true; } return pg_atomic_add_fetch_u32(&m->next_generation, 1); } void cfs_handle_refresh_if_stale(CfsRelation *cfs) { uint64 generation; Assert(cfs != NULL); generation = cfs_map_cache_get_generation(cfs->rlocator, cfs->forknum); if (generation == cfs->open_generation) return; /* * The generation moved: a compaction swapped the sidecar files while we * were waiting for the append lock. The old descriptors point at the * replaced inode, so writing through them would be lost silently. Reopen * and continue on the new pair. cfs_reopen() retags the handle with the * current generation; the generation cannot move again while we hold the * append lock. */ ereport(DEBUG1, (errmsg("CFS: refreshing stale handle for relation %u/%u/%u " "(generation %llu -> %llu)", cfs->rlocator.locator.spcOid, cfs->rlocator.locator.dbOid, cfs->rlocator.locator.relNumber, (unsigned long long) cfs->open_generation, (unsigned long long) generation))); cfs_reopen(cfs); } void cfs_map_cache_truncate(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber nblocks) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); Assert(cfs_control != NULL); /* * Shrink the cached logical size under the metadata slot's own partition * lock (selected by rel_hash; the sweep above only holds the block-entry * partition locks). Done exactly once, not per sweep iteration. */ { int mpart = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; LWLockAcquire(&cfs_map_locks[mpart].lock, LW_EXCLUSIVE); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL) { m->generation++; m->nblocks = Min(m->nblocks, (uint64) nblocks); m->access_clock = cfs_map_clock_tick(mpart); } LWLockRelease(&cfs_map_locks[mpart].lock); } } /* ================================================================ * Map cache: pinning * ================================================================ */ void cfs_map_cache_pin(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; bool reaped = false; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); m = cfs_meta_get_or_create(rel_hash, rlocator, forknum); if (m == NULL) { /* * Every slot of the partition is pinned or dirty. Pins of processes * that died hard never unpinned themselves - reap them once before * giving up (cfs_map_slot_reap_dead_pins takes ALL partition locks * itself, so drop ours first). The overflow ERROR must be raised * with no partition lock held: ereport(ERROR) would longjmp past * LWLockRelease and leak the lock. */ LWLockRelease(&cfs_map_locks[part].lock); if (!reaped && cfs_map_slot_reap_dead_pins(false)) { reaped = true; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); m = cfs_meta_get_or_create(rel_hash, rlocator, forknum); if (m == NULL) LWLockRelease(&cfs_map_locks[part].lock); } if (m == NULL) cfs_meta_overflow_error(rlocator, part); } cfs_map_pin_track(rlocator, forknum, rel_hash); m->refcount++; m->access_clock = cfs_map_clock_tick(part); LWLockRelease(&cfs_map_locks[part].lock); } /* * Record this process's pin of the relation's slot in the pin-owner * registry (or bump the count of an existing record). The caller holds * the partition lock selected by part. */ static void cfs_map_pin_track(RelFileLocatorBackend rlocator, ForkNumber forknum, uint32 rel_hash) { CfsMapPinKey key; CfsMapPinOwner *owner; uint32 pin_hash; bool found; if (cfs_map_pin_live == NULL) return; pin_hash = cfs_map_pin_key_hash(rlocator, forknum, MyProcNumber, &key, rel_hash); owner = (CfsMapPinOwner *) hash_search_with_hash_value(cfs_map_pin_live, &key, pin_hash, HASH_ENTER_NULL, &found); if (owner == NULL) { /* * ponytail: the registry holds cfs_map_pin_registry_size() owners; a * backend pinning more relations than that loses the death protection * for the excess pins - the pins themselves keep working, only the * reaper cannot return them later. Ceiling and upgrade path: size * the hash from a GUC. */ if (!cfs_pin_registry_overflow_logged) { cfs_pin_registry_overflow_logged = true; ereport(LOG, (errmsg("CFS: pin-owner registry is full (%d entries); pins left by processes that die hard cannot be reclaimed", cfs_map_pin_registry_size()))); } return; } if (!found || owner->owner_pid != MyProcPid || owner->owner_epoch != cfs_map_owner_epoch_get()) { /* * A fresh record, one recycled from the dynahash freelist, or one * adopted from a dead predecessor on this ProcNumber: dynahash copies * only the key into a (re)used element, and a recycled ProcNumber * reuses the key as well, so the payload - and with a dead * predecessor its slot pins - must be returned here, not inferred * from a zero pin_count. */ if (found && owner->pin_count > 0) { CfsRelMetaSlot *m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL) m->refcount = (m->refcount > (uint32) owner->pin_count) ? m->refcount - owner->pin_count : 0; } owner->owner_pid = MyProcPid; owner->owner_epoch = cfs_map_owner_epoch_get(); owner->pin_count = 0; } owner->pin_count++; } /* * Drop one pin of this process from the registry. The caller holds the * partition lock selected by rel_hash. */ static void cfs_map_pin_untrack(RelFileLocatorBackend rlocator, ForkNumber forknum, uint32 rel_hash) { CfsMapPinKey key; CfsMapPinOwner *owner; uint32 pin_hash; if (cfs_map_pin_live == NULL) return; pin_hash = cfs_map_pin_key_hash(rlocator, forknum, MyProcNumber, &key, rel_hash); owner = (CfsMapPinOwner *) hash_search_with_hash_value(cfs_map_pin_live, &key, pin_hash, HASH_FIND, NULL); if (owner != NULL && owner->pin_count > 0 && --owner->pin_count == 0) hash_search_with_hash_value(cfs_map_pin_live, &key, pin_hash, HASH_REMOVE, NULL); } /* * Reap pins whose owner died hard: walk the pin-owner registry, and for * every record whose (procno, pid, epoch) no longer names a live process, * return its pins to the slot and drop the record. Returns true when * anything was reaped. */ static bool cfs_map_slot_reap_dead_pins(bool force) { HASH_SEQ_STATUS status; CfsMapPinOwner *owner; bool reaped = false; int i; if (cfs_map_pin_live == NULL) return false; /* * Throttle repeated empty sweeps: a partition saturated with live pins * would otherwise repeat this stop-the-world scan (all partition locks * exclusively) on every failed pin attempt. The timestamp is set only by * a sweep that reaped nothing and cleared by one that reaped, so a rescue * is delayed by at most the retry interval, never lost. */ if (!force && pg_atomic_read_u64(&cfs_control->map_pin_reap_empty_at) != 0 && (uint64) GetCurrentTimestamp() - pg_atomic_read_u64(&cfs_control->map_pin_reap_empty_at) < CFS_PIN_REAP_EMPTY_RETRY_USECS) return false; /* * The pg_locks pattern (GetLockStatusData in lock.c): hold every * partition lock of the table for the whole scan. dynahash requires at * least a shared lock on all partitions throughout hash_seq_search and * tolerates no concurrent insertions or deletions by other backends; our * removals make them exclusive. With all locks held no track or untrack * can run, two reapers serialise on partition 0 instead of racing for one * record, and deleting the returned element is the one deletion dynahash * explicitly allows during a scan. The scan always runs to completion, * so no hash_seq_term() is needed. */ for (i = 0; i < CFS_MAP_CACHE_NUM_PARTITIONS; i++) LWLockAcquire(&cfs_map_locks[i].lock, LW_EXCLUSIVE); hash_seq_init(&status, cfs_map_pin_live); while ((owner = (CfsMapPinOwner *) hash_seq_search(&status)) != NULL) { uint32 rel_hash; CfsRelMetaSlot *m; bool removed; int pin_count; if (cfs_map_owner_alive(owner->key.procno, owner->owner_pid, owner->owner_epoch)) continue; rel_hash = cfs_cache_hash_rel(owner->key.rlocator, owner->key.forknum); m = cfs_meta_find(rel_hash, owner->key.rlocator, owner->key.forknum); pin_count = owner->pin_count; (void) hash_search_with_hash_value(cfs_map_pin_live, &owner->key, cfs_map_pin_hash(&owner->key, rel_hash), HASH_REMOVE, &removed); if (removed) { if (m != NULL) m->refcount = (m->refcount > pin_count) ? m->refcount - pin_count : 0; reaped = true; } } for (i = 0; i < CFS_MAP_CACHE_NUM_PARTITIONS; i++) LWLockRelease(&cfs_map_locks[i].lock); pg_atomic_write_u64(&cfs_control->map_pin_reap_empty_at, reaped ? 0 : (uint64) GetCurrentTimestamp()); return reaped; } /* * Test hook: raise a slot's refcount on behalf of a process that is * already dead (a negative procno can never name a live backend, and * never the caller's own), recording the pin in the registry exactly * like cfs_map_cache_pin() would have. Returns the partition the slot * lives in, so the caller can fill it. */ int cfs_map_cache_test_pin_orphan(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; CfsMapPinKey key; CfsMapPinOwner *owner; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); m = cfs_meta_get_or_create(rel_hash, rlocator, forknum); if (m != NULL) m->refcount++; if (cfs_map_pin_live != NULL) { uint32 pin_hash; pin_hash = cfs_map_pin_key_hash(rlocator, forknum, -1, &key, rel_hash); owner = (CfsMapPinOwner *) hash_search_with_hash_value(cfs_map_pin_live, &key, pin_hash, HASH_ENTER, NULL); if (owner != NULL) { owner->owner_pid = 0; owner->owner_epoch = 0; owner->pin_count = 1; } } LWLockRelease(&cfs_map_locks[part].lock); return part; } /* * Test hook: run the dead-pin reaper directly and report whether it * reaped anything. Used by test_cfs to prove reaper idempotence: a * second run must find nothing and must not touch any refcount again. * The call bypasses and clears the empty-sweep throttle so the suite * stays deterministic no matter when it runs. */ bool cfs_map_cache_test_reap_dead_pins(void) { bool reaped; pg_atomic_write_u64(&cfs_control->map_pin_reap_empty_at, 0); reaped = cfs_map_slot_reap_dead_pins(true); pg_atomic_write_u64(&cfs_control->map_pin_reap_empty_at, 0); return reaped; } /* * Test hook: the current refcount of the relation's metadata slot, or -1 * when no slot exists. Used by test_cfs to prove the reaper returns * exactly the dead owner's pins and never a live owner's. */ int cfs_map_cache_test_slot_refcount(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; int refcount; LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED); m = cfs_meta_find(rel_hash, rlocator, forknum); refcount = (m != NULL) ? (int) m->refcount : -1; LWLockRelease(&cfs_map_locks[part].lock); return refcount; } /* * Test hook: does the pin-owner registry exist? It must for every pool * size, including cfs_map_memory = 0, where metadata slots are pinned * and reaped just the same. */ bool cfs_map_cache_test_pin_registry_live(void) { return cfs_map_pin_live != NULL; } void cfs_map_cache_unpin(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL && m->refcount > 0) { m->refcount--; cfs_map_pin_untrack(rlocator, forknum, rel_hash); /* * The relation's segments may have become evictable: wake the * exhaustion memo of every backend (see cfs_shared_map_ensure). */ pg_atomic_fetch_add_u64(&cfs_control->map_pool_churn, 1); } LWLockRelease(&cfs_map_locks[part].lock); } void cfs_map_cache_release_relation(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL) { if (m->refcount > 0) { m->refcount--; cfs_map_pin_untrack(rlocator, forknum, rel_hash); } if (m->refcount == 0) { /* * Make the metadata slot reclaimable. Cached block entries are * left in place; they will be evicted lazily by LRU pressure or * discarded by an explicit invalidate. Unlink before the clear * (invariant I3). */ cfs_meta_chain_unlink(part, m); MemSet(m, 0, sizeof(CfsRelMetaSlot)); pg_atomic_fetch_add_u64(&cfs_control->map_pool_churn, 1); } } LWLockRelease(&cfs_map_locks[part].lock); } /* ================================================================ * Map cache: relation metadata accessors * ================================================================ */ bool cfs_map_cache_get_nblocks(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 *out_nblocks) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; bool found = false; LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL) { *out_nblocks = m->nblocks; found = true; } LWLockRelease(&cfs_map_locks[part].lock); return found; } void cfs_map_cache_set_meta(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 nblocks) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); m = cfs_meta_get_or_create(rel_hash, rlocator, forknum); if (m == NULL) { LWLockRelease(&cfs_map_locks[part].lock); cfs_meta_overflow_error(rlocator, part); } /* * The logical size is monotonic under publication: a writer (bgwriter * flushing a stale page, an extender) may carry a private map whose * nblocks lags behind another backend's concurrent extension. The * callers try to publish max(local, cached), but that read-modify-write * is not atomic: between the get_nblocks() and this set_meta() another * backend can advance the slot, and an unconditional store here would * clobber the larger value, regressing the authoritative size. A later * P_NEW (smgrnblocks reads this slot) would then target an existing * block, raising "unexpected data beyond EOF". Grow-only here, under the * partition lock, makes the regression impossible. Truncation shrinks * the size through the dedicated cfs_map_cache_truncate() (which applies * Min() atomically under this same lock) before calling here, so the * grow-only rule never blocks a legitimate shrink. */ if (nblocks > m->nblocks) m->nblocks = nblocks; m->access_clock = cfs_map_clock_tick(part); /* * Mark dirty so checkpoint fsyncs sidecars */ if (m->is_cfs) m->dirty_checkpoint = true; LWLockRelease(&cfs_map_locks[part].lock); /* The statistics high-water mark: only grows, never shrinks here. */ cfs_stats_note_logical_pages(rel_hash, rlocator, forknum, nblocks); } void cfs_map_cache_mark_dirty(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); m = cfs_meta_find(rel_hash, rlocator, forknum); /* * A writer always holds a pinned slot (smgr open pins it), so a missing * slot means the relation is not open for writing; nothing to mark. */ if (m != NULL) { m->access_clock = cfs_map_clock_tick(part); if (m->is_cfs) m->dirty_checkpoint = true; } LWLockRelease(&cfs_map_locks[part].lock); } void cfs_map_cache_clear_dirty(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL) m->dirty_checkpoint = false; LWLockRelease(&cfs_map_locks[part].lock); } /* * Common body of cfs_publish_options / cfs_publish_options_postcommit. * soft_overflow selects the slot-exhaustion behaviour: raise ERROR (safe * only while the transaction can still roll back) or degrade to a WARNING * and skip the entry (mandatory on post-commit paths). */ static uint64 cfs_publish_options_internal(RelFileLocatorBackend rlocator, ForkNumber forknum, const CfsEffectiveOptions *opts, bool soft_overflow) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; uint64 gen = 0; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); m = cfs_meta_get_or_create(rel_hash, rlocator, forknum); if (m == NULL) { LWLockRelease(&cfs_map_locks[part].lock); if (soft_overflow) { cfs_meta_overflow_warning(rlocator, part); return 0; } cfs_meta_overflow_error(rlocator, part); } else { uint8 new_algo = opts->is_cfs ? (uint8) opts->algorithm : 0; /* * Bump the policy generation when the published policy actually * changes (a fresh slot counts as a change), so that SMgrRelation * holders — auxiliary processes in particular — notice and * re-resolve. The is_cfs flag is compared explicitly: on a * codec-less build a valid policy is RAW (new_algo == 0), which a * plain cfs_algo comparison would miss. The set-flags are part of * the comparison: a SET-vs-RESET of a field is a policy change even * when the resolved value happens to stay the same. The generation * comes from the partition's map-domain access clock, which is * strictly increasing within the partition: a relation and every * observer of its policy always hash to the same partition, so a * generation can never collide with one observed from an * evicted-and-recreated slot (the ABA case; the clock is never reset * within a server run). */ if (m->is_cfs != opts->is_cfs || m->cfs_algo != new_algo || m->level != opts->level || m->min_gain_bytes != opts->min_gain_bytes || m->level_set != opts->level_set || m->min_gain_bytes_set != opts->min_gain_bytes_set) m->policy_gen = cfs_map_clock_tick(part); m->is_cfs = opts->is_cfs; m->cfs_algo = new_algo; m->level = opts->level; m->min_gain_bytes = opts->min_gain_bytes; m->level_set = opts->level_set; m->min_gain_bytes_set = opts->min_gain_bytes_set; m->access_clock = cfs_map_clock_tick(part); gen = m->policy_gen; } LWLockRelease(&cfs_map_locks[part].lock); return gen; } uint64 cfs_publish_options(RelFileLocatorBackend rlocator, ForkNumber forknum, const CfsEffectiveOptions *opts) { return cfs_publish_options_internal(rlocator, forknum, opts, false); } uint64 cfs_publish_options_postcommit(RelFileLocatorBackend rlocator, ForkNumber forknum, const CfsEffectiveOptions *opts) { return cfs_publish_options_internal(rlocator, forknum, opts, true); } bool cfs_get_options(RelFileLocatorBackend rlocator, ForkNumber forknum, CfsEffectiveOptions *out) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; bool found = false; LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL && m->is_cfs) { /* * The algorithm may legitimately be RAW (= 0) on a codec-less build; * is_cfs, not the algorithm value, decides whether a policy is * stored. */ out->is_cfs = true; out->algorithm = (CfsAlgorithm) m->cfs_algo; out->level = m->level; out->min_gain_bytes = m->min_gain_bytes; out->level_set = m->level_set; out->min_gain_bytes_set = m->min_gain_bytes_set; found = true; } LWLockRelease(&cfs_map_locks[part].lock); return found; } bool cfs_slot_present(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; bool present; LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED); m = cfs_meta_find(rel_hash, rlocator, forknum); present = (m != NULL); LWLockRelease(&cfs_map_locks[part].lock); return present; } void cfs_forget_options(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL && m->refcount == 0) { /* Unlink from the chain before the clear (invariant I3). */ cfs_meta_chain_unlink(part, m); MemSet(m, 0, sizeof(CfsRelMetaSlot)); } else if (m != NULL) { /* * Bump the generation so cached copies of the policy are dropped. * The map-domain partition clock keeps the value unique within the * partition (the ABA-safe source cfs_publish_options_internal * documents). */ if (m->is_cfs) m->policy_gen = cfs_map_clock_tick(part); m->is_cfs = false; m->cfs_algo = 0; } LWLockRelease(&cfs_map_locks[part].lock); } /* ================================================================ * Deferred policy publication * * DDL that changes the CFS tunables (level / min_gain_bytes) of an * already-CFS relation publishes the new policy into the shared cache only * after the transaction commits durably, matching the vanilla pattern for * externally-visible DDL effects (sinval invalidation, smgr pending * deletes): private effects are applied immediately, public effects at * commit. An ALTER that aborts — at any subtransaction depth — therefore * leaves the shared cache untouched; a committed ALTER still reaches every * process through the generation check before the first reopen of the * relation. * * The deferred list is per-process and lives in TopMemoryContext. It * follows the transaction tree exactly like the vanilla PendingRelDelete * list (catalog/storage.c): each entry records the nesting level it was * queued at, a subtransaction commit hands its entries to the parent, and * a subtransaction abort drops the entries queued inside it. Every entry * is self-contained — "publish this policy for this storage node" — and * entries never interact, like the entries of the vanilla list: the fate * of an entry is decided by the transaction tree alone. Entries are * never merged on requeue: they survive in queue order, so the last * queued surviving version of a policy is the one published at commit — * which is also the surviving catalog state. * * An ALTER that turns the relation non-CFS queues nothing: the relation * goes through a rewrite, the old storage node is scheduled for deletion * like a vanilla RelationDropStorage() would, and the entries queued for * it earlier (if any) still publish at commit — harmlessly. The * publication bumps the generation for a node that dies at the same * commit: XACT_EVENT_COMMIT callbacks run before smgrDoPendingDeletes() * (xact.c), nothing reads the replaced node in that window, and the * unlink forgets the slot together with the sidecar files. This is the * vanilla double-entry answer (a pending delete scheduled for a node * that is deleted anyway): harmless execution beats a cancel mechanism. * The COMMIT PREPARED path is the one exception: there the files are * dropped before the postcommit callbacks run, so the entries of the * deleted nodes are never transferred to the two-phase state file * (cfs_publish_at_prepare). * ================================================================ */ typedef struct CfsDeferredPublish { RelFileLocatorBackend rlocator; ForkNumber forknum; int nestLevel; /* xact nesting level of request */ CfsEffectiveOptions opts; } CfsDeferredPublish; static CfsDeferredPublish * cfs_deferred = NULL; static int cfs_deferred_count = 0; static int cfs_deferred_cap = 0; static bool cfs_deferred_cb_registered = false; static void cfs_publish_xact_callback(XactEvent event, void *arg); static void cfs_publish_subxact_callback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg); /* * cfs_deferred_push * Append a policy publication entry to the deferred list. */ static void cfs_deferred_push(RelFileLocatorBackend rlocator, ForkNumber forknum, const CfsEffectiveOptions *opts) { MemoryContext oldctx; /* Lazily register the transaction callbacks on first use. */ if (!cfs_deferred_cb_registered) { RegisterXactCallback(cfs_publish_xact_callback, NULL); RegisterSubXactCallback(cfs_publish_subxact_callback, NULL); cfs_deferred_cb_registered = true; } /* Grow the array in TopMemoryContext if needed. */ oldctx = MemoryContextSwitchTo(TopMemoryContext); if (cfs_deferred_count == cfs_deferred_cap) { int newcap = cfs_deferred_cap == 0 ? 4 : cfs_deferred_cap * 2; cfs_deferred = cfs_deferred == NULL ? palloc(newcap * sizeof(CfsDeferredPublish)) : repalloc(cfs_deferred, newcap * sizeof(CfsDeferredPublish)); cfs_deferred_cap = newcap; } cfs_deferred[cfs_deferred_count].rlocator = rlocator; cfs_deferred[cfs_deferred_count].forknum = forknum; cfs_deferred[cfs_deferred_count].nestLevel = GetCurrentTransactionNestLevel(); cfs_deferred[cfs_deferred_count].opts = *opts; cfs_deferred_count++; MemoryContextSwitchTo(oldctx); } /* * cfs_publish_options_deferred * Queue a policy publication for the end of the current transaction * instead of publishing immediately. See the block comment above. */ void cfs_publish_options_deferred(RelFileLocatorBackend rlocator, ForkNumber forknum, const CfsEffectiveOptions *opts) { cfs_deferred_push(rlocator, forknum, opts); } /* * cfs_publish_is_pending * True when (rlocator, forknum) has a deferred publication queued in the * current transaction. Used by cfs_open_relation_smgr() to skip the immediate * publication for a relation whose policy comes from an uncommitted * catalog change: the flush after the durable commit (or the first * reopen after abort) publishes the surviving policy. */ bool cfs_publish_is_pending(RelFileLocatorBackend rlocator, ForkNumber forknum) { int i; for (i = 0; i < cfs_deferred_count; i++) { if (RelFileLocatorBackendEquals(cfs_deferred[i].rlocator, rlocator) && cfs_deferred[i].forknum == forknum) return true; } return false; } /* * cfs_publish_xact_callback * Flush deferred policy publications after the durable commit, and * drop them without publishing at abort or prepare. */ static void cfs_publish_xact_callback(XactEvent event, void *arg) { MemoryContext oldctx; if (event == XACT_EVENT_COMMIT) { int i; /* * The post-commit phase, after RecordTransactionCommit(): the * transaction can no longer roll back, so publishing here can never * leak an uncommitted policy — the same phase the vanilla * invalidation messages are sent from (AtEOXact_Inval). A failure in * any of the pre-commit steps above leaves the list intact for * XACT_EVENT_ABORT instead. Publication uses the postcommit variant: * an ERROR here is no longer abortable and would escalate to PANIC, * so slot exhaustion degrades to a WARNING and the entry is * republished on the next open of the relation. */ for (i = 0; i < cfs_deferred_count; i++) { cfs_publish_options_postcommit(cfs_deferred[i].rlocator, cfs_deferred[i].forknum, &cfs_deferred[i].opts); } } else if (event != XACT_EVENT_ABORT && event != XACT_EVENT_PREPARE) return; /* * Clear the list. At abort nothing has been published; at prepare the * entries have already been transferred to the two-phase state file by * cfs_publish_at_prepare() (which runs between StartPrepare and * EndPrepare, where RegisterTwoPhaseRecord is legal), and COMMIT PREPARED * publishes them after the durable commit. */ oldctx = MemoryContextSwitchTo(TopMemoryContext); if (cfs_deferred != NULL) pfree(cfs_deferred); cfs_deferred = NULL; cfs_deferred_count = 0; cfs_deferred_cap = 0; MemoryContextSwitchTo(oldctx); } /* * cfs_publish_at_prepare * Transfer the deferred publications of a preparing transaction into * the two-phase state file, following the vanilla pattern of * AtPrepare_MultiXact: called from PrepareTransaction() between * StartPrepare() and EndPrepare(), where RegisterTwoPhaseRecord() is * legal. A ROLLBACK PREPARED discards the records; a COMMIT PREPARED * replays them through cfs_twophase_postcommit after the durable * commit — mirroring how the shared invalidation messages of a * prepared transaction behave. * * Entries for storage nodes the transaction schedules for deletion are * skipped. FinishPreparedTransaction() drops those files (DropRelationFiles) * before replaying the postcommit callbacks — the reverse of the * CommitTransaction() order, where the unlink that follows the * publication forgets the slot again. A skipped entry therefore never * reaches the state file, and COMMIT PREPARED cannot republish a stale * policy for an already-deleted node. The same list is used here that * StartPrepare() itself puts into the state-file header * (smgrGetPendingDeletes(true)); it is safe to call again because the * in-memory list is only dropped later, by PostPrepare_smgr(). */ void cfs_publish_at_prepare(void) { RelFileLocator *delrels; int ndelrels; int i; int j; ndelrels = smgrGetPendingDeletes(true, &delrels); for (i = 0; i < cfs_deferred_count; i++) { CfsDeferredPublish *entry = &cfs_deferred[i]; bool node_dropped = false; /* * smgrGetPendingDeletes() returns only non-temp relations, so a * deferred entry for a temp backend can never match — but keep the * comparison honest by checking the backend id anyway. */ if (entry->rlocator.backend == INVALID_PROC_NUMBER) { for (j = 0; j < ndelrels; j++) { if (RelFileLocatorEquals(entry->rlocator.locator, delrels[j])) { node_dropped = true; break; } } } if (node_dropped) continue; RegisterTwoPhaseRecord(TWOPHASE_RM_CFS_POLICY_ID, 0, entry, sizeof(CfsDeferredPublish)); } if (delrels != NULL) pfree(delrels); /* The entries now live in the state file; nothing to flush locally. */ cfs_deferred_count = 0; } /* * cfs_twophase_postcommit * Publish the policy entries a committed prepared transaction carried * in its state file. Runs from FinishPreparedTransaction() after the * commit WAL record is durable, in the session executing COMMIT * PREPARED. */ void cfs_twophase_postcommit(FullTransactionId fxid, uint16 info, void *recdata, uint32 len) { CfsDeferredPublish *entry = (CfsDeferredPublish *) recdata; TransactionId xid = XidFromFullTransactionId(fxid); if (len != sizeof(CfsDeferredPublish)) { elog(WARNING, "CFS: ignoring malformed deferred policy record of length %u in prepared transaction %u", len, xid); return; } /* * Runs after the commit WAL record of COMMIT PREPARED is durable: use the * postcommit variant, which degrades to a WARNING instead of an ERROR * that could no longer be rolled back here. */ cfs_publish_options_postcommit(entry->rlocator, entry->forknum, &entry->opts); } /* * cfs_publish_subxact_callback * Track the transaction tree exactly like AtSubCommit_smgr / * AtSubAbort_smgr (catalog/storage.c): a subtransaction commit hands * its queued entries to the parent level, a subtransaction abort * drops the entries queued inside it. */ static void cfs_publish_subxact_callback(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg) { int nestLevel = GetCurrentTransactionNestLevel(); int i; int j; if (event == SUBXACT_EVENT_COMMIT_SUB) { for (i = 0; i < cfs_deferred_count; i++) { if (cfs_deferred[i].nestLevel >= nestLevel) cfs_deferred[i].nestLevel = nestLevel - 1; } } else if (event == SUBXACT_EVENT_ABORT_SUB) { j = 0; for (i = 0; i < cfs_deferred_count; i++) { if (cfs_deferred[i].nestLevel >= nestLevel) continue; cfs_deferred[j++] = cfs_deferred[i]; } cfs_deferred_count = j; } } uint64 cfs_policy_generation(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelMetaSlot *m; uint64 gen = 0; LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED); m = cfs_meta_find(rel_hash, rlocator, forknum); if (m != NULL) gen = m->policy_gen; LWLockRelease(&cfs_map_locks[part].lock); return gen; } void cfs_for_each_cfs_relation(CfsRelCB cb, void *arg) { /* * Maximum number of relation-metadata slots across all partitions. * Collecting a snapshot keeps the partition lock held only while copying * the (rlocator, forknum) keys, then invokes the callback without any CFS * lock held. This avoids releasing and reacquiring the lock inside the * iteration, which previously let another backend evict or replace a slot * mid-scan (skip / double-process). * * Only relations marked dirty_checkpoint (written since the last * checkpoint) are enumerated: the sole caller is the checkpoint path, * which must not re-snapshot and re-fsync relations that saw no writes. */ int max_rels = CFS_MAP_CACHE_NUM_PARTITIONS * cfs_map_cache_rels_per_partition; RelFileLocatorBackend *snapshot_rlocator; ForkNumber *snapshot_forknum; int nrels = 0; int part; int i; int j; Assert(cfs_control != NULL); snapshot_rlocator = (RelFileLocatorBackend *) palloc(max_rels * sizeof(RelFileLocatorBackend)); snapshot_forknum = (ForkNumber *) palloc(max_rels * sizeof(ForkNumber)); /* * First pass: collect the keys of the relations written since the last * checkpoint (dirty_checkpoint) under each partition's shared lock. A * relation without a single write since then needs no new map snapshot or * fsync and is skipped. A relation dirtied only after its partition was * scanned is left for the next checkpoint: its journal is not truncated * by this run, and WAL replay from the previous redo pointer still covers * those writes after a crash, so nothing is lost. */ for (part = 0; part < CFS_MAP_CACHE_NUM_PARTITIONS; part++) { LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED); for (i = 0; i < cfs_map_cache_rels_per_partition; i++) { CfsRelMetaSlot *m = cfs_rel_meta_slot(part, i); if (m->hash != 0 && m->is_cfs && m->dirty_checkpoint) { if (nrels < max_rels) { snapshot_rlocator[nrels] = m->rlocator; snapshot_forknum[nrels] = m->forknum; nrels++; } } } LWLockRelease(&cfs_map_locks[part].lock); } /* Second pass: invoke the callback without holding any CFS lock. */ for (j = 0; j < nrels; j++) cb(snapshot_rlocator[j], snapshot_forknum[j], arg); pfree(snapshot_rlocator); pfree(snapshot_forknum); } /* * The statistics counters, their slots and the statsfile moved to * cfs_stats.c (a leaf module the storage layer may call directly). */ /* ================================================================ * Cache integration with the storage layer * ================================================================ */ /* * cfs_map_segment_invalidate_block — clear one entry of a resident segment * (the entry proved unusable: CRC mismatch or unreadable record), so the * next lookup misses and the authoritative path re-resolves it. */ static void cfs_map_segment_invalidate_block(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum) { CfsMapSegmentKey key; uint32 hash; int id; if (cfs_map_seg_count == 0) return; key.rlocator = rlocator; key.forknum = forknum; key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1); hash = cfs_map_segment_hash(rlocator, forknum, key.first_block); id = cfs_map_segment_find(&key, hash, LW_SHARED); if (id < 0) return; LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE); if (cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator, forknum, key.first_block)) { MemSet(&cfs_map_seg_data[id][blocknum - key.first_block], 0, sizeof(CfsMapEntry)); /* * The cleared slot must be re-resolvable from the snapshot on the * next miss (a corrupted record keeps re-reporting its error, a store * that could not land gets re-read authoritatively): let the next * ensure merge the snapshot part again. */ cfs_map_seg_descs[id].snapshot_loaded = false; cfs_map_seg_descs[id].journal_synced = false; } LWLockRelease(&cfs_map_seg_locks[id].lock); } /* Context for the segment journal-delta replay callback. */ typedef struct CfsSegSyncCtx { int id; uint32 hash; RelFileLocatorBackend rlocator; ForkNumber forknum; BlockNumber first_block; char *corrupt_mask; /* blocks still needing a heal */ } CfsSegSyncCtx; /* One replayed journal record: store/clear the entry in the segment. */ static void cfs_seg_sync_cb(BlockNumber blocknum, const CfsMapEntry *entry, void *arg) { CfsSegSyncCtx *ctx = (CfsSegSyncCtx *) arg; CfsMapSegmentDesc *desc = &cfs_map_seg_descs[ctx->id]; int off = blocknum - ctx->first_block; LWLockAcquire(&cfs_map_seg_locks[ctx->id].lock, LW_EXCLUSIVE); if (cfs_map_segment_valid(desc, ctx->hash, ctx->rlocator, ctx->forknum, ctx->first_block)) { if (entry != NULL) cfs_map_seg_data[ctx->id][off] = *entry; else MemSet(&cfs_map_seg_data[ctx->id][off], 0, sizeof(CfsMapEntry)); if (ctx->corrupt_mask != NULL) ctx->corrupt_mask[off] = 0; /* * A journal record (UPDATE or DELETE) resolves this block: it is no * longer torn, so the block may serve again. */ cfs_seg_unhealed_clear(desc, off); } LWLockRelease(&cfs_map_seg_locks[ctx->id].lock); } /* * cfs_shared_map_sync_segment — replay the journal delta into the resident * segment covering 'blocknum', advancing its jrn_synced_off. The caller * must hold the relation's append lock (shared suffices: the journal is * append-only and replaying the same records twice is idempotent), which * also serialises against compaction so the handle's descriptors are * stable while the segment reads the journal through them. * * A journal whose header incarnation differs from the segment's stamp — or * that shrank below the segment's sync offset — was reset by a checkpoint * (truncate + incarnation bump) whose snapshot already contains everything * the journal no longer does. The incarnation catches the ABA case the * size check cannot: the new-incarnation journal may grow back past the * stale offset, and replaying from there would silently skip the records * below it. Either way the segment resyncs: the fresh .cfsmap is merged * into its INVALID slots and the replay restarts from the journal header. * * Returns 1 on success, 0 when the segment vanished or could not be read * (a concurrent eviction or reopen — transient, the caller may retry or * fall back), -1 when the journal replay itself rejected the segment * (mid-journal corruption — fatal), and * CFS_STORAGE_CORRUPT when the requested block still has a row no * journal record healed: that block's bit is left in the segment's * unhealed bitmap (lookup refuses only it) and the caller must fail the * read through the smgr entry point's corruption report. Neither * failure path throws from here: the caller may run under the append * lock / inside an AIO callback. */ /* * Post-replay validation of a segment's corrupt rows. * Every still-set mask byte names a block whose snapshot row failed its * entry_crc; a byte the journal healed was cleared by cfs_seg_sync_cb. * The still-torn blocks are recorded in the descriptor's per-block bitmap * (the segment itself stays publishable for the rest of the range), and * the requested block decides whether the caller reports corruption. * * The caller must hold the segment's lock (either mode): the bitmap is * part of the segment's published state. */ static inline bool cfs_seg_unhealed_test(const CfsMapSegmentDesc *desc, uint32 off) { return (desc->unhealed_mask[off >> 3] & (1u << (off & 7))) != 0; } static inline void cfs_seg_unhealed_set(CfsMapSegmentDesc *desc, uint32 off) { desc->unhealed_mask[off >> 3] |= (1u << (off & 7)); } static inline void cfs_seg_unhealed_clear(CfsMapSegmentDesc *desc, uint32 off) { desc->unhealed_mask[off >> 3] &= ~(1u << (off & 7)); } /* Can the resident segment serve this block, or is the row still torn? */ static bool cfs_map_segment_unhealed_at(int id, uint32 hash, RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber first_block, BlockNumber blocknum) { CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id]; uint32 off = blocknum - first_block; if (!cfs_map_segment_valid(desc, hash, rlocator, forknum, first_block)) return false; if (off >= CFS_MAP_SEGMENT_BLOCKS) return false; return cfs_seg_unhealed_test(desc, off); } /* * Merge the still-torn rows of one snapshot load into the descriptor's * sticky bitmap: a mask bit whose slot the journal healed (the callback * cleared the byte) or whose slot holds a valid row is not corruption. * Returns the number of blocks left unhealed by this pass. */ static void cfs_map_segment_collect_unhealed(int id, uint32 hash, RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber first_block, const char *corrupt_mask) { CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id]; uint32 off; if (!cfs_map_segment_valid(desc, hash, rlocator, forknum, first_block)) return; for (off = 0; off < CFS_MAP_SEGMENT_BLOCKS; off++) { if (corrupt_mask[off] && cfs_map_seg_data[id][off].physical_offset == CFS_ENTRY_INVALID_OFFSET) cfs_seg_unhealed_set(desc, off); } } static int cfs_shared_map_sync_segment(CfsRelation *cfs, BlockNumber blocknum, char *corrupt_mask) { char *owned_mask = NULL; RelFileLocatorBackend rlocator = cfs->rlocator; ForkNumber forknum = cfs->forknum; CfsMapSegmentKey key; uint32 hash; CfsSegSyncCtx ctx; CfsJournalFileHeader jhdr; uint16 stamped_incarnation; int state_fl; off_t cur_size; off_t start; off_t stop; if (cfs_map_seg_count == 0) return 0; key.rlocator = rlocator; key.forknum = forknum; key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1); hash = cfs_map_segment_hash(rlocator, forknum, key.first_block); ctx.id = cfs_map_segment_find(&key, hash, LW_SHARED); if (ctx.id < 0) return 0; LWLockAcquire(&cfs_map_seg_locks[ctx.id].lock, LW_SHARED); if (!cfs_seg_matches(&cfs_map_seg_descs[ctx.id], hash, rlocator, forknum, key.first_block, cfs)) { LWLockRelease(&cfs_map_seg_locks[ctx.id].lock); return 0; } start = (off_t) cfs_map_seg_descs[ctx.id].jrn_synced_off; stamped_incarnation = cfs_map_seg_descs[ctx.id].jrn_incarnation; LWLockRelease(&cfs_map_seg_locks[ctx.id].lock); /* Journal records begin after the file header. */ if (start < (off_t) CFS_JOURNAL_HEADER_SIZE) start = CFS_JOURNAL_HEADER_SIZE; cur_size = cfs_fd_size(cfs->jrn_fd); if (cur_size < 0) return 0; /* * The judge derives the reset/shrink signals against the segment's * stamped baseline (see the caller mask table in cfs_state.c); this site * gives up on a stale/unreadable header exactly like it always did. */ state_fl = cfs_state_journal_moved(cfs, stamped_incarnation, start, &jhdr); if (state_fl & (CFS_STATE_JRN_STAT_FAILED | CFS_STATE_JRN_HEADER_STALE)) return 0; if (state_fl & (CFS_STATE_JRN_RESET | CFS_STATE_JRN_SHRANK)) { if (corrupt_mask == NULL) { owned_mask = palloc0(CFS_MAP_SEGMENT_BLOCKS); corrupt_mask = owned_mask; } /* * Journal reset since the segment last synced: re-baseline the * segment (fresh snapshot merge + replay from the header). Under the * append lock the reset has completed, so the on-disk header is * stable here. */ LWLockAcquire(&cfs_map_seg_locks[ctx.id].lock, LW_EXCLUSIVE); if (cfs_seg_matches(&cfs_map_seg_descs[ctx.id], hash, rlocator, forknum, key.first_block, cfs)) { cfs_map_seg_descs[ctx.id].snapshot_loaded = false; cfs_map_seg_descs[ctx.id].journal_synced = false; cfs_map_seg_descs[ctx.id].jrn_synced_off = 0; cfs_map_seg_descs[ctx.id].jrn_incarnation = jhdr.incarnation; } else { LWLockRelease(&cfs_map_seg_locks[ctx.id].lock); return 0; } LWLockRelease(&cfs_map_seg_locks[ctx.id].lock); if (!cfs_map_segment_merge_snapshot(cfs, ctx.id, hash, rlocator, forknum, key.first_block, corrupt_mask)) { if (owned_mask != NULL) pfree(owned_mask); return 0; } start = (off_t) CFS_JOURNAL_HEADER_SIZE; } if (start >= cur_size) { /* Already synced (or the journal holds no new records). */ LWLockAcquire(&cfs_map_seg_locks[ctx.id].lock, LW_EXCLUSIVE); if (cfs_seg_matches(&cfs_map_seg_descs[ctx.id], hash, rlocator, forknum, key.first_block, cfs)) { /* * The journal cannot heal anything anymore (it holds no new * records): still-set mask bits are unhealed corruption, and * those blocks must not serve their INVALID slots as zero pages . * Only the requested block decides this call's outcome; the other * bits stay in the bitmap so their own reads report the damage on * the right block. */ if (corrupt_mask != NULL) cfs_map_segment_collect_unhealed(ctx.id, hash, rlocator, forknum, key.first_block, corrupt_mask); if (cfs_map_segment_unhealed_at(ctx.id, hash, rlocator, forknum, key.first_block, blocknum)) { LWLockRelease(&cfs_map_seg_locks[ctx.id].lock); if (owned_mask != NULL) pfree(owned_mask); return CFS_STORAGE_CORRUPT; } cfs_map_seg_descs[ctx.id].journal_synced = true; } LWLockRelease(&cfs_map_seg_locks[ctx.id].lock); if (owned_mask != NULL) pfree(owned_mask); return 1; } ctx.hash = hash; ctx.rlocator = rlocator; ctx.forknum = forknum; ctx.first_block = key.first_block; ctx.corrupt_mask = corrupt_mask; stop = cfs_journal_replay_segment(cfs, start, key.first_block, cfs_seg_sync_cb, &ctx); if (stop < 0) { if (owned_mask != NULL) pfree(owned_mask); return -1; } LWLockAcquire(&cfs_map_seg_locks[ctx.id].lock, LW_EXCLUSIVE); if (cfs_seg_matches(&cfs_map_seg_descs[ctx.id], hash, rlocator, forknum, key.first_block, cfs)) { /* * The replay is done: mask bits it did not heal name rows no journal * record covers. Keep them in the per-block bitmap and publish the * segment for everything else; the requested block fails the call if * it is one of the still-torn ones. */ if (corrupt_mask != NULL) cfs_map_segment_collect_unhealed(ctx.id, hash, rlocator, forknum, key.first_block, corrupt_mask); if (cfs_map_segment_unhealed_at(ctx.id, hash, rlocator, forknum, key.first_block, blocknum)) { LWLockRelease(&cfs_map_seg_locks[ctx.id].lock); if (owned_mask != NULL) pfree(owned_mask); return CFS_STORAGE_CORRUPT; } if ((off_t) cfs_map_seg_descs[ctx.id].jrn_synced_off < stop) cfs_map_seg_descs[ctx.id].jrn_synced_off = (uint64) stop; cfs_map_seg_descs[ctx.id].jrn_incarnation = jhdr.incarnation; cfs_map_seg_descs[ctx.id].journal_synced = true; } LWLockRelease(&cfs_map_seg_locks[ctx.id].lock); if (owned_mask != NULL) pfree(owned_mask); return 1; } /* * Validate a segment entry and read the page through it. On an integrity * failure the block's entry is cleared so the next read re-resolves it. */ static int cfs_read_entry_record(CfsRelation *cfs, BlockNumber blocknum, CfsMapEntry *entry, char *dst) { RelFileLocatorBackend rl = cfs->rlocator; ForkNumber forknum = cfs->forknum; CfsFormatStatus st; int rc; st = cfs_map_entry_validate(entry, true); if (st != CFS_FORMAT_OK) { cfs_stats_count_crc_failure(rl, forknum); cfs_map_segment_invalidate_block(rl, forknum, blocknum); /* * Escalate through the configured severity (error/panic) exactly like * the authoritative map path: the entry-level detail is logged here, * the client-facing ERROR/PANIC comes from cfs_report_corruption(). */ cfs_report_corruption(rl, forknum, blocknum, psprintf("invalid page map entry for block %u " "(status %s)", blocknum, CfsFormatStatusString(st)), false); return CFS_STORAGE_CORRUPT; } rc = cfs_read_record(cfs, (off_t) entry->physical_offset, entry->compressed_size, dst, CFS_BLCKSZ); if (rc != CFS_STORAGE_OK) { cfs_stats_count_crc_failure(rl, forknum); cfs_map_segment_invalidate_block(rl, forknum, blocknum); return rc; } cfs_stats_count_read(rl, forknum, entry->compressed_size); return CFS_STORAGE_OK; } /* * True when the resident segment covering 'blocknum' can speak for the whole * range: it is the current incarnation of the relation's map, its snapshot * part has been merged and the journal replay has caught it up. Only then * does an INVALID slot mean "never written" rather than "not resolved yet". */ static bool cfs_shared_map_segment_authoritative(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum, uint64 generation) { CfsMapSegmentKey key; uint32 hash; int id; bool ok; if (cfs_map_seg_count == 0) return false; key.rlocator = rlocator; key.forknum = forknum; key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1); hash = cfs_map_segment_hash(rlocator, forknum, key.first_block); id = cfs_map_segment_find(&key, hash, LW_SHARED); if (id < 0) return false; LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED); ok = cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator, forknum, key.first_block) && cfs_map_seg_descs[id].rel_generation == generation && cfs_map_seg_descs[id].snapshot_loaded && cfs_map_seg_descs[id].journal_synced && !cfs_map_segment_unhealed_at(id, hash, rlocator, forknum, key.first_block, blocknum); LWLockRelease(&cfs_map_seg_locks[id].lock); return ok; } /* Context for the non-pool (scratch) journal replay callback. */ typedef struct CfsScratchSyncCtx { CfsMapEntry *buf; BlockNumber first_block; char *corrupt_mask; /* byte per block; a replayed record for a * masked block heals it (clears the bit) */ } CfsScratchSyncCtx; /* One replayed journal record into the private scratch segment. */ static void cfs_scratch_sync_cb(BlockNumber blocknum, const CfsMapEntry *entry, void *arg) { CfsScratchSyncCtx *ctx = (CfsScratchSyncCtx *) arg; int off = blocknum - ctx->first_block; if (entry != NULL) ctx->buf[off] = *entry; else MemSet(&ctx->buf[off], 0, sizeof(CfsMapEntry)); /* A journal record covers the block: its corruption is healed. */ if (ctx->corrupt_mask != NULL) ctx->corrupt_mask[off] = 0; } /* * Resolve an authoritative INVALID slot: inside the logical size it is an * extension gap, so a zero page is returned; beyond it the read is out of * range exactly like the full-map path. The caller must have established * that the map it consults is current — this never fabricates zeroes from a * stale or unsynced map. */ static int cfs_read_extension_gap(CfsRelation *cfs, BlockNumber blocknum, char *dst) { RelFileLocatorBackend rl = cfs->rlocator; ForkNumber forknum = cfs->forknum; uint64 nblocks = 0; if (!cfs_map_cache_get_nblocks(rl, forknum, &nblocks)) nblocks = cfs->map_hdr.nblocks; if ((uint64) blocknum >= nblocks) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: read_page: block %u out of range (nblocks=%llu)", blocknum, (unsigned long long) nblocks))); MemSet(dst, 0, CFS_BLCKSZ); cfs_stats_count_read(rl, forknum, 0); return CFS_STORAGE_OK; } /* * cfs_read_page_authoritative — resolve one page without a pool segment. * * Called when the shared pool has no free or evictable segment but the data * is still available on disk. Load the 768 kB .cfsmap range covering the * block into the per-backend scratch buffer, replay the journal delta for * that range on top of it and resolve the entry from the result. Nothing * is published into the pool, so a pool that stays exhausted (many open * relations pin their segments) degrades to one segment load per miss * instead of a full map load per page. * * The append lock is held while the snapshot range and the journal are * read: every .cfsmap rewrite (checkpoint, compaction, truncate) and the * journal truncate take it exclusively, so under it the pair is stable and * a torn record can only be a peer mid-append. A stale handle is reopened * first, exactly like the pool miss path does. * * The result has the same authority as a fully synced resident segment: * the snapshot plus the complete journal delta over it. An INVALID slot * therefore means "never written", which cfs_read_extension_gap() turns * into a zero page (or an out-of-range error); a short or corrupt snapshot * raises instead of being published as zeroes, and a row that failed its * entry_crc and that no journal record healed is returned as * CFS_STORAGE_CORRUPT for the smgr entry point to report. An ERROR raised * here inside the synchronous read of cfs_smgr_startreadv() is caught * there, converted to the inline AIO failure code and reported later by * aio_cfs_readv_report(), so this path never throws out of an AIO * operation. */ static int cfs_read_page_authoritative(CfsRelation *cfs, BlockNumber blocknum, char *dst) { RelFileLocatorBackend rl = cfs->rlocator; ForkNumber forknum = cfs->forknum; BlockNumber first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1); CfsMapEntry *buf; Size seg_bytes = (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry); CfsScratchSyncCtx ctx; uint32 save_holdoff; uint32 save_crit_section; char *corrupt_mask; bool unhealed = false; int off; Assert(cfs->map == NULL); buf = cfs_map_segment_scratch(); MemSet(buf, 0, seg_bytes); /* * Byte-per-block mask of the rows whose snapshot load failed the * entry_crc; cfs_scratch_sync_cb clears the bits journal records cover. * Only the still-set bits after the replay name corruption. Cold * fallback path: the palloc is fine here. */ corrupt_mask = palloc0(CFS_MAP_SEGMENT_BLOCKS); cfs_append_lock_acquire(rl, forknum, LW_SHARED); save_holdoff = InterruptHoldoffCount; save_crit_section = CritSectionCount; PG_TRY(); { cfs_handle_refresh_if_stale(cfs); { int load_rc; load_rc = cfs_map_segment_load_buf(cfs, first_block, buf, seg_bytes, corrupt_mask); if (load_rc == -2) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not read map segment from \"%s\"", cfs->map_path))); } ctx.buf = buf; ctx.first_block = first_block; ctx.corrupt_mask = corrupt_mask; if (cfs_journal_replay_segment(cfs, (off_t) CFS_JOURNAL_HEADER_SIZE, first_block, cfs_scratch_sync_cb, &ctx) < 0) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not replay the journal into the block map " "segment for block %u of relation %u/%u/%u", blocknum, rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber))); /* * Only the requested block decides this read: a masked row no record * healed is unhealed corruption for that block, while its healthy * neighbours in the same 768 KiB range still read normally. */ off = (int) (blocknum - first_block); if (corrupt_mask[off] && buf[off].physical_offset == CFS_ENTRY_INVALID_OFFSET) unhealed = true; } PG_CATCH(); { /* * errfinish() zeroes InterruptHoldoffCount and CritSectionCount on * ERROR (elog.c), so a plain release would trip the assert inside * RESUME_INTERRUPTS(). Restore the values as they were with the lock * held, release, then rethrow: cfs_smgr_startreadv() converts the * structural error into an AIO failure code. */ InterruptHoldoffCount = save_holdoff; CritSectionCount = save_crit_section; cfs_append_lock_release(rl, forknum); PG_RE_THROW(); } PG_END_TRY(); cfs_append_lock_release(rl, forknum); pfree(corrupt_mask); /* * Row-level corruption is still deferred to the entry point, which raises * the checksum-failure report; structural errors above are caught by * cfs_smgr_startreadv() and converted to the AIO failure code. */ if (unhealed) return CFS_STORAGE_CORRUPT; if (buf[blocknum - first_block].physical_offset != CFS_ENTRY_INVALID_OFFSET) return cfs_read_entry_record(cfs, blocknum, &buf[blocknum - first_block], dst); return cfs_read_extension_gap(cfs, blocknum, dst); } /* * cfs_map_contiguous_run — length of the run of physically contiguous * records in .cfp starting at 'blocknum', capped at 'maxblocks' (the * caller passes io_combine_limit). Purely advisory and cheap: entries are * only read from already-resident state (the private map array or resident * pool segments), with no I/O, no segment residency and no journal replay; * the first miss, hole, offset gap, segment boundary or capacity limit * ends the run. Returns at least 1. cfs_smgr_maxcombine() publishes this * to the buffer manager, while cfs_read_pages_batch() re-derives the * grouping independently at read time — correctness never depends on the * value returned here (a compaction between planning and reading merely * shrinks the batches). */ int cfs_map_contiguous_run(CfsRelation *cfs, BlockNumber blocknum, BlockNumber maxblocks) { RelFileLocatorBackend rl = cfs->rlocator; ForkNumber forknum = cfs->forknum; CfsMapEntry prev; CfsMapEntry entry; uint64 seg_gen = 0; BlockNumber run = 1; if (maxblocks <= 1) return 1; if (cfs->map != NULL) { /* * Private map (cfs_map_memory=0, compaction, the checkpoint * snapshot writer): the array may legitimately lag nblocks, so cap * the walk by the allocated capacity as well. Stale rows are fine: * the answer is advisory. */ uint64 limit = cfs->map_hdr.nblocks; if (limit > cfs->map_capacity) limit = cfs->map_capacity; if ((uint64) blocknum >= limit || limit == 0) return 1; limit -= blocknum; while (run < maxblocks && (uint64) run < limit) { CfsMapEntry *e = &cfs->map[blocknum + run]; CfsMapEntry *p = &cfs->map[blocknum + run - 1]; if (!CFS_MAP_ENTRY_VALID(p) || !CFS_MAP_ENTRY_VALID(e)) break; if (e->physical_offset != p->physical_offset + CFS_RECORD_SIZE(p->compressed_size)) break; if (CFS_CFP_SEGNO(e->physical_offset) != CFS_CFP_SEGNO(p->physical_offset)) break; run++; } return run; } /* Pool-backed handle: resident entries only, tag-checked. */ if (!cfs_shared_map_lookup(rl, forknum, blocknum, &prev, &seg_gen) || !cfs_seg_tag_matches(seg_gen, cfs)) return 1; while (run < maxblocks) { if (!cfs_shared_map_lookup(rl, forknum, blocknum + run, &entry, &seg_gen) || !cfs_seg_tag_matches(seg_gen, cfs)) break; if (entry.physical_offset != prev.physical_offset + CFS_RECORD_SIZE(prev.compressed_size)) break; if (CFS_CFP_SEGNO(entry.physical_offset) != CFS_CFP_SEGNO(prev.physical_offset)) break; prev = entry; run++; } return run; } /* * cfs_read_span_corrupt_bookkeeping — pool-side failure bookkeeping for * an offloaded span whose executor detected corruption (see cfs_shmem.h). * Defined here so the static pool helper is already in scope. */ void cfs_read_span_corrupt_bookkeeping(RelFileLocatorBackend rl, ForkNumber forknum, BlockNumber fail_block, bool pooled) { if (pooled) { cfs_stats_count_crc_failure(rl, forknum); cfs_map_segment_invalidate_block(rl, forknum, fail_block); } } /* * cfs_gather_contiguous_run — copy the map rows of the longest physically * contiguous run of stored records starting at 'blocknum' into 'entries' * (capacity 'nmax') and return its length. Pure map state consultation * (private array or already-resident pool segments, tag-checked): no I/O, * no residency work. The first miss, hole, stale tag, offset gap or * segment boundary ends the run. Shared by cfs_read_pages_batch() and * cfs_read_span_plan(), so the two paths can never disagree about what a * run is. */ static BlockNumber cfs_gather_contiguous_run(CfsRelation *cfs, CfsMapEntry *entries, BlockNumber nmax, BlockNumber blocknum) { RelFileLocatorBackend rl = cfs->rlocator; ForkNumber forknum = cfs->forknum; BlockNumber run = 0; while (run < nmax) { BlockNumber blk = blocknum + run; CfsMapEntry entry; uint64 seg_gen = 0; bool have = false; if (cfs->map != NULL) { if ((uint64) blk < cfs->map_hdr.nblocks && (uint64) blk < cfs->map_capacity) { entry = cfs->map[blk]; have = true; } } else { have = cfs_shared_map_lookup(rl, forknum, blk, &entry, &seg_gen) && cfs_seg_tag_matches(seg_gen, cfs); } if (!have || !CFS_MAP_ENTRY_VALID(&entry)) break; if (run > 0) { CfsMapEntry *prev = &entries[run - 1]; if (entry.physical_offset != prev->physical_offset + CFS_RECORD_SIZE(prev->compressed_size)) break; if (CFS_CFP_SEGNO(entry.physical_offset) != CFS_CFP_SEGNO(prev->physical_offset)) break; } entries[run++] = entry; } return run; } /* * cfs_read_pages_batch — fill 'nblocks' buffers starting at 'blocknum', * batching runs of physically contiguous records into single preads * (cfs_read_records_span) and serving everything else through the existing * per-block path cfs_read_page_cached() (pool misses, stale tags, holes, * offset gaps, segment boundaries, out-of-range reads). The produced pages * are bit-identical to the per-block path: positions come from the map * entries, integrity from each record's own header CRC. * * On failure returns the CfsStorageStatus of the first failure and stores * the code and failing block for the caller (the synchronous entry point * reports centrally, the AIO one encodes the code — same contract as * before batching). Pool-sourced failures mirror cfs_read_entry_record(): * the failing block is invalidated in the pool and counted as a CRC * failure, so the next read re-resolves it from the journal. */ int cfs_read_pages_batch(CfsRelation *cfs, BlockNumber blocknum, void **buffers, BlockNumber nblocks, int *fail_code, BlockNumber *fail_block) { RelFileLocatorBackend rl = cfs->rlocator; ForkNumber forknum = cfs->forknum; CfsMapEntry *entries; BlockNumber b; Assert(cfs != NULL && buffers != NULL); Assert(nblocks >= 1); if (nblocks == 1) { int rc = cfs_read_page_cached(cfs, blocknum, buffers[0]); if (rc != CFS_STORAGE_OK) { if (fail_code != NULL) *fail_code = rc; if (fail_block != NULL) *fail_block = blocknum; return rc; } /* * read_count is only maintained for shared-pool reads: on a * private map the per-block path never reaches it, so the fallback * counter must skip it too to keep the invariant balanced. */ if (cfs->map == NULL) cfs_stats_count_read_fallback(rl, forknum, 1); return rc; } /* * Private map: one journal refresh covers the whole call — the per-block * path pays it per block. The append-lock protocol (including the * errfinish holdoff subtlety) is identical to cfs_read_page_cached(). */ if (cfs->map != NULL && cfs_map_needs_refresh(cfs)) { int refresh_rc = CFS_STORAGE_OK; cfs_append_lock_acquire(rl, forknum, LW_SHARED); PG_TRY(); { refresh_rc = cfs_refresh_map(cfs, true, CFS_LOAD_READ); } PG_CATCH(); { /* * errfinish() resets InterruptHoldoffCount to zero on ERROR * (elog.c), so the RESUME_INTERRUPTS() inside LWLockRelease * would assert even though the lock is still held. Put the * holdoff back for the release, then rethrow: the caller * (cfs_smgr_startreadv) is the one that converts the error * into an AIO failure. */ HOLD_INTERRUPTS(); cfs_append_lock_release(rl, forknum); PG_RE_THROW(); } PG_END_TRY(); cfs_append_lock_release(rl, forknum); if (refresh_rc != CFS_STORAGE_OK) { if (fail_code != NULL) *fail_code = refresh_rc; if (fail_block != NULL) *fail_block = blocknum; return refresh_rc; } } entries = (CfsMapEntry *) palloc(nblocks * sizeof(CfsMapEntry)); b = 0; while (b < nblocks) { BlockNumber run; /* Gather the longest contiguous run starting at blocknum + b. */ run = cfs_gather_contiguous_run(cfs, entries, nblocks - b, blocknum + b); if (run >= 2) { BlockNumber fblock = blocknum + b; int rc; rc = cfs_read_records_span(cfs, entries, blocknum + b, run, &buffers[b], &fblock); if (rc != CFS_STORAGE_OK) { /* * Mirror cfs_read_entry_record()'s bookkeeping for * pool-sourced runs: drop the failing block from the pool * and count the failure, so the next read re-resolves it * from the journal. For private-map runs the per-block * path does neither, and neither do we. */ if (cfs->map == NULL) { cfs_stats_count_crc_failure(rl, forknum); cfs_map_segment_invalidate_block(rl, forknum, fblock); } if (fail_code != NULL) *fail_code = rc; if (fail_block != NULL) *fail_block = fblock; pfree(entries); return rc; } b += run; } else { int rc = cfs_read_page_cached(cfs, blocknum + b, buffers[b]); if (rc != CFS_STORAGE_OK) { if (fail_code != NULL) *fail_code = rc; if (fail_block != NULL) *fail_block = blocknum + b; pfree(entries); return rc; } /* Same pool-only rule as the nblocks == 1 fast path above. */ if (cfs->map == NULL) cfs_stats_count_read_fallback(rl, forknum, 1); b++; } } pfree(entries); return CFS_STORAGE_OK; } /* * cfs_read_span_plan — build the offload plan for one readv request; see * cfs_shmem.h for the contract. The body mirrors the corresponding * halves of cfs_read_pages_batch() (map refresh prologue, run gathering) * and cfs_read_records_span() (row validation, boundary check, segment * fd), so an offloaded read produces exactly the pages and exactly the * failure codes its inline counterpart would. */ CfsReadPlanStatus cfs_read_span_plan(CfsRelation *cfs, BlockNumber blocknum, BlockNumber nblocks, CfsReadScratchSlot **out_slot, int *out_fd, uint64 *out_span_off, int *fail_code, BlockNumber *fail_block) { RelFileLocatorBackend rl = cfs->rlocator; ForkNumber forknum = cfs->forknum; CfsMapEntry *entries; CfsReadScratchSlot *slot; uint64 span_off; uint64 span_end; uint32 segno; size_t span_len; BlockNumber run; BlockNumber b; int fd; Assert(cfs != NULL && out_slot != NULL && out_fd != NULL && out_span_off != NULL); Assert(nblocks >= 2); /* * Requests beyond the plan capacity cannot be represented; the combine * clamp makes this unreachable, but degrading is cheaper than trusting * two GUCs to agree forever. */ if (nblocks > CFS_READ_PLAN_MAX) { return CFS_READ_PLAN_DEGRADE; } /* * Private map: one journal refresh covers the whole plan, exactly the * cfs_read_pages_batch() prologue (including the errfinish holdoff * subtlety). */ if (cfs->map != NULL && cfs_map_needs_refresh(cfs)) { int refresh_rc = CFS_STORAGE_OK; cfs_append_lock_acquire(rl, forknum, LW_SHARED); PG_TRY(); { refresh_rc = cfs_refresh_map(cfs, true, CFS_LOAD_READ); } PG_CATCH(); { HOLD_INTERRUPTS(); cfs_append_lock_release(rl, forknum); PG_RE_THROW(); } PG_END_TRY(); cfs_append_lock_release(rl, forknum); if (refresh_rc != CFS_STORAGE_OK) { if (fail_code != NULL) *fail_code = refresh_rc; if (fail_block != NULL) *fail_block = blocknum; return CFS_READ_PLAN_FAIL; } } entries = (CfsMapEntry *) palloc(nblocks * sizeof(CfsMapEntry)); run = cfs_gather_contiguous_run(cfs, entries, nblocks, blocknum); /* * Only a request that is one whole span can be offloaded: a partial * run would leave the remaining blocks to the caller, and the buffers * of one IO must never be written by both paths. */ if (run < nblocks) { pfree(entries); return CFS_READ_PLAN_DEGRADE; } /* * Row validation before anything else, mirroring * cfs_read_records_span(): a corrupted last-record size must not * drive an overlong span, and the failure stays attributed to the * exact block. */ for (b = 0; b < nblocks; b++) { const CfsMapEntry *e = &entries[b]; CfsFormatStatus fst = cfs_map_entry_validate(e, true); if (fst != CFS_FORMAT_OK || e->compressed_size > CFS_BLCKSZ) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: invalid page map entry for block %u " "(offset %llu, status %s)", blocknum + b, (unsigned long long) e->physical_offset, CfsFormatStatusString(fst)))); if (cfs->map == NULL) { cfs_stats_count_crc_failure(rl, forknum); cfs_map_segment_invalidate_block(rl, forknum, blocknum + b); } if (fail_code != NULL) *fail_code = CFS_STORAGE_CORRUPT; if (fail_block != NULL) *fail_block = blocknum + b; pfree(entries); return CFS_READ_PLAN_FAIL; } } span_off = entries[0].physical_offset; span_end = entries[nblocks - 1].physical_offset + CFS_RECORD_SIZE(entries[nblocks - 1].compressed_size); span_len = (size_t) (span_end - span_off); segno = CFS_CFP_SEGNO(span_off); /* Same segment-boundary rejection as cfs_read_records_span(). */ if (CFS_CFP_SEGNO(span_end - 1) != segno) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: record span at offset %llu crosses a segment boundary", (unsigned long long) span_off))); if (cfs->map == NULL) { cfs_stats_count_crc_failure(rl, forknum); cfs_map_segment_invalidate_block(rl, forknum, blocknum + nblocks - 1); } if (fail_code != NULL) *fail_code = CFS_STORAGE_CORRUPT; if (fail_block != NULL) *fail_block = blocknum + nblocks - 1; pfree(entries); return CFS_READ_PLAN_FAIL; } /* The span cannot outgrow the slot capacity (see cfs_read_span_capacity). */ if (span_len > cfs_read_span_capacity()) { pfree(entries); return CFS_READ_PLAN_DEGRADE; } fd = cfs_cfp_read_segment_fd(cfs, segno); if (fd < 0) { if (fd == -1) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: .cfp segment %u referenced by the map is missing", segno))); if (fail_code != NULL) *fail_code = CFS_STORAGE_CORRUPT; } else { ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not open .cfp segment %u for reading", segno))); if (fail_code != NULL) *fail_code = CFS_STORAGE_ERROR; } if (fail_block != NULL) *fail_block = blocknum; if (cfs->map == NULL) { cfs_stats_count_crc_failure(rl, forknum); cfs_map_segment_invalidate_block(rl, forknum, blocknum); } pfree(entries); return CFS_READ_PLAN_FAIL; } /* * Debug fault injection, mirroring cfs_read_records_span(): the * counter is spent on the span, so the offloaded and the inline read * paths fail deterministically under the same GUC. The failure is * reported through the inline code path (the owner backend raises * it); exercising a real preadv errno in the executor is the * recovery injection's job (aio-worker-after-reopen). */ if (cfs_debug_fail_read > 0) { cfs_debug_fail_read--; errno = EIO; ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not read %zu-byte record span at " "offset %llu from .cfp", span_len, (unsigned long long) span_off))); if (fail_code != NULL) *fail_code = CFS_STORAGE_ERROR; if (fail_block != NULL) *fail_block = blocknum; if (cfs->map == NULL) { cfs_stats_count_crc_failure(rl, forknum); cfs_map_segment_invalidate_block(rl, forknum, blocknum); } pfree(entries); return CFS_READ_PLAN_FAIL; } slot = cfs_read_scratch_acquire(); if (slot == NULL) { pfree(entries); return CFS_READ_PLAN_DEGRADE; } slot->pooled = (cfs->map == NULL); slot->span_len = (uint32) span_len; slot->plan_len = (uint32) nblocks; for (b = 0; b < nblocks; b++) { CfsReadPlanEntry *pe = &slot->entries[b]; pe->rec_off = (uint32) (entries[b].physical_offset - span_off); pe->payload = entries[b].compressed_size; pe->buf_off = (uint8) b; pe->flags = 0; } pfree(entries); *out_slot = slot; *out_fd = fd; *out_span_off = span_off; return CFS_READ_PLAN_OK; } int cfs_read_page_cached(CfsRelation *cfs, BlockNumber blocknum, char *dst) { RelFileLocatorBackend rl; ForkNumber forknum; CfsMapEntry entry; uint64 seg_gen = 0; bool have_entry; bool ensured; int sync_rc; int ensure_rc; int attempt; uint32 save_holdoff; uint32 save_crit_section; Assert(cfs != NULL && dst != NULL); rl = cfs->rlocator; forknum = cfs->forknum; /* * A full handle carries its own private map (cfs_map_memory=0, * compaction, the checkpoint snapshot writer, tests) and resolves every * read through it, exactly like before the segment pool; the steps below * only serve lazy (pool-backed) handles. * * The private map is a cache: another backend may have appended journal * records (including updates of blocks this map already holds) since it * was last synced. Probe the journal cheaply and refresh under the same * lock writers use, exactly as the base branch did before the segment * pool moved reads to shared memory. */ if (cfs->map != NULL) { if (cfs_map_needs_refresh(cfs)) { int refresh_rc = CFS_STORAGE_OK; /* * The READ context defers row-level corruption: the refresh * returns CORRUPT instead and the smgr report path re-reports it * centrally. Structural failures (corrupt prologue or journal * header) still raise ERROR here. That is safe inside * cfs_smgr_startreadv(): its PG_TRY/PG_CATCH converts the ERROR * into the inline AIO failure code, which aio_cfs_readv_report() * later raises to the caller. The append lock is released on * both paths; see the catch below for the interrupt-holdoff * subtlety. */ cfs_append_lock_acquire(rl, forknum, LW_SHARED); PG_TRY(); { refresh_rc = cfs_refresh_map(cfs, true, CFS_LOAD_READ); } PG_CATCH(); { /* * errfinish() resets InterruptHoldoffCount to zero on ERROR * (elog.c), so the RESUME_INTERRUPTS() inside LWLockRelease * would assert even though the lock is still held. Put the * holdoff back for the release, then rethrow: the caller * (cfs_smgr_startreadv) is the one that converts the error * into an AIO failure. A plain PG_FINALLY release cannot be * used here for exactly this reason. */ HOLD_INTERRUPTS(); cfs_append_lock_release(rl, forknum); PG_RE_THROW(); } PG_END_TRY(); cfs_append_lock_release(rl, forknum); if (refresh_rc != CFS_STORAGE_OK) return refresh_rc; } return cfs_read_page(cfs, blocknum, dst); } /* * Step 1: the shared segment pool. On a hit the entry was published * either by a writer (under the append lock, right after journaling) or * by a delta replay; its offset is safe to read without any CFS lock * because .cfp is append-only — provided the entry belongs to the * sidecar pair this handle's descriptors point at. The segment tag (the * relation map generation of its offsets) tells them apart: a compaction * or truncate bumps the generation AND drops every segment of the * relation, so a tagged disagreement means the handle is stale — reopen * it and re-lookup before reading. */ have_entry = cfs_shared_map_lookup(rl, forknum, blocknum, &entry, &seg_gen); if (have_entry && !cfs_seg_tag_matches(seg_gen, cfs)) { cfs_append_lock_acquire(rl, forknum, LW_SHARED); save_holdoff = InterruptHoldoffCount; save_crit_section = CritSectionCount; PG_TRY(); { cfs_handle_refresh_if_stale(cfs); } PG_CATCH(); { /* * A reopen inside the refresh can raise on structural map * corruption. Restore the counters errfinish() zeroed, release * the append lock, and let the caller convert the error. */ InterruptHoldoffCount = save_holdoff; CritSectionCount = save_crit_section; cfs_append_lock_release(rl, forknum); PG_RE_THROW(); } PG_END_TRY(); cfs_append_lock_release(rl, forknum); have_entry = cfs_shared_map_lookup(rl, forknum, blocknum, &entry, &seg_gen); } if (have_entry && cfs_seg_tag_matches(seg_gen, cfs)) return cfs_read_entry_record(cfs, blocknum, &entry, dst); /* * A lookup that still misses (or whose tag still disagrees after the * reopen — a second compaction raced it) falls through to the miss * path, which re-resolves everything from disk. */ /* * Step 2: miss. Under the append lock (shared): reopen a stale handle * (compaction swap), make the segment resident from the .cfsmap snapshot * and replay the journal delta into it. The lock guarantees the journal * records we replay are fully written (a peer mid-append holds the * exclusive mode); replay stops before its torn record. * * The 768 kB snapshot read therefore happens while the relation's writers * wait for the shared append lock. That is a deliberate trade-off rather * than an oversight: the lock is exactly what makes the snapshot and the * journal a consistent pair (both are rewritten only under the exclusive * mode), and an optimistic load-then-revalidate would need an identity * check of the snapshot file plus a retry loop for a case that only * occurs when the pool must load a segment anyway. The one-time journal * scan in cfs_map_cache_next_generation() follows the same reasoning. */ for (attempt = 0; attempt < 2; attempt++) { cfs_append_lock_acquire(rl, forknum, LW_SHARED); save_holdoff = InterruptHoldoffCount; save_crit_section = CritSectionCount; PG_TRY(); { cfs_handle_refresh_if_stale(cfs); ensure_rc = cfs_shared_map_ensure(cfs, blocknum); sync_rc = (ensure_rc == CFS_STORAGE_OK) ? cfs_shared_map_sync_segment(cfs, blocknum, NULL) : 0; } PG_CATCH(); { /* * ensure/sync raise on structural map or journal corruption. * Restore the counters errfinish() zeroed, release the append * lock, and rethrow so cfs_smgr_startreadv() turns it into an AIO * failure instead of leaking the lock into the transaction. */ InterruptHoldoffCount = save_holdoff; CritSectionCount = save_crit_section; cfs_append_lock_release(rl, forknum); PG_RE_THROW(); } PG_END_TRY(); cfs_append_lock_release(rl, forknum); /* * Unhealed corruption (a map row that failed its entry_crc with no * covering journal record) is returned, not raised: the read path may * run inside an AIO callback, and the caller reports it centrally * through cfs_checksum_failure. Structural errors do raise, but the * catch above has already released the append lock, so a producer is * never left waiting on it. */ if (ensure_rc == CFS_STORAGE_CORRUPT || sync_rc == CFS_STORAGE_CORRUPT) return CFS_STORAGE_CORRUPT; ensured = (ensure_rc == CFS_STORAGE_OK); /* Step 3: re-lookup; a resident VALID entry now resolves the read. */ if (cfs_shared_map_lookup(rl, forknum, blocknum, &entry, &seg_gen) && cfs_seg_tag_matches(seg_gen, cfs)) return cfs_read_entry_record(cfs, blocknum, &entry, dst); /* * Step 4: no entry exists — or the pool could not make the segment * resident. An unavailable segment is a resource shortage, not a * reason to fail: the authoritative on-disk state still holds the * data, so degrade to a one-segment scratch read and account for it. * Only when even that path fails does the pool-exhaustion error * stand. * * A zero page must never be fabricated here: the authoritative * conclusion below is only drawn when the segment was actually made * resident and the journal replayed into it. */ if (!ensured) { int rc; pg_atomic_fetch_add_u64(&cfs_control->map_fallback_reads, 1); rc = cfs_read_page_authoritative(cfs, blocknum, dst); if (rc == CFS_STORAGE_OK || rc == CFS_STORAGE_CORRUPT) return rc; ereport(ERROR, (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED), errmsg("CFS: could not load the block map segment for block " "%u of relation %u/%u/%u", blocknum, rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber), errdetail("The shared block-map pool has no free or evictable segment, " "and the authoritative map could not serve the read."), errhint("Increase \"cfs_map_memory\"."))); } /* * Mid-journal corruption is real and stays fatal (the replay has * already reported it): the segment must not be published as * journal_synced, and no fallback may paper over a corrupt map. */ if (sync_rc < 0) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not replay the journal into the block map " "segment for block %u of relation %u/%u/%u", blocknum, rl.locator.spcOid, rl.locator.dbOid, rl.locator.relNumber))); /* * An INVALID slot is only evidence of "never written" when the * segment is the current map incarnation, snapshot-loaded and fully * caught up with the journal: then it is an extension gap. Otherwise * the segment may be stale or freshly evicted and reloaded by a * competitor — retry once, and after the retry degrade to the * authoritative fallback instead of failing: with segments now * evictable a small pool under a parallel scan can lose that race * repeatedly, while the on-disk state still holds the data (and never * yields a fabricated zero). */ if (!cfs_shared_map_segment_authoritative(rl, forknum, blocknum, cfs->open_generation)) { if (attempt == 0) continue; pg_atomic_fetch_add_u64(&cfs_control->map_fallback_reads, 1); return cfs_read_page_authoritative(cfs, blocknum, dst); } /* * Inside the logical size an unwritten block is an extension gap: * return a zero page. Beyond it, the read is out of range exactly * like the authoritative map path. */ return cfs_read_extension_gap(cfs, blocknum, dst); } return CFS_STORAGE_ERROR; } int cfs_write_page_cached(CfsRelation *cfs, BlockNumber blocknum, const char *src, const CfsWriteOptions *opts) { RelFileLocatorBackend rl; ForkNumber forknum; CfsCompressResult cres; CfsMapEntry new_entry; int rc; Assert(cfs != NULL && src != NULL && opts != NULL); rl = cfs->rlocator; forknum = cfs->forknum; /* * Step 1: compress the page into the per-handle scratch buffer *before* * acquiring the per-relation append lock. * * Compression is the most expensive part of the write path (tens of ms * for high zstd levels) and is fully self-contained: the compressed * record depends only on the source page and the compression options, not * on the append offset or the map state. Performing it outside the lock * lets concurrent writers of the same relation compress in parallel on * different CPU cores, so single-relation write throughput scales with * the number of backends instead of being capped at one core. * * The scratch buffer is per-CfsRelation (per-backend handle) and is not * reallocated by cfs_reopen(), so the compressed blob stays valid even * when cfs_handle_refresh_if_stale() swaps the sidecar files under us * while we wait for the lock. */ if (cfs_compress_page(cfs, src, CFS_BLCKSZ, opts, &cres) != CFS_STORAGE_OK) return CFS_STORAGE_ERROR; /* * Step 2: under the per-relation append lock, append the pre-compressed * record, journal the update and refresh the local in-memory map. Only * the offset computation + pwrite + journal append + map/cache update * remain inside the critical section — the operations that actually * need serialisation to avoid two backends computing the same append * offset. */ cfs_append_lock_acquire(rl, forknum, LW_EXCLUSIVE); /* * A compaction may have swapped the sidecar files while we waited for the * append lock; reopen the handle if its generation is stale. cfs_reopen() * reloads the map and re-derives the append cursor but does not touch the * compression scratch, so the compressed blob prepared above is still * valid for the pwrite. */ cfs_handle_refresh_if_stale(cfs); /* * Derive the new generation under the append lock. The generation is * relation-wide, so it no longer needs the old entry — and therefore no * longer ensures or replicates the segment (that forced a journal replay * of the whole segment on the write path after every eviction). Dead * accounting is exact and lives at the checkpoint: the fold sees every * superseded row since the last reset, so the write path counts nothing * here. */ { uint32 generation = cfs_map_cache_next_generation(cfs); rc = cfs_write_compressed_page(cfs, blocknum, &cres, opts, generation, &new_entry); } /* * Step 3: publish the new entry into the shared segment pool while the * append lock is still held: the lock serialises against the compactor, * which invalidates the relation's segments right after swapping the * sidecars, so a store racing a compaction is either dropped by the * segment-key validation or lands in a segment the compaction already * dropped — never into the new pair. Only the cheap store happens * here, no I/O. */ if (rc == CFS_STORAGE_OK) { if (!cfs_shared_map_store(rl, forknum, blocknum, &new_entry, cfs->open_generation)) { /* * The store failed (all segments pinned, or a lost race): drop * any older resident entry of the block so no reader is served a * superseded version — the authoritative miss path re-resolves * the block from the journal on the next lookup. */ cfs_map_segment_invalidate_block(rl, forknum, blocknum); } cfs_stats_count_write(rl, forknum, new_entry.compressed_size, cres.is_raw); } cfs_append_lock_release(rl, forknum); if (rc != CFS_STORAGE_OK) return rc; /* * Register the dirtied sidecar files (.cfp first, then .cfsjrn) with the * checkpointer sync queue. This deliberately happens OUTSIDE the append * lock: when the queue is full, RegisterSyncRequest() returns false and * cfs_register_dirty_file() falls back to a synchronous local fsync of * the whole segment chain — holding the append lock through that would * park every writer of the relation behind the fsync. md.c makes the * same choice: register_dirty_segment() performs its fallback fsync * without any relation-level lock. * * A bulk write (skip_fsync, e.g. CREATE INDEX / CLUSTER / * RelationCopyStorage) skips this exactly like md.c skips * register_dirty_segment() when skipFsync is true; it registers or syncs * the files once at the end of the operation instead (smgrregistersync() * / smgrimmedsync()). * * Doing this before the metadata refresh below is safe in both * directions: if the refresh errored out, the request is merely a * redundant fsync that the transaction abort makes harmless, while * registering after a potential failure point could lose it. And a * checkpoint that sneaks in before the request is absorbed still syncs * the sidecars through the dirty_checkpoint mark set below, so durability * never depends on this queue entry. */ if (!opts->skip_fsync) { cfs_register_dirty_file(rl, forknum, CFS_FILE_DATA); cfs_register_dirty_file(rl, forknum, CFS_FILE_JOURNAL); } /* * Step 4: refresh the cached relation metadata. Only a genuine extension * changes the logical size; a plain overwrite (bgwriter or checkpoint * flush) says nothing about it, and a lazy handle's local nblocks is a * stale snapshot value. Publishing it here is what used to resurrect the * pre-VACUUM size after an in-place truncate. Both helpers mark the slot * dirty_checkpoint so the checkpointer fsyncs and snapshots the sidecars. */ if (opts->is_extend) cfs_map_cache_set_meta(rl, forknum, (uint64) blocknum + 1); else cfs_map_cache_mark_dirty(rl, forknum); return CFS_STORAGE_OK; }