/*------------------------------------------------------------------------- * cfs_cfp.c * Compressed File Store (CFS) — the segmented .cfp data chain, one * module. * * Implements cfs_cfp.h: segment path building, the sidecar opener, the * append-segment switch, the global append EOF discovery, the read * cache, the stat walk and the per-segment fsync. Page-level readers * and writers build on these primitives from cfs_storage.c. * * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group * * IDENTIFICATION * src/backend/storage/cfs/cfs_cfp.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include #include #include "storage/aio.h" #include "storage/cfs/cfs.h" #include "storage/cfs/cfs_cfp.h" #include "storage/cfs/cfs_storage.h" #include "storage/cfs/cfs_guc.h" #include "storage/fd.h" #include "utils/palloc.h" #include "utils/wait_event.h" /* * cfs_cfp_close_fd — close a descriptor cached in a CfsRelation (.cfp * reader/writer caches). Since the P4-2 read offload, such a descriptor * may also sit in a staged or in-flight AIO handle (op_data.read.fd), so * the vanilla fd-close discipline applies: submit everything staged with * this fd (and let the method wait for in-flight users when it asks for * it), exactly what FileClose() does for vfd descriptors (fd.c). A raw * close(2) could otherwise recycle the number while an IO still names * it, and a backend-side synchronous execution would read through the * recycled descriptor into unrelated bytes. No-op for descriptors that * never reached an IO. */ void cfs_cfp_close_fd(int fd) { pgaio_closing_fd(fd); close(fd); } /* Build the path of .cfp segment 'segno' for an open handle. */ static char * cfs_cfp_segment_path(const CfsRelation *cfs, uint32 segno) { return cfs_segment_path(cfs->cfp_path, segno); } int cfs_open_sidecar(const char *path, int flags, bool create) { int oflags = PG_BINARY; int fd; if (flags & CFS_OPEN_RDONLY) oflags |= O_RDONLY; else oflags |= O_RDWR; if (create) oflags |= O_CREAT; fd = BasicOpenFile(path, oflags); if (fd < 0 && !(create && errno == EEXIST)) { ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not open sidecar file \"%s\": %m", path))); return -1; } return fd; } char * cfs_segment_path(const char *base_path, uint32 segno) { if (segno == 0) return pstrdup(base_path); return psprintf("%s.%u", base_path, segno); } char * cfs_segment_suffixed(const char *base_path, uint32 segno, const char *suffix) { if (segno == 0) return psprintf("%s%s", base_path, suffix); return psprintf("%s.%u%s", base_path, segno, suffix); } /* * Open (and optionally create) .cfp segment 'segno' of an open handle. * Returns the fd, -1 when the segment does not exist and 'create' is * false, or -2 on a hard error (the segment may exist but cannot be * stat'ed or opened). Callers walking the segment chain must treat -2 * as fatal: mistaking it for the end of the chain truncates the append * EOF and lets a later append overwrite live records. */ static int cfs_cfp_open_segment(const CfsRelation *cfs, uint32 segno, bool create) { char *path = cfs_cfp_segment_path(cfs, segno); int fd; struct stat st; if (!create && stat(path, &st) != 0) { if (errno == ENOENT) { pfree(path); return -1; } ereport(WARNING, (errcode_for_file_access(), errmsg("CFS: could not stat .cfp segment \"%s\": %m", path))); pfree(path); return -2; } fd = cfs_open_sidecar(path, cfs->flags, create); pfree(path); if (fd < 0) return -2; /* cfs_open_sidecar already warned */ return fd; } /* * Switch the append descriptor of 'cfs' to segment 'segno', creating the * segment when the handle is writable. The previous append segment is * closed; its durability is covered by the per-segment fsync loop in * cfs_fsync_kind() and by the checkpointer sync handler, both of which * walk the segment chain by path. */ int cfs_cfp_switch_append_segment(CfsRelation *cfs, uint32 segno) { char *path; int fd; struct stat st; bool existed; Assert(!cfs->read_only); path = cfs_cfp_segment_path(cfs, segno); existed = (stat(path, &st) == 0); fd = cfs_cfp_open_segment(cfs, segno, true); if (fd < 0) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not open .cfp segment \"%s\"", path))); if (cfs->cfp_fd >= 0) cfs_cfp_close_fd(cfs->cfp_fd); cfs->cfp_fd = fd; cfs->cfp_append_segno = segno; /* * A freshly created segment gets no WAL record (unlike the base sidecars, * which the XLOG_SMGR_CFS_POLICY redo recreates), so make its directory * entry durable right away: a crash that loses the dirent while the * journal record survives would leave map entries pointing at a segment * that does not exist. */ if (!existed) cfs_fsync_parent_dir(path, WARNING); pfree(path); ereport(DEBUG1, (errmsg("CFS: switched .cfp append segment to %u for relation %u/%u/%u", segno, cfs->rlocator.locator.spcOid, cfs->rlocator.locator.dbOid, cfs->rlocator.locator.relNumber))); return CFS_STORAGE_OK; } /* * Discover the append EOF of the segmented .cfp chain: walk forward from * the current append segment to the last existing one and return the * global EOF offset. A non-final segment may be SHORT — its rollover * padding was never written — so "size < CFS_SEGMENT_SIZE" does NOT * terminate the chain; only a missing next segment does. When the last * segment is exactly full, the EOF lands on the next boundary and the * first append creates that segment. */ off_t cfs_cfp_discover_eof(CfsRelation *cfs) { uint32 segno = cfs->cfp_append_segno; int fd = cfs->cfp_fd; off_t sz = cfs_fd_size(fd); for (;;) { int next_fd; /* * The engine never writes a segment larger than CFS_SEGMENT_SIZE, so * an oversized one can only come from outside interference with the * data directory. */ if (sz > (off_t) CFS_SEGMENT_SIZE) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg("CFS: .cfp segment %u of relation %u/%u/%u is larger than the segment size", segno, cfs->rlocator.locator.spcOid, cfs->rlocator.locator.dbOid, cfs->rlocator.locator.relNumber))); /* * Fast path: while the last segment still has room for one more * maximal record, no peer append can have rolled into a new segment, * so the next-segment probe can be skipped. (This also keeps the * common single-segment case at one fstat per append, same as before * segmentation.) */ if (sz <= (off_t) (CFS_SEGMENT_SIZE - CFS_RECORD_SIZE(CFS_BLCKSZ))) break; next_fd = cfs_cfp_open_segment(cfs, segno + 1, false); if (next_fd == -2) ereport(ERROR, (errcode_for_file_access(), errmsg("CFS: could not open .cfp segment %u of relation %u/%u/%u", segno + 1, cfs->rlocator.locator.spcOid, cfs->rlocator.locator.dbOid, cfs->rlocator.locator.relNumber))); if (next_fd < 0) break; /* end of the chain */ if (fd >= 0) cfs_cfp_close_fd(fd); fd = next_fd; segno++; /* * Keep the handle's descriptor fields in sync with the walk: an ERROR * raised by the probes above (oversized segment, or a hard open error * on the next iteration) must not leave cfs->cfp_fd holding a * descriptor this loop has already closed. The OS is free to recycle * the numeric value for an unrelated file, and a later append through * the handle would then write into that file. */ cfs->cfp_fd = fd; cfs->cfp_append_segno = segno; sz = cfs_fd_size(fd); } return (off_t) ((uint64) segno * CFS_SEGMENT_SIZE) + sz; } int cfs_cfp_read_segment_fd(CfsRelation *cfs, uint32 segno) { if (cfs->cfp_fd >= 0 && cfs->cfp_append_segno == segno) return cfs->cfp_fd; if (cfs->cfp_read_fd >= 0 && cfs->cfp_read_segno == segno) return cfs->cfp_read_fd; if (cfs->cfp_read_fd >= 0) cfs_cfp_close_fd(cfs->cfp_read_fd); cfs->cfp_read_fd = cfs_cfp_open_segment(cfs, segno, false); cfs->cfp_read_segno = segno; /* * ponytail: a single cached read descriptor; reads that alternate between * two segments reopen on every switch. Upgrade path: a small LRU of * segment descriptors. */ return cfs->cfp_read_fd; } void cfs_fsync_parent_dir(const char *path, int elevel) { char *dname = pstrdup(path); char *slash = strrchr(dname, '/'); if (slash != NULL) { if (slash == dname) slash[1] = '\0'; /* keep the root "/" */ else *slash = '\0'; (void) fsync_fname_ext(dname, true, false, elevel); } pfree(dname); } /* * Stat-walk the segmented .cfp chain rooted at 'cfp_path'. Sets * *total_size to the global EOF (segno_last * CFS_SEGMENT_SIZE + size of * the last segment) and *closed_padding to the bytes the CLOSED segments * never received: a record never crosses a segment boundary, so a * non-final segment simply ends short of CFS_SEGMENT_SIZE, and that * unwritten tail is structural padding - neither live data nor dead * (compaction cannot reclaim it), which the checkpoint's dead-space * accounting must subtract. Either out pointer may be * NULL. Returns false when the chain holds no readable segment. */ bool cfs_cfp_chain_stat(const char *cfp_path, uint64 *total_size, uint64 *closed_padding) { uint64 total = 0; uint64 padding = 0; uint64 prev_size = 0; bool any = false; uint32 segno; /* A NULL path is "no chain at all", like a missing base segment. */ if (cfp_path == NULL) { if (total_size != NULL) *total_size = 0; if (closed_padding != NULL) *closed_padding = 0; return false; } for (segno = 0;; segno++) { char *seg_path = cfs_segment_path(cfp_path, segno); struct stat st; uint64 size; if (stat(seg_path, &st) != 0 || st.st_size < 0) { pfree(seg_path); break; } any = true; /* * The engine never writes past the boundary; clamp defensively so an * oversized segment (outside interference) cannot wrap the unsigned * arithmetic below. */ size = (uint64) Min(st.st_size, (off_t) CFS_SEGMENT_SIZE); /* * The existence of THIS segment closes the previous one: its * unwritten tail is padding. The LAST segment (the one the loop ends * on) is still growing - including when it is exactly full (total % * SEG == 0: the next segment appears lazily on the next append) - and * contributes no padding. */ if (segno > 0) padding += (uint64) CFS_SEGMENT_SIZE - prev_size; prev_size = size; total = (uint64) segno * CFS_SEGMENT_SIZE + size; pfree(seg_path); } if (!any) return false; if (total_size != NULL) *total_size = total; if (closed_padding != NULL) *closed_padding = padding; return true; } /* * fsync every existing .cfp segment of the handle. The per-relation * append descriptor covers only the current append segment, and other * backends may have written earlier segments through their own handles, * so durability is arranged by walking the segment chain by path. */ int cfs_fsync_cfp_segments(CfsRelation *cfs) { uint32 segno; for (segno = 0;; segno++) { char *path; int fd; bool close_needed = false; int status; int save_errno; /* * Reuse the already-open append descriptor for its segment (the * common single-segment case then costs no extra open/close). */ path = cfs_cfp_segment_path(cfs, segno); if (segno == cfs->cfp_append_segno && cfs->cfp_fd >= 0) { fd = cfs->cfp_fd; } else { fd = BasicOpenFile(path, O_RDWR | PG_BINARY); if (fd < 0) { save_errno = errno; pfree(path); if (save_errno == ENOENT && segno > 0) break; /* end of the segment chain */ errno = save_errno; ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: could not open .cfp segment %u of \"%s\" for fsync: %m", segno, cfs->cfp_path))); return CFS_STORAGE_ERROR; } close_needed = true; } pgstat_report_wait_start(WAIT_EVENT_CFS_FSYNC); /* * Honor the cfs_debug_fail_fsync fault injection exactly like * cfs_fsync_kind() does for the single-file kinds. */ if (cfs_debug_fail_fsync > 0) { cfs_debug_fail_fsync--; errno = EIO; status = -1; } else status = pg_fsync(fd); save_errno = errno; if (close_needed) close(fd); pgstat_report_wait_end(); if (status != 0) { errno = save_errno; ereport(data_sync_elevel(ERROR), (errcode_for_file_access(), errmsg("CFS: fsync of %s failed: %m", path))); pfree(path); return CFS_STORAGE_ERROR; } pfree(path); } return CFS_STORAGE_OK; }