/*-------------------------------------------------------------------------
|
* cfs_journal.c
|
* Compressed File Store (CFS) — the .cfsjrn journal, one module.
|
*
|
* The journal-side primitives every consumer shares: the chunked record
|
* reader, the header reads (strict and lenient), the reset (the single
|
* home of the durability sequence header -> truncate -> fsync) and the
|
* torn-record tail classification. The append path and the replay/fold
|
* engines stay in cfs_storage.c: they are write-path state machines, not
|
* journal-file primitives.
|
*
|
* Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
|
*
|
* IDENTIFICATION
|
* src/backend/storage/cfs/cfs_journal.c
|
*
|
*-------------------------------------------------------------------------
|
*/
|
#include "postgres.h"
|
|
#include "access/xlogutils.h"
|
#include "utils/injection_point.h"
|
|
#include <sys/stat.h>
|
#include <unistd.h>
|
|
#include "storage/cfs/cfs_cfp.h"
|
#include "storage/cfs/cfs_format.h"
|
#include "storage/cfs/cfs_guc.h"
|
#include "storage/cfs/cfs_journal.h"
|
#include "storage/cfs/cfs_path.h"
|
#include "storage/cfs/cfs_recovery.h"
|
#include "storage/cfs/cfs_storage.h"
|
#include "storage/fd.h"
|
#include "utils/palloc.h"
|
#include "utils/wait_event.h"
|
|
void
|
cfs_journal_reader_init(CfsJournalReader *r, int fd, off_t start_off)
|
{
|
r->fd = fd;
|
r->off = start_off;
|
r->buf = palloc(CFS_JOURNAL_READ_CHUNK);
|
r->buflen = 0;
|
r->bufpos = 0;
|
r->rc = CFS_STORAGE_OK;
|
r->fail_next_read = false;
|
}
|
|
void
|
cfs_journal_reader_free(CfsJournalReader *r)
|
{
|
pfree(r->buf);
|
}
|
|
/*
|
* Fetch the next full journal record into *je. Returns false at the
|
* clean end of records (rc == NOENT) or after an I/O error (rc ==
|
* ERROR); the caller checks r->rc to tell them apart.
|
*/
|
bool
|
cfs_journal_reader_next(CfsJournalReader *r, CfsJournalEntry *je)
|
{
|
if (r->bufpos + CFS_JOURNAL_ENTRY_SIZE <= r->buflen)
|
{
|
memcpy(je, r->buf + r->bufpos, CFS_JOURNAL_ENTRY_SIZE);
|
r->bufpos += CFS_JOURNAL_ENTRY_SIZE;
|
r->rec_off = r->off;
|
r->off += CFS_JOURNAL_ENTRY_SIZE;
|
return true;
|
}
|
|
if (r->rc != CFS_STORAGE_OK)
|
return false;
|
|
{
|
size_t done = 0;
|
|
while (done < CFS_JOURNAL_READ_CHUNK)
|
{
|
ssize_t n;
|
size_t len = CFS_JOURNAL_READ_CHUNK - done;
|
|
if (r->fail_next_read)
|
{
|
r->fail_next_read = false;
|
errno = EIO;
|
n = -1;
|
}
|
else
|
n = pg_pread(r->fd, r->buf + done, len, r->off + done);
|
if (n < 0)
|
{
|
if (errno == EINTR)
|
continue;
|
ereport(WARNING,
|
(errcode_for_file_access(),
|
errmsg("CFS: pread failed: %m")));
|
r->rc = CFS_STORAGE_ERROR;
|
return false;
|
}
|
if (n == 0)
|
break;
|
done += n;
|
}
|
|
r->buflen = done;
|
r->bufpos = 0;
|
|
/* A partial trailing record is the clean end (see above). */
|
if (done < CFS_JOURNAL_ENTRY_SIZE)
|
{
|
r->rc = CFS_STORAGE_NOENT;
|
return false;
|
}
|
}
|
|
return cfs_journal_reader_next(r, je);
|
}
|
|
bool
|
cfs_journal_read_header(int fd, CfsJournalFileHeader *out)
|
{
|
if (cfs_pread_all(fd, out, sizeof(*out), 0) != CFS_STORAGE_OK)
|
return false;
|
return cfs_journal_header_validate(out) == CFS_FORMAT_OK;
|
}
|
|
bool
|
cfs_journal_read_header_fields(int fd, CfsJournalFileHeader *out)
|
{
|
if (cfs_pread_all(fd, out, sizeof(*out), 0) != CFS_STORAGE_OK)
|
return false;
|
return out->magic == CFS_JRN_MAGIC && out->version == CFS_JRN_VERSION;
|
}
|
|
void
|
cfs_journal_header_init_bumped(int fd, CfsJournalFileHeader *jhdr,
|
uint32 max_generation)
|
{
|
CfsJournalFileHeader old_jhdr;
|
|
cfs_journal_header_init(jhdr);
|
if (cfs_journal_read_header_fields(fd, &old_jhdr))
|
{
|
jhdr->incarnation = old_jhdr.incarnation + 1;
|
if (old_jhdr.max_generation > max_generation)
|
max_generation = old_jhdr.max_generation;
|
}
|
jhdr->max_generation = max_generation;
|
cfs_journal_header_set_crc(jhdr);
|
}
|
|
void
|
cfs_journal_finish_reset(int fd, const char *jrn_path,
|
CfsJournalFileHeader *jhdr,
|
off_t end_off, int elevel)
|
{
|
/*
|
* Every step of the reset tail respects 'elevel': the whole sequence is
|
* idempotent (a crash mid-way repeats it on the next pass), so a soft
|
* elevel (recovery's WARNING) applies uniformly - not just to the
|
* truncate, which used to be the only step that honoured it.
|
*/
|
if (cfs_pwrite_all(fd, jhdr, sizeof(*jhdr), 0) != CFS_STORAGE_OK)
|
ereport(elevel,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not rewrite journal header of \"%s\"",
|
jrn_path)));
|
|
{
|
bool truncate_failed;
|
|
if (cfs_debug_fail_truncate > 0)
|
{
|
cfs_debug_fail_truncate--;
|
errno = EIO;
|
truncate_failed = true;
|
}
|
else
|
truncate_failed = (pg_truncate(jrn_path, end_off) != 0);
|
|
if (truncate_failed)
|
ereport(elevel,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not truncate journal \"%s\": %m",
|
jrn_path)));
|
}
|
|
pgstat_report_wait_start(WAIT_EVENT_CFS_FSYNC);
|
if (pg_fsync(fd) != 0)
|
{
|
pgstat_report_wait_end();
|
ereport(elevel,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not fsync journal \"%s\": %m",
|
jrn_path)));
|
}
|
pgstat_report_wait_end();
|
}
|
|
void
|
cfs_journal_reset_file(const char *jrn_path, uint32 max_generation)
|
{
|
CfsJournalFileHeader jhdr;
|
int fd;
|
|
fd = BasicOpenFile(jrn_path, O_CREAT | O_RDWR | PG_BINARY);
|
if (fd < 0)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not open journal \"%s\" for reset: %m",
|
jrn_path)));
|
|
/*
|
* Bump the incarnation so backends notice the reset even when the journal
|
* later grows back past their saved replay offset (ABA). An unreadable
|
* previous header starts the incarnation sequence over.
|
*/
|
cfs_journal_header_init_bumped(fd, &jhdr, max_generation);
|
|
/*
|
* Finish through the shared reset tail - the durability sequence (header,
|
* truncate, fsync) is the same one every reset point runs.
|
*/
|
cfs_journal_finish_reset(fd, jrn_path, &jhdr,
|
(off_t) CFS_JOURNAL_HEADER_SIZE, ERROR);
|
close(fd);
|
|
ereport(DEBUG1,
|
(errmsg("CFS: journal \"%s\" reset to bare header", jrn_path)));
|
}
|
|
/* The private handle-based reset tail (see cfs_journal_reset_point). */
|
static void cfs_journal_reset(struct CfsRelation *cfs, uint32 max_generation,
|
int elevel);
|
|
void
|
cfs_journal_reset_point(CfsRelation *cfs, uint32 watermark, int elevel)
|
{
|
/*
|
* The one reset entry point for every handle-based path (checkpoint,
|
* immedsync, recovery). The contract, fixed HERE:
|
*
|
* 1. the caller has already made the payload durable - the .cfsmap rows
|
* the fold wrote / the saved snapshot / the swapped-in pair - and fsynced
|
* the .cfp data the surviving journal records reference; 2. this helper
|
* then flushes the journal itself, so the boundary it stamps is durable
|
* before any reset can erase the records; 3. the watermark never
|
* regresses: header_init_bumped() takes the max over the passed value and
|
* the previous header, so every caller's source (fold maxima, map
|
* summary) meets the same single maximum.
|
*
|
* The caller must hold the relation's append lock. The one path that
|
* resets by path on files it no longer owns - compaction, after its swap
|
* - uses cfs_journal_reset_file() instead (the documented exception, see
|
* the CFS review rules (README.md, "Review rules")).
|
*/
|
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();
|
|
cfs_journal_reset(cfs, watermark, elevel);
|
}
|
|
/*
|
* The handle-based reset itself: private to this module so that
|
* cfs_journal_reset_point() (the durability contract) and
|
* cfs_journal_reset_file() (the compaction exception) are the only two
|
* ways a journal ever gets reset.
|
*/
|
static void
|
cfs_journal_reset(struct CfsRelation *cfs, uint32 max_generation, int elevel)
|
{
|
CfsJournalFileHeader jhdr;
|
|
Assert(cfs != NULL && !cfs->read_only);
|
|
if (cfs->jrn_fd < 0)
|
return;
|
|
cfs_journal_header_init_bumped(cfs->jrn_fd, &jhdr, max_generation);
|
cfs_journal_finish_reset(cfs->jrn_fd, cfs->jrn_path, &jhdr,
|
(off_t) CFS_JOURNAL_HEADER_SIZE, elevel);
|
|
cfs->jrn_write_off = (off_t) CFS_JOURNAL_HEADER_SIZE;
|
cfs->jrn_incarnation = jhdr.incarnation;
|
|
ereport(DEBUG1,
|
(errmsg("CFS: journal reset (incarnation %u)",
|
(unsigned) jhdr.incarnation)));
|
}
|
|
/*
|
* The torn-record classification of the scan engine: a torn record with
|
* nothing (but a partial of itself) behind it is the crash artifact - the
|
* tail; a torn record with whole records following it is corruption,
|
* because those records are the only durable trace of their changes.
|
* Reports ONCE, with the caller's role in the message.
|
*/
|
static bool
|
cfs_scan_torn_is_tail(CfsRelation *cfs, off_t rec_off, const char *role,
|
bool during_recovery)
|
{
|
off_t jrn_size = cfs_fd_size(cfs->jrn_fd);
|
bool is_tail;
|
|
/*
|
* Without the file size the tail question cannot be answered, and
|
* guessing "tail" would let a caller drop valid records behind the torn
|
* one. An I/O failure here is fatal, not a torn-tail verdict.
|
*/
|
if (jrn_size < 0)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not determine the journal size of \"%s\"",
|
cfs->jrn_path)));
|
|
is_tail = (jrn_size - rec_off <= (off_t) sizeof(CfsJournalEntry));
|
if (!is_tail)
|
{
|
if (cfs->strict)
|
cfs_report_corruption(cfs->rlocator, cfs->forknum,
|
InvalidBlockNumber,
|
psprintf("torn journal record at offset "
|
"%lld with %lld byte(s) of "
|
"records following it",
|
(long long) rec_off,
|
(long long) (jrn_size - rec_off)),
|
during_recovery);
|
ereport(WARNING,
|
(errcode(ERRCODE_DATA_CORRUPTED),
|
errmsg("CFS: stopping journal %s at offset %lld (torn record)",
|
role, (long long) rec_off)));
|
}
|
else
|
{
|
ereport(DEBUG1,
|
(errmsg("CFS: stopping journal %s at offset %lld (torn record)",
|
role, (long long) rec_off)));
|
}
|
|
return is_tail;
|
}
|
|
/*
|
* The size-only form of the classification, shared with the descriptor
|
* consumers that hold no handle (cfs_journal_scan_fd): the verdict is the
|
* same, but there is no strict-mode corruption report channel (and no
|
* applying consumer that would need one) - the message is the whole
|
* report.
|
*/
|
static bool
|
cfs_scan_torn_is_tail_fd(int jrn_fd, const char *jrn_path, off_t rec_off,
|
const char *role)
|
{
|
off_t jrn_size = cfs_fd_size(jrn_fd);
|
bool is_tail;
|
|
if (jrn_size < 0)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not determine the journal size of \"%s\"",
|
jrn_path)));
|
|
is_tail = (jrn_size - rec_off <= (off_t) sizeof(CfsJournalEntry));
|
ereport(is_tail ? DEBUG1 : WARNING,
|
(errcode(ERRCODE_DATA_CORRUPTED),
|
errmsg("CFS: stopping journal %s at offset %lld (torn record)",
|
role, (long long) rec_off)));
|
return is_tail;
|
}
|
|
/*
|
* The one journal scan loop (review I3), both entry points included:
|
* every consumer that walks the journal runs this core with its own
|
* policy and sink. 'cfs' non-NULL selects the applying form
|
* (cfs_journal_scan); NULL selects the descriptor form
|
* (cfs_journal_scan_fd), which only observes records through
|
* sink->see_record / sink->invalid_record and never applies them.
|
*/
|
static int64
|
cfs_journal_scan_core(int jrn_fd, const char *jrn_path, CfsRelation *cfs,
|
off_t start_off, const CfsJournalScanPolicy * policy,
|
CfsJournalSink *sink, CfsJournalScanResult * result)
|
{
|
CfsJournalReader jr;
|
CfsJournalEntry je;
|
int64 applied = 0;
|
int64 map_rows = 0;
|
|
memset(result, 0, sizeof(*result));
|
result->reason = CFS_SCAN_STOP_EOF;
|
result->stop_off = start_off;
|
|
if (start_off < (off_t) CFS_JOURNAL_HEADER_SIZE)
|
start_off = (off_t) CFS_JOURNAL_HEADER_SIZE;
|
|
pgstat_report_wait_start(WAIT_EVENT_CFS_JOURNAL_REPLAY);
|
cfs_journal_reader_init(&jr, jrn_fd, start_off);
|
if (policy->fail_next_read)
|
jr.fail_next_read = true;
|
|
while (cfs_journal_reader_next(&jr, &je))
|
{
|
CfsFormatStatus vst = cfs_journal_entry_validate(&je);
|
|
if (policy->limit > 0 &&
|
jr.rec_off + (off_t) sizeof(CfsJournalEntry) > policy->limit)
|
{
|
/*
|
* The fold boundary: the caller sampled the limit BEFORE its .cfp
|
* fsync, so every record below it references data that fsync
|
* flushed; a record at/after it stays in the tail.
|
*/
|
ereport(DEBUG1,
|
(errmsg("CFS: journal fold stopped at fold boundary %lld (record offset %lld)",
|
(long long) policy->limit,
|
(long long) jr.rec_off)));
|
result->reason = CFS_SCAN_STOP_BOUNDARY;
|
result->stop_off = Min(jr.rec_off, policy->limit);
|
break;
|
}
|
|
if (vst != CFS_FORMAT_OK)
|
{
|
if (policy->continue_on_invalid)
|
{
|
if (sink != NULL && sink->invalid_record != NULL)
|
sink->invalid_record(sink->arg, jr.rec_off, vst);
|
continue;
|
}
|
|
/*
|
* The soft stop: no classification, no size stat, no report - the
|
* aggregate consumer keeps whatever its sink raised so far and
|
* the next checkpoint recomputes the stamp. TORN_TAIL is the
|
* closest reason (the record is dead weight to this consumer),
|
* and an aggregate reads nothing but the IO_ERROR bit anyway.
|
*/
|
if (policy->soft_invalid_stop)
|
{
|
result->reason = CFS_SCAN_STOP_TORN_TAIL;
|
result->stop_off = jr.rec_off;
|
break;
|
}
|
|
result->reason =
|
cfs != NULL
|
? (cfs_scan_torn_is_tail(cfs, jr.rec_off, policy->role,
|
policy->during_recovery)
|
? CFS_SCAN_STOP_TORN_TAIL
|
: CFS_SCAN_STOP_TORN_MIDFILE)
|
: (cfs_scan_torn_is_tail_fd(jrn_fd, jrn_path, jr.rec_off,
|
policy->role)
|
? CFS_SCAN_STOP_TORN_TAIL
|
: CFS_SCAN_STOP_TORN_MIDFILE);
|
result->stop_off = jr.rec_off;
|
break;
|
}
|
|
if (sink != NULL && sink->see_record != NULL)
|
sink->see_record(sink->arg, &je);
|
if (cfs != NULL)
|
cfs_journal_apply_record(cfs, &je, sink);
|
applied++;
|
|
if (je.op != CFS_JRN_OP_RESIZE)
|
map_rows++;
|
if (policy->pause_after_first_row != NULL && map_rows == 1)
|
INJECTION_POINT(policy->pause_after_first_row, NULL);
|
}
|
|
if (jr.rc == CFS_STORAGE_ERROR)
|
result->reason = CFS_SCAN_STOP_IO_ERROR;
|
else if (result->reason == CFS_SCAN_STOP_EOF)
|
result->stop_off = jr.off;
|
|
cfs_journal_reader_free(&jr);
|
pgstat_report_wait_end();
|
|
result->applied = applied;
|
return applied;
|
}
|
|
int64
|
cfs_journal_scan(CfsRelation *cfs, off_t start_off,
|
const CfsJournalScanPolicy * policy,
|
CfsJournalSink *sink, CfsJournalScanResult * result)
|
{
|
return cfs_journal_scan_core(cfs->jrn_fd, cfs->jrn_path, cfs,
|
start_off, policy, sink, result);
|
}
|
|
int64
|
cfs_journal_scan_fd(int jrn_fd, const char *jrn_path, off_t start_off,
|
const CfsJournalScanPolicy * policy,
|
CfsJournalSink *sink, CfsJournalScanResult * result)
|
{
|
return cfs_journal_scan_core(jrn_fd, jrn_path, NULL,
|
start_off, policy, sink, result);
|
}
|
|
/* The max-generation aggregate: one observer, no application. */
|
static void
|
cfs_journal_max_generation_sink(void *arg, const CfsJournalEntry *je)
|
{
|
uint32 *max_gen = (uint32 *) arg;
|
|
if (je->op == CFS_JRN_OP_UPDATE &&
|
je->new_entry.generation > *max_gen)
|
*max_gen = je->new_entry.generation;
|
}
|
|
int
|
cfs_journal_fd_scan_max_generation(int jrn_fd, const char *jrn_path,
|
uint32 *max_gen)
|
{
|
CfsJournalScanPolicy policy;
|
CfsJournalSink sink;
|
CfsJournalScanResult result;
|
|
memset(&policy, 0, sizeof(policy));
|
policy.role = "seed";
|
policy.soft_invalid_stop = true;
|
memset(&sink, 0, sizeof(sink));
|
sink.see_record = cfs_journal_max_generation_sink;
|
sink.arg = max_gen;
|
|
(void) cfs_journal_scan_fd(jrn_fd, jrn_path,
|
(off_t) CFS_JOURNAL_HEADER_SIZE,
|
&policy, &sink, &result);
|
if (result.reason == CFS_SCAN_STOP_IO_ERROR)
|
return CFS_STORAGE_ERROR;
|
return CFS_STORAGE_OK;
|
}
|
|
/*
|
* The size observer of cfs_journal_measure_nblocks: remember only the
|
* last RESIZE target. Records arrive in journal order and a RESIZE
|
* record carries the absolute target nblocks (not a delta), so the last
|
* one seen is the last one on disk and simply overwrites whatever an
|
* earlier RESIZE set; UPDATE/DELETE records never change the size.
|
*/
|
typedef struct CfsJournalMeasureCtx
|
{
|
BlockNumber resize_target; /* last RESIZE target seen */
|
bool have_resize; /* a valid RESIZE record was seen */
|
} CfsJournalMeasureCtx;
|
|
static void
|
cfs_journal_measure_record(void *arg, const CfsJournalEntry *je)
|
{
|
CfsJournalMeasureCtx *ctx = (CfsJournalMeasureCtx *) arg;
|
|
if (je->op == CFS_JRN_OP_RESIZE)
|
{
|
ctx->resize_target = je->blocknum;
|
ctx->have_resize = true;
|
}
|
}
|
|
/*
|
* cfs_journal_measure_nblocks - measure the logical size of a CFS
|
* relation from the sidecar pair alone: the row count derived from the
|
* .cfsmap file size (the base every fold leaves behind) plus, when the
|
* journal holds any, the last valid RESIZE record's absolute target.
|
* Built for the smgrnblocks() cache-miss path (QDB-1516), which must
|
* stay O(journal) and never build a private full map here.
|
*
|
* Correctness: the .cfsmap file is resized only at fold points (the
|
* checkpoint and recovery folds, the compaction and immedsync swaps),
|
* all under the EXCLUSIVE append lock, and every size-changing writer
|
* journals a RESIZE under that same lock. The caller therefore holds
|
* the append lock (SHARED is enough): the stat and the scan observe one
|
* consistent map/journal pair, and no RESIZE can land between them.
|
*
|
* Damage policy, mirroring the non-recovery load (cfs_map_load /
|
* cfs_journal_replay): a missing journal or one shorter than its header
|
* is the legal fresh state (the base rows stand); a full-size header
|
* that fails validation is structural damage - during recovery a hard
|
* ERROR, outside recovery routed through cfs_report_corruption() so the
|
* cfs_checksum_failure GUC decides the severity (QDB-1507 U8, parity
|
* with the replay paths); a torn TAIL is the normal crash artifact (the
|
* scanner classifies it, and the RESIZEs before it stand); a torn record
|
* with valid records behind it is corruption - the RESIZEs past it are
|
* unreachable, so no size can be trusted. That outcome is REPORTED,
|
* not raised: the call answers CFS_JOURNAL_MEASURE_MIDFILE with the
|
* torn offset, and the caller escalates by its own context (a backend
|
* through cfs_report_corruption; the startup process with the recovery
|
* severity contract, which WARNINGs and falls back to the full-map
|
* measurement when non-strict).
|
*/
|
CfsJournalMeasureStatus
|
cfs_journal_measure_nblocks(RelFileLocatorBackend rl, ForkNumber forknum,
|
BlockNumber *nblocks, off_t *torn_off)
|
{
|
char *map_path;
|
char *jrn_path;
|
struct stat st;
|
uint64 base_rows;
|
int fd;
|
CfsJournalMeasureStatus status;
|
|
map_path = cfs_make_filename(rl, forknum, CFS_FILE_MAP);
|
jrn_path = cfs_make_filename(rl, forknum, CFS_FILE_JOURNAL);
|
Assert(map_path != NULL && jrn_path != NULL);
|
|
/*
|
* The base size: rows derived from the file size (a partial trailing
|
* row is a torn write every loader ignores). A missing map with the
|
* journal still present is a damaged sidecar set, not a vanished
|
* relation: the triple is materialized atomically and only a drop
|
* removes it, and the drop takes the whole triple - answering zero
|
* here (with WAL replay possibly overwriting live blocks from block
|
* 0, see the nblocks contract) would launder the damage, so raise
|
* exactly like the full-open path this measurement replaced. When
|
* the journal is gone too, the .cfp decides: a surviving data file
|
* with neither map nor journal is external damage (the drop removes
|
* the whole triple) and fails just as loudly; only all three gone
|
* is the drop or rewrite race that raced the caller's cfs_exists()
|
* check, and zero is the genuine answer.
|
*/
|
if (stat(map_path, &st) != 0)
|
{
|
if (errno == ENOENT)
|
{
|
struct stat jst;
|
char *cfp_path;
|
uint32 segno;
|
|
if (stat(jrn_path, &jst) == 0)
|
ereport(ERROR,
|
(errcode(ERRCODE_DATA_CORRUPTED),
|
errmsg("CFS: map file is missing for "
|
"relation %u/%u/%u",
|
rl.locator.spcOid, rl.locator.dbOid,
|
rl.locator.relNumber),
|
errdetail("Sidecar journal \"%s\" exists but "
|
"\"%s\" does not.",
|
jrn_path, map_path)));
|
if (errno != ENOENT)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not stat journal file \"%s\": %m",
|
jrn_path)));
|
|
/*
|
* The journal is gone too, so the pair may be mid-drop - but
|
* only the whole triple disappears at once, and the .cfp is
|
* the witness that decides: a surviving data file with
|
* neither map nor journal is external damage and must fail
|
* loudly exactly like the journal witness above; all three
|
* gone is the drop (or rewrite) race, and zero is the true
|
* answer. A surviving numbered segment (.cfp.1, .cfp.2,
|
* ...) is the same witness, so the walk below checks the
|
* whole chain.
|
*/
|
cfp_path = cfs_make_filename(rl, forknum, CFS_FILE_DATA);
|
if (stat(cfp_path, &jst) == 0)
|
ereport(ERROR,
|
(errcode(ERRCODE_DATA_CORRUPTED),
|
errmsg("CFS: map file is missing for "
|
"relation %u/%u/%u",
|
rl.locator.spcOid, rl.locator.dbOid,
|
rl.locator.relNumber),
|
errdetail("Sidecar data file \"%s\" exists but "
|
"neither \"%s\" nor \"%s\" does.",
|
cfp_path, map_path, jrn_path)));
|
if (errno != ENOENT)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not stat data file \"%s\": %m",
|
cfp_path)));
|
|
/*
|
* The data file is segmented (.cfp.1, .cfp.2, ... for large
|
* relations), so a missing base segment is not yet a missing
|
* data witness: walk the chain until the first hole. The
|
* chain is append-ordered and dense, so the first ENOENT ends
|
* it; any surviving segment is the same loud witness as the
|
* base file above.
|
*/
|
for (segno = 1;; segno++)
|
{
|
char *seg_path =
|
cfs_make_segment_filename(rl, forknum,
|
CFS_FILE_DATA, segno);
|
|
if (stat(seg_path, &jst) == 0)
|
ereport(ERROR,
|
(errcode(ERRCODE_DATA_CORRUPTED),
|
errmsg("CFS: map file is missing for "
|
"relation %u/%u/%u",
|
rl.locator.spcOid, rl.locator.dbOid,
|
rl.locator.relNumber),
|
errdetail("Sidecar data file \"%s\" exists "
|
"but neither \"%s\" nor \"%s\" "
|
"does.",
|
seg_path, map_path, jrn_path)));
|
if (errno != ENOENT)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not stat data file \"%s\": %m",
|
seg_path)));
|
pfree(seg_path);
|
break;
|
}
|
pfree(cfp_path);
|
pfree(map_path);
|
pfree(jrn_path);
|
*nblocks = 0;
|
return CFS_JOURNAL_MEASURE_OK;
|
}
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not stat map file \"%s\": %m",
|
map_path)));
|
}
|
base_rows = cfs_map_rows_from_size((uint64) st.st_size);
|
|
fd = OpenTransientFile(jrn_path, O_RDONLY | PG_BINARY);
|
if (fd < 0)
|
{
|
/*
|
* No journal at all: no RESIZE can exist past the fold, and the
|
* base rows are the whole answer.
|
*/
|
if (errno == ENOENT)
|
{
|
pfree(map_path);
|
pfree(jrn_path);
|
*nblocks = (BlockNumber) base_rows;
|
return CFS_JOURNAL_MEASURE_OK;
|
}
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not open journal \"%s\": %m", jrn_path)));
|
}
|
|
PG_TRY();
|
{
|
CfsJournalMeasureCtx ctx;
|
CfsJournalSink sink;
|
CfsJournalScanPolicy policy;
|
CfsJournalScanResult scan;
|
CfsJournalFileHeader jhdr;
|
int rc;
|
|
/*
|
* Header first, with the load path's exact policy: a short read is
|
* the legal fresh state (folded into NOENT below), while a
|
* full-size header that fails validation means the records cannot
|
* even be trusted to describe themselves.
|
*/
|
rc = cfs_pread_all(fd, &jhdr, sizeof(jhdr), 0);
|
if (rc == CFS_STORAGE_NOENT)
|
{
|
*nblocks = (BlockNumber) base_rows;
|
status = CFS_JOURNAL_MEASURE_OK;
|
}
|
else
|
{
|
if (rc != CFS_STORAGE_OK)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not read journal header of \"%s\": %m",
|
jrn_path)));
|
if (cfs_journal_header_validate(&jhdr) != CFS_FORMAT_OK)
|
{
|
/*
|
* A full-size header that fails validation is structural
|
* damage. Outside a normal backend session it stays a
|
* hard ERROR (parity with the full replay path); a normal
|
* backend routes it through cfs_report_corruption()
|
* (QDB-1507 U8), so the cfs_checksum_failure GUC decides
|
* ERROR or PANIC exactly like every other structural
|
* header site (cfs_corruption_guc_applies).
|
*/
|
if (!cfs_corruption_guc_applies())
|
ereport(ERROR,
|
(errcode(ERRCODE_DATA_CORRUPTED),
|
errmsg("CFS: corrupt page map journal"),
|
errdetail("Invalid .cfsjrn header in \"%s\".",
|
jrn_path)));
|
else
|
cfs_report_corruption(rl, forknum, InvalidBlockNumber,
|
psprintf("invalid .cfsjrn header "
|
"in file \"%s\"",
|
jrn_path),
|
false);
|
}
|
|
ctx.resize_target = 0;
|
ctx.have_resize = false;
|
|
memset(&sink, 0, sizeof(sink));
|
sink.see_record = cfs_journal_measure_record;
|
sink.arg = &ctx;
|
|
memset(&policy, 0, sizeof(policy));
|
policy.role = "nblocks";
|
|
(void) cfs_journal_scan_fd(fd, jrn_path,
|
(off_t) CFS_JOURNAL_HEADER_SIZE,
|
&policy, &sink, &scan);
|
|
/* The transport already logged the failed pread with its errno. */
|
if (scan.reason == CFS_SCAN_STOP_IO_ERROR)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not read journal \"%s\" to "
|
"measure the relation size",
|
jrn_path)));
|
|
/*
|
* Mid-file damage: never answer a size here - the unreachable
|
* records behind the torn one may hold the real last RESIZE.
|
* Hand the torn offset back; the caller owns the severity
|
* decision (its context decides, not this file).
|
*/
|
if (scan.reason == CFS_SCAN_STOP_TORN_MIDFILE)
|
{
|
*torn_off = scan.stop_off;
|
status = CFS_JOURNAL_MEASURE_MIDFILE;
|
}
|
else
|
{
|
*nblocks = ctx.have_resize ? ctx.resize_target :
|
(BlockNumber) base_rows;
|
status = (scan.reason == CFS_SCAN_STOP_TORN_TAIL)
|
? CFS_JOURNAL_MEASURE_TORN_TAIL
|
: CFS_JOURNAL_MEASURE_OK;
|
}
|
}
|
}
|
PG_CATCH();
|
{
|
CloseTransientFile(fd);
|
PG_RE_THROW();
|
}
|
PG_END_TRY();
|
|
CloseTransientFile(fd);
|
pfree(map_path);
|
pfree(jrn_path);
|
|
return status;
|
}
|
|
/*
|
* The one documented exception to the "no race checks outside cfs_state.c"
|
* rule (README.md, "Review rules"): the size signal below is fetched
|
* directly because the caller needs the byte count, and re-reading one
|
* record past the torn offset is record CONTENT, not pair identity.
|
* Everything else about staleness here is derived by the judge.
|
*/
|
bool
|
cfs_journal_tail_changed(CfsRelation *cfs, off_t rec_off)
|
{
|
CfsJournalEntry rec;
|
off_t jrn_size = cfs_fd_size(cfs->jrn_fd);
|
ssize_t n;
|
|
if (jrn_size < 0)
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("CFS: could not determine the journal size of \"%s\"",
|
cfs->jrn_path)));
|
|
/* Any bytes behind the torn record are a change phase 1 never saw. */
|
if (jrn_size - rec_off > (off_t) sizeof(rec))
|
return true;
|
|
/* A record that validates now was completed by a writer meanwhile. */
|
do
|
{
|
n = pg_pread(cfs->jrn_fd, &rec, sizeof(rec), rec_off);
|
} while (n < 0 && errno == EINTR);
|
|
return (n == (ssize_t) sizeof(rec) &&
|
cfs_journal_entry_validate(&rec) == CFS_FORMAT_OK);
|
}
|
|
/*
|
* Verify that the .cfp record an UPDATE journal record references is on
|
* disk and structurally intact.
|
*/
|
static bool
|
cfs_journal_update_data_durable(CfsRelation *cfs, const CfsJournalEntry *je)
|
{
|
CfsCompressedBlockHeader bh;
|
off_t offset = (off_t) je->new_entry.physical_offset;
|
int fd;
|
|
if (offset < (off_t) CFS_CFP_BASE_OFFSET)
|
return false;
|
|
fd = cfs_cfp_read_segment_fd(cfs, CFS_CFP_SEGNO(offset));
|
if (fd < 0)
|
return false;
|
|
if (cfs_pread_all(fd, &bh, sizeof(bh),
|
CFS_CFP_SEG_OFF(offset)) != CFS_STORAGE_OK)
|
return false;
|
|
return cfs_block_header_validate(&bh) == CFS_FORMAT_OK;
|
}
|
|
/*
|
* Decide whether an UPDATE record's referenced .cfp data is trustworthy.
|
* The journal record can be durable while the data it points at never
|
* reached the disk (the kernel may write .cfsjrn pages ahead of .cfp).
|
* The replay skips such a record, and the checkpoint fold must apply the
|
* same policy: installing the row would freeze the missing data in the
|
* map and let the journal reset erase the only evidence. Reports through
|
* the same channel in every caller (WARNING in the normal mode, the
|
* centralised corruption handler in strict mode) and returns false when
|
* the record must be skipped.
|
*/
|
static bool
|
cfs_journal_update_data_usable(CfsRelation *cfs, const CfsJournalEntry *je,
|
bool during_recovery)
|
{
|
if (cfs_journal_update_data_durable(cfs, je))
|
return true;
|
|
if (cfs->strict)
|
cfs_report_corruption(cfs->rlocator, cfs->forknum, je->blocknum,
|
psprintf("journal UPDATE references missing "
|
".cfp data at offset %llu",
|
(unsigned long long) je->new_entry.physical_offset),
|
during_recovery);
|
ereport(WARNING,
|
(errcode(ERRCODE_DATA_CORRUPTED),
|
errmsg("CFS: skipping journal UPDATE for block %u: "
|
"no valid record at .cfp offset %llu",
|
je->blocknum,
|
(unsigned long long) je->new_entry.physical_offset)));
|
return false;
|
}
|
|
void
|
cfs_journal_apply_record(CfsRelation *cfs, const CfsJournalEntry *je,
|
CfsJournalSink *sink)
|
{
|
if (je->op == CFS_JRN_OP_UPDATE)
|
{
|
/*
|
* The generation must be considered occupied even when the record is
|
* later skipped for missing .cfp data: the write path must never
|
* reuse a value already present in the journal.
|
*/
|
if (je->new_entry.generation > sink->max_generation)
|
sink->max_generation = je->new_entry.generation;
|
if (sink->filter_range &&
|
(je->blocknum < sink->first_block ||
|
je->blocknum >= sink->last_block))
|
return;
|
if (sink->update_usable != NULL)
|
{
|
if (!sink->update_usable(sink->arg, je))
|
return;
|
}
|
else if (!cfs_journal_update_data_usable(cfs, je,
|
sink->recovery_severity))
|
return;
|
sink->write_row(sink->arg, je->blocknum, &je->new_entry);
|
}
|
else if (je->op == CFS_JRN_OP_DELETE)
|
{
|
if (sink->filter_range &&
|
(je->blocknum < sink->first_block ||
|
je->blocknum >= sink->last_block))
|
return;
|
{
|
CfsMapEntry row;
|
|
cfs_map_entry_init(&row);
|
sink->write_row(sink->arg, je->blocknum, &row);
|
}
|
}
|
else if (je->op == CFS_JRN_OP_RESIZE)
|
{
|
sink->resize_target = je->blocknum;
|
sink->have_resize = true;
|
if (sink->resize != NULL)
|
sink->resize(sink->arg, je->blocknum);
|
}
|
}
|
|
/*
|
* cfs_journal_identity()/cfs_journal_identity_equal() were absorbed by the
|
* ownership-state judge: the snapshot and the identity comparison now live
|
* in cfs_state.c (CfsStateSnapshot, CFS_STATE_JRN_IDENTITY_MOVED).
|
*/
|