/*------------------------------------------------------------------------- * cfs_stats.c * Per-relation CFS statistics: the shared slots, their counters, the * snapshot/enumeration API, and the pg_cfs_stats statsfile * (save at shutdown, restore at startup). A leaf module: it touches * no other CFS layer. Dead space has a single publisher, the * checkpoint (which is also the one that truncates the dropped rows * off the map file, so it sees their payloads); compaction resets * the counters with its exact recomputation. * * Locking model (QDB-1516 Д3): the counters are pg_atomic_uint64. * Accounting events take the partition lock in LW_SHARED mode, find * the slot through its hash chain and bump the counters with * pg_atomic_fetch_add_u64(); only a miss upgrades to LW_EXCLUSIVE * (release, re-acquire, re-find) to create the slot. Creation, * eviction, reset and the wholesale publications after a fold or * compaction always run under LW_EXCLUSIVE. * * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group * Portions Copyright (c) 2026, Diasoft * * src/backend/storage/cfs/cfs_stats.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include #include "miscadmin.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_cfp.h" #include "storage/cfs/cfs_guc.h" #include "storage/cfs/cfs_shmem.h" #include "storage/cfs/cfs_shmem_internal.h" #include "storage/cfs/cfs_stats.h" #include "storage/fd.h" #include "storage/shmem.h" #include "utils/timestamp.h" #include "utils/palloc.h" #include "utils/memutils.h" #include "utils/guc.h" /* * Partition locks, the flat slot array, the per-partition bucket heads and * the stats-domain access clock (allocated in cfs_stats_shmem_init). The * slot count is the cfs_stats_slots_per_partition GUC (frozen in * cfs_control->stats_slots_per_part), so the array is indexed through * cfs_stats_slot(), not with a compile-time second dimension. */ static LWLockPadded *cfs_stats_locks = NULL; static CfsRelationStats *cfs_stats_slots = NULL; static int32 *cfs_stats_bucket_heads = NULL; pg_atomic_uint64 *cfs_stats_clocks = NULL; /* Index the flat statistics slot array by (partition, slot). */ static inline CfsRelationStats * cfs_stats_slot(int part, int i) { return &cfs_stats_slots[part * cfs_stats_slots_per_partition + i]; } /* * Initialise every counter of a freshly claimed (zeroed) slot to zero. * Called on the first-boot zeroing pass and whenever a slot is claimed * (fresh or evicted): pg_atomic_init_u64 is legal here because the caller * either just cleared the memory or runs before any concurrent access. */ static void cfs_stats_counters_init(CfsRelationStats *s) { pg_atomic_init_u64(&s->logical_pages, 0); pg_atomic_init_u64(&s->compressed_bytes, 0); pg_atomic_init_u64(&s->raw_bytes, 0); pg_atomic_init_u64(&s->dead_bytes, 0); pg_atomic_init_u64(&s->dead_pages, 0); pg_atomic_init_u64(&s->checkpoint_map_rows_written, 0); pg_atomic_init_u64(&s->compressed_pages, 0); pg_atomic_init_u64(&s->uncompressed_pages, 0); pg_atomic_init_u64(&s->read_count, 0); pg_atomic_init_u64(&s->read_batch_count, 0); pg_atomic_init_u64(&s->read_batched_pages, 0); pg_atomic_init_u64(&s->read_fallback_pages, 0); pg_atomic_init_u64(&s->write_count, 0); pg_atomic_init_u64(&s->compress_count, 0); pg_atomic_init_u64(&s->decompress_count, 0); pg_atomic_init_u64(&s->crc_failures, 0); } /* * cfs_stats_clock_tick — advance and return the stats-domain access clock * of a partition (QDB-1516 Д1). Unlike the map domain, the accounting * paths tick the clock while holding the partition lock only in * LW_SHARED mode, so two backends may tick the same partition * concurrently: the cells are atomic and the tick is an atomic * fetch-add — the acceptable per-partition RMW, in exchange for keeping * the whole accounting path free of exclusive locks. The caller must * hold the partition lock in some mode. */ uint64 cfs_stats_clock_tick(int part) { Assert(cfs_stats_clocks != NULL); Assert(LWLockHeldByMe(&cfs_stats_locks[part].lock)); return pg_atomic_fetch_add_u64(&cfs_stats_clocks[part], 1) + 1; } /* * cfs_stats_shmem_init — allocate the statistics locks, slots, chain * heads and access clock. Called by CfsShmemInit(); the tranche id comes * from the control block the caller owns. */ void cfs_stats_shmem_init(void) { Size slots_size; Size heads_size; bool found; int i; /* * The slot count is frozen in the control block by the postmaster. A * process attaching to already allocated shared memory (EXEC_BACKEND * children) re-parses its own configuration: a different value here * means the arrays were laid out for another count, and indexing them * would corrupt shared memory — refuse to start instead (the * cfs_map_cache_rels_per_partition overflow-hint style). */ if (cfs_control->stats_slots_per_part != cfs_stats_slots_per_partition) ereport(ERROR, (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED), errmsg("CFS: statistics slots per partition mismatch"), errdetail("Shared memory holds %d statistics slots per " "partition, but this process is configured " "with %d.", cfs_control->stats_slots_per_part, cfs_stats_slots_per_partition), errhint("Check the configuration parameter " "\"cfs_stats_slots_per_partition\" and restart " "the server with the value it was started " "with."))); cfs_stats_locks = ShmemInitStruct("CFS Stats 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_stats_locks[i].lock, cfs_control->stats_tranche_id); } /* * Stats-domain per-partition access clock: its own CACHELINEALIGN-ed * allocation keeps the clock off the partition locks' cache lines; the * atomic cells are updated under the partition lock in either mode * (see cfs_stats_clock_tick). */ cfs_stats_clocks = ShmemInitStruct("CFS Stats Clocks", CACHELINEALIGN((Size) CFS_MAP_CACHE_NUM_PARTITIONS * sizeof(pg_atomic_uint64)), &found); if (!found) { for (i = 0; i < CFS_MAP_CACHE_NUM_PARTITIONS; i++) pg_atomic_init_u64(&cfs_stats_clocks[i], 0); } slots_size = mul_size(sizeof(CfsRelationStats), mul_size(CFS_MAP_CACHE_NUM_PARTITIONS, cfs_stats_slots_per_partition)); cfs_stats_slots = ShmemInitStruct("CFS Stats", slots_size, &found); if (!found) { MemSet(cfs_stats_slots, 0, slots_size); for (i = 0; i < CFS_MAP_CACHE_NUM_PARTITIONS * cfs_stats_slots_per_partition; i++) cfs_stats_counters_init(&cfs_stats_slots[i]); } /* * Bucket heads of the statistics hash chains (QDB-1516 Д2): all heads * start empty (-1), matching the zeroed (all-free) slot array. */ heads_size = mul_size(sizeof(int32), mul_size(CFS_MAP_CACHE_NUM_PARTITIONS, cfs_stats_slots_per_partition)); cfs_stats_bucket_heads = ShmemInitStruct("CFS Stats Buckets", heads_size, &found); if (!found) MemSet(cfs_stats_bucket_heads, 0xFF, heads_size); } /* ================================================================ * Per-partition hash chains over the statistics 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 partition is selected by the * low CFS_PART_BITS bits of rel_hash; the multiply (Knuth's 2654435761) * folds those partition bits — and every other input bit — into the bits * above the shift, so the choice of chain is decorrelated from the choice * of partition (mirrors cfs_meta_bucket() in cfs_shmem.c). */ static inline int cfs_stats_bucket(uint32 rel_hash) { uint32 b = rel_hash * 2654435761U; return (int) ((b >> CFS_PART_BITS) % (uint32) cfs_stats_slots_per_partition); } /* The bucket-head cell (part, bucket) of the statistics chains. */ static inline int32 * cfs_stats_head(int part, int bucket) { return &cfs_stats_bucket_heads[part * cfs_stats_slots_per_partition + bucket]; } /* Partition-relative index of a statistics slot. */ static inline int cfs_stats_slot_index(int part, const CfsRelationStats *slot) { return (int) (slot - &cfs_stats_slots[part * cfs_stats_slots_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_stats_chain_link(int part, CfsRelationStats *slot) { int bucket = cfs_stats_bucket(slot->hash); int32 *head = cfs_stats_head(part, bucket); slot->chain_next = *head; *head = cfs_stats_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_stats_chain_unlink(int part, CfsRelationStats *slot) { int idx = cfs_stats_slot_index(part, slot); int bucket = cfs_stats_bucket(slot->hash); int32 *head = cfs_stats_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: statistics slot %d not found in its " "hash chain", idx); prev = cur; cur = cfs_stats_slot(part, cur)->chain_next; } if (prev == -1) *head = slot->chain_next; else cfs_stats_slot(part, prev)->chain_next = slot->chain_next; } /* * Locate the statistics slot of a relation by walking its hash chain. * The caller must hold the partition lock selected by rel_hash in either * mode. Returns NULL when none exists. */ static CfsRelationStats * cfs_stats_find(uint32 rel_hash, RelFileLocatorBackend rlocator, ForkNumber forknum) { int part = rel_hash & CFS_PART_MASK; int bucket = cfs_stats_bucket(rel_hash); int cur; Assert(LWLockHeldByMe(&cfs_stats_locks[part].lock)); for (cur = *cfs_stats_head(part, bucket); cur != -1;) { CfsRelationStats *s = cfs_stats_slot(part, cur); int next = s->chain_next; if (s->hash == rel_hash && cfs_rlbe_eq(s->rlocator, rlocator) && s->forknum == forknum) return s; cur = next; } return NULL; } /* * Find or create a statistics slot. The caller must hold the lock of the * partition selected by rel_hash in LW_EXCLUSIVE mode. * * Creation order (QDB-1516 Д2, mirrors cfs_meta_get_or_create): the key's * own chain is searched first; on a miss the first free slot (hash == 0) * is taken by a plain scan, and only when no free slot remains is the LRU * victim (smallest access_clock) chosen by a full partition scan and * unlinked from its chain BEFORE the clear (I3). A claimed slot is * linked at the head of its bucket. Returns NULL only when the partition * holds no slot at all (impossible with the GUC minimum of 4). */ static CfsRelationStats * cfs_stats_get_or_create(uint32 rel_hash, RelFileLocatorBackend rlocator, ForkNumber forknum) { int part = rel_hash & CFS_PART_MASK; int bucket = cfs_stats_bucket(rel_hash); CfsRelationStats *free_slot = NULL; CfsRelationStats *victim = NULL; uint64 min_clock = PG_UINT64_MAX; int i; int cur; Assert(LWLockHeldByMeInMode(&cfs_stats_locks[part].lock, LW_EXCLUSIVE)); /* Search the key's own chain (the hit path of the partition). */ for (cur = *cfs_stats_head(part, bucket); cur != -1;) { CfsRelationStats *s = cfs_stats_slot(part, cur); int next = s->chain_next; if (s->hash == rel_hash && cfs_rlbe_eq(s->rlocator, rlocator) && s->forknum == forknum) return s; cur = next; } /* Miss: take the first free slot of the partition. */ for (i = 0; i < cfs_stats_slots_per_partition; i++) { CfsRelationStats *s = cfs_stats_slot(part, i); if (s->hash == 0) { free_slot = s; break; } } /* No free slot: LRU victim among the occupied slots, full scan. */ if (free_slot == NULL) { for (i = 0; i < cfs_stats_slots_per_partition; i++) { CfsRelationStats *s = cfs_stats_slot(part, i); if (s->hash != 0 && s->access_clock < min_clock) { min_clock = s->access_clock; victim = s; } } free_slot = victim; if (free_slot != NULL) { pg_atomic_fetch_add_u64(&cfs_control->evictions, 1); cfs_stats_chain_unlink(part, free_slot); MemSet(free_slot, 0, sizeof(CfsRelationStats)); cfs_stats_counters_init(free_slot); } } if (free_slot == NULL) return NULL; free_slot->hash = rel_hash; free_slot->rlocator = rlocator; free_slot->forknum = forknum; free_slot->access_clock = cfs_stats_clock_tick(part); /* * QDB-1507 U1: a slot claimed while the crash-boot sweep is still * pending starts stale - its zeroed counters know nothing about * the dead space accumulated before the crash, exactly like a * restored value, so the first measurement resyncs it from the * map. The owners that publish right after claiming (set_dead, * note_compaction, resync_dead) clear the mark under the same * exclusive partition lock they already hold here, so the * created -> published -> stale = false order is preserved. */ if (cfs_control->stats_boot_stale) free_slot->stale = true; /* Insert the claimed slot at the head of its bucket chain (I2). */ cfs_stats_chain_link(part, free_slot); return free_slot; } /* * Find or create the statistics slot for an accounting event (QDB-1516 * Д3). The fast path holds the partition lock in LW_SHARED mode: the * counters are atomics and the slot pointer stays valid for the whole * critical section, because evicting or clearing the slot requires * LW_EXCLUSIVE of the same partition. Only a miss upgrades: release the * shared lock, take the exclusive one and re-find through * cfs_stats_get_or_create, so a slot created by a concurrent backend in * between is reused rather than duplicated. On return the lock is held * in *mode and the caller must release it with that mode. */ static CfsRelationStats * cfs_stats_find_or_create_locked(uint32 rel_hash, RelFileLocatorBackend rlocator, ForkNumber forknum, LWLockMode *mode) { int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; LWLockAcquire(&cfs_stats_locks[part].lock, LW_SHARED); s = cfs_stats_find(rel_hash, rlocator, forknum); if (s != NULL) { *mode = LW_SHARED; return s; } LWLockRelease(&cfs_stats_locks[part].lock); LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE); *mode = LW_EXCLUSIVE; return cfs_stats_get_or_create(rel_hash, rlocator, forknum); } /* * Touch the slot's LRU clock. A plain field write is enough here: the * value only orders eviction, and its only readers (victim scans) run * under LW_EXCLUSIVE. Two backends accounting the same relation under * LW_SHARED may race the store - one of their ticks is lost, which can * reorder the LRU by a single tick but never loses a relation or mixes * counters. */ static inline void cfs_stats_touch(int part, CfsRelationStats *s) { s->access_clock = cfs_stats_clock_tick(part); } void cfs_stats_count_read(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 compressed_bytes) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; LWLockMode mode; s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode); if (s != NULL) { pg_atomic_fetch_add_u64(&s->read_count, 1); pg_atomic_fetch_add_u64(&s->decompress_count, 1); cfs_stats_touch(part, s); } LWLockRelease(&cfs_stats_locks[part].lock); } /* * Batched-read accounting, see cfs_stats.h. Both counters share the same * partition lock pattern as cfs_stats_count_read(); they run after the * read itself succeeded, so no accounting happens for failed reads. */ void cfs_stats_count_read_span(RelFileLocatorBackend rlocator, ForkNumber forknum, uint32 npages) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; LWLockMode mode; s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode); if (s != NULL) { pg_atomic_fetch_add_u64(&s->read_batch_count, 1); pg_atomic_fetch_add_u64(&s->read_batched_pages, npages); cfs_stats_touch(part, s); } LWLockRelease(&cfs_stats_locks[part].lock); } void cfs_stats_count_read_fallback(RelFileLocatorBackend rlocator, ForkNumber forknum, uint32 npages) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; LWLockMode mode; s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode); if (s != NULL) { pg_atomic_fetch_add_u64(&s->read_fallback_pages, npages); cfs_stats_touch(part, s); } LWLockRelease(&cfs_stats_locks[part].lock); } void cfs_stats_count_write(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 compressed_bytes, bool is_raw) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; LWLockMode mode; s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode); if (s != NULL) { pg_atomic_fetch_add_u64(&s->write_count, 1); pg_atomic_fetch_add_u64(&s->compress_count, 1); if (is_raw) { pg_atomic_fetch_add_u64(&s->raw_bytes, compressed_bytes); pg_atomic_fetch_add_u64(&s->uncompressed_pages, 1); } else { pg_atomic_fetch_add_u64(&s->compressed_bytes, compressed_bytes); pg_atomic_fetch_add_u64(&s->compressed_pages, 1); } cfs_stats_touch(part, s); } LWLockRelease(&cfs_stats_locks[part].lock); } /* * cfs_stats_note_logical_pages — the logical-size high-water mark: only * grows, never shrinks (a truncate is accounted separately by the * caller). Split out of cfs_map_cache_set_meta so the slot array stays * private to this module. The read-modify-write "grow only" comparison * is not commutative, so this stays on the exclusive path. */ void cfs_stats_note_logical_pages(uint32 rel_hash, RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 nblocks) { CfsRelationStats *s2; int spart = rel_hash & CFS_PART_MASK; LWLockAcquire(&cfs_stats_locks[spart].lock, LW_EXCLUSIVE); s2 = cfs_stats_get_or_create(rel_hash, rlocator, forknum); if (s2 != NULL) { if (nblocks > pg_atomic_read_u64(&s2->logical_pages)) pg_atomic_write_u64(&s2->logical_pages, nblocks); cfs_stats_touch(spart, s2); } LWLockRelease(&cfs_stats_locks[spart].lock); } void cfs_stats_set_dead(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 dead_bytes, uint64 dead_pages_add) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE); s = cfs_stats_get_or_create(rel_hash, rlocator, forknum); if (s != NULL) { /* * dead_bytes is set wholesale by its owner: the checkpoint publishes * the previous value plus its fold's delta (superseded payloads and, * in the crash-recovery window, truncated ones), and compaction - * which walks the live rows - publishes the exact recomputation. * dead_pages accumulates the checkpoint deltas: the folds' * supersession counts plus the rows the truncating RESIZE dropped (no * other source exists, so the counter reads "superseded page versions * and dropped truncation rows since the last compaction or reset"). */ pg_atomic_write_u64(&s->dead_bytes, dead_bytes); pg_atomic_fetch_add_u64(&s->dead_pages, dead_pages_add); /* * The owner's publication makes the restored value current, so * the crash-boot resync must not overwrite it (QDB-1507 U1). */ s->stale = false; cfs_stats_touch(part, s); } LWLockRelease(&cfs_stats_locks[part].lock); } void cfs_stats_count_checkpoint_rows(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 nrows) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; LWLockMode mode; s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode); if (s != NULL) { pg_atomic_fetch_add_u64(&s->checkpoint_map_rows_written, nrows); cfs_stats_touch(part, s); } LWLockRelease(&cfs_stats_locks[part].lock); } void cfs_stats_note_compaction(RelFileLocatorBackend rlocator, ForkNumber forknum, int64 ts) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE); s = cfs_stats_get_or_create(rel_hash, rlocator, forknum); if (s != NULL) { s->last_compaction = ts; pg_atomic_write_u64(&s->dead_bytes, 0); pg_atomic_write_u64(&s->dead_pages, 0); /* * Compaction publishes its exact recomputation (QDB-1507 U1). */ s->stale = false; cfs_stats_touch(part, s); } LWLockRelease(&cfs_stats_locks[part].lock); } /* * QDB-1507 U1: the crash-boot resync marker - an empty file whose * presence is the signal. Written at a clean shutdown that overtook * the still-pending sweep; unlinked only when the sweep retires * (cfs_stats_boot_sweep_done), never at boot, so an interrupted * start loses nothing. */ #define CFS_STATS_SWEEP_PENDING_FILENAME "pg_cfs_stats_resync" /* * cfs_stats_slot_stale - does the slot's dead_bytes predate the last * crash? The slot is looked up under the partition's shared lock and * is never created here; a missing slot reports false (the callers * decide separately what a missing entry means: the crash-boot sweep * resyncs unconditionally, the checkpoint samples its base from the * map). */ bool cfs_stats_slot_stale(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; bool stale = false; LWLockAcquire(&cfs_stats_locks[part].lock, LW_SHARED); s = cfs_stats_find(rel_hash, rlocator, forknum); if (s != NULL) stale = s->stale; LWLockRelease(&cfs_stats_locks[part].lock); return stale; } /* * cfs_stats_resync_dead - publish a map-derived dead_bytes into a * stale slot. When the slot is missing and create_slot is set, the * slot is created and the value is published unconditionally (a fresh * slot has no owner to race with). An existing stale slot takes the * value and loses the stale mark; an existing non-stale slot keeps its * value - the conditional publication prevents a stale resync scan * from regressing a newer owner's exact value (a checkpoint's or a * compaction's). Returns true when this call published the value. */ bool cfs_stats_resync_dead(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 dead_bytes, bool create_slot) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; bool created = false; bool published = false; LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE); s = cfs_stats_find(rel_hash, rlocator, forknum); if (s == NULL && create_slot) { s = cfs_stats_get_or_create(rel_hash, rlocator, forknum); created = (s != NULL); } if (s != NULL && (created || s->stale)) { pg_atomic_write_u64(&s->dead_bytes, dead_bytes); s->stale = false; cfs_stats_touch(part, s); published = true; } LWLockRelease(&cfs_stats_locks[part].lock); return published; } /* * cfs_stats_forget_stale_flags - clear the stale mark of every * occupied slot. Called at a clean boot: the persisted values were * written at the clean shutdown that produced them, so they stay * authoritative and no map resync must run on a clean start * (QDB-1507 U1). */ void cfs_stats_forget_stale_flags(void) { int p; int i; for (p = 0; p < CFS_MAP_CACHE_NUM_PARTITIONS; p++) { LWLockAcquire(&cfs_stats_locks[p].lock, LW_EXCLUSIVE); for (i = 0; i < cfs_stats_slots_per_partition; i++) { CfsRelationStats *s = cfs_stats_slot(p, i); if (s->hash != 0) s->stale = false; } LWLockRelease(&cfs_stats_locks[p].lock); } } /* * cfs_stats_boot_after_crash - arm the one dead-space resync pass of * the first full background worker cycle after a crash boot (the * restored counters predate the crash; QDB-1507 U1). The sweep is * also armed at a clean boot that found the persistent resync marker * (cfs_stats_boot_restore_marker): a clean shutdown overtook it, and * the persisted values are equally unresynced. */ void cfs_stats_boot_after_crash(void) { cfs_control->stats_boot_stale = true; } /* * cfs_stats_boot_sweep_pending - is the crash-boot resync pass still * ahead (QDB-1507 U1)? Read by StartupXLOG to decide whether a * clean boot may declare the restored values authoritative, by the * statsfile writer to decide whether the resync marker must persist, * and by the background worker to gate the sweep. */ bool cfs_stats_boot_sweep_pending(void) { return cfs_control->stats_boot_stale; } /* * cfs_stats_boot_sweep_done - retire the crash-boot resync pass after * the first complete launcher cycle (every database serviced, no * pause, no early exit); relations the sweep could not heal keep * their stale slots and are resynced by their next checkpoint's * map-based base instead (QDB-1507 U1). * * The durable marker is removed HERE, not at the boot that armed the * sweep: removing it at boot would leave a start killed before the * first full cycle (whose control file may still read as a clean * shutdown) with no carrier of the obligation at all. The unlink * runs before the shared flag clears, and a non-ENOENT failure keeps * the flag armed, so the next full cycle retries the retirement; * ENOENT is the norm - a crash boot never wrote the marker at all. */ void cfs_stats_boot_sweep_done(void) { char *markerfile; if (!cfs_control->stats_boot_stale) return; markerfile = psprintf("%s/%s", DataDir, CFS_STATS_SWEEP_PENDING_FILENAME); if (unlink(markerfile) != 0 && errno != ENOENT) { ereport(LOG, (errcode_for_file_access(), errmsg("CFS: could not remove statistics resync " "marker \"%s\": %m", markerfile))); pfree(markerfile); return; } pfree(markerfile); cfs_control->stats_boot_stale = false; } void cfs_stats_count_crc_failure(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; LWLockMode mode; s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode); if (s != NULL) { pg_atomic_fetch_add_u64(&s->crc_failures, 1); cfs_stats_touch(part, s); } LWLockRelease(&cfs_stats_locks[part].lock); } /* * Copy the counters of one slot into a snapshot. Each counter is read * atomically, so every single value is consistent; cross-counter * consistency of the whole snapshot is not guaranteed (the pgstat * approximation). The caller holds the partition lock (either mode). */ static void cfs_stats_snapshot_copy(CfsRelationStats *s, CfsStatsSnapshot *out) { out->found = true; out->logical_pages = pg_atomic_read_u64(&s->logical_pages); out->compressed_bytes = pg_atomic_read_u64(&s->compressed_bytes); out->raw_bytes = pg_atomic_read_u64(&s->raw_bytes); out->dead_bytes = pg_atomic_read_u64(&s->dead_bytes); out->dead_pages = pg_atomic_read_u64(&s->dead_pages); out->checkpoint_map_rows_written = pg_atomic_read_u64(&s->checkpoint_map_rows_written); out->compressed_pages = pg_atomic_read_u64(&s->compressed_pages); out->uncompressed_pages = pg_atomic_read_u64(&s->uncompressed_pages); out->read_count = pg_atomic_read_u64(&s->read_count); out->read_batch_count = pg_atomic_read_u64(&s->read_batch_count); out->read_batched_pages = pg_atomic_read_u64(&s->read_batched_pages); out->read_fallback_pages = pg_atomic_read_u64(&s->read_fallback_pages); out->write_count = pg_atomic_read_u64(&s->write_count); out->compress_count = pg_atomic_read_u64(&s->compress_count); out->decompress_count = pg_atomic_read_u64(&s->decompress_count); out->crc_failures = pg_atomic_read_u64(&s->crc_failures); out->last_reset = s->last_reset; out->last_compaction = s->last_compaction; } bool cfs_stats_snapshot(RelFileLocatorBackend rlocator, ForkNumber forknum, CfsStatsSnapshot *out) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; MemSet(out, 0, sizeof(CfsStatsSnapshot)); LWLockAcquire(&cfs_stats_locks[part].lock, LW_SHARED); s = cfs_stats_find(rel_hash, rlocator, forknum); if (s != NULL) cfs_stats_snapshot_copy(s, out); LWLockRelease(&cfs_stats_locks[part].lock); return out->found; } /* * Zero the counters of one occupied slot, keeping its identity. The * caller holds the partition lock exclusively: reset cannot interleave * with an atomic add (creation/eviction/reset stay exclusive by design). */ static void cfs_stats_reset_slot(CfsRelationStats *s, bool clear_compaction) { pg_atomic_write_u64(&s->logical_pages, 0); pg_atomic_write_u64(&s->compressed_bytes, 0); pg_atomic_write_u64(&s->raw_bytes, 0); pg_atomic_write_u64(&s->dead_bytes, 0); pg_atomic_write_u64(&s->dead_pages, 0); pg_atomic_write_u64(&s->checkpoint_map_rows_written, 0); pg_atomic_write_u64(&s->compressed_pages, 0); pg_atomic_write_u64(&s->uncompressed_pages, 0); pg_atomic_write_u64(&s->read_count, 0); pg_atomic_write_u64(&s->read_batch_count, 0); pg_atomic_write_u64(&s->read_batched_pages, 0); pg_atomic_write_u64(&s->read_fallback_pages, 0); pg_atomic_write_u64(&s->write_count, 0); pg_atomic_write_u64(&s->compress_count, 0); pg_atomic_write_u64(&s->decompress_count, 0); pg_atomic_write_u64(&s->crc_failures, 0); s->last_reset = (int64) GetCurrentTimestamp(); if (clear_compaction) s->last_compaction = 0; } void cfs_stats_reset(RelFileLocatorBackend rlocator, ForkNumber forknum) { uint32 rel_hash = cfs_cache_hash_rel(rlocator, forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s; LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE); s = cfs_stats_find(rel_hash, rlocator, forknum); if (s != NULL) { /* Keep the slot but zero the counters. */ cfs_stats_reset_slot(s, false); cfs_stats_touch(part, s); } LWLockRelease(&cfs_stats_locks[part].lock); } /* * cfs_stats_reset_all — zero the counters of every statistics slot across * all partitions. Used by pg_cfs_reset_stats(NULL). The relation identity * of each slot is preserved so a subsequent snapshot still 'finds' the * relation, but the per-relation last_compaction timestamp is also cleared * because the whole point of a reset is a clean slate. */ void cfs_stats_reset_all(void) { int p; int i; for (p = 0; p < CFS_MAP_CACHE_NUM_PARTITIONS; p++) { LWLockAcquire(&cfs_stats_locks[p].lock, LW_EXCLUSIVE); for (i = 0; i < cfs_stats_slots_per_partition; i++) { CfsRelationStats *s = cfs_stats_slot(p, i); if (s->hash != 0) { cfs_stats_reset_slot(s, true); cfs_stats_touch(p, s); } } LWLockRelease(&cfs_stats_locks[p].lock); } } /* * cfs_stats_for_each — enumerate every populated statistics slot and invoke * the callback with a consistent snapshot. Used by the pg_stat_cfs view. */ void cfs_stats_for_each(CfsStatsEnumCB cb, void *arg) { int p; int i; for (p = 0; p < CFS_MAP_CACHE_NUM_PARTITIONS; p++) { LWLockAcquire(&cfs_stats_locks[p].lock, LW_SHARED); for (i = 0; i < cfs_stats_slots_per_partition; i++) { CfsRelationStats *s = cfs_stats_slot(p, i); CfsStatsSnapshot snap; if (s->hash == 0) continue; MemSet(&snap, 0, sizeof(snap)); cfs_stats_snapshot_copy(s, &snap); if (!cb(s->rlocator, s->forknum, &snap, arg)) { LWLockRelease(&cfs_stats_locks[p].lock); return; } } LWLockRelease(&cfs_stats_locks[p].lock); } } /* ================================================================ * Persistence of the per-relation statistics * * The PG15 pgstat pattern (pgstat_before_server_shutdown / * pgstat_restore_stats): the checkpointer writes the counters to * PGDATA/pg_cfs_stats at a regular shutdown, only on proc_exit(0), and * the postmaster restores them at startup. Without this the background * compaction worker loses the accumulated dead-space estimates to every * maintenance restart: dead_bytes comes back as 0 and the relations stop * being candidates until new writes re-fragment them. A crash loses * everything since the last regular shutdown -- the same degradation * vanilla pgstat accepts. * ================================================================ */ #define CFS_STATS_FILE_FORMATID UINT64CONST(0x01C5F51A9D) #define CFS_STATS_FILENAME "pg_cfs_stats" #define CFS_STATS_TMPNAME "pg_cfs_stats.tmp" typedef struct CfsStatsFileHeader { uint64 formatid; uint32 nentries; uint32 entry_size; } CfsStatsFileHeader; typedef struct CfsStatsFileEntry { RelFileLocatorBackend rlocator; ForkNumber forknum; CfsStatsSnapshot stats; } CfsStatsFileEntry; typedef struct CfsStatsCollectCtx { CfsStatsFileEntry *entries; int n; int max; } CfsStatsCollectCtx; static bool cfs_stats_collect_cb(RelFileLocatorBackend rlocator, ForkNumber forknum, const CfsStatsSnapshot *stats, void *arg) { CfsStatsCollectCtx *ctx = (CfsStatsCollectCtx *) arg; if (ctx->n >= ctx->max) return false; /* cannot happen: slots bound entries */ ctx->entries[ctx->n].rlocator = rlocator; ctx->entries[ctx->n].forknum = forknum; ctx->entries[ctx->n].stats = *stats; ctx->n++; return true; } /* * Copy the persisted counters into a fresh slot. The hash and access * clock are recomputed: they are runtime bookkeeping, not data. The slot * is linked into its bucket chain exactly like a runtime creation would * (invariant I2); the partition lock is taken even though only the * postmaster runs here, so the chain invariants hold uniformly. * * Returns false when the partition holds no free slot (skew): the * caller counts the entry as not restored instead of silently * dropping it. */ static bool cfs_stats_restore_entry(const CfsStatsFileEntry * e) { uint32 rel_hash = cfs_cache_hash_rel(e->rlocator, e->forknum); int part = rel_hash & CFS_PART_MASK; CfsRelationStats *s = NULL; int i; bool ok = false; LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE); for (i = 0; i < cfs_stats_slots_per_partition; i++) { if (cfs_stats_slot(part, i)->hash == 0) { s = cfs_stats_slot(part, i); break; } } if (s == NULL) { LWLockRelease(&cfs_stats_locks[part].lock); return false; /* partition skew: skip the extra entry */ } s->rlocator = e->rlocator; s->forknum = e->forknum; s->hash = rel_hash; pg_atomic_write_u64(&s->logical_pages, e->stats.logical_pages); pg_atomic_write_u64(&s->compressed_bytes, e->stats.compressed_bytes); pg_atomic_write_u64(&s->raw_bytes, e->stats.raw_bytes); pg_atomic_write_u64(&s->dead_bytes, e->stats.dead_bytes); pg_atomic_write_u64(&s->dead_pages, e->stats.dead_pages); pg_atomic_write_u64(&s->checkpoint_map_rows_written, e->stats.checkpoint_map_rows_written); pg_atomic_write_u64(&s->compressed_pages, e->stats.compressed_pages); pg_atomic_write_u64(&s->uncompressed_pages, e->stats.uncompressed_pages); pg_atomic_write_u64(&s->read_count, e->stats.read_count); pg_atomic_write_u64(&s->read_batch_count, e->stats.read_batch_count); pg_atomic_write_u64(&s->read_batched_pages, e->stats.read_batched_pages); pg_atomic_write_u64(&s->read_fallback_pages, e->stats.read_fallback_pages); pg_atomic_write_u64(&s->write_count, e->stats.write_count); pg_atomic_write_u64(&s->compress_count, e->stats.compress_count); pg_atomic_write_u64(&s->decompress_count, e->stats.decompress_count); pg_atomic_write_u64(&s->crc_failures, e->stats.crc_failures); s->last_reset = e->stats.last_reset; s->last_compaction = e->stats.last_compaction; /* * The restored dead_bytes may predate the last crash (the file is * written only at a clean shutdown): mark the value stale, so the * first measurement after a crash boot resyncs it from the map * (QDB-1507 U1). A clean boot clears the marks again * (cfs_stats_forget_stale_flags). */ s->stale = true; cfs_stats_touch(part, s); cfs_stats_chain_link(part, s); ok = true; LWLockRelease(&cfs_stats_locks[part].lock); return ok; } void cfs_stats_write_statsfile(int code, Datum arg) { MemoryContext oldctx; CfsStatsCollectCtx ctx; CfsStatsFileHeader hdr; char *tmpfile; char *statfile; FILE *fp; /* Only a regular shutdown persists the counters (pgstat pattern). */ if (code != 0) return; /* Single writer by construction (registered in the checkpointer). */ if (cfs_control->stats_saved) return; tmpfile = psprintf("%s/%s", DataDir, CFS_STATS_TMPNAME); statfile = psprintf("%s/%s", DataDir, CFS_STATS_FILENAME); oldctx = MemoryContextSwitchTo(TopMemoryContext); ctx.max = CFS_MAP_CACHE_NUM_PARTITIONS * cfs_stats_slots_per_partition; ctx.entries = palloc(sizeof(CfsStatsFileEntry) * ctx.max); ctx.n = 0; cfs_stats_for_each(cfs_stats_collect_cb, &ctx); hdr.formatid = CFS_STATS_FILE_FORMATID; hdr.nentries = ctx.n; hdr.entry_size = sizeof(CfsStatsFileEntry); if ((fp = AllocateFile(tmpfile, "wb")) == NULL) { ereport(LOG, (errcode_for_file_access(), errmsg("CFS: could not open \"%s\" for writing: %m", tmpfile))); } else if (fwrite(&hdr, sizeof(hdr), 1, fp) != 1 || fwrite(ctx.entries, sizeof(CfsStatsFileEntry), ctx.n, fp) != (size_t) ctx.n || fflush(fp) != 0 || pg_fsync(fileno(fp)) != 0) { ereport(LOG, (errcode_for_file_access(), errmsg("CFS: could not write statistics file \"%s\": %m", tmpfile))); FreeFile(fp); unlink(tmpfile); } else if (FreeFile(fp) != 0) { ereport(LOG, (errcode_for_file_access(), errmsg("CFS: could not write statistics file \"%s\": %m", tmpfile))); unlink(tmpfile); } else if (durable_rename(tmpfile, statfile, LOG) != 0) { /* durable_rename has already logged the failure. */ } else { cfs_control->stats_saved = true; ereport(DEBUG1, (errmsg("CFS: wrote %d per-relation statistics entries to \"%s\"", ctx.n, statfile))); /* * QDB-1507 U1: a clean shutdown that overtook the crash-boot * sweep persists values that were never resynced. Record that * durably: the next - clean! - start must keep the sweep armed * instead of declaring the just-persisted values * authoritative. The marker is removed only by the sweep * itself (cfs_stats_boot_sweep_done): with the sweep already * completed the pending flag is clear and this writer creates * nothing, and a start interrupted before the sweep keeps the * obligation on disk. A creation failure is only LOG: the * degradation is that a clean restart after this one trusts * understated values - the exact window the marker closes. */ if (cfs_stats_boot_sweep_pending()) { char *markerfile = psprintf("%s/%s", DataDir, CFS_STATS_SWEEP_PENDING_FILENAME); int mfd = OpenTransientFile(markerfile, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY); if (mfd < 0) ereport(LOG, (errcode_for_file_access(), errmsg("CFS: could not create statistics resync " "marker \"%s\": %m", markerfile))); else { if (pg_fsync(mfd) != 0) ereport(LOG, (errcode_for_file_access(), errmsg("CFS: could not fsync statistics resync " "marker \"%s\": %m", markerfile))); CloseTransientFile(mfd); cfs_fsync_parent_dir(markerfile, LOG); } pfree(markerfile); } } MemoryContextSwitchTo(oldctx); } void cfs_stats_restore_statsfile(void) { char *statfile = psprintf("%s/%s", DataDir, CFS_STATS_FILENAME); CfsStatsFileHeader hdr; CfsStatsFileEntry *entries = NULL; FILE *fp; int i; if ((fp = AllocateFile(statfile, "rb")) == NULL) return; /* first boot: nothing to restore */ if (fread(&hdr, sizeof(hdr), 1, fp) != 1 || hdr.formatid != CFS_STATS_FILE_FORMATID || hdr.entry_size != sizeof(CfsStatsFileEntry) || hdr.nentries > CFS_MAP_CACHE_NUM_PARTITIONS * cfs_stats_slots_per_partition) goto discard; entries = palloc(hdr.nentries * sizeof(CfsStatsFileEntry)); if (fread(entries, sizeof(CfsStatsFileEntry), hdr.nentries, fp) != hdr.nentries) goto discard; FreeFile(fp); fp = NULL; /* * All slots are free at this point: postmaster, before any child. A full * partition (skew) still skips its extra entries, so the LOG below * reports how many were actually restored, never just how many were read. */ { int restored = 0; for (i = 0; i < hdr.nentries; i++) { if (cfs_stats_restore_entry(&entries[i])) restored++; } ereport(LOG, (errmsg("CFS: restored %d of %d per-relation statistics entries from \"%s\"", restored, hdr.nentries, statfile))); } return; discard: if (fp) FreeFile(fp); ereport(LOG, (errmsg("CFS: discarding invalid statistics file \"%s\"", statfile))); } /* * cfs_stats_boot_restore_marker - arm the sweep from the persistent * crash-boot resync marker (QDB-1507 U1). A clean shutdown that * happened before the sweep completed wrote the marker next to the * stats file: the values it persisted are just as unresynced as the * ones the crash left, so the next boot - a clean one, where * StartupXLOG would otherwise declare them authoritative - must keep * the sweep armed. * * Presence detection only: the marker is NOT unlinked here. It is * the durable carrier of the still-unfulfilled obligation, so a boot * killed before the first full cycle (whose control file can still * read as a clean shutdown) loses nothing - the marker survives and * the next boot re-arms; it is removed only when the sweep itself * retires (cfs_stats_boot_sweep_done). Runs in the postmaster * (CfsShmemInit), before StartupXLOG's crash/clean decision. */ void cfs_stats_boot_restore_marker(void) { char *markerfile = psprintf("%s/%s", DataDir, CFS_STATS_SWEEP_PENDING_FILENAME); FILE *fp; if ((fp = AllocateFile(markerfile, "rb")) != NULL) { FreeFile(fp); cfs_control->stats_boot_stale = true; } pfree(markerfile); }