/*------------------------------------------------------------------------- * cfs_storage.c * Compressed File Store (CFS) — autonomous storage engine. * * Implements the standalone CFS storage layer declared in cfs_storage.h. * It manages the three sidecar files (.cfp / .cfsmap / .cfsjrn) for one * relation fork and provides page-level read/write, crash-safe map updates * through the journal and the journal replay * dispatch table. * * Crash-safety summary (see cfs_storage.h for the full model): * * write: compress -> append to .cfp -> append journal record -> map * open: load .cfsmap snapshot -> replay .cfsjrn -> in-memory map ready * checkpoint: rewrite .cfsmap atomically -> truncate .cfsjrn * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_storage.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include #include #include "access/xlogdefs.h" #include "access/xlogutils.h" #include "common/relpath.h" #include "port.h" #include "port/pg_iovec.h" #include "storage/block.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_cfp.h" #include "storage/cfs/cfs_compress.h" #include "storage/cfs/cfs_format.h" #include "storage/cfs/cfs_guc.h" #include "storage/cfs/cfs_journal.h" #include "storage/cfs/cfs_map_file.h" #include "storage/cfs/cfs_path.h" #include "storage/cfs/cfs_recovery.h" #include "storage/cfs/cfs_stats.h" #include "storage/cfs/cfs_sync.h" #include "storage/cfs/cfs_state.h" #include "storage/cfs/cfs_swap.h" #include "storage/cfs/cfs_storage.h" #include "storage/fd.h" #include "storage/relfilelocator.h" #include "utils/injection_point.h" #include "utils/memutils.h" #include "utils/palloc.h" #include "utils/timestamp.h" #include "utils/wait_event.h" /* Compile-time sanity: the page size we operate on must match BLCKSZ. */ StaticAssertDecl(CFS_BLCKSZ == BLCKSZ, "CFS_BLCKSZ must match PostgreSQL BLCKSZ"); /* * The .cfp segment size must match the relation-file convention exactly * (RELSEG_SIZE blocks of BLCKSZ) and be a multiple of the record alignment * so that a global offset maps to a naturally aligned in-segment offset. */ StaticAssertDecl(CFS_SEGMENT_SIZE == (uint64) RELSEG_SIZE * BLCKSZ, "CFS_SEGMENT_SIZE must equal RELSEG_SIZE * BLCKSZ"); StaticAssertDecl(CFS_SEGMENT_SIZE % CFS_BLOCK_ALIGN == 0, "CFS_SEGMENT_SIZE must be a multiple of CFS_BLOCK_ALIGN"); /* ================================================================ * Internal I/O helpers * ================================================================ * * The raw primitives (cfs_pwrite_all / cfs_pread_all / cfs_fd_size) * moved to cfs_io.c: every CFS module shares them, and keeping them out * of cfs_storage.c lets the sibling headers depend on cfs_io.h only. */ /* Forward: used by cfs_open_paths before its definition below. */ static int cfs_map_load_header(CfsRelation *cfs); /* * Ensure the .cfp file has its reserved lead-in. Real records begin at * CFS_CFP_BASE_OFFSET, so a physical_offset below that unambiguously means * "block absent". The lead-in carries the file-creation epoch; a zero * lead-in means "unknown epoch" and readers fall back to a full copy. */ static int cfs_ensure_cfp_leadin(int fd) { off_t sz = cfs_fd_size(fd); CfsDataFileLeadIn leadin; if (sz < 0) return CFS_STORAGE_ERROR; if (sz >= (off_t) CFS_CFP_BASE_OFFSET) return CFS_STORAGE_OK; leadin.epoch = (uint64) GetCurrentTimestamp(); return cfs_pwrite_all(fd, &leadin, sizeof(leadin), sz); } /* * cfs_read_cfp_epoch * Read the lead-in epoch of a .cfp file (any segment-0 path). * * Returns true and sets *epoch on success. Returns false and sets *epoch * to 0 when the file is missing, unreadable or shorter than the lead-in; * callers must treat that (and a zero epoch) as "unknown epoch". */ bool cfs_read_cfp_epoch(const char *cfp_path, uint64 *epoch) { CfsDataFileLeadIn leadin; int fd; *epoch = 0; fd = BasicOpenFile(cfp_path, O_RDONLY | PG_BINARY); if (fd < 0) { elog(DEBUG1, "CFS: could not open \"%s\" to read the lead-in epoch: %m", cfp_path); return false; } if (cfs_pread_all(fd, &leadin, sizeof(leadin), 0) != CFS_STORAGE_OK) { close(fd); elog(DEBUG1, "CFS: could not read the lead-in epoch of \"%s\": %m", cfp_path); return false; } close(fd); *epoch = leadin.epoch; elog(DEBUG1, "CFS: .cfp file \"%s\" has epoch " UINT64_FORMAT, cfp_path, leadin.epoch); return true; } /* * Remember the journal incarnation of a (re)opened handle for the ABA * staleness check in cfs_refresh_map(). The delta-replay cursor is * baselined by cfs_map_load() at the offset where the replay actually * stopped. Kept in one place so that cfs_open_paths() and cfs_reopen() * cannot drift. */ static void cfs_baseline_journal_cursor(CfsRelation *cfs) { CfsJournalFileHeader jhdr; if (cfs_journal_read_header(cfs->jrn_fd, &jhdr)) cfs->jrn_incarnation = jhdr.incarnation; } /* * True when the .cfsmap file was replaced (compaction swap) since this * handle opened it: the handle's descriptor then points at the old inode, * and reloading the map through it would mix the old snapshot with journal * records whose offsets reference the new .cfp. The derivation moved to * the ownership-state judge (cfs_state.c); the reopen policy stays here. */ bool cfs_reopen_if_map_swapped(CfsRelation *cfs) { if (!cfs_map_file_swapped(cfs)) return false; (void) cfs_reopen(cfs); return true; } /* * Ensure the .cfsjrn file starts with a valid journal header. When the file * is empty or shorter than the header, write a fresh header at offset 0 so * that appended records are discoverable during replay. */ static int cfs_ensure_journal_header(int fd) { off_t sz = cfs_fd_size(fd); if (sz < 0) return CFS_STORAGE_ERROR; if (sz >= (off_t) CFS_JOURNAL_HEADER_SIZE) return CFS_STORAGE_OK; { CfsJournalFileHeader jhdr; cfs_journal_header_init(&jhdr); return cfs_pwrite_all(fd, &jhdr, sizeof(jhdr), 0); } } /* ================================================================ * Path construction * ================================================================ */ /* * Build the three sidecar paths for a relation fork into caller-provided * char * slots. Returns false when the locator is unsupported (temp). */ static bool cfs_build_paths(RelFileLocatorBackend rlocator, ForkNumber forknum, char **cfp_path, char **map_path, char **jrn_path) { *cfp_path = cfs_make_filename(rlocator, forknum, CFS_FILE_DATA); if (*cfp_path == NULL) return false; *map_path = cfs_make_filename(rlocator, forknum, CFS_FILE_MAP); *jrn_path = cfs_make_filename(rlocator, forknum, CFS_FILE_JOURNAL); return true; } /* ================================================================ * Relation lifecycle * ================================================================ */ /* * Allocate a CfsRelation and fill in paths / fds / scratch buffer. The * in-memory map is loaded afterwards by cfs_map_load(). */ static CfsRelation * cfs_alloc_relation(RelFileLocatorBackend rlocator, ForkNumber forknum, char *cfp_path, char *map_path, char *jrn_path, int flags) { CfsRelation *cfs; MemoryContext oldcontext; cfs = palloc0(sizeof(CfsRelation)); cfs->rlocator = rlocator; cfs->forknum = forknum; cfs->flags = flags; cfs->cfp_path = cfp_path; cfs->map_path = map_path; cfs->jrn_path = jrn_path; cfs->cfp_fd = -1; cfs->cfp_append_segno = 0; cfs->cfp_read_fd = -1; cfs->cfp_read_segno = 0; cfs->map_fd = -1; cfs->jrn_fd = -1; cfs->read_only = ((flags & CFS_OPEN_RDONLY) != 0); cfs->strict = ((flags & CFS_OPEN_STRICT) != 0); /* * Scratch buffer survives across writes; keep it in TopMemoryContext so * it is not freed prematurely by a per-query context reset. */ oldcontext = MemoryContextSwitchTo(TopMemoryContext); cfs->compress_scratch_sz = CfsCompressScratchSize(CFS_BLCKSZ); cfs->compress_scratch = palloc(cfs->compress_scratch_sz); MemoryContextSwitchTo(oldcontext); return cfs; } /* ---------------------------------------------------------------- * Crash-safe compaction swap. * * Compaction builds a fresh .cfp / .cfsmap pair whose physical offsets * differ from the old pair. Swapping both files in place with two * independent renames is not atomic: a crash between them leaves a new .cfp * combined with the old .cfsmap, after which every read returns garbage. * * The protocol below uses a single durable commit marker (".cfsswap") so the * pair always switches atomically: * * 1. write & fsync .cfp[.N].tmp, .cfsmap.cfscand (one tmp per .cfp * segment; the map candidate's suffix is compaction-specific so it * can never collide with the snapshot writer's ".tmp") * 2. rename .cfp[.N].tmp -> .cfp[.N].new (durable_rename, per segment) * 3. rename .cfsmap.cfscand -> .cfsmap.new (durable_rename) * 4. create ".cfsswap" + fsync parent dir <-- COMMIT POINT * 5. rename .cfp[.N].new -> .cfp[.N] (activate data, per segment) * 6. rename .cfsmap.new -> .cfsmap (activate map) * 7. unlink stale .cfp segments of the old chain beyond the new EOF * 8. reset .cfsjrn to a bare header + fsync (journal reset) * 9. unlink ".cfsswap" + fsync parent dir * * Existence of ".cfsswap" means the candidate pair (.cfp[.N].new / * .cfsmap.new) is fully durable and ready; recovery simply finishes the * activation renames (they are idempotent: a missing ".new" file means * that rename already happened) and repeats the trailing-segment cleanup * of step 7, driven by the freshly activated map's cfp_size. If * ".cfsswap" is absent, any leftover candidate / temp files are orphaned * and removed, leaving the old pair in place. * * Step 8 must happen before the marker is dropped: the journal records * reference physical offsets of the *pre-swap* .cfp, so replaying them on * top of the freshly swapped-in map would corrupt it. Recovery therefore * repeats the journal reset (idempotently) whenever it finds the marker, * which closes the crash window between step 6 and the durable journal * reset. * ---------------------------------------------------------------- */ /* The swap protocol (rename/unlink helpers, trailing-segment cleanup, * marker and the interrupted-swap recovery) moved to cfs_swap.c. */ /* cfs_journal_fd_scan_max_generation moved to cfs_journal.c: it is a * journal-stream aggregate, and the review rules keep every journal read * in the scan engine's home. */ /* * The all-missing probe of CFS_OPEN_MISSING_OK: true only when every one * of the three sidecars is absent (ENOENT). A partially-present pair is * damage, not a race with a drop, and must fail loudly as always. */ static bool cfs_sidecars_missing(const char *cfp_path, const char *map_path, const char *jrn_path) { struct stat st; return stat(cfp_path, &st) != 0 && errno == ENOENT && stat(map_path, &st) != 0 && errno == ENOENT && stat(jrn_path, &st) != 0 && errno == ENOENT; } CfsRelation * cfs_open_paths(RelFileLocatorBackend rlocator, ForkNumber forknum, const char *cfp_path, const char *map_path, const char *jrn_path, int flags) { CfsRelation *cfs; bool create = ((flags & CFS_OPEN_CREATE) != 0); volatile bool guarded = false; /* * The optional-open contract (CFS_OPEN_MISSING_OK): the sidecars vanished * between the caller's check and here - the relation was dropped or * rewritten - so there is nothing to open and nothing to persist; the * caller that asked for the soft contract handles the NULL. Checked * before the compaction recovery below, which must not touch the files of * a relation that no longer exists. */ if ((flags & CFS_OPEN_MISSING_OK) && cfs_sidecars_missing(cfp_path, map_path, jrn_path)) return NULL; /* * Make sure any interrupted compaction swap is resolved before we touch * the sidecars, so we always open a self-consistent .cfp / .cfsmap pair * -- unless an online compaction is running right now (QDB-1514): its * .tmp/.new candidates are live state owned by the compactor, not * orphans. Only a dead owner (crashed backend, FATAL without cleanup) * leaves candidates this recovery may discard; the liveness answer * comes from the state judge's compaction provider. */ if (!cfs_state_compaction_active(rlocator, forknum)) cfs_recover_compaction(cfp_path, map_path, jrn_path); cfs = cfs_alloc_relation(rlocator, forknum, pstrdup(cfp_path), pstrdup(map_path), pstrdup(jrn_path), flags); /* * Serialize the descriptor resolution and the generation tagging below * against an online compaction's swap phase (QDB-1514): a shared hold * of the append lock, taken unconditionally (it is cheap — opens are * per-handle, not per-read) so that a compaction starting mid-open * cannot slip past either. Without it, the opened descriptors and the * tag could straddle the swap: a mixed old/new pair that no staleness * check can detect afterwards. The guard is a no-op for callers that * already hold the append lock (checkpoint, fsck, the compactor * itself) and before the shared memory exists (single-threaded * startup). Acquired after the allocation above: an ERROR in the * allocation must not leak the guard's pin, and abort's * LWLockReleaseAll() knows nothing about pins. * * The guard deliberately covers ONLY the descriptor resolution and the * generation tag. The map load and the journal replay below read * through the already-opened descriptors and run OUTSIDE the lock: a * compaction that swaps the pair mid-load bumps the slot generation, * the handle's tag then disagrees with the slot, and the regular * staleness machinery (refresh-if-stale, the read gate) reopens — the * same protocol that already covers a concurrent TRUNCATE or immedsync. * Holding the shared append lock across the whole load would instead * serialize every checkpoint fold and immedsync against cold opens * (an O(map) writer stall), and is directly observable as a lost * journal reset in test_cfs t/005. */ /* * The handle's descriptors are raw (not tracked by the VFD layer or the * resource owner), and its scratch/map memory lives in TopMemoryContext, * so neither is reclaimed by a transaction abort. Any ERROR between here * and the successful return must therefore close the half-built handle * explicitly, or a caller that catches the error and keeps running (the * background compaction worker) leaks the descriptors and the memory for * the rest of the process lifetime. */ PG_TRY(); { guarded = cfs_state_open_guard_acquire(rlocator, forknum); ereport(DEBUG1, (errmsg("CFS: opening sidecars cfp=\"%s\" map=\"%s\" jrn=\"%s\" (create=%d)", cfs->cfp_path, cfs->map_path, cfs->jrn_path, (int) create))); cfs->cfp_fd = cfs_open_sidecar(cfs->cfp_path, flags, create); cfs->map_fd = cfs_open_sidecar(cfs->map_path, flags, create); cfs->jrn_fd = cfs_open_sidecar(cfs->jrn_path, flags, create); if (cfs->cfp_fd < 0 || cfs->map_fd < 0 || cfs->jrn_fd < 0) { ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not open sidecar files for relation"), errdetail("cfp=\"%s\" map=\"%s\" jrn=\"%s\".", cfs->cfp_path, cfs->map_path, cfs->jrn_path))); } /* Make sure the .cfp lead-in exists. */ if (!cfs->read_only && cfs_ensure_cfp_leadin(cfs->cfp_fd) != CFS_STORAGE_OK) { ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not initialise .cfp lead-in for \"%s\"", cfs->cfp_path))); } /* Make sure the .cfsmap carries its prologue. */ if (!cfs->read_only) { int rc = cfs_map_file_prologue_ensure(cfs->map_fd); if (rc == CFS_STORAGE_CORRUPT) { /* * Structural corruption of an existing prologue: during * recovery keep the historical hard ERROR; outside * recovery route through the centralised handler, so the * cfs_checksum_failure GUC decides ERROR or PANIC. */ if (!cfs_corruption_guc_applies()) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: corrupt page map snapshot"), errdetail("File \"%s\" has a truncated header.", cfs->map_path))); else cfs_report_corruption(cfs->rlocator, cfs->forknum, InvalidBlockNumber, psprintf("page map file \"%s\" has " "a truncated header", cfs->map_path), false); } if (rc != CFS_STORAGE_OK) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not initialise page map \"%s\"", cfs->map_path))); } /* Make sure the .cfsjrn header exists for new files. */ if (!cfs->read_only && cfs_ensure_journal_header(cfs->jrn_fd) != CFS_STORAGE_OK) { ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not initialise .cfsjrn header for \"%s\"", cfs->jrn_path))); } /* * Set append cursors from the actual file sizes. The .cfp cursor is * the global EOF of the segment chain; cfp_fd ends up on the last * existing segment. */ cfs->cfp_write_off = cfs_cfp_discover_eof(cfs); if (cfs->cfp_write_off < (off_t) CFS_CFP_BASE_OFFSET) cfs->cfp_write_off = CFS_CFP_BASE_OFFSET; cfs->jrn_write_off = cfs_fd_size(cfs->jrn_fd); if (cfs->jrn_write_off < (off_t) CFS_JOURNAL_HEADER_SIZE) cfs->jrn_write_off = CFS_JOURNAL_HEADER_SIZE; /* * Tag the freshly opened handle with the shared-cache map generation: * compaction bumps it when it swaps the sidecar files, and holders * detect the mismatch and reopen. Setting it here — the single * place that opens sidecars — keeps every caller (cfs_open, * cfs_create) from hand-maintaining the field, which used to leave it * at the palloc0 zero and make the handle look stale on its first * use. Still under the guard: the tag and the descriptors must not * straddle a swap (see the comment above the acquire). */ cfs->open_generation = cfs_state_relation_generation(rlocator, forknum); /* * The guarded part of the open ends here: from this point the * handle owns its descriptors and its generation tag, and a swap * that interleaves with the map load below is detected through the * generation protocol instead of excluded by the lock. */ if (guarded) { cfs_state_open_guard_release(rlocator, forknum, false); guarded = false; } /* * Rebuild the in-memory map from snapshot + journal. A lazy handle * (regular smgr paths) reads only the snapshot header and resolves * entries through the shared segment pool instead. */ if ((flags & CFS_OPEN_LAZY_MAP) != 0) { if (cfs_map_load_header(cfs) != CFS_STORAGE_OK) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not load page map header for \"%s\"", cfs->map_path))); } } else if (cfs_map_load(cfs, (flags & CFS_OPEN_REPAIR_TAIL) != 0, ((flags & CFS_OPEN_RECOVERY_SCAN) != 0) ? CFS_LOAD_RECOVERY : CFS_LOAD_NORMAL) != CFS_STORAGE_OK) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not load page map for \"%s\"", cfs->map_path))); } /* * The initial map_load already replayed the journal, so the in-memory * map reflects every record up to where the replay stopped (the last * valid record; a torn trailing record from a concurrent writer * mid-append is not consumed). Baseline the delta-replay cursor (set * inside map_load) so cfs_refresh_map() only replays future appends, * and remember the journal incarnation for the ABA staleness check. */ cfs_baseline_journal_cursor(cfs); ereport(DEBUG1, (errmsg("CFS: opened relation with %u logical blocks, cfp_size %llu", cfs_map_nblocks(cfs), (unsigned long long) cfs->map_hdr.cfp_size))); } PG_CATCH(); { if (guarded) cfs_state_open_guard_release(rlocator, forknum, true); cfs_close(cfs); PG_RE_THROW(); } PG_END_TRY(); if (guarded) cfs_state_open_guard_release(rlocator, forknum, false); return cfs; } CfsRelation * cfs_open(RelFileLocatorBackend rlocator, ForkNumber forknum, int flags) { char *cfp_path; char *map_path; char *jrn_path; CfsRelation *cfs; if (!cfs_build_paths(rlocator, forknum, &cfp_path, &map_path, &jrn_path)) { ereport(DEBUG1, (errmsg("CFS: cfs_open: locator unsupported (temp relation)"))); return NULL; } cfs = cfs_open_paths(rlocator, forknum, cfp_path, map_path, jrn_path, flags); pfree(cfp_path); pfree(map_path); pfree(jrn_path); return cfs; } /* * Close every open sidecar descriptor and reset it to -1. A descriptor must * never be left holding an already-closed value, otherwise a later cfs_close() * could close a recycled number. */ static void cfs_reset_sidecar_fds(CfsRelation *cfs) { if (cfs->cfp_fd >= 0) cfs_cfp_close_fd(cfs->cfp_fd); cfs->cfp_fd = -1; if (cfs->cfp_read_fd >= 0) cfs_cfp_close_fd(cfs->cfp_read_fd); cfs->cfp_read_fd = -1; if (cfs->map_fd >= 0) close(cfs->map_fd); cfs->map_fd = -1; if (cfs->jrn_fd >= 0) close(cfs->jrn_fd); cfs->jrn_fd = -1; } /* * cfs_reopen — close and reopen the sidecar files of an existing handle, * reloading the in-memory map from the current on-disk state. Called when * a compaction swapped the files underneath this handle (detected through * the shared-cache generation, see cfs_handle_refresh_if_stale()): the old * descriptors point at the replaced inode, where writes would be lost * silently, and the in-memory map holds stale physical offsets. */ int cfs_reopen(CfsRelation *cfs) { Assert(cfs != NULL); ereport(DEBUG1, (errmsg("CFS: reopening sidecars for relation %u/%u/%u after compaction swap", cfs->rlocator.locator.spcOid, cfs->rlocator.locator.dbOid, cfs->rlocator.locator.relNumber))); PG_TRY(); { /* * Reset every field to the invalid state right after closing its * descriptor: cfs_recover_compaction() below can raise an ERROR, and * a field left holding an already-closed value would later be closed * again by cfs_close() -- by then the OS may have recycled the * numeric value for an unrelated file. */ cfs_reset_sidecar_fds(cfs); /* * Resolve any interrupted swap before touching the files -- unless * an online compaction owns the candidates right now (QDB-1514); * a dead owner's candidates are orphans and are cleaned here as * before. The reopen path runs under the append lock, so it can * never observe the owner's own short exclusive phases mid-swap. */ if (!cfs_state_compaction_active(cfs->rlocator, cfs->forknum)) cfs_recover_compaction(cfs->cfp_path, cfs->map_path, cfs->jrn_path); cfs->cfp_fd = cfs_open_sidecar(cfs->cfp_path, cfs->flags, false); cfs->cfp_append_segno = 0; cfs->map_fd = cfs_open_sidecar(cfs->map_path, cfs->flags, false); cfs->jrn_fd = cfs_open_sidecar(cfs->jrn_path, cfs->flags, false); if (cfs->cfp_fd < 0 || cfs->map_fd < 0 || cfs->jrn_fd < 0) { ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not reopen sidecar files for relation"), errdetail("cfp=\"%s\" map=\"%s\" jrn=\"%s\".", cfs->cfp_path, cfs->map_path, cfs->jrn_path))); } /* Set append cursors from the actual file sizes (segment chain EOF). */ cfs->cfp_write_off = cfs_cfp_discover_eof(cfs); if (cfs->cfp_write_off < (off_t) CFS_CFP_BASE_OFFSET) cfs->cfp_write_off = CFS_CFP_BASE_OFFSET; cfs->jrn_write_off = cfs_fd_size(cfs->jrn_fd); if (cfs->jrn_write_off < (off_t) CFS_JOURNAL_HEADER_SIZE) cfs->jrn_write_off = CFS_JOURNAL_HEADER_SIZE; /* Drop the stale map and reload from snapshot + journal. */ if (cfs->map != NULL) { pfree(cfs->map); cfs->map = NULL; } cfs->map_capacity = 0; if ((cfs->flags & CFS_OPEN_LAZY_MAP) != 0) { /* Lazy handle: only the header, the segment pool holds entries. */ if (cfs_map_load_header(cfs) != CFS_STORAGE_OK) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not load page map header for \"%s\"", cfs->map_path))); } } else if (cfs_map_load(cfs, false, CFS_LOAD_NORMAL) != CFS_STORAGE_OK) { /* * repair=false: a reopen always follows a sidecar swap, and every * swap resets the new journal to a bare header, so the only torn * tail the new journal can hold comes from a writer mid-append - * truncating it would corrupt the record out from under the * writer (see cfs_map_load). A persistent torn tail from a crash * is repaired by the recovery scan before any backend can write. * during_recovery=false also selects the non-recovery corruption * policy (cfs_checksum_failure), which is the right one for a * reopen. */ ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: could not load page map for \"%s\"", cfs->map_path))); } cfs_baseline_journal_cursor(cfs); /* * Retag the handle with the current shared-cache generation: the * caller holds the append lock, so the generation cannot move again * while we reopen, and this value matches the inode pair we just * opened. Keeping it next to the reload itself prevents the * stale-field drift that caused spurious extra reopens. */ cfs->open_generation = cfs_state_relation_generation(cfs->rlocator, cfs->forknum); } PG_CATCH(); { /* * Close whatever was opened before the failure and reset every * descriptor to -1 so a later cfs_close() never closes a recycled * number. The handle itself belongs to the caller (stored in * SMgrRelation), so do NOT cfs_close() it here. */ cfs_reset_sidecar_fds(cfs); PG_RE_THROW(); } PG_END_TRY(); return CFS_STORAGE_OK; } void cfs_close(CfsRelation *cfs) { if (cfs == NULL) return; if (cfs->cfp_fd >= 0) cfs_cfp_close_fd(cfs->cfp_fd); if (cfs->cfp_read_fd >= 0) cfs_cfp_close_fd(cfs->cfp_read_fd); if (cfs->map_fd >= 0) close(cfs->map_fd); if (cfs->jrn_fd >= 0) close(cfs->jrn_fd); if (cfs->map) pfree(cfs->map); if (cfs->cfp_path) pfree(cfs->cfp_path); if (cfs->map_path) pfree(cfs->map_path); if (cfs->jrn_path) pfree(cfs->jrn_path); if (cfs->compress_scratch) pfree(cfs->compress_scratch); pfree(cfs); } /* * Create fresh sidecar files for a relation: .cfp gets the reserved * lead-in, .cfsmap gets a header with nblocks=0, .cfsjrn gets a header. */ CfsRelation * cfs_create(RelFileLocatorBackend rlocator, ForkNumber forknum) { char *cfp_path; char *map_path; char *jrn_path; int fd; CfsJournalFileHeader jhdr; if (!cfs_build_paths(rlocator, forknum, &cfp_path, &map_path, &jrn_path)) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("CFS: cannot create sidecar files for an unsupported (temp) relation"))); } ereport(DEBUG1, (errmsg("CFS: creating sidecar files cfp=\"%s\" map=\"%s\" jrn=\"%s\"", cfp_path, map_path, jrn_path))); /* .cfp: reserved lead-in carrying the file-creation epoch. */ fd = BasicOpenFile(cfp_path, O_CREAT | O_RDWR | O_TRUNC | PG_BINARY); if (fd < 0) { ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not create .cfp file \"%s\": %m", cfp_path))); } { CfsDataFileLeadIn leadin; leadin.epoch = (uint64) GetCurrentTimestamp(); if (cfs_pwrite_all(fd, &leadin, sizeof(leadin), 0) != CFS_STORAGE_OK) { close(fd); ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not write .cfp lead-in"))); } } close(fd); /* .cfsmap: header only, nblocks=0. */ fd = BasicOpenFile(map_path, O_CREAT | O_RDWR | O_TRUNC | PG_BINARY); if (fd < 0) { ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not create .cfsmap file \"%s\": %m", map_path))); } { CfsMapPrologue prologue; cfs_map_prologue_init(&prologue); if (cfs_pwrite_all(fd, &prologue, sizeof(prologue), 0) != CFS_STORAGE_OK) { close(fd); ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not write .cfsmap header"))); } } close(fd); /* .cfsjrn: header only. */ fd = BasicOpenFile(jrn_path, O_CREAT | O_RDWR | O_TRUNC | PG_BINARY); if (fd < 0) { ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not create .cfsjrn file \"%s\": %m", jrn_path))); } cfs_journal_header_init(&jhdr); if (cfs_pwrite_all(fd, &jhdr, sizeof(jhdr), 0) != CFS_STORAGE_OK) { close(fd); ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not write .cfsjrn header"))); } close(fd); /* Open normally (read/write, no create needed now). */ { CfsRelation *cfs = cfs_open_paths(rlocator, forknum, cfp_path, map_path, jrn_path, CFS_OPEN_RDWR); pfree(cfp_path); pfree(map_path); pfree(jrn_path); return cfs; } } void cfs_unlink(RelFileLocatorBackend rlocator, ForkNumber forknum) { char *cfp_path; char *map_path; char *jrn_path; if (!cfs_build_paths(rlocator, forknum, &cfp_path, &map_path, &jrn_path)) return; ereport(DEBUG1, (errmsg("CFS: unlinking sidecar files cfp=\"%s\" map=\"%s\" jrn=\"%s\"", cfp_path, map_path, jrn_path))); /* Drop a leftover compaction swap marker first. */ { char *swap_marker = psprintf("%s%s", cfp_path, CFS_SWAP_MARKER_SUFFIX); cfs_unlink_if_exists(swap_marker); pfree(swap_marker); } /* * The .cfp chain may span multiple segments: remove them all, along with * any leftover compaction candidate / temp file of each segment. */ { uint32 segno; for (segno = 0;; segno++) { char *seg_path = (segno == 0) ? pstrdup(cfp_path) : psprintf("%s.%u", cfp_path, segno); struct stat st; if (stat(seg_path, &st) != 0) { if (errno == ENOENT) { pfree(seg_path); break; /* end of the segment chain */ } ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not stat \"%s\": %m", seg_path))); pfree(seg_path); break; /* persistent error: stop the chain walk */ } /* Drop leftover compaction candidates of this segment. */ { char *seg_new = psprintf("%s%s", seg_path, CFS_CANDIDATE_SUFFIX); char *seg_tmp = psprintf("%s.tmp", seg_path); cfs_unlink_if_exists(seg_new); cfs_unlink_if_exists(seg_tmp); pfree(seg_new); pfree(seg_tmp); } if (unlink(seg_path) != 0 && errno != ENOENT) ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not unlink \"%s\": %m", seg_path))); pfree(seg_path); } } if (unlink(map_path) != 0 && errno != ENOENT) ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not unlink \"%s\": %m", map_path))); /* Drop leftover map candidates of an interrupted compaction. */ { char *map_new = psprintf("%s%s", map_path, CFS_CANDIDATE_SUFFIX); char *map_cand = psprintf("%s%s", map_path, CFS_MAP_CANDIDATE_TMP_SUFFIX); char *map_tmp = psprintf("%s.tmp", map_path); cfs_unlink_if_exists(map_new); cfs_unlink_if_exists(map_cand); /* ".tmp" is the snapshot writer's namespace; drop it too on * relation removal - it is garbage of a dead relation either way. */ cfs_unlink_if_exists(map_tmp); pfree(map_new); pfree(map_cand); pfree(map_tmp); } if (unlink(jrn_path) != 0 && errno != ENOENT) ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not unlink \"%s\": %m", jrn_path))); /* * QDB-1514: the metadata slot survives the file removal (it is dropped * lazily), and its published .cfp tail refers to the deleted chain. * Drop the tail's trust now: the next writer on a recreated relation * must re-discover the chain end instead of appending at the stale * offset. No-op when the slot does not exist or the provider is not * installed yet (single-threaded startup). */ cfs_state_cfp_tail_dirty(rlocator, forknum); pfree(cfp_path); pfree(map_path); pfree(jrn_path); } bool cfs_exists(RelFileLocatorBackend rlocator, ForkNumber forknum) { char *cfp_path; char *map_path; char *jrn_path; struct stat st; bool result; if (!cfs_build_paths(rlocator, forknum, &cfp_path, &map_path, &jrn_path)) return false; result = (stat(cfp_path, &st) == 0 || stat(map_path, &st) == 0 || stat(jrn_path, &st) == 0); pfree(cfp_path); pfree(map_path); pfree(jrn_path); return result; } const char * cfs_relation_path(const CfsRelation *cfs, CfsFileKind kind) { switch (kind) { case CFS_FILE_DATA: return cfs->cfp_path; case CFS_FILE_MAP: return cfs->map_path; case CFS_FILE_JOURNAL: return cfs->jrn_path; default: Assert(false); return NULL; } } /* ================================================================ * .cfp append-only data file * ================================================================ */ int cfs_append_compressed_record(CfsRelation *cfs, const CfsCompressResult *cres, CfsMapEntry *out_entry) { off_t offset; uint64 shared_tail; int rc; Assert(cfs != NULL && cres != NULL && out_entry != NULL); Assert(!cfs->read_only); /* Report the .cfp append as a wait event. */ pgstat_report_wait_start(WAIT_EVENT_CFS_WRITE); /* * Determine the append offset (the D1 shared-tail protocol). * * The caller (cfs_write_page_cached) holds the per-relation append lock, * so no other backend can be appending to .cfp concurrently. A local * per-handle cache would still be wrong: another backend may have * appended (and released the lock) since this handle last wrote, so the * authoritative end lives in the relation's metadata slot. It is * trustworthy exactly when the slot's append state is IDLE: a crashed or * failed appender leaves IN_PROGRESS/DIRTY behind and every writer must * then re-walk the chain (cfs_cfp_discover_eof stays the single rule for * segment chaining, including the torn-tail alignment below). */ if (cfs_state_cfp_tail_fetch(cfs->rlocator, cfs->forknum, &shared_tail)) { offset = (off_t) CFS_ALIGN_UP(shared_tail); if (offset < (off_t) CFS_CFP_BASE_OFFSET) offset = CFS_CFP_BASE_OFFSET; cfs->cfp_write_off = offset; } else { off_t real_off = cfs_cfp_discover_eof(cfs); if (real_off < 0) { pgstat_report_wait_end(); ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not stat .cfp to determine append offset"))); return CFS_STORAGE_ERROR; } if (real_off < (off_t) CFS_CFP_BASE_OFFSET) real_off = CFS_CFP_BASE_OFFSET; cfs->cfp_write_off = CFS_ALIGN_UP(real_off); } /* The append cursor is now authoritative. */ offset = cfs->cfp_write_off; Assert(CFS_ALIGN_UP(offset) == (size_t) offset); /* * Segment rollover: a record never crosses a segment boundary. When it * would not fit into the current segment, advance the cursor to the next * boundary; the unwritten tail of the previous segment is padding * (shorter than one maximal record) that fsck recognises and skips. */ offset = (off_t) cfs_cfp_roll_offset((uint64) offset, cres->total_size); /* Make sure the append descriptor points at the target segment. */ if (CFS_CFP_SEGNO(offset) != cfs->cfp_append_segno) cfs_cfp_switch_append_segment(cfs, CFS_CFP_SEGNO(offset)); /* * Announce the append before touching the file: a crash between the * pwrite and the tail publication below leaves IN_PROGRESS in the slot, * and the next writer re-discovers the chain end instead of trusting a * tail that may or may not include this record. Nothing between this * mark and the publication below can raise an ERROR: the segment switch * above already ran, and both write primitives return status codes * instead of throwing. */ cfs_state_cfp_tail_begin(cfs->rlocator, cfs->forknum); if (cres->payload_external) { /* * D4: a RAW record written straight from the caller's page: the * 28-byte header sits in the scratch buffer, the payload is the * original page and the zeroed alignment padding comes from a * static const buffer. Three iovecs, no 8 KiB copy. */ static const char zero_pad[CFS_BLOCK_ALIGN] = {0}; struct iovec iov[3]; int iovcnt = 0; iov[iovcnt].iov_base = cres->result_data; iov[iovcnt].iov_len = CFS_BLOCK_HEADER_SIZE; iovcnt++; iov[iovcnt].iov_base = cres->payload_data; iov[iovcnt].iov_len = cres->compressed_size; iovcnt++; if (cres->padding_bytes > 0) { iov[iovcnt].iov_base = (void *) zero_pad; iov[iovcnt].iov_len = cres->padding_bytes; iovcnt++; } rc = cfs_pwritev_all(cfs->cfp_fd, iov, iovcnt, CFS_CFP_SEG_OFF(offset)); } else rc = cfs_pwrite_all(cfs->cfp_fd, cres->result_data, cres->total_size, CFS_CFP_SEG_OFF(offset)); if (rc != CFS_STORAGE_OK) { /* * The file end is now whatever the failed write left behind: the * stored tail must not be trusted by the next writer. */ cfs_state_cfp_tail_dirty(cfs->rlocator, cfs->forknum); pgstat_report_wait_end(); ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not append record to .cfp at offset %llu", (unsigned long long) offset))); return CFS_STORAGE_ERROR; } pgstat_report_wait_end(); /* Advance the append cursor and publish the authoritative tail. */ cfs->cfp_write_off = offset + cres->total_size; cfs->map_hdr.cfp_size = (uint64) cfs->cfp_write_off; cfs_state_cfp_tail_commit(cfs->rlocator, cfs->forknum, (uint64) cfs->cfp_write_off); /* * Build the new map entry. The generation counter is left at zero here; * the caller (cfs_write_page) knows the logical block number and sets the * real monotonically-increasing generation before journaling the update. */ MemSet(out_entry, 0, sizeof(CfsMapEntry)); out_entry->physical_offset = (uint64) offset; out_entry->compressed_size = cres->compressed_size; out_entry->generation = 0; cfs_map_entry_crc_set(out_entry); return CFS_STORAGE_OK; } int cfs_compress_page(CfsRelation *cfs, const void *page, size_t page_size, const CfsWriteOptions *opts, CfsCompressResult *cres) { CfsCompressOptions copts; Assert(cfs != NULL && page != NULL && opts != NULL && cres != NULL); Assert(page_size == CFS_BLCKSZ); /* Translate write options into compress options. */ MemSet(&copts, 0, sizeof(copts)); copts.algorithm = opts->algorithm; copts.level = opts->level; copts.explicit_algorithm = opts->explicit_algorithm; copts.allow_raw_fallback = opts->allow_raw_fallback; copts.min_gain_bytes = opts->min_gain_bytes; /* * Report the compress as a wait event so the (potentially expensive) * compression time stays visible in pg_stat_wait_events. This mirrors * the pre-split behaviour where the compress and the .cfp append were a * single function covered by WAIT_EVENT_CFS_WRITE. */ pgstat_report_wait_start(WAIT_EVENT_CFS_WRITE); CfsCompressPageNoCopy(page, page_size, &copts, cfs->compress_scratch, cfs->compress_scratch_sz, cres); pgstat_report_wait_end(); return CFS_STORAGE_OK; } int cfs_read_raw_record(CfsRelation *cfs, off_t offset, uint32 compressed_size, void *buf) { size_t rec_size = CFS_RECORD_SIZE(compressed_size); uint32 segno; int fd; int rc; Assert(cfs != NULL && buf != NULL); if (offset < (off_t) CFS_CFP_BASE_OFFSET) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: read_raw_record: offset %llu inside reserved lead-in", (unsigned long long) offset))); return CFS_STORAGE_CORRUPT; } /* * A record never crosses a segment boundary (see * cfs_append_compressed_record). */ if ((uint64) CFS_CFP_SEG_OFF(offset) + rec_size > CFS_SEGMENT_SIZE) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: read_raw_record: record at offset %llu crosses a segment boundary", (unsigned long long) offset))); return CFS_STORAGE_CORRUPT; } segno = CFS_CFP_SEGNO(offset); /* * Generation gate on the by-path segment open (QDB-1514): a cache hit * below reads through a descriptor that still names the inode the * handle's resolved offsets were planned against, which stays correct * after a swap. A cache miss opens by name, and an online compaction * may have replaced that name after this handle was tagged: fail the * read transiently, exactly like the AIO read path's gate in * cfs_smgr.c, instead of reading wrong bytes; the next access * refreshes the handle and re-plans against the new pair. */ if ((cfs->cfp_fd < 0 || cfs->cfp_append_segno != segno) && (cfs->cfp_read_fd < 0 || cfs->cfp_read_segno != segno) && cfs->open_generation != cfs_state_relation_generation(cfs->rlocator, cfs->forknum)) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: .cfp segment %u of relation %u/%u/%u was " "replaced while a read was in flight", segno, cfs->rlocator.locator.spcOid, cfs->rlocator.locator.dbOid, cfs->rlocator.locator.relNumber))); } fd = cfs_cfp_read_segment_fd(cfs, segno); if (fd < 0) { if (fd == -1) { /* * The map references a segment that does not exist on disk. This * is the same class of corruption as a truncated segment, so * route it through cfs_report_corruption() like any other * CFS_STORAGE_CORRUPT (it may PANIC depending on * cfs_checksum_failure). */ ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: .cfp segment %u referenced by the map is missing", segno))); return CFS_STORAGE_CORRUPT; } ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not open .cfp segment %u for reading", segno))); return CFS_STORAGE_ERROR; } /* * Debug fault injection: simulate a pread() failure of the record so the * test suite can exercise the read-path error handling. Both the * synchronous and the AIO read path funnel through this point. No-op in * production (cfs_debug_fail_read defaults to 0). */ if (cfs_debug_fail_read > 0) { cfs_debug_fail_read--; errno = EIO; ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not read record at offset %llu from .cfp", (unsigned long long) offset))); return CFS_STORAGE_ERROR; } rc = cfs_pread_all(fd, buf, rec_size, CFS_CFP_SEG_OFF(offset)); if (rc != CFS_STORAGE_OK) { ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not read record at offset %llu from .cfp", (unsigned long long) offset))); return (rc == CFS_STORAGE_NOENT) ? CFS_STORAGE_CORRUPT : rc; } return CFS_STORAGE_OK; } int cfs_read_record(CfsRelation *cfs, off_t offset, uint32 compressed_size, void *dst, size_t dst_size) { size_t rec_size = CFS_RECORD_SIZE(compressed_size); char *buf; int rc; CfsDecompressStatus dstatus; Assert(cfs != NULL && dst != NULL); Assert(dst_size >= CFS_BLCKSZ); /* * A valid writer never stores more than a full page of payload: a page * that does not compress below CFS_BLCKSZ is stored RAW. Reject an * out-of-range size before allocating the record buffer so that a * corrupted map entry cannot drive a multi-megabyte palloc. */ if (compressed_size > CFS_BLCKSZ) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: compressed record size %u exceeds the page size at offset %llu", compressed_size, (unsigned long long) offset))); return CFS_STORAGE_CORRUPT; } buf = palloc(rec_size); /* * The raw read and the decompression are reported as separate wait * events so that IO time (CFS_READ) and decompression CPU time * (CFS_DECOMPRESS) are distinguishable in wait-event sampling. */ pgstat_report_wait_start(WAIT_EVENT_CFS_READ); rc = cfs_read_raw_record(cfs, offset, compressed_size, buf); if (rc != CFS_STORAGE_OK) { pgstat_report_wait_end(); pfree(buf); return rc; } pgstat_report_wait_end(); pgstat_report_wait_start(WAIT_EVENT_CFS_DECOMPRESS); dstatus = CfsDecompressPage(buf, rec_size, dst, dst_size, NULL); pgstat_report_wait_end(); pfree(buf); if (dstatus != CFS_DECOMPRESS_OK) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: decompression failed at offset %llu (status=%s)", (unsigned long long) offset, CfsDecompressStatusString(dstatus)))); return CFS_STORAGE_CORRUPT; } return CFS_STORAGE_OK; } /* * cfs_read_records_span — bulk variant of cfs_read_record() for a run of * physically contiguous records of one .cfp segment. 'entries' holds * 'nentries' map entries for consecutive logical blocks first_block.., * gathered by the caller so that entries[i+1].physical_offset == * entries[i].physical_offset + CFS_RECORD_SIZE(entries[i].compressed_size) * and the whole run stays inside one segment. The span is fetched with a * single pread into a scratch buffer, then every record is validated and * decompressed exactly as cfs_read_record() would — positions come from * the map, integrity from each record's own header — so the produced pages * are bit-identical to the per-block path. * * On failure returns the CfsStorageStatus of the first failure and stores * the failing block number in *fail_block (when non-NULL): the first block * of the span for a span-level failure (missing segment, pread error or * short read), first_block + i for a record-level one (invalid entry, * decompression failure). Blocks before the failure keep their * decompressed content; the callers raise the ERROR anyway, so the partial * fill is unobservable. Corruption is reported by the caller through the * centralised handler, not here. */ int cfs_read_records_span(CfsRelation *cfs, const CfsMapEntry *entries, BlockNumber first_block, BlockNumber nentries, void **buffers, BlockNumber *fail_block) { uint64 span_off = entries[0].physical_offset; uint64 span_end = entries[nentries - 1].physical_offset + CFS_RECORD_SIZE(entries[nentries - 1].compressed_size); size_t span_len = (size_t) (span_end - span_off); uint32 segno = CFS_CFP_SEGNO(span_off); char *buf; int fd; int rc; BlockNumber b; Assert(cfs != NULL && entries != NULL && buffers != NULL); Assert(nentries >= 1); /* * Validate every map row BEFORE computing the span length and * allocating the scratch buffer: a corrupted last-record size could * otherwise drive a multi-gigabyte palloc (the entry CRC is checked * here, but the guard stays cheap and keeps the failure attributed to * the exact block, like the per-block path that validates before any * allocation — see cfs_read_entry_record/cfs_read_page). */ for (b = 0; b < nentries; b++) { const CfsMapEntry *e = &entries[b]; CfsFormatStatus fst = cfs_map_entry_validate(e, true); if (fst != CFS_FORMAT_OK || e->compressed_size > CFS_BLCKSZ) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: invalid page map entry for block %u " "(offset %llu, status %s)", first_block + b, (unsigned long long) e->physical_offset, CfsFormatStatusString(fst)))); if (fail_block != NULL) *fail_block = first_block + b; return CFS_STORAGE_CORRUPT; } } /* * A valid writer never lets a record cross a segment boundary, and the * pairwise contiguity of the run keeps every start offset inside the * first entry's segment — only a corrupted last-record size (or a * grouping bug) could push the span end across it. Reject that the * same way cfs_read_raw_record() rejects a boundary-crossing record * instead of trusting the caller. */ if (CFS_CFP_SEGNO(span_end - 1) != segno) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: record span at offset %llu crosses a segment boundary", (unsigned long long) span_off))); if (fail_block != NULL) *fail_block = first_block + nentries - 1; return CFS_STORAGE_CORRUPT; } fd = cfs_cfp_read_segment_fd(cfs, segno); if (fd < 0) { if (fail_block != NULL) *fail_block = first_block; if (fd == -1) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: .cfp segment %u referenced by the map is missing", segno))); return CFS_STORAGE_CORRUPT; } ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not open .cfp segment %u for reading", segno))); return CFS_STORAGE_ERROR; } /* * Debug fault injection, mirroring cfs_read_raw_record(): the counter is * spent on the span pread, so both the batched and the per-block read * paths fail deterministically under the same GUC. */ if (cfs_debug_fail_read > 0) { cfs_debug_fail_read--; errno = EIO; ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not read %zu-byte record span at " "offset %llu from .cfp", span_len, (unsigned long long) span_off))); if (fail_block != NULL) *fail_block = first_block; return CFS_STORAGE_ERROR; } /* * The span buffer is allocated outside the wait-event window so an * ereport from palloc (OOM) cannot leave CFS_READ active, mirroring * cfs_read_record(). */ buf = palloc(span_len); pgstat_report_wait_start(WAIT_EVENT_CFS_READ); rc = cfs_pread_all(fd, buf, span_len, CFS_CFP_SEG_OFF((off_t) span_off)); pgstat_report_wait_end(); if (rc != CFS_STORAGE_OK) { pfree(buf); ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not read %zu-byte record span at " "offset %llu from .cfp", span_len, (unsigned long long) span_off))); if (fail_block != NULL) *fail_block = first_block; return (rc == CFS_STORAGE_NOENT) ? CFS_STORAGE_CORRUPT : rc; } /* * Decompression is a separate wait event from the span pread, mirroring * cfs_read_record(): wait-event sampling must be able to attribute the * read phase (IO) and the validate+decompress phase (CPU) independently. */ pgstat_report_wait_start(WAIT_EVENT_CFS_DECOMPRESS); for (b = 0; b < nentries; b++) { const CfsMapEntry *e = &entries[b]; size_t rec_size = CFS_RECORD_SIZE(e->compressed_size); char *rec = buf + (e->physical_offset - span_off); CfsDecompressStatus dstatus; /* Map rows were validated before the palloc; decompress each * record from its slice of the span buffer exactly like * cfs_read_record() would. */ dstatus = CfsDecompressPage(rec, rec_size, buffers[b], CFS_BLCKSZ, NULL); if (dstatus != CFS_DECOMPRESS_OK) { pgstat_report_wait_end(); /* * Records 0..b-1 were already served and counted per page by * cfs_stats_count_read(); count them as a (partial) batch here, * so read_count == read_batched_pages + read_fallback_pages * survives this error path too. A span whose very first record * fails has served no page and stays uncounted. */ if (b > 0) cfs_stats_count_read_span(cfs->rlocator, cfs->forknum, b); pfree(buf); ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: decompression failed at offset %llu (status=%s)", (unsigned long long) e->physical_offset, CfsDecompressStatusString(dstatus)))); if (fail_block != NULL) *fail_block = first_block + b; return CFS_STORAGE_CORRUPT; } cfs_stats_count_read(cfs->rlocator, cfs->forknum, e->compressed_size); } pgstat_report_wait_end(); /* One batched span read served nentries pages (QDB-1513 evidence). */ cfs_stats_count_read_span(cfs->rlocator, cfs->forknum, nentries); pfree(buf); return CFS_STORAGE_OK; } int cfs_fsync_kind(CfsRelation *cfs, CfsFileKind kind) { int fd; int status; if (kind == CFS_FILE_DATA) return cfs_fsync_cfp_segments(cfs); switch (kind) { case CFS_FILE_MAP: fd = cfs->map_fd; break; case CFS_FILE_JOURNAL: fd = cfs->jrn_fd; break; default: return CFS_STORAGE_ERROR; } if (fd < 0) return CFS_STORAGE_ERROR; /* Report fsync as a wait event. */ pgstat_report_wait_start(WAIT_EVENT_CFS_FSYNC); /* * Debug fault injection: simulate an fsync() failure so the test suite * can exercise the checkpoint durability path. No-op in production * (cfs_debug_fail_fsync defaults to 0). */ if (cfs_debug_fail_fsync > 0) { cfs_debug_fail_fsync--; errno = EIO; status = -1; } /* * Test seam: cfs-fail-journal-fsync makes the journal fsync fail like a * real syscall error, so t/504 exercises the phase-2 durability order and * its PANIC escalation. Without --enable-injection-points the check is a * compile-time false. */ else if (kind == CFS_FILE_JOURNAL && IS_INJECTION_POINT_ATTACHED("cfs-fail-journal-fsync")) { errno = EIO; status = -1; } else status = pg_fsync(fd); if (status != 0) { pgstat_report_wait_end(); ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: fsync of %s failed: %m", cfs_relation_path(cfs, kind)))); return CFS_STORAGE_ERROR; } pgstat_report_wait_end(); return CFS_STORAGE_OK; } /* ================================================================ * .cfsmap page map snapshot * ================================================================ */ void cfs_map_ensure_capacity(CfsRelation *cfs, uint64 capacity) { uint64 i; uint64 old_cap; MemoryContext oldcontext; if (cfs->map_capacity >= capacity) return; old_cap = cfs->map_capacity; /* Grow geometrically, starting from 16. */ if (capacity < 16) capacity = 16; while (cfs->map_capacity < capacity) cfs->map_capacity = cfs->map_capacity * 2 + 16; /* * The map array is long-lived alongside the CfsRelation; allocate it in * TopMemoryContext to survive per-query resets. */ oldcontext = MemoryContextSwitchTo(TopMemoryContext); if (cfs->map == NULL) cfs->map = palloc0(cfs->map_capacity * CFS_MAP_ENTRY_SIZE); else { cfs->map = repalloc(cfs->map, cfs->map_capacity * CFS_MAP_ENTRY_SIZE); MemSet(cfs->map + old_cap, 0, (cfs->map_capacity - old_cap) * CFS_MAP_ENTRY_SIZE); } MemoryContextSwitchTo(oldcontext); /* Initialise freshly allocated slots to the "never written" state. */ for (i = old_cap; i < cfs->map_capacity; i++) { CfsMapEntry *e = &cfs->map[i]; e->physical_offset = CFS_ENTRY_INVALID_OFFSET; cfs_map_entry_crc_set(e); } } BlockNumber cfs_map_nblocks(const CfsRelation *cfs) { return (BlockNumber) cfs->map_hdr.nblocks; } /* * Return a pointer to entry 'blocknum', growing the in-memory array capacity * as needed. This is a pure lookup: it never changes the logical size of the * relation (map_hdr.nblocks). Growth of nblocks is an explicit operation * performed only at genuine extend points (cfs_write_page / cfs_zero_extend), * each of which journals a RESIZE record so recovery restores nblocks * deterministically instead of inferring it from the highest UPDATE block. */ CfsMapEntry * cfs_map_get_entry(CfsRelation *cfs, BlockNumber blocknum) { uint64 idx = blocknum; if (idx >= cfs->map_capacity) cfs_map_ensure_capacity(cfs, idx + 1); return &cfs->map[idx]; } void cfs_map_set_entry(CfsRelation *cfs, BlockNumber blocknum, const CfsMapEntry *entry) { CfsMapEntry *e = cfs_map_get_entry(cfs, blocknum); *e = *entry; cfs_map_entry_crc_set(e); } void cfs_map_truncate(CfsRelation *cfs, BlockNumber nblocks) { uint64 i; uint64 old_nblocks = cfs->map_hdr.nblocks; if ((uint64) nblocks >= old_nblocks) return; if (cfs->map != NULL) { for (i = nblocks; i < old_nblocks; i++) cfs_map_entry_init(&cfs->map[i]); } cfs->map_hdr.nblocks = nblocks; ereport(DEBUG1, (errmsg("CFS: truncated map from %llu to %u blocks", (unsigned long long) old_nblocks, nblocks))); } /* * Load the .cfsmap snapshot into the handle's private array. The file * is the 8-byte prologue followed by positional * rows; the row count comes from the file size (a partial trailing row is * a torn write and ignored). Every row is self-verifying (see * cfs_map_file_read_range): a valid row loads as-is, a sparse hole and a * corrupt row load as INVALID, and the corrupt ones are remembered in * *corrupt_mask so cfs_map_load() can verify after the journal replay * that a covering record healed them - otherwise the strict contract * applies. * * The mask length is the nblocks this load actually read, not the file size * sampled before the prologue: a snapshot shortened by a concurrent truncate * can therefore never index past the mask. * * Missing/empty snapshot yields an empty map (nblocks=0); a corrupt * prologue is a hard error during recovery, and outside recovery the * centralised corruption handler (cfs_report_corruption) decides the * severity (cfs_map_file_prologue_read). */ static int cfs_map_load_snapshot(CfsRelation *cfs, char **corrupt_mask, uint64 *corrupt_mask_len) { uint64 nblocks; uint64 i; int rc; *corrupt_mask = NULL; *corrupt_mask_len = 0; rc = cfs_map_file_prologue_read(cfs, &nblocks); if (rc == CFS_STORAGE_ERROR) return CFS_STORAGE_ERROR; cfs->map_hdr.nblocks = nblocks; cfs->map_hdr.cfp_size = 0; /* refreshed by EOF discovery at open */ cfs->map_hdr.max_generation = 0; /* seeded from the journal header */ { CfsJournalFileHeader jhdr; /* * Seed the in-memory watermark from the journal header, then let the * rows below raise it further. After a TRUNCATE or a mass DELETE no * row carries the high generations anymore, but the watermark * contract is monotonic: the next reset stamp and the allocator seed * must never drop below what was ever issued. */ if (cfs_journal_read_header(cfs->jrn_fd, &jhdr) && jhdr.max_generation > cfs->map_hdr.max_generation) cfs->map_hdr.max_generation = jhdr.max_generation; } cfs_map_ensure_capacity(cfs, nblocks); if (nblocks > 0) { int attempt; for (attempt = 0;; attempt++) { rc = cfs_map_file_read_range(cfs->map_fd, 0, nblocks, cfs->map, corrupt_mask, nblocks); if (rc == CFS_STORAGE_OK) break; /* * The row count came from fstat a moment ago; a concurrent * TRUNCATE (which holds the append lock) may have shortened the * file since. Re-measure and retry once on the smaller snapshot * instead of failing the whole load: the RESIZE journal record * carries the logical size anyway, and the classification loop * below invalidates the slots past the new nblocks. */ if (attempt == 0) { off_t now = cfs_fd_size(cfs->map_fd); uint64 rows = (now >= 0) ? cfs_map_rows_from_size((uint64) now) : 0; if (now >= 0 && rows < nblocks) { nblocks = rows; cfs->map_hdr.nblocks = nblocks; if (nblocks == 0) break; continue; } } ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not read map entries from \"%s\"", cfs->map_path))); return CFS_STORAGE_ERROR; } } /* The mask length follows the nblocks the read above settled on. */ *corrupt_mask_len = nblocks; /* * The rows are the watermark source now that the header is gone, and * every slot past the loaded snapshot is invalidated: the array may * outlive a larger previous map in this handle (a reload that does not * recreate the array), and a stale entry beyond nblocks would resurrect * pre-truncate data when the relation later extends back over that slot. * (Rows the range reader turned INVALID carry generation 0 and never * raise the watermark.) */ for (i = 0; i < cfs->map_capacity; i++) { CfsMapEntry *e = &cfs->map[i]; if (i >= nblocks) { cfs_map_entry_init(e); continue; } if (e->generation > cfs->map_hdr.max_generation) cfs->map_hdr.max_generation = e->generation; } ereport(DEBUG1, (errmsg("CFS: loaded map snapshot: %llu blocks", (unsigned long long) nblocks))); return CFS_STORAGE_OK; } /* * cfs_map_load_header — validate the .cfsmap prologue and derive the lazy * handle's local row count from the file size, leaving the private entry * array untouched (lazy handles keep map == NULL and resolve entries * through the shared segment pool). */ static int cfs_map_load_header(CfsRelation *cfs) { uint64 nblocks; int rc; rc = cfs_map_file_prologue_read(cfs, &nblocks); if (rc == CFS_STORAGE_ERROR) return CFS_STORAGE_ERROR; cfs->map_hdr.nblocks = nblocks; return CFS_STORAGE_OK; } int cfs_map_load(CfsRelation *cfs, bool repair_torn_tail, CfsMapLoadContext context) { char *corrupt_mask = NULL; uint64 corrupt_mask_len = 0; int rc; int64 replayed; off_t stop_off; bool mid_file_stop; uint64 blk; bool retried = false; bool test_seam_taken = false; /* * The snapshot and the journal are two preads with no lock held: a * concurrent checkpoint fold+reset landing between them folds the healing * journal records into the map and resets the journal, so the stale * snapshot's corrupt rows look unhealed and the validation would report * corruption the map file no longer has; an immedsync can even replace * the map file mid-read. Sample the journal identity around the reads; * any change means the load raced a reset and is retried once on the * fresh files (the map descriptor is refreshed too when the path moved). */ for (;;) { CfsStateSnapshot base; int state_fl; /* * The ownership-state judge owns the whole derivation: the retry * below fires exactly when the journal identity moved (see the caller * mask table in cfs_state.c). */ cfs_state_capture(cfs, &base); /* * Re-baselined by the post-replay validation below (a handle may be * reloaded by cfs_reopen). */ cfs->unhealed_corruption = false; /* * Rows that failed their CRC load as INVALID; the replay below heals * those the journal still covers. The mask only exists while there * is something to remember (corruption is the exceptional case), and * its length is the nblocks the snapshot load actually read. */ rc = cfs_map_load_snapshot(cfs, &corrupt_mask, &corrupt_mask_len); if (rc != CFS_STORAGE_OK) { if (corrupt_mask != NULL) pfree(corrupt_mask); return rc; } /* * Test seam: the lock-free window between the snapshot read and the * journal replay. t/005 pauses here and lets a foreign checkpoint * fold and reset the journal, proving the identity guard retries. * Taken once per load, so the retry itself does not pause again. * Compiles to nothing without --enable-injection-points. */ if (!test_seam_taken) { test_seam_taken = true; INJECTION_POINT("cfs-map-load-before-journal", NULL); } /* Replay the journal on top of the snapshot (clears healed blocks). */ replayed = cfs_journal_replay(cfs, &stop_off, &mid_file_stop, corrupt_mask, corrupt_mask_len, context); if (replayed < 0) { if (corrupt_mask != NULL) pfree(corrupt_mask); return CFS_STORAGE_ERROR; } /* * A stop in the middle of the journal is corruption, not a crash * artifact: the records behind the torn one are the only durable * trace of their changes. Mark the map unhealed (any writer that * persists the in-memory map must refuse now, see * CfsRelation.unhealed_corruption) and leave the journal untouched - * the tail truncation below is for a genuine torn tail only. */ if (mid_file_stop) cfs->unhealed_corruption = true; /* * Retry on ANY journal identity change, not only when a corrupt row * is left unhealed: a foreign fold+reset between the two reads can * also have replaced the map file (immedsync) while this pass read * the old inode. The retry re-reads both files from a consistent * state; a second consecutive change means real activity keeps * winning, and the report goes out on the fresh evidence. */ if (base.jrn_fd_valid && !retried) { state_fl = cfs_state_check(&base, cfs, base.jrn_size, NULL); if (state_fl & CFS_STATE_JRN_IDENTITY_MOVED) { /* * If the snapshot itself was replaced, the old descriptor * would make the retry read the same stale inode again. */ if (state_fl & CFS_STATE_MAP_SWAPPED) { int new_fd; if (cfs->map_fd >= 0) close(cfs->map_fd); new_fd = cfs_open_sidecar(cfs->map_path, cfs->flags, false); if (new_fd < 0) { if (corrupt_mask != NULL) pfree(corrupt_mask); return CFS_STORAGE_ERROR; } cfs->map_fd = new_fd; } if (corrupt_mask != NULL) pfree(corrupt_mask); corrupt_mask = NULL; retried = true; continue; } } break; } /* * Post-replay validation: a corrupt row whose block no journal record * covered is real damage - the row's data exists nowhere else. Escalate * through the centralised handler; during the recovery scan (the * repair-tail open) that honours cfs_recovery_strict, everywhere else * cfs_checksum_failure. */ if (corrupt_mask != NULL) { for (blk = 0; blk < corrupt_mask_len; blk++) { if (!corrupt_mask[blk]) continue; /* * The damage is unhealed in every context: remember it on the * handle so a later full-map writer can refuse to persist its * in-memory map (saving it would launder the corruption - see * CfsRelation.unhealed_corruption). */ cfs->unhealed_corruption = true; /* * The read context may run inside an AIO callback, which must not * throw: defer the report (the corrupt rows stay INVALID) and * fail the load with CORRUPT; cfs_smgr_readv() re-reports * centrally through the backend policy. Only row-level damage is * deferred: a corrupt prologue or journal header still raises * here, and cfs_smgr_startreadv() converts that ERROR into the * AIO failure code instead of letting it escape. */ if (context == CFS_LOAD_READ) { rc = CFS_STORAGE_CORRUPT; continue; } cfs_report_corruption(cfs->rlocator, cfs->forknum, blk, "page map entry failed its checksum " "and the journal holds no covering " "record", context == CFS_LOAD_RECOVERY); } pfree(corrupt_mask); } /* * Baseline the delta-replay cursor where the replay actually stopped, not * at the raw file size: a writer mid-append leaves a torn trailing record * that the replay stops short of, and starting a later cfs_refresh_map() * past it would skip the record even after the writer completes it, * leaving this handle's map permanently stale. */ cfs->map_synced_jrn_off = stop_off; /* * Physically truncate a genuine torn tail (a half-written record left by * a crash mid-append) so that the append cursor — which every append * re-derives from the raw file size — lands at the real end of valid * data instead of past the garbage. Without this, the next backend * appends behind the garbage and every later replay still stops on it, * burying the freshly written records forever. * * Mid-file corruption is not repaired here: valid records follow the torn * one (mid_file_stop), so truncating at the stop would destroy them. The * journal is preserved instead, the map is marked unhealed (it already is * above) and the recovery snapshot+reset is vetoed downstream, so the * intact tail survives for a later checkpoint or manual repair. * * This repair is gated on repair_torn_tail because it is only safe when * no concurrent writer can be mid-append on this journal. That holds in * two contexts: the single-writer recovery scan (cfs_replay_one_locator, * which passes CFS_OPEN_REPAIR_TAIL) and any caller that holds the * per-relation append lock (cfs_refresh_map, cfs_reopen). The normal * handle open is lock-free, so a concurrent backend flushing a page under * the append lock legitimately leaves a half-written trailing record; * truncating it here would corrupt that record out from under the writer, * and the writer's second pwrite would land in the gap, producing a * permanently torn entry that defeats later delta replay (the checkpoint * stale-map race). A persistent torn tail from a crash is repaired once, * by the recovery scan, before any backend can write; during normal * operation a torn tail is always transient (the writer holding the lock * completes it), so never needs truncating here. */ if (repair_torn_tail && !cfs->read_only && !mid_file_stop) { off_t jrn_size = cfs_fd_size(cfs->jrn_fd); if (jrn_size > stop_off) { if (ftruncate(cfs->jrn_fd, stop_off) != 0) ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not truncate torn journal tail in \"%s\": %m", cfs->jrn_path))); else { /* * Make the truncation durable, mirroring the checkpoint's * journal reset. The repair is idempotent — a crash that * loses it just re-runs it at the next open — but a fsync * failure is still surfaced loud, like every other journal * durability point. */ pgstat_report_wait_start(WAIT_EVENT_CFS_FSYNC); if (pg_fsync(cfs->jrn_fd) != 0) { pgstat_report_wait_end(); ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: could not fsync journal \"%s\": %m", cfs->jrn_path))); } pgstat_report_wait_end(); ereport(DEBUG1, (errmsg("CFS: truncated torn journal tail %lld..%lld in \"%s\"", (long long) stop_off, (long long) jrn_size, cfs->jrn_path))); /* Keep the append cursor in sync with the truncated file. */ cfs->jrn_write_off = stop_off; } } } ereport(DEBUG1, (errmsg("CFS: map loaded: %u blocks after replaying %lld journal records", cfs_map_nblocks(cfs), (long long) replayed))); return rc; } int cfs_map_save_snapshot(CfsRelation *cfs) { off_t real; Assert(cfs != NULL && !cfs->read_only); /* * A full (non-lazy) handle is a prerequisite: lazy handles resolve * entries through the shared segment pool and never snapshot. Its * private entry array may legitimately be absent, though, for a young * relation whose snapshot is empty AND whose journal holds no records * (nblocks == 0 — freshly published, or truncated by the previous * checkpoint): the snapshot then consists of the prologue alone. * * This is an internal invariant, but a runtime check is cheaper than * letting a misplaced caller write a snapshot from a handle that has no * private map (cfs->map == NULL) and crash or publish garbage. */ if ((cfs->flags & CFS_OPEN_LAZY_MAP) != 0) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: cannot save a page map snapshot from a lazy handle"))); /* * Refresh the in-memory state from the live map. cfp_size must reflect * the real end of the .cfp segment chain, not this handle's possibly * stale append cursor: another backend may have appended since this * handle last wrote. On discovery error keep the cursor as-is. */ real = cfs_cfp_discover_eof(cfs); if (real >= 0) { cfs->cfp_write_off = real; cfs->map_hdr.cfp_size = (uint64) real; } /* * Recompute the relation-wide generation watermark from the live map. A * handle may have assembled the entries without replaying every journal * record (or with a stale in-memory max), so the value must never lag the * entries the snapshot actually writes: the journal header stamps it at * the next reset. */ cfs->map_hdr.max_generation = cfs_map_live_summary(cfs); (void) cfs_map_file_write_snapshot_path(cfs->map_path, cfs->map, cfs->map_hdr.nblocks); /* * Reopen the map fd on the new file so future loads see it. */ if (cfs->map_fd >= 0) close(cfs->map_fd); cfs->map_fd = BasicOpenFile(cfs->map_path, O_RDWR | PG_BINARY); if (cfs->map_fd < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not reopen .cfsmap \"%s\": %m", cfs->map_path))); return CFS_STORAGE_OK; } /* ================================================================ * .cfsjrn journal * * Invariant: records are only ever appended at the end of the file, never * rewritten in place. A torn (partially written) record can therefore * only ever be the LAST one - which is what lets every reader (replay, * fold, repair) treat the first invalid record as a clean stop point and * drop the bytes behind it. * ================================================================ */ void cfs_journal_append_update(CfsRelation *cfs, BlockNumber blocknum, const CfsMapEntry *new_entry) { CfsJournalEntry je; Assert(cfs != NULL && !cfs->read_only); cfs_journal_entry_init_update(&je, blocknum, new_entry); /* * Refresh journal append cursor from actual file size — another backend * may have appended to .cfsjrn since our handle was opened. The caller * holds the per-relation append lock. */ { off_t real_off = cfs_fd_size(cfs->jrn_fd); if (real_off < (off_t) CFS_JOURNAL_HEADER_SIZE) real_off = CFS_JOURNAL_HEADER_SIZE; cfs->jrn_write_off = real_off; } /* * Append the UPDATE record. When the debug torn-journal delay is * enabled, write the record in two halves with a sleep in between, so a * concurrent reader refreshing its map can observe a half-written (torn) * entry — the exact window the read-path append-lock coordination * guards against. The caller holds the append lock (LW_EXCLUSIVE), so no * other writer can interleave; only a lock-free reader is exposed to the * torn bytes, which is the defect under test. The default (delay == 0) * is a single pwrite and a complete no-op in production. */ if (cfs_debug_torn_journal_ms > 0) { size_t half = sizeof(je) / 2; if (cfs_pwrite_all(cfs->jrn_fd, &je, half, cfs->jrn_write_off) != CFS_STORAGE_OK) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not append UPDATE journal record for block %u", blocknum))); pg_usleep((long) cfs_debug_torn_journal_ms * 1000L); if (cfs_pwrite_all(cfs->jrn_fd, (const char *) &je + half, sizeof(je) - half, cfs->jrn_write_off + (off_t) half) != CFS_STORAGE_OK) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not append UPDATE journal record for block %u", blocknum))); } else if (cfs_pwrite_all(cfs->jrn_fd, &je, sizeof(je), cfs->jrn_write_off) != CFS_STORAGE_OK) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not append UPDATE journal record for block %u", blocknum))); cfs->jrn_write_off += sizeof(je); } void cfs_journal_append_resize(CfsRelation *cfs, BlockNumber nblocks) { CfsJournalEntry je; Assert(cfs != NULL && !cfs->read_only); cfs_journal_entry_init_resize(&je, nblocks); { off_t real_off = cfs_fd_size(cfs->jrn_fd); if (real_off < (off_t) CFS_JOURNAL_HEADER_SIZE) real_off = CFS_JOURNAL_HEADER_SIZE; cfs->jrn_write_off = real_off; } if (cfs_pwrite_all(cfs->jrn_fd, &je, sizeof(je), cfs->jrn_write_off) != CFS_STORAGE_OK) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not append RESIZE journal record for nblocks %u", nblocks))); cfs->jrn_write_off += sizeof(je); } /* * cfs_journal_incarnation - the incarnation currently stamped in the * journal header - was absorbed by the ownership-state judge * (cfs_state_capture / cfs_state_check, cfs_state.c). */ /* * cfs_journal_fold - fold journal records in [start_off, limit) into the * .cfsmap file in place. Every UPDATE record rewrites * exactly one row at its positional offset (a hole between the previous * end of rows and the rewritten row is a sparse gap that reads as * INVALID), every DELETE writes a CRC-valid INVALID row. One map fsync * covers the batch. RESIZE records are only reported: the checkpoint * applies the last one in phase 2, under the append lock, so a reader never * observes a map shorter than the logical size. * * Stage 1 (the checkpoint's phase 1) runs without the append lock: writers * append concurrently, and every record they add at or beyond 'limit' * stops the pass and survives as the journal tail (the caller folds it in * phase 2). The durability order is the caller's: .cfp is durable before * this pass, so a crash mid-fold leaves torn rows that the journal heals * on the next load. Stage 3 (the startup recovery fold) runs under the * append lock the recovery scan already holds, after the caller re-resolved * a swapped pair and fsynced the payload (cfs_recovery.c): on startup * there is no competitor, and a test-backend call is serialised against * live writers and swappers by that same lock; its skipped UPDATE records * report through the recovery channel (sink.recovery_severity), because * the missing .cfp data is exactly the crash window WAL redo re-applies. * * Stops at the first torn/invalid record, classified like the replay * (cfs_journal_torn_is_tail). The caller decides from torn_is_tail: a torn * tail is dropped with the journal reset, while a torn record with valid * records behind it aborts the fold so that tail is preserved for a retry. * * Returns the number of rows folded (UPDATE + DELETE), or -1 on an I/O * error (raised). The caller publishes the row count in the * checkpoint_map_rows_written counter. */ /* * The fold's sink argument: everything its write_row callback needs - the * descriptor to pwrite through, the error level a write failure raises at * (stages 1/3: ERROR; stage 2: the sync elevel), and the pass's counters. */ typedef struct CfsJournalFoldSinkArg { CfsRelation *cfs; int elevel; int64 folded; bool wrote_any; uint64 superseded; uint64 superseded_bytes; } CfsJournalFoldSinkArg; /* * Write one applied row into the .cfsmap at its positional offset, * counting the superseded (previously written) row it replaces: its * payload turns from live to dead, which is exactly the dead-space delta * the checkpoint publishes - the row is read here anyway, so the sum * costs no extra I/O. * * A replaced row identical to the one being written means an earlier * fold pass already applied this very record (a retried checkpoint * after a phase-2 failure left the journal intact): nothing is * superseded, and neither counter may charge the row twice. The * accepted cost of that guard: a checkpoint that fails after folding * but before resetting loses its delta for good - the retry sees * identical rows, so it cannot charge them once either - and only * compaction's exact recomputation restores the value. The counter is * the compaction-threshold heuristic, so the loss delays compaction; * it never hides dead space. */ static void cfs_fold_write_row(void *arg, BlockNumber block, const CfsMapEntry *row) { CfsJournalFoldSinkArg *f = (CfsJournalFoldSinkArg *) arg; off_t row_off = cfs_map_row_off(block); CfsMapEntry old_row; if (cfs_pread_all(f->cfs->map_fd, &old_row, CFS_MAP_ENTRY_SIZE, row_off) == CFS_STORAGE_OK && cfs_map_entry_validate(&old_row, false) == CFS_FORMAT_OK && CFS_MAP_ENTRY_VALID(&old_row) && memcmp(&old_row, row, offsetof(CfsMapEntry, entry_crc)) != 0) { f->superseded++; f->superseded_bytes += CFS_RECORD_SIZE(old_row.compressed_size); } if (cfs_pwrite_all(f->cfs->map_fd, row, CFS_MAP_ENTRY_SIZE, row_off) != CFS_STORAGE_OK) { /* * The scan engine that drives this sink started the replay wait * event; end it here so the ereport's longjmp cannot leave it stuck * on whatever the catcher above goes on to do (and the scan's own * end, never reached on this path, stays balanced). */ pgstat_report_wait_end(); ereport(f->elevel, (errcode_for_file_access(), errmsg("CFS: could not fold journal into page map \"%s\"", f->cfs->map_path))); } f->folded++; f->wrote_any = true; } int64 cfs_journal_fold(CfsRelation *cfs, off_t start_off, off_t limit, int stage, CfsJournalFoldResult *result) { CfsJournalSink sink; CfsJournalFoldSinkArg farg; int fold_elevel; Assert(cfs != NULL && !cfs->read_only); Assert(cfs->map_fd >= 0); Assert(result != NULL); Assert(limit >= (off_t) CFS_JOURNAL_HEADER_SIZE); if (start_off < (off_t) CFS_JOURNAL_HEADER_SIZE) start_off = (off_t) CFS_JOURNAL_HEADER_SIZE; if (start_off > limit) start_off = limit; /* * Stage 2 runs under the exclusive append lock. An ERROR there would * longjmp past the release, so a persistence-class failure escalates the * same way every other locked durability step does (PANIC in the * checkpointer); stage 1 and the recovery fold (stage 3, whose release * arm is a PG_FINALLY) simply abort with ERROR. */ fold_elevel = (stage == 2) ? data_sync_elevel(ERROR) : ERROR; MemSet(result, 0, sizeof(*result)); result->stop_off = start_off; /* * Refresh the in-memory cfp_size the way a full snapshot would: the * checkpoint's dead-space recomputation reads it. */ { off_t real = cfs_cfp_discover_eof(cfs); if (real >= 0) { cfs->cfp_write_off = real; cfs->map_hdr.cfp_size = (uint64) real; } } /* * The fold's sink: an applied row is written straight into the .cfsmap at * its positional offset, and a superseded (previously written) row counts * as one dead page version and adds its payload bytes to the dead-space * delta - the exact dead_pages and dead_bytes inputs for the checkpoint. * A retried checkpoint (phase 2 failed with the journal intact) * re-applies records the aborted pass already wrote: the identical-row * guard in cfs_fold_write_row keeps both counters from charging those * twice. The durability policy (skip an UPDATE whose .cfp data is * missing/foreign instead of freezing it into the map right before the * journal reset erases the evidence) is the apply engine's. */ farg.cfs = cfs; farg.elevel = fold_elevel; farg.folded = 0; farg.wrote_any = false; farg.superseded = 0; farg.superseded_bytes = 0; memset(&sink, 0, sizeof(sink)); sink.write_row = cfs_fold_write_row; sink.arg = &farg; sink.recovery_severity = (stage == CFS_FOLD_STAGE_RECOVERY); { CfsJournalScanPolicy policy; CfsJournalScanResult scan; /* * The scan engine owns the loop, the boundary stop and the torn * classification (reported once, with this caller's role). The test * seams: fail the next journal block read (t/504; stages 1, 2 and * the recovery fold carry distinct injection-point names) and pause * stage 1 or the recovery fold after the first applied row (the * parked-fold tests). Both compile to nothing without * --enable-injection-points. */ memset(&policy, 0, sizeof(policy)); policy.limit = limit; policy.role = (stage == CFS_FOLD_STAGE_RECOVERY) ? "recovery" : "fold"; policy.during_recovery = (stage == CFS_FOLD_STAGE_RECOVERY); policy.fail_next_read = (stage == 1 && IS_INJECTION_POINT_ATTACHED("cfs-fail-journal-read-phase1")) || (stage == 2 && IS_INJECTION_POINT_ATTACHED("cfs-fail-journal-read-phase2")) || (stage == CFS_FOLD_STAGE_RECOVERY && IS_INJECTION_POINT_ATTACHED("cfs-fail-journal-read-recovery")); policy.pause_after_first_row = (stage == CFS_FOLD_STAGE_RECOVERY) ? "cfs-recovery-fold-row" : (stage == 1) ? "cfs-checkpoint-fold-row" : NULL; cfs_journal_scan(cfs, start_off, &policy, &sink, &scan); result->stop_off = scan.stop_off; switch (scan.reason) { case CFS_SCAN_STOP_BOUNDARY: break; case CFS_SCAN_STOP_TORN_TAIL: result->torn_stop = true; result->torn_is_tail = true; break; case CFS_SCAN_STOP_TORN_MIDFILE: result->torn_stop = true; result->torn_is_tail = false; break; case CFS_SCAN_STOP_IO_ERROR: /* * Returning a partial stop offset would let the journal reset * below and the checkpoint report success without doing its * job. Fail instead: nothing has been truncated yet, so the * next checkpoint retries the fold from scratch. (The reader * already logged the pread failure with its errno at the * point of failure.) */ ereport(fold_elevel, (errcode_for_file_access(), errmsg("CFS: could not read journal \"%s\" during the checkpoint fold", cfs->jrn_path))); break; case CFS_SCAN_STOP_EOF: break; } } if (result->stop_off < (off_t) CFS_JOURNAL_HEADER_SIZE) result->stop_off = (off_t) CFS_JOURNAL_HEADER_SIZE; /* Merge what the apply engine and the fold sink counted. */ result->superseded_pages = farg.superseded; result->superseded_bytes = farg.superseded_bytes; result->max_generation = sink.max_generation; result->resize_target = sink.resize_target; result->have_resize = sink.have_resize; if (farg.wrote_any) { pgstat_report_wait_start(WAIT_EVENT_CFS_FSYNC); if (pg_fsync(cfs->map_fd) != 0) { pgstat_report_wait_end(); ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: could not fsync page map \"%s\": %m", cfs->map_path))); } pgstat_report_wait_end(); } ereport(DEBUG1, (errmsg("CFS: folded %lld journal row(s) into \"%s\"", (long long) farg.folded, cfs->map_path))); return farg.folded; } /* * cfs_map_live_summary - the full-map scan returning the relation's * generation watermark (the highest generation the in-memory map holds). * Only the paths that legitimately own a full map call it (immedsync, * the pool seed); the checkpoint and the startup recovery fold never do - * they take the watermark from the journal header and their folds, so * their cost stays proportional to the journal, never the table. */ uint32 cfs_map_live_summary(CfsRelation *cfs) { BlockNumber nblocks = cfs_map_nblocks(cfs); BlockNumber blk; uint32 max_gen = cfs->map_hdr.max_generation; /* * The rows live in the handle's private array: a lazy (pool-served) * handle keeps map == NULL, so an nblocks above zero would index the NULL * array. An empty relation (nblocks == 0) legitimately has no array at * all - the loop below never runs. */ Assert(cfs->map != NULL || nblocks == 0); for (blk = 0; blk < nblocks; blk++) { CfsMapEntry *e = &cfs->map[blk]; if (CFS_MAP_ENTRY_VALID(e)) { if (e->generation > max_gen) max_gen = e->generation; } } return max_gen; } /* * Outcome of applying one journal record to the in-memory map. * * CFS_JRN_APPLY_TORN means the record itself failed validation (bad magic, * op or CRC). A .cfsjrn append can only be interrupted at the tail of the * file, so replay stops at the first such record. * * CFS_JRN_APPLY_SKIP means the record itself is intact, but the .cfp data * it references is not there. Between checkpoints neither file is fsync'd, * so after a crash the kernel may have flushed .cfsjrn pages ahead of the * .cfp pages they reference - and that reordering is not tied to the * record's position in the journal: any record, not just the last one, can * point at data that never became durable. Such a record is skipped (the * map keeps the previous, genuinely durable state for the block) and replay * continues with the next record; ordinary WAL redo then re-applies the * lost change on top of the old page version, exactly as it does for * uncompressed relations. */ typedef enum CfsJournalApplyResult { CFS_JRN_APPLY_OK, /* record applied to the map */ CFS_JRN_APPLY_SKIP, /* referenced .cfp data missing: skipped */ CFS_JRN_APPLY_TORN /* invalid record: stop the replay */ } CfsJournalApplyResult; /* * Verify that the .cfp record referenced by an UPDATE journal record * actually reached the disk: read its CfsCompressedBlockHeader and validate * the magic and the header CRC. The header alone proves that a genuine * record starts at this offset; the payload does not need to be unpacked * for that. * * Scope note: a record is written by a single pwrite, but OS writeback is * per-page and unordered, so after a crash the page holding the header can * theoretically be durable while a page holding the payload tail is not * (only realistic for large RAW records spanning several OS pages). That * residue is intentionally not checked here: the first read of the block * catches it via the payload CRC (CfsDecompressPage) and reports it through * the normal corruption handler - fail-loud, never silent. */ /* * The in-memory sink of the full and the delta replay: an applied row goes * into the handle's private array, a covered corrupt block is unmarked, * and a RESIZE updates the logical size (invalidating the dropped slots). */ typedef struct CfsJournalMemSink { CfsRelation *cfs; char *corrupt_mask; uint64 corrupt_mask_len; bool wrote; /* at least one row applied (vs skipped) */ int64 wrote_rows; /* rows actually written (OK only) */ } CfsJournalMemSink; static void cfs_mem_write_row(void *arg, BlockNumber block, const CfsMapEntry *row) { CfsJournalMemSink *m = (CfsJournalMemSink *) arg; cfs_map_set_entry(m->cfs, block, row); if (m->corrupt_mask != NULL && (uint64) block < m->corrupt_mask_len) m->corrupt_mask[block] = 0; m->wrote = true; m->wrote_rows++; } static void cfs_mem_resize(void *arg, BlockNumber target) { CfsJournalMemSink *m = (CfsJournalMemSink *) arg; uint64 old_nblocks = m->cfs->map_hdr.nblocks; /* * Set the logical block count deterministically. The last RESIZE record * wins (idempotent: replaying the same sequence twice yields the same * nblocks). A shrink must also invalidate the slots being dropped, * otherwise re-extending past the new nblocks would resurrect * pre-truncate entries. */ cfs_map_ensure_capacity(m->cfs, (uint64) target); if ((uint64) target < old_nblocks) { uint64 i; for (i = (uint64) target; i < old_nblocks; i++) { cfs_map_entry_init(&m->cfs->map[i]); if (m->corrupt_mask != NULL && i < m->corrupt_mask_len) m->corrupt_mask[i] = 0; } } m->cfs->map_hdr.nblocks = target; } /* * cfs_journal_apply (the one-record TORN/SKIP/OK wrapper) was removed: the * scan engine validates before applying, and both replay loops install the * memory sink directly. The TORN verdict is CFS_SCAN_STOP_TORN_* now. */ int64 cfs_journal_replay(CfsRelation *cfs, off_t *stop_off, bool *mid_file_stop, char *corrupt_mask, uint64 corrupt_mask_len, CfsMapLoadContext context) { CfsJournalFileHeader jhdr; off_t off; int64 applied = 0; int rc; Assert(cfs != NULL); Assert(stop_off != NULL); Assert(mid_file_stop != NULL); *mid_file_stop = false; /* * Validate the journal header (a missing/empty journal is fine). No wait * event is active here: the scan engine owns the replay wait event and * starts it itself, so the early returns below must not report an end for * a start that has not happened (the unbalanced report would clobber * whatever wait the caller is in). */ rc = cfs_pread_all(cfs->jrn_fd, &jhdr, sizeof(jhdr), 0); if (rc == CFS_STORAGE_NOENT) { *stop_off = CFS_JOURNAL_HEADER_SIZE; return 0; } if (rc != CFS_STORAGE_OK) return -1; if (cfs_journal_header_validate(&jhdr) != CFS_FORMAT_OK) { /* * The journal header is structural damage: without a valid header the * records cannot be interpreted at all, so no replay decision can be * made safely. Mirror vanilla PostgreSQL, where an invalid WAL * record is fatal in every mode — there is no "treat the file as * empty" escape hatch. Outside a normal backend session (recovery, * standby, auxiliary processes) it stays a direct hard ERROR * exactly like vanilla WAL validation. A normal backend routes * the damage through cfs_report_corruption() (QDB-1507 U8), keeping * the same policy as the segment replay path: the * cfs_checksum_failure GUC decides ERROR or PANIC. */ /* * Structural .cfsjrn header corruption outside recovery: through * the centralised corruption handler (severity by GUC), matching * cfs_journal_replay_segment(). */ if (!cfs_corruption_guc_applies()) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: corrupt page map journal"), errdetail("Invalid .cfsjrn header in \"%s\".", cfs->jrn_path))); else cfs_report_corruption(cfs->rlocator, cfs->forknum, InvalidBlockNumber, psprintf("invalid .cfsjrn header in " "file \"%s\"", cfs->jrn_path), false); } { CfsJournalSink sink; CfsJournalMemSink mem; CfsJournalScanPolicy policy; CfsJournalScanResult scan; /* * The scan engine runs the loop; the mem sink applies rows to the * in-memory map and clears the corrupt mask a journal record heals. */ mem.cfs = cfs; mem.corrupt_mask = corrupt_mask; mem.corrupt_mask_len = corrupt_mask_len; mem.wrote_rows = 0; memset(&sink, 0, sizeof(sink)); sink.write_row = cfs_mem_write_row; sink.resize = cfs_mem_resize; sink.arg = &mem; sink.max_generation = cfs->map_hdr.max_generation; /* * A backend's delta replay picks the recovery severity on purpose: * the missing-.cfp record is skippable here, and the checksum-failure * channel must not take the session down for it. */ sink.recovery_severity = true; memset(&policy, 0, sizeof(policy)); policy.role = "replay"; policy.during_recovery = (context == CFS_LOAD_RECOVERY); cfs_journal_scan(cfs, (off_t) CFS_JOURNAL_HEADER_SIZE, &policy, &sink, &scan); cfs->map_hdr.max_generation = sink.max_generation; applied = mem.wrote_rows; off = scan.stop_off; /* * A torn record with valid records behind it is corruption the load * must remember: only a tail may be repaired by truncation below. */ *mid_file_stop = (scan.reason == CFS_SCAN_STOP_TORN_MIDFILE); if (scan.reason == CFS_SCAN_STOP_IO_ERROR) return -1; } /* * nblocks is restored deterministically by CFS_JRN_OP_RESIZE records * appended by cfs_write_page() (single-block extend), cfs_zero_extend() * and cfs_truncate(). UPDATE records never grow nblocks: the map lookup * (cfs_map_get_entry) is a pure capacity-grow, so replaying records in * any order yields the same nblocks. */ ereport(DEBUG1, (errmsg("CFS: journal replay applied %lld records, nblocks=%llu", (long long) applied, (unsigned long long) cfs->map_hdr.nblocks))); *stop_off = off; return applied; } /* * Replay journal entries in [start_off, current EOF), applying them to the * in-memory map. Stops at a torn/invalid trailing record (expected after a * crash or while a peer is mid-append). Returns the offset at which replay * stopped (>= start_off), or -1 on a read error. */ static off_t cfs_journal_replay_from(CfsRelation *cfs, off_t start_off) { CfsJournalSink sink; CfsJournalMemSink mem; CfsJournalScanPolicy policy; CfsJournalScanResult scan; /* * The delta replay for a cache miss: apply [start_off, EOF) to the * in-memory map through the scan engine. A torn record stops the scan: * the tail is the expected mid-append artifact of a peer writer (the * caller holds no lock), mid-file corruption cannot be delta-replayed * around, so the caller gets the reload sentinel. */ mem.cfs = cfs; mem.corrupt_mask = NULL; mem.corrupt_mask_len = 0; mem.wrote_rows = 0; memset(&sink, 0, sizeof(sink)); sink.write_row = cfs_mem_write_row; sink.resize = cfs_mem_resize; sink.arg = &mem; sink.max_generation = cfs->map_hdr.max_generation; sink.recovery_severity = true; memset(&policy, 0, sizeof(policy)); policy.role = "replay"; cfs_journal_scan(cfs, start_off, &policy, &sink, &scan); cfs->map_hdr.max_generation = sink.max_generation; if (scan.reason == CFS_SCAN_STOP_IO_ERROR) return (off_t) -1; if (scan.reason == CFS_SCAN_STOP_TORN_MIDFILE) return (off_t) -2; return scan.stop_off; } static int cfs_journal_scan_max_generation(CfsRelation *cfs, uint32 *max_gen) { return cfs_journal_fd_scan_max_generation(cfs->jrn_fd, cfs->jrn_path, max_gen); } int cfs_generation_summary(CfsRelation *cfs, uint32 *max_generation) { CfsJournalFileHeader jhdr; uint32 max_gen; /* * A lazy (pool-served) handle keeps no row array; its watermark is the * header it loaded. The journal scan below raises it past the header * either way. */ if (cfs->map != NULL) max_gen = cfs_map_live_summary(cfs); else max_gen = cfs->map_hdr.max_generation; if (cfs_journal_read_header(cfs->jrn_fd, &jhdr) && jhdr.max_generation > max_gen) max_gen = jhdr.max_generation; if (cfs_journal_scan_max_generation(cfs, &max_gen) != CFS_STORAGE_OK) return CFS_STORAGE_ERROR; *max_generation = max_gen; return CFS_STORAGE_OK; } /* * The segment replay's sink: an applied row in [first_block, last_block) * goes to the caller's callback (a NULL row means "the block is gone" - * DELETE), and a RESIZE below the segment's end invalidates every block * in [max(resize, first_block), last_block); grows carry no per-block * state and are the caller's (metadata) business. */ typedef struct CfsJournalSegSink { BlockNumber first_block; BlockNumber last_block; CfsJournalSegCB cb; void *cb_arg; } CfsJournalSegSink; static void cfs_seg_write_row(void *arg, BlockNumber block, const CfsMapEntry *row) { CfsJournalSegSink *s = (CfsJournalSegSink *) arg; s->cb(block, CFS_MAP_ENTRY_VALID(row) ? row : NULL, s->cb_arg); } static void cfs_seg_resize(void *arg, BlockNumber target) { CfsJournalSegSink *s = (CfsJournalSegSink *) arg; BlockNumber b; if (target >= s->last_block) return; for (b = Max(target, s->first_block); b < s->last_block; b++) s->cb(b, NULL, s->cb_arg); } off_t cfs_journal_replay_segment(CfsRelation *cfs, off_t start_off, BlockNumber first_block, CfsJournalSegCB cb, void *arg) { CfsJournalFileHeader jhdr; CfsJournalSink sink; CfsJournalSegSink sarg; BlockNumber last_block = first_block + CFS_MAP_SEGMENT_BLOCKS; /* * A journal header that does not validate is corruption, never a * legitimate empty journal: every reset leaves a header behind. Same * report as the full replay outside a normal backend session * (a hard ERROR - the startup process must not come up on a * journal it cannot trust); a normal backend takes the * centralised handler (cfs_report_corruption), where the * cfs_checksum_failure GUC decides the severity. The pool sync reads * the header on its own before calling here, but no caller can bypass * this check once it replays: every record the function interprets * passes it first. */ if (!cfs_journal_read_header(cfs->jrn_fd, &jhdr)) { if (!cfs_corruption_guc_applies()) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: corrupt page map journal"), errdetail("Invalid .cfsjrn header in \"%s\".", cfs->jrn_path))); else cfs_report_corruption(cfs->rlocator, cfs->forknum, InvalidBlockNumber, psprintf("invalid .cfsjrn header in " "file \"%s\"", cfs->jrn_path), false); } sarg.first_block = first_block; sarg.last_block = last_block; sarg.cb = cb; sarg.cb_arg = arg; memset(&sink, 0, sizeof(sink)); sink.write_row = cfs_seg_write_row; sink.resize = cfs_seg_resize; sink.arg = &sarg; sink.first_block = first_block; sink.last_block = last_block; sink.filter_range = true; sink.recovery_severity = true; /* * The caller (cfs_shared_map_sync_segment) holds the relation's append * lock, so a torn trailing record can only be a peer mid-append: stop * before it. Mid-file corruption additionally fails the sync: the caller * must not mark the segment journal_synced and publish a partially * replayed map to every backend. */ { CfsJournalScanPolicy policy; CfsJournalScanResult scan; memset(&policy, 0, sizeof(policy)); policy.role = "replay"; cfs_journal_scan(cfs, start_off, &policy, &sink, &scan); if (scan.reason == CFS_SCAN_STOP_IO_ERROR || scan.reason == CFS_SCAN_STOP_TORN_MIDFILE) return (off_t) -1; return scan.stop_off; } } bool cfs_map_needs_refresh(CfsRelation *cfs) { Assert(cfs != NULL && cfs->map != NULL); /* * Any journal-side flag (stat failure, unreadable header, incarnation * move, size move in either direction) means the in-memory map is not in * sync with the journal; the derivation lives in the judge. */ return cfs_state_journal_moved(cfs, cfs->jrn_incarnation, cfs->map_synced_jrn_off, NULL) != 0; } /* * Reload the whole map (snapshot + journal) for a handle whose delta replay * cannot be trusted: the journal was reset (incarnation change), shrank, or * holds mid-file corruption. A swapped pair is reopened only by a caller * that holds the append lock (repair = true), exactly like the delta caller. */ static int cfs_refresh_map_full_reload(CfsRelation *cfs, bool repair, CfsMapLoadContext context, bool have_hdr, const CfsJournalFileHeader *jhdr) { int rc; if (cfs_map_file_swapped(cfs)) { if (!repair) return CFS_STORAGE_NOENT; return cfs_reopen(cfs); } rc = cfs_map_load(cfs, repair, context); if (rc != CFS_STORAGE_OK) return rc; if (have_hdr) cfs->jrn_incarnation = jhdr->incarnation; return CFS_STORAGE_OK; } int cfs_refresh_map(CfsRelation *cfs, bool repair, CfsMapLoadContext context) { CfsJournalFileHeader jhdr; bool have_hdr; int fl; Assert(cfs != NULL); /* * The judge derives every signal; this function only picks the reaction. * 'have_hdr' keeps the old unreadable-header fallback: when the header * cannot be read mid-reset the incarnation branch is skipped and the size * comparison alone decides. */ fl = cfs_state_journal_moved(cfs, cfs->jrn_incarnation, cfs->map_synced_jrn_off, &jhdr); have_hdr = !(fl & CFS_STATE_JRN_HEADER_STALE); if (fl & CFS_STATE_JRN_STAT_FAILED) return CFS_STORAGE_ERROR; if (have_hdr && fl & CFS_STATE_JRN_RESET) { /* * The journal was reset (checkpoint truncate or compaction swap) * since this handle last synced its map. The incarnation check * catches the ABA case a pure size comparison cannot: the journal may * have been truncated AND grown back past the saved replay offset, in * which case delta-replaying from that offset would silently skip * legitimate updates of the new incarnation. Do a full reload * instead. */ ereport(DEBUG1, (errmsg("CFS: journal incarnation changed %u -> %u for \"%s\", reloading map", (unsigned) cfs->jrn_incarnation, (unsigned) jhdr.incarnation, cfs->jrn_path))); /* * When the reset came from a compaction swap, this handle's * descriptors point at the replaced inodes; reloading the map through * them would mix the old snapshot with journal records referencing * the new .cfp. Reopen by path in that case - but only for a caller * that holds the append lock: cfs_reopen() resolves an interrupted * swap (cfs_recover_compaction), which may only run under the lock or * in the single-writer recovery (the invariant at * cfs_recover_compaction). The lock-free caller (checkpoint phase 1, * repair = false) gets CFS_STORAGE_NOENT instead and must skip the * relation: the swap already owns the files, and the next checkpoint * folds whatever the new pair holds. */ return cfs_refresh_map_full_reload(cfs, repair, context, have_hdr, &jhdr); } if (fl & CFS_STATE_JRN_SHRANK) { /* * The journal shrank: a checkpoint saved a fresh snapshot and * truncated the journal. Reload the snapshot and replay whatever * (little) journal is left, then re-baseline the synced offset. Kept * as a fallback for journals whose header predates the incarnation * field (or is momentarily unreadable mid-reset). */ /* * See the incarnation branch above: never load via a swapped fd, and * never reopen lock-free (repair = false means the caller cannot be * holding the append lock). */ return cfs_refresh_map_full_reload(cfs, repair, context, have_hdr, &jhdr); } if (fl & CFS_STATE_JRN_GREW) { off_t stopped_at; stopped_at = cfs_journal_replay_from(cfs, cfs->map_synced_jrn_off); if (stopped_at == (off_t) -2) return cfs_refresh_map_full_reload(cfs, repair, context, have_hdr, &jhdr); if (stopped_at < 0) return CFS_STORAGE_ERROR; cfs->map_synced_jrn_off = stopped_at; } return CFS_STORAGE_OK; } /* ================================================================ * Page-level read/write API * ================================================================ */ int cfs_read_page(CfsRelation *cfs, BlockNumber blocknum, char *dst) { CfsMapEntry *e; Assert(cfs != NULL && dst != NULL); /* * A read beyond the logical size is an error; a never-written block * inside the range returns a zero page (extension gap / recovery). */ if ((uint64) blocknum >= cfs->map_hdr.nblocks) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("CFS: read_page: block %u out of range (nblocks=%llu)", blocknum, (unsigned long long) cfs->map_hdr.nblocks))); } /* * Every in-range block lives in the private map. A full handle of an * empty relation (nblocks == 0) may legitimately have no entry array yet: * it grows lazily on the first write or zero-extend, and the out-of-range * error above is the correct answer for any read before that. */ Assert(cfs->map != NULL); /* Ensure the map array covers this block. */ cfs_map_ensure_capacity(cfs, (uint64) blocknum + 1); e = &cfs->map[blocknum]; /* * Validate the entry before trusting its fields. The validator accepts a * never-written slot, so this cannot clash with the zero-page branch * below. A corrupt entry (bit rot in .cfsmap) must surface as an error * routed through cfs_report_corruption() instead of serving stale data. */ { CfsFormatStatus st = cfs_map_entry_validate(e, true); if (st != CFS_FORMAT_OK) { ereport(WARNING, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: invalid page map entry for block %u (offset %llu, status %s)", blocknum, (unsigned long long) e->physical_offset, CfsFormatStatusString(st)))); return CFS_STORAGE_CORRUPT; } } if (e->physical_offset == CFS_ENTRY_INVALID_OFFSET) { /* Never-written block: return a zero page. */ MemSet(dst, 0, CFS_BLCKSZ); return CFS_STORAGE_OK; } return cfs_read_record(cfs, (off_t) e->physical_offset, e->compressed_size, dst, CFS_BLCKSZ); } int cfs_write_compressed_page(CfsRelation *cfs, BlockNumber blocknum, const CfsCompressResult *cres, const CfsWriteOptions *opts, uint32 generation, CfsMapEntry *out_entry) { CfsMapEntry new_entry; Assert(cfs != NULL && cres != NULL && opts != NULL); Assert(!cfs->read_only); /* * The caller (cfs_write_page_cached) holds the per-relation append lock, * so the pwrite/journal sequence below is serialised across backends. * Compression was already performed outside the lock; only the offset * computation, pwrite, journal append and map/cache update remain here. */ /* * Step 1: append the already-compressed record to .cfp. * * NOTE: cfs_append_compressed_record returns a fresh entry with * generation=0; we set the real generation (derived by the caller under * the append lock) below before journaling. */ if (cfs_append_compressed_record(cfs, cres, &new_entry) != CFS_STORAGE_OK) return CFS_STORAGE_ERROR; new_entry.generation = generation; cfs_map_entry_crc_set(&new_entry); /* * The new generation is occupied the moment its journal record exists; * keep the header watermark and its CRC in sync right away so the * in-memory header always covers every entry the map holds (the snapshot * save re-derives the watermark, but the handle must not rely on a * checkpoint happening before a reopen). */ if (generation > cfs->map_hdr.max_generation) { cfs->map_hdr.max_generation = generation; } /* * Step 2: if this write extends the logical size, grow nblocks and — * for a genuine extend (smgrextend) — journal a RESIZE record BEFORE * the UPDATE. This makes recovery restore nblocks deterministically from * the RESIZE record instead of inferring it from the highest UPDATE * block, so the result no longer depends on the order UPDATE records are * replayed. * * The in-memory nblocks growth always happens (so the cached relation * size published below stays consistent), but the RESIZE journal record * is written only for a real extend. A plain overwrite reaching here * with a stale handle (a bgwriter flushing a page beyond its cached * nblocks) must not emit a RESIZE: its extend was already recorded, and a * late low-valued RESIZE would lose to "last RESIZE wins" and shrink the * replayed size. RESIZE precedes UPDATE on purpose: a crash between the * two leaves the block zero-filled (entry invalid) with the correct size, * never a live entry beyond a stale nblocks. */ if (opts->is_extend && (cfs->flags & CFS_OPEN_LAZY_MAP) != 0) { /* * A lazy handle's map_hdr.nblocks comes from the .cfsmap snapshot, * which is only rewritten at checkpoint; after an in-place truncate * it is stale and may be larger than the real size. The extension * itself is authoritative (relation extension lock), so journal the * new end unconditionally instead of comparing with the stale value. */ cfs->map_hdr.nblocks = (uint64) blocknum + 1; cfs_journal_append_resize(cfs, blocknum + 1); } else if ((uint64) blocknum >= (uint64) cfs->map_hdr.nblocks) { cfs->map_hdr.nblocks = (uint64) blocknum + 1; if (opts->is_extend) cfs_journal_append_resize(cfs, blocknum + 1); } /* * Step 3: append the journal UPDATE record. Step 4: update the in-memory * map. * * Order matters for crash-safety: .cfp is already durable in kernel * cache; the journal record makes the map update discoverable on * recovery. The .cfsmap snapshot is deferred to checkpoint. * * Registering the dirtied sidecar files with the checkpointer sync queue * is the caller's business, deliberately outside the append lock (a full * sync queue turns the registration into a synchronous fallback fsync * that must not hold other writers). */ cfs_journal_append_update(cfs, blocknum, &new_entry); if (cfs->map != NULL) cfs_map_set_entry(cfs, blocknum, &new_entry); /* * A full handle of a fresh (empty) relation may not have allocated its * map array yet — it grows lazily on the next cfs_map_get_entry(); the * authoritative readers (tests, compaction) go through that path. The * shared segment pool owns the entry for lazy handles and for callers * that received it through 'out_entry'. */ if (out_entry != NULL) *out_entry = new_entry; return CFS_STORAGE_OK; } int cfs_write_page(CfsRelation *cfs, BlockNumber blocknum, const char *src, const CfsWriteOptions *opts) { CfsCompressResult cres; CfsMapEntry *old; uint32 generation; int rc; Assert(cfs != NULL && src != NULL && opts != NULL); Assert(!cfs->read_only); if (cfs_compress_page(cfs, src, CFS_BLCKSZ, opts, &cres) != CFS_STORAGE_OK) return CFS_STORAGE_ERROR; /* Single-threaded API: derive the generation from the local map. */ old = cfs_map_get_entry(cfs, blocknum); generation = (old->physical_offset != CFS_ENTRY_INVALID_OFFSET) ? old->generation + 1 : 1; rc = cfs_write_compressed_page(cfs, blocknum, &cres, opts, generation, NULL); /* * Single-threaded API: no append lock is held, so registering the dirtied * sidecars with the checkpointer queue right here cannot serialize anyone * (see cfs_write_page_cached for the locked path). */ if (rc == CFS_STORAGE_OK && !opts->skip_fsync) { cfs_register_dirty_file(cfs->rlocator, cfs->forknum, CFS_FILE_DATA); cfs_register_dirty_file(cfs->rlocator, cfs->forknum, CFS_FILE_JOURNAL); } return rc; } int cfs_zero_extend(CfsRelation *cfs, BlockNumber start, BlockNumber count) { BlockNumber end; Assert(cfs != NULL && !cfs->read_only); if (count == 0) return CFS_STORAGE_OK; if (start > MaxBlockNumber || count > MaxBlockNumber - start) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("CFS: cannot zero-extend relation beyond %u blocks", MaxBlockNumber))); end = start + count; /* exclusive */ /* * A full handle owns a private entry array even while the relation is * empty: cfs_map_ensure_capacity() allocates it on demand, and * cfs_read_page() reads the new zero pages from it. A lazy handle must * not allocate a private map — its entries live in the shared segment * pool, and the RESIZE below is recorded from the header alone. */ if ((cfs->flags & CFS_OPEN_LAZY_MAP) == 0) cfs_map_ensure_capacity(cfs, (uint64) end); /* * Record a single RESIZE entry. The new blocks in [nblocks, end) are * already initialised to the "never written" state by * cfs_map_ensure_capacity() above and are read back as zero pages by * cfs_read_page() (physical_offset == CFS_ENTRY_INVALID_OFFSET), so we do * not need a per-block UPDATE journal record per new block. This keeps * the journal O(1) regardless of how many blocks a COPY extends. */ if ((cfs->flags & CFS_OPEN_LAZY_MAP) != 0) { /* * A lazy handle's local nblocks is a snapshot value and may be larger * than the real size after an in-place truncate: journal the * authoritative end unconditionally (see cfs_write_compressed_page). */ cfs->map_hdr.nblocks = end; cfs_journal_append_resize(cfs, end); } else if ((uint64) end > cfs->map_hdr.nblocks) { cfs->map_hdr.nblocks = end; /* * Append a RESIZE record so that journal replay restores nblocks * deterministically after a crash. */ cfs_journal_append_resize(cfs, end); } /* * The RESIZE record dirtied the journal. Registration with the * checkpointer sync queue is left to the caller: the smgr wrapper does it * after releasing the append lock, so the fallback fsync of a full queue * never parks the relation's writers behind it (the same contract as * cfs_write_page_cached). */ ereport(DEBUG1, (errmsg("CFS: zero-extended to %u blocks (start=%u count=%u)", end, start, count))); return CFS_STORAGE_OK; } int cfs_truncate(CfsRelation *cfs, BlockNumber nblocks) { uint64 old_nblocks = cfs->map_hdr.nblocks; Assert(cfs != NULL && !cfs->read_only); if ((uint64) nblocks >= old_nblocks && cfs->map != NULL) return CFS_STORAGE_OK; /* * Lazy handles must not take the early exit: their map_hdr.nblocks is * only a local counter (the on-disk truth lives in the journal and the * metadata slot), so "nblocks >= old" proves nothing. Always journal the * RESIZE — a redundant record is idempotent ("last wins") — and * update the counter. */ if ((uint64) nblocks >= old_nblocks && cfs->map == NULL) { cfs->map_hdr.nblocks = (uint64) nblocks; cfs_journal_append_resize(cfs, nblocks); return CFS_STORAGE_OK; } /* * The caller (cfs_smgr_truncate) holds the per-relation append lock, so * the journal append below is serialised across backends. */ /* * Invalidate the dropped slots and journal a single RESIZE record. The * RESIZE replay path invalidates the [nblocks, old) slots itself, so no * per-block DELETE records are needed. */ cfs_map_truncate(cfs, nblocks); cfs_journal_append_resize(cfs, nblocks); /* * The physical truncation of the map file is deliberately NOT done here. * This runs inside RelationTruncate()'s critical section, where an I/O * failure escalates to PANIC, and the tail read it used to do costs * O(dropped rows). The RESIZE record journaled above is the single * durable instruction; every consumer applies it to the logical size and * the on-disk file catches up at the next persist point: * * - the checkpoint's phase 2 applies the last RESIZE under the append * lock - charging the dropped payloads while they are still readable, * then truncating and fsyncing the map (cfs_checkpoint_fold_tail); - the * immediate-sync snapshot is written from the replayed in-memory map and * so carries the new size already; - compaction builds its candidate map * at the replayed size. * * Until then the rows beyond the new logical size stay on disk as dead * weight: every reader resolves blocks against the logical size (the * metadata slot updated by the smgr wrapper, or the replayed * map_hdr.nblocks), never against the map file's row count, and fsck * drops the truncated interval from its coverage the same way replay * does. */ /* * The RESIZE record dirtied the journal; the caller registers it with the * checkpointer sync queue (outside the append lock, like cfs_zero_extend * above). */ return CFS_STORAGE_OK; }