/*------------------------------------------------------------------------- * cfs_shmem.h * Compressed File Store (CFS) — shared memory map cache, statistics * and synchronisation. * * This module provides the multi-process layer that sits on top of the * autonomous storage engine: a partitioned shared-memory pool of fixed * block-map segments (the logical-block to .cfp-offset map, shared by all * backends), per-relation metadata and aggregated statistics, and cached * read/write helpers that keep the storage layer's lock hold times minimal. * * Design highlights: * * * The cache is partitioned. Lookups take an LW_SHARED partition lock; * updates take LW_EXCLUSIVE. Partitioning by a hash of the lookup key * reduces contention compared with a single global lock. * * * Compression, decompression and disk I/O are never performed while a * CFS partition lock is held — only the (cheap) map-entry copy / update * happens inside the critical section. * * * Per-relation metadata (logical size, generation) is kept in * a separate partitioned table and protected by the same set of locks. * * * Statistics counters live in their own partitioned table so that * observations do not require a relation lock. * * * Relation metadata occupies a bounded number of slots per partition * and is evicted by an access-clock LRU; pinned metadata (an open CFS * handle) is never evicted. Block-map segments live in a separate, * fixed-size pool and are evicted by a clock sweep (usage_count), never * while their relation is pinned. * * Copyright (c) 2026, Kirillov Vyacheslav, QDB Development Group * * IDENTIFICATION * src/include/storage/cfs/cfs_shmem.h * *------------------------------------------------------------------------- */ #ifndef CFS_SHMEM_H #define CFS_SHMEM_H #include "access/transam.h" #include "access/xlogdefs.h" #include "common/relpath.h" #include "datatype/timestamp.h" #include "lib/ilist.h" #include "port/atomics.h" #include "storage/block.h" #include "storage/bufmgr.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_storage.h" #include "storage/lwlock.h" #include "storage/procnumber.h" #include "storage/relfilelocator.h" /* ================================================================ * Tuning constants * * Every count is a power of two so that the modulo used to select a * partition reduces to a cheap bitwise AND. The values chosen give a * modest shared-memory footprint suitable for a first production version; * they can be revisited after load testing. * ================================================================ */ /* Number of partitions (LWLocks) shared by the map cache and statistics. */ #define CFS_MAP_CACHE_NUM_PARTITIONS 64 /* * Per-partition slots for relation metadata. This is the default (and the * compile-time upper bound is CFS_MAP_CACHE_MAX_RELS_PER_PART); the actual * number of slots per partition is set by the cfs_map_cache_rels_per_partition * GUC at server start. * * Each slot also carries a per-relation LWLock (the "append lock") that * serialises writes/checkpoint/compaction of that one relation, so the * total number of slots doubles as the maximum number of concurrently * open CFS relations. Exhaustion is a hard ERROR (the relation cannot be * written to), so the default is intentionally generous. */ #define CFS_MAP_CACHE_RELS_PER_PART 16 #define CFS_MAP_CACHE_MAX_RELS_PER_PART 64 /* Per-partition slots for statistics. */ /* * Shared block-map segment pool. One segment holds the map * entries of CFS_MAP_SEGMENT_BLOCKS consecutive logical blocks of one * relation fork: 32,768 entries x sizeof(CfsMapEntry) = 768 KiB with the * current 24-byte entry. The pool is sized by the cfs_map_memory GUC * (megabytes, modelled on shared_buffers) and is absent when the GUC is 0. */ /* * Clock-sweep saturation point for a segment's usage counter, matching * BUF_USAGECOUNT_ONE / the bufmgr clock sweep model: a segment touched more * often than this is treated the same as one touched exactly this often. */ #define CFS_MAP_SEG_USAGE_MAX 5 /* ================================================================ * Shared-memory structures * ================================================================ */ /* * CfsCfpAppendState — the trust state of the slot's authoritative .cfp tail * (see cfp_tail below). Writers transition it under the relation's append * lock only; readers must treat every non-IDLE value as "the tail is not * authoritative, re-discover the chain end". */ typedef enum CfsCfpAppendState { CFS_CFP_APPEND_IDLE = 0, /* cfp_tail is the authoritative chain end */ CFS_CFP_APPEND_IN_PROGRESS = 1, /* an appender is between its pwrite and * the tail publication; the tail may or * may not include its record */ CFS_CFP_APPEND_DIRTY = 2, /* the tail is unknown or stale (fresh slot, * compaction swap, failed pwrite) */ } CfsCfpAppendState; /* * CfsRelMetaSlot — cached per-relation metadata. * * Holds the authoritative grow-only logical size visible to other * backends, plus a generation counter that is bumped whenever the relation * is invalidated or truncated (so cached block entries can be discarded). * 'refcount' counts active pins; a pinned slot is never evicted. * * 'append_lock' is the per-relation LWLock that serialises all writes, * checkpoints and compactions of this relation's sidecars. It is * initialised when the slot is first populated and lives as long as the * slot exists. Because it is private to one relation, two unrelated * relations never contend on the same lock, regardless of how their hash * values collide on the partition array. * * 'cfp_tail' / 'cfp_append_state' / 'cfp_append_proc' hold the * authoritative end of the segmented .cfp chain. The tail is updated only * under the append lock, after a successful pwrite (CFS_CFP_APPEND_IDLE), * or marked untrusted (DIRTY) when the files were replaced or a write * failed. A crash between the pwrite and the publication leaves * IN_PROGRESS behind with the dead owner recorded in cfp_append_proc; the * next writer re-discovers the chain end instead of trusting the tail. * This replaces the per-append fstat walk of cfs_cfp_discover_eof() for * the common write path; the walk itself stays the single rule for * segment chaining and remains mandatory for cold slots and every * non-IDLE state. * * 'compact_proc' / 'compact_pid' mark an online compaction in progress * (QDB-1514). The pair is set under the append lock before the compaction * releases it for the copy phase and cleared when the compaction ends. * The liveness test (matching pid at the ProcNumber's PGPROC) is what makes * a leftover mark harmless: a compaction whose backend died without the * cleanup reads as "not active", and the interrupted-swap recovery below * the storage layer proceeds over its orphaned candidates as before. */ typedef struct CfsRelMetaSlot { uint32 hash; /* hash of the key; 0 == empty slot */ int32 chain_next; /* index of the next slot in the partition's * hash chain; -1 = end of chain. Only * meaningful while the slot is occupied * (see the chain invariants in * cfs_shmem_internal.h) */ RelFileLocatorBackend rlocator; ForkNumber forknum; uint64 generation; /* bumped on invalidate/truncate */ uint64 access_clock; uint32 refcount; /* number of active pins */ uint64 nblocks; /* grow-only logical size */ uint64 cfp_tail; /* authoritative end of the .cfp chain; */ /* valid only when cfp_append_state is */ /* CFS_CFP_APPEND_IDLE; updated under the */ /* append lock only */ uint8 cfp_append_state; /* CfsCfpAppendState; a fresh slot */ /* starts DIRTY so the first writer */ /* discovers the chain end */ int cfp_append_proc; /* ProcNumber of an IN_PROGRESS owner; */ /* diagnostics only, never a validity */ /* test (a dead owner leaves the state */ /* at IN_PROGRESS until the next writer) */ int compact_proc; /* ProcNumber of an online-compaction */ /* owner; INVALID_PROC_NUMBER when idle; */ /* paired with compact_pid for liveness */ int compact_pid; /* pid of the compact_proc owner at mark */ /* time; a recycled ProcNumber never */ /* validates a stale mark (pid mismatch) */ bool is_cfs; /* this relation stores its forks in CFS; * deliberately separate from the algorithm * value: on a codec-less build a valid policy * is RAW (cfs_algo == 0) */ uint8 cfs_algo; /* CfsAlgorithm value; RAW (= 0) is valid when * is_cfs is set; 0 with is_cfs clear means * "no policy stored" */ int level; /* explicit compression level; valid only when * level_set is true */ int min_gain_bytes; /* explicit minimum gain (bytes); valid only * when min_gain_bytes_set is true */ bool level_set; /* "level" was stored explicitly; writers * resolve unset fields from their session * GUCs at write time */ bool min_gain_bytes_set; /* "min_gain_bytes" was stored explicitly */ uint64 policy_gen; /* policy generation: set to a fresh value * of the partition's map-domain access * clock whenever the published policy * (algo/level/min_gain_bytes and their * set-flags) changes; SMgrRelation holders * compare it against their cached copy and * re-resolve */ bool dirty_checkpoint; /* written since last checkpoint; never * evicted until checkpoint fsyncs */ pg_atomic_uint32 next_generation; /* relation-wide map-entry generation * counter; strictly above every * generation in the map and journal */ bool generation_initialized; /* next_generation has been seeded * from the snapshot header and * journal */ pg_atomic_uint64 full_map_opens; /* throwaway full-map handles opened * for THIS relation (eviction * restarts it at zero); the * per-relation half of the global * counter, so the incremental * checkpoint test measures the * relation it checkpoints, not the * cluster */ LWLock append_lock; /* per-relation append serialisation lock */ } CfsRelMetaSlot; /* * CfsMapSegmentDesc — descriptor of one segment of the shared block-map * pool. The descriptor array and the segment data live in shared memory * and are sized at postmaster start; each segment owns one LWLock from * the segment tranche (the buffer-mapping model: readers copy a single * CfsMapEntry under LW_SHARED, writers store one entry under * LW_EXCLUSIVE while holding the relation's append lock). * * 'hash' doubles as the "in use" marker (0 == free) and is validated * together with the full key under the segment lock, so a reader that * waited for the lock while the segment was evicted and re-used detects * the mismatch and retries. * * 'usage_count' is the bufmgr-style clock-sweep counter: a lookup hit or a * successful store bumps it (saturated at CFS_MAP_SEG_USAGE_MAX), and the * victim sweep decrements it before reconsidering the segment. This keeps * the choice O(1)-ish instead of an LRU scan with two locks per candidate. */ typedef struct CfsMapSegmentDesc { uint32 hash; /* hash of the key; 0 == free segment */ RelFileLocatorBackend rlocator; ForkNumber forknum; BlockNumber first_block; /* covers [first_block, first_block + * CFS_MAP_SEGMENT_BLOCKS) */ pg_atomic_uint32 usage_count; /* clock sweep usage counter, * CFS_MAP_SEG_USAGE_MAX is the saturation * point */ uint64 jrn_synced_off; /* journal offset the segment content is * synced up to; 0 after a snapshot load (the * replay that follows re-reads the whole * journal: an immedsync-written snapshot does * not truncate it), advanced by delta replay */ uint16 jrn_incarnation; /* journal incarnation jrn_synced_off * belongs to. A checkpoint truncates the * journal and bumps the incarnation; a * mismatch against the on-disk header * means the offset is meaningless (the * journal may even have grown back past * it — the ABA a pure size check cannot * catch) and the segment must resync from * the journal header with a fresh * snapshot merge. 0 = not stamped yet * (first sync resyncs once) */ uint64 rel_generation; /* relation map generation the physical * offsets belong to; a compaction or truncate * bumps the generation and drops every * segment of the relation, so a surviving * segment whose tag disagrees with the * reader's handle must not be read through * that handle's descriptors */ bool snapshot_loaded; /* true once the .cfsmap snapshot part of * the range has been merged in. A segment * first created by a writer store holds * only journaled entries; until the * snapshot is merged, its INVALID slots * do not mean "never written" and must * resolve through the authoritative path */ bool journal_synced; /* true once the journal replay has caught the * segment up with its snapshot; lookup must * treat a false segment as a miss, or a * reader could serve a pre-checkpoint version * while the journal already holds a newer * one. snapshot_loaded controls the merge, * this field controls the right to serve * entries */ unsigned char unhealed_mask[CFS_MAP_SEGMENT_BLOCKS / 8]; /* * one bit per block: the snapshot load found a row that failed its * entry_crc and no journal record covers it. Only those blocks are * unservable (their INVALID slots must not read as "never written" * pages); a rewrite or journal heal clears the bit. Reset on publish and * on a fresh snapshot merge. */ uint64 seg_epoch; /* instance counter: bumped on every * reservation, publication and eviction, so a * victim sampled before a re-use of the same * id/key is not evicted again after the * descriptor was recycled */ bool reserved; /* an acquirer has claimed the descriptor and * is publishing its mapping entry / data: * find_free and pick_victim must skip it (the * buffer-manager pin-before- publish model), * or a competitor would steal the id and * leave two mapping entries pointing at one * descriptor */ dlist_node rel_node; /* link in the per-relation segment list; * protected by the relation-index lock */ bool rel_linked; /* true while rel_node sits in that list; also * protected by the relation-index lock */ } CfsMapSegmentDesc; /* * CfsMapSegmentKey / CfsMapSegmentHashEnt — the lookup-table entries that * map (relation, fork, segment range) to a pool segment id. This is the * buffer-mapping model: a partitioned shared dynahash in front of the * segment array, with the same 64 partition locks the map cache uses * (cfs_map_locks). Callers serialise hash access with those locks and * segment access with the per-segment LWLock. The only nesting allowed is * mapping lock -> segment lock, in the short re-check inside * cfs_map_segment_acquire(); the reverse order is forbidden. */ typedef struct CfsMapSegmentKey { RelFileLocatorBackend rlocator; ForkNumber forknum; BlockNumber first_block; /* blocknum & ~(CFS_MAP_SEGMENT_BLOCKS-1) */ } CfsMapSegmentKey; typedef struct CfsMapSegmentHashEnt { CfsMapSegmentKey key; int segment_id; /* index into the segment pool */ } CfsMapSegmentHashEnt; /* * In-flight reservation: maps a key to the descriptor an acquirer has * claimed but not yet published. The descriptor's hash stays 0 until the * data is ready, so the victim sweep must consult this table (not the * descriptor alone) before treating an id as free. */ typedef struct CfsMapSegmentReservation { CfsMapSegmentKey key; int segment_id; int32 owner_pid; /* backend that claimed the descriptor */ ProcNumber owner_procno; /* its ProcNumber (also for aux procs) */ uint64 owner_epoch; /* per-process incarnation; a recycled * ProcNumber gets a new epoch on first use, * so a stale reservation cannot look alive * after PID reuse */ } CfsMapSegmentReservation; /* * CFS_READ_PLAN_MAX — plan entries per scratch slot. One entry per block * of the IO the slot serves; the largest possible IO carries at most * io_max_combine_limit blocks, the same clamp bufmgr applies to every * combined read. */ #define CFS_READ_PLAN_MAX MAX_IO_COMBINE_LIMIT /* * A plan entry addresses the target buffer by its index in the IO handle * data, whose length is a uint8; the combine-limit clamp keeps the index * range inside that width. */ StaticAssertDecl(MAX_IO_COMBINE_LIMIT <= UINT8_MAX, "CFS_READ_PLAN_MAX must fit the uint8 buffer index"); /* * CfsReadScratchSlotState — lifecycle of one read-scratch slot. The slot * is the unit of ownership passed from the planning backend to the IO * executor and back. Every transition is one atomic store or CAS on * 'state', so the arena needs no LWLock; the AIO submit / completion * paths provide the cross-process synchronisation points the state * machine sits on. */ typedef enum CfsReadScratchSlotState { CFS_READ_SCRATCH_FREE = 0, /* available for acquisition */ CFS_READ_SCRATCH_BUILDING, /* backend is writing the plan */ CFS_READ_SCRATCH_INFLIGHT, /* IO handed to the executor */ } CfsReadScratchSlotState; /* * CfsReadPlanEntry — one block of a span plan. 'rec_off' locates the * record inside the slot's span buffer and 'payload' is the record's * compressed payload size, so the executor re-derives the aligned record * size with CFS_RECORD_SIZE() and the per-page read statistic exactly * like the inline span path does; 'buf_off' indexes the IO handle's * buffer array (pgaio_io_get_handle_data()), which the completion * callback resolves to the pinned target buffer. A plan only ever * covers one contiguous run of stored blocks: holes and pool misses * break the run and the whole request degrades to the inline path, so * no zero-page entry kind is needed. */ typedef struct CfsReadPlanEntry { uint32 rec_off; /* record offset within the span buffer */ uint32 payload; /* compressed_size of the record */ uint8 buf_off; /* target buffer index within the IO */ uint8 flags; /* reserved, must be zero */ } CfsReadPlanEntry; /* * CfsReadScratchSlot — one arena slot: the plan and its bookkeeping. * The span bytes live in a separate contiguous array (one * cfs_read_span_capacity() region per slot), because the capacity * depends on io_max_combine_limit and must not inflate this descriptor. */ typedef struct CfsReadScratchSlot { pg_atomic_uint32 state; /* CfsReadScratchSlotState */ uint32 plan_len; /* entries[] used, set before publish */ uint32 span_len; /* span bytes used, set before publish */ bool pooled; /* plan came from the shared pool, so * a completion-time corruption must do * the pool bookkeeping the inline path * does (crc failure + entry drop) */ int owner_procno; /* acquiring backend; DIAGNOSTICS ONLY * (crash debugging); no reclamation * mechanism exists: a backend dying * between acquire and publish (a * no-throw window) leaves the slot * BUILDING forever — the known, * operator-accepted limitation of * questions.md #6. Staged IOs of a * dying backend are submitted by the * resource-owner path and completed by * the executor, releasing their slots */ CfsReadPlanEntry entries[CFS_READ_PLAN_MAX]; } CfsReadScratchSlot; /* * CfsShmemControl — top-level shared-memory control block. * * Holds the dynamic tranche ids assigned at postmaster startup and a small * set of global counters used for clock-sweep/LRU bookkeeping and * observability. */ typedef struct CfsShmemControl { int map_tranche_id; /* LWLock tranche for map cache / metadata */ int stats_tranche_id; /* LWLock tranche for statistics */ int append_tranche_id; /* LWLock tranche for .cfp/.cfsjrn append */ int bg_tranche_id; /* LWLock tranche for bgworker control */ int map_seg_tranche_id; /* LWLock tranche for block-map segments */ /* * Statistics slots per partition (the cfs_stats_slots_per_partition GUC * value) frozen at postmaster start. A process attaching to already * allocated shared memory (EXEC_BACKEND children) re-parses its own * configuration; a mismatch against this value means the arrays were * laid out for a different slot count, and the statistics module * refuses to attach instead of indexing them out of layout. */ int stats_slots_per_part; /* * Global counters. These are updated from many backends without * holding a partition lock, so they use 64-bit atomics to stay correct * and tear-free on every platform. (The per-relation LRU clocks are * the per-partition cfs_map_clocks / cfs_stats_clocks arrays, updated * only under their partition's lock.) */ pg_atomic_uint64 evictions; /* slots reclaimed by LRU eviction */ pg_atomic_uint64 map_segment_loads; /* map segments read from .cfsmap */ pg_atomic_uint64 map_segment_evictions; /* map segments reclaimed by the * clock sweep */ pg_atomic_uint64 map_segments_in_use; /* map segments currently held */ pg_atomic_uint64 map_fallback_reads; /* reads served through the * authoritative full map because * the pool had no evictable * segment */ pg_atomic_uint64 map_pool_churn; /* bumped whenever a segment becomes * evictable or resident (publication, * eviction, unpin, pool reset); lets * a backend memoise "the pool is * exhausted" without rescanning the * clock sweep on every miss */ pg_atomic_uint64 map_pin_reap_empty_at; /* timestamp (GetCurrentTimestamp) * of the last pin-reaper sweep * that reaped nothing; throttles * repeats of the * all-partition-locks scan on * partitions saturated with live * pins; 0 = rescan at once */ pg_atomic_uint64 owner_epoch_next; /* source of per-process epochs for * segment reservations */ pg_atomic_uint64 full_map_opens; /* throwaway full-map handles opened * by any process (checkpoint, * immedsync, sizing); shared, not * per-process, because the checkpoint * runs in the checkpointer */ /* * Set when the checkpointer has persisted the per-relation statistics at * a regular shutdown (the pgstat is_shutdown pattern): exactly one * process writes the file, and only on proc_exit(0). */ bool stats_saved; /* * QDB-1507 U1: crash-boot marker of the restored statistics - the * first background worker pass resyncs the restored dead counters * from the relation maps. */ bool stats_boot_stale; } CfsShmemControl; /* * CFS_BG_HISTORY_MAX — capacity of the bgworker's per-relation * compaction-history hash (a shared dynahash: the lock-manager pattern for * shared hashes that grow with the number of tracked objects). Vanilla * keeps per-relation "last autovacuum time" entries without any count cap * (PgStat_StatTabEntry.last_autovac_time in a shared hash); the constant * here only caps the reserved shared memory. Entries older than * cfs_bg_min_interval_s are retired by cfs_bg_history_sweep(), so the live * set is bounded by the relations compacted (or failed on) within that * window. * * ponytail: when the window genuinely holds more relations than this, the * insert is skipped with a one-time LOG and that one relation runs without * its throttle until the sweep frees space -- extra background work, not a * correctness problem. Ceiling and upgrade path: a GUC-sized hash. */ #define CFS_BG_HISTORY_MAX 32768 /* * CfsBgHistoryKey / CfsBgHistoryEntry — one per-relation entry of the * bgworker's compaction history: the last time the relation was compacted * (or a compaction attempt failed), used to enforce cfs_bg_min_interval_s. * The key carries the database: relid values are unique only within a * database, and a cluster-wide history must not throttle one database's * relation through another database's relation with the same relid. */ typedef struct CfsBgHistoryKey { Oid dboid; Oid relid; } CfsBgHistoryKey; typedef struct CfsBgHistoryEntry { CfsBgHistoryKey key; int64 last_compact; /* TimestampTz of the last compaction (or * attempt) */ } CfsBgHistoryEntry; /* * CfsBgControl — shared state for the background compaction worker. * * Holds the pause flag, an optional expiry for a timed pause and the * timestamps of the last compaction cycle. Protected by cfs_bg_lock (a * dedicated LWLock from the bg tranche). Survives SIGHUP (it lives in * shared memory) but not a full server restart, so a restart always clears * a pause. * * Timestamps are stored as the internal TimestampTz representation * (microseconds since 2000-01-01) as plain int64. */ typedef struct CfsBgControl { bool paused; /* automatic compaction is paused */ int64 paused_until; /* TimestampTz; 0 = no expiry */ int64 last_cycle_started_at; /* TimestampTz of the current/last * pass */ int64 last_cycle_finished_at; /* TimestampTz of the last completed * pass */ } CfsBgControl; /* ================================================================ * Shared-memory lifecycle * ================================================================ */ /* Amount of shared memory required by the CFS subsystem. */ extern Size CfsShmemSize(void); /* Allocate and initialise the CFS shared-memory structures. */ extern void CfsShmemInit(void); /* ================================================================ * Partitioned map cache * ================================================================ */ /* * Pinning. A pin prevents the relation's metadata slot (and, by policy, * its block entries) from being evicted. Acquire a pin when a relation is * opened for CFS access; release it on close / drop. */ extern void cfs_map_cache_pin(RelFileLocatorBackend rlocator, ForkNumber forknum); extern void cfs_map_cache_unpin(RelFileLocatorBackend rlocator, ForkNumber forknum); /* Decrement the pin count and drop the metadata slot when it reaches zero. */ extern void cfs_map_cache_release_relation(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * Cache-publication contract: a cached entry is always tagged with the * relation map generation of the map its offsets came from. For storage * layer callers that is the publishing handle's open_generation, captured * when that handle's map was loaded (under the append lock) and therefore * always describing the offsets being published. Never pass a generation * re-read from the shared metadata for entries taken from an older map: a * compaction racing the publication would stamp old offsets with a fresh * tag, and the lookup validation would then serve them against the new * sidecar files. A correctly tagged entry is at worst rejected as stale * by the next lookup, costing one authoritative re-read. */ /* * cfs_map_cache_invalidate — drop every cached entry and the metadata slot * * Callers that also hold pool segments for the relation must drop them * through cfs_shared_map_invalidate_relation(): this function serves both * pool-backed and full (cfs_map_memory = 0) handles, so it cannot know * whether a pool exists, and folding the segment sweep in here would run it * for handles that own no segments. * for a relation (used on DROP / rewrite). */ extern void cfs_map_cache_invalidate(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * Test hook: leave an orphaned slot pin behind (refcount raised for an * already-dead process, recorded in the pin-owner registry). Returns * the partition of the slot. Used by test_cfs to prove the reaper. */ extern int cfs_map_cache_test_pin_orphan(RelFileLocatorBackend rlocator, ForkNumber forknum); /* Test hooks: run the dead-pin reaper directly; read a slot's refcount * (-1 when no slot); report whether the pin-owner registry exists (it * must for every cfs_map_memory, 0 included). */ extern bool cfs_map_cache_test_reap_dead_pins(void); extern int cfs_map_cache_test_slot_refcount(RelFileLocatorBackend rlocator, ForkNumber forknum); extern bool cfs_map_cache_test_pin_registry_live(void); /* * cfs_drop_database_caches — drop every cached entry, metadata slot and * published policy belonging to a database (used on DROP DATABASE, whose * wholesale directory removal bypasses per-relation invalidation). */ extern void cfs_drop_database_caches(Oid dbid); /* * cfs_map_cache_compact_reset — drop the cached block entries for a relation * (whose physical offsets have just changed) but keep its metadata slot alive * and mark it dirty for checkpoint. Used after background compaction: unlike * cfs_map_cache_invalidate(), this does NOT remove the metadata slot, so the * next CfsCheckpoint() still finds the relation, snapshots the fresh map and * clears the journal. The cached logical size is preserved (compaction does * not change it). */ extern void cfs_map_cache_compact_reset(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * cfs_map_cache_truncate — discard cached entries for blocks >= nblocks and * shrink the cached logical size. */ extern void cfs_map_cache_truncate(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber nblocks); /* * cfs_map_cache_get_generation — current map generation of a relation * (0 when no metadata slot exists). Compaction bumps the generation when * it swaps the sidecar files, so a handle opened before the swap observes * a mismatch. */ extern uint64 cfs_map_cache_get_generation(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * cfs_map_cache_next_generation — allocate the next map-entry generation for * the relation. Relation-wide: the returned value is strictly above every * generation already present in the .cfsmap snapshot or the journal, so the * write path can stamp new entries without resolving the old one through * the segment pool. Must be called under the relation's append lock: the * counter lives in the metadata slot, and the lock serialises both the * one-time seeding scan and concurrent allocators; the caller's pin keeps * the slot (and the pointer) alive. */ extern uint32 cfs_map_cache_next_generation(CfsRelation *cfs); /* * cfs_handle_refresh_if_stale — reopen a CfsRelation whose sidecar files * were swapped by a compaction since the handle was opened. The caller * must hold the per-relation append lock, which serialises against the * compactor, so the generation is stable while it is being checked. */ extern void cfs_handle_refresh_if_stale(CfsRelation *cfs); /* ---- relation metadata ---- */ /* Return the cached logical block count; false when no metadata is cached. */ extern bool cfs_map_cache_get_nblocks(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 *out_nblocks); /* Insert / refresh the cached relation metadata (grow-only nblocks). */ extern void cfs_map_cache_set_meta(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 nblocks); /* * cfs_map_cache_mark_dirty — record that the relation was written without * publishing a new logical size. Used by writes that are not extensions: * only an extension may change nblocks. */ extern void cfs_map_cache_mark_dirty(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * cfs_map_cache_clear_dirty — clear the dirty-checkpoint flag for a relation * after a checkpoint has fsync'd its sidecars. */ extern void cfs_map_cache_clear_dirty(RelFileLocatorBackend rlocator, ForkNumber forknum); struct CfsEffectiveOptions; /* forward, defined in cfs_rel.h */ /* * cfs_publish_options — publish the effective policy of a relation into * the shared cache. Returns the policy generation the slot carries after * the call (0 when no slot could be allocated); the generation is bumped * only when the policy actually changes, and the return value is read * under the same lock that published it, so a caller caching it cannot * miss a concurrent policy change. */ extern uint64 cfs_publish_options(RelFileLocatorBackend rlocator, ForkNumber forknum, const struct CfsEffectiveOptions *opts); /* * cfs_publish_options_postcommit — publish like cfs_publish_options, but * from a path that runs after the durable commit (the XACT_EVENT_COMMIT * flush of deferred publications, the two-phase postcommit callback). * Raising ERROR there is no longer safe — the transaction cannot roll * back, and the abort machinery escalates to PANIC — so slot exhaustion * degrades to a WARNING and the entry is skipped; the next open of the * relation republishes the policy through cfs_open_relation_smgr(). Do not call from * paths that still run inside the transaction. */ extern uint64 cfs_publish_options_postcommit(RelFileLocatorBackend rlocator, ForkNumber forknum, const struct CfsEffectiveOptions *opts); extern bool cfs_get_options(RelFileLocatorBackend rlocator, ForkNumber forknum, struct CfsEffectiveOptions *out); /* * cfs_slot_present — true when the shared cache holds a slot for this * (rlocator, forknum), regardless of what the slot says. Useful for tests: * distinguishes "no slot at all" from "a slot lying is_cfs=false". */ extern bool cfs_slot_present(RelFileLocatorBackend rlocator, ForkNumber forknum); extern void cfs_forget_options(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * cfs_publish_options_deferred — queue a policy publication for the end of the * current transaction (flushed after the durable commit, dropped at abort or * subtransaction rollback) instead of publishing immediately. See * cfs_shmem.c for the rationale. */ extern void cfs_publish_options_deferred(RelFileLocatorBackend rlocator, ForkNumber forknum, const struct CfsEffectiveOptions *opts); /* * cfs_publish_is_pending — true when (rlocator, forknum) has a deferred * publication queued in the current transaction. */ extern bool cfs_publish_is_pending(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * cfs_publish_at_prepare — transfer the deferred publications of a * preparing transaction into the two-phase state file (called from * PrepareTransaction between StartPrepare and EndPrepare). */ extern void cfs_publish_at_prepare(void); /* * cfs_twophase_postcommit — publish the policy entries a committed * prepared transaction carried in its state file (two-phase postcommit * callback). */ extern void cfs_twophase_postcommit(FullTransactionId fxid, uint16 info, void *recdata, uint32 len); /* * cfs_policy_generation — current policy generation of a relation (0 when * no metadata slot exists). Cheap shared-lock read used by * cfs_smgr_ensure_state() to detect that the published policy changed since * the SMgrRelation's local copy was resolved. */ extern uint64 cfs_policy_generation(RelFileLocatorBackend rlocator, ForkNumber forknum); typedef void (*CfsRelCB) (RelFileLocatorBackend rlocator, ForkNumber forknum, void *arg); extern void cfs_for_each_cfs_relation(CfsRelCB cb, void *arg); /* ================================================================ * Shared block-map segment pool API * ================================================================ */ /* * cfs_shared_map_lookup — find the map entry of one block in the shared * segment pool. Returns true and copies the entry into *out_entry on a * hit; returns false when the pool is off, the segment is not resident or * the entry is the INVALID sentinel (the caller then takes the * authoritative miss path). When out_generation is not NULL it receives * the relation map generation the segment's offsets belong to: the caller * must compare it against its handle's open generation and reopen before * reading through the entry when they disagree (see cfs_read_page_cached). * Only the 24-byte copy happens under locks. */ extern bool cfs_shared_map_lookup(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum, CfsMapEntry *out_entry, uint64 *out_generation); /* * cfs_seg_tag_matches — does a map-generation tag (a segment descriptor's * or the one cfs_shared_map_lookup() returns) still name the sidecar-pair * epoch this handle works on? The single definition of segment-vs-handle * epoch agreement, shared with the smgr bridges: no call site compares the * generation fields by hand. */ extern bool cfs_seg_tag_matches(uint64 seg_generation, const CfsRelation *cfs); /* * cfs_shared_map_store — insert or replace the map entry of one block in * its segment. The caller must hold the relation's append lock (the * stored entry is the result of a journal replay or a write append). * 'generation' is the publishing handle's open_generation per the * cache-publication contract above, never a value re-read from the shared * metadata inside the store. * * Allocates a free segment on first touch; when the pool has no free * segment left the store is dropped (returns false) — segment eviction * and loading arrive with the ensure path and are always correct because * a dropped entry costs one authoritative re-read, never corruption. */ extern bool cfs_shared_map_store(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum, const CfsMapEntry *entry, uint64 generation); /* * cfs_shared_map_ensure — make sure the segment covering 'blocknum' of * 'cfs' is resident in the pool, loading it from the .cfsmap snapshot * when it is not. Disk I/O happens into a private buffer, outside any * lock; only the final segment copy happens under the segment lock. * Returns CFS_STORAGE_OK when the segment is resident and complete; * CFS_STORAGE_ERROR when the pool is off, no victim could be found * (every segment pinned) or the load raced a concurrent eviction — the * caller then proceeds through the authoritative miss path, which stays * correct without a resident segment; CFS_STORAGE_CORRUPT when the * segment holds rows that failed their entry_crc and that no journal * record healed — the caller must fail the read through the smgr entry * point's corruption report (never serve those blocks as zero pages). * The CORRUPT path never throws from here; a structural prologue/header * error does raise, and the caller releases the append lock and lets * cfs_smgr_startreadv() convert it into the AIO failure code. */ extern int cfs_shared_map_ensure(CfsRelation *cfs, BlockNumber blocknum); /* * cfs_shared_map_invalidate_relation — drop every segment of a relation * (DROP / rewrite / truncate). Segments are re-read from .cfsmap when * needed again. */ extern void cfs_shared_map_invalidate_relation(RelFileLocatorBackend rlocator, ForkNumber forknum); extern void cfs_shared_map_invalidate_db(Oid dbid); /* * Number of block-map segments the cfs_map_memory GUC buys (0 = the pool * is off). Pure GUC arithmetic, valid before the shared memory is up. */ extern int cfs_map_pool_segments(void); /* * True when cfs_map_memory actually buys at least one segment. A positive * value smaller than one segment leaves the pool disabled, so callers must * test the effective state, not the raw GUC. */ extern bool cfs_map_memory_effective(void); /* * cfs_shared_map_stats — pool observability counters (segments currently * held, segments loaded from .cfsmap, segments reclaimed by eviction and * the total pool capacity; 0 when the pool is off). */ extern void cfs_shared_map_stats(uint64 *segments_in_use, uint64 *segment_loads, uint64 *segment_evictions, uint64 *pool_segments); /* * cfs_shared_map_fallback_reads — number of reads served through a private * authoritative map because the pool had no free or evictable segment. * A growing value means the pool is undersized for the working set. */ extern uint64 cfs_shared_map_fallback_reads(void); /* * cfs_shared_full_map_opens — count of throwaway full-map handles opened * cluster-wide (the checkpoint runs in the checkpointer, so a per-process * counter cannot observe it). cfs_shared_note_full_map_open() bumps it. */ extern uint64 cfs_shared_full_map_opens(void); extern void cfs_shared_note_full_map_open(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * The per-relation half of the full-map-open counter (the slot's own * atomic; 0 when the relation has no metadata slot). An evicted slot * restarts its count at zero - the value is a measurement base for * short windows, not a lifetime total. */ extern uint64 cfs_shared_full_map_opens_rel(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * Deterministic test hooks for the pool races (C2, I4 and I9). They are * compiled only in assert-enabled builds, so a production build carries no * such API and no test-only branch in the hot paths. */ #ifdef USE_ASSERT_CHECKING extern bool cfs_shared_map_test_publish_unsynced(CfsRelation *cfs, BlockNumber blocknum); extern int cfs_shared_map_test_reserve_orphan(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum); extern int cfs_shared_map_test_segment_id(RelFileLocatorBackend rlocator, ForkNumber forknum, BlockNumber blocknum); extern uint32 cfs_shared_map_test_desc_usage(int id); extern void cfs_shared_map_test_set_desc_usage(int id, uint32 value); extern void cfs_shared_map_test_dec_desc_usage(int id); extern bool cfs_shared_map_test_merge_race(CfsRelation *cfs, BlockNumber blocknum); #endif /* * Test-only switch (no ifdef: the fallback path must stay covered in * non-assert builds too, following the cfs_test_smgr_full_map_open_count * precedent): while true, victim selection reports an exhausted pool, so * the read path degrades to the authoritative fallback exactly like a * genuinely unallocatable pool would. Set only by test_cfs. */ extern bool cfs_test_pool_block_victim; /* ================================================================ * Read scratch arena (QDB-1513 P4-2) * * Fixed-slot shared arena backing the offloaded read path: the planning * backend claims a slot, describes the span (per-block plan entries) in * it and points a vanilla PGAIO_OP_READV at the slot's span buffer; the * IO executor (worker, or the owner backend when completion is reaped * inline) validates and decompresses the records straight into the * pinned target buffers and releases the slot. The arena is sized at * server start; 0 slots (cfs_read_scratch_mb = 0 or a GUC budget too * small for one slot) keeps every read on the inline path. * ================================================================ */ /* * cfs_read_scratch_slot_count — number of scratch slots the GUCs buy: * min(2 * io_max_concurrency, the cfs_read_scratch_mb budget). Zero * when the arena is off. Pure GUC arithmetic, valid before the shared * memory is up (the cfs_map_pool_segments() model); requires * io_max_concurrency to have been resolved, which AioShmemSize() does * before CfsShmemSize() runs. */ extern int cfs_read_scratch_slot_count(void); /* True when the arena actually has at least one slot. */ extern bool cfs_read_scratch_effective(void); /* * cfs_read_span_capacity — per-slot span buffer size in bytes: the * largest block count one IO can carry (io_max_combine_limit) times the * largest possible record (a RAW page and its header, CFS_RECORD_SIZE * aligned). A span longer than this cannot be offloaded and stays * inline. */ extern Size cfs_read_span_capacity(void); /* * cfs_read_scratch_acquire — claim a FREE slot (state -> BUILDING) and * reset its bookkeeping. The caller then fills entries[] and span_len * and hands the slot to its IO with cfs_read_scratch_publish(). Returns * NULL when every slot is busy: the caller degrades that span to the * inline read path (never waits). */ extern CfsReadScratchSlot *cfs_read_scratch_acquire(void); /* * cfs_read_scratch_publish — after the plan is fully written, make the * slot visible to the IO executor (BUILDING -> INFLIGHT). The executor * pairs this with a read barrier before loading the plan. */ extern void cfs_read_scratch_publish(CfsReadScratchSlot *slot); /* * cfs_read_scratch_release — return a slot to the arena (-> FREE). The * executor calls this as the last step of completion; the planning * backend calls it on abort paths that never reach submission. After * the call the slot may be re-acquired and overwritten by anyone. */ extern void cfs_read_scratch_release(CfsReadScratchSlot *slot); /* * cfs_read_scratch_span — the slot's span buffer (cfs_read_span_capacity() * bytes): the destination of the raw preadv the IO worker performs. */ extern char *cfs_read_scratch_span(const CfsReadScratchSlot *slot); /* * cfs_read_scratch_slot / cfs_read_scratch_slot_index — map between the * slot array and the uint32 slot id carried in the AIO target data. */ extern CfsReadScratchSlot *cfs_read_scratch_slot(uint32 slot_id); extern uint32 cfs_read_scratch_slot_index(const CfsReadScratchSlot *slot); /* * cfs_read_scratch_exhaustions — acquisitions that found no free slot and * degraded to the inline path. A growing value means the arena is * undersized for the workload (or the budget in cfs_read_scratch_mb). */ extern uint64 cfs_read_scratch_exhaustions(void); /* * Outcome of cfs_read_span_plan(). */ typedef enum CfsReadPlanStatus { CFS_READ_PLAN_DEGRADE = 0, /* not offloadable: serve inline */ CFS_READ_PLAN_OK = 1, /* plan built; caller submits the IO */ CFS_READ_PLAN_FAIL = 2, /* fail_code/fail_block set: encode the * inline failure code as today */ } CfsReadPlanStatus; /* * cfs_read_span_plan — build the offload plan for one readv request * (QDB-1513 P4-2). Gathers the map rows of [blocknum, blocknum+nblocks) * exactly like cfs_read_pages_batch() and requires them to form ONE * physically contiguous run inside one .cfp segment — the request shape * smgrmaxcombine() promises for a combined read. Anything else * (race-shrunk run, pool miss, hole, offset gap, segment boundary, * exhausted arena) returns DEGRADE: the whole request takes the inline * path, so the buffers of one IO are never written by both paths. * * Map-row validation, the span boundary check and the segment fd are the * backend's half of cfs_read_records_span(); on their failure the pool * bookkeeping mirrors cfs_read_pages_batch() and FAIL is returned with * fail_code/fail_block set for the caller's inline failure encoding. * * On OK the slot is filled but NOT published: the caller registers the * IO and publishes with cfs_read_scratch_publish() as the last step * before staging, so an aborted submit leaves no INFLIGHT slot. The * caller receives the raw segment fd and the span's global .cfp offset. */ extern 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); /* * cfs_read_span_corrupt_bookkeeping — pool-side failure bookkeeping for * an offloaded span whose executor detected corruption: count the crc * failure and drop the failing block's pool entry, so the next read * re-resolves it from the journal — exactly what cfs_read_pages_batch() * does when cfs_read_records_span() fails on pool-sourced rows. A no-op * for private-map plans ('pooled' false), mirroring the inline rule. * Callable from the IO executor (shared-memory state only). */ extern void cfs_read_span_corrupt_bookkeeping(RelFileLocatorBackend rl, ForkNumber forknum, BlockNumber fail_block, bool pooled); /* The per-relation statistics API moved to cfs_stats.h. */ #include "storage/cfs/cfs_stats.h" /* ================================================================ * Cache integration with the storage layer * ================================================================ */ /* * cfs_map_contiguous_run — advisory length of the physically contiguous * .cfp run starting at 'blocknum' (capped at 'maxblocks'): cheap lookups of * already-resident map state only, no I/O; at least 1. Used by * cfs_smgr_maxcombine(); correctness of reads never depends on it. */ extern int cfs_map_contiguous_run(CfsRelation *cfs, BlockNumber blocknum, BlockNumber maxblocks); /* * cfs_read_pages_batch — fill nblocks buffers starting at blocknum, * batching physically contiguous runs of records into single preads and * degrading everything else to the per-block cfs_read_page_cached() path. * On failure stores the first failure code and failing block (when the * out-parameters are non-NULL) and returns it, mirroring the pre-batching * contract of cfs_read_blocks_status(). */ extern int cfs_read_pages_batch(CfsRelation *cfs, BlockNumber blocknum, void **buffers, BlockNumber nblocks, int *fail_code, BlockNumber *fail_block); /* * cfs_read_page_cached — read & decompress one page, consulting the shared * map cache first and populating it on a miss. Compression / decompression * and disk I/O happen outside any CFS partition lock. */ extern int cfs_read_page_cached(CfsRelation *cfs, BlockNumber blocknum, char *dst); /* * cfs_write_page_cached — write one page through the storage engine, then * publish the new map entry into the shared cache and update statistics. * The exclusive partition lock is held only around the cache update, never * around compression or the .cfp / .cfsjrn appends. */ extern int cfs_write_page_cached(CfsRelation *cfs, BlockNumber blocknum, const char *src, const CfsWriteOptions *opts); /* ================================================================ * Append serialization * * cfs_append_lock_acquire / cfs_append_lock_release serialise all writes to * the append-only .cfp / .cfsjrn files of one relation across backends. * The lock lives inside the relation's CfsRelMetaSlot and is therefore * private to that one relation: two unrelated relations never contend on * the same lock, even when their hash values collide on the same * partition. The caller must ensure the metadata slot is pinned (it is * pinned when the SMgrRelation handle is opened, or explicitly for * compaction) before the first acquire, so the slot — and hence the lock * — cannot be evicted while it is in use. If the slot is not found the * call raises ERROR: the relation cannot be written without its lock. * ================================================================ */ extern void cfs_append_lock_acquire(RelFileLocatorBackend rlocator, ForkNumber forknum, LWLockMode mode); extern bool cfs_append_lock_try_acquire(RelFileLocatorBackend rlocator, ForkNumber forknum); extern void cfs_append_lock_release(RelFileLocatorBackend rlocator, ForkNumber forknum); extern void cfs_append_lock_release_after_error(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * ================================================================ * Authoritative .cfp tail (shared append cursor) * * The four operations below implement the D1 write-path protocol. All of * them look the metadata slot up by (rlocator, forknum) and are no-ops * when the relation has no slot (the unlocked single-threaded API and * pre-shmem callers then keep the cfs_cfp_discover_eof() behaviour). The * caller must hold the relation's append lock for every state-changing * operation, and must hold a pin on the slot (any smgr-path handle does) * for the returned state to stay valid. * ================================================================ */ /* * cfs_cfp_tail_fetch — read the slot's authoritative .cfp tail. Returns * true and stores the tail in *out_tail when the slot exists and its * append state is CFS_CFP_APPEND_IDLE; returns false for a missing slot, * IN_PROGRESS (an appender crashed or is mid-append) and DIRTY (stale * tail), in which case the caller must re-discover the chain end. */ extern bool cfs_cfp_tail_fetch(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 *out_tail); /* * cfs_cfp_tail_begin — mark the slot's append as IN_PROGRESS with this * backend as the recorded owner, immediately before the record pwrite. * A crash between the pwrite and cfs_cfp_tail_commit() leaves this state * behind, so the next writer cannot trust the stored tail. */ extern void cfs_cfp_tail_begin(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * cfs_cfp_tail_commit — publish the new authoritative tail after a * successful pwrite and return the slot to CFS_CFP_APPEND_IDLE. The value * must be the first free offset after the record just written (aligned). */ extern void cfs_cfp_tail_commit(RelFileLocatorBackend rlocator, ForkNumber forknum, uint64 new_tail); /* * cfs_cfp_tail_dirty — drop trust in the stored tail (state DIRTY): used * after a failed pwrite, when the sidecar pair was replaced (compaction * swap) and anywhere else the tail may no longer match the files. */ extern void cfs_cfp_tail_dirty(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * cfs_compact_mark_active / cfs_compact_mark_inactive — publish the * "an online compaction owns this relation's candidate files" mark * (QDB-1514). The mark is set under the append lock before the compaction * releases it for the copy phase, and cleared on every completion path. * A backend that died between the two (FATAL, crash) leaves the mark * behind; cfs_map_cache_compaction_active() then reports it inactive via * the pid liveness check, so the interrupted-swap recovery below the * storage layer treats the candidates as orphans and cleans them up. */ extern void cfs_compact_mark_active(RelFileLocatorBackend rlocator, ForkNumber forknum); extern void cfs_compact_mark_inactive(RelFileLocatorBackend rlocator, ForkNumber forknum); /* * cfs_map_cache_compaction_active — is an online compaction with a live * owner running for this relation fork? Installed as the compaction * provider of the ownership-state judge (cfs_state.c) so the storage layer * can ask without calling into this one. */ extern bool cfs_map_cache_compaction_active(RelFileLocatorBackend rlocator, ForkNumber forknum); /* ================================================================ * Background worker control * * Pause / resume / status for the automatic CfsBgWorker. These operate on * the shared CfsBgControl block protected by a dedicated LWLock. * ================================================================ */ /* * cfs_bg_pause — suspend automatic compaction until cfs_bg_resume() or, * when 'paused_until' is non-zero, until that timestamp passes. */ extern void cfs_bg_pause(int64 paused_until); /* Clear the pause flag immediately. */ extern void cfs_bg_resume(void); /* Return true when automatic compaction is currently paused. */ extern bool cfs_bg_is_paused(void); /* * Record / look up the last compaction (or failed attempt) time of a * relation in the shared bgworker history hash. The caller enforces the * cfs_bg_min_interval_s throttle on top of these timestamps. The entries * are keyed by (database, relation), so equal relids in different * databases do not interfere. */ extern void cfs_bg_history_set(Oid relid, TimestampTz ts); extern TimestampTz cfs_bg_history_get(Oid relid); /* * Retire history entries older than cfs_bg_min_interval_s: they cannot * matter any more, and retiring them also retires the entries of dropped * relations (entries of that kind age out; no catalog cross-check like * pgstat's is needed, because the history is not persistent). Called by * the launcher after each cycle. */ extern void cfs_bg_history_sweep(void); /* Record that a worker cycle just started / finished. */ extern void cfs_bg_set_cycle_started(void); extern void cfs_bg_set_cycle_finished(void); /* Read the current bgworker control state into *out. */ typedef struct CfsBgStatus { bool paused; int64 paused_until; int64 last_cycle_started_at; int64 last_cycle_finished_at; } CfsBgStatus; extern void cfs_bg_get_status(CfsBgStatus *out); #endif /* CFS_SHMEM_H */