/*------------------------------------------------------------------------- * cfs_fsck.c * Compressed File Store (CFS) — structural integrity checker. * * Implements the offline format checker declared in cfs_fsck.h. It reads the * raw sidecar files and validates them purely through the format layer * (cfs_format.c), independent of the storage manager and buffer cache. * * Every checker streams the file through a fixed-size buffer instead of * allocating the whole file: a .cfp / .cfsmap larger than MaxAllocSize (~1 * GB) must be checkable, because such files are the norm for the relations * CFS exists for. The .cfp walker is segment-aware: it follows the * ".cfp", ".cfp.1", ... chain and recognises the unwritten * padding a segment tail contains when the append cursor rolled over to the * next segment boundary. * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_fsck.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include #include #include "common/relpath.h" #include "port.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_cfp.h" #include "storage/cfs/cfs_format.h" #include "storage/cfs/cfs_fsck.h" #include "storage/cfs/cfs_journal.h" #include "storage/cfs/cfs_map_file.h" #include "storage/cfs/cfs_path.h" #include "storage/cfs/cfs_shmem.h" #include "storage/fd.h" #include "storage/relfilelocator.h" #include "utils/hsearch.h" #include "utils/palloc.h" /* * Number of maximal records per .cfp pread() chunk. The buffer holds this * many CFS_RECORD_SIZE(CFS_BLCKSZ) units, so a whole record always fits * (~514 kB at 64 records). */ #define CFS_FSCK_CFP_CHUNK_RECORDS 64 /* * Cap on the per-run corrupt-row tracker. A map with more corrupt rows than * this is damage on a scale no journal-heal contract can cover, so further * rows are counted as errors immediately: memory stays bounded (a few tens of * MB, like CFS_FSCK_GEN_TRACK_MAX) instead of growing with the map. */ #define CFS_FSCK_COVERAGE_MAX (1 << 20) void cfs_fsck_result_init(CfsFsckResult *result) { MemSet(result, 0, sizeof(CfsFsckResult)); } /* ---------------------------------------------------------------- * Streaming read helpers * ---------------------------------------------------------------- */ /* * Read up to 'len' bytes from 'fd' at 'offset'. Returns the number of * bytes read (short on EOF), or -1 on a hard error. */ static ssize_t cfs_fsck_pread(int fd, void *buf, size_t len, off_t offset) { char *p = (char *) buf; size_t done = 0; while (done < len) { ssize_t n = pg_pread(fd, p + done, len - done, offset + done); if (n < 0) { if (errno == EINTR) continue; return -1; } if (n == 0) break; /* EOF */ done += n; } return (ssize_t) done; } /* * Open a sidecar file read-only. Returns the fd, or -1 when the file does * not exist or cannot be opened. */ static int cfs_fsck_open(const char *path) { int fd; fd = BasicOpenFile(path, O_RDONLY | PG_BINARY); if (fd < 0) ereport(DEBUG1, (errmsg("CFS: fsck cannot open \"%s\": %m", path))); return fd; } static uint64 cfs_file_size(const char *path) { struct stat st; if (path == NULL || stat(path, &st) != 0) return 0; return (uint64) st.st_size; } /* * Report a missing file according to the require_files option. Returns 1 * so the caller can "return 1" uniformly. */ static int cfs_fsck_missing(const CfsFsckOptions *opts, CfsFsckResult *result) { if (opts != NULL && opts->require_files) { result->missing_files++; result->errors++; } return 1; } /* ---------------------------------------------------------------- * Journal coverage of corrupt map rows * ---------------------------------------------------------------- */ /* * One block in a coverage set. The map scanner records why the row failed * validation; the resolution pass uses the status to keep the counters apart. */ typedef struct CfsFsckCorruptEntry { uint32 blocknum; /* hash key */ CfsFormatStatus status; /* map row's validation status */ } CfsFsckCorruptEntry; /* One block the journal healed; kept only for the .cfp cross-check. */ typedef struct CfsFsckHealedEntry { uint32 blocknum; /* hash key */ } CfsFsckHealedEntry; /* Half-open block interval [start, end) dropped by a journal RESIZE. */ typedef struct CfsFsckInterval { uint64 start; uint64 end; } CfsFsckInterval; /* * Cross-section state of one fsck run: corrupt map rows, the rows the journal * heals, and the intervals a shrink RESIZE drops. The standalone scanners do * not need it (cov == NULL) and keep their immediate verdict; * cfs_fsck_relation() always collects, so that a map row torn by a lock-free * fold pwrite is judged with the journal in hand. * * Memory is bounded: the corrupt set stops growing at * CFS_FSCK_COVERAGE_MAX and the healed set can never outgrow it, so a huge * map paired with an equally huge journal costs a bounded few tens of MB - * the same contract the streaming scanners already follow. */ struct CfsFsckCoverage { HTAB *corrupt; /* blockno -> row failed validation */ HTAB *healed; /* blockno -> healed by the journal */ bool coverage_degraded; /* corrupt set hit its cap */ uint64 nblocks; /* logical size, RESIZE by RESIZE */ CfsFsckInterval *dropped; /* intervals a shrink dropped */ uint64 ndropped; uint64 maxdropped; }; static HTAB * cfs_fsck_coverage_hash(const char *name, Size entrysize) { HASHCTL ctl; ctl.keysize = sizeof(uint32); ctl.entrysize = entrysize; ctl.hcxt = CurrentMemoryContext; return hash_create(name, 64, &ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); } /* * Create the sets of an already zeroed coverage. Kept out of the caller's * initialisation so that cfs_fsck_coverage_free() can run from * the error cleanup even when this allocation fails halfway. */ static void cfs_fsck_coverage_init(CfsFsckCoverage *cov) { cov->corrupt = cfs_fsck_coverage_hash("cfs fsck corrupt map rows", sizeof(CfsFsckCorruptEntry)); cov->healed = cfs_fsck_coverage_hash("cfs fsck healed map rows", sizeof(CfsFsckHealedEntry)); } static void cfs_fsck_coverage_add_corrupt(CfsFsckCoverage *cov, uint32 blocknum, CfsFormatStatus status) { CfsFsckCorruptEntry *ce; ce = hash_search(cov->corrupt, &blocknum, HASH_ENTER, NULL); ce->status = status; } /* Record that a corrupt row is healed (already removed from 'corrupt'). */ static void cfs_fsck_coverage_heal(CfsFsckCoverage *cov, uint32 blocknum, CfsFsckResult *result) { hash_search(cov->healed, &blocknum, HASH_ENTER, NULL); result->healed_entries++; } static bool cfs_fsck_coverage_is_healed(CfsFsckCoverage *cov, uint32 blocknum) { return hash_search(cov->healed, &blocknum, HASH_FIND, NULL) != NULL; } /* * Remember that RESIZE dropped [start, end). The array is tiny in practice * (a shrink is rare) and only exists to answer "was this block dropped?" for * the corrupt rows left after the journal pass. */ static void cfs_fsck_coverage_drop(CfsFsckCoverage *cov, uint64 start, uint64 end) { if (cov->ndropped == cov->maxdropped) { cov->maxdropped = (cov->maxdropped == 0) ? 8 : cov->maxdropped * 2; if (cov->dropped == NULL) cov->dropped = palloc(sizeof(CfsFsckInterval) * cov->maxdropped); else cov->dropped = repalloc(cov->dropped, sizeof(CfsFsckInterval) * cov->maxdropped); } cov->dropped[cov->ndropped].start = start; cov->dropped[cov->ndropped].end = end; cov->ndropped++; } static bool cfs_fsck_coverage_is_dropped(CfsFsckCoverage *cov, uint32 blocknum) { uint64 i; for (i = 0; i < cov->ndropped; i++) { if (blocknum >= cov->dropped[i].start && blocknum < cov->dropped[i].end) return true; } return false; } /* Safe on a zeroed coverage and on a partly initialised one. */ static void cfs_fsck_coverage_free(CfsFsckCoverage *cov) { if (cov->corrupt != NULL) { hash_destroy(cov->corrupt); cov->corrupt = NULL; } if (cov->healed != NULL) { hash_destroy(cov->healed); cov->healed = NULL; } if (cov->dropped != NULL) { pfree(cov->dropped); cov->dropped = NULL; } cov->ndropped = 0; cov->maxdropped = 0; } /* * Resolve the map rows the journal pass left: a row a shrink RESIZE dropped is * healed (replay zeroed its slot, and a later grow leaves it sparse), every * other row keeps the counts the standalone scanner raises immediately. */ static void cfs_fsck_coverage_resolve(CfsFsckCoverage *cov, CfsFsckResult *result) { HASH_SEQ_STATUS seq; CfsFsckCorruptEntry *ce; hash_seq_init(&seq, cov->corrupt); while ((ce = hash_seq_search(&seq)) != NULL) { if (cfs_fsck_coverage_is_dropped(cov, ce->blocknum)) { cfs_fsck_coverage_heal(cov, ce->blocknum, result); continue; } if (ce->status == CFS_FORMAT_BAD_CRC) result->crc_failures++; else result->field_failures++; result->errors++; } } /* ---------------------------------------------------------------- * .cfsmap * ---------------------------------------------------------------- */ int cfs_fsck_map_file(const char *map_path, const char *cfp_path, const CfsFsckOptions *opts, CfsFsckResult *result, CfsFsckCoverage *cov) { int fd; uint64 nblocks; uint64 cfp_size; CfsMapRangeIter it; uint64 blk; const CfsMapEntry *e; bool check_fields = (opts != NULL && opts->check_fields); int prologue_rc; fd = cfs_fsck_open(map_path); if (fd < 0) return cfs_fsck_missing(opts, result); /* * The shared prologue read, in its status-returning form: fsck reports * damage instead of aborting, so it tells a short/empty file from an * invalid header itself. The empty file (NOENT) is the LEGAL fresh state * the open path's prologue_ensure creates for a brand-new relation - the * one classification cfs_map_file.c owns and every consumer (the loader, * the recovery header check, fsck) shares: 0 bytes fresh, 1..7 bytes * corruption, 8+ bytes validated. */ prologue_rc = cfs_map_file_prologue_check(fd, &nblocks); if (prologue_rc != CFS_STORAGE_OK && prologue_rc != CFS_STORAGE_NOENT) { off_t map_size = lseek(fd, 0, SEEK_END); if (prologue_rc == CFS_STORAGE_ERROR || map_size < (off_t) sizeof(CfsMapPrologue)) { ereport(DEBUG1, (errmsg("CFS: fsck: map file \"%s\" is truncated", map_path))); result->truncated_records++; } else result->map_header_ok = false; result->errors++; close(fd); return 1; } result->map_header_ok = true; /* * Rows are derived from the file size. A partial trailing row is a torn * write: the loader ignores it (the next snapshot rewrites the file * exactly), but fsck still reports it so the artifact is visible. */ { off_t map_size = lseek(fd, 0, SEEK_END); if (map_size < 0) { ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: fsck: could not measure map file \"%s\": %m", map_path))); close(fd); return 1; } nblocks = cfs_map_rows_from_size((uint64) map_size); { uint64 tail = (map_size >= (off_t) CFS_MAP_HEADER_SIZE) ? ((uint64) map_size - CFS_MAP_HEADER_SIZE) % CFS_MAP_ENTRY_SIZE : 0; if (tail != 0) { /* * A partial trailing row is the normal crash artifact of a * torn positional pwrite; the loader ignores it and the next * snapshot rewrites the file exactly. Count it as a torn * tail (visible, not an error), never as damage - otherwise a * kill -9 mid-fold fails pg_cfs_check. */ ereport(DEBUG1, (errmsg("CFS: fsck: map file \"%s\" ends with a partial row (%llu bytes)", map_path, (unsigned long long) tail))); result->torn_tails++; } } } if (!cfs_cfp_chain_stat(cfp_path, &cfp_size, NULL)) cfp_size = 0; cfs_map_range_iter_init(&it, fd, nblocks); while (cfs_map_range_iter_next(&it, &blk, &e)) { CfsFormatStatus st = CFS_FORMAT_OK; CfsMapRowClass rowclass; uint32 blocknum = (uint32) blk; result->map_entries++; /* * The shared row contract (cfs_map_row_classify): an all-zero row is * a sparse hole and legal; anything else that fails validation is * corruption, with '*status' telling a CRC mismatch from a * field-contract violation. */ rowclass = cfs_map_row_classify(e, check_fields, &st); if (rowclass == CFS_MAP_ROW_HOLE) { result->empty_entries++; continue; } if (rowclass == CFS_MAP_ROW_CORRUPT) { if (cov == NULL) { /* * Distinguish a CRC mismatch from a field-contract violation * so the counters say what actually broke. */ if (st == CFS_FORMAT_BAD_CRC) result->crc_failures++; else result->field_failures++; result->errors++; } else if (hash_get_num_entries(cov->corrupt) >= CFS_FSCK_COVERAGE_MAX) { /* * Past the cap the row is judged immediately: keeping the set * bounded is worth losing the (already implausible) chance of * healing it. */ if (!cov->coverage_degraded) { cov->coverage_degraded = true; ereport(DEBUG1, (errmsg("CFS: fsck: corrupt-row coverage hit its cap of %d entries; further corrupt map rows are reported as errors", CFS_FSCK_COVERAGE_MAX))); } if (st == CFS_FORMAT_BAD_CRC) result->crc_failures++; else result->field_failures++; result->errors++; } else { /* * Defer the verdict to the journal scan: while a row is torn * by a fold pwrite its covering record still exists (the * journal is reset only after the map fsync), so the row may * be healable rather than damage. */ cfs_fsck_coverage_add_corrupt(cov, blocknum, st); } } else if (e->physical_offset == CFS_ENTRY_INVALID_OFFSET) { result->empty_entries++; } else if (e->physical_offset < CFS_CFP_BASE_OFFSET) { /* * A non-zero offset that falls inside the reserved lead-in can * never point at a real record. */ ereport(DEBUG1, (errmsg("CFS: fsck: map entry %llu has offset %llu inside reserved lead-in", (unsigned long long) blk, (unsigned long long) e->physical_offset))); result->offset_out_of_range++; result->errors++; } else { uint64 end; /* * Every written entry carries generation >= 1 (the first write of * a block sets it); zero on a non-empty entry is corruption. */ if (e->generation == 0) { ereport(DEBUG1, (errmsg("CFS: fsck: map entry %llu has zero generation", (unsigned long long) blk))); result->generation_violations++; result->errors++; } result->live_entries++; end = e->physical_offset + CFS_RECORD_SIZE(e->compressed_size); if (cfp_size > 0 && end > cfp_size) { ereport(DEBUG1, (errmsg("CFS: fsck: map entry %llu points past .cfp EOF (offset %llu, end %llu, cfp_size %llu)", (unsigned long long) blk, (unsigned long long) e->physical_offset, (unsigned long long) end, (unsigned long long) cfp_size))); result->offset_out_of_range++; result->errors++; } } } if (it.truncated) { ereport(DEBUG1, (errmsg("CFS: fsck: map file \"%s\" truncated at entry %llu", map_path, (unsigned long long) it.next_block))); result->truncated_records++; result->errors++; } cfs_map_range_iter_free(&it); /* * A map with live entries but no .cfp data is inconsistent: the entries * point at records that cannot exist. Checked here rather than per entry * because the per-entry EOF check above only runs when cfp_size > 0. This * applies in both modes (deep and not), and a fully empty map with no * .cfp is not an error. */ if (result->live_entries > 0 && cfp_size == 0) { ereport(DEBUG1, (errmsg("CFS: fsck: live map entries but .cfp chain is missing or empty"))); result->missing_files++; result->errors++; } close(fd); return (result->errors > 0) ? 1 : 0; } /* ---------------------------------------------------------------- * .cfsjrn * ---------------------------------------------------------------- */ /* Per-block generation tracker for the journal monotonicity check. */ typedef struct CfsFsckGenEntry { uint32 blocknum; /* hash key */ uint32 generation; /* highest generation seen so far */ } CfsFsckGenEntry; /* The census observers the fsck journal scan runs with (see below). */ typedef struct CfsFsckJournalCtx { CfsFsckResult *result; CfsFsckCoverage *cov; HTAB *gen_tab; } CfsFsckJournalCtx; /* One structurally present but invalid record: count it and carry on. */ static void cfs_fsck_journal_invalid(void *arg, off_t rec_off, CfsFormatStatus st) { CfsFsckJournalCtx *ctx = (CfsFsckJournalCtx *) arg; if (st == CFS_FORMAT_BAD_CRC) ctx->result->crc_failures++; else ctx->result->field_failures++; ctx->result->errors++; } /* One valid record: the census itself, unchanged from the loop it was. */ static void cfs_fsck_journal_record(void *arg, const CfsJournalEntry *je) { CfsFsckJournalCtx *ctx = (CfsFsckJournalCtx *) arg; CfsFsckResult *result = ctx->result; CfsFsckCoverage *cov = ctx->cov; HTAB *gen_tab = ctx->gen_tab; result->journal_records++; /* * A corrupt map row whose block the journal still rewrites is healed, not * damage: the next fold installs this record's mapping. Removing the * block from the pending set keeps the cost proportional to the corrupt * rows, never to the journal. * * ponytail: coverage is decided by the record alone, not by the replay's * durability policy (cfs_journal.c): a valid UPDATE whose .cfp bytes are * missing still heals here while replay skips it, so simultaneous map and * .cfp damage can read as clean. Ceiling accepted (inherited: this scan * never opens .cfp); the upgrade path is to check data usability here, * which needs .cfp access in the journal scan. */ if (cov != NULL) { if ((je->op == CFS_JRN_OP_UPDATE || je->op == CFS_JRN_OP_DELETE) && hash_search(cov->corrupt, &je->blocknum, HASH_REMOVE, NULL) != NULL) cfs_fsck_coverage_heal(cov, je->blocknum, result); else if (je->op == CFS_JRN_OP_RESIZE) { /* * Replay applies RESIZE in order: a shrink zeroes the slots it * drops and a later grow leaves them sparse, so a corrupt row in * the dropped interval is healed even when nblocks grows again * (see cfs_fsck_coverage_resolve()). */ if ((uint64) je->blocknum < cov->nblocks) cfs_fsck_coverage_drop(cov, je->blocknum, cov->nblocks); cov->nblocks = je->blocknum; } } if (je->op == CFS_JRN_OP_UPDATE) { uint32 gen = je->new_entry.generation; bool found; CfsFsckGenEntry *gent; CfsFormatStatus nest_st; /* * The embedded new_entry carries its own CRC and field contract; * validate it even though the outer journal record already passed its * own CRC check. A live new_entry must also never point inside the * reserved lead-in: replay would silently skip such a record. */ nest_st = cfs_map_entry_validate(&je->new_entry, true); if (nest_st != CFS_FORMAT_OK) { ereport(DEBUG1, (errmsg("CFS: fsck: journal record for block %u has an invalid new_entry", je->blocknum))); if (nest_st == CFS_FORMAT_BAD_CRC) result->crc_failures++; else result->field_failures++; result->errors++; } else if (je->new_entry.physical_offset != CFS_ENTRY_INVALID_OFFSET && je->new_entry.physical_offset < CFS_CFP_BASE_OFFSET) { ereport(DEBUG1, (errmsg("CFS: fsck: journal record for block %u has new_entry offset %llu inside reserved lead-in", je->blocknum, (unsigned long long) je->new_entry.physical_offset))); result->offset_out_of_range++; result->errors++; } /* A written entry always carries generation >= 1. */ if (gen == 0) { ereport(DEBUG1, (errmsg("CFS: fsck: journal record for block %u has zero generation", je->blocknum))); result->generation_violations++; result->errors++; } /* * Cap the per-block generation tracker. Once the hash holds * CFS_FSCK_GEN_TRACK_MAX unique blocks the monotonicity check is * skipped (HASH_ENTER and the comparison below), while the CRC/field * checks above and the gen == 0 check keep running. */ if (!result->generation_check_degraded && hash_get_num_entries(gen_tab) >= CFS_FSCK_GEN_TRACK_MAX) { ereport(DEBUG1, (errmsg("CFS: fsck: journal generation tracker hit its cap; monotonicity check degraded"))); result->generation_check_degraded = true; } if (!result->generation_check_degraded) { gent = hash_search(gen_tab, &je->blocknum, HASH_ENTER, &found); if (found && gen <= gent->generation) { ereport(DEBUG1, (errmsg("CFS: fsck: journal record for block %u has non-increasing generation (%u after %u)", je->blocknum, gen, gent->generation))); result->generation_violations++; } if (!found || gen > gent->generation) gent->generation = gen; } } } int cfs_fsck_journal_file(const char *journal_path, const CfsFsckOptions *opts, CfsFsckResult *result, CfsFsckCoverage *cov) { int fd; CfsJournalFileHeader hdr; ssize_t got; HASHCTL ctl; HTAB *gen_tab; off_t jrn_end; int rc; fd = cfs_fsck_open(journal_path); if (fd < 0) return cfs_fsck_missing(opts, result); got = cfs_fsck_pread(fd, &hdr, sizeof(hdr), 0); if (got < 0 || (size_t) got < sizeof(hdr)) { ereport(DEBUG1, (errmsg("CFS: fsck: journal file \"%s\" is truncated", journal_path))); result->truncated_records++; result->errors++; close(fd); return 1; } if (cfs_journal_header_validate(&hdr) != CFS_FORMAT_OK) { result->journal_header_ok = false; result->errors++; close(fd); return 1; } result->journal_header_ok = true; /* * The RESIZE chain starts from the map file's row count: replay sees the * snapshot first, then every record in order. The map scan has already * run when a collector is passed (cfs_fsck_relation() does that), so its * row count is the snapshot size. */ if (cov != NULL) cov->nblocks = result->map_entries; /* * Track the highest generation seen per block so that a non-increasing * UPDATE record is flagged. See CfsFsckResult.generation_violations for * why a regression is an anomaly and not a hard error. */ ctl.keysize = sizeof(uint32); ctl.entrysize = sizeof(CfsFsckGenEntry); ctl.hcxt = CurrentMemoryContext; gen_tab = hash_create("cfs fsck journal generations", 1024, &ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); /* * Walk the record stream through the shared scan engine (review rule 3: * no hand-written reader loops) with the census policy: every * structurally present record - valid or not - is reported through the * observers above, and the scan carries on past invalid records so all * damage is reported. A torn final record is the clean end for the * transport; fsck reports it below from the bytes the scan left behind. */ { CfsJournalScanPolicy policy; CfsJournalSink sink; CfsJournalScanResult scan; CfsFsckJournalCtx ctx; memset(&policy, 0, sizeof(policy)); policy.role = "fsck"; policy.continue_on_invalid = true; ctx.result = result; ctx.cov = cov; ctx.gen_tab = gen_tab; memset(&sink, 0, sizeof(sink)); sink.see_record = cfs_fsck_journal_record; sink.invalid_record = cfs_fsck_journal_invalid; sink.arg = &ctx; (void) cfs_journal_scan_fd(fd, journal_path, (off_t) CFS_JOURNAL_HEADER_SIZE, &policy, &sink, &scan); jrn_end = scan.stop_off; rc = (scan.reason == CFS_SCAN_STOP_IO_ERROR) ? CFS_STORAGE_ERROR : CFS_STORAGE_OK; } if (rc == CFS_STORAGE_ERROR) { /* The transport reported the failed pread already. */ result->truncated_records++; result->errors++; } else { /* * Bytes past the last full record: the torn crash artifact the * transport folds into a clean end. Reported, never fatal. */ off_t size = lseek(fd, 0, SEEK_END); if (size > jrn_end) { ereport(DEBUG1, (errmsg("CFS: fsck: journal file \"%s\" has a torn final record", journal_path))); result->torn_tails++; } } hash_destroy(gen_tab); close(fd); return (result->errors > 0) ? 1 : 0; } /* ---------------------------------------------------------------- * .cfp * ---------------------------------------------------------------- */ /* * Return true when the [off, seg_size) tail of a full segment is entirely * zero — the unwritten padding left when the append cursor rolled over to * the next segment boundary. */ static bool cfs_fsck_tail_is_zero(int fd, off_t off, uint64 gap) { char zero_buf[8192]; uint64 done = 0; while (done < gap) { size_t want = Min((uint64) sizeof(zero_buf), gap - done); ssize_t got = cfs_fsck_pread(fd, zero_buf, want, off + (off_t) done); size_t k; if (got < 0 || (size_t) got < want) return false; for (k = 0; k < want; k++) { if (zero_buf[k] != 0) return false; } done += want; } return true; } /* * Return true when 'len' bytes at 'buf' are all zero. Used to verify the * rollover padding directly from the chunk buffer when the tail is entirely * inside it, avoiding a separate pread(). */ static bool cfs_fsck_buf_is_zero(const char *buf, size_t len) { size_t i; for (i = 0; i < len; i++) { if (buf[i] != 0) return false; } return true; } int cfs_fsck_cfp_file(const char *cfp_path, const CfsFsckOptions *opts, CfsFsckResult *result) { uint32 segno; size_t chunk_bytes; char *chunk; if (opts != NULL && !opts->verify_block_headers) return 0; /* * The buffer is a multiple of the maximal record size, so a whole record * always fits; see the per-segment scan loop below. */ chunk_bytes = CFS_FSCK_CFP_CHUNK_RECORDS * CFS_RECORD_SIZE(CFS_BLCKSZ); chunk = palloc(chunk_bytes); /* * Walk the segment chain (".cfp", ".cfp.1", ...). Within a segment the * append-only record stream is scanned header by header: each record * starts with a CfsCompressedBlockHeader whose compressed_size tells us * where the next record begins. Only segment 0 carries the reserved * lead-in. */ for (segno = 0;; segno++) { char *seg_path = cfs_segment_path(cfp_path, segno); int fd; uint64 seg_size; off_t off; bool seg_full; off_t chunk_start = 0; size_t chunk_len = 0; bool chunk_loaded = false; fd = cfs_fsck_open(seg_path); if (fd < 0) { pfree(seg_path); if (segno == 0) { pfree(chunk); return cfs_fsck_missing(opts, result); } break; /* end of the segment chain */ } seg_size = cfs_file_size(seg_path); /* * The engine never writes a segment larger than CFS_SEGMENT_SIZE; an * oversized one is corruption, and walking further is unsafe. */ if (seg_size > CFS_SEGMENT_SIZE) { ereport(DEBUG1, (errmsg("CFS: fsck: .cfp segment \"%s\" is larger than CFS_SEGMENT_SIZE", seg_path))); result->offset_out_of_range++; result->errors++; close(fd); pfree(seg_path); break; } seg_full = (seg_size == CFS_SEGMENT_SIZE); off = (segno == 0) ? (off_t) CFS_CFP_BASE_OFFSET : 0; while ((uint64) off + CFS_BLOCK_HEADER_SIZE <= seg_size) { CfsCompressedBlockHeader *bh; size_t rec_size; CfsFormatStatus bhst; /* * Refill the chunk when the header at 'off' is not fully covered * by the buffered bytes. The loop guard guarantees at least a * full header remains, so 'want' never drops below * CFS_BLOCK_HEADER_SIZE. */ if (!chunk_loaded || (uint64) off + CFS_BLOCK_HEADER_SIZE > (uint64) chunk_start + chunk_len) { size_t want = Min(chunk_bytes, (size_t) (seg_size - (uint64) off)); ssize_t got = cfs_fsck_pread(fd, chunk, want, off); if (got < 0 || (size_t) got < CFS_BLOCK_HEADER_SIZE) { result->truncated_records++; result->errors++; break; } chunk_start = off; chunk_len = (size_t) got; chunk_loaded = true; } bh = (CfsCompressedBlockHeader *) (chunk + (size_t) (off - chunk_start)); bhst = cfs_block_header_validate(bh); if (bhst != CFS_FORMAT_OK) { /* * In a full segment an invalid header may simply be the zero * padding left when the append cursor rolled over to the next * boundary. Legitimate padding is shorter than one maximal * record and entirely zero. */ if (seg_full) { uint64 gap = CFS_SEGMENT_SIZE - (uint64) off; bool zero_tail = false; if (gap < CFS_RECORD_SIZE(CFS_BLCKSZ)) { if ((uint64) chunk_start + chunk_len >= seg_size) { const char *tail = chunk + (size_t) (off - chunk_start); zero_tail = cfs_fsck_buf_is_zero(tail, (size_t) gap); } else zero_tail = cfs_fsck_tail_is_zero(fd, off, gap); } if (zero_tail) { /* * Padding: the segment is done. Consume it so the * torn-header check below does not misfire on a gap * shorter than a block header. */ off = (off_t) seg_size; break; } } if (bhst == CFS_FORMAT_BAD_CRC) result->crc_failures++; else result->field_failures++; result->errors++; break; /* cannot trust compressed_size to advance */ } result->cfp_records++; rec_size = CFS_RECORD_SIZE(bh->compressed_size); if (rec_size == 0 || (uint64) off + rec_size > seg_size) { /* * The engine never writes a record crossing a segment * boundary (rollover) and never reads the bytes past the last * record; compaction reclaims that space. So a truncated * record at the end of a short last segment is a crash-torn * append, not corruption. A full segment or an existing next * segment means real corruption or truncation and stays a * hard error. */ if (rec_size != 0 && !seg_full) { /* * The chain is contiguous, so a missing next segment * means this is the last one. */ char *next = cfs_segment_path(cfp_path, segno + 1); struct stat st; bool next_exists = (stat(next, &st) == 0); pfree(next); if (!next_exists) { ereport(DEBUG1, (errmsg("CFS: fsck: .cfp file \"%s\" ends with a torn record (truncated at %llu)", seg_path, (unsigned long long) ((uint64) segno * CFS_SEGMENT_SIZE + off)))); result->torn_tails++; break; } } ereport(DEBUG1, (errmsg("CFS: fsck: .cfp record at offset %llu of \"%s\" runs past EOF", (unsigned long long) ((uint64) segno * CFS_SEGMENT_SIZE + off), seg_path))); result->truncated_records++; result->errors++; break; } off += rec_size; } /* * A partial header at the very end of a short segment is a torn * write, not corruption: the tail is never used by the engine and * does not interfere with reading; compaction will reclaim the space. * (Repair by truncation is done for the journal only.) */ if ((uint64) off < seg_size && (uint64) off + CFS_BLOCK_HEADER_SIZE > seg_size) { ereport(DEBUG1, (errmsg("CFS: fsck: .cfp file \"%s\" ends with a torn header", seg_path))); result->torn_tails++; } close(fd); pfree(seg_path); } pfree(chunk); return (result->errors > 0) ? 1 : 0; } /* * Deep-mode cross-check: for every live map entry, read the * CfsCompressedBlockHeader at the entry's physical offset and verify that the * record agrees with the map (algorithm, sizes). A live entry pointing at * zero padding, an inter-record gap, or the middle of a foreign record — or * whose header disagrees with the entry — is corruption that the independent * .cfsmap and .cfp scans cannot see. * * The map is re-read here in chunks (same streaming pattern as * cfs_fsck_map_file()): the map scan above does not keep the entries around, * and deep mode is not on the hot path. */ static void cfs_fsck_cross_check(const char *map_path, const char *cfp_path, const CfsFsckOptions *opts, CfsFsckResult *result, CfsFsckCoverage *cov) { int map_fd; uint64 nblocks; ssize_t got; CfsMapRangeIter it; uint64 blk; const CfsMapEntry *e; int cfp_fd = -1; uint32 cfp_segno = UINT32_MAX; /* no segment open yet */ bool check_fields = (opts != NULL && opts->check_fields); /* A missing/empty .cfp chain was already reported by the map scan. */ { uint64 chain_size = 0; if (!cfs_cfp_chain_stat(cfp_path, &chain_size, NULL) || chain_size == 0) return; } map_fd = cfs_fsck_open(map_path); if (map_fd < 0) return; /* The map scan already reported any prologue damage; nothing more. */ if (cfs_map_file_prologue_check(map_fd, &nblocks) != CFS_STORAGE_OK) { close(map_fd); return; } cfs_map_range_iter_init(&it, map_fd, nblocks); while (cfs_map_range_iter_next(&it, &blk, &e)) { CfsCompressedBlockHeader bh; uint32 segno; uint32 blocknum = (uint32) blk; /* * A row the journal heals is still corrupt on disk until the next * fold rewrites it, so it must not contribute to the cross-check * verdict either. */ if (cov != NULL && cfs_fsck_coverage_is_healed(cov, blocknum)) continue; if (!CFS_MAP_ENTRY_VALID(e)) continue; /* An invalid entry was already reported by the map scan. */ if (cfs_map_entry_validate(e, check_fields) != CFS_FORMAT_OK) continue; /* Open the referenced segment once, switching on demand. */ segno = CFS_CFP_SEGNO(e->physical_offset); if (segno != cfp_segno) { char *seg_path = cfs_segment_path(cfp_path, segno); if (cfp_fd >= 0) close(cfp_fd); cfp_fd = cfs_fsck_open(seg_path); cfp_segno = segno; pfree(seg_path); } if (cfp_fd < 0) { ereport(DEBUG1, (errmsg("CFS: fsck: map entry %llu references a missing .cfp segment %u", (unsigned long long) blk, segno))); result->cross_check_failures++; result->errors++; continue; } got = cfs_fsck_pread(cfp_fd, &bh, sizeof(bh), CFS_CFP_SEG_OFF(e->physical_offset)); if (got < 0 || (size_t) got < sizeof(bh) || cfs_block_header_validate(&bh) != CFS_FORMAT_OK || bh.compressed_size != e->compressed_size) { ereport(DEBUG1, (errmsg("CFS: fsck: map entry %llu disagrees with the .cfp record header at offset %llu", (unsigned long long) blk, (unsigned long long) e->physical_offset))); result->cross_check_failures++; result->errors++; continue; } /* * The map no longer duplicates the algorithm (the record header is * the single source of truth), so count RAW entries here, where the * header is at hand. */ if (bh.algorithm == CFS_ALGORITHM_RAW) result->raw_entries++; } cfs_map_range_iter_free(&it); if (cfp_fd >= 0) close(cfp_fd); close(map_fd); } /* ---------------------------------------------------------------- * Relation-level convenience wrapper * ---------------------------------------------------------------- */ int cfs_fsck_relation(RelFileLocatorBackend rlocator, ForkNumber forknum, const CfsFsckOptions *opts, CfsFsckResult *result) { char *cfp_path; char *map_path; char *jrn_path; CfsFsckCoverage *cov; if (opts == NULL) { static const CfsFsckOptions default_opts = CFS_FSCK_OPTIONS_DEFAULT; opts = &default_opts; } if (!cfs_locator_supported(rlocator)) { /* Temporary relations have no CFS sidecar files. */ return 0; } cfp_path = cfs_make_filename(rlocator, forknum, CFS_FILE_DATA); map_path = cfs_make_filename(rlocator, forknum, CFS_FILE_MAP); jrn_path = cfs_make_filename(rlocator, forknum, CFS_FILE_JOURNAL); ereport(DEBUG1, (errmsg("CFS: fsck relation (%u/%u/%u): map=\"%s\", cfp=\"%s\", jrn=\"%s\"", rlocator.locator.spcOid, rlocator.locator.dbOid, rlocator.locator.relNumber, map_path ? map_path : "(none)", cfp_path ? cfp_path : "(none)", jrn_path ? jrn_path : "(none)"))); /* * The scan reads a file set that several rewriters touch: the phase-2 * journal reset (header rewrite + truncate) and every compaction swap and * TRUNCATE hold the append lock exclusively, so taking it shared makes * those steps invisible to the scan - without it a half-renamed sidecar * pair reads as corruption it is not. * * Deliberate cost: the shared lock is held for the WHOLE scan, so writers * of this relation wait for the complete walk (potentially minutes on a * large relation). Splitting the scan into short lock windows was * considered and rejected for now: it would need inode/size revalidation * after every window for no correctness gain. The lock also does not * cover the checkpoint's per-row map pwrites (phase 1 is lock-free); a * row caught mid-pwrite is healed by the journal record that covers it, * exactly like a live reader sees it. * * The fold's per-row map pwrites (phase 1) deliberately run lock-free, so * a row caught mid-pwrite stays corrupt on disk until the next fold. The * coverage collected below is what keeps that artifact from being * reported as damage: the journal record covering the block is still * there (the reset happens only after the map fsync). * * The append lock lives in the relation's metadata slot, which a relation * nobody has open does not have - but then no rewriter exists either. Pin * the slot (creating it when absent, exactly like an opener would) so the * lock is always available; fsck takes no other CFS lock, so the append → * partition lock order is respected. An ereport inside the scans must * not leak the pin or the lock: release both on success and ERROR. */ cov = palloc0(sizeof(*cov)); cfs_map_cache_pin(rlocator, forknum); PG_TRY(); { cfs_append_lock_acquire(rlocator, forknum, LW_SHARED); /* * The map scan only collects corrupt rows: the journal scan that * follows decides which of them are healed, and only then are the * remaining rows counted as damage. */ cfs_fsck_coverage_init(cov); cfs_fsck_map_file(map_path, cfp_path, opts, result, cov); cfs_fsck_journal_file(jrn_path, opts, result, cov); cfs_fsck_coverage_resolve(cov, result); cfs_fsck_cfp_file(cfp_path, opts, result); /* * Deep mode additionally cross-checks each live map entry against * .cfp. */ if (opts->verify_block_headers) cfs_fsck_cross_check(map_path, cfp_path, opts, result, cov); } PG_CATCH(); { cfs_append_lock_release_after_error(rlocator, forknum); cfs_map_cache_unpin(rlocator, forknum); cfs_fsck_coverage_free(cov); pfree(cov); PG_RE_THROW(); } PG_END_TRY(); cfs_append_lock_release(rlocator, forknum); cfs_map_cache_unpin(rlocator, forknum); cfs_fsck_coverage_free(cov); pfree(cov); pfree(cfp_path); pfree(map_path); pfree(jrn_path); return (result->errors > 0) ? 1 : 0; }