pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
aio: Async fsyncs for crash recovery and checkpointer
9+ messages / 3 participants
[nested] [flat]

* aio: Async fsyncs for crash recovery and checkpointer
@ 2026-08-25 12:48  Nazir Bilal Yavuz <byavuz81@gmail.com>
  0 siblings, 1 reply; 9+ messages in thread

From: Nazir Bilal Yavuz @ 2026-08-25 12:48 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; +Cc: Andres Freund <andres@anarazel.de>

Hi,

This patch implements async fsyncs for crash recovery and checkpoints
by using the AIO system. I got the idea from Andres' older work [1].

----------

High level design and implementation details:

- Since there is no interface like read-stream for the fsyncs, each
user has its own AIO functions like register_one(), drain_one() and
drain_all().

- Number of in-flight I/Os are determined by
GetFsyncConcurrencyLimit(). It uses both io_max_concurrency and the
file descriptor budget to determine max number of available in-flight
fsync I/Os.

- I/O workers need re-open files to do async I/O. Some targets open
files by path (for example, SyncDataDirectory()). This path needs to
be copied to shared memory so that worker processes can re-open these
files. However, adding 'char path[MAXPGPATH]' to PgAioTargetData seems
overkill because of the size; so it is not implemented for now. I am
open to suggestions.

----------

Patches:

- 0001 is just a base patch for adding fsync support to the AIO
system. There is no user of this patch yet.

- 0002 makes SyncDataDirectory() use async fsyncs. Its files are
identified only by path; I/O workers cannot re-open them. So, this
path is asynchronous with io_uring, while worker behaves like sync.
pre_sync_fname() doesn't use AIO because it is already very fast, less
than 1/1000 of of datadir_fsync_fname() time in my benchmarks.

- 0003 makes ProcessSyncRequests() use async fsyncs. Its files use the
smgr target and can be re-opened by an I/O worker, so both worker and
io_uring can execute these fsyncs asynchronously.

- 0004 adds a FileTag-based target for SLRU files. This gives I/O
workers enough information to re-open SLRU segments, so they can use
async fsyncs in the worker mode.

- benchmark-repro.sh is a benchmark script that I used.

----------

Benchmark:

I used a simple benchmark script generated by an LLM. I checked the
script, and it works correctly. The numbers below use the default
settings + the following:

```
checkpoint_timeout = '1h'
max_wal_size = '32GB'
checkpoint_flush_after = 0
bgwriter_lru_maxpages = 0
autovacuum = off
```
io_min_workers, io_max_workers and io_max_concurrency are default in
[2]. They are changed to 8, 8, and 64, respectively, for the second
benchmark [3].

You can run the attached benchmark script by './benchmark-repro.sh
{--syncdatadirectory, --checkpointer, --slru}' command.

- SyncDataDirectory() synced a data directory containing 4000 small relations:

[2]
io_method  |         startup (ms) | speedup vs sync
-----------+----------------------+----------------
sync       |               1411.8 |           1.00x
worker     |               1210.6 |           1.17x
io_uring   |                310.3 |           4.55

[3]
io_method  |         startup (ms) | speedup vs sync
-----------+----------------------+----------------
sync       |               1310.6 |           1.00x
worker     |               1210.0 |           1.08x
io_uring   |                310.6 |           4.22x

- Checkpointer benchmark dirtied 4000 relation files before checkpoint:

[2]
io_method  |      checkpoint (ms) | speedup vs sync
-----------+----------------------+----------------
sync       |               1860.5 |           1.00x
worker     |                697.1 |           2.67x
io_uring   |                478.4 |           3.89x

[3]
io_method  |      checkpoint (ms) | speedup vs sync
-----------+----------------------+----------------
sync       |               1875.5 |           1.00x
worker     |                541.1 |           3.47x
io_uring   |                479.9 |           3.91x

- SLRU benchmark created 640000 transactions, producing ~30 files to sync:

[2]
io_method  | SLRU checkpoint (ms) | speedup vs sync
-----------+----------------------+----------------
sync       |                 94.1 |           1.00x
worker     |                 67.1 |           1.40x
io_uring   |                 57.1 |           1.65x

[3]
io_method  | SLRU checkpoint (ms) | speedup vs sync
-----------+----------------------+----------------
sync       |                 97.3 |           1.00x
worker     |                 48.7 |           2.00x
io_uring   |                 37.4 |           2.60x

Any feedback would be appreciated.

[1]
https://github.com/anarazel/postgres/commit/9829a1f18176e572759ecf8b8bb99205a71a476f
https://github.com/anarazel/postgres/commit/2e180547aef6fe2a409cc144e04cbc2f0a607bed

--
Regards,
Nazir Bilal Yavuz
Microsoft

Attachments: download all (5 files, .tar.gz)

v1-0001-aio-Add-fsync-support.patch (text/x-patch, 5.9K) download From d3197f4e6fb6a24d5ea35448b521edeca9717aeb Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Tue, 11 Aug 2026 10:40:14 +0300 Subject: [PATCH v1 1/4] aio: Add fsync support The AIO subsystem currently supports only reads and writes (writes are not used yet). Add PGAIO_OP_FSYNC so callers can submit fsync() and fdatasync() operations through AIO. This allows callers such as the checkpointer to keep multiple syncs in flight instead of waiting for each one in turn. Let callers select the wait event because fsync targets can represent different kinds of files. The process that performs the operation reports that event; io_uring uses the generic AIO wait events because the kernel performs the operation. (Also see [1]) No callers are converted in this commit; subsequent commits do that. [1] https://postgr.es/m/CAN55FZ0Rp+94rdQ-zeTX0sF9H1e4uWZxH8r1cVXZX0swfqww3g@mail.gmail.com --- src/backend/storage/aio/aio_funcs.c | 4 ++++ src/backend/storage/aio/aio_io.c | 27 +++++++++++++++++++++++ src/backend/storage/aio/method_io_uring.c | 6 +++++ src/backend/storage/smgr/smgr.c | 3 +++ src/include/storage/aio.h | 14 ++++++++++-- 5 files changed, 52 insertions(+), 2 deletions(-) diff --git a/src/backend/storage/aio/aio_funcs.c b/src/backend/storage/aio/aio_funcs.c index bcdd82318f7..2719556e858 100644 --- a/src/backend/storage/aio/aio_funcs.c +++ b/src/backend/storage/aio/aio_funcs.c @@ -191,6 +191,10 @@ retry: values[6] = Int64GetDatum(iov_byte_length(iov_copy, ioh_copy.op_data.write.iov_length)); break; + case PGAIO_OP_FSYNC: + nulls[5] = true; + nulls[6] = true; + break; } /* column: IO's target */ diff --git a/src/backend/storage/aio/aio_io.c b/src/backend/storage/aio/aio_io.c index 132868130e7..324fb6911e2 100644 --- a/src/backend/storage/aio/aio_io.c +++ b/src/backend/storage/aio/aio_io.c @@ -100,6 +100,19 @@ pgaio_io_start_writev(PgAioHandle *ioh, pgaio_io_stage(ioh, PGAIO_OP_WRITEV); } +void +pgaio_io_start_fsync(PgAioHandle *ioh, + int fd, bool datasync, uint32 wait_event_info) +{ + pgaio_io_before_start(ioh); + + ioh->op_data.fsync.fd = fd; + ioh->op_data.fsync.datasync = datasync; + ioh->op_data.fsync.wait_event_info = wait_event_info; + + pgaio_io_stage(ioh, PGAIO_OP_FSYNC); +} + /* -------------------------------------------------------------------------------- @@ -137,6 +150,14 @@ pgaio_io_perform_synchronously(PgAioHandle *ioh) ioh->op_data.write.offset); pgstat_report_wait_end(); break; + case PGAIO_OP_FSYNC: + pgstat_report_wait_start(ioh->op_data.fsync.wait_event_info); + if (ioh->op_data.fsync.datasync) + result = pg_fdatasync(ioh->op_data.fsync.fd); + else + result = pg_fsync(ioh->op_data.fsync.fd); + pgstat_report_wait_end(); + break; case PGAIO_OP_INVALID: elog(ERROR, "trying to execute invalid IO operation"); } @@ -189,6 +210,8 @@ pgaio_io_get_op_name(PgAioHandle *ioh) return "readv"; case PGAIO_OP_WRITEV: return "writev"; + case PGAIO_OP_FSYNC: + return "fsync"; } return NULL; /* silence compiler */ @@ -209,6 +232,8 @@ pgaio_io_uses_fd(PgAioHandle *ioh, int fd) return ioh->op_data.read.fd == fd; case PGAIO_OP_WRITEV: return ioh->op_data.write.fd == fd; + case PGAIO_OP_FSYNC: + return ioh->op_data.fsync.fd == fd; case PGAIO_OP_INVALID: return false; } @@ -233,6 +258,8 @@ pgaio_io_get_iovec_length(PgAioHandle *ioh, struct iovec **iov) return ioh->op_data.read.iov_length; case PGAIO_OP_WRITEV: return ioh->op_data.write.iov_length; + case PGAIO_OP_FSYNC: + return 0; default: pg_unreachable(); return 0; diff --git a/src/backend/storage/aio/method_io_uring.c b/src/backend/storage/aio/method_io_uring.c index 3ffe5061a20..675a91fb5f7 100644 --- a/src/backend/storage/aio/method_io_uring.c +++ b/src/backend/storage/aio/method_io_uring.c @@ -802,6 +802,12 @@ pgaio_uring_sq_from_io(PgAioHandle *ioh, struct io_uring_sqe *sqe) break; + case PGAIO_OP_FSYNC: + io_uring_prep_fsync(sqe, + ioh->op_data.fsync.fd, + ioh->op_data.fsync.datasync ? IORING_FSYNC_DATASYNC : 0); + break; + case PGAIO_OP_INVALID: elog(ERROR, "trying to prepare invalid IO operation for execution"); } diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c index 5391640d861..69e61ea1661 100644 --- a/src/backend/storage/smgr/smgr.c +++ b/src/backend/storage/smgr/smgr.c @@ -1094,6 +1094,9 @@ smgr_aio_reopen(PgAioHandle *ioh) od->write.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); Assert(off == od->write.offset); break; + case PGAIO_OP_FSYNC: + od->fsync.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); + break; } } diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index ec543b78409..a1d5f49e51a 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -91,10 +91,10 @@ typedef enum PgAioOp PGAIO_OP_READV, PGAIO_OP_WRITEV, + PGAIO_OP_FSYNC, /** * In the near term we'll need at least: - * - fsync / fdatasync * - flush_range * * Eventually we'll additionally want at least: @@ -104,7 +104,7 @@ typedef enum PgAioOp **/ } PgAioOp; -#define PGAIO_OP_COUNT (PGAIO_OP_WRITEV + 1) +#define PGAIO_OP_COUNT (PGAIO_OP_FSYNC + 1) /* @@ -146,6 +146,13 @@ typedef union uint16 iov_length; uint64 offset; } write; + + struct + { + int fd; + bool datasync; + uint32 wait_event_info; + } fsync; } PgAioOpData; @@ -300,6 +307,9 @@ extern void pgaio_io_start_readv(PgAioHandle *ioh, int fd, int iovcnt, uint64 offset); extern void pgaio_io_start_writev(PgAioHandle *ioh, int fd, int iovcnt, uint64 offset); +extern void pgaio_io_start_fsync(PgAioHandle *ioh, int fd, bool datasync, + uint32 wait_event_info); + /* functions in aio_target.c */ extern void pgaio_io_set_target(PgAioHandle *ioh, PgAioTargetID targetid); -- 2.47.3
v1-0002-Issue-SyncDataDirectory-fsyncs-through-AIO.patch (text/x-patch, 18.9K) download From 4a3f5e41edbef815059ab4ed4c64abc85e5e227a Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 19 Aug 2026 15:56:39 +0300 Subject: [PATCH v1 2/4] Issue SyncDataDirectory() fsyncs through AIO After a crash, the startup process fsyncs every file in the data directory serially. Submit the fsyncs through AIO and keep a bounded ring of operations in flight. Each operation holds a transient file descriptor, while the directory walk needs descriptors of its own. Limit the ring with GetFsyncConcurrencyLimit() and wait before opening the next file to avoid exhausting the descriptor reserve. The files are identified by paths held only in the startup process. PGAIO_TID_SYNC does not copy those paths into shared memory, so the worker method cannot reopen the files and executes the fsyncs synchronously in the startup process. The io_uring method can execute them concurrently. Storing MAXPGPATH bytes in every AIO target does not seem justified for this startup-only operation. Use the DATA_DIR_SYNC wait event when an fsync is executed synchronously. --- src/backend/storage/aio/aio_target.c | 24 ++ src/backend/storage/file/fd.c | 277 +++++++++++++++--- .../utils/activity/wait_event_names.txt | 1 + src/include/storage/aio.h | 3 +- src/include/storage/fd.h | 1 + src/tools/pgindent/typedefs.list | 2 + 6 files changed, 265 insertions(+), 43 deletions(-) diff --git a/src/backend/storage/aio/aio_target.c b/src/backend/storage/aio/aio_target.c index fa98f010d5a..82b24b0026d 100644 --- a/src/backend/storage/aio/aio_target.c +++ b/src/backend/storage/aio/aio_target.c @@ -18,6 +18,17 @@ #include "storage/aio_internal.h" #include "storage/smgr.h" +static char *pgaio_sync_describe_identity(const PgAioTargetData *sd); + +/* + * Target info for generic file syncs (PGAIO_TID_SYNC). The file being synced + * is identified by a path that is not stored in shared memory, therefore no + * reopen callback is provided. + */ +static const PgAioTargetInfo aio_sync_target_info = { + .name = "sync", + .describe_identity = pgaio_sync_describe_identity, +}; /* * Registry for entities that can be the target of AIO. @@ -27,9 +38,22 @@ static const PgAioTargetInfo *pgaio_target_info[] = { .name = "invalid", }, [PGAIO_TID_SMGR] = &aio_smgr_target_info, + [PGAIO_TID_SYNC] = &aio_sync_target_info, }; +/* + * describe_identity callback for PGAIO_TID_SYNC. As we do not store the path + * of the file being synced in shared memory, only a generic description can + * be provided. + */ +static char * +pgaio_sync_describe_identity(const PgAioTargetData *sd) +{ + return pstrdup("generic file sync"); +} + + /* -------------------------------------------------------------------------------- * Public target related functions operating on IO Handles diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index 190c9974494..0fcae14541d 100644 --- a/src/backend/storage/file/fd.c +++ b/src/backend/storage/file/fd.c @@ -268,6 +268,31 @@ typedef struct } desc; } AllocateDesc; +/* + * State for asynchronously issuing the fsync()s in SyncDataDirectory(). We + * keep a bounded number of fsync IOs in flight, using a simple ring of + * entries; when the ring is full, we wait for the oldest IO to complete + * before issuing another. + */ +typedef struct DataDirSyncEntry +{ + int fd; /* transient fd being synced */ + bool isdir; /* is this a directory? */ + char path[MAXPGPATH]; /* path to file being synced */ + PgAioReturn ioret; + PgAioWaitRef iow; + bool in_use; /* is this entry being used */ +} DataDirSyncEntry; + +typedef struct DataDirSyncState +{ + int elevel; /* level to log errors at */ + int max_inflight; /* size of the ring */ + int head; /* index of oldest in-flight entry */ + int count; /* number of in-flight entries */ + DataDirSyncEntry *entries; /* ring of max_inflight entries */ +} DataDirSyncState; + static int numAllocatedDescs = 0; static int maxAllocatedDescs = 0; static AllocateDesc *allocatedDescs = NULL; @@ -346,14 +371,20 @@ static void RemovePgTempRelationFiles(const char *tsdirname); static void RemovePgTempRelationFilesInDbspace(const char *dbspacedirname); static void walkdir(const char *path, - void (*action) (const char *fname, bool isdir, int elevel), + void (*action) (const char *fname, bool isdir, int elevel, DataDirSyncState *state), bool process_symlinks, - int elevel); + int elevel, + DataDirSyncState *state); #ifdef PG_FLUSH_DATA_WORKS -static void pre_sync_fname(const char *fname, bool isdir, int elevel); +static void pre_sync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state); #endif -static void datadir_fsync_fname(const char *fname, bool isdir, int elevel); -static void unlink_if_exists_fname(const char *fname, bool isdir, int elevel); +static void datadir_fsync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state); +static void unlink_if_exists_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state); +static bool fsync_fname_open(const char *fname, bool isdir, bool ignore_perm, + int elevel, int *ret); +static bool fsync_fname_close(const char *fname, bool isdir, int elevel, int fd, int returncode); +static void datadir_sync_wait_one(DataDirSyncState *state); +static void datadir_sync_drain_all(DataDirSyncState *state); static int fsync_parent_path(const char *fname, int elevel); @@ -1691,7 +1722,7 @@ PathNameDeleteTemporaryDir(const char *dirname) * used in a cleanup path, we wouldn't actually behave differently: we'll * just log failures. */ - walkdir(dirname, unlink_if_exists_fname, false, LOG); + walkdir(dirname, unlink_if_exists_fname, false, LOG, NULL); } /* @@ -3566,6 +3597,24 @@ do_syncfs(const char *path) } #endif +/* + * Return a safe upper bound for the number of fsyncs to keep in flight. + * + * Callers that fsync files opened with OpenTransientFile() hold one + * AllocateDesc for each in-flight IO. At most max_safe_fds / 3 of those can + * be allocated at a time (see reserveAllocatedDesc()), and the callers of + * interest also traverse directories (see walkdir()), which needs + * AllocateDescs of its own. So, hand out at most half of the budget. + * + * XXX: This is too safe for places that don't use OpenTransientFile() and/or + * walkdir(). + */ +int +GetFsyncConcurrencyLimit(void) +{ + return Max(1, Min(io_max_concurrency, max_safe_fds / 6)); +} + /* * Issue fsync recursively on PGDATA and all its contents, or issue syncfs for * all potential filesystem, depending on recovery_init_sync_method setting. @@ -3592,6 +3641,7 @@ void SyncDataDirectory(void) { bool xlog_is_symlink; + DataDirSyncState sync_state_data = {0}; /* We can skip this whole thing if fsync is disabled. */ if (!enableFsync) @@ -3663,15 +3713,22 @@ SyncDataDirectory(void) * directory and its contents. Errors in this step are even less * interesting than normal, so log them only at DEBUG1. */ - walkdir(".", pre_sync_fname, false, DEBUG1); + walkdir(".", pre_sync_fname, false, DEBUG1, NULL); if (xlog_is_symlink) - walkdir("pg_wal", pre_sync_fname, false, DEBUG1); - walkdir(PG_TBLSPC_DIR, pre_sync_fname, true, DEBUG1); + walkdir("pg_wal", pre_sync_fname, false, DEBUG1, NULL); + walkdir(PG_TBLSPC_DIR, pre_sync_fname, true, DEBUG1, NULL); #endif /* Prepare to report progress syncing the data directory via fsync. */ begin_startup_progress_phase(); + sync_state_data.elevel = LOG; + sync_state_data.max_inflight = GetFsyncConcurrencyLimit(); + sync_state_data.head = 0; + sync_state_data.count = 0; + sync_state_data.entries = palloc0(sizeof(DataDirSyncEntry) * + sync_state_data.max_inflight); + /* * Now we do the fsync()s in the same order. * @@ -3681,10 +3738,14 @@ SyncDataDirectory(void) * in pg_tblspc, they'll get fsync'd twice. That's not an expected case * so we don't worry about optimizing it. */ - walkdir(".", datadir_fsync_fname, false, LOG); + walkdir(".", datadir_fsync_fname, false, LOG, &sync_state_data); if (xlog_is_symlink) - walkdir("pg_wal", datadir_fsync_fname, false, LOG); - walkdir(PG_TBLSPC_DIR, datadir_fsync_fname, true, LOG); + walkdir("pg_wal", datadir_fsync_fname, false, LOG, &sync_state_data); + walkdir(PG_TBLSPC_DIR, datadir_fsync_fname, true, LOG, &sync_state_data); + + datadir_sync_drain_all(&sync_state_data); + + pfree(sync_state_data.entries); } /* @@ -3704,9 +3765,10 @@ SyncDataDirectory(void) */ static void walkdir(const char *path, - void (*action) (const char *fname, bool isdir, int elevel), + void (*action) (const char *fname, bool isdir, int elevel, DataDirSyncState *state), bool process_symlinks, - int elevel) + int elevel, + DataDirSyncState *state) { DIR *dir; struct dirent *de; @@ -3728,10 +3790,10 @@ walkdir(const char *path, switch (get_dirent_type(subpath, de, process_symlinks, elevel)) { case PGFILETYPE_REG: - (*action) (subpath, false, elevel); + (*action) (subpath, false, elevel, state); break; case PGFILETYPE_DIR: - walkdir(subpath, action, false, elevel); + walkdir(subpath, action, false, elevel, state); break; default: @@ -3753,7 +3815,7 @@ walkdir(const char *path, * might not be robust against that. */ if (dir) - (*action) (path, true, elevel); + (*action) (path, true, elevel, state); } @@ -3766,10 +3828,12 @@ walkdir(const char *path, #ifdef PG_FLUSH_DATA_WORKS static void -pre_sync_fname(const char *fname, bool isdir, int elevel) +pre_sync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state) { int fd; + Assert(!state); + /* Don't try to flush directories, it'll likely just fail */ if (isdir) return; @@ -3804,21 +3868,98 @@ pre_sync_fname(const char *fname, bool isdir, int elevel) #endif /* PG_FLUSH_DATA_WORKS */ static void -datadir_fsync_fname(const char *fname, bool isdir, int elevel) +datadir_sync_wait_one(DataDirSyncState *state) +{ + DataDirSyncEntry *entry; + + Assert(state->count > 0); + + entry = &state->entries[state->head]; + Assert(entry->in_use); + + pgaio_wref_wait(&entry->iow); + + /* + * As we didn't register a completion callback, the IO's status is always + * PGAIO_RS_OK; the raw fsync() return (0 or -errno) is available in + * ->result.result. Use the same error handling as fsync_fname_ext(). + */ + if (entry->ioret.result.result < 0) + errno = -entry->ioret.result.result; + + fsync_fname_close(entry->path, entry->isdir, state->elevel, entry->fd, entry->ioret.result.result); + + entry->in_use = false; + state->head = (state->head + 1) % state->max_inflight; + state->count--; +} + +static void +datadir_sync_drain_all(DataDirSyncState *state) +{ + while (state->count > 0) + datadir_sync_wait_one(state); + + Assert(state->count == 0); +} + +static void +datadir_fsync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state) { + int fd; + int slot; + DataDirSyncEntry *entry; + PgAioHandle *ioh; + ereport_startup_progress("syncing data directory (fsync), elapsed time: %ld.%02d s, current path: %s", fname); /* - * We want to silently ignoring errors about unreadable files. Pass that - * desire on to fsync_fname_ext(). + * If the ring is full, wait before opening the next file, so that the + * number of open descriptors never temporarily exceeds the ring size. */ - fsync_fname_ext(fname, isdir, true, elevel); + if (state->count == state->max_inflight) + datadir_sync_wait_one(state); + + /* + * We want to silently ignore errors about unreadable files. Pass that + * desire on to fsync_fname_open(). + */ + if (!fsync_fname_open(fname, isdir, true, elevel, &fd)) + return; + + Assert(state->count < state->max_inflight); + slot = (state->head + state->count) % state->max_inflight; + entry = &state->entries[slot]; + Assert(!entry->in_use); + + entry->fd = fd; + entry->isdir = isdir; + strlcpy(entry->path, fname, MAXPGPATH); + entry->in_use = true; + + ioh = pgaio_io_acquire(CurrentResourceOwner, &entry->ioret); + pgaio_io_set_target(ioh, PGAIO_TID_SYNC); + pgaio_io_get_wref(ioh, &entry->iow); + + /* + * Interrupts must be held across staging the IO, so that the file + * descriptor it references cannot be closed by interrupt processing + * before the IO has been submitted. + */ + HOLD_INTERRUPTS(); + pgaio_io_start_fsync(ioh, fd, false, WAIT_EVENT_DATA_DIR_SYNC); + RESUME_INTERRUPTS(); + + state->count++; } static void -unlink_if_exists_fname(const char *fname, bool isdir, int elevel) +unlink_if_exists_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state) { + + Assert(!state); + if (isdir) { if (rmdir(fname) != 0 && errno != ENOENT) @@ -3834,19 +3975,24 @@ unlink_if_exists_fname(const char *fname, bool isdir, int elevel) } /* - * fsync_fname_ext -- Try to fsync a file or directory + * Helper for opening a file as part of fsync_fname_ext() and + * datadir_fsync_fname(). Split out because the latter performs the fsync + * asynchronously via AIO. * - * If ignore_perm is true, ignore errors upon trying to open unreadable - * files. Logs other errors at a caller-specified level. + * If ignore_perm is true, ignore errors upon trying to open unreadable files. * - * Returns 0 if the operation succeeded, -1 otherwise. + * If the file could not be opened, false is returned; *fd is set to 0 if the + * failure should be ignored, or -1 otherwise. Other errors are logged at the + * caller-specified level. + * + * If the file was opened successfully, true is returned and *fd is set to + * the file descriptor. */ -int -fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) +static bool +fsync_fname_open(const char *fname, bool isdir, bool ignore_perm, + int elevel, int *fd) { - int fd; int flags; - int returncode; /* * Some OSs require directories to be opened read-only whereas other @@ -3860,27 +4006,48 @@ fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) else flags |= O_RDONLY; - fd = OpenTransientFile(fname, flags); + *fd = OpenTransientFile(fname, flags); /* * Some OSs don't allow us to open directories at all (Windows returns * EACCES), just ignore the error in that case. If desired also silently * ignoring errors about unreadable files. Log others. */ - if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES)) - return 0; - else if (fd < 0 && ignore_perm && errno == EACCES) - return 0; - else if (fd < 0) + if (*fd >= 0) + return true; + if (isdir && (errno == EISDIR || errno == EACCES)) { + *fd = 0; + return false; + } + else if (ignore_perm && errno == EACCES) + { + *fd = 0; + return false; + } + else + { + *fd = -1; ereport(elevel, (errcode_for_file_access(), errmsg("could not open file \"%s\": %m", fname))); - return -1; + return false; } +} - returncode = pg_fsync(fd); - +/* + * Helper for closing a file, and reporting any fsync failure, as part of + * fsync_fname_ext() and datadir_fsync_fname(). Split out because the latter + * performs the fsync asynchronously via AIO. + * + * "returncode" is the result of the preceding fsync; if it is negative, errno + * must describe the failure. + * + * Returns true if the operation succeeded, false otherwise. + */ +static bool +fsync_fname_close(const char *fname, bool isdir, int elevel, int fd, int returncode) +{ /* * Some OSes don't allow us to fsync directories at all, so we can ignore * those errors. Anything else needs to be logged. @@ -3897,7 +4064,7 @@ fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) ereport(elevel, (errcode_for_file_access(), errmsg("could not fsync file \"%s\": %m", fname))); - return -1; + return false; } if (CloseTransientFile(fd) != 0) @@ -3905,9 +4072,35 @@ fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) ereport(elevel, (errcode_for_file_access(), errmsg("could not close file \"%s\": %m", fname))); - return -1; + return false; } + return true; +} + +/* + * fsync_fname_ext -- Try to fsync a file or directory + * + * If ignore_perm is true, ignore errors upon trying to open unreadable + * files. Logs other errors at a caller-specified level. + * + * Returns 0 if the operation succeeded, -1 otherwise. + */ +int +fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) +{ + int fd; + int returncode; + + if (!fsync_fname_open(fname, isdir, ignore_perm, elevel, &fd)) + return fd; + + Assert(fd >= 0); + returncode = pg_fsync(fd); + + if (!fsync_fname_close(fname, isdir, elevel, fd, returncode)) + return -1; + return 0; } diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt index 256b3a3c02e..aede94dcfc3 100644 --- a/src/backend/utils/activity/wait_event_names.txt +++ b/src/backend/utils/activity/wait_event_names.txt @@ -219,6 +219,7 @@ COPY_FILE_READ "Waiting for a read during a file copy operation." COPY_FILE_WRITE "Waiting for a write during a file copy operation." COPY_FROM_READ "Waiting to read data from a pipe, a file or a program during COPY FROM." COPY_TO_WRITE "Waiting to write data to a pipe, a file or a program during COPY TO." +DATA_DIR_SYNC "Waiting for the contents of the data directory to reach durable storage after a crash." DATA_FILE_EXTEND "Waiting for a relation data file to be extended." DATA_FILE_FLUSH "Waiting for a relation data file to reach durable storage." DATA_FILE_IMMEDIATE_SYNC "Waiting for an immediate synchronization of a relation data file to durable storage." diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index a1d5f49e51a..428504c0472 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -118,9 +118,10 @@ typedef enum PgAioTargetID /* intentionally the zero value, to help catch zeroed memory etc */ PGAIO_TID_INVALID = 0, PGAIO_TID_SMGR, + PGAIO_TID_SYNC, } PgAioTargetID; -#define PGAIO_TID_COUNT (PGAIO_TID_SMGR + 1) +#define PGAIO_TID_COUNT (PGAIO_TID_SYNC + 1) /* diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h index 8ac466fd346..c79f3312544 100644 --- a/src/include/storage/fd.h +++ b/src/include/storage/fd.h @@ -219,6 +219,7 @@ extern int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int extern int durable_rename(const char *oldfile, const char *newfile, int elevel); extern int durable_unlink(const char *fname, int elevel); extern void SyncDataDirectory(void); +extern int GetFsyncConcurrencyLimit(void); extern int data_sync_elevel(int elevel); static inline ssize_t diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 6c366d3a523..a95b09859b5 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -639,7 +639,9 @@ DataChecksumsStateStruct DataChecksumsWorkerDatabase DataChecksumsWorkerOperation DataChecksumsWorkerResult +DataDirSyncEntry DataDirSyncMethod +DataDirSyncState DataDumperPtr DataPageDeleteStack DataTypesUsageChecks -- 2.47.3
v1-0003-Issue-checkpointer-fsyncs-asynchronously.patch (text/x-patch, 38.9K) download From 1845c07e610d9651759f9ce4239c042074916e7c Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Tue, 25 Aug 2026 11:27:22 +0300 Subject: [PATCH v1 3/4] Issue checkpointer fsyncs asynchronously ProcessSyncRequests() previously fsynced pending files one at a time. For checkpoints with many files, this serialized I/O that storage could perform concurrently. Submit the fsyncs through AIO, keeping a bounded set in flight and reaping completions in submission order. Each in-flight SLRU fsync holds a transient file descriptor, so limit the depth with GetFsyncConcurrencyLimit() rather than io_max_concurrency to avoid exhausting the descriptor reserve. Reshape the sync handler API so handlers open the file, assign an AIO target, start the fsync, and record how to close it. sync.c manages the in-flight operations, errors, retries, and pendingOps bookkeeping. Absorbing requests while fsyncs are in flight requires some care: - Recheck cancellation when an operation is reaped because a request can be canceled after its fsync starts. - Defer completion bookkeeping until the pendingOps scan ends because dynahash permits removing only the entry most recently returned. - Keep a new request for a file already in flight until the next checkpoint cycle because the running fsync might not cover its write. Relation files can be reopened through the smgr target, allowing I/O workers to perform their fsyncs. SLRU files use the generic sync target and execute synchronously with the worker I/O method, although io_uring can still overlap them. Because handlers now return before an fsync completes, md.c reports submission time to pg_stat_io, as it does for asynchronous reads. Methods that execute the fsync immediately still report its duration, and fsync counts are unchanged. The per-file checkpoint timing statistics now measure submission-to-reap time rather than fsync duration. Submission-order reaping can overstate individual times, and overlapping operations can make the aggregate exceed the wall-clock time of the sync phase. --- src/backend/access/transam/clog.c | 6 +- src/backend/access/transam/commit_ts.c | 6 +- src/backend/access/transam/multixact.c | 12 +- src/backend/access/transam/slru.c | 35 +- src/backend/storage/file/fd.c | 23 ++ src/backend/storage/smgr/md.c | 68 +++- src/backend/storage/sync/sync.c | 537 ++++++++++++++++++++----- src/include/access/clog.h | 2 +- src/include/access/commit_ts.h | 2 +- src/include/access/multixact.h | 4 +- src/include/access/slru.h | 2 +- src/include/storage/fd.h | 1 + src/include/storage/md.h | 2 +- src/include/storage/sync.h | 56 +++ src/test/modules/test_slru/test_slru.c | 45 ++- src/tools/pgindent/typedefs.list | 3 + 16 files changed, 645 insertions(+), 159 deletions(-) diff --git a/src/backend/access/transam/clog.c b/src/backend/access/transam/clog.c index 6f7f6b86eb6..89fb77ea5da 100644 --- a/src/backend/access/transam/clog.c +++ b/src/backend/access/transam/clog.c @@ -1117,8 +1117,8 @@ clog_redo(XLogReaderState *record) /* * Entrypoint for sync.c to sync clog files. */ -int -clogsyncfiletag(const FileTag *ftag, char *path) +void +clogsyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(XactCtl, ftag, path); + SlruSyncFileTag(XactCtl, ioh, entry); } diff --git a/src/backend/access/transam/commit_ts.c b/src/backend/access/transam/commit_ts.c index 9e6fd5d4657..7cbbad383b2 100644 --- a/src/backend/access/transam/commit_ts.c +++ b/src/backend/access/transam/commit_ts.c @@ -1028,8 +1028,8 @@ commit_ts_redo(XLogReaderState *record) /* * Entrypoint for sync.c to sync commit_ts files. */ -int -committssyncfiletag(const FileTag *ftag, char *path) +void +committssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(CommitTsCtl, ftag, path); + SlruSyncFileTag(CommitTsCtl, ioh, entry); } diff --git a/src/backend/access/transam/multixact.c b/src/backend/access/transam/multixact.c index d688815083c..deb866cd7f0 100644 --- a/src/backend/access/transam/multixact.c +++ b/src/backend/access/transam/multixact.c @@ -2998,17 +2998,17 @@ multixact_redo(XLogReaderState *record) /* * Entrypoint for sync.c to sync offsets files. */ -int -multixactoffsetssyncfiletag(const FileTag *ftag, char *path) +void +multixactoffsetssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(MultiXactOffsetCtl, ftag, path); + SlruSyncFileTag(MultiXactOffsetCtl, ioh, entry); } /* * Entrypoint for sync.c to sync members files. */ -int -multixactmemberssyncfiletag(const FileTag *ftag, char *path) +void +multixactmemberssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(MultiXactMemberCtl, ftag, path); + SlruSyncFileTag(MultiXactMemberCtl, ioh, entry); } diff --git a/src/backend/access/transam/slru.c b/src/backend/access/transam/slru.c index 885fd068535..b1e513ac3b6 100644 --- a/src/backend/access/transam/slru.c +++ b/src/backend/access/transam/slru.c @@ -68,6 +68,7 @@ #include "access/xlogutils.h" #include "miscadmin.h" #include "pgstat.h" +#include "storage/aio.h" #include "storage/fd.h" #include "storage/shmem.h" #include "storage/shmem_internal.h" @@ -1880,26 +1881,32 @@ SlruScanDirectory(SlruDesc *ctl, SlruScanCallback callback, void *data) * build the path), but they just forward to this common implementation that * performs the fsync. */ -int -SlruSyncFileTag(SlruDesc *ctl, const FileTag *ftag, char *path) +void +SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, InflightSyncEntry *entry) { int fd; - int save_errno; - int result; - SlruFileName(ctl, path, ftag->segno); + SlruFileName(ctl, entry->path, entry->tag.segno); - fd = OpenTransientFile(path, O_RDWR | PG_BINARY); + fd = OpenTransientFile(entry->path, O_RDWR | PG_BINARY); if (fd < 0) - return -1; + { + entry->started = false; + entry->open_errno = errno; + return; + } - pgstat_report_wait_start(WAIT_EVENT_SLRU_FLUSH_SYNC); - result = pg_fsync(fd); - pgstat_report_wait_end(); - save_errno = errno; + /* + * Use the generic sync target. SLRU segments are not smgr relations and + * cannot be reopened from a FileTag in another process, so this fsync + * will run synchronously in worker mode. + */ + pgaio_io_set_target(ioh, PGAIO_TID_SYNC); - CloseTransientFile(fd); + /* Start the asynchronous fsync; the fd is closed once it completes. */ + pgaio_io_start_fsync(ioh, fd, false, WAIT_EVENT_SLRU_FLUSH_SYNC); - errno = save_errno; - return result; + entry->started = true; + entry->close_method = SYNC_CLOSE_TRANSIENT; + entry->close_file = fd; } diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index 0fcae14541d..f91ee488b89 100644 --- a/src/backend/storage/file/fd.c +++ b/src/backend/storage/file/fd.c @@ -2258,6 +2258,29 @@ FileStartReadV(PgAioHandle *ioh, File file, return 0; } +int +FileStartSync(PgAioHandle *ioh, File file, bool datasync, + uint32 wait_event_info) +{ + int returnCode; + Vfd *vfdP; + + Assert(FileIsValid(file)); + + DO_DB(elog(LOG, "FileStartSync: %d (%s)", + file, VfdCache[file].fileName)); + + returnCode = FileAccess(file); + if (returnCode < 0) + return returnCode; + + vfdP = &VfdCache[file]; + + pgaio_io_start_fsync(ioh, vfdP->fd, datasync, wait_event_info); + + return 0; +} + ssize_t FileWriteV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info) diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c index 780c88c0630..e1fca54d9d9 100644 --- a/src/backend/storage/smgr/md.c +++ b/src/backend/storage/smgr/md.c @@ -1896,26 +1896,27 @@ _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg) } /* - * Sync a file to disk, given a file tag. Write the path into an output - * buffer so the caller can use it in error messages. + * Sync a file to disk, given a file tag. * - * Return 0 on success, -1 on failure, with errno set. + * Starts an asynchronous fsync on the given AIO handle and records in "entry" + * the path (for error messages), whether an IO was started, and how the file + * is to be closed once the fsync has completed. */ -int -mdsyncfiletag(const FileTag *ftag, char *path) +void +mdsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry) { + FileTag *ftag = &entry->tag; SMgrRelation reln = smgropen(ftag->rlocator, INVALID_PROC_NUMBER); + BlockNumber segfirstblock = ftag->segno * ((BlockNumber) RELSEG_SIZE); File file; - instr_time io_start; bool need_to_close; - int result, - save_errno; + instr_time io_start; /* See if we already have the file open, or need to open it. */ if (ftag->segno < reln->md_num_open_segs[ftag->forknum]) { file = reln->md_seg_fds[ftag->forknum][ftag->segno].mdfd_vfd; - strlcpy(path, FilePathName(file), MAXPGPATH); + strlcpy(entry->path, FilePathName(file), MAXPGPATH); need_to_close = false; } else @@ -1923,28 +1924,53 @@ mdsyncfiletag(const FileTag *ftag, char *path) MdPathStr p; p = _mdfd_segpath(reln, ftag->forknum, ftag->segno); - strlcpy(path, p.str, MD_PATH_STR_MAXLEN); + strlcpy(entry->path, p.str, MD_PATH_STR_MAXLEN); - file = PathNameOpenFile(path, _mdfd_open_flags()); + file = PathNameOpenFile(entry->path, _mdfd_open_flags()); if (file < 0) - return -1; + { + entry->started = false; + entry->open_errno = errno; + return; + } need_to_close = true; } + pgaio_io_set_target_smgr(ioh, reln, ftag->forknum, segfirstblock, + 0, false); + + /* + * As with asynchronous reads, measure the time spent starting the IO. + * Synchronous execution includes the fsync itself; otherwise this only + * measures submission. + */ io_start = pgstat_prepare_io_time(track_io_timing); - /* Sync the file. */ - result = FileSync(file, WAIT_EVENT_DATA_FILE_SYNC); - save_errno = errno; + if (FileStartSync(ioh, file, false, WAIT_EVENT_DATA_FILE_SYNC) < 0) + { + entry->started = false; + entry->open_errno = errno; + if (need_to_close) + FileClose(file); + return; + } - if (need_to_close) - FileClose(file); + pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL, IOOP_FSYNC, + io_start, 1, 0); - pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL, - IOOP_FSYNC, io_start, 1, 0); + entry->started = true; - errno = save_errno; - return result; + /* + * If we opened the segment ourselves it has to be closed once the fsync + * has completed; segments owned by smgr are left to smgr to manage. + */ + if (need_to_close) + { + entry->close_method = SYNC_CLOSE_VFD; + entry->close_file = (int) file; + } + else + entry->close_method = SYNC_CLOSE_NONE; } /* diff --git a/src/backend/storage/sync/sync.c b/src/backend/storage/sync/sync.c index 2c964b6f3d9..4263881ddd8 100644 --- a/src/backend/storage/sync/sync.c +++ b/src/backend/storage/sync/sync.c @@ -26,7 +26,9 @@ #include "pgstat.h" #include "portability/instr_time.h" #include "postmaster/bgwriter.h" +#include "storage/aio.h" #include "storage/fd.h" +#include "storage/ipc.h" #include "storage/latch.h" #include "storage/md.h" #include "utils/hsearch.h" @@ -54,11 +56,22 @@ */ typedef uint16 CycleCtr; /* can be any convenient integer size */ -typedef struct +typedef struct PendingFsyncEntry { FileTag tag; /* identifies handler and file */ CycleCtr cycle_ctr; /* sync_cycle_ctr of oldest request */ bool canceled; /* canceled is true if we canceled "recently" */ + + /* + * Set when a request arrives for a tag that already has an entry, and + * cleared whenever an fsync for it is started. If it is set once that + * fsync completes, the request came in while the fsync was in flight, so + * the fsync cannot be assumed to have covered it. + */ + bool re_requested; + + /* fsync is done, pending hash-table bookkeeping */ + bool sync_completed; } PendingFsyncEntry; typedef struct @@ -68,10 +81,44 @@ typedef struct bool canceled; /* true if request has been canceled */ } PendingUnlinkEntry; +/* + * Transient state used while processing a batch of fsync requests. A single + * SyncState instance lives on the stack of ProcessSyncRequests() so that no + * partial state survives across calls. + */ +typedef struct SyncState +{ + dlist_head inflight; /* InflightSyncEntry being fsync'd right now */ + dlist_head retry; /* InflightSyncEntry to be retried */ + int inflight_count; /* number of entries in "inflight" */ + int max_inflight; /* max number of concurrent fsyncs */ + int absorb_counter; + + /* stats */ + int processed; + instr_time longest; + instr_time total_elapsed; +} SyncState; + static HTAB *pendingOps = NULL; static List *pendingUnlinks = NIL; static MemoryContext pendingOpsCxt; /* context for the above */ +/* + * Context for the InflightSyncEntry structs allocated while a batch of fsync + * requests is being processed. It is kept separate from pendingOpsCxt (which + * must survive for the lifetime of the process, as it holds pendingOps + * itself), so that it can be reset between batches. + */ +static MemoryContext inflightSyncCxt; + +/* + * All InflightSyncEntry structs that have not yet been freed. Unlike the + * lists in SyncState, this survives an error so that handler-owned files can + * be closed before their entries are discarded. + */ +static dlist_head activeSyncEntries = DLIST_STATIC_INIT(activeSyncEntries); + static CycleCtr sync_cycle_ctr = 0; static CycleCtr checkpoint_cycle_ctr = 0; @@ -84,7 +131,7 @@ static CycleCtr checkpoint_cycle_ctr = 0; */ typedef struct SyncOps { - int (*sync_syncfiletag) (const FileTag *ftag, char *path); + void (*sync_syncfiletag) (PgAioHandle *ioh, InflightSyncEntry *entry); int (*sync_unlinkfiletag) (const FileTag *ftag, char *path); bool (*sync_filetagmatches) (const FileTag *ftag, const FileTag *candidate); @@ -155,6 +202,10 @@ InitSync(void) &hash_ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); pendingUnlinks = NIL; + + inflightSyncCxt = AllocSetContextCreate(TopMemoryContext, + "Inflight sync context", + ALLOCSET_DEFAULT_SIZES); } } @@ -281,25 +332,295 @@ SyncPostCheckpoint(void) } /* - * ProcessSyncRequests() -- Process queued fsync requests. + * Close the file that a sync handler opened for an in-flight fsync. */ -void -ProcessSyncRequests(void) +static void +sync_close_file(InflightSyncEntry *entry) { - static bool sync_in_progress = false; + switch (entry->close_method) + { + case SYNC_CLOSE_NONE: + break; + case SYNC_CLOSE_TRANSIENT: + CloseTransientFile(entry->close_file); + break; + case SYNC_CLOSE_VFD: + FileClose((File) entry->close_file); + break; + default: + pg_unreachable(); + } + + entry->close_method = SYNC_CLOSE_NONE; +} + +static void +sync_free_entry(InflightSyncEntry *entry) +{ + dlist_delete_from(&activeSyncEntries, &entry->cleanup_node); + pfree(entry); +} + +/* + * Error cleanup callback for ProcessSyncRequests(). + */ +static void +sync_cleanup_inflight(int code, Datum arg) +{ + while (!dlist_is_empty(&activeSyncEntries)) + { + dlist_node *node = dlist_pop_head_node(&activeSyncEntries); + InflightSyncEntry *entry; + + entry = dlist_container(InflightSyncEntry, cleanup_node, node); + + if (entry->started) + pgaio_wref_wait(&entry->iow); + + sync_close_file(entry); + pfree(entry); + } +} + +static void +sync_start_one(SyncState *sync_state, InflightSyncEntry *entry) +{ + struct PgAioHandle *ioh; + instr_time io_start; + + INSTR_TIME_SET_CURRENT(io_start); + entry->start_time = io_start; + + entry->started = false; + entry->open_errno = 0; + entry->close_method = SYNC_CLOSE_NONE; + pgaio_wref_clear(&entry->iow); + + /* + * Any request that arrives from here on may cover data that the fsync + * started below does not, so start out with a clean slate. This has to + * happen before the IO is submitted; requests absorbed in between are + * covered by the fsync, so treating them as newer is merely conservative. + */ + entry->hash_entry->re_requested = false; + + ioh = pgaio_io_acquire(CurrentResourceOwner, &entry->ioret); + pgaio_io_get_wref(ioh, &entry->iow); + + /* + * The handler opens the file, assigns the target and stages the fsync. + * Hold interrupts so that the referenced descriptor cannot be closed + * during submission. + */ + HOLD_INTERRUPTS(); + syncsw[entry->tag.handler].sync_syncfiletag(ioh, entry); + RESUME_INTERRUPTS(); + + if (!entry->started) + pgaio_io_release(ioh); + + dlist_push_tail(&sync_state->inflight, &entry->node); + sync_state->inflight_count++; +} + +static void +sync_drain_one(SyncState *sync_state) +{ + dlist_node *node; + InflightSyncEntry *entry; + int result; + + Assert(sync_state->inflight_count > 0); + + node = dlist_pop_head_node(&sync_state->inflight); + entry = dlist_container(InflightSyncEntry, node, node); + sync_state->inflight_count--; + + if (entry->started) + { + pgaio_wref_wait(&entry->iow); + + /* + * We did not register a completion callback, so the distilled status + * is always PGAIO_RS_OK and the raw fsync() return value (0 on + * success, -errno on failure) is available in ->result.result. + */ + result = -entry->ioret.result.result; + } + else + result = entry->open_errno; + + sync_close_file(entry); + + if (!result) + { + instr_time io_time; + + /* + * These values measure submission-to-reap time, not necessarily fsync + * duration. Submission-order reaping can overstate individual + * durations, and the aggregate can exceed wall-clock time because + * fsyncs overlap. + */ + INSTR_TIME_SET_CURRENT(io_time); + INSTR_TIME_SUBTRACT(io_time, entry->start_time); + + if (INSTR_TIME_GT(io_time, sync_state->longest)) + sync_state->longest = io_time; + INSTR_TIME_ADD(sync_state->total_elapsed, io_time); + sync_state->processed++; + + if (log_checkpoints) + elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f ms", + sync_state->processed, + entry->path, + INSTR_TIME_GET_MILLISEC(io_time)); + + entry->hash_entry->sync_completed = true; + sync_free_entry(entry); + } + else + { + /* + * The request may have been canceled after we started the fsync, e.g. + * because the relation was dropped in the meantime and an intervening + * AbsorbSyncRequests() picked up the cancel message. Since + * mdunlink() queues the "cancel" before actually unlinking, a + * cancellation means the failure is expected and the entry can simply + * be dropped. + * + * The upstream, synchronous code checked this at the top of its retry + * loop; because the fsync is now in flight while requests are being + * absorbed, we have to re-check it here. + */ + if (entry->hash_entry->canceled) + { + entry->hash_entry->sync_completed = true; + sync_free_entry(entry); + return; + } + + /* + * It is possible that the relation has been dropped or truncated + * since the fsync request was entered. Therefore, allow ENOENT, but + * only if we didn't fail already on this file. + */ + errno = result; + if (!FILE_POSSIBLY_DELETED(errno) || entry->retry_count > 0) + ereport(data_sync_elevel(ERROR), + (errcode_for_file_access(), + errmsg("could not fsync file \"%s\": %m", + entry->path))); + else + ereport(DEBUG1, + (errcode_for_file_access(), + errmsg_internal("could not fsync file \"%s\" but retrying: %m", + entry->path))); + + entry->retry_count++; + dlist_push_tail(&sync_state->retry, &entry->node); + } +} +static void +sync_drain_all(SyncState *sync_state) +{ + while (sync_state->inflight_count) + sync_drain_one(sync_state); +} + +/* + * Finish requests whose fsyncs have completed. + * + * The main hash scan may only remove the entry it most recently returned, so + * completion processing is deferred until it ends. This second scan can then + * remove each completed entry as the current entry. Recheck the hash entry + * now because requests absorbed since the fsync completed may require it to + * remain for the next checkpoint cycle. + */ +static void +sync_process_completed(void) +{ HASH_SEQ_STATUS hstat; PendingFsyncEntry *entry; - int absorb_counter; - /* Statistics on sync times */ - int processed = 0; - instr_time sync_start, - sync_end, - sync_diff; - uint64 elapsed; - uint64 longest = 0; - uint64 total_elapsed = 0; + hash_seq_init(&hstat, pendingOps); + while ((entry = (PendingFsyncEntry *) hash_seq_search(&hstat)) != NULL) + { + if (!entry->sync_completed) + continue; + + /* + * We are done with this entry, unless a request for it arrived while + * the fsync was in flight. A cancel supersedes any such request, as + * RememberSyncRequest() clears "canceled" when it records a new one. + */ + if (!entry->re_requested || entry->canceled) + { + if (hash_search(pendingOps, &entry->tag, HASH_REMOVE, NULL) == NULL) + elog(ERROR, "pendingOps corrupted"); + } + else + entry->sync_completed = false; + } +} + +/* + * Reissue any fsync requests that previously failed with an ignorable error. + * + * The fsync table could contain requests to fsync segments that have been + * deleted (unlinked) by the time we get to them. Rather than just hoping an + * ENOENT (or EACCES on Windows) error can be ignored, what we do on error is + * absorb pending requests and then retry. Since mdunlink() queues a "cancel" + * message before actually unlinking, the fsync request is guaranteed to be + * marked canceled after the absorb if it really was this case. + */ +static void +sync_process_retries(SyncState *sync_state) +{ + if (dlist_is_empty(&sync_state->retry)) + return; + + AbsorbSyncRequests(); + + while (!dlist_is_empty(&sync_state->retry)) + { + dlist_node *node = dlist_pop_head_node(&sync_state->retry); + InflightSyncEntry *entry = dlist_container(InflightSyncEntry, node, node); + + if (entry->hash_entry->canceled) + { + /* Safe to remove here, the scan has already finished. */ + if (hash_search(pendingOps, &entry->hash_entry->tag, + HASH_REMOVE, NULL) == NULL) + elog(ERROR, "pendingOps corrupted"); + sync_free_entry(entry); + continue; + } + + Assert(sync_state->inflight_count <= sync_state->max_inflight); + if (sync_state->inflight_count == sync_state->max_inflight) + sync_drain_one(sync_state); + + sync_start_one(sync_state, entry); + } + + sync_drain_all(sync_state); + sync_process_completed(); +} + +/* + * Process queued fsync requests. The public wrapper ensures that any error + * closes files owned by in-flight entries. + */ +static void +ProcessSyncRequestsInternal(void) +{ + static bool sync_in_progress = false; + + HASH_SEQ_STATUS hstat; + PendingFsyncEntry *entry; + SyncState sync_state; /* * This is only called during checkpoints, and checkpoints should only @@ -350,6 +671,7 @@ ProcessSyncRequests(void) while ((entry = (PendingFsyncEntry *) hash_seq_search(&hstat)) != NULL) { entry->cycle_ctr = sync_cycle_ctr; + entry->sync_completed = false; } } @@ -359,13 +681,26 @@ ProcessSyncRequests(void) /* Set flag to detect failure if we don't reach the end of the loop */ sync_in_progress = true; + /* + * Bound concurrent fsyncs by both the AIO handle and transient descriptor + * budgets. + */ + dlist_init(&sync_state.inflight); + dlist_init(&sync_state.retry); + sync_state.inflight_count = 0; + sync_state.max_inflight = GetFsyncConcurrencyLimit(); + sync_state.processed = 0; + INSTR_TIME_SET_ZERO(sync_state.longest); + INSTR_TIME_SET_ZERO(sync_state.total_elapsed); + + Assert(dlist_is_empty(&activeSyncEntries)); + MemoryContextReset(inflightSyncCxt); + /* Now scan the hashtable for fsync requests to process */ - absorb_counter = FSYNCS_PER_ABSORB; + sync_state.absorb_counter = FSYNCS_PER_ABSORB; hash_seq_init(&hstat, pendingOps); while ((entry = (PendingFsyncEntry *) hash_seq_search(&hstat)) != NULL) { - int failures; - /* * If the entry is new then don't process it this time; it is new. * Note "continue" bypasses the hash-remove call at the bottom of the @@ -378,103 +713,94 @@ ProcessSyncRequests(void) Assert((CycleCtr) (entry->cycle_ctr + 1) == sync_cycle_ctr); /* - * If fsync is off then we don't have to bother opening the file at - * all. (We delay checking until this point so that changing fsync on - * the fly behaves sensibly.) + * If in checkpointer, we want to absorb pending requests every so + * often to prevent overflow of the fsync request queue. It is + * unspecified whether newly-added entries will be visited by + * hash_seq_search, but we don't care since we don't need to process + * them anyway. */ - if (enableFsync) + if (enableFsync && --sync_state.absorb_counter <= 0) { - /* - * If in checkpointer, we want to absorb pending requests every so - * often to prevent overflow of the fsync request queue. It is - * unspecified whether newly-added entries will be visited by - * hash_seq_search, but we don't care since we don't need to - * process them anyway. - */ - if (--absorb_counter <= 0) - { - AbsorbSyncRequests(); - absorb_counter = FSYNCS_PER_ABSORB; - } + AbsorbSyncRequests(); + sync_state.absorb_counter = FSYNCS_PER_ABSORB; + } + + if (!enableFsync || entry->canceled) + { + /* We are done with this entry, remove it */ + if (hash_search(pendingOps, &entry->tag, HASH_REMOVE, NULL) == NULL) + elog(ERROR, "pendingOps corrupted"); + } + else + { + InflightSyncEntry *inflight_entry; + + Assert(sync_state.inflight_count <= sync_state.max_inflight); + if (sync_state.inflight_count == sync_state.max_inflight) + sync_drain_one(&sync_state); /* - * The fsync table could contain requests to fsync segments that - * have been deleted (unlinked) by the time we get to them. Rather - * than just hoping an ENOENT (or EACCES on Windows) error can be - * ignored, what we do on error is absorb pending requests and - * then retry. Since mdunlink() queues a "cancel" message before - * actually unlinking, the fsync request is guaranteed to be - * marked canceled after the absorb if it really was this case. - * DROP DATABASE likewise has to tell us to forget fsync requests - * before it starts deletions. + * Mark the entry as already dealt with in this cycle. It must + * remain in the hash table until its fsync completes and the scan + * ends. If a new request arrives meanwhile, this cycle counter + * leaves the entry to be processed by the next checkpoint. */ - for (failures = 0; !entry->canceled; failures++) - { - char path[MAXPGPATH]; - - INSTR_TIME_SET_CURRENT(sync_start); - if (syncsw[entry->tag.handler].sync_syncfiletag(&entry->tag, - path) == 0) - { - /* Success; update statistics about sync timing */ - INSTR_TIME_SET_CURRENT(sync_end); - sync_diff = sync_end; - INSTR_TIME_SUBTRACT(sync_diff, sync_start); - elapsed = INSTR_TIME_GET_MICROSEC(sync_diff); - if (elapsed > longest) - longest = elapsed; - total_elapsed += elapsed; - processed++; - - if (log_checkpoints) - elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f ms", - processed, - path, - (double) elapsed / 1000); - - break; /* out of retry loop */ - } - - /* - * It is possible that the relation has been dropped or - * truncated since the fsync request was entered. Therefore, - * allow ENOENT, but only if we didn't fail already on this - * file. - */ - if (!FILE_POSSIBLY_DELETED(errno) || failures > 0) - ereport(data_sync_elevel(ERROR), - (errcode_for_file_access(), - errmsg("could not fsync file \"%s\": %m", - path))); - else - ereport(DEBUG1, - (errcode_for_file_access(), - errmsg_internal("could not fsync file \"%s\" but retrying: %m", - path))); - - /* - * Absorb incoming requests and check to see if a cancel - * arrived for this relation fork. - */ - AbsorbSyncRequests(); - absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */ - } /* end retry loop */ + entry->cycle_ctr = sync_cycle_ctr; + + inflight_entry = MemoryContextAllocZero(inflightSyncCxt, + sizeof(InflightSyncEntry)); + inflight_entry->tag = entry->tag; + inflight_entry->hash_entry = entry; + dlist_push_tail(&activeSyncEntries, + &inflight_entry->cleanup_node); + + sync_start_one(&sync_state, inflight_entry); } + } - /* We are done with this entry, remove it */ - if (hash_search(pendingOps, &entry->tag, HASH_REMOVE, NULL) == NULL) - elog(ERROR, "pendingOps corrupted"); - } /* end loop over hashtable entries */ + sync_drain_all(&sync_state); + sync_process_completed(); + + /* + * A second failure raises an error, so normally one retry pass is enough. + * Keep an explicit bound in case that changes. + */ + for (int failures = 0; failures < 5; failures++) + { + if (dlist_is_empty(&sync_state.retry)) + break; + + sync_process_retries(&sync_state); + } + + if (!dlist_is_empty(&sync_state.inflight) || + !dlist_is_empty(&sync_state.retry)) + elog(PANIC, "in-flight sync requests remain after ProcessSyncRequests"); /* Return sync performance metrics for report at checkpoint end */ - CheckpointStats.ckpt_sync_rels = processed; - CheckpointStats.ckpt_longest_sync = longest; - CheckpointStats.ckpt_agg_sync_time = total_elapsed; + CheckpointStats.ckpt_sync_rels = sync_state.processed; + CheckpointStats.ckpt_longest_sync = INSTR_TIME_GET_MICROSEC(sync_state.longest); + CheckpointStats.ckpt_agg_sync_time = INSTR_TIME_GET_MICROSEC(sync_state.total_elapsed); /* Flag successful completion of ProcessSyncRequests */ sync_in_progress = false; } +/* + * ProcessSyncRequests() -- Process queued fsync requests. + */ +void +ProcessSyncRequests(void) +{ + PG_ENSURE_ERROR_CLEANUP(sync_cleanup_inflight, (Datum) 0); + { + ProcessSyncRequestsInternal(); + } + PG_END_ENSURE_ERROR_CLEANUP(sync_cleanup_inflight, (Datum) 0); + + Assert(dlist_is_empty(&activeSyncEntries)); +} + /* * RememberSyncRequest() -- callback from checkpointer side of sync request * @@ -554,11 +880,20 @@ RememberSyncRequest(const FileTag *ftag, SyncRequestType type) ftag, HASH_ENTER, &found); + + /* + * If an entry already existed, an fsync for it may be in flight right + * now, in which case it cannot be assumed to cover this request; see + * sync_drain_one(). + */ + entry->re_requested = found; + /* if new entry, or was previously canceled, initialize it */ if (!found || entry->canceled) { entry->cycle_ctr = sync_cycle_ctr; entry->canceled = false; + entry->sync_completed = false; } /* diff --git a/src/include/access/clog.h b/src/include/access/clog.h index 7894998c763..e089106f7fe 100644 --- a/src/include/access/clog.h +++ b/src/include/access/clog.h @@ -47,7 +47,7 @@ extern void CheckPointCLOG(void); extern void ExtendCLOG(TransactionId newestXact); extern void TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid); -extern int clogsyncfiletag(const FileTag *ftag, char *path); +extern void clogsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); /* XLOG stuff */ #define CLOG_ZEROPAGE 0x00 diff --git a/src/include/access/commit_ts.h b/src/include/access/commit_ts.h index 825ccda90ed..fa4880e0d03 100644 --- a/src/include/access/commit_ts.h +++ b/src/include/access/commit_ts.h @@ -38,7 +38,7 @@ extern void SetCommitTsLimit(TransactionId oldestXact, TransactionId newestXact); extern void AdvanceOldestCommitTsXid(TransactionId oldestXact); -extern int committssyncfiletag(const FileTag *ftag, char *path); +extern void committssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); /* XLOG stuff */ #define COMMIT_TS_ZEROPAGE 0x00 diff --git a/src/include/access/multixact.h b/src/include/access/multixact.h index 6be5299ab68..3f980b4120d 100644 --- a/src/include/access/multixact.h +++ b/src/include/access/multixact.h @@ -114,8 +114,8 @@ extern bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2); extern bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2); -extern int multixactoffsetssyncfiletag(const FileTag *ftag, char *path); -extern int multixactmemberssyncfiletag(const FileTag *ftag, char *path); +extern void multixactoffsetssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern void multixactmemberssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); extern void AtEOXact_MultiXact(void); extern void AtPrepare_MultiXact(void); diff --git a/src/include/access/slru.h b/src/include/access/slru.h index b4adb1789c7..0e91df5609c 100644 --- a/src/include/access/slru.h +++ b/src/include/access/slru.h @@ -240,7 +240,7 @@ typedef bool (*SlruScanCallback) (SlruDesc *ctl, char *filename, int64 segpage, extern bool SlruScanDirectory(SlruDesc *ctl, SlruScanCallback callback, void *data); extern void SlruDeleteSegment(SlruDesc *ctl, int64 segno); -extern int SlruSyncFileTag(SlruDesc *ctl, const FileTag *ftag, char *path); +extern void SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, struct InflightSyncEntry *entry); /* SlruScanDirectory public callbacks */ extern bool SlruScanDirCbReportPresence(SlruDesc *ctl, char *filename, diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h index c79f3312544..f39469058b7 100644 --- a/src/include/storage/fd.h +++ b/src/include/storage/fd.h @@ -138,6 +138,7 @@ extern int FilePrefetch(File file, pgoff_t offset, pgoff_t amount, uint32 wait_e extern ssize_t FileReadV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info); extern ssize_t FileWriteV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info); extern int FileStartReadV(struct PgAioHandle *ioh, File file, int iovcnt, pgoff_t offset, uint32 wait_event_info); +extern int FileStartSync(struct PgAioHandle *ioh, File file, bool datasync, uint32 wait_event_info); extern int FileSync(File file, uint32 wait_event_info); extern int FileZero(File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info); extern int FileFallocate(File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info); diff --git a/src/include/storage/md.h b/src/include/storage/md.h index b8d10329eb8..53f75802ac0 100644 --- a/src/include/storage/md.h +++ b/src/include/storage/md.h @@ -58,7 +58,7 @@ extern void ForgetDatabaseSyncRequests(Oid dbid); extern void DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo); /* md sync callbacks */ -extern int mdsyncfiletag(const FileTag *ftag, char *path); +extern void mdsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); extern int mdunlinkfiletag(const FileTag *ftag, char *path); extern bool mdfiletagmatches(const FileTag *ftag, const FileTag *candidate); diff --git a/src/include/storage/sync.h b/src/include/storage/sync.h index 88290500bc9..a72ce4c3fd3 100644 --- a/src/include/storage/sync.h +++ b/src/include/storage/sync.h @@ -13,6 +13,9 @@ #ifndef SYNC_H #define SYNC_H +#include "lib/ilist.h" +#include "portability/instr_time.h" +#include "storage/aio_types.h" #include "storage/relfilelocator.h" /* @@ -55,6 +58,59 @@ typedef struct FileTag uint64 segno; } FileTag; +struct PendingFsyncEntry; +struct PgAioHandle; + +/* + * How the file opened by a sync handler must be closed once its asynchronous + * fsync has completed. + */ +typedef enum SyncFileCloseMethod +{ + SYNC_CLOSE_NONE = 0, /* nothing to close */ + SYNC_CLOSE_TRANSIENT, /* CloseTransientFile(close_file) */ + SYNC_CLOSE_VFD, /* FileClose((File) close_file) */ +} SyncFileCloseMethod; + +/* + * State for a single in-flight asynchronous fsync request. A sync handler + * opens the file to be synced, fills in the fields it is responsible for, and + * starts an asynchronous fsync on the AIO handle it is given. + */ +typedef struct InflightSyncEntry +{ + FileTag tag; /* identifies handler and file */ + + char path[MAXPGPATH]; + + /* + * Set by the handler: whether it started an asynchronous fsync on the + * passed-in AIO handle. If the file could not be opened, the handler + * sets started = false and open_errno to the errno of the failed open. + */ + bool started; + int open_errno; + + /* set by the handler: how to close the opened file after completion */ + SyncFileCloseMethod close_method; + int close_file; /* fd, or File, depending on close_method */ + + struct PendingFsyncEntry *hash_entry; + + int retry_count; + + instr_time start_time; + + PgAioReturn ioret; + PgAioWaitRef iow; + + /* membership in the inflight / retry lists */ + dlist_node node; + + /* membership in the error-cleanup list */ + dlist_node cleanup_node; +} InflightSyncEntry; + extern void InitSync(void); extern void SyncPreCheckpoint(void); extern void SyncPostCheckpoint(void); diff --git a/src/test/modules/test_slru/test_slru.c b/src/test/modules/test_slru/test_slru.c index 40efffdbf62..ccac09a9285 100644 --- a/src/test/modules/test_slru/test_slru.c +++ b/src/test/modules/test_slru/test_slru.c @@ -17,10 +17,13 @@ #include "access/slru.h" #include "access/transam.h" #include "miscadmin.h" +#include "storage/aio.h" #include "storage/fd.h" #include "storage/ipc.h" #include "storage/shmem.h" +#include "storage/sync.h" #include "utils/builtins.h" +#include "utils/resowner.h" PG_MODULE_MAGIC; @@ -152,15 +155,47 @@ Datum test_slru_page_sync(PG_FUNCTION_ARGS) { int64 pageno = PG_GETARG_INT64(0); - FileTag ftag; - char path[MAXPGPATH]; + InflightSyncEntry entry = {0}; + PgAioHandle *ioh; + int result; /* note that this flushes the full file a segment is located in */ - ftag.segno = pageno / SLRU_PAGES_PER_SEGMENT; - SlruSyncFileTag(TestSlruCtl, &ftag, path); + entry.tag.segno = pageno / SLRU_PAGES_PER_SEGMENT; + + /* + * SlruSyncFileTag() now performs the fsync asynchronously. Drive it the + * same way sync.c does: acquire an AIO handle, let the handler start the + * fsync, wait for its completion and close the file it opened. + */ + ioh = pgaio_io_acquire(CurrentResourceOwner, &entry.ioret); + pgaio_io_get_wref(ioh, &entry.iow); + + HOLD_INTERRUPTS(); + SlruSyncFileTag(TestSlruCtl, ioh, &entry); + RESUME_INTERRUPTS(); + + if (entry.started) + { + pgaio_wref_wait(&entry.iow); + result = -entry.ioret.result.result; + CloseTransientFile(entry.close_file); + } + else + { + pgaio_io_release(ioh); + result = entry.open_errno; + } + + if (result != 0) + { + errno = result; + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not fsync file \"%s\": %m", entry.path))); + } elog(NOTICE, "Called SlruSyncFileTag() for segment %" PRIu64 " on path %s", - ftag.segno, path); + entry.tag.segno, entry.path); PG_RETURN_VOID(); } diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index a95b09859b5..4fd08012e1b 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1361,6 +1361,7 @@ IndexVacuumInfo IndxInfo InferClause InferenceElem +InflightSyncEntry InfoItem InhInfo InheritableSocket @@ -3078,12 +3079,14 @@ SupportRequestSimplify SupportRequestSimplifyAggref SupportRequestWFuncMonotonic Syn +SyncFileCloseMethod SyncOps SyncRepConfigData SyncRepStandbyData SyncRequestHandler SyncRequestType SyncStandbySlotsConfigData +SyncState SyncingRelationsState SysCacheIdentifier SysFKRelationship -- 2.47.3
v1-0004-Allow-IO-workers-to-execute-SLRU-fsyncs.patch (text/x-patch, 20.5K) download From 203cf306618d1440e74e7b192edc3b13b3c679a7 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Tue, 25 Aug 2026 15:00:40 +0300 Subject: [PATCH v1 4/4] Allow IO workers to execute SLRU fsyncs The SLRU fsyncs introduced by the preceding commit use the generic PGAIO_TID_SYNC target. It does not store paths in shared memory, so I/O workers cannot reopen the files and the checkpointer must perform the operations itself. Add PGAIO_TID_SYNC_FILETAG, which identifies a file by the FileTag registered with sync.c. A FileTag contains enough information to reopen the file in another process. Dispatch reopening through an optional SyncOps callback, implemented for SLRUs using the new SlruOpenFileTag(). SLRUs that are not registered with sync.c continue to use PGAIO_TID_SYNC. Define the shared FileTag representation in storage/aio_types.h so PgAioTargetData can store it directly without duplicating its layout. Describe the target and worker-side open errors using the SLRU name and segment number. Unlike the smgr target, the FileTag target opens a new descriptor for each operation instead of using a cache. Add an optional PgAioTargetInfo close callback so I/O workers release these descriptors after executing the operation. SLRU_FLUSH_SYNC is now reported by the I/O worker rather than the checkpointer, as for relation fsyncs. SyncDataDirectory() continues to use PGAIO_TID_SYNC because its files have no FileTag. --- src/backend/access/transam/clog.c | 8 +- src/backend/access/transam/commit_ts.c | 8 +- src/backend/access/transam/multixact.c | 16 +++- src/backend/access/transam/slru.c | 32 ++++++- src/backend/storage/aio/aio_io.c | 8 ++ src/backend/storage/aio/aio_target.c | 36 +++++++ src/backend/storage/sync/sync.c | 125 ++++++++++++++++++++++++- src/include/access/clog.h | 1 + src/include/access/commit_ts.h | 1 + src/include/access/multixact.h | 2 + src/include/access/slru.h | 1 + src/include/storage/aio.h | 13 ++- src/include/storage/aio_internal.h | 1 + src/include/storage/aio_types.h | 14 +++ src/include/storage/sync.h | 19 ++-- src/tools/pgindent/typedefs.list | 1 + 16 files changed, 263 insertions(+), 23 deletions(-) diff --git a/src/backend/access/transam/clog.c b/src/backend/access/transam/clog.c index 89fb77ea5da..0fe0491d877 100644 --- a/src/backend/access/transam/clog.c +++ b/src/backend/access/transam/clog.c @@ -1115,10 +1115,16 @@ clog_redo(XLogReaderState *record) } /* - * Entrypoint for sync.c to sync clog files. + * Entrypoints for sync.c to sync and reopen clog files. */ void clogsyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { SlruSyncFileTag(XactCtl, ioh, entry); } + +int +clogopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(XactCtl, ftag); +} diff --git a/src/backend/access/transam/commit_ts.c b/src/backend/access/transam/commit_ts.c index 7cbbad383b2..4bb95e415ac 100644 --- a/src/backend/access/transam/commit_ts.c +++ b/src/backend/access/transam/commit_ts.c @@ -1026,10 +1026,16 @@ commit_ts_redo(XLogReaderState *record) } /* - * Entrypoint for sync.c to sync commit_ts files. + * Entrypoints for sync.c to sync and reopen commit_ts files. */ void committssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { SlruSyncFileTag(CommitTsCtl, ioh, entry); } + +int +committsopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(CommitTsCtl, ftag); +} diff --git a/src/backend/access/transam/multixact.c b/src/backend/access/transam/multixact.c index deb866cd7f0..11f5f266075 100644 --- a/src/backend/access/transam/multixact.c +++ b/src/backend/access/transam/multixact.c @@ -2996,7 +2996,7 @@ multixact_redo(XLogReaderState *record) } /* - * Entrypoint for sync.c to sync offsets files. + * Entrypoints for sync.c to sync and reopen offsets files. */ void multixactoffsetssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) @@ -3004,11 +3004,23 @@ multixactoffsetssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) SlruSyncFileTag(MultiXactOffsetCtl, ioh, entry); } +int +multixactoffsetsopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(MultiXactOffsetCtl, ftag); +} + /* - * Entrypoint for sync.c to sync members files. + * Entrypoints for sync.c to sync and reopen members files. */ void multixactmemberssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { SlruSyncFileTag(MultiXactMemberCtl, ioh, entry); } + +int +multixactmembersopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(MultiXactMemberCtl, ftag); +} diff --git a/src/backend/access/transam/slru.c b/src/backend/access/transam/slru.c index b1e513ac3b6..8e0d9af16df 100644 --- a/src/backend/access/transam/slru.c +++ b/src/backend/access/transam/slru.c @@ -1897,11 +1897,16 @@ SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, InflightSyncEntry *entry } /* - * Use the generic sync target. SLRU segments are not smgr relations and - * cannot be reopened from a FileTag in another process, so this fsync - * will run synchronously in worker mode. + * If this SLRU is registered with sync.c, identify the file by its + * FileTag, so that the fsync can be executed by an IO worker, which will + * reopen the file with SlruOpenFileTag(). Otherwise there is no handler + * to reopen the file through, so use the generic sync target, whose IOs + * cannot be handed off to a worker. */ - pgaio_io_set_target(ioh, PGAIO_TID_SYNC); + if (ctl->options.sync_handler != SYNC_HANDLER_NONE) + pgaio_io_set_target_sync_filetag(ioh, &entry->tag); + else + pgaio_io_set_target(ioh, PGAIO_TID_SYNC); /* Start the asynchronous fsync; the fd is closed once it completes. */ pgaio_io_start_fsync(ioh, fd, false, WAIT_EVENT_SLRU_FLUSH_SYNC); @@ -1910,3 +1915,22 @@ SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, InflightSyncEntry *entry entry->close_method = SYNC_CLOSE_TRANSIENT; entry->close_file = fd; } + +/* + * Counterpart to SlruSyncFileTag(), opening the segment identified by ftag in + * a process that did not stage the IO. As with SlruSyncFileTag(), individual + * SLRUs have to provide the handler function, so that the correct "SlruCtl" + * is used. + * + * Returns a file descriptor opened with OpenTransientFile(), or -1 with errno + * set. + */ +int +SlruOpenFileTag(SlruDesc *ctl, const FileTag *ftag) +{ + char path[MAXPGPATH]; + + SlruFileName(ctl, path, ftag->segno); + + return OpenTransientFile(path, O_RDWR | PG_BINARY); +} diff --git a/src/backend/storage/aio/aio_io.c b/src/backend/storage/aio/aio_io.c index 324fb6911e2..070a5ff70b3 100644 --- a/src/backend/storage/aio/aio_io.c +++ b/src/backend/storage/aio/aio_io.c @@ -169,6 +169,14 @@ pgaio_io_perform_synchronously(PgAioHandle *ioh) Assert(result <= INT_MAX); ioh->result = result < 0 ? -errno : result; + /* + * If we, rather than the process that staged the IO, opened the file, + * close it again. Has to happen after the result has been determined, as + * closing may clobber errno, and before the completion is processed, as + * that can recycle the handle. + */ + pgaio_io_close_reopened(ioh); + pgaio_io_process_completion(ioh, ioh->result); END_CRIT_SECTION(); diff --git a/src/backend/storage/aio/aio_target.c b/src/backend/storage/aio/aio_target.c index 82b24b0026d..795e8ac7046 100644 --- a/src/backend/storage/aio/aio_target.c +++ b/src/backend/storage/aio/aio_target.c @@ -17,6 +17,7 @@ #include "storage/aio.h" #include "storage/aio_internal.h" #include "storage/smgr.h" +#include "storage/sync.h" static char *pgaio_sync_describe_identity(const PgAioTargetData *sd); @@ -39,8 +40,16 @@ static const PgAioTargetInfo *pgaio_target_info[] = { }, [PGAIO_TID_SMGR] = &aio_smgr_target_info, [PGAIO_TID_SYNC] = &aio_sync_target_info, + [PGAIO_TID_SYNC_FILETAG] = &aio_sync_filetag_target_info, }; +/* + * The IO whose descriptor this process reopened and whose target requires the + * descriptor to be released after execution. Only set between + * pgaio_io_reopen() and pgaio_io_close_reopened(). + */ +static PgAioHandle *pgaio_reopened_ioh = NULL; + /* * describe_identity callback for PGAIO_TID_SYNC. As we do not store the path @@ -141,6 +150,33 @@ pgaio_io_reopen(PgAioHandle *ioh) { Assert(ioh->target > PGAIO_TID_INVALID && ioh->target < PGAIO_TID_COUNT); Assert(ioh->op > PGAIO_OP_INVALID && ioh->op < PGAIO_OP_COUNT); + Assert(pgaio_reopened_ioh == NULL); pgaio_target_info[ioh->target]->reopen(ioh); + + /* + * Remember that this process, rather than the one that staged the IO, + * owns the file descriptor now, so that pgaio_io_close_reopened() can + * release it once the IO has been executed. + */ + if (pgaio_target_info[ioh->target]->close != NULL) + pgaio_reopened_ioh = ioh; +} + +/* + * Internal: Counterpart to pgaio_io_reopen(), releasing the file descriptor it + * acquired. Does nothing unless this process reopened this very IO and its + * target needs the descriptor to be released. + * + * This has to be called before the IO's completion is processed, as that can + * make the handle be reused for an unrelated IO. + */ +void +pgaio_io_close_reopened(PgAioHandle *ioh) +{ + if (pgaio_reopened_ioh != ioh) + return; + + pgaio_reopened_ioh = NULL; + pgaio_target_info[ioh->target]->close(ioh); } diff --git a/src/backend/storage/sync/sync.c b/src/backend/storage/sync/sync.c index 4263881ddd8..35f87793171 100644 --- a/src/backend/storage/sync/sync.c +++ b/src/backend/storage/sync/sync.c @@ -132,9 +132,19 @@ static CycleCtr checkpoint_cycle_ctr = 0; typedef struct SyncOps { void (*sync_syncfiletag) (PgAioHandle *ioh, InflightSyncEntry *entry); + + /* + * Optional. Reopen the file identified by ftag, so that an fsync started + * by sync_syncfiletag() can be executed in a different process, e.g. an + * IO worker. Returns a file descriptor opened with OpenTransientFile(), + * or -1 with errno set. Handlers that provide this must use the + * PGAIO_TID_SYNC_FILETAG target (see pgaio_io_set_target_sync_filetag()). + */ + int (*sync_openfiletag) (const FileTag *ftag); int (*sync_unlinkfiletag) (const FileTag *ftag, char *path); bool (*sync_filetagmatches) (const FileTag *ftag, const FileTag *candidate); + const char *sync_target_name; } SyncOps; /* @@ -149,22 +159,129 @@ static const SyncOps syncsw[] = { }, /* pg_xact */ [SYNC_HANDLER_CLOG] = { - .sync_syncfiletag = clogsyncfiletag + .sync_syncfiletag = clogsyncfiletag, + .sync_openfiletag = clogopenfiletag, + .sync_target_name = "pg_xact" }, /* pg_commit_ts */ [SYNC_HANDLER_COMMIT_TS] = { - .sync_syncfiletag = committssyncfiletag + .sync_syncfiletag = committssyncfiletag, + .sync_openfiletag = committsopenfiletag, + .sync_target_name = "pg_commit_ts" }, /* pg_multixact/offsets */ [SYNC_HANDLER_MULTIXACT_OFFSET] = { - .sync_syncfiletag = multixactoffsetssyncfiletag + .sync_syncfiletag = multixactoffsetssyncfiletag, + .sync_openfiletag = multixactoffsetsopenfiletag, + .sync_target_name = "pg_multixact/offsets" }, /* pg_multixact/members */ [SYNC_HANDLER_MULTIXACT_MEMBER] = { - .sync_syncfiletag = multixactmemberssyncfiletag + .sync_syncfiletag = multixactmemberssyncfiletag, + .sync_openfiletag = multixactmembersopenfiletag, + .sync_target_name = "pg_multixact/members" } }; +static void sync_aio_reopen(PgAioHandle *ioh); +static void sync_aio_close(PgAioHandle *ioh); +static char *sync_aio_describe_identity(const PgAioTargetData *sd); + +/* + * Target info for files identified by a FileTag (see PGAIO_TID_SYNC_FILETAG). + * Unlike PGAIO_TID_SYNC, a FileTag contains everything needed to find the + * file again in another process, so such IOs can be executed by IO workers. + */ +const PgAioTargetInfo aio_sync_filetag_target_info = { + .name = "sync_filetag", + .reopen = sync_aio_reopen, + .close = sync_aio_close, + .describe_identity = sync_aio_describe_identity, +}; + +/* + * Set up ioh to operate on the file identified by ftag. + */ +void +pgaio_io_set_target_sync_filetag(PgAioHandle *ioh, const FileTag *ftag) +{ + PgAioTargetData *sd = pgaio_io_get_target_data(ioh); + + Assert(syncsw[ftag->handler].sync_openfiletag != NULL); + Assert(syncsw[ftag->handler].sync_target_name != NULL); + + pgaio_io_set_target(ioh, PGAIO_TID_SYNC_FILETAG); + + sd->sync_filetag = *ftag; +} + +static FileTag +sync_aio_filetag(const PgAioTargetData *sd) +{ + return sd->sync_filetag; +} + +/* + * reopen callback for PGAIO_TID_SYNC_FILETAG, to open the file in the process + * executing the IO. + */ +static void +sync_aio_reopen(PgAioHandle *ioh) +{ + PgAioTargetData *sd = pgaio_io_get_target_data(ioh); + PgAioOpData *od = pgaio_io_get_op_data(ioh); + FileTag ftag = sync_aio_filetag(sd); + int fd; + + /* + * The caller needs to prevent interrupts from being processed, otherwise + * the FD could be closed again before we get to executing the IO. + */ + Assert(!INTERRUPTS_CAN_BE_PROCESSED()); + + Assert(pgaio_io_get_op(ioh) == PGAIO_OP_FSYNC); + + fd = syncsw[ftag.handler].sync_openfiletag(&ftag); + if (fd < 0) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not open segment " UINT64_FORMAT " of SLRU \"%s\": %m", + ftag.segno, + syncsw[ftag.handler].sync_target_name))); + + od->fsync.fd = fd; +} + +/* + * close callback for PGAIO_TID_SYNC_FILETAG, releasing the descriptor + * acquired by sync_aio_reopen(). + * + * Called in a critical section, so a failure to close cannot be reported. + * That is not a meaningful loss: the data has already been flushed by the + * fsync, and the descriptor is not written to. + */ +static void +sync_aio_close(PgAioHandle *ioh) +{ + PgAioOpData *od = pgaio_io_get_op_data(ioh); + + (void) CloseTransientFile(od->fsync.fd); + od->fsync.fd = -1; +} + +/* + * describe_identity callback for PGAIO_TID_SYNC_FILETAG. + */ +static char * +sync_aio_describe_identity(const PgAioTargetData *sd) +{ + FileTag ftag = sync_aio_filetag(sd); + + return psprintf(_("segment " UINT64_FORMAT " of SLRU \"%s\""), + ftag.segno, + syncsw[ftag.handler].sync_target_name); +} + /* * Initialize data structures for the file sync tracking. */ diff --git a/src/include/access/clog.h b/src/include/access/clog.h index e089106f7fe..fc06794d186 100644 --- a/src/include/access/clog.h +++ b/src/include/access/clog.h @@ -48,6 +48,7 @@ extern void ExtendCLOG(TransactionId newestXact); extern void TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid); extern void clogsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int clogopenfiletag(const FileTag *ftag); /* XLOG stuff */ #define CLOG_ZEROPAGE 0x00 diff --git a/src/include/access/commit_ts.h b/src/include/access/commit_ts.h index fa4880e0d03..ebb87d9534e 100644 --- a/src/include/access/commit_ts.h +++ b/src/include/access/commit_ts.h @@ -39,6 +39,7 @@ extern void SetCommitTsLimit(TransactionId oldestXact, extern void AdvanceOldestCommitTsXid(TransactionId oldestXact); extern void committssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int committsopenfiletag(const FileTag *ftag); /* XLOG stuff */ #define COMMIT_TS_ZEROPAGE 0x00 diff --git a/src/include/access/multixact.h b/src/include/access/multixact.h index 3f980b4120d..3f5233a3bcd 100644 --- a/src/include/access/multixact.h +++ b/src/include/access/multixact.h @@ -115,7 +115,9 @@ extern bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2); extern void multixactoffsetssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int multixactoffsetsopenfiletag(const FileTag *ftag); extern void multixactmemberssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int multixactmembersopenfiletag(const FileTag *ftag); extern void AtEOXact_MultiXact(void); extern void AtPrepare_MultiXact(void); diff --git a/src/include/access/slru.h b/src/include/access/slru.h index 0e91df5609c..43429392c7d 100644 --- a/src/include/access/slru.h +++ b/src/include/access/slru.h @@ -241,6 +241,7 @@ extern bool SlruScanDirectory(SlruDesc *ctl, SlruScanCallback callback, void *da extern void SlruDeleteSegment(SlruDesc *ctl, int64 segno); extern void SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, struct InflightSyncEntry *entry); +extern int SlruOpenFileTag(SlruDesc *ctl, const FileTag *ftag); /* SlruScanDirectory public callbacks */ extern bool SlruScanDirCbReportPresence(SlruDesc *ctl, char *filename, diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index 428504c0472..904ab185458 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -119,9 +119,10 @@ typedef enum PgAioTargetID PGAIO_TID_INVALID = 0, PGAIO_TID_SMGR, PGAIO_TID_SYNC, + PGAIO_TID_SYNC_FILETAG, } PgAioTargetID; -#define PGAIO_TID_COUNT (PGAIO_TID_SYNC + 1) +#define PGAIO_TID_COUNT (PGAIO_TID_SYNC_FILETAG + 1) /* @@ -171,6 +172,16 @@ struct PgAioTargetInfo */ void (*reopen) (PgAioHandle *ioh); + /* + * Optional counterpart to reopen, releasing the file descriptor it + * acquired. Called in the process that reopened the IO, after the IO has + * been executed. Targets whose reopen callback hands out a descriptor + * that is cached and reused, like smgr's, do not need this. + * + * This is called in a critical section, so it must not raise errors. + */ + void (*close) (PgAioHandle *ioh); + /* describe the target of the IO, used for log messages and views */ char *(*describe_identity) (const PgAioTargetData *sd); diff --git a/src/include/storage/aio_internal.h b/src/include/storage/aio_internal.h index 9ca4087aa7f..9d2e92c6538 100644 --- a/src/include/storage/aio_internal.h +++ b/src/include/storage/aio_internal.h @@ -360,6 +360,7 @@ extern int pgaio_io_get_iovec_length(PgAioHandle *ioh, struct iovec **iov); /* aio_target.c */ extern bool pgaio_io_can_reopen(PgAioHandle *ioh); extern void pgaio_io_reopen(PgAioHandle *ioh); +extern void pgaio_io_close_reopened(PgAioHandle *ioh); extern const char *pgaio_io_get_target_name(PgAioHandle *ioh); diff --git a/src/include/storage/aio_types.h b/src/include/storage/aio_types.h index 17b59aeed7c..90bc4c73989 100644 --- a/src/include/storage/aio_types.h +++ b/src/include/storage/aio_types.h @@ -23,6 +23,18 @@ typedef struct PgAioHandle PgAioHandle; typedef struct PgAioHandleCallbacks PgAioHandleCallbacks; typedef struct PgAioTargetInfo PgAioTargetInfo; +/* + * A tag identifying a file handled by sync.c. This is defined here so that + * PgAioTargetData can store it without duplicating its representation. + */ +typedef struct PgAioSyncFileTag +{ + int16 handler; /* SyncRequestHandler value */ + int16 forknum; /* ForkNumber */ + RelFileLocator rlocator; /* physical relation identifier */ + uint64 segno; +} PgAioSyncFileTag; + /* * A reference to an IO that can be used to wait for the IO (using * pgaio_wref_wait()) to complete. @@ -69,6 +81,8 @@ typedef union PgAioTargetData bool is_temp:1; /* proc can be inferred by owning AIO */ bool skip_fsync:1; } smgr; + + PgAioSyncFileTag sync_filetag; } PgAioTargetData; diff --git a/src/include/storage/sync.h b/src/include/storage/sync.h index a72ce4c3fd3..4a2cca50703 100644 --- a/src/include/storage/sync.h +++ b/src/include/storage/sync.h @@ -46,17 +46,11 @@ typedef enum SyncRequestHandler } SyncRequestHandler; /* - * A tag identifying a file. Currently it has the members required for md.c's - * usage, but sync.c has no knowledge of the internal structure, and it is - * liable to change as required by future handlers. + * A tag identifying a file. Its representation is shared with AIO target + * data, so changes are automatically visible to processes that reopen files + * on behalf of sync.c. */ -typedef struct FileTag -{ - int16 handler; /* SyncRequestHandler value, saving space */ - int16 forknum; /* ForkNumber, saving space */ - RelFileLocator rlocator; - uint64 segno; -} FileTag; +typedef PgAioSyncFileTag FileTag; struct PendingFsyncEntry; struct PgAioHandle; @@ -119,4 +113,9 @@ extern void RememberSyncRequest(const FileTag *ftag, SyncRequestType type); extern bool RegisterSyncRequest(const FileTag *ftag, SyncRequestType type, bool retryOnError); +/* AIO support */ +extern PGDLLIMPORT const PgAioTargetInfo aio_sync_filetag_target_info; +extern void pgaio_io_set_target_sync_filetag(PgAioHandle *ioh, + const FileTag *ftag); + #endif /* SYNC_H */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 4fd08012e1b..0812aae6793 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2285,6 +2285,7 @@ PgAioOpData PgAioResult PgAioResultStatus PgAioReturn +PgAioSyncFileTag PgAioTargetData PgAioTargetID PgAioTargetInfo -- 2.47.3
benchmark-repro.sh (application/x-shellscript, 3.6K) download ^ permalink raw reply [nested|flat] 9+ messages in thread

* Re: aio: Async fsyncs for crash recovery and checkpointer
@ 2026-08-31 15:19  Nitin Jadhav <nitinjadhavpostgres@gmail.com>
  parent: Nazir Bilal Yavuz <byavuz81@gmail.com>
  0 siblings, 1 reply; 9+ messages in thread

From: Nitin Jadhav @ 2026-08-31 15:19 UTC (permalink / raw)
  To: Nazir Bilal Yavuz <byavuz81@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Andres Freund <andres@anarazel.de>

Hi Nazir!

Thanks for working on this. The overall direction looks promising and
the patch splits are easy to follow. I reviewed the v1 series and
found a few issues/questions.

pg_stat_io.fsync_time no longer measures fsync wait time. In
mdsyncfiletag(), the time attributed to IOOP_FSYNC is measured around
FileStartSync(). With io_method=worker or io_method=io_uring,
FileStartSync() generally returns after submitting the operation,
before the fsync has completed. As a result, pg_stat_io.fsync_time
records mostly submission overhead rather than time spent waiting for
the fsync. This appears inconsistent with the documented meaning of
fsync_time, which is "time spent waiting for fsync operations." It
also makes the statistic method-dependent - synchronous execution
includes the fsync itself, while worker and io_uring execution
generally do not. A synchronous fallback under the worker method would
change the semantics. Should the timing instead be accounted when
completion is observed or the request is reaped? Alternatively, if
asynchronous fsyncs require different accounting semantics, should
those semantics be explicitly defined and documented?

SLRU reopen errors terminate I/O workers and lose the original errno.
sync_aio_reopen()  raises  ERROR if an I/O worker cannot reopen an
SLRU segment. The worker’s exception-recovery path completes every
reopen failure as  ENOENT. An ENOENT here can be an expected race -
the SLRU segment may have been truncated after the fsync was submitted
but before the worker reopened it. ProcessSyncRequests()  already has
cancellation and FILE_POSSIBLY_DELETED() handling for this case.
However, before that logic sees the result, the I/O worker has emitted
an error and exited. Repeated SLRU truncation concurrent with
checkpoints could therefore cause unnecessary logging and worker
churn. There is also an errno-preservation issue. Failures such as
EACCES, EMFILE, or EIO are delivered to the issuing process as ENOENT.
The worker’s initial error report may contain the original  %m , but
the AIO completion result does not. The checkpointer may consequently
treat the first failure as a possible deletion race and retry it, then
eventually report a misleading “No such file or directory” error.
Could the reopen interface return an errno for ordinary open failures
instead of raising  ERROR ? The worker could complete the request with
-errno and continue processing. That would preserve the actual error,
allow the existing cancellation/retry logic to handle ENOENT, and
reserve worker termination for genuinely unexpected failures.

The new worker-side SLRU target does not appear to be covered by the
test. The updated  test_slru_page_sync()  test uses ".sync_handler =
SYNC_HANDLER_NONE". That causes  SlruSyncFileTag()  to select
PGAIO_TID_SYNC  rather than  PGAIO_TID_SYNC_FILETAG. Since
PGAIO_TID_SYNC has no reopen callback,  io_method=worker  executes
this request synchronously in the submitting process instead of
handing it to an I/O worker. The test therefore covers the refactored
local fsync path, but not the main path introduced by patch 0004.
Could we add a TAP test to cover this?

Best Regards,
Nitin Jadhav
Azure Database for PostgreSQL
Microsoft






^ permalink  raw  reply  [nested|flat] 9+ messages in thread

* Re: aio: Async fsyncs for crash recovery and checkpointer
@ 2026-09-01 11:50  Nazir Bilal Yavuz <byavuz81@gmail.com>
  parent: Nitin Jadhav <nitinjadhavpostgres@gmail.com>
  0 siblings, 1 reply; 9+ messages in thread

From: Nazir Bilal Yavuz @ 2026-09-01 11:50 UTC (permalink / raw)
  To: Nitin Jadhav <nitinjadhavpostgres@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Andres Freund <andres@anarazel.de>

Hi Nitin,

On Mon, 31 Aug 2026 at 18:20, Nitin Jadhav
<nitinjadhavpostgres@gmail.com> wrote:
>
> Thanks for working on this. The overall direction looks promising and
> the patch splits are easy to follow. I reviewed the v1 series and
> found a few issues/questions.

Thank you for looking into this!


> pg_stat_io.fsync_time no longer measures fsync wait time. In
> mdsyncfiletag(), the time attributed to IOOP_FSYNC is measured around
> FileStartSync(). With io_method=worker or io_method=io_uring,
> FileStartSync() generally returns after submitting the operation,
> before the fsync has completed. As a result, pg_stat_io.fsync_time
> records mostly submission overhead rather than time spent waiting for
> the fsync. This appears inconsistent with the documented meaning of
> fsync_time, which is "time spent waiting for fsync operations." It
> also makes the statistic method-dependent - synchronous execution
> includes the fsync itself, while worker and io_uring execution
> generally do not. A synchronous fallback under the worker method would
> change the semantics. Should the timing instead be accounted when
> completion is observed or the request is reaped? Alternatively, if
> asynchronous fsyncs require different accounting semantics, should
> those semantics be explicitly defined and documented?

Yes, you are right. We can copy the timing calculation used for async
read I/Os. So, it means that total time of fsyncs will be submission
of I/O + wait time for pgaio_wref_wait() in the drain() functions. If
we do that, we don't need to change documentation because this will
represent the total "time spent waiting for fsync operations."
regardless of io_method.


> SLRU reopen errors terminate I/O workers and lose the original errno.
> sync_aio_reopen()  raises  ERROR if an I/O worker cannot reopen an
> SLRU segment. The worker’s exception-recovery path completes every
> reopen failure as  ENOENT. An ENOENT here can be an expected race -
> the SLRU segment may have been truncated after the fsync was submitted
> but before the worker reopened it. ProcessSyncRequests()  already has
> cancellation and FILE_POSSIBLY_DELETED() handling for this case.
> However, before that logic sees the result, the I/O worker has emitted
> an error and exited. Repeated SLRU truncation concurrent with
> checkpoints could therefore cause unnecessary logging and worker
> churn. There is also an errno-preservation issue. Failures such as
> EACCES, EMFILE, or EIO are delivered to the issuing process as ENOENT.
> The worker’s initial error report may contain the original  %m , but
> the AIO completion result does not. The checkpointer may consequently
> treat the first failure as a possible deletion race and retry it, then
> eventually report a misleading “No such file or directory” error.
> Could the reopen interface return an errno for ordinary open failures
> instead of raising  ERROR ? The worker could complete the request with
> -errno and continue processing. That would preserve the actual error,
> allow the existing cancellation/retry logic to handle ENOENT, and
> reserve worker termination for genuinely unexpected failures.

Yes, this is a valid problem. Thank you for the detailed explanation.
I will change the reopen interface so that ordinary failures return
-errno. The I/O worker can then complete the request and continue
processing, while errors raised for unexpected failures will retain
the existing worker-termination path.


> The new worker-side SLRU target does not appear to be covered by the
> test. The updated  test_slru_page_sync()  test uses ".sync_handler =
> SYNC_HANDLER_NONE". That causes  SlruSyncFileTag()  to select
> PGAIO_TID_SYNC  rather than  PGAIO_TID_SYNC_FILETAG. Since
> PGAIO_TID_SYNC has no reopen callback,  io_method=worker  executes
> this request synchronously in the submitting process instead of
> handing it to an I/O worker. The test therefore covers the refactored
> local fsync path, but not the main path introduced by patch 0004.
> Could we add a TAP test to cover this?

You are right. However, I think what needs to be done is having a
general AIO fsync tests (which will cover the path you mentioned too)
in the test_aio test suite. I will try to implement it in the v2.

-- 
Regards,
Nazir Bilal Yavuz
Microsoft






^ permalink  raw  reply  [nested|flat] 9+ messages in thread

* Re: aio: Async fsyncs for crash recovery and checkpointer
@ 2026-09-03 13:15  Yuhang Qiu <iamqyh@gmail.com>
  parent: Nazir Bilal Yavuz <byavuz81@gmail.com>
  0 siblings, 1 reply; 9+ messages in thread

From: Yuhang Qiu @ 2026-09-03 13:15 UTC (permalink / raw)
  To: Nazir Bilal Yavuz <byavuz81@gmail.com>; +Cc: Nitin Jadhav <nitinjadhavpostgres@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Andres Freund <andres@anarazel.de>

Hi Nazir,

The overall direction looks good to me. A few points:

> This patch implements async fsyncs for crash recovery and checkpoints by
> using the AIO system.

For crash recovery, Linux already has `recovery_init_sync_method=syncfs` as an
alternative to per-file fsyncs. I think it would be useful to include that in
the `SyncDataDirectory()` benchmark.

> I will change the reopen interface so that ordinary failures return
> `-errno`.

Agreed. I think all AIO target reopen callbacks should follow this convention.
Relation fsyncs can hit the same problem through `smgr_aio_reopen()`, not only
SLRUs.

> It uses both io_max_concurrency and the file descriptor budget to determine
> max number of available in-flight fsync I/Os.

I wonder whether submitting a batch of concurrent fsyncs could cause an I/O
storm and hurt foreground I/O latency.

The `max_safe_fds / 6` cap protects the `AllocateDesc` budget used by
`OpenTransientFile()`, while relation fsyncs use VFDs. Should the descriptor
cap apply only to handlers that use `OpenTransientFile()`?

Best regards,
Yuhang Qiu







^ permalink  raw  reply  [nested|flat] 9+ messages in thread

* Re: aio: Async fsyncs for crash recovery and checkpointer
@ 2026-09-18 10:54  Nazir Bilal Yavuz <byavuz81@gmail.com>
  parent: Yuhang Qiu <iamqyh@gmail.com>
  0 siblings, 1 reply; 9+ messages in thread

From: Nazir Bilal Yavuz @ 2026-09-18 10:54 UTC (permalink / raw)
  To: Yuhang Qiu <iamqyh@gmail.com>; +Cc: Nitin Jadhav <nitinjadhavpostgres@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Andres Freund <andres@anarazel.de>

Hi,

Thank you for looking into this!

On Thu, 3 Sept 2026 at 16:15, Yuhang Qiu <iamqyh@gmail.com> wrote:
>
> The overall direction looks good to me. A few points:
>
> > This patch implements async fsyncs for crash recovery and checkpoints by
> > using the AIO system.
>
> For crash recovery, Linux already has `recovery_init_sync_method=syncfs` as an
> alternative to per-file fsyncs. I think it would be useful to include that in
> the `SyncDataDirectory()` benchmark.

Good point. I tested recovery_init_sync_method=syncfs and it seems it
is better than or on par with fsync and AIO. Here are two different
benchmark results:

io_method  | recovery_init_sync_method |         startup (ms) |         speedup
-----------+---------------------------+----------------------+----------------
sync       | fsync                     |                609.4 |           1.00x
worker     | fsync                     |                610.8 |           1.00x
io_uring   | fsync                     |                308.6 |           1.97x
sync       | syncfs                    |                210.7 |           2.89x

io_method  | recovery_init_sync_method |         startup (ms) |         speedup
-----------+---------------------------+----------------------+----------------
sync       | fsync                     |                609.2 |           1.00x
worker     | fsync                     |                610.0 |           1.00x
io_uring   | fsync                     |                211.0 |           2.89x
sync       | syncfs                    |                209.0 |           2.91x


> > I will change the reopen interface so that ordinary failures return
> > `-errno`.
>
> Agreed. I think all AIO target reopen callbacks should follow this convention.
> Relation fsyncs can hit the same problem through `smgr_aio_reopen()`, not only
> SLRUs.

I played with that a bit but there were some problems; it was more
complicated than I thought. If we want to return -errno, we lose quite
a bit of error information because we don't reach the actual error
message. We short-circuit these error messages to return -errno and
continue without terminating the worker process.

For now, ordinary reopen failures for both relation and SLRU fsyncs
return -errno. This allows the checkpointer to apply its cancellation,
retry, and error-handling policy without terminating the I/O worker.
Read and write IO reopening retains its existing error handling. I
will continue working to improve this.


> > It uses both io_max_concurrency and the file descriptor budget to determine
> > max number of available in-flight fsync I/Os.
>
> I wonder whether submitting a batch of concurrent fsyncs could cause an I/O
> storm and hurt foreground I/O latency.

I think this is a valid concern. With io_method=worker, fsyncs also
share the worker pool with reads so that could cause a performance
problems. However, I think increasing the number of worker processes
should solve this problem.


> The `max_safe_fds / 6` cap protects the `AllocateDesc` budget used by
> `OpenTransientFile()`, while relation fsyncs use VFDs. Should the descriptor
> cap apply only to handlers that use `OpenTransientFile()`?

Done. Relation fsync requests now use io_max_concurrency as their
limit. For handlers that hold transient descriptors in the
issuingprocess, the limit is also capped at max_safe_fds / 6.


Here are some additional updates compared to v1:

- 0001 enables fsync on tests so CI will run tests with fsync enabled.

- 0002 clears SMGR caches for the worker processes. These caches are
created on the smgr_reopen path and not get destroyed later so these
remain for the lifetime of worker processes. Patch clears the SMGR
cache after a checkpoint and when the worker is not busy. I created
another thread for this [1].

- 0005 for reopen error changes.

- 0008 is for doc changes.

I am still working on the tests; no tests are included yet.


[1] https://postgr.es/m/CAN55FZ2BesKUnajdgpw1fPSe3S6_CHOugryaUEtD7vdP%3DdRKEQ%40mail.gmail.com

--
Regards,
Nazir Bilal Yavuz
Microsoft

Attachments: download all (8 files, .tar.gz)

v2-0001-ci-Temporarily-enable-fsync-everywhere.patch (text/x-patch, 2.1K) download From 1e8086153347e3a35fc2997632791153e1c36032 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Fri, 4 Sep 2026 17:21:51 +0300 Subject: [PATCH v2 1/8] ci: Temporarily enable fsync everywhere To test AIO fsync support patches. Not submitted for commit. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- .github/workflows/pg-ci.yml | 2 +- src/test/ssl/t/SSL/Server.pm | 1 - src/tools/ci/pg_ci_base.conf | 3 +++ 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pg-ci.yml b/.github/workflows/pg-ci.yml index a2629c8335a..c0019a1f91f 100644 --- a/.github/workflows/pg-ci.yml +++ b/.github/workflows/pg-ci.yml @@ -608,7 +608,7 @@ jobs: # Log into a place that will be archived in case of failure mkdir -p build/testrun - build/tmp_install/usr/local/pgsql/bin/pg_ctl -c -o '-c fsync=off' -D build/runningcheck -l build/testrun/runningcheck.log start + build/tmp_install/usr/local/pgsql/bin/pg_ctl -c -D build/runningcheck -l build/testrun/runningcheck.log start # Run the tests supporting running against an already running meson test ${{env.MTEST_ARGS}} --num-processes ${{env.TEST_JOBS}} --setup running diff --git a/src/test/ssl/t/SSL/Server.pm b/src/test/ssl/t/SSL/Server.pm index 4400a432f42..d5e723d156f 100644 --- a/src/test/ssl/t/SSL/Server.pm +++ b/src/test/ssl/t/SSL/Server.pm @@ -199,7 +199,6 @@ sub configure_test_server_for_ssl # enable logging etc. $node->append_conf( 'postgresql.conf', <<EOF -fsync=off log_connections=all log_hostname=on listen_addresses='$serverhost' diff --git a/src/tools/ci/pg_ci_base.conf b/src/tools/ci/pg_ci_base.conf index ff05646c90e..b96bd4a4786 100644 --- a/src/tools/ci/pg_ci_base.conf +++ b/src/tools/ci/pg_ci_base.conf @@ -5,6 +5,9 @@ restart_after_crash = false # prepared statements max_prepared_transactions = 10 +# Exercise fsync code paths in CI +fsync = on + # Settings that make logs more useful log_autovacuum_min_duration = 0 log_autoanalyze_min_duration = 0 -- 2.47.3
v2-0002-aio-worker-Free-SMGR-objects-when-idle.patch (text/x-patch, 2.1K) download From a23ddf32574cb7a7e391c31f11c94204bb3bdb15 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Fri, 18 Sep 2026 10:17:23 +0300 Subject: [PATCH v2 2/8] aio: worker: Free SMGR objects when idle IO workers create SMGR objects when reopening relations, but don't have a transaction-end cleanup to destroy them. Long-lived workers can therefore retain entries for an increasing number of relations, including dropped ones. Destroy these objects when when a completed checkpoint is observed and when the worker is idle. At this point no borrowed descriptors or SMGR references remain in use. Discussion: https://postgr.es/m/CAN55FZ2BesKUnajdgpw1fPSe3S6_CHOugryaUEtD7vdP%3DdRKEQ%40mail.gmail.com --- src/backend/storage/aio/method_worker.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/backend/storage/aio/method_worker.c b/src/backend/storage/aio/method_worker.c index cf75b2816b7..7639d093677 100644 --- a/src/backend/storage/aio/method_worker.c +++ b/src/backend/storage/aio/method_worker.c @@ -34,6 +34,7 @@ #include "miscadmin.h" #include "port/pg_bitutils.h" #include "postmaster/auxprocess.h" +#include "postmaster/bgwriter.h" #include "postmaster/interrupt.h" #include "storage/aio.h" #include "storage/aio_internal.h" @@ -45,6 +46,7 @@ #include "storage/pmsignal.h" #include "storage/proc.h" #include "storage/shmem.h" +#include "storage/smgr.h" #include "tcop/tcopprot.h" #include "utils/injection_point.h" #include "utils/memdebug.h" @@ -962,6 +964,16 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len) /* Cancel new worker request if pending. */ pgaio_worker_cancel_grow(); + /* + * Like the background writer, IO workers don't have a + * transaction-end cleanup to destroy SMGR objects, so do that + * when idle after a checkpoint. Any IO has completed and its + * error context has been cleared here, so no borrowed file + * descriptors or SMGR references remain in use. + */ + if (FirstCallSinceLastCheckpoint()) + smgrdestroyall(); + /* Compute the remaining allowed idle time. */ if (io_worker_idle_timeout == -1) { -- 2.47.3
v2-0003-aio-Add-fsync-support.patch (text/x-patch, 6.1K) download From 4c1437b6e7ffa37880ec1b7c1a0ac49fc8ff16d5 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 9 Sep 2026 15:39:57 +0300 Subject: [PATCH v2 3/8] aio: Add fsync support The AIO subsystem currently supports only reads and writes (writes are not used yet). Add PGAIO_OP_FSYNC so callers can submit fsync() and fdatasync() operations through AIO. This allows callers such as the checkpointer to keep multiple syncs in flight instead of waiting for each one in turn. Let callers select the wait event because fsync targets can represent different kinds of files. The process that performs the operation reports that event; io_uring uses the generic AIO wait events because the kernel performs the operation. (Also see [1]) No callers are converted in this commit; subsequent commits do that. [1] https://postgr.es/m/CAN55FZ0Rp+94rdQ-zeTX0sF9H1e4uWZxH8r1cVXZX0swfqww3g@mail.gmail.com Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- src/backend/storage/aio/aio_funcs.c | 4 +++ src/backend/storage/aio/aio_io.c | 31 +++++++++++++++++++++++ src/backend/storage/aio/method_io_uring.c | 6 +++++ src/backend/storage/smgr/smgr.c | 3 +++ src/include/storage/aio.h | 14 ++++++++-- 5 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/backend/storage/aio/aio_funcs.c b/src/backend/storage/aio/aio_funcs.c index bcdd82318f7..2719556e858 100644 --- a/src/backend/storage/aio/aio_funcs.c +++ b/src/backend/storage/aio/aio_funcs.c @@ -191,6 +191,10 @@ retry: values[6] = Int64GetDatum(iov_byte_length(iov_copy, ioh_copy.op_data.write.iov_length)); break; + case PGAIO_OP_FSYNC: + nulls[5] = true; + nulls[6] = true; + break; } /* column: IO's target */ diff --git a/src/backend/storage/aio/aio_io.c b/src/backend/storage/aio/aio_io.c index 132868130e7..0525643cc2b 100644 --- a/src/backend/storage/aio/aio_io.c +++ b/src/backend/storage/aio/aio_io.c @@ -100,6 +100,23 @@ pgaio_io_start_writev(PgAioHandle *ioh, pgaio_io_stage(ioh, PGAIO_OP_WRITEV); } +void +pgaio_io_start_fsync(PgAioHandle *ioh, + int fd, bool datasync, uint32 wait_event_info) +{ + pgaio_io_before_start(ioh); + + ioh->op_data.fsync.fd = fd; + ioh->op_data.fsync.datasync = datasync; + ioh->op_data.fsync.wait_event_info = wait_event_info; + + /* Let the synchronous implementation skip the syscall when fsync is off. */ + if (!enableFsync) + pgaio_io_set_flag(ioh, PGAIO_HF_SYNCHRONOUS); + + pgaio_io_stage(ioh, PGAIO_OP_FSYNC); +} + /* -------------------------------------------------------------------------------- @@ -137,6 +154,14 @@ pgaio_io_perform_synchronously(PgAioHandle *ioh) ioh->op_data.write.offset); pgstat_report_wait_end(); break; + case PGAIO_OP_FSYNC: + pgstat_report_wait_start(ioh->op_data.fsync.wait_event_info); + if (ioh->op_data.fsync.datasync) + result = pg_fdatasync(ioh->op_data.fsync.fd); + else + result = pg_fsync(ioh->op_data.fsync.fd); + pgstat_report_wait_end(); + break; case PGAIO_OP_INVALID: elog(ERROR, "trying to execute invalid IO operation"); } @@ -189,6 +214,8 @@ pgaio_io_get_op_name(PgAioHandle *ioh) return "readv"; case PGAIO_OP_WRITEV: return "writev"; + case PGAIO_OP_FSYNC: + return "fsync"; } return NULL; /* silence compiler */ @@ -209,6 +236,8 @@ pgaio_io_uses_fd(PgAioHandle *ioh, int fd) return ioh->op_data.read.fd == fd; case PGAIO_OP_WRITEV: return ioh->op_data.write.fd == fd; + case PGAIO_OP_FSYNC: + return ioh->op_data.fsync.fd == fd; case PGAIO_OP_INVALID: return false; } @@ -233,6 +262,8 @@ pgaio_io_get_iovec_length(PgAioHandle *ioh, struct iovec **iov) return ioh->op_data.read.iov_length; case PGAIO_OP_WRITEV: return ioh->op_data.write.iov_length; + case PGAIO_OP_FSYNC: + return 0; default: pg_unreachable(); return 0; diff --git a/src/backend/storage/aio/method_io_uring.c b/src/backend/storage/aio/method_io_uring.c index 3ffe5061a20..675a91fb5f7 100644 --- a/src/backend/storage/aio/method_io_uring.c +++ b/src/backend/storage/aio/method_io_uring.c @@ -802,6 +802,12 @@ pgaio_uring_sq_from_io(PgAioHandle *ioh, struct io_uring_sqe *sqe) break; + case PGAIO_OP_FSYNC: + io_uring_prep_fsync(sqe, + ioh->op_data.fsync.fd, + ioh->op_data.fsync.datasync ? IORING_FSYNC_DATASYNC : 0); + break; + case PGAIO_OP_INVALID: elog(ERROR, "trying to prepare invalid IO operation for execution"); } diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c index 5391640d861..69e61ea1661 100644 --- a/src/backend/storage/smgr/smgr.c +++ b/src/backend/storage/smgr/smgr.c @@ -1094,6 +1094,9 @@ smgr_aio_reopen(PgAioHandle *ioh) od->write.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); Assert(off == od->write.offset); break; + case PGAIO_OP_FSYNC: + od->fsync.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); + break; } } diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index ec543b78409..a1d5f49e51a 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -91,10 +91,10 @@ typedef enum PgAioOp PGAIO_OP_READV, PGAIO_OP_WRITEV, + PGAIO_OP_FSYNC, /** * In the near term we'll need at least: - * - fsync / fdatasync * - flush_range * * Eventually we'll additionally want at least: @@ -104,7 +104,7 @@ typedef enum PgAioOp **/ } PgAioOp; -#define PGAIO_OP_COUNT (PGAIO_OP_WRITEV + 1) +#define PGAIO_OP_COUNT (PGAIO_OP_FSYNC + 1) /* @@ -146,6 +146,13 @@ typedef union uint16 iov_length; uint64 offset; } write; + + struct + { + int fd; + bool datasync; + uint32 wait_event_info; + } fsync; } PgAioOpData; @@ -300,6 +307,9 @@ extern void pgaio_io_start_readv(PgAioHandle *ioh, int fd, int iovcnt, uint64 offset); extern void pgaio_io_start_writev(PgAioHandle *ioh, int fd, int iovcnt, uint64 offset); +extern void pgaio_io_start_fsync(PgAioHandle *ioh, int fd, bool datasync, + uint32 wait_event_info); + /* functions in aio_target.c */ extern void pgaio_io_set_target(PgAioHandle *ioh, PgAioTargetID targetid); -- 2.47.3
v2-0004-aio-Issue-SyncDataDirectory-fsyncs-through-AIO.patch (text/x-patch, 18.9K) download From 52ed054573f2c744ea029391b3fe68d5683abe66 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 16 Sep 2026 10:43:11 +0300 Subject: [PATCH v2 4/8] aio: Issue SyncDataDirectory() fsyncs through AIO After a crash, the startup process fsyncs every file in the data directory serially. Submit the fsyncs through AIO and keep a bounded ring of operations in flight. Each operation holds a transient file descriptor, while the directory walk needs descriptors of its own. Limit the ring with GetFsyncConcurrencyLimit() and wait before opening the next file to avoid exhausting the descriptor reserve. The files are identified by paths held only in the startup process. PGAIO_TID_SYNC does not copy those paths into shared memory, so the worker method cannot reopen the files and executes the fsyncs synchronously in the startup process. The io_uring method can execute them concurrently. Storing MAXPGPATH bytes in every AIO target does not seem justified for this startup-only operation. Use the DATA_DIR_SYNC wait event when an fsync is executed synchronously. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- src/backend/storage/aio/aio_target.c | 24 ++ src/backend/storage/file/fd.c | 275 +++++++++++++++--- .../utils/activity/wait_event_names.txt | 1 + src/include/storage/aio.h | 3 +- src/include/storage/fd.h | 1 + src/tools/pgindent/typedefs.list | 2 + 6 files changed, 263 insertions(+), 43 deletions(-) diff --git a/src/backend/storage/aio/aio_target.c b/src/backend/storage/aio/aio_target.c index fa98f010d5a..82b24b0026d 100644 --- a/src/backend/storage/aio/aio_target.c +++ b/src/backend/storage/aio/aio_target.c @@ -18,6 +18,17 @@ #include "storage/aio_internal.h" #include "storage/smgr.h" +static char *pgaio_sync_describe_identity(const PgAioTargetData *sd); + +/* + * Target info for generic file syncs (PGAIO_TID_SYNC). The file being synced + * is identified by a path that is not stored in shared memory, therefore no + * reopen callback is provided. + */ +static const PgAioTargetInfo aio_sync_target_info = { + .name = "sync", + .describe_identity = pgaio_sync_describe_identity, +}; /* * Registry for entities that can be the target of AIO. @@ -27,9 +38,22 @@ static const PgAioTargetInfo *pgaio_target_info[] = { .name = "invalid", }, [PGAIO_TID_SMGR] = &aio_smgr_target_info, + [PGAIO_TID_SYNC] = &aio_sync_target_info, }; +/* + * describe_identity callback for PGAIO_TID_SYNC. As we do not store the path + * of the file being synced in shared memory, only a generic description can + * be provided. + */ +static char * +pgaio_sync_describe_identity(const PgAioTargetData *sd) +{ + return pstrdup("generic file sync"); +} + + /* -------------------------------------------------------------------------------- * Public target related functions operating on IO Handles diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index 190c9974494..245ce6eccdd 100644 --- a/src/backend/storage/file/fd.c +++ b/src/backend/storage/file/fd.c @@ -268,6 +268,31 @@ typedef struct } desc; } AllocateDesc; +/* + * State for asynchronously issuing the fsync()s in SyncDataDirectory(). We + * keep a bounded number of fsync IOs in flight, using a simple ring of + * entries; when the ring is full, we wait for the oldest IO to complete + * before issuing another. + */ +typedef struct DataDirSyncEntry +{ + int fd; + bool isdir; + char path[MAXPGPATH]; + PgAioReturn ioret; + PgAioWaitRef iow; + bool in_use; +} DataDirSyncEntry; + +typedef struct DataDirSyncState +{ + int elevel; /* level to log errors at */ + int max_inflight; /* size of the ring */ + int head; /* index of oldest in-flight entry */ + int count; /* number of in-flight entries */ + DataDirSyncEntry *entries; /* ring of max_inflight entries */ +} DataDirSyncState; + static int numAllocatedDescs = 0; static int maxAllocatedDescs = 0; static AllocateDesc *allocatedDescs = NULL; @@ -346,14 +371,20 @@ static void RemovePgTempRelationFiles(const char *tsdirname); static void RemovePgTempRelationFilesInDbspace(const char *dbspacedirname); static void walkdir(const char *path, - void (*action) (const char *fname, bool isdir, int elevel), + void (*action) (const char *fname, bool isdir, int elevel, DataDirSyncState *state), bool process_symlinks, - int elevel); + int elevel, + DataDirSyncState *state); #ifdef PG_FLUSH_DATA_WORKS -static void pre_sync_fname(const char *fname, bool isdir, int elevel); +static void pre_sync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state); #endif -static void datadir_fsync_fname(const char *fname, bool isdir, int elevel); -static void unlink_if_exists_fname(const char *fname, bool isdir, int elevel); +static void datadir_fsync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state); +static void unlink_if_exists_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state); +static bool fsync_fname_open(const char *fname, bool isdir, bool ignore_perm, + int elevel, int *ret); +static bool fsync_fname_close(const char *fname, bool isdir, int elevel, int fd, int returncode); +static void datadir_sync_wait_one(DataDirSyncState *state); +static void datadir_sync_drain_all(DataDirSyncState *state); static int fsync_parent_path(const char *fname, int elevel); @@ -1691,7 +1722,7 @@ PathNameDeleteTemporaryDir(const char *dirname) * used in a cleanup path, we wouldn't actually behave differently: we'll * just log failures. */ - walkdir(dirname, unlink_if_exists_fname, false, LOG); + walkdir(dirname, unlink_if_exists_fname, false, LOG, NULL); } /* @@ -3566,6 +3597,21 @@ do_syncfs(const char *path) } #endif +/* + * Return a safe upper bound for the number of fsyncs to keep in flight. + * + * Callers that fsync files opened with OpenTransientFile() hold one + * AllocateDesc for each in-flight IO. At most max_safe_fds / 3 of those can + * be allocated at a time (see reserveAllocatedDesc()), and the callers of + * interest also traverse directories (see walkdir()), which needs + * AllocateDescs of its own. So, hand out at most half of the budget. + */ +int +GetFsyncConcurrencyLimit(void) +{ + return Max(1, Min(io_max_concurrency, max_safe_fds / 6)); +} + /* * Issue fsync recursively on PGDATA and all its contents, or issue syncfs for * all potential filesystem, depending on recovery_init_sync_method setting. @@ -3592,6 +3638,7 @@ void SyncDataDirectory(void) { bool xlog_is_symlink; + DataDirSyncState sync_state_data = {0}; /* We can skip this whole thing if fsync is disabled. */ if (!enableFsync) @@ -3663,15 +3710,22 @@ SyncDataDirectory(void) * directory and its contents. Errors in this step are even less * interesting than normal, so log them only at DEBUG1. */ - walkdir(".", pre_sync_fname, false, DEBUG1); + walkdir(".", pre_sync_fname, false, DEBUG1, NULL); if (xlog_is_symlink) - walkdir("pg_wal", pre_sync_fname, false, DEBUG1); - walkdir(PG_TBLSPC_DIR, pre_sync_fname, true, DEBUG1); + walkdir("pg_wal", pre_sync_fname, false, DEBUG1, NULL); + walkdir(PG_TBLSPC_DIR, pre_sync_fname, true, DEBUG1, NULL); #endif /* Prepare to report progress syncing the data directory via fsync. */ begin_startup_progress_phase(); + sync_state_data.elevel = LOG; + sync_state_data.max_inflight = GetFsyncConcurrencyLimit(); + sync_state_data.head = 0; + sync_state_data.count = 0; + sync_state_data.entries = palloc0(sizeof(DataDirSyncEntry) * + sync_state_data.max_inflight); + /* * Now we do the fsync()s in the same order. * @@ -3681,10 +3735,14 @@ SyncDataDirectory(void) * in pg_tblspc, they'll get fsync'd twice. That's not an expected case * so we don't worry about optimizing it. */ - walkdir(".", datadir_fsync_fname, false, LOG); + walkdir(".", datadir_fsync_fname, false, LOG, &sync_state_data); if (xlog_is_symlink) - walkdir("pg_wal", datadir_fsync_fname, false, LOG); - walkdir(PG_TBLSPC_DIR, datadir_fsync_fname, true, LOG); + walkdir("pg_wal", datadir_fsync_fname, false, LOG, &sync_state_data); + walkdir(PG_TBLSPC_DIR, datadir_fsync_fname, true, LOG, &sync_state_data); + + datadir_sync_drain_all(&sync_state_data); + + pfree(sync_state_data.entries); } /* @@ -3704,9 +3762,10 @@ SyncDataDirectory(void) */ static void walkdir(const char *path, - void (*action) (const char *fname, bool isdir, int elevel), + void (*action) (const char *fname, bool isdir, int elevel, DataDirSyncState *state), bool process_symlinks, - int elevel) + int elevel, + DataDirSyncState *state) { DIR *dir; struct dirent *de; @@ -3728,10 +3787,10 @@ walkdir(const char *path, switch (get_dirent_type(subpath, de, process_symlinks, elevel)) { case PGFILETYPE_REG: - (*action) (subpath, false, elevel); + (*action) (subpath, false, elevel, state); break; case PGFILETYPE_DIR: - walkdir(subpath, action, false, elevel); + walkdir(subpath, action, false, elevel, state); break; default: @@ -3753,7 +3812,7 @@ walkdir(const char *path, * might not be robust against that. */ if (dir) - (*action) (path, true, elevel); + (*action) (path, true, elevel, state); } @@ -3766,10 +3825,13 @@ walkdir(const char *path, #ifdef PG_FLUSH_DATA_WORKS static void -pre_sync_fname(const char *fname, bool isdir, int elevel) +pre_sync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state) { int fd; + /* No AIO implementation, so state should be NULL */ + Assert(!state); + /* Don't try to flush directories, it'll likely just fail */ if (isdir) return; @@ -3804,21 +3866,98 @@ pre_sync_fname(const char *fname, bool isdir, int elevel) #endif /* PG_FLUSH_DATA_WORKS */ static void -datadir_fsync_fname(const char *fname, bool isdir, int elevel) +datadir_sync_wait_one(DataDirSyncState *state) +{ + DataDirSyncEntry *entry; + + Assert(state->count > 0); + + entry = &state->entries[state->head]; + Assert(entry->in_use); + + pgaio_wref_wait(&entry->iow); + + /* + * As we didn't register a completion callback, the IO's status is always + * PGAIO_RS_OK; the raw fsync() return (0 or -errno) is available in + * ->result.result. Use the same error handling as fsync_fname_ext(). + */ + if (entry->ioret.result.result < 0) + errno = -entry->ioret.result.result; + + fsync_fname_close(entry->path, entry->isdir, state->elevel, entry->fd, entry->ioret.result.result); + + entry->in_use = false; + state->head = (state->head + 1) % state->max_inflight; + state->count--; +} + +static void +datadir_sync_drain_all(DataDirSyncState *state) +{ + while (state->count > 0) + datadir_sync_wait_one(state); + + Assert(state->count == 0); +} + +static void +datadir_fsync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state) { + int fd; + int slot; + DataDirSyncEntry *entry; + PgAioHandle *ioh; + ereport_startup_progress("syncing data directory (fsync), elapsed time: %ld.%02d s, current path: %s", fname); /* - * We want to silently ignoring errors about unreadable files. Pass that - * desire on to fsync_fname_ext(). + * If the ring is full, wait before opening the next file, so that the + * number of open descriptors never temporarily exceeds the ring size. */ - fsync_fname_ext(fname, isdir, true, elevel); + if (state->count == state->max_inflight) + datadir_sync_wait_one(state); + + /* + * We want to silently ignore errors about unreadable files. Pass that + * desire on to fsync_fname_open(). + */ + if (!fsync_fname_open(fname, isdir, true, elevel, &fd)) + return; + + Assert(state->count < state->max_inflight); + slot = (state->head + state->count) % state->max_inflight; + entry = &state->entries[slot]; + Assert(!entry->in_use); + + entry->fd = fd; + entry->isdir = isdir; + strlcpy(entry->path, fname, MAXPGPATH); + entry->in_use = true; + + ioh = pgaio_io_acquire(CurrentResourceOwner, &entry->ioret); + pgaio_io_set_target(ioh, PGAIO_TID_SYNC); + pgaio_io_get_wref(ioh, &entry->iow); + + /* + * Interrupts must be held across staging the IO, so that the file + * descriptor it references cannot be closed by interrupt processing + * before the IO has been submitted. + */ + HOLD_INTERRUPTS(); + pgaio_io_start_fsync(ioh, fd, false, WAIT_EVENT_DATA_DIR_SYNC); + RESUME_INTERRUPTS(); + + state->count++; } static void -unlink_if_exists_fname(const char *fname, bool isdir, int elevel) +unlink_if_exists_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state) { + /* No AIO implementation, so state should be NULL */ + Assert(!state); + if (isdir) { if (rmdir(fname) != 0 && errno != ENOENT) @@ -3834,19 +3973,24 @@ unlink_if_exists_fname(const char *fname, bool isdir, int elevel) } /* - * fsync_fname_ext -- Try to fsync a file or directory + * Helper for opening a file as part of fsync_fname_ext() and + * datadir_fsync_fname(). Split out because the latter performs the fsync + * asynchronously via AIO. * - * If ignore_perm is true, ignore errors upon trying to open unreadable - * files. Logs other errors at a caller-specified level. + * If ignore_perm is true, ignore errors upon trying to open unreadable files. * - * Returns 0 if the operation succeeded, -1 otherwise. + * If the file could not be opened, false is returned; *fd is set to 0 if the + * failure should be ignored, or -1 otherwise. Other errors are logged at the + * caller-specified level. + * + * If the file was opened successfully, true is returned and *fd is set to + * the file descriptor. */ -int -fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) +static bool +fsync_fname_open(const char *fname, bool isdir, bool ignore_perm, + int elevel, int *fd) { - int fd; int flags; - int returncode; /* * Some OSs require directories to be opened read-only whereas other @@ -3860,27 +4004,48 @@ fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) else flags |= O_RDONLY; - fd = OpenTransientFile(fname, flags); + *fd = OpenTransientFile(fname, flags); /* * Some OSs don't allow us to open directories at all (Windows returns * EACCES), just ignore the error in that case. If desired also silently * ignoring errors about unreadable files. Log others. */ - if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES)) - return 0; - else if (fd < 0 && ignore_perm && errno == EACCES) - return 0; - else if (fd < 0) + if (*fd >= 0) + return true; + if (isdir && (errno == EISDIR || errno == EACCES)) + { + *fd = 0; + return false; + } + else if (ignore_perm && errno == EACCES) { + *fd = 0; + return false; + } + else + { + *fd = -1; ereport(elevel, (errcode_for_file_access(), errmsg("could not open file \"%s\": %m", fname))); - return -1; + return false; } +} - returncode = pg_fsync(fd); - +/* + * Helper for closing a file, and reporting any fsync failure, as part of + * fsync_fname_ext() and datadir_fsync_fname(). Split out because the latter + * performs the fsync asynchronously via AIO. + * + * "returncode" is the result of the preceding fsync; if it is negative, errno + * must describe the failure. + * + * Returns true if the operation succeeded, false otherwise. + */ +static bool +fsync_fname_close(const char *fname, bool isdir, int elevel, int fd, int returncode) +{ /* * Some OSes don't allow us to fsync directories at all, so we can ignore * those errors. Anything else needs to be logged. @@ -3897,7 +4062,7 @@ fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) ereport(elevel, (errcode_for_file_access(), errmsg("could not fsync file \"%s\": %m", fname))); - return -1; + return false; } if (CloseTransientFile(fd) != 0) @@ -3905,9 +4070,35 @@ fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) ereport(elevel, (errcode_for_file_access(), errmsg("could not close file \"%s\": %m", fname))); - return -1; + return false; } + return true; +} + +/* + * fsync_fname_ext -- Try to fsync a file or directory + * + * If ignore_perm is true, ignore errors upon trying to open unreadable + * files. Logs other errors at a caller-specified level. + * + * Returns 0 if the operation succeeded, -1 otherwise. + */ +int +fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) +{ + int fd; + int returncode; + + if (!fsync_fname_open(fname, isdir, ignore_perm, elevel, &fd)) + return fd; + + Assert(fd >= 0); + returncode = pg_fsync(fd); + + if (!fsync_fname_close(fname, isdir, elevel, fd, returncode)) + return -1; + return 0; } diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt index 3d366fd1114..5b303ba0fb4 100644 --- a/src/backend/utils/activity/wait_event_names.txt +++ b/src/backend/utils/activity/wait_event_names.txt @@ -219,6 +219,7 @@ COPY_FILE_READ "Waiting for a read during a file copy operation." COPY_FILE_WRITE "Waiting for a write during a file copy operation." COPY_FROM_READ "Waiting to read data from a pipe, a file or a program during COPY FROM." COPY_TO_WRITE "Waiting to write data to a pipe, a file or a program during COPY TO." +DATA_DIR_SYNC "Waiting for the contents of the data directory to reach durable storage after a crash." DATA_FILE_EXTEND "Waiting for a relation data file to be extended." DATA_FILE_FLUSH "Waiting for a relation data file to reach durable storage." DATA_FILE_IMMEDIATE_SYNC "Waiting for an immediate synchronization of a relation data file to durable storage." diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index a1d5f49e51a..428504c0472 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -118,9 +118,10 @@ typedef enum PgAioTargetID /* intentionally the zero value, to help catch zeroed memory etc */ PGAIO_TID_INVALID = 0, PGAIO_TID_SMGR, + PGAIO_TID_SYNC, } PgAioTargetID; -#define PGAIO_TID_COUNT (PGAIO_TID_SMGR + 1) +#define PGAIO_TID_COUNT (PGAIO_TID_SYNC + 1) /* diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h index 8ac466fd346..c79f3312544 100644 --- a/src/include/storage/fd.h +++ b/src/include/storage/fd.h @@ -219,6 +219,7 @@ extern int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int extern int durable_rename(const char *oldfile, const char *newfile, int elevel); extern int durable_unlink(const char *fname, int elevel); extern void SyncDataDirectory(void); +extern int GetFsyncConcurrencyLimit(void); extern int data_sync_elevel(int elevel); static inline ssize_t diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 5d432074c2c..21bf56da4fa 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -636,7 +636,9 @@ DataChecksumsStateStruct DataChecksumsWorkerDatabase DataChecksumsWorkerOperation DataChecksumsWorkerResult +DataDirSyncEntry DataDirSyncMethod +DataDirSyncState DataDumperPtr DataPageDeleteStack DataTypesUsageChecks -- 2.47.3
v2-0005-aio-Allow-AIO-reopen-callbacks-to-return-errors.patch (text/x-patch, 9.2K) download From 7e95a3ef2f67d2e3312e7a5898bfa57a7716c8f2 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 16 Sep 2026 10:53:05 +0300 Subject: [PATCH v2 5/8] aio: Allow AIO reopen callbacks to return errors Allow target reopen callbacks to return -errno for ordinary failures. IO workers pass these results through completion so the issuer can apply its error policy. Exceptions retain the existing worker recovery path, and relation read/write descriptor lookup keeps its existing error reporting. This prepares for asynchronous checkpoint fsyncs, where the issuer needs to distinguish potentially deleted files from other failures when deciding whether to retry or report a sync failure. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- src/backend/storage/aio/aio_target.c | 8 +- src/backend/storage/aio/method_worker.c | 99 ++++++++++++++----------- src/backend/storage/smgr/smgr.c | 20 +++-- src/include/storage/aio.h | 7 +- src/include/storage/aio_internal.h | 2 +- 5 files changed, 81 insertions(+), 55 deletions(-) diff --git a/src/backend/storage/aio/aio_target.c b/src/backend/storage/aio/aio_target.c index 82b24b0026d..1a0088fa382 100644 --- a/src/backend/storage/aio/aio_target.c +++ b/src/backend/storage/aio/aio_target.c @@ -136,11 +136,15 @@ pgaio_io_can_reopen(PgAioHandle *ioh) * IO has been staged in, the file descriptor has to be reopened - any FD * referenced in the IO itself, won't be valid in the separate process. */ -void +int pgaio_io_reopen(PgAioHandle *ioh) { + int result; + Assert(ioh->target > PGAIO_TID_INVALID && ioh->target < PGAIO_TID_COUNT); Assert(ioh->op > PGAIO_OP_INVALID && ioh->op < PGAIO_OP_COUNT); - pgaio_target_info[ioh->target]->reopen(ioh); + result = pgaio_target_info[ioh->target]->reopen(ioh); + + return result; } diff --git a/src/backend/storage/aio/method_worker.c b/src/backend/storage/aio/method_worker.c index 7639d093677..746d1be20e4 100644 --- a/src/backend/storage/aio/method_worker.c +++ b/src/backend/storage/aio/method_worker.c @@ -872,6 +872,7 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len) if (io_index != -1) { PgAioHandle *ioh = NULL; + int reopen_result; /* Cancel timeout and update wakeup:work ratio. */ idle_timeout_abs = 0; @@ -897,62 +898,72 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len) HOLD_INTERRUPTS(); /* - * It's very unlikely, but possible, that reopen fails. E.g. due - * to memory allocations failing or file permissions changing or - * such. In that case we need to fail the IO. - * - * There's not really a good errno we can report here. + * Ordinary reopen failures can return -errno below. If the + * callback instead raises an error, use the existing worker-exit + * recovery path, which has no reliable errno to report. */ error_errno = ENOENT; - pgaio_io_reopen(ioh); + reopen_result = pgaio_io_reopen(ioh); - /* - * To be able to exercise the reopen-fails path, allow injection - * points to trigger a failure at this point. - */ - INJECTION_POINT("aio-worker-after-reopen", ioh); + if (reopen_result < 0) + { + error_errno = 0; + error_ioh = NULL; + + START_CRIT_SECTION(); + pgaio_io_process_completion(ioh, reopen_result); + END_CRIT_SECTION(); + } + else + { + /* + * To be able to exercise the reopen-fails path, allow + * injection points to trigger a failure at this point. + */ + INJECTION_POINT("aio-worker-after-reopen", ioh); - error_errno = 0; - error_ioh = NULL; + error_errno = 0; + error_ioh = NULL; - /* - * As part of IO completion the buffer will be marked as NOACCESS, - * until the buffer is pinned again - which never happens in io - * workers. Therefore the next time there is IO for the same - * buffer, the memory will be considered inaccessible. To avoid - * that, explicitly allow access to the memory before reading data - * into it. - */ + /* + * As part of IO completion the buffer will be marked as + * NOACCESS, until the buffer is pinned again - which never + * happens in io workers. Therefore the next time there is IO + * for the same buffer, the memory will be considered + * inaccessible. To avoid that, explicitly allow access to the + * memory before reading data into it. + */ #ifdef USE_VALGRIND - { - struct iovec *iov; - uint16 iov_length = pgaio_io_get_iovec_length(ioh, &iov); + { + struct iovec *iov; + uint16 iov_length = pgaio_io_get_iovec_length(ioh, &iov); - for (int i = 0; i < iov_length; i++) - VALGRIND_MAKE_MEM_UNDEFINED(iov[i].iov_base, iov[i].iov_len); - } + for (int i = 0; i < iov_length; i++) + VALGRIND_MAKE_MEM_UNDEFINED(iov[i].iov_base, iov[i].iov_len); + } #endif #ifdef PGAIO_WORKER_SHOW_PS_INFO - { - char *description = pgaio_io_get_target_description(ioh); - - sprintf(cmd, "%d: [%s] %s", - MyIoWorkerId, - pgaio_io_get_op_name(ioh), - description); - pfree(description); - set_ps_display(cmd); - } + { + char *description = pgaio_io_get_target_description(ioh); + + sprintf(cmd, "%d: [%s] %s", + MyIoWorkerId, + pgaio_io_get_op_name(ioh), + description); + pfree(description); + set_ps_display(cmd); + } #endif - /* - * We don't expect this to ever fail with ERROR or FATAL, no need - * to keep error_ioh set to the IO. - * pgaio_io_perform_synchronously() contains a critical section to - * ensure we don't accidentally fail. - */ - pgaio_io_perform_synchronously(ioh); + /* + * We don't expect this to ever fail with ERROR or FATAL, no + * need to keep error_ioh set to the IO. + * pgaio_io_perform_synchronously() contains a critical + * section to ensure we don't accidentally fail. + */ + pgaio_io_perform_synchronously(ioh); + } RESUME_INTERRUPTS(); errcallback.arg = NULL; diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c index 69e61ea1661..83417e1bcc2 100644 --- a/src/backend/storage/smgr/smgr.c +++ b/src/backend/storage/smgr/smgr.c @@ -165,7 +165,7 @@ static dlist_head unpinned_relns; static void smgrshutdown(int code, Datum arg); static void smgrdestroy(SMgrRelation reln); -static void smgr_aio_reopen(PgAioHandle *ioh); +static int smgr_aio_reopen(PgAioHandle *ioh); static char *smgr_aio_describe_identity(const PgAioTargetData *sd); @@ -1058,9 +1058,11 @@ pgaio_io_set_target_smgr(PgAioHandle *ioh, /* * Callback for the smgr AIO target, to reopen the file (e.g. because the IO - * is executed in a worker). + * is executed in a worker). Returns 0 on success. Failures can return + * -errno, but relation read/write descriptor lookup retains its existing + * error reporting and may raise an error instead. */ -static void +static int smgr_aio_reopen(PgAioHandle *ioh) { PgAioTargetData *sd = pgaio_io_get_target_data(ioh); @@ -1068,6 +1070,7 @@ smgr_aio_reopen(PgAioHandle *ioh) SMgrRelation reln; ProcNumber procno; uint32 off; + int fd; /* * The caller needs to prevent interrupts from being processed, otherwise @@ -1089,15 +1092,18 @@ smgr_aio_reopen(PgAioHandle *ioh) case PGAIO_OP_READV: od->read.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); Assert(off == od->read.offset); - break; + return 0; case PGAIO_OP_WRITEV: od->write.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); Assert(off == od->write.offset); - break; + return 0; case PGAIO_OP_FSYNC: - od->fsync.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); - break; + fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); + od->fsync.fd = fd; + return 0; } + + pg_unreachable(); } /* diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index 428504c0472..7f056f43e78 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -168,8 +168,13 @@ struct PgAioTargetInfo /* * To support executing using worker processes, the file descriptor for an * IO may need to be reopened in a different process. + * + * Returns 0 on success. Callbacks can return -errno for an ordinary + * failure to reopen, allowing the issuer to handle the failure without + * terminating the worker. Callbacks that raise an error instead use the + * worker's exception-recovery path, which does not preserve errno. */ - void (*reopen) (PgAioHandle *ioh); + int (*reopen) (PgAioHandle *ioh); /* describe the target of the IO, used for log messages and views */ char *(*describe_identity) (const PgAioTargetData *sd); diff --git a/src/include/storage/aio_internal.h b/src/include/storage/aio_internal.h index 9ca4087aa7f..35d4f3f310d 100644 --- a/src/include/storage/aio_internal.h +++ b/src/include/storage/aio_internal.h @@ -359,7 +359,7 @@ extern int pgaio_io_get_iovec_length(PgAioHandle *ioh, struct iovec **iov); /* aio_target.c */ extern bool pgaio_io_can_reopen(PgAioHandle *ioh); -extern void pgaio_io_reopen(PgAioHandle *ioh); +extern int pgaio_io_reopen(PgAioHandle *ioh); extern const char *pgaio_io_get_target_name(PgAioHandle *ioh); -- 2.47.3
v2-0006-aio-Issue-checkpointer-fsyncs-asynchronously.patch (text/x-patch, 56.1K) download From 74c1eb7ae5307c7959704935d20262c26222c6f7 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 16 Sep 2026 13:30:15 +0300 Subject: [PATCH v2 6/8] aio: Issue checkpointer fsyncs asynchronously ProcessSyncRequests() previously fsynced pending files one at a time. For checkpoints with many files, this serialized I/O that storage could perform concurrently. Submit the fsyncs through AIO, keeping a bounded set in flight and reaping completions in submission order. Relation requests may use all io_max_concurrency slots. For SLRU requests, apply a transient-descriptor limit to the total in-flight count so their open files do not exhaust the descriptor reserve. Reshape the sync handler API so handlers open the file, assign an AIO target, start the fsync, and record how to close it. sync.c manages the in-flight operations, errors, retries, and pendingOps bookkeeping. Absorbing requests while fsyncs are in flight requires some care: - Recheck cancellation when an operation is reaped because a request can be canceled after its fsync starts. - Defer completion bookkeeping until the pendingOps scan ends because dynahash permits removing only the entry most recently returned. - Keep a new request for a file already in flight until the next checkpoint cycle because the running fsync might not cover its write. Error cleanup drains and closes all outstanding operations while preserving the first durability error that requires PANIC. Otherwise, preserve the original error and leave retries to the next checkpoint. Do not reinterpret an already-handled deletion failure as a failed retry during cleanup. Relation files can be reopened through the smgr target, allowing I/O workers to perform their fsyncs. Open the exact segment path so inactive segments following a truncated partial segment remain syncable. Add a target close callback to release transient worker-side descriptors after execution. SLRU files use the generic sync target and execute synchronously with the worker I/O method, although io_uring can still overlap them. Measure time spent starting each request and waiting for operations that are not already complete. Include only successful attempts in checkpoint longest and aggregate statistics. Add a pgstat helper that accepts an end timestamp. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- src/backend/access/transam/clog.c | 6 +- src/backend/access/transam/commit_ts.c | 6 +- src/backend/access/transam/multixact.c | 12 +- src/backend/access/transam/slru.c | 35 +- src/backend/storage/aio/aio_io.c | 8 + src/backend/storage/aio/aio_target.c | 39 +- src/backend/storage/file/fd.c | 39 +- src/backend/storage/smgr/md.c | 84 +++- src/backend/storage/smgr/smgr.c | 46 +- src/backend/storage/sync/sync.c | 632 ++++++++++++++++++++----- src/backend/utils/activity/pgstat_io.c | 47 +- src/include/access/clog.h | 2 +- src/include/access/commit_ts.h | 2 +- src/include/access/multixact.h | 4 +- src/include/access/slru.h | 2 +- src/include/pgstat.h | 4 + src/include/storage/aio.h | 6 + src/include/storage/aio_internal.h | 1 + src/include/storage/fd.h | 3 +- src/include/storage/md.h | 3 +- src/include/storage/sync.h | 55 +++ src/test/modules/test_slru/test_slru.c | 45 +- src/tools/pgindent/typedefs.list | 3 + 23 files changed, 893 insertions(+), 191 deletions(-) diff --git a/src/backend/access/transam/clog.c b/src/backend/access/transam/clog.c index 6f7f6b86eb6..89fb77ea5da 100644 --- a/src/backend/access/transam/clog.c +++ b/src/backend/access/transam/clog.c @@ -1117,8 +1117,8 @@ clog_redo(XLogReaderState *record) /* * Entrypoint for sync.c to sync clog files. */ -int -clogsyncfiletag(const FileTag *ftag, char *path) +void +clogsyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(XactCtl, ftag, path); + SlruSyncFileTag(XactCtl, ioh, entry); } diff --git a/src/backend/access/transam/commit_ts.c b/src/backend/access/transam/commit_ts.c index 9e6fd5d4657..7cbbad383b2 100644 --- a/src/backend/access/transam/commit_ts.c +++ b/src/backend/access/transam/commit_ts.c @@ -1028,8 +1028,8 @@ commit_ts_redo(XLogReaderState *record) /* * Entrypoint for sync.c to sync commit_ts files. */ -int -committssyncfiletag(const FileTag *ftag, char *path) +void +committssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(CommitTsCtl, ftag, path); + SlruSyncFileTag(CommitTsCtl, ioh, entry); } diff --git a/src/backend/access/transam/multixact.c b/src/backend/access/transam/multixact.c index 70a4ea69486..deb0b110ee8 100644 --- a/src/backend/access/transam/multixact.c +++ b/src/backend/access/transam/multixact.c @@ -3003,17 +3003,17 @@ multixact_redo(XLogReaderState *record) /* * Entrypoint for sync.c to sync offsets files. */ -int -multixactoffsetssyncfiletag(const FileTag *ftag, char *path) +void +multixactoffsetssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(MultiXactOffsetCtl, ftag, path); + SlruSyncFileTag(MultiXactOffsetCtl, ioh, entry); } /* * Entrypoint for sync.c to sync members files. */ -int -multixactmemberssyncfiletag(const FileTag *ftag, char *path) +void +multixactmemberssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(MultiXactMemberCtl, ftag, path); + SlruSyncFileTag(MultiXactMemberCtl, ioh, entry); } diff --git a/src/backend/access/transam/slru.c b/src/backend/access/transam/slru.c index 885fd068535..b1e513ac3b6 100644 --- a/src/backend/access/transam/slru.c +++ b/src/backend/access/transam/slru.c @@ -68,6 +68,7 @@ #include "access/xlogutils.h" #include "miscadmin.h" #include "pgstat.h" +#include "storage/aio.h" #include "storage/fd.h" #include "storage/shmem.h" #include "storage/shmem_internal.h" @@ -1880,26 +1881,32 @@ SlruScanDirectory(SlruDesc *ctl, SlruScanCallback callback, void *data) * build the path), but they just forward to this common implementation that * performs the fsync. */ -int -SlruSyncFileTag(SlruDesc *ctl, const FileTag *ftag, char *path) +void +SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, InflightSyncEntry *entry) { int fd; - int save_errno; - int result; - SlruFileName(ctl, path, ftag->segno); + SlruFileName(ctl, entry->path, entry->tag.segno); - fd = OpenTransientFile(path, O_RDWR | PG_BINARY); + fd = OpenTransientFile(entry->path, O_RDWR | PG_BINARY); if (fd < 0) - return -1; + { + entry->started = false; + entry->open_errno = errno; + return; + } - pgstat_report_wait_start(WAIT_EVENT_SLRU_FLUSH_SYNC); - result = pg_fsync(fd); - pgstat_report_wait_end(); - save_errno = errno; + /* + * Use the generic sync target. SLRU segments are not smgr relations and + * cannot be reopened from a FileTag in another process, so this fsync + * will run synchronously in worker mode. + */ + pgaio_io_set_target(ioh, PGAIO_TID_SYNC); - CloseTransientFile(fd); + /* Start the asynchronous fsync; the fd is closed once it completes. */ + pgaio_io_start_fsync(ioh, fd, false, WAIT_EVENT_SLRU_FLUSH_SYNC); - errno = save_errno; - return result; + entry->started = true; + entry->close_method = SYNC_CLOSE_TRANSIENT; + entry->close_file = fd; } diff --git a/src/backend/storage/aio/aio_io.c b/src/backend/storage/aio/aio_io.c index 0525643cc2b..a5f5c286fb0 100644 --- a/src/backend/storage/aio/aio_io.c +++ b/src/backend/storage/aio/aio_io.c @@ -173,6 +173,14 @@ pgaio_io_perform_synchronously(PgAioHandle *ioh) Assert(result <= INT_MAX); ioh->result = result < 0 ? -errno : result; + /* + * If we, rather than the process that staged the IO, opened the file, + * close it again. Has to happen after the result has been determined, as + * closing may clobber errno, and before the completion is processed, as + * that can recycle the handle. + */ + pgaio_io_close_reopened(ioh); + pgaio_io_process_completion(ioh, ioh->result); END_CRIT_SECTION(); diff --git a/src/backend/storage/aio/aio_target.c b/src/backend/storage/aio/aio_target.c index 1a0088fa382..534382b423b 100644 --- a/src/backend/storage/aio/aio_target.c +++ b/src/backend/storage/aio/aio_target.c @@ -41,6 +41,13 @@ static const PgAioTargetInfo *pgaio_target_info[] = { [PGAIO_TID_SYNC] = &aio_sync_target_info, }; +/* + * The IO whose descriptor this process reopened and whose target requires the + * descriptor to be released after execution. Only set between + * pgaio_io_reopen() and pgaio_io_close_reopened(). + */ +static PgAioHandle *pgaio_reopened_ioh = NULL; + /* * describe_identity callback for PGAIO_TID_SYNC. As we do not store the path @@ -143,8 +150,38 @@ pgaio_io_reopen(PgAioHandle *ioh) Assert(ioh->target > PGAIO_TID_INVALID && ioh->target < PGAIO_TID_COUNT); Assert(ioh->op > PGAIO_OP_INVALID && ioh->op < PGAIO_OP_COUNT); + Assert(pgaio_reopened_ioh == NULL); result = pgaio_target_info[ioh->target]->reopen(ioh); - return result; + if (result < 0) + return result; + + /* + * Remember that this process, rather than the one that staged the IO, + * owns the file descriptor now, so that pgaio_io_close_reopened() can + * release it once the IO has been executed. + */ + if (pgaio_target_info[ioh->target]->close != NULL) + pgaio_reopened_ioh = ioh; + + return 0; +} + +/* + * Internal: Counterpart to pgaio_io_reopen(), releasing the file descriptor it + * acquired. Does nothing unless this process reopened this very IO and its + * target needs the descriptor to be released. + * + * This has to be called before the IO's completion is processed, as that can + * make the handle be reused for an unrelated IO. + */ +void +pgaio_io_close_reopened(PgAioHandle *ioh) +{ + if (pgaio_reopened_ioh != ioh) + return; + + pgaio_reopened_ioh = NULL; + pgaio_target_info[ioh->target]->close(ioh); } diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index 245ce6eccdd..27184557b8f 100644 --- a/src/backend/storage/file/fd.c +++ b/src/backend/storage/file/fd.c @@ -2258,6 +2258,29 @@ FileStartReadV(PgAioHandle *ioh, File file, return 0; } +int +FileStartSync(PgAioHandle *ioh, File file, bool datasync, + uint32 wait_event_info) +{ + int returnCode; + Vfd *vfdP; + + Assert(FileIsValid(file)); + + DO_DB(elog(LOG, "FileStartSync: %d (%s)", + file, VfdCache[file].fileName)); + + returnCode = FileAccess(file); + if (returnCode < 0) + return returnCode; + + vfdP = &VfdCache[file]; + + pgaio_io_start_fsync(ioh, vfdP->fd, datasync, wait_event_info); + + return 0; +} + ssize_t FileWriteV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info) @@ -3602,14 +3625,18 @@ do_syncfs(const char *path) * * Callers that fsync files opened with OpenTransientFile() hold one * AllocateDesc for each in-flight IO. At most max_safe_fds / 3 of those can - * be allocated at a time (see reserveAllocatedDesc()), and the callers of - * interest also traverse directories (see walkdir()), which needs - * AllocateDescs of its own. So, hand out at most half of the budget. + * be allocated at a time (see reserveAllocatedDesc()). Keep half of that + * budget available for directory traversal and other AllocateDesc users. + * + * Other callers only need to respect the AIO handle limit. */ int -GetFsyncConcurrencyLimit(void) +GetFsyncConcurrencyLimit(bool uses_transient_fd) { - return Max(1, Min(io_max_concurrency, max_safe_fds / 6)); + if (uses_transient_fd) + return Max(1, Min(io_max_concurrency, max_safe_fds / 6)); + + return io_max_concurrency; } /* @@ -3720,7 +3747,7 @@ SyncDataDirectory(void) begin_startup_progress_phase(); sync_state_data.elevel = LOG; - sync_state_data.max_inflight = GetFsyncConcurrencyLimit(); + sync_state_data.max_inflight = GetFsyncConcurrencyLimit(true); sync_state_data.head = 0; sync_state_data.count = 0; sync_state_data.entries = palloc0(sizeof(DataDirSyncEntry) * diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c index 780c88c0630..053f121ef8a 100644 --- a/src/backend/storage/smgr/md.c +++ b/src/backend/storage/smgr/md.c @@ -1505,6 +1505,22 @@ mdfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, uint32 *off) return FileGetRawDesc(v->mdfd_vfd); } +/* + * Open the exact segment containing blocknum for fsync, or return -1 with + * errno set. + */ +int +mdfsyncfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum) +{ + MdPathStr path; + BlockNumber segno; + + segno = blocknum / ((BlockNumber) RELSEG_SIZE); + path = _mdfd_segpath(reln, forknum, segno); + + return OpenTransientFile(path.str, _mdfd_open_flags()); +} + /* * register_dirty_segment() -- Mark a relation segment as needing fsync * @@ -1896,26 +1912,27 @@ _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg) } /* - * Sync a file to disk, given a file tag. Write the path into an output - * buffer so the caller can use it in error messages. + * Sync a file to disk, given a file tag. * - * Return 0 on success, -1 on failure, with errno set. + * Starts an asynchronous fsync on the given AIO handle and records in "entry" + * the path (for error messages), whether an IO was started, and how the file + * is to be closed once the fsync has completed. */ -int -mdsyncfiletag(const FileTag *ftag, char *path) +void +mdsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry) { + FileTag *ftag = &entry->tag; SMgrRelation reln = smgropen(ftag->rlocator, INVALID_PROC_NUMBER); + BlockNumber segfirstblock = ftag->segno * ((BlockNumber) RELSEG_SIZE); File file; - instr_time io_start; bool need_to_close; - int result, - save_errno; + instr_time io_start; /* See if we already have the file open, or need to open it. */ if (ftag->segno < reln->md_num_open_segs[ftag->forknum]) { file = reln->md_seg_fds[ftag->forknum][ftag->segno].mdfd_vfd; - strlcpy(path, FilePathName(file), MAXPGPATH); + strlcpy(entry->path, FilePathName(file), MAXPGPATH); need_to_close = false; } else @@ -1923,28 +1940,53 @@ mdsyncfiletag(const FileTag *ftag, char *path) MdPathStr p; p = _mdfd_segpath(reln, ftag->forknum, ftag->segno); - strlcpy(path, p.str, MD_PATH_STR_MAXLEN); + strlcpy(entry->path, p.str, MD_PATH_STR_MAXLEN); - file = PathNameOpenFile(path, _mdfd_open_flags()); + file = PathNameOpenFile(entry->path, _mdfd_open_flags()); if (file < 0) - return -1; + { + entry->started = false; + entry->open_errno = errno; + return; + } need_to_close = true; } + pgaio_io_set_target_smgr(ioh, reln, ftag->forknum, segfirstblock, + 0, false); + + /* + * As with asynchronous reads, measure the time spent starting the IO. + * Synchronous execution includes the fsync itself; otherwise this only + * measures submission. + */ io_start = pgstat_prepare_io_time(track_io_timing); - /* Sync the file. */ - result = FileSync(file, WAIT_EVENT_DATA_FILE_SYNC); - save_errno = errno; + if (FileStartSync(ioh, file, false, WAIT_EVENT_DATA_FILE_SYNC) < 0) + { + entry->started = false; + entry->open_errno = errno; + if (need_to_close) + FileClose(file); + return; + } - if (need_to_close) - FileClose(file); + pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL, IOOP_FSYNC, + io_start, 1, 0); - pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL, - IOOP_FSYNC, io_start, 1, 0); + entry->started = true; - errno = save_errno; - return result; + /* + * If we opened the segment ourselves it has to be closed once the fsync + * has completed; segments owned by smgr are left to smgr to manage. + */ + if (need_to_close) + { + entry->close_method = SYNC_CLOSE_VFD; + entry->close_file = (int) file; + } + else + entry->close_method = SYNC_CLOSE_NONE; } /* diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c index 83417e1bcc2..325386ec58e 100644 --- a/src/backend/storage/smgr/smgr.c +++ b/src/backend/storage/smgr/smgr.c @@ -68,6 +68,7 @@ #include "miscadmin.h" #include "storage/aio.h" #include "storage/bufmgr.h" +#include "storage/fd.h" #include "storage/ipc.h" #include "storage/md.h" #include "storage/smgr.h" @@ -123,6 +124,7 @@ typedef struct f_smgr void (*smgr_immedsync) (SMgrRelation reln, ForkNumber forknum); void (*smgr_registersync) (SMgrRelation reln, ForkNumber forknum); int (*smgr_fd) (SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, uint32 *off); + int (*smgr_fsync_fd) (SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum); } f_smgr; static const f_smgr smgrsw[] = { @@ -148,6 +150,7 @@ static const f_smgr smgrsw[] = { .smgr_immedsync = mdimmedsync, .smgr_registersync = mdregistersync, .smgr_fd = mdfd, + .smgr_fsync_fd = mdfsyncfd, } }; @@ -166,12 +169,14 @@ static void smgrshutdown(int code, Datum arg); static void smgrdestroy(SMgrRelation reln); static int smgr_aio_reopen(PgAioHandle *ioh); +static void smgr_aio_close(PgAioHandle *ioh); static char *smgr_aio_describe_identity(const PgAioTargetData *sd); const PgAioTargetInfo aio_smgr_target_info = { .name = "smgr", .reopen = smgr_aio_reopen, + .close = smgr_aio_close, .describe_identity = smgr_aio_describe_identity, }; @@ -1001,6 +1006,18 @@ smgrfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, uint32 *off) return fd; } +/* + * Open the exact segment containing blocknum for fsync, returning a transient + * descriptor, or -1 with errno set if the file cannot be opened. + */ +static int +smgrfsyncfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum) +{ + Assert(!INTERRUPTS_CAN_BE_PROCESSED()); + + return smgrsw[reln->smgr_which].smgr_fsync_fd(reln, forknum, blocknum); +} + /* * AtEOXact_SMgr * @@ -1098,7 +1115,10 @@ smgr_aio_reopen(PgAioHandle *ioh) Assert(off == od->write.offset); return 0; case PGAIO_OP_FSYNC: - fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); + fd = smgrfsyncfd(reln, sd->smgr.forkNum, sd->smgr.blockNum); + /* We need errno for only checkpointer fsyncs for now */ + if (fd < 0) + return -errno; od->fsync.fd = fd; return 0; } @@ -1106,6 +1126,21 @@ smgr_aio_reopen(PgAioHandle *ioh) pg_unreachable(); } +/* + * Release a transient descriptor opened for a worker-executed fsync. + */ +static void +smgr_aio_close(PgAioHandle *ioh) +{ + PgAioOpData *od = pgaio_io_get_op_data(ioh); + + if (pgaio_io_get_op(ioh) == PGAIO_OP_FSYNC) + { + (void) CloseTransientFile(od->fsync.fd); + od->fsync.fd = -1; + } +} + /* * Callback for the smgr AIO target, describing the target of the IO. */ @@ -1121,7 +1156,14 @@ smgr_aio_describe_identity(const PgAioTargetData *sd) sd->smgr.forkNum); if (sd->smgr.nblocks == 0) - desc = psprintf(_("file \"%s\""), path.str); + { + BlockNumber segno = sd->smgr.blockNum / ((BlockNumber) RELSEG_SIZE); + + if (segno > 0) + desc = psprintf(_("file \"%s.%u\""), path.str, segno); + else + desc = psprintf(_("file \"%s\""), path.str); + } else if (sd->smgr.nblocks == 1) desc = psprintf(_("block %u in file \"%s\""), sd->smgr.blockNum, diff --git a/src/backend/storage/sync/sync.c b/src/backend/storage/sync/sync.c index 2c964b6f3d9..2442492d6a9 100644 --- a/src/backend/storage/sync/sync.c +++ b/src/backend/storage/sync/sync.c @@ -26,7 +26,10 @@ #include "pgstat.h" #include "portability/instr_time.h" #include "postmaster/bgwriter.h" +#include "storage/aio.h" +#include "storage/bufmgr.h" #include "storage/fd.h" +#include "storage/ipc.h" #include "storage/latch.h" #include "storage/md.h" #include "utils/hsearch.h" @@ -54,11 +57,22 @@ */ typedef uint16 CycleCtr; /* can be any convenient integer size */ -typedef struct +typedef struct PendingFsyncEntry { FileTag tag; /* identifies handler and file */ CycleCtr cycle_ctr; /* sync_cycle_ctr of oldest request */ bool canceled; /* canceled is true if we canceled "recently" */ + + /* + * Set when a request arrives for a tag that already has an entry, and + * cleared whenever an fsync for it is started. If it is set once that + * fsync completes, the request came in while the fsync was in flight, so + * the fsync cannot be assumed to have covered it. + */ + bool re_requested; + + /* fsync is done, pending hash-table bookkeeping */ + bool sync_completed; } PendingFsyncEntry; typedef struct @@ -68,10 +82,43 @@ typedef struct bool canceled; /* true if request has been canceled */ } PendingUnlinkEntry; +/* + * Transient state used while processing a batch of fsync requests. A single + * SyncState instance lives on the stack of ProcessSyncRequests() so that no + * partial state survives across calls. + */ +typedef struct SyncState +{ + dlist_head inflight; /* InflightSyncEntry being fsync'd right now */ + dlist_head retry; /* InflightSyncEntry to be retried */ + int inflight_count; /* number of entries in "inflight" */ + int absorb_counter; + + /* stats */ + int processed; + instr_time longest; + instr_time total_elapsed; +} SyncState; + static HTAB *pendingOps = NULL; static List *pendingUnlinks = NIL; static MemoryContext pendingOpsCxt; /* context for the above */ +/* + * Context for the InflightSyncEntry structs allocated while a batch of fsync + * requests is being processed. It is kept separate from pendingOpsCxt (which + * must survive for the lifetime of the process, as it holds pendingOps + * itself), so that it can be reset between batches. + */ +static MemoryContext inflightSyncCxt; + +/* + * All InflightSyncEntry structs that have not yet been freed. Unlike the + * lists in SyncState, this survives an error so that handler-owned files can + * be closed before their entries are discarded. + */ +static dlist_head activeSyncEntries = DLIST_STATIC_INIT(activeSyncEntries); + static CycleCtr sync_cycle_ctr = 0; static CycleCtr checkpoint_cycle_ctr = 0; @@ -84,10 +131,11 @@ static CycleCtr checkpoint_cycle_ctr = 0; */ typedef struct SyncOps { - int (*sync_syncfiletag) (const FileTag *ftag, char *path); + void (*sync_syncfiletag) (PgAioHandle *ioh, InflightSyncEntry *entry); int (*sync_unlinkfiletag) (const FileTag *ftag, char *path); bool (*sync_filetagmatches) (const FileTag *ftag, const FileTag *candidate); + bool uses_transient_fd; } SyncOps; /* @@ -98,23 +146,28 @@ static const SyncOps syncsw[] = { [SYNC_HANDLER_MD] = { .sync_syncfiletag = mdsyncfiletag, .sync_unlinkfiletag = mdunlinkfiletag, - .sync_filetagmatches = mdfiletagmatches + .sync_filetagmatches = mdfiletagmatches, + .uses_transient_fd = false }, /* pg_xact */ [SYNC_HANDLER_CLOG] = { - .sync_syncfiletag = clogsyncfiletag + .sync_syncfiletag = clogsyncfiletag, + .uses_transient_fd = true }, /* pg_commit_ts */ [SYNC_HANDLER_COMMIT_TS] = { - .sync_syncfiletag = committssyncfiletag + .sync_syncfiletag = committssyncfiletag, + .uses_transient_fd = true }, /* pg_multixact/offsets */ [SYNC_HANDLER_MULTIXACT_OFFSET] = { - .sync_syncfiletag = multixactoffsetssyncfiletag + .sync_syncfiletag = multixactoffsetssyncfiletag, + .uses_transient_fd = true }, /* pg_multixact/members */ [SYNC_HANDLER_MULTIXACT_MEMBER] = { - .sync_syncfiletag = multixactmemberssyncfiletag + .sync_syncfiletag = multixactmemberssyncfiletag, + .uses_transient_fd = true } }; @@ -155,6 +208,10 @@ InitSync(void) &hash_ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); pendingUnlinks = NIL; + + inflightSyncCxt = AllocSetContextCreate(TopMemoryContext, + "Inflight sync context", + ALLOCSET_DEFAULT_SIZES); } } @@ -281,25 +338,373 @@ SyncPostCheckpoint(void) } /* - * ProcessSyncRequests() -- Process queued fsync requests. + * Close the file that a sync handler opened for an in-flight fsync. */ -void -ProcessSyncRequests(void) +static void +sync_close_file(InflightSyncEntry *entry) { - static bool sync_in_progress = false; + switch (entry->close_method) + { + case SYNC_CLOSE_NONE: + break; + case SYNC_CLOSE_TRANSIENT: + CloseTransientFile(entry->close_file); + break; + case SYNC_CLOSE_VFD: + FileClose((File) entry->close_file); + break; + default: + pg_unreachable(); + } + + entry->close_method = SYNC_CLOSE_NONE; +} + +static void +sync_free_entry(InflightSyncEntry *entry) +{ + dlist_delete_from(&activeSyncEntries, &entry->cleanup_node); + pfree(entry); +} + +/* + * Error cleanup callback for ProcessSyncRequests(). + */ +static void +sync_cleanup_inflight(int code, Datum arg) +{ + int save_errno = 0; + char path[MAXPGPATH]; + + /* Do not let an interrupt abandon the remaining IOs during cleanup. */ + HOLD_INTERRUPTS(); + + while (!dlist_is_empty(&activeSyncEntries)) + { + dlist_node *node = dlist_pop_head_node(&activeSyncEntries); + InflightSyncEntry *entry; + int result; + + entry = dlist_container(InflightSyncEntry, cleanup_node, node); + + if (entry->started) + { + pgaio_wref_wait(&entry->iow); + result = -entry->ioret.result.result; + } + else + result = entry->open_errno; + + /* + * These IOs have no error-reporting completion callback. Even though + * the checkpoint has already failed, we must not discard a durability + * error that requires PANIC, including a recorded failure to open the + * file. As in sync_drain_one(), ignore canceled requests and allow a + * first failure that could be due to deletion. Leave retries to the + * next checkpoint. + * + * Save the first such error without allocating memory or raising + * another ERROR, so that all outstanding IOs are cleaned up. + */ + if (result != 0 && save_errno == 0 && + !entry->hash_entry->canceled && + (!FILE_POSSIBLY_DELETED(result) || entry->retry_count > 0) && + data_sync_elevel(ERROR) == PANIC) + { + save_errno = result; + strlcpy(path, entry->path, sizeof(path)); + } + + sync_close_file(entry); + pfree(entry); + } + + RESUME_INTERRUPTS(); + + if (save_errno != 0) + { + errno = save_errno; + ereport(data_sync_elevel(ERROR), + (errcode_for_file_access(), + errmsg("could not fsync file \"%s\": %m", path))); + } +} + +static void +sync_start_one(SyncState *sync_state, InflightSyncEntry *entry) +{ + struct PgAioHandle *ioh; + instr_time io_start; + + entry->started = false; + entry->open_errno = 0; + entry->close_method = SYNC_CLOSE_NONE; + INSTR_TIME_SET_ZERO(entry->io_time); + pgaio_wref_clear(&entry->iow); + + /* + * Any request that arrives from here on may cover data that the fsync + * started below does not, so start out with a clean slate. This has to + * happen before the IO is submitted; requests absorbed in between are + * covered by the fsync, so treating them as newer is merely conservative. + */ + entry->hash_entry->re_requested = false; + + ioh = pgaio_io_acquire(CurrentResourceOwner, &entry->ioret); + pgaio_io_get_wref(ioh, &entry->iow); + + /* + * The handler opens the file, assigns the target and stages the fsync. + * Hold interrupts so that the referenced descriptor cannot be closed + * during submission. + */ + HOLD_INTERRUPTS(); + INSTR_TIME_SET_CURRENT(io_start); + syncsw[entry->tag.handler].sync_syncfiletag(ioh, entry); + INSTR_TIME_SET_CURRENT(entry->io_time); + RESUME_INTERRUPTS(); + INSTR_TIME_SUBTRACT(entry->io_time, io_start); + + if (!entry->started) + pgaio_io_release(ioh); + + Assert(!entry->started || + (entry->close_method == SYNC_CLOSE_TRANSIENT) == + syncsw[entry->tag.handler].uses_transient_fd); + + dlist_push_tail(&sync_state->inflight, &entry->node); + sync_state->inflight_count++; + + Assert(sync_state->inflight_count <= io_max_concurrency); +} + +static void +sync_drain_one(SyncState *sync_state) +{ + dlist_node *node; + InflightSyncEntry *entry; + int result; + instr_time io_time; + + Assert(sync_state->inflight_count > 0); + + node = dlist_pop_head_node(&sync_state->inflight); + entry = dlist_container(InflightSyncEntry, node, node); + sync_state->inflight_count--; + if (entry->started) + { + if (entry->ioret.result.status == PGAIO_RS_UNKNOWN && + !pgaio_wref_check_done(&entry->iow)) + { + instr_time io_start; + instr_time io_end; + bool track_stat_time; + + track_stat_time = entry->tag.handler == SYNC_HANDLER_MD && + track_io_timing; + INSTR_TIME_SET_CURRENT(io_start); + pgaio_wref_wait(&entry->iow); + INSTR_TIME_SET_CURRENT(io_end); + + /* + * The operation itself was counted when it was started. Add only + * time actually spent waiting for relation IO to complete. + */ + if (track_stat_time) + pgstat_count_io_op_time_end(IOOBJECT_RELATION, + IOCONTEXT_NORMAL, IOOP_FSYNC, + io_start, io_end, 0, 0); + + INSTR_TIME_ACCUM_DIFF(entry->io_time, io_end, io_start); + } + + /* + * We did not register a completion callback, so the distilled status + * is always PGAIO_RS_OK and the raw fsync() return value (0 on + * success, -errno on failure) is available in ->result.result. + */ + result = -entry->ioret.result.result; + } + else + result = entry->open_errno; + + sync_close_file(entry); + io_time = entry->io_time; + + if (!result) + { + if (INSTR_TIME_GT(io_time, sync_state->longest)) + sync_state->longest = io_time; + INSTR_TIME_ADD(sync_state->total_elapsed, io_time); + + sync_state->processed++; + + if (log_checkpoints) + elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f ms", + sync_state->processed, + entry->path, + INSTR_TIME_GET_MILLISEC(io_time)); + + entry->hash_entry->sync_completed = true; + sync_free_entry(entry); + } + else + { + /* + * The request may have been canceled after we started the fsync, e.g. + * because the relation was dropped in the meantime and an intervening + * AbsorbSyncRequests() picked up the cancel message. Since + * mdunlink() queues the "cancel" before actually unlinking, a + * cancellation means the failure is expected and the entry can simply + * be dropped. + * + * The upstream, synchronous code checked this at the top of its retry + * loop; because the fsync is now in flight while requests are being + * absorbed, we have to re-check it here. + */ + if (entry->hash_entry->canceled) + { + entry->hash_entry->sync_completed = true; + sync_free_entry(entry); + return; + } + + /* + * It is possible that the relation has been dropped or truncated + * since the fsync request was entered. Therefore, allow ENOENT, but + * only if we didn't fail already on this file. + */ + errno = result; + if (!FILE_POSSIBLY_DELETED(errno) || entry->retry_count > 0) + ereport(data_sync_elevel(ERROR), + (errcode_for_file_access(), + errmsg("could not fsync file \"%s\": %m", + entry->path))); + else + ereport(DEBUG1, + (errcode_for_file_access(), + errmsg_internal("could not fsync file \"%s\" but retrying: %m", + entry->path))); + + /* Cleanup must not check this already-handled result as a retry. */ + entry->started = false; + entry->open_errno = 0; + entry->retry_count++; + dlist_push_tail(&sync_state->retry, &entry->node); + } +} + +static void +sync_drain_all(SyncState *sync_state) +{ + while (sync_state->inflight_count) + sync_drain_one(sync_state); +} + +/* + * Make room for another fsync using the limit appropriate for its handler. + */ +static void +sync_ensure_room(SyncState *sync_state, const FileTag *tag) +{ + int max_inflight; + + max_inflight = + GetFsyncConcurrencyLimit(syncsw[tag->handler].uses_transient_fd); + while (sync_state->inflight_count >= max_inflight) + sync_drain_one(sync_state); +} + +/* + * Finish requests whose fsyncs have completed. + * + * The main hash scan may only remove the entry it most recently returned, so + * completion processing is deferred until it ends. This second scan can then + * remove each completed entry as the current entry. Recheck the hash entry + * now because requests absorbed since the fsync completed may require it to + * remain for the next checkpoint cycle. + */ +static void +sync_process_completed(void) +{ HASH_SEQ_STATUS hstat; PendingFsyncEntry *entry; - int absorb_counter; - /* Statistics on sync times */ - int processed = 0; - instr_time sync_start, - sync_end, - sync_diff; - uint64 elapsed; - uint64 longest = 0; - uint64 total_elapsed = 0; + hash_seq_init(&hstat, pendingOps); + while ((entry = (PendingFsyncEntry *) hash_seq_search(&hstat)) != NULL) + { + if (!entry->sync_completed) + continue; + + /* + * We are done with this entry, unless a request for it arrived while + * the fsync was in flight. A cancel supersedes any such request, as + * RememberSyncRequest() clears "canceled" when it records a new one. + */ + if (!entry->re_requested || entry->canceled) + { + if (hash_search(pendingOps, &entry->tag, HASH_REMOVE, NULL) == NULL) + elog(ERROR, "pendingOps corrupted"); + } + else + entry->sync_completed = false; + } +} + +/* + * Reissue any fsync requests that previously failed with an ignorable error. + * + * The fsync table could contain requests to fsync segments that have been + * deleted (unlinked) by the time we get to them. Rather than just hoping an + * ENOENT (or EACCES on Windows) error can be ignored, what we do on error is + * absorb pending requests and then retry. Since mdunlink() queues a "cancel" + * message before actually unlinking, the fsync request is guaranteed to be + * marked canceled after the absorb if it really was this case. + */ +static void +sync_process_retries(SyncState *sync_state) +{ + if (dlist_is_empty(&sync_state->retry)) + return; + + AbsorbSyncRequests(); + + while (!dlist_is_empty(&sync_state->retry)) + { + dlist_node *node = dlist_pop_head_node(&sync_state->retry); + InflightSyncEntry *entry = dlist_container(InflightSyncEntry, node, node); + + if (entry->hash_entry->canceled) + { + /* Safe to remove here, the scan has already finished. */ + if (hash_search(pendingOps, &entry->hash_entry->tag, + HASH_REMOVE, NULL) == NULL) + elog(ERROR, "pendingOps corrupted"); + sync_free_entry(entry); + continue; + } + + sync_ensure_room(sync_state, &entry->tag); + sync_start_one(sync_state, entry); + } + + sync_drain_all(sync_state); + sync_process_completed(); +} + +/* + * Process queued fsync requests. The public wrapper ensures that any error + * closes files owned by in-flight entries. + */ +static void +ProcessSyncRequestsInternal(void) +{ + static bool sync_in_progress = false; + + HASH_SEQ_STATUS hstat; + PendingFsyncEntry *entry; + SyncState sync_state; /* * This is only called during checkpoints, and checkpoints should only @@ -350,6 +755,7 @@ ProcessSyncRequests(void) while ((entry = (PendingFsyncEntry *) hash_seq_search(&hstat)) != NULL) { entry->cycle_ctr = sync_cycle_ctr; + entry->sync_completed = false; } } @@ -359,17 +765,27 @@ ProcessSyncRequests(void) /* Set flag to detect failure if we don't reach the end of the loop */ sync_in_progress = true; + /* + * The limit for each request depends on whether its handler holds a + * transient descriptor until completion. + */ + dlist_init(&sync_state.inflight); + dlist_init(&sync_state.retry); + sync_state.inflight_count = 0; + sync_state.processed = 0; + INSTR_TIME_SET_ZERO(sync_state.longest); + INSTR_TIME_SET_ZERO(sync_state.total_elapsed); + + Assert(dlist_is_empty(&activeSyncEntries)); + MemoryContextReset(inflightSyncCxt); + /* Now scan the hashtable for fsync requests to process */ - absorb_counter = FSYNCS_PER_ABSORB; + sync_state.absorb_counter = FSYNCS_PER_ABSORB; hash_seq_init(&hstat, pendingOps); while ((entry = (PendingFsyncEntry *) hash_seq_search(&hstat)) != NULL) { - int failures; - /* - * If the entry is new then don't process it this time; it is new. - * Note "continue" bypasses the hash-remove call at the bottom of the - * loop. + * Leave requests added in this cycle for the next checkpoint. */ if (entry->cycle_ctr == sync_cycle_ctr) continue; @@ -378,103 +794,92 @@ ProcessSyncRequests(void) Assert((CycleCtr) (entry->cycle_ctr + 1) == sync_cycle_ctr); /* - * If fsync is off then we don't have to bother opening the file at - * all. (We delay checking until this point so that changing fsync on - * the fly behaves sensibly.) + * If in checkpointer, we want to absorb pending requests every so + * often to prevent overflow of the fsync request queue. It is + * unspecified whether newly-added entries will be visited by + * hash_seq_search, but we don't care since we don't need to process + * them anyway. */ - if (enableFsync) + if (enableFsync && --sync_state.absorb_counter <= 0) { - /* - * If in checkpointer, we want to absorb pending requests every so - * often to prevent overflow of the fsync request queue. It is - * unspecified whether newly-added entries will be visited by - * hash_seq_search, but we don't care since we don't need to - * process them anyway. - */ - if (--absorb_counter <= 0) - { - AbsorbSyncRequests(); - absorb_counter = FSYNCS_PER_ABSORB; - } + AbsorbSyncRequests(); + sync_state.absorb_counter = FSYNCS_PER_ABSORB; + } + + if (!enableFsync || entry->canceled) + { + /* We are done with this entry, remove it */ + if (hash_search(pendingOps, &entry->tag, HASH_REMOVE, NULL) == NULL) + elog(ERROR, "pendingOps corrupted"); + } + else + { + InflightSyncEntry *inflight_entry; + + sync_ensure_room(&sync_state, &entry->tag); /* - * The fsync table could contain requests to fsync segments that - * have been deleted (unlinked) by the time we get to them. Rather - * than just hoping an ENOENT (or EACCES on Windows) error can be - * ignored, what we do on error is absorb pending requests and - * then retry. Since mdunlink() queues a "cancel" message before - * actually unlinking, the fsync request is guaranteed to be - * marked canceled after the absorb if it really was this case. - * DROP DATABASE likewise has to tell us to forget fsync requests - * before it starts deletions. + * Mark the entry as already dealt with in this cycle. It must + * remain in the hash table until its fsync completes and the scan + * ends. If a new request arrives meanwhile, this cycle counter + * leaves the entry to be processed by the next checkpoint. */ - for (failures = 0; !entry->canceled; failures++) - { - char path[MAXPGPATH]; - - INSTR_TIME_SET_CURRENT(sync_start); - if (syncsw[entry->tag.handler].sync_syncfiletag(&entry->tag, - path) == 0) - { - /* Success; update statistics about sync timing */ - INSTR_TIME_SET_CURRENT(sync_end); - sync_diff = sync_end; - INSTR_TIME_SUBTRACT(sync_diff, sync_start); - elapsed = INSTR_TIME_GET_MICROSEC(sync_diff); - if (elapsed > longest) - longest = elapsed; - total_elapsed += elapsed; - processed++; - - if (log_checkpoints) - elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f ms", - processed, - path, - (double) elapsed / 1000); - - break; /* out of retry loop */ - } - - /* - * It is possible that the relation has been dropped or - * truncated since the fsync request was entered. Therefore, - * allow ENOENT, but only if we didn't fail already on this - * file. - */ - if (!FILE_POSSIBLY_DELETED(errno) || failures > 0) - ereport(data_sync_elevel(ERROR), - (errcode_for_file_access(), - errmsg("could not fsync file \"%s\": %m", - path))); - else - ereport(DEBUG1, - (errcode_for_file_access(), - errmsg_internal("could not fsync file \"%s\" but retrying: %m", - path))); - - /* - * Absorb incoming requests and check to see if a cancel - * arrived for this relation fork. - */ - AbsorbSyncRequests(); - absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */ - } /* end retry loop */ + entry->cycle_ctr = sync_cycle_ctr; + + inflight_entry = MemoryContextAllocZero(inflightSyncCxt, + sizeof(InflightSyncEntry)); + inflight_entry->tag = entry->tag; + inflight_entry->hash_entry = entry; + dlist_push_tail(&activeSyncEntries, + &inflight_entry->cleanup_node); + + sync_start_one(&sync_state, inflight_entry); } + } + + sync_drain_all(&sync_state); + sync_process_completed(); + + /* + * A second failure raises an error, so normally one retry pass is enough. + * Keep an explicit bound in case that changes. + */ + for (int failures = 0; failures < 5; failures++) + { + if (dlist_is_empty(&sync_state.retry)) + break; + + sync_process_retries(&sync_state); + } - /* We are done with this entry, remove it */ - if (hash_search(pendingOps, &entry->tag, HASH_REMOVE, NULL) == NULL) - elog(ERROR, "pendingOps corrupted"); - } /* end loop over hashtable entries */ + if (!dlist_is_empty(&sync_state.inflight) || + !dlist_is_empty(&sync_state.retry)) + elog(PANIC, "in-flight sync requests remain after ProcessSyncRequests"); /* Return sync performance metrics for report at checkpoint end */ - CheckpointStats.ckpt_sync_rels = processed; - CheckpointStats.ckpt_longest_sync = longest; - CheckpointStats.ckpt_agg_sync_time = total_elapsed; + CheckpointStats.ckpt_sync_rels = sync_state.processed; + CheckpointStats.ckpt_longest_sync = INSTR_TIME_GET_MICROSEC(sync_state.longest); + CheckpointStats.ckpt_agg_sync_time = INSTR_TIME_GET_MICROSEC(sync_state.total_elapsed); /* Flag successful completion of ProcessSyncRequests */ sync_in_progress = false; } +/* + * ProcessSyncRequests() -- Process queued fsync requests. + */ +void +ProcessSyncRequests(void) +{ + PG_ENSURE_ERROR_CLEANUP(sync_cleanup_inflight, (Datum) 0); + { + ProcessSyncRequestsInternal(); + } + PG_END_ENSURE_ERROR_CLEANUP(sync_cleanup_inflight, (Datum) 0); + + Assert(dlist_is_empty(&activeSyncEntries)); +} + /* * RememberSyncRequest() -- callback from checkpointer side of sync request * @@ -554,11 +959,20 @@ RememberSyncRequest(const FileTag *ftag, SyncRequestType type) ftag, HASH_ENTER, &found); + + /* + * If an entry already existed, an fsync for it may be in flight right + * now, in which case it cannot be assumed to cover this request; see + * sync_drain_one(). + */ + entry->re_requested = found; + /* if new entry, or was previously canceled, initialize it */ if (!found || entry->canceled) { entry->cycle_ctr = sync_cycle_ctr; entry->canceled = false; + entry->sync_completed = false; } /* diff --git a/src/backend/utils/activity/pgstat_io.c b/src/backend/utils/activity/pgstat_io.c index 8ec1aad5078..761847fac05 100644 --- a/src/backend/utils/activity/pgstat_io.c +++ b/src/backend/utils/activity/pgstat_io.c @@ -99,6 +99,26 @@ pgstat_prepare_io_time(bool track_io_guc) return io_start; } +/* + * Like pgstat_count_io_op_time_end() except IO end time is not supplied, it + * is calculated inside of the function. + */ +void +pgstat_count_io_op_time(IOObject io_object, IOContext io_context, IOOp io_op, + instr_time start_time, uint32 cnt, uint64 bytes) +{ + if (!INSTR_TIME_IS_ZERO(start_time)) + { + instr_time cur_time; + + INSTR_TIME_SET_CURRENT(cur_time); + pgstat_count_io_op_time_end(io_object, io_context, io_op, + start_time, cur_time, cnt, bytes); + } + else + pgstat_count_io_op(io_object, io_context, io_op, cnt, bytes); +} + /* * Like pgstat_count_io_op() except it also accumulates time. * @@ -111,42 +131,41 @@ pgstat_prepare_io_time(bool track_io_guc) * activity of temporary blocks, so these are ignored here. */ void -pgstat_count_io_op_time(IOObject io_object, IOContext io_context, IOOp io_op, - instr_time start_time, uint32 cnt, uint64 bytes) +pgstat_count_io_op_time_end(IOObject io_object, IOContext io_context, IOOp io_op, + instr_time start_time, instr_time end_time, uint32 cnt, + uint64 bytes) { if (!INSTR_TIME_IS_ZERO(start_time)) { - instr_time io_time; - - INSTR_TIME_SET_CURRENT(io_time); - INSTR_TIME_SUBTRACT(io_time, start_time); + Assert(!INSTR_TIME_GT(start_time, end_time)); + INSTR_TIME_SUBTRACT(end_time, start_time); if (io_object != IOOBJECT_WAL) { if (io_op == IOOP_WRITE || io_op == IOOP_EXTEND) { - pgstat_count_buffer_write_time(INSTR_TIME_GET_MICROSEC(io_time)); + pgstat_count_buffer_write_time(INSTR_TIME_GET_MICROSEC(end_time)); if (io_object == IOOBJECT_RELATION) - INSTR_TIME_ADD(pgBufferUsage.shared_blk_write_time, io_time); + INSTR_TIME_ADD(pgBufferUsage.shared_blk_write_time, end_time); else if (io_object == IOOBJECT_TEMP_RELATION) - INSTR_TIME_ADD(pgBufferUsage.local_blk_write_time, io_time); + INSTR_TIME_ADD(pgBufferUsage.local_blk_write_time, end_time); } else if (io_op == IOOP_READ) { - pgstat_count_buffer_read_time(INSTR_TIME_GET_MICROSEC(io_time)); + pgstat_count_buffer_read_time(INSTR_TIME_GET_MICROSEC(end_time)); if (io_object == IOOBJECT_RELATION) - INSTR_TIME_ADD(pgBufferUsage.shared_blk_read_time, io_time); + INSTR_TIME_ADD(pgBufferUsage.shared_blk_read_time, end_time); else if (io_object == IOOBJECT_TEMP_RELATION) - INSTR_TIME_ADD(pgBufferUsage.local_blk_read_time, io_time); + INSTR_TIME_ADD(pgBufferUsage.local_blk_read_time, end_time); } } INSTR_TIME_ADD(PendingIOStats.pending_times[io_object][io_context][io_op], - io_time); + end_time); /* Add the per-backend count */ pgstat_count_backend_io_op_time(io_object, io_context, io_op, - io_time); + end_time); } pgstat_count_io_op(io_object, io_context, io_op, cnt, bytes); diff --git a/src/include/access/clog.h b/src/include/access/clog.h index 7894998c763..e089106f7fe 100644 --- a/src/include/access/clog.h +++ b/src/include/access/clog.h @@ -47,7 +47,7 @@ extern void CheckPointCLOG(void); extern void ExtendCLOG(TransactionId newestXact); extern void TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid); -extern int clogsyncfiletag(const FileTag *ftag, char *path); +extern void clogsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); /* XLOG stuff */ #define CLOG_ZEROPAGE 0x00 diff --git a/src/include/access/commit_ts.h b/src/include/access/commit_ts.h index 825ccda90ed..fa4880e0d03 100644 --- a/src/include/access/commit_ts.h +++ b/src/include/access/commit_ts.h @@ -38,7 +38,7 @@ extern void SetCommitTsLimit(TransactionId oldestXact, TransactionId newestXact); extern void AdvanceOldestCommitTsXid(TransactionId oldestXact); -extern int committssyncfiletag(const FileTag *ftag, char *path); +extern void committssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); /* XLOG stuff */ #define COMMIT_TS_ZEROPAGE 0x00 diff --git a/src/include/access/multixact.h b/src/include/access/multixact.h index 6be5299ab68..3f980b4120d 100644 --- a/src/include/access/multixact.h +++ b/src/include/access/multixact.h @@ -114,8 +114,8 @@ extern bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2); extern bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2); -extern int multixactoffsetssyncfiletag(const FileTag *ftag, char *path); -extern int multixactmemberssyncfiletag(const FileTag *ftag, char *path); +extern void multixactoffsetssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern void multixactmemberssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); extern void AtEOXact_MultiXact(void); extern void AtPrepare_MultiXact(void); diff --git a/src/include/access/slru.h b/src/include/access/slru.h index b4adb1789c7..0e91df5609c 100644 --- a/src/include/access/slru.h +++ b/src/include/access/slru.h @@ -240,7 +240,7 @@ typedef bool (*SlruScanCallback) (SlruDesc *ctl, char *filename, int64 segpage, extern bool SlruScanDirectory(SlruDesc *ctl, SlruScanCallback callback, void *data); extern void SlruDeleteSegment(SlruDesc *ctl, int64 segno); -extern int SlruSyncFileTag(SlruDesc *ctl, const FileTag *ftag, char *path); +extern void SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, struct InflightSyncEntry *entry); /* SlruScanDirectory public callbacks */ extern bool SlruScanDirCbReportPresence(SlruDesc *ctl, char *filename, diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 187d82c96fe..8c91aa4ef85 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -703,6 +703,10 @@ extern instr_time pgstat_prepare_io_time(bool track_io_guc); extern void pgstat_count_io_op_time(IOObject io_object, IOContext io_context, IOOp io_op, instr_time start_time, uint32 cnt, uint64 bytes); +extern void pgstat_count_io_op_time_end(IOObject io_object, IOContext io_context, + IOOp io_op, instr_time start_time, + instr_time end_time, uint32 cnt, + uint64 bytes); extern PgStat_IO *pgstat_fetch_stat_io(void); extern const char *pgstat_get_io_context_name(IOContext io_context); diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index 7f056f43e78..6ea230ccad5 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -176,6 +176,12 @@ struct PgAioTargetInfo */ int (*reopen) (PgAioHandle *ioh); + /* + * Optional counterpart to reopen, releasing the file descriptor it + * acquired once the IO has been executed. + */ + void (*close) (PgAioHandle *ioh); + /* describe the target of the IO, used for log messages and views */ char *(*describe_identity) (const PgAioTargetData *sd); diff --git a/src/include/storage/aio_internal.h b/src/include/storage/aio_internal.h index 35d4f3f310d..ccf0fe4c7bf 100644 --- a/src/include/storage/aio_internal.h +++ b/src/include/storage/aio_internal.h @@ -360,6 +360,7 @@ extern int pgaio_io_get_iovec_length(PgAioHandle *ioh, struct iovec **iov); /* aio_target.c */ extern bool pgaio_io_can_reopen(PgAioHandle *ioh); extern int pgaio_io_reopen(PgAioHandle *ioh); +extern void pgaio_io_close_reopened(PgAioHandle *ioh); extern const char *pgaio_io_get_target_name(PgAioHandle *ioh); diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h index c79f3312544..49f93b6a7ad 100644 --- a/src/include/storage/fd.h +++ b/src/include/storage/fd.h @@ -138,6 +138,7 @@ extern int FilePrefetch(File file, pgoff_t offset, pgoff_t amount, uint32 wait_e extern ssize_t FileReadV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info); extern ssize_t FileWriteV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info); extern int FileStartReadV(struct PgAioHandle *ioh, File file, int iovcnt, pgoff_t offset, uint32 wait_event_info); +extern int FileStartSync(struct PgAioHandle *ioh, File file, bool datasync, uint32 wait_event_info); extern int FileSync(File file, uint32 wait_event_info); extern int FileZero(File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info); extern int FileFallocate(File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info); @@ -219,7 +220,7 @@ extern int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int extern int durable_rename(const char *oldfile, const char *newfile, int elevel); extern int durable_unlink(const char *fname, int elevel); extern void SyncDataDirectory(void); -extern int GetFsyncConcurrencyLimit(void); +extern int GetFsyncConcurrencyLimit(bool uses_transient_fd); extern int data_sync_elevel(int elevel); static inline ssize_t diff --git a/src/include/storage/md.h b/src/include/storage/md.h index b8d10329eb8..9f03354c2bc 100644 --- a/src/include/storage/md.h +++ b/src/include/storage/md.h @@ -53,12 +53,13 @@ extern void mdtruncate(SMgrRelation reln, ForkNumber forknum, extern void mdimmedsync(SMgrRelation reln, ForkNumber forknum); extern void mdregistersync(SMgrRelation reln, ForkNumber forknum); extern int mdfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, uint32 *off); +extern int mdfsyncfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum); extern void ForgetDatabaseSyncRequests(Oid dbid); extern void DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo); /* md sync callbacks */ -extern int mdsyncfiletag(const FileTag *ftag, char *path); +extern void mdsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); extern int mdunlinkfiletag(const FileTag *ftag, char *path); extern bool mdfiletagmatches(const FileTag *ftag, const FileTag *candidate); diff --git a/src/include/storage/sync.h b/src/include/storage/sync.h index 88290500bc9..8d48151730f 100644 --- a/src/include/storage/sync.h +++ b/src/include/storage/sync.h @@ -13,6 +13,9 @@ #ifndef SYNC_H #define SYNC_H +#include "lib/ilist.h" +#include "portability/instr_time.h" +#include "storage/aio_types.h" #include "storage/relfilelocator.h" /* @@ -55,6 +58,58 @@ typedef struct FileTag uint64 segno; } FileTag; +struct PendingFsyncEntry; +struct PgAioHandle; + +/* + * How the file opened by a sync handler must be closed once its asynchronous + * fsync has completed. + */ +typedef enum SyncFileCloseMethod +{ + SYNC_CLOSE_NONE = 0, /* nothing to close */ + SYNC_CLOSE_TRANSIENT, /* CloseTransientFile(close_file) */ + SYNC_CLOSE_VFD, /* FileClose((File) close_file) */ +} SyncFileCloseMethod; + +/* + * State for a single in-flight asynchronous fsync request. A sync handler + * opens the file to be synced, fills in the fields it is responsible for, and + * starts an asynchronous fsync on the AIO handle it is given. + */ +typedef struct InflightSyncEntry +{ + FileTag tag; /* identifies handler and file */ + + char path[MAXPGPATH]; + + /* + * Set by the handler: whether it started an asynchronous fsync on the + * passed-in AIO handle. If the file could not be opened, the handler + * sets started = false and open_errno to the errno of the failed open. + */ + bool started; + int open_errno; + + /* set by the handler: how to close the opened file after completion */ + SyncFileCloseMethod close_method; + int close_file; /* fd, or File, depending on close_method */ + + struct PendingFsyncEntry *hash_entry; + + int retry_count; + instr_time io_time; /* time spent starting and waiting */ + + PgAioReturn ioret; + PgAioWaitRef iow; + + /* membership in the inflight / retry lists */ + dlist_node node; + + /* membership in the error-cleanup list */ + dlist_node cleanup_node; +} InflightSyncEntry; + extern void InitSync(void); extern void SyncPreCheckpoint(void); extern void SyncPostCheckpoint(void); diff --git a/src/test/modules/test_slru/test_slru.c b/src/test/modules/test_slru/test_slru.c index 40efffdbf62..ccac09a9285 100644 --- a/src/test/modules/test_slru/test_slru.c +++ b/src/test/modules/test_slru/test_slru.c @@ -17,10 +17,13 @@ #include "access/slru.h" #include "access/transam.h" #include "miscadmin.h" +#include "storage/aio.h" #include "storage/fd.h" #include "storage/ipc.h" #include "storage/shmem.h" +#include "storage/sync.h" #include "utils/builtins.h" +#include "utils/resowner.h" PG_MODULE_MAGIC; @@ -152,15 +155,47 @@ Datum test_slru_page_sync(PG_FUNCTION_ARGS) { int64 pageno = PG_GETARG_INT64(0); - FileTag ftag; - char path[MAXPGPATH]; + InflightSyncEntry entry = {0}; + PgAioHandle *ioh; + int result; /* note that this flushes the full file a segment is located in */ - ftag.segno = pageno / SLRU_PAGES_PER_SEGMENT; - SlruSyncFileTag(TestSlruCtl, &ftag, path); + entry.tag.segno = pageno / SLRU_PAGES_PER_SEGMENT; + + /* + * SlruSyncFileTag() now performs the fsync asynchronously. Drive it the + * same way sync.c does: acquire an AIO handle, let the handler start the + * fsync, wait for its completion and close the file it opened. + */ + ioh = pgaio_io_acquire(CurrentResourceOwner, &entry.ioret); + pgaio_io_get_wref(ioh, &entry.iow); + + HOLD_INTERRUPTS(); + SlruSyncFileTag(TestSlruCtl, ioh, &entry); + RESUME_INTERRUPTS(); + + if (entry.started) + { + pgaio_wref_wait(&entry.iow); + result = -entry.ioret.result.result; + CloseTransientFile(entry.close_file); + } + else + { + pgaio_io_release(ioh); + result = entry.open_errno; + } + + if (result != 0) + { + errno = result; + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not fsync file \"%s\": %m", entry.path))); + } elog(NOTICE, "Called SlruSyncFileTag() for segment %" PRIu64 " on path %s", - ftag.segno, path); + entry.tag.segno, entry.path); PG_RETURN_VOID(); } diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 21bf56da4fa..c5ed5bc6c0f 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1338,6 +1338,7 @@ IndexVacuumInfo IndxInfo InferClause InferenceElem +InflightSyncEntry InfoItem InhInfo InheritableSocket @@ -3050,12 +3051,14 @@ SupportRequestSimplify SupportRequestSimplifyAggref SupportRequestWFuncMonotonic Syn +SyncFileCloseMethod SyncOps SyncRepConfigData SyncRepStandbyData SyncRequestHandler SyncRequestType SyncStandbySlotsConfigData +SyncState SyncingRelationsState SysCacheIdentifier SysFKRelationship -- 2.47.3
v2-0007-aio-Allow-IO-workers-to-execute-SLRU-fsyncs.patch (text/x-patch, 17.7K) download From ef979e23f2c0c0a9c238dad1f21f1309b8c5952f Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Tue, 25 Aug 2026 15:00:40 +0300 Subject: [PATCH v2 7/8] aio: Allow IO workers to execute SLRU fsyncs The SLRU fsyncs introduced by the preceding commit use the generic PGAIO_TID_SYNC target. It does not store paths in shared memory, so I/O workers cannot reopen the files and the checkpointer must perform the operations itself. Add PGAIO_TID_SYNC_FILETAG, which identifies a file by the FileTag registered with sync.c. A FileTag contains enough information to reopen the file in another process. Dispatch reopening through an optional SyncOps callback, implemented for SLRUs using the new SlruOpenFileTag(). SLRUs that are not registered with sync.c continue to use PGAIO_TID_SYNC. Define the shared FileTag representation in storage/aio_types.h so PgAioTargetData can store it directly without duplicating its layout. Describe the target using the SLRU name and segment number, and return worker-side open failures to the checkpointer as negative errno values. Like relation fsyncs, the FileTag target opens a transient descriptor for each operation. Use the existing PgAioTargetInfo close callback to release it after execution, and document that the callback runs in a critical section. SLRU_FLUSH_SYNC is now reported by the I/O worker rather than the checkpointer, as for relation fsyncs. SyncDataDirectory() continues to use PGAIO_TID_SYNC because its files have no FileTag. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- src/backend/access/transam/clog.c | 8 +- src/backend/access/transam/commit_ts.c | 8 +- src/backend/access/transam/multixact.c | 16 +++- src/backend/access/transam/slru.c | 32 ++++++- src/backend/storage/aio/aio_target.c | 2 + src/backend/storage/sync/sync.c | 123 ++++++++++++++++++++++++- src/include/access/clog.h | 1 + src/include/access/commit_ts.h | 1 + src/include/access/multixact.h | 2 + src/include/access/slru.h | 1 + src/include/storage/aio.h | 9 +- src/include/storage/aio_types.h | 14 +++ src/include/storage/sync.h | 19 ++-- src/tools/pgindent/typedefs.list | 1 + 14 files changed, 213 insertions(+), 24 deletions(-) diff --git a/src/backend/access/transam/clog.c b/src/backend/access/transam/clog.c index 89fb77ea5da..0fe0491d877 100644 --- a/src/backend/access/transam/clog.c +++ b/src/backend/access/transam/clog.c @@ -1115,10 +1115,16 @@ clog_redo(XLogReaderState *record) } /* - * Entrypoint for sync.c to sync clog files. + * Entrypoints for sync.c to sync and reopen clog files. */ void clogsyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { SlruSyncFileTag(XactCtl, ioh, entry); } + +int +clogopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(XactCtl, ftag); +} diff --git a/src/backend/access/transam/commit_ts.c b/src/backend/access/transam/commit_ts.c index 7cbbad383b2..4bb95e415ac 100644 --- a/src/backend/access/transam/commit_ts.c +++ b/src/backend/access/transam/commit_ts.c @@ -1026,10 +1026,16 @@ commit_ts_redo(XLogReaderState *record) } /* - * Entrypoint for sync.c to sync commit_ts files. + * Entrypoints for sync.c to sync and reopen commit_ts files. */ void committssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { SlruSyncFileTag(CommitTsCtl, ioh, entry); } + +int +committsopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(CommitTsCtl, ftag); +} diff --git a/src/backend/access/transam/multixact.c b/src/backend/access/transam/multixact.c index deb0b110ee8..8054a60afba 100644 --- a/src/backend/access/transam/multixact.c +++ b/src/backend/access/transam/multixact.c @@ -3001,7 +3001,7 @@ multixact_redo(XLogReaderState *record) } /* - * Entrypoint for sync.c to sync offsets files. + * Entrypoints for sync.c to sync and reopen offsets files. */ void multixactoffsetssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) @@ -3009,11 +3009,23 @@ multixactoffsetssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) SlruSyncFileTag(MultiXactOffsetCtl, ioh, entry); } +int +multixactoffsetsopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(MultiXactOffsetCtl, ftag); +} + /* - * Entrypoint for sync.c to sync members files. + * Entrypoints for sync.c to sync and reopen members files. */ void multixactmemberssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { SlruSyncFileTag(MultiXactMemberCtl, ioh, entry); } + +int +multixactmembersopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(MultiXactMemberCtl, ftag); +} diff --git a/src/backend/access/transam/slru.c b/src/backend/access/transam/slru.c index b1e513ac3b6..058a58baa52 100644 --- a/src/backend/access/transam/slru.c +++ b/src/backend/access/transam/slru.c @@ -1897,11 +1897,16 @@ SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, InflightSyncEntry *entry } /* - * Use the generic sync target. SLRU segments are not smgr relations and - * cannot be reopened from a FileTag in another process, so this fsync - * will run synchronously in worker mode. + * If this SLRU is registered with sync.c, identify the file by its + * FileTag, so that the fsync can be executed by an IO worker, which will + * reopen the file with SlruOpenFileTag(). Otherwise there is no handler + * to reopen the file through, so use the generic sync target, whose IOs + * cannot be handed off to a worker. */ - pgaio_io_set_target(ioh, PGAIO_TID_SYNC); + if (ctl->options.sync_handler != SYNC_HANDLER_NONE) + pgaio_io_set_target_sync_filetag(ioh, &entry->tag); + else + pgaio_io_set_target(ioh, PGAIO_TID_SYNC); /* Start the asynchronous fsync; the fd is closed once it completes. */ pgaio_io_start_fsync(ioh, fd, false, WAIT_EVENT_SLRU_FLUSH_SYNC); @@ -1910,3 +1915,22 @@ SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, InflightSyncEntry *entry entry->close_method = SYNC_CLOSE_TRANSIENT; entry->close_file = fd; } + +/* + * Counterpart to SlruSyncFileTag(), opening the segment identified by ftag in + * a process that did not stage the IO. As with SlruSyncFileTag(), individual + * SLRUs have to provide the handler function, so that the correct SlruDesc + * is used. + * + * Returns a file descriptor opened with OpenTransientFile(), or -1 with errno + * set. + */ +int +SlruOpenFileTag(SlruDesc *ctl, const FileTag *ftag) +{ + char path[MAXPGPATH]; + + SlruFileName(ctl, path, ftag->segno); + + return OpenTransientFile(path, O_RDWR | PG_BINARY); +} diff --git a/src/backend/storage/aio/aio_target.c b/src/backend/storage/aio/aio_target.c index 534382b423b..a62c194c8f2 100644 --- a/src/backend/storage/aio/aio_target.c +++ b/src/backend/storage/aio/aio_target.c @@ -17,6 +17,7 @@ #include "storage/aio.h" #include "storage/aio_internal.h" #include "storage/smgr.h" +#include "storage/sync.h" static char *pgaio_sync_describe_identity(const PgAioTargetData *sd); @@ -39,6 +40,7 @@ static const PgAioTargetInfo *pgaio_target_info[] = { }, [PGAIO_TID_SMGR] = &aio_smgr_target_info, [PGAIO_TID_SYNC] = &aio_sync_target_info, + [PGAIO_TID_SYNC_FILETAG] = &aio_sync_filetag_target_info, }; /* diff --git a/src/backend/storage/sync/sync.c b/src/backend/storage/sync/sync.c index 2442492d6a9..80ba569f50b 100644 --- a/src/backend/storage/sync/sync.c +++ b/src/backend/storage/sync/sync.c @@ -132,10 +132,20 @@ static CycleCtr checkpoint_cycle_ctr = 0; typedef struct SyncOps { void (*sync_syncfiletag) (PgAioHandle *ioh, InflightSyncEntry *entry); + + /* + * Optional. Reopen the file identified by ftag, so that an fsync started + * by sync_syncfiletag() can be executed in a different process, e.g. an + * IO worker. Returns a file descriptor opened with OpenTransientFile(), + * or -1 with errno set. Handlers that provide this must use the + * PGAIO_TID_SYNC_FILETAG target (see pgaio_io_set_target_sync_filetag()). + */ + int (*sync_openfiletag) (const FileTag *ftag); int (*sync_unlinkfiletag) (const FileTag *ftag, char *path); bool (*sync_filetagmatches) (const FileTag *ftag, const FileTag *candidate); bool uses_transient_fd; + const char *sync_target_name; } SyncOps; /* @@ -152,25 +162,130 @@ static const SyncOps syncsw[] = { /* pg_xact */ [SYNC_HANDLER_CLOG] = { .sync_syncfiletag = clogsyncfiletag, - .uses_transient_fd = true + .sync_openfiletag = clogopenfiletag, + .uses_transient_fd = true, + .sync_target_name = "pg_xact" }, /* pg_commit_ts */ [SYNC_HANDLER_COMMIT_TS] = { .sync_syncfiletag = committssyncfiletag, - .uses_transient_fd = true + .sync_openfiletag = committsopenfiletag, + .uses_transient_fd = true, + .sync_target_name = "pg_commit_ts" }, /* pg_multixact/offsets */ [SYNC_HANDLER_MULTIXACT_OFFSET] = { .sync_syncfiletag = multixactoffsetssyncfiletag, - .uses_transient_fd = true + .sync_openfiletag = multixactoffsetsopenfiletag, + .uses_transient_fd = true, + .sync_target_name = "pg_multixact/offsets" }, /* pg_multixact/members */ [SYNC_HANDLER_MULTIXACT_MEMBER] = { .sync_syncfiletag = multixactmemberssyncfiletag, - .uses_transient_fd = true + .sync_openfiletag = multixactmembersopenfiletag, + .uses_transient_fd = true, + .sync_target_name = "pg_multixact/members" } }; +static int sync_aio_reopen(PgAioHandle *ioh); +static void sync_aio_close(PgAioHandle *ioh); +static char *sync_aio_describe_identity(const PgAioTargetData *sd); + +/* + * Target info for files identified by a FileTag (see PGAIO_TID_SYNC_FILETAG). + * Unlike PGAIO_TID_SYNC, a FileTag contains everything needed to find the + * file again in another process, so such IOs can be executed by IO workers. + */ +const PgAioTargetInfo aio_sync_filetag_target_info = { + .name = "sync_filetag", + .reopen = sync_aio_reopen, + .close = sync_aio_close, + .describe_identity = sync_aio_describe_identity, +}; + +/* + * Set up ioh to operate on the file identified by ftag. + */ +void +pgaio_io_set_target_sync_filetag(PgAioHandle *ioh, const FileTag *ftag) +{ + PgAioTargetData *sd = pgaio_io_get_target_data(ioh); + + Assert(syncsw[ftag->handler].sync_openfiletag != NULL); + Assert(syncsw[ftag->handler].sync_target_name != NULL); + + pgaio_io_set_target(ioh, PGAIO_TID_SYNC_FILETAG); + + sd->sync_filetag = *ftag; +} + +static FileTag +sync_aio_filetag(const PgAioTargetData *sd) +{ + return sd->sync_filetag; +} + +/* + * reopen callback for PGAIO_TID_SYNC_FILETAG, to open the file in the process + * executing the IO. + */ +static int +sync_aio_reopen(PgAioHandle *ioh) +{ + PgAioTargetData *sd = pgaio_io_get_target_data(ioh); + PgAioOpData *od = pgaio_io_get_op_data(ioh); + FileTag ftag = sync_aio_filetag(sd); + int fd; + + /* + * The caller needs to prevent interrupts from being processed, otherwise + * the FD could be closed again before we get to executing the IO. + */ + Assert(!INTERRUPTS_CAN_BE_PROCESSED()); + + Assert(pgaio_io_get_op(ioh) == PGAIO_OP_FSYNC); + + fd = syncsw[ftag.handler].sync_openfiletag(&ftag); + if (fd < 0) + return -errno; + + od->fsync.fd = fd; + + return 0; +} + +/* + * close callback for PGAIO_TID_SYNC_FILETAG, releasing the descriptor + * acquired by sync_aio_reopen(). + * + * Called in a critical section after the fsync result has been saved for + * the issuer. Do not report close failures here: this descriptor was only + * used for fsync, and any fsync failure is handled by the issuer. + */ +static void +sync_aio_close(PgAioHandle *ioh) +{ + PgAioOpData *od = pgaio_io_get_op_data(ioh); + + (void) CloseTransientFile(od->fsync.fd); + od->fsync.fd = -1; +} + +/* + * describe_identity callback for PGAIO_TID_SYNC_FILETAG. + */ +static char * +sync_aio_describe_identity(const PgAioTargetData *sd) +{ + FileTag ftag = sync_aio_filetag(sd); + + return psprintf(_("segment " UINT64_FORMAT " of SLRU \"%s\""), + ftag.segno, + syncsw[ftag.handler].sync_target_name); +} + /* * Initialize data structures for the file sync tracking. */ diff --git a/src/include/access/clog.h b/src/include/access/clog.h index e089106f7fe..fc06794d186 100644 --- a/src/include/access/clog.h +++ b/src/include/access/clog.h @@ -48,6 +48,7 @@ extern void ExtendCLOG(TransactionId newestXact); extern void TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid); extern void clogsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int clogopenfiletag(const FileTag *ftag); /* XLOG stuff */ #define CLOG_ZEROPAGE 0x00 diff --git a/src/include/access/commit_ts.h b/src/include/access/commit_ts.h index fa4880e0d03..ebb87d9534e 100644 --- a/src/include/access/commit_ts.h +++ b/src/include/access/commit_ts.h @@ -39,6 +39,7 @@ extern void SetCommitTsLimit(TransactionId oldestXact, extern void AdvanceOldestCommitTsXid(TransactionId oldestXact); extern void committssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int committsopenfiletag(const FileTag *ftag); /* XLOG stuff */ #define COMMIT_TS_ZEROPAGE 0x00 diff --git a/src/include/access/multixact.h b/src/include/access/multixact.h index 3f980b4120d..3f5233a3bcd 100644 --- a/src/include/access/multixact.h +++ b/src/include/access/multixact.h @@ -115,7 +115,9 @@ extern bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2); extern void multixactoffsetssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int multixactoffsetsopenfiletag(const FileTag *ftag); extern void multixactmemberssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int multixactmembersopenfiletag(const FileTag *ftag); extern void AtEOXact_MultiXact(void); extern void AtPrepare_MultiXact(void); diff --git a/src/include/access/slru.h b/src/include/access/slru.h index 0e91df5609c..43429392c7d 100644 --- a/src/include/access/slru.h +++ b/src/include/access/slru.h @@ -241,6 +241,7 @@ extern bool SlruScanDirectory(SlruDesc *ctl, SlruScanCallback callback, void *da extern void SlruDeleteSegment(SlruDesc *ctl, int64 segno); extern void SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, struct InflightSyncEntry *entry); +extern int SlruOpenFileTag(SlruDesc *ctl, const FileTag *ftag); /* SlruScanDirectory public callbacks */ extern bool SlruScanDirCbReportPresence(SlruDesc *ctl, char *filename, diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index 6ea230ccad5..1f32314f2b6 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -119,9 +119,10 @@ typedef enum PgAioTargetID PGAIO_TID_INVALID = 0, PGAIO_TID_SMGR, PGAIO_TID_SYNC, + PGAIO_TID_SYNC_FILETAG, } PgAioTargetID; -#define PGAIO_TID_COUNT (PGAIO_TID_SYNC + 1) +#define PGAIO_TID_COUNT (PGAIO_TID_SYNC_FILETAG + 1) /* @@ -178,7 +179,11 @@ struct PgAioTargetInfo /* * Optional counterpart to reopen, releasing the file descriptor it - * acquired once the IO has been executed. + * acquired. Called in the process that reopened the IO, after the IO has + * been executed. Targets whose reopen callback reuses a cached + * descriptor do not need this. + * + * This is called in a critical section, so it must not raise errors. */ void (*close) (PgAioHandle *ioh); diff --git a/src/include/storage/aio_types.h b/src/include/storage/aio_types.h index 17b59aeed7c..90bc4c73989 100644 --- a/src/include/storage/aio_types.h +++ b/src/include/storage/aio_types.h @@ -23,6 +23,18 @@ typedef struct PgAioHandle PgAioHandle; typedef struct PgAioHandleCallbacks PgAioHandleCallbacks; typedef struct PgAioTargetInfo PgAioTargetInfo; +/* + * A tag identifying a file handled by sync.c. This is defined here so that + * PgAioTargetData can store it without duplicating its representation. + */ +typedef struct PgAioSyncFileTag +{ + int16 handler; /* SyncRequestHandler value */ + int16 forknum; /* ForkNumber */ + RelFileLocator rlocator; /* physical relation identifier */ + uint64 segno; +} PgAioSyncFileTag; + /* * A reference to an IO that can be used to wait for the IO (using * pgaio_wref_wait()) to complete. @@ -69,6 +81,8 @@ typedef union PgAioTargetData bool is_temp:1; /* proc can be inferred by owning AIO */ bool skip_fsync:1; } smgr; + + PgAioSyncFileTag sync_filetag; } PgAioTargetData; diff --git a/src/include/storage/sync.h b/src/include/storage/sync.h index 8d48151730f..e85c97c2ba4 100644 --- a/src/include/storage/sync.h +++ b/src/include/storage/sync.h @@ -46,17 +46,11 @@ typedef enum SyncRequestHandler } SyncRequestHandler; /* - * A tag identifying a file. Currently it has the members required for md.c's - * usage, but sync.c has no knowledge of the internal structure, and it is - * liable to change as required by future handlers. + * A tag identifying a file. Its representation is shared with AIO target + * data, so changes are automatically visible to processes that reopen files + * on behalf of sync.c. */ -typedef struct FileTag -{ - int16 handler; /* SyncRequestHandler value, saving space */ - int16 forknum; /* ForkNumber, saving space */ - RelFileLocator rlocator; - uint64 segno; -} FileTag; +typedef PgAioSyncFileTag FileTag; struct PendingFsyncEntry; struct PgAioHandle; @@ -118,4 +112,9 @@ extern void RememberSyncRequest(const FileTag *ftag, SyncRequestType type); extern bool RegisterSyncRequest(const FileTag *ftag, SyncRequestType type, bool retryOnError); +/* AIO support */ +extern PGDLLIMPORT const PgAioTargetInfo aio_sync_filetag_target_info; +extern void pgaio_io_set_target_sync_filetag(PgAioHandle *ioh, + const FileTag *ftag); + #endif /* SYNC_H */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index c5ed5bc6c0f..5e09f3c2a06 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2261,6 +2261,7 @@ PgAioOpData PgAioResult PgAioResultStatus PgAioReturn +PgAioSyncFileTag PgAioTargetData PgAioTargetID PgAioTargetInfo -- 2.47.3
v2-0008-aio-doc-Document-AIO-fsync.patch (text/x-patch, 3.6K) download From 6150103c1e2f8ceafda43d4d7d0beec62368e72e Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 9 Sep 2026 14:16:40 +0300 Subject: [PATCH v2 8/8] aio: doc: Document AIO fsync Describe the fsync operation and sync and sync_filetag targets exposed by pg_aios, including the NULL offset and length for synchronization operations. Explain that crash-recovery file synchronization can overlap with io_uring but runs synchronously with the worker method because workers cannot reopen these path-only targets. Distinguish this fallback from relation and SLRU synchronization during checkpoints. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- doc/src/sgml/config.sgml | 10 ++++++++++ doc/src/sgml/system-views.sgml | 22 ++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml index 0165eb9ec02..984be7c7167 100644 --- a/doc/src/sgml/config.sgml +++ b/doc/src/sgml/config.sgml @@ -12292,6 +12292,16 @@ dynamic_library_path = '/usr/local/lib/postgresql:$libdir' starting a database cluster that did not shut down cleanly, including copies created with <application>pg_basebackup</application>. </para> + <para> + When this parameter is set to <literal>fsync</literal> and + <xref linkend="guc-io-method"/> is set to <literal>io_uring</literal>, + multiple file synchronization operations can run concurrently. + With <literal>worker</literal> or <literal>sync</literal>, these + operations run synchronously in the startup process. Unlike relation + and SLRU synchronization during checkpoints, data-directory + synchronization does not provide the information needed for I/O + workers to reopen the files. + </para> <para> On Linux, <literal>syncfs</literal> may be used instead, to ask the operating system to synchronize the file systems that contain the diff --git a/doc/src/sgml/system-views.sgml b/doc/src/sgml/system-views.sgml index 77202e2c765..9ed5e1b7d49 100644 --- a/doc/src/sgml/system-views.sgml +++ b/doc/src/sgml/system-views.sgml @@ -387,6 +387,12 @@ <literal>writev</literal>, a vectored write </para> </listitem> + <listitem> + <para> + <literal>fsync</literal>, file synchronization using + <function>fsync()</function> or <function>fdatasync()</function> + </para> + </listitem> </itemizedlist> </para></entry> </row> @@ -396,7 +402,7 @@ <structfield>off</structfield> <type>int8</type> </para> <para> - Offset of the I/O operation. + Offset of the I/O operation, or NULL for <literal>fsync</literal>. </para></entry> </row> @@ -405,7 +411,7 @@ <structfield>length</structfield> <type>int8</type> </para> <para> - Length of the I/O operation. + Length of the I/O operation, or NULL for <literal>fsync</literal>. </para></entry> </row> @@ -421,6 +427,18 @@ <literal>smgr</literal>, I/O on relations </para> </listitem> + <listitem> + <para> + <literal>sync</literal>, file synchronization using a process-local + file descriptor + </para> + </listitem> + <listitem> + <para> + <literal>sync_filetag</literal>, file synchronization identified by + a file tag, currently used for SLRU segments + </para> + </listitem> </itemizedlist> </para></entry> </row> -- 2.47.3
^ permalink raw reply [nested|flat] 9+ messages in thread

* Re: aio: Async fsyncs for crash recovery and checkpointer
@ 2026-09-22 04:03  Yuhang Qiu <iamqyh@gmail.com>
  parent: Nazir Bilal Yavuz <byavuz81@gmail.com>
  0 siblings, 2 replies; 9+ messages in thread

From: Yuhang Qiu @ 2026-09-22 04:03 UTC (permalink / raw)
  To: Nazir Bilal Yavuz <byavuz81@gmail.com>; +Cc: Nitin Jadhav <nitinjadhavpostgres@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Andres Freund <andres@anarazel.de>

Hi Nazir,

Thanks for the comparison. The main benefit of this patch series seems
to be in checkpointing rather than crash recovery, so I think further
testing should focus on that.

> For now, ordinary reopen failures for both relation and SLRU fsyncs
> return -errno.
> 
> Done. Relation fsync requests now use io_max_concurrency as their
> limit.

These two changes LGTM.

> However, I think increasing the number of worker processes
> should solve this problem.

Increasing the worker count may help with worker availability, but it
doesn't address contention for storage bandwidth.

One more point: when a worker calls pg_fsync() or pg_fdatasync(), it checks
its own enableFsync. If the issuer has reloaded fsync=on but the worker
still has the old off value, the worker can skip the sync and report
success. Should the issuer's setting or the worker's determine whether
the sync is performed?

Best regards,
Yuhang Qiu






^ permalink  raw  reply  [nested|flat] 9+ messages in thread

* Re: aio: Async fsyncs for crash recovery and checkpointer
@ 2026-09-22 15:20  Nitin Jadhav <nitinjadhavpostgres@gmail.com>
  parent: Yuhang Qiu <iamqyh@gmail.com>
  1 sibling, 1 reply; 9+ messages in thread

From: Nitin Jadhav @ 2026-09-22 15:20 UTC (permalink / raw)
  To: Nazir Bilal Yavuz <byavuz81@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Andres Freund <andres@anarazel.de>; iamqyh@gmail.com

Hi Nazir,

Thanks for the updated patch set. I reviewed v2. The changes address
my earlier comments about fsync timing and reopen-error handling. In
particular, wait time is now accounted for when the issuer actually
blocks for completion, and ordinary reopen failures preserve the errno
without terminating the I/O worker.

I found two further points, and the worker-side SLRU test-coverage
question from v1 still appears applicable.

An I/O worker can skip a required fsync after fsync is enabled. As
Yuhang noted, there appears to be a race when reloading fsync from off
to on. pgaio_io_start_fsync()  makes the dispatch decision using the
issuing process's enableFsync. Therefore, once the checkpointer has
processed the new configuration and sees  fsync=on, it can submit the
operation to an I/O worker. However, worker execution eventually calls
pg_fsync() or pg_fdatasync(). Those functions check the worker
process's own enableFsync. An I/O worker can consume and execute a
queued request before processing its pending configuration reload. If
the worker still has the old fsync=off value, pg_fsync() returns
success without issuing the syscall. The checkpointer then treats the
operation as successfully completed even though the required
synchronization did not occur. The unsafe direction is specifically
off to on; the reverse direction can cause an unnecessary fsync but
does not lose durability. Could the decision to perform the fsync be
captured in the AIO operation when it is submitted, with worker
execution using a syscall helper that does not re-evaluate the
worker-local enableFsync value? Alternatively, the worker would need
to guarantee that it has applied the relevant configuration generation
before executing the request. I think this should be treated as
blocking because it can allow a checkpoint to complete without
executing a required fsync.

Worker SMGR cleanup appears dependent on the worker becoming idle.
Patch 0002 calls smgrdestroyall() only after the worker finds that no
request is available. This means a continuously busy worker may never
perform the cleanup. Worker-side relation reopening calls smgropen(),
and those unpinned SMgrRelation objects remain in the worker's SMGR
hash until smgrdestroyall() is called. With sustained I/O over many
distinct relations, a worker whose queue never becomes empty could
therefore retain an increasing number of SMGR entries, including
entries for relations that have since been dropped. Would it be safer
to check FirstCallSinceLastCheckpoint() at a safe point after
completing each request, before consuming the next request, rather
than only on the idle path? At that point any descriptor reopened for
the completed operation has already been released.

The worker-side SLRU path does not appear to have targeted test
coverage. The test_slru_page_sync() still registers the test SLRU with
SYNC_HANDLER_NONE. Consequently, SlruSyncFileTag() selects
PGAIO_TID_SYNC, which has no reopen callback and is executed
synchronously in the submitting process under io_method=worker.

Best Regards,
Nitin Jadhav
Azure Database for PostgreSQL
Microsoft






^ permalink  raw  reply  [nested|flat] 9+ messages in thread

* Re: aio: Async fsyncs for crash recovery and checkpointer
@ 2026-09-30 08:42  Nazir Bilal Yavuz <byavuz81@gmail.com>
  parent: Yuhang Qiu <iamqyh@gmail.com>
  1 sibling, 0 replies; 9+ messages in thread

From: Nazir Bilal Yavuz @ 2026-09-30 08:42 UTC (permalink / raw)
  To: Yuhang Qiu <iamqyh@gmail.com>; +Cc: Nitin Jadhav <nitinjadhavpostgres@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Andres Freund <andres@anarazel.de>

Hi,

On Tue, 22 Sept 2026 at 07:03, Yuhang Qiu <iamqyh@gmail.com> wrote:
>
> Thanks for the comparison. The main benefit of this patch series seems
> to be in checkpointing rather than crash recovery, so I think further
> testing should focus on that.

I agree. Crash recovery is useful but checkpoint's impact is much
greater than that IMO.


> > However, I think increasing the number of worker processes
> > should solve this problem.
>
> Increasing the worker count may help with worker availability, but it
> doesn't address contention for storage bandwidth.

Could you please elaborate more on this?


> One more point: when a worker calls pg_fsync() or pg_fdatasync(), it checks
> its own enableFsync. If the issuer has reloaded fsync=on but the worker
> still has the old off value, the worker can skip the sync and report
> success. Should the issuer's setting or the worker's determine whether
> the sync is performed?

Nice find. I think it makes sense to use the issuing process's
enableFsync. Done like that in v3-0002.


--
Regards,
Nazir Bilal Yavuz
Microsoft

Attachments: download all (8 files, .tar.gz)

v3-0001-ci-Temporarily-enable-fsync-everywhere.patch (text/x-patch, 2.1K) download From 589f9097dfd7e6f3e590ea44fa29c50624de66d7 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Fri, 4 Sep 2026 17:21:51 +0300 Subject: [PATCH v3 1/8] ci: Temporarily enable fsync everywhere To test AIO fsync support patches. Not submitted for commit. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- .github/workflows/pg-ci.yml | 2 +- src/test/ssl/t/SSL/Server.pm | 1 - src/tools/ci/pg_ci_base.conf | 3 +++ 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pg-ci.yml b/.github/workflows/pg-ci.yml index a2629c8335a..c0019a1f91f 100644 --- a/.github/workflows/pg-ci.yml +++ b/.github/workflows/pg-ci.yml @@ -608,7 +608,7 @@ jobs: # Log into a place that will be archived in case of failure mkdir -p build/testrun - build/tmp_install/usr/local/pgsql/bin/pg_ctl -c -o '-c fsync=off' -D build/runningcheck -l build/testrun/runningcheck.log start + build/tmp_install/usr/local/pgsql/bin/pg_ctl -c -D build/runningcheck -l build/testrun/runningcheck.log start # Run the tests supporting running against an already running meson test ${{env.MTEST_ARGS}} --num-processes ${{env.TEST_JOBS}} --setup running diff --git a/src/test/ssl/t/SSL/Server.pm b/src/test/ssl/t/SSL/Server.pm index 4400a432f42..d5e723d156f 100644 --- a/src/test/ssl/t/SSL/Server.pm +++ b/src/test/ssl/t/SSL/Server.pm @@ -199,7 +199,6 @@ sub configure_test_server_for_ssl # enable logging etc. $node->append_conf( 'postgresql.conf', <<EOF -fsync=off log_connections=all log_hostname=on listen_addresses='$serverhost' diff --git a/src/tools/ci/pg_ci_base.conf b/src/tools/ci/pg_ci_base.conf index ff05646c90e..b96bd4a4786 100644 --- a/src/tools/ci/pg_ci_base.conf +++ b/src/tools/ci/pg_ci_base.conf @@ -5,6 +5,9 @@ restart_after_crash = false # prepared statements max_prepared_transactions = 10 +# Exercise fsync code paths in CI +fsync = on + # Settings that make logs more useful log_autovacuum_min_duration = 0 log_autoanalyze_min_duration = 0 -- 2.47.3
v3-0002-aio-Add-fsync-support.patch (text/x-patch, 12.3K) download From 7347ca28504be508f57eec89c34620b50641a7bc Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 9 Sep 2026 15:39:57 +0300 Subject: [PATCH v3 2/8] aio: Add fsync support The AIO subsystem currently supports only reads and writes (writes are not used yet). Add PGAIO_OP_FSYNC so callers can submit fsync() and fdatasync() operations through AIO. This allows callers such as the checkpointer to keep multiple syncs in flight instead of waiting for each one in turn. Capture the issuer's enableFsync setting and writethrough choice in the operation, and use unconditional synchronization helpers during execution. An I/O worker may not yet have processed the issuer's configuration reload; consulting its local enableFsync could otherwise skip a required fsync after fsync is enabled. Let callers select the wait event because fsync targets can represent different kinds of files. The process that performs the operation reports that event; io_uring uses the generic AIO wait events because the kernel performs the operation. (Also see [1]) No callers are converted in this commit; subsequent commits do that. [1] https://postgr.es/m/CAN55FZ0Rp+94rdQ-zeTX0sF9H1e4uWZxH8r1cVXZX0swfqww3g@mail.gmail.com Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- src/backend/storage/aio/aio_funcs.c | 4 ++ src/backend/storage/aio/aio_io.c | 47 +++++++++++++ src/backend/storage/aio/method_io_uring.c | 8 +++ src/backend/storage/file/fd.c | 80 ++++++++++++++++++----- src/backend/storage/smgr/smgr.c | 3 + src/include/storage/aio.h | 16 ++++- src/include/storage/fd.h | 2 + src/test/modules/test_aio/test_aio.c | 14 ++++ 8 files changed, 154 insertions(+), 20 deletions(-) diff --git a/src/backend/storage/aio/aio_funcs.c b/src/backend/storage/aio/aio_funcs.c index bcdd82318f7..2719556e858 100644 --- a/src/backend/storage/aio/aio_funcs.c +++ b/src/backend/storage/aio/aio_funcs.c @@ -191,6 +191,10 @@ retry: values[6] = Int64GetDatum(iov_byte_length(iov_copy, ioh_copy.op_data.write.iov_length)); break; + case PGAIO_OP_FSYNC: + nulls[5] = true; + nulls[6] = true; + break; } /* column: IO's target */ diff --git a/src/backend/storage/aio/aio_io.c b/src/backend/storage/aio/aio_io.c index 132868130e7..72c43ee54e4 100644 --- a/src/backend/storage/aio/aio_io.c +++ b/src/backend/storage/aio/aio_io.c @@ -18,6 +18,7 @@ #include "postgres.h" +#include "access/xlog.h" #include "miscadmin.h" #include "storage/aio.h" #include "storage/aio_internal.h" @@ -100,6 +101,29 @@ pgaio_io_start_writev(PgAioHandle *ioh, pgaio_io_stage(ioh, PGAIO_OP_WRITEV); } +void +pgaio_io_start_fsync(PgAioHandle *ioh, + int fd, bool datasync, uint32 wait_event_info) +{ + pgaio_io_before_start(ioh); + + ioh->op_data.fsync.fd = fd; + ioh->op_data.fsync.datasync = datasync; + ioh->op_data.fsync.enabled = enableFsync; + ioh->op_data.fsync.writethrough = false; +#ifdef HAVE_FSYNC_WRITETHROUGH + if (!datasync && wal_sync_method == WAL_SYNC_METHOD_FSYNC_WRITETHROUGH) + ioh->op_data.fsync.writethrough = true; +#endif + ioh->op_data.fsync.wait_event_info = wait_event_info; + + /* Complete disabled fsyncs locally, without submitting a syscall. */ + if (!ioh->op_data.fsync.enabled) + pgaio_io_set_flag(ioh, PGAIO_HF_SYNCHRONOUS); + + pgaio_io_stage(ioh, PGAIO_OP_FSYNC); +} + /* -------------------------------------------------------------------------------- @@ -137,6 +161,23 @@ pgaio_io_perform_synchronously(PgAioHandle *ioh) ioh->op_data.write.offset); pgstat_report_wait_end(); break; + case PGAIO_OP_FSYNC: + + /* + * Honor the issuer's decisions about whether and how to + * synchronize. An IO worker may not yet have processed the same + * configuration reload as the issuer. + */ + if (!ioh->op_data.fsync.enabled) + break; + pgstat_report_wait_start(ioh->op_data.fsync.wait_event_info); + if (ioh->op_data.fsync.datasync) + result = pg_fdatasync_unconditional(ioh->op_data.fsync.fd); + else + result = pg_fsync_unconditional(ioh->op_data.fsync.fd, + ioh->op_data.fsync.writethrough); + pgstat_report_wait_end(); + break; case PGAIO_OP_INVALID: elog(ERROR, "trying to execute invalid IO operation"); } @@ -189,6 +230,8 @@ pgaio_io_get_op_name(PgAioHandle *ioh) return "readv"; case PGAIO_OP_WRITEV: return "writev"; + case PGAIO_OP_FSYNC: + return "fsync"; } return NULL; /* silence compiler */ @@ -209,6 +252,8 @@ pgaio_io_uses_fd(PgAioHandle *ioh, int fd) return ioh->op_data.read.fd == fd; case PGAIO_OP_WRITEV: return ioh->op_data.write.fd == fd; + case PGAIO_OP_FSYNC: + return ioh->op_data.fsync.fd == fd; case PGAIO_OP_INVALID: return false; } @@ -233,6 +278,8 @@ pgaio_io_get_iovec_length(PgAioHandle *ioh, struct iovec **iov) return ioh->op_data.read.iov_length; case PGAIO_OP_WRITEV: return ioh->op_data.write.iov_length; + case PGAIO_OP_FSYNC: + return 0; default: pg_unreachable(); return 0; diff --git a/src/backend/storage/aio/method_io_uring.c b/src/backend/storage/aio/method_io_uring.c index 3ffe5061a20..4e4338c6748 100644 --- a/src/backend/storage/aio/method_io_uring.c +++ b/src/backend/storage/aio/method_io_uring.c @@ -802,6 +802,14 @@ pgaio_uring_sq_from_io(PgAioHandle *ioh, struct io_uring_sqe *sqe) break; + case PGAIO_OP_FSYNC: + Assert(ioh->op_data.fsync.enabled); + Assert(!ioh->op_data.fsync.writethrough); + io_uring_prep_fsync(sqe, + ioh->op_data.fsync.fd, + ioh->op_data.fsync.datasync ? IORING_FSYNC_DATASYNC : 0); + break; + case PGAIO_OP_INVALID: elog(ERROR, "trying to prepare invalid IO operation for execution"); } diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index 190c9974494..f7103c0e42f 100644 --- a/src/backend/storage/file/fd.c +++ b/src/backend/storage/file/fd.c @@ -335,6 +335,10 @@ static void ReleaseLruFiles(void); static File AllocateVfd(void); static void FreeVfd(File file); +static int pg_fsync_impl(int fd, bool do_fsync, bool writethrough); +static int pg_fsync_no_writethrough_unconditional(int fd); +static int pg_fsync_writethrough_unconditional(int fd); + static int FileAccess(File file); static File OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError); static bool reserveAllocatedDesc(void); @@ -388,6 +392,29 @@ ResourceOwnerForgetFile(ResourceOwner owner, File file) */ int pg_fsync(int fd) +{ + bool writethrough = false; + +#ifdef HAVE_FSYNC_WRITETHROUGH + writethrough = wal_sync_method == WAL_SYNC_METHOD_FSYNC_WRITETHROUGH; +#endif + return pg_fsync_impl(fd, enableFsync, writethrough); +} + +/* + * Synchronize using the specified method, regardless of enableFsync and + * wal_sync_method. AIO uses this after the issuer has decided whether and how + * to synchronize, since an IO worker's configuration may differ from the + * issuer's. + */ +int +pg_fsync_unconditional(int fd, bool writethrough) +{ + return pg_fsync_impl(fd, true, writethrough); +} + +static int +pg_fsync_impl(int fd, bool do_fsync, bool writethrough) { #if !defined(WIN32) && defined(USE_ASSERT_CHECKING) struct stat st; @@ -424,13 +451,13 @@ pg_fsync(int fd) errno = 0; #endif - /* #if is to skip the wal_sync_method test if there's no need for it */ -#if defined(HAVE_FSYNC_WRITETHROUGH) - if (wal_sync_method == WAL_SYNC_METHOD_FSYNC_WRITETHROUGH) - return pg_fsync_writethrough(fd); + if (!do_fsync) + return 0; + + if (writethrough) + return pg_fsync_writethrough_unconditional(fd); else -#endif - return pg_fsync_no_writethrough(fd); + return pg_fsync_no_writethrough_unconditional(fd); } @@ -441,11 +468,17 @@ pg_fsync(int fd) int pg_fsync_no_writethrough(int fd) { - int rc; - if (!enableFsync) return 0; + return pg_fsync_no_writethrough_unconditional(fd); +} + +static int +pg_fsync_no_writethrough_unconditional(int fd) +{ + int rc; + retry: rc = fsync(fd); @@ -461,17 +494,21 @@ retry: int pg_fsync_writethrough(int fd) { - if (enableFsync) - { + if (!enableFsync) + return 0; + + return pg_fsync_writethrough_unconditional(fd); +} + +static int +pg_fsync_writethrough_unconditional(int fd) +{ #if defined(F_FULLFSYNC) - return (fcntl(fd, F_FULLFSYNC, 0) == -1) ? -1 : 0; + return (fcntl(fd, F_FULLFSYNC, 0) == -1) ? -1 : 0; #else - errno = ENOSYS; - return -1; + errno = ENOSYS; + return -1; #endif - } - else - return 0; } /* @@ -480,11 +517,18 @@ pg_fsync_writethrough(int fd) int pg_fdatasync(int fd) { - int rc; - if (!enableFsync) return 0; + return pg_fdatasync_unconditional(fd); +} + +/* Like pg_fsync_unconditional(), but synchronize only file data. */ +int +pg_fdatasync_unconditional(int fd) +{ + int rc; + retry: rc = fdatasync(fd); diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c index 5391640d861..69e61ea1661 100644 --- a/src/backend/storage/smgr/smgr.c +++ b/src/backend/storage/smgr/smgr.c @@ -1094,6 +1094,9 @@ smgr_aio_reopen(PgAioHandle *ioh) od->write.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); Assert(off == od->write.offset); break; + case PGAIO_OP_FSYNC: + od->fsync.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); + break; } } diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index ec543b78409..9e96317b5c3 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -91,10 +91,10 @@ typedef enum PgAioOp PGAIO_OP_READV, PGAIO_OP_WRITEV, + PGAIO_OP_FSYNC, /** * In the near term we'll need at least: - * - fsync / fdatasync * - flush_range * * Eventually we'll additionally want at least: @@ -104,7 +104,7 @@ typedef enum PgAioOp **/ } PgAioOp; -#define PGAIO_OP_COUNT (PGAIO_OP_WRITEV + 1) +#define PGAIO_OP_COUNT (PGAIO_OP_FSYNC + 1) /* @@ -146,6 +146,15 @@ typedef union uint16 iov_length; uint64 offset; } write; + + struct + { + int fd; + bool datasync; + bool enabled; /* issuer's enableFsync at start */ + bool writethrough; /* issuer's choice of full cache flush */ + uint32 wait_event_info; + } fsync; } PgAioOpData; @@ -300,6 +309,9 @@ extern void pgaio_io_start_readv(PgAioHandle *ioh, int fd, int iovcnt, uint64 offset); extern void pgaio_io_start_writev(PgAioHandle *ioh, int fd, int iovcnt, uint64 offset); +extern void pgaio_io_start_fsync(PgAioHandle *ioh, int fd, bool datasync, + uint32 wait_event_info); + /* functions in aio_target.c */ extern void pgaio_io_set_target(PgAioHandle *ioh, PgAioTargetID targetid); diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h index 8ac466fd346..850af783a5c 100644 --- a/src/include/storage/fd.h +++ b/src/include/storage/fd.h @@ -211,6 +211,8 @@ extern int pg_fsync(int fd); extern int pg_fsync_no_writethrough(int fd); extern int pg_fsync_writethrough(int fd); extern int pg_fdatasync(int fd); +extern int pg_fsync_unconditional(int fd, bool writethrough); +extern int pg_fdatasync_unconditional(int fd); extern bool pg_file_exists(const char *name); extern void pg_flush_data(int fd, pgoff_t offset, pgoff_t nbytes); extern int pg_truncate(const char *path, pgoff_t length); diff --git a/src/test/modules/test_aio/test_aio.c b/src/test/modules/test_aio/test_aio.c index 39d857557cf..db9d5a30322 100644 --- a/src/test/modules/test_aio/test_aio.c +++ b/src/test/modules/test_aio/test_aio.c @@ -1145,6 +1145,13 @@ inj_io_short_read_hook(const char *name, const void *private_data, void *arg) void inj_io_completion_hook(const char *name, const void *private_data, void *arg) { + PgAioHandle *ioh = (PgAioHandle *) arg; + + /* These hooks inspect SMGR block ranges and read-specific iovecs. */ + if (pgaio_io_get_op(ioh) != PGAIO_OP_READV || + ioh->target != PGAIO_TID_SMGR) + return; + inj_io_completion_wait_hook(name, private_data, arg); inj_io_short_read_hook(name, private_data, arg); } @@ -1152,6 +1159,13 @@ inj_io_completion_hook(const char *name, const void *private_data, void *arg) void inj_io_reopen(const char *name, const void *private_data, void *arg) { + PgAioHandle *ioh = (PgAioHandle *) arg; + + /* Read-error injection must not fail a concurrent checkpoint fsync. */ + if (pgaio_io_get_op(ioh) != PGAIO_OP_READV || + ioh->target != PGAIO_TID_SMGR) + return; + ereport(LOG, errmsg("reopen injection point called, is enabled: %d", inj_io_error_state->enabled_reopen), -- 2.47.3
v3-0003-aio-worker-Bound-SMGR-cache-growth.patch (text/x-patch, 4.0K) download From fd7770a838c204345e94f9ed9422e99da59b507c Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Thu, 24 Sep 2026 11:53:00 +0300 Subject: [PATCH v3 3/8] aio: worker: Bound SMGR cache growth IO workers create SMGR objects when reopening relations, but don't have a transaction-end cleanup to destroy them. Long-lived workers can therefore retain entries for an increasing number of relations, including dropped ones. Destroy these objects when the worker's SMGR hash reaches 1024 entries, and release any remaining objects before sleeping. Workers do not pin SMGR objects, so the hash entry count is also the unpinned entry count. Discussion: https://postgr.es/m/CAN55FZ2BesKUnajdgpw1fPSe3S6_CHOugryaUEtD7vdP%3DdRKEQ%40mail.gmail.com --- src/backend/storage/aio/method_worker.c | 22 ++++++++++++++++++++++ src/backend/storage/smgr/smgr.c | 13 +++++++++++++ src/include/storage/smgr.h | 1 + 3 files changed, 36 insertions(+) diff --git a/src/backend/storage/aio/method_worker.c b/src/backend/storage/aio/method_worker.c index cf75b2816b7..a2271393179 100644 --- a/src/backend/storage/aio/method_worker.c +++ b/src/backend/storage/aio/method_worker.c @@ -45,6 +45,7 @@ #include "storage/pmsignal.h" #include "storage/proc.h" #include "storage/shmem.h" +#include "storage/smgr.h" #include "tcop/tcopprot.h" #include "utils/injection_point.h" #include "utils/memdebug.h" @@ -65,6 +66,9 @@ */ #define PGAIO_WORKER_WAKEUP_RATIO_SATURATE 4 +/* Number of SMGR entries that triggers cleanup while busy. */ +#define PGAIO_WORKER_SMGR_CLEANUP_THRESHOLD 1024 + /* Debugging support: show current IO and wakeups:ios statistics in ps. */ /* #define PGAIO_WORKER_SHOW_PS_INFO */ @@ -954,6 +958,17 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len) RESUME_INTERRUPTS(); errcallback.arg = NULL; + + /* + * IO workers don't have transaction-end cleanup to destroy SMGR + * objects. Destroy them when the cache grows large enough. + * Workers don't pin SMGR objects, so all entries can be + * destroyed. The IO has completed and its error context has been + * cleared, so no borrowed file descriptors or SMGR references + * remain in use. + */ + if (smgrnumentries() >= PGAIO_WORKER_SMGR_CLEANUP_THRESHOLD) + smgrdestroyall(); } else { @@ -962,6 +977,13 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len) /* Cancel new worker request if pending. */ pgaio_worker_cancel_grow(); + /* + * Release any remaining SMGR objects before sleeping. See + * PGAIO_WORKER_SMGR_CLEANUP_THRESHOLD for more information. + */ + if (smgrnumentries() > 0) + smgrdestroyall(); + /* Compute the remaining allowed idle time. */ if (io_worker_idle_timeout == -1) { diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c index 69e61ea1661..1eeedb0931e 100644 --- a/src/backend/storage/smgr/smgr.c +++ b/src/backend/storage/smgr/smgr.c @@ -288,6 +288,19 @@ smgropen(RelFileLocator rlocator, ProcNumber backend) return reln; } +/* + * smgrnumentries() -- Return the number of cached SMgrRelation objects, + * including pinned objects. + */ +int64 +smgrnumentries(void) +{ + if (SMgrRelationHash == NULL) + return 0; + + return hash_get_num_entries(SMgrRelationHash); +} + /* * smgrpin() -- Prevent an SMgrRelation object from being destroyed at end of * transaction diff --git a/src/include/storage/smgr.h b/src/include/storage/smgr.h index 09bd42fcf4b..16cfaeebcb3 100644 --- a/src/include/storage/smgr.h +++ b/src/include/storage/smgr.h @@ -112,6 +112,7 @@ extern void smgrwriteback(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, BlockNumber nblocks); extern BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum); extern BlockNumber smgrnblocks_cached(SMgrRelation reln, ForkNumber forknum); +extern int64 smgrnumentries(void); extern void smgrtruncate(SMgrRelation reln, ForkNumber *forknum, int nforks, BlockNumber *old_nblocks, BlockNumber *nblocks); -- 2.47.3
v3-0004-aio-Issue-SyncDataDirectory-fsyncs-through-AIO.patch (text/x-patch, 18.9K) download From 88e90c76e78c563e766f238e4a8ea208fdfc6c12 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 16 Sep 2026 10:43:11 +0300 Subject: [PATCH v3 4/8] aio: Issue SyncDataDirectory() fsyncs through AIO After a crash, the startup process fsyncs every file in the data directory serially. Submit the fsyncs through AIO and keep a bounded ring of operations in flight. Each operation holds a transient file descriptor, while the directory walk needs descriptors of its own. Limit the ring with GetFsyncConcurrencyLimit() and wait before opening the next file to avoid exhausting the descriptor reserve. The files are identified by paths held only in the startup process. PGAIO_TID_SYNC does not copy those paths into shared memory, so the worker method cannot reopen the files and executes the fsyncs synchronously in the startup process. The io_uring method can execute them concurrently. Storing MAXPGPATH bytes in every AIO target does not seem justified for this startup-only operation. Use the DATA_DIR_SYNC wait event when an fsync is executed synchronously. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- src/backend/storage/aio/aio_target.c | 24 ++ src/backend/storage/file/fd.c | 275 +++++++++++++++--- .../utils/activity/wait_event_names.txt | 1 + src/include/storage/aio.h | 3 +- src/include/storage/fd.h | 1 + src/tools/pgindent/typedefs.list | 2 + 6 files changed, 263 insertions(+), 43 deletions(-) diff --git a/src/backend/storage/aio/aio_target.c b/src/backend/storage/aio/aio_target.c index fa98f010d5a..82b24b0026d 100644 --- a/src/backend/storage/aio/aio_target.c +++ b/src/backend/storage/aio/aio_target.c @@ -18,6 +18,17 @@ #include "storage/aio_internal.h" #include "storage/smgr.h" +static char *pgaio_sync_describe_identity(const PgAioTargetData *sd); + +/* + * Target info for generic file syncs (PGAIO_TID_SYNC). The file being synced + * is identified by a path that is not stored in shared memory, therefore no + * reopen callback is provided. + */ +static const PgAioTargetInfo aio_sync_target_info = { + .name = "sync", + .describe_identity = pgaio_sync_describe_identity, +}; /* * Registry for entities that can be the target of AIO. @@ -27,9 +38,22 @@ static const PgAioTargetInfo *pgaio_target_info[] = { .name = "invalid", }, [PGAIO_TID_SMGR] = &aio_smgr_target_info, + [PGAIO_TID_SYNC] = &aio_sync_target_info, }; +/* + * describe_identity callback for PGAIO_TID_SYNC. As we do not store the path + * of the file being synced in shared memory, only a generic description can + * be provided. + */ +static char * +pgaio_sync_describe_identity(const PgAioTargetData *sd) +{ + return pstrdup("generic file sync"); +} + + /* -------------------------------------------------------------------------------- * Public target related functions operating on IO Handles diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index f7103c0e42f..cb3927f814c 100644 --- a/src/backend/storage/file/fd.c +++ b/src/backend/storage/file/fd.c @@ -268,6 +268,31 @@ typedef struct } desc; } AllocateDesc; +/* + * State for asynchronously issuing the fsync()s in SyncDataDirectory(). We + * keep a bounded number of fsync IOs in flight, using a simple ring of + * entries; when the ring is full, we wait for the oldest IO to complete + * before issuing another. + */ +typedef struct DataDirSyncEntry +{ + int fd; + bool isdir; + char path[MAXPGPATH]; + PgAioReturn ioret; + PgAioWaitRef iow; + bool in_use; +} DataDirSyncEntry; + +typedef struct DataDirSyncState +{ + int elevel; /* level to log errors at */ + int max_inflight; /* size of the ring */ + int head; /* index of oldest in-flight entry */ + int count; /* number of in-flight entries */ + DataDirSyncEntry *entries; /* ring of max_inflight entries */ +} DataDirSyncState; + static int numAllocatedDescs = 0; static int maxAllocatedDescs = 0; static AllocateDesc *allocatedDescs = NULL; @@ -350,14 +375,20 @@ static void RemovePgTempRelationFiles(const char *tsdirname); static void RemovePgTempRelationFilesInDbspace(const char *dbspacedirname); static void walkdir(const char *path, - void (*action) (const char *fname, bool isdir, int elevel), + void (*action) (const char *fname, bool isdir, int elevel, DataDirSyncState *state), bool process_symlinks, - int elevel); + int elevel, + DataDirSyncState *state); #ifdef PG_FLUSH_DATA_WORKS -static void pre_sync_fname(const char *fname, bool isdir, int elevel); +static void pre_sync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state); #endif -static void datadir_fsync_fname(const char *fname, bool isdir, int elevel); -static void unlink_if_exists_fname(const char *fname, bool isdir, int elevel); +static void datadir_fsync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state); +static void unlink_if_exists_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state); +static bool fsync_fname_open(const char *fname, bool isdir, bool ignore_perm, + int elevel, int *ret); +static bool fsync_fname_close(const char *fname, bool isdir, int elevel, int fd, int returncode); +static void datadir_sync_wait_one(DataDirSyncState *state); +static void datadir_sync_drain_all(DataDirSyncState *state); static int fsync_parent_path(const char *fname, int elevel); @@ -1735,7 +1766,7 @@ PathNameDeleteTemporaryDir(const char *dirname) * used in a cleanup path, we wouldn't actually behave differently: we'll * just log failures. */ - walkdir(dirname, unlink_if_exists_fname, false, LOG); + walkdir(dirname, unlink_if_exists_fname, false, LOG, NULL); } /* @@ -3610,6 +3641,21 @@ do_syncfs(const char *path) } #endif +/* + * Return a safe upper bound for the number of fsyncs to keep in flight. + * + * Callers that fsync files opened with OpenTransientFile() hold one + * AllocateDesc for each in-flight IO. At most max_safe_fds / 3 of those can + * be allocated at a time (see reserveAllocatedDesc()), and the callers of + * interest also traverse directories (see walkdir()), which needs + * AllocateDescs of its own. So, hand out at most half of the budget. + */ +int +GetFsyncConcurrencyLimit(void) +{ + return Max(1, Min(io_max_concurrency, max_safe_fds / 6)); +} + /* * Issue fsync recursively on PGDATA and all its contents, or issue syncfs for * all potential filesystem, depending on recovery_init_sync_method setting. @@ -3636,6 +3682,7 @@ void SyncDataDirectory(void) { bool xlog_is_symlink; + DataDirSyncState sync_state_data = {0}; /* We can skip this whole thing if fsync is disabled. */ if (!enableFsync) @@ -3707,15 +3754,22 @@ SyncDataDirectory(void) * directory and its contents. Errors in this step are even less * interesting than normal, so log them only at DEBUG1. */ - walkdir(".", pre_sync_fname, false, DEBUG1); + walkdir(".", pre_sync_fname, false, DEBUG1, NULL); if (xlog_is_symlink) - walkdir("pg_wal", pre_sync_fname, false, DEBUG1); - walkdir(PG_TBLSPC_DIR, pre_sync_fname, true, DEBUG1); + walkdir("pg_wal", pre_sync_fname, false, DEBUG1, NULL); + walkdir(PG_TBLSPC_DIR, pre_sync_fname, true, DEBUG1, NULL); #endif /* Prepare to report progress syncing the data directory via fsync. */ begin_startup_progress_phase(); + sync_state_data.elevel = LOG; + sync_state_data.max_inflight = GetFsyncConcurrencyLimit(); + sync_state_data.head = 0; + sync_state_data.count = 0; + sync_state_data.entries = palloc0(sizeof(DataDirSyncEntry) * + sync_state_data.max_inflight); + /* * Now we do the fsync()s in the same order. * @@ -3725,10 +3779,14 @@ SyncDataDirectory(void) * in pg_tblspc, they'll get fsync'd twice. That's not an expected case * so we don't worry about optimizing it. */ - walkdir(".", datadir_fsync_fname, false, LOG); + walkdir(".", datadir_fsync_fname, false, LOG, &sync_state_data); if (xlog_is_symlink) - walkdir("pg_wal", datadir_fsync_fname, false, LOG); - walkdir(PG_TBLSPC_DIR, datadir_fsync_fname, true, LOG); + walkdir("pg_wal", datadir_fsync_fname, false, LOG, &sync_state_data); + walkdir(PG_TBLSPC_DIR, datadir_fsync_fname, true, LOG, &sync_state_data); + + datadir_sync_drain_all(&sync_state_data); + + pfree(sync_state_data.entries); } /* @@ -3748,9 +3806,10 @@ SyncDataDirectory(void) */ static void walkdir(const char *path, - void (*action) (const char *fname, bool isdir, int elevel), + void (*action) (const char *fname, bool isdir, int elevel, DataDirSyncState *state), bool process_symlinks, - int elevel) + int elevel, + DataDirSyncState *state) { DIR *dir; struct dirent *de; @@ -3772,10 +3831,10 @@ walkdir(const char *path, switch (get_dirent_type(subpath, de, process_symlinks, elevel)) { case PGFILETYPE_REG: - (*action) (subpath, false, elevel); + (*action) (subpath, false, elevel, state); break; case PGFILETYPE_DIR: - walkdir(subpath, action, false, elevel); + walkdir(subpath, action, false, elevel, state); break; default: @@ -3797,7 +3856,7 @@ walkdir(const char *path, * might not be robust against that. */ if (dir) - (*action) (path, true, elevel); + (*action) (path, true, elevel, state); } @@ -3810,10 +3869,13 @@ walkdir(const char *path, #ifdef PG_FLUSH_DATA_WORKS static void -pre_sync_fname(const char *fname, bool isdir, int elevel) +pre_sync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state) { int fd; + /* No AIO implementation, so state should be NULL */ + Assert(!state); + /* Don't try to flush directories, it'll likely just fail */ if (isdir) return; @@ -3848,21 +3910,98 @@ pre_sync_fname(const char *fname, bool isdir, int elevel) #endif /* PG_FLUSH_DATA_WORKS */ static void -datadir_fsync_fname(const char *fname, bool isdir, int elevel) +datadir_sync_wait_one(DataDirSyncState *state) +{ + DataDirSyncEntry *entry; + + Assert(state->count > 0); + + entry = &state->entries[state->head]; + Assert(entry->in_use); + + pgaio_wref_wait(&entry->iow); + + /* + * As we didn't register a completion callback, the IO's status is always + * PGAIO_RS_OK; the raw fsync() return (0 or -errno) is available in + * ->result.result. Use the same error handling as fsync_fname_ext(). + */ + if (entry->ioret.result.result < 0) + errno = -entry->ioret.result.result; + + fsync_fname_close(entry->path, entry->isdir, state->elevel, entry->fd, entry->ioret.result.result); + + entry->in_use = false; + state->head = (state->head + 1) % state->max_inflight; + state->count--; +} + +static void +datadir_sync_drain_all(DataDirSyncState *state) +{ + while (state->count > 0) + datadir_sync_wait_one(state); + + Assert(state->count == 0); +} + +static void +datadir_fsync_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state) { + int fd; + int slot; + DataDirSyncEntry *entry; + PgAioHandle *ioh; + ereport_startup_progress("syncing data directory (fsync), elapsed time: %ld.%02d s, current path: %s", fname); /* - * We want to silently ignoring errors about unreadable files. Pass that - * desire on to fsync_fname_ext(). + * If the ring is full, wait before opening the next file, so that the + * number of open descriptors never temporarily exceeds the ring size. */ - fsync_fname_ext(fname, isdir, true, elevel); + if (state->count == state->max_inflight) + datadir_sync_wait_one(state); + + /* + * We want to silently ignore errors about unreadable files. Pass that + * desire on to fsync_fname_open(). + */ + if (!fsync_fname_open(fname, isdir, true, elevel, &fd)) + return; + + Assert(state->count < state->max_inflight); + slot = (state->head + state->count) % state->max_inflight; + entry = &state->entries[slot]; + Assert(!entry->in_use); + + entry->fd = fd; + entry->isdir = isdir; + strlcpy(entry->path, fname, MAXPGPATH); + entry->in_use = true; + + ioh = pgaio_io_acquire(CurrentResourceOwner, &entry->ioret); + pgaio_io_set_target(ioh, PGAIO_TID_SYNC); + pgaio_io_get_wref(ioh, &entry->iow); + + /* + * Interrupts must be held across staging the IO, so that the file + * descriptor it references cannot be closed by interrupt processing + * before the IO has been submitted. + */ + HOLD_INTERRUPTS(); + pgaio_io_start_fsync(ioh, fd, false, WAIT_EVENT_DATA_DIR_SYNC); + RESUME_INTERRUPTS(); + + state->count++; } static void -unlink_if_exists_fname(const char *fname, bool isdir, int elevel) +unlink_if_exists_fname(const char *fname, bool isdir, int elevel, DataDirSyncState *state) { + /* No AIO implementation, so state should be NULL */ + Assert(!state); + if (isdir) { if (rmdir(fname) != 0 && errno != ENOENT) @@ -3878,19 +4017,24 @@ unlink_if_exists_fname(const char *fname, bool isdir, int elevel) } /* - * fsync_fname_ext -- Try to fsync a file or directory + * Helper for opening a file as part of fsync_fname_ext() and + * datadir_fsync_fname(). Split out because the latter performs the fsync + * asynchronously via AIO. * - * If ignore_perm is true, ignore errors upon trying to open unreadable - * files. Logs other errors at a caller-specified level. + * If ignore_perm is true, ignore errors upon trying to open unreadable files. * - * Returns 0 if the operation succeeded, -1 otherwise. + * If the file could not be opened, false is returned; *fd is set to 0 if the + * failure should be ignored, or -1 otherwise. Other errors are logged at the + * caller-specified level. + * + * If the file was opened successfully, true is returned and *fd is set to + * the file descriptor. */ -int -fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) +static bool +fsync_fname_open(const char *fname, bool isdir, bool ignore_perm, + int elevel, int *fd) { - int fd; int flags; - int returncode; /* * Some OSs require directories to be opened read-only whereas other @@ -3904,27 +4048,48 @@ fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) else flags |= O_RDONLY; - fd = OpenTransientFile(fname, flags); + *fd = OpenTransientFile(fname, flags); /* * Some OSs don't allow us to open directories at all (Windows returns * EACCES), just ignore the error in that case. If desired also silently * ignoring errors about unreadable files. Log others. */ - if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES)) - return 0; - else if (fd < 0 && ignore_perm && errno == EACCES) - return 0; - else if (fd < 0) + if (*fd >= 0) + return true; + if (isdir && (errno == EISDIR || errno == EACCES)) + { + *fd = 0; + return false; + } + else if (ignore_perm && errno == EACCES) { + *fd = 0; + return false; + } + else + { + *fd = -1; ereport(elevel, (errcode_for_file_access(), errmsg("could not open file \"%s\": %m", fname))); - return -1; + return false; } +} - returncode = pg_fsync(fd); - +/* + * Helper for closing a file, and reporting any fsync failure, as part of + * fsync_fname_ext() and datadir_fsync_fname(). Split out because the latter + * performs the fsync asynchronously via AIO. + * + * "returncode" is the result of the preceding fsync; if it is negative, errno + * must describe the failure. + * + * Returns true if the operation succeeded, false otherwise. + */ +static bool +fsync_fname_close(const char *fname, bool isdir, int elevel, int fd, int returncode) +{ /* * Some OSes don't allow us to fsync directories at all, so we can ignore * those errors. Anything else needs to be logged. @@ -3941,7 +4106,7 @@ fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) ereport(elevel, (errcode_for_file_access(), errmsg("could not fsync file \"%s\": %m", fname))); - return -1; + return false; } if (CloseTransientFile(fd) != 0) @@ -3949,9 +4114,35 @@ fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) ereport(elevel, (errcode_for_file_access(), errmsg("could not close file \"%s\": %m", fname))); - return -1; + return false; } + return true; +} + +/* + * fsync_fname_ext -- Try to fsync a file or directory + * + * If ignore_perm is true, ignore errors upon trying to open unreadable + * files. Logs other errors at a caller-specified level. + * + * Returns 0 if the operation succeeded, -1 otherwise. + */ +int +fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel) +{ + int fd; + int returncode; + + if (!fsync_fname_open(fname, isdir, ignore_perm, elevel, &fd)) + return fd; + + Assert(fd >= 0); + returncode = pg_fsync(fd); + + if (!fsync_fname_close(fname, isdir, elevel, fd, returncode)) + return -1; + return 0; } diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt index 3d366fd1114..5b303ba0fb4 100644 --- a/src/backend/utils/activity/wait_event_names.txt +++ b/src/backend/utils/activity/wait_event_names.txt @@ -219,6 +219,7 @@ COPY_FILE_READ "Waiting for a read during a file copy operation." COPY_FILE_WRITE "Waiting for a write during a file copy operation." COPY_FROM_READ "Waiting to read data from a pipe, a file or a program during COPY FROM." COPY_TO_WRITE "Waiting to write data to a pipe, a file or a program during COPY TO." +DATA_DIR_SYNC "Waiting for the contents of the data directory to reach durable storage after a crash." DATA_FILE_EXTEND "Waiting for a relation data file to be extended." DATA_FILE_FLUSH "Waiting for a relation data file to reach durable storage." DATA_FILE_IMMEDIATE_SYNC "Waiting for an immediate synchronization of a relation data file to durable storage." diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index 9e96317b5c3..81d7632536d 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -118,9 +118,10 @@ typedef enum PgAioTargetID /* intentionally the zero value, to help catch zeroed memory etc */ PGAIO_TID_INVALID = 0, PGAIO_TID_SMGR, + PGAIO_TID_SYNC, } PgAioTargetID; -#define PGAIO_TID_COUNT (PGAIO_TID_SMGR + 1) +#define PGAIO_TID_COUNT (PGAIO_TID_SYNC + 1) /* diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h index 850af783a5c..c20b74cd9c3 100644 --- a/src/include/storage/fd.h +++ b/src/include/storage/fd.h @@ -221,6 +221,7 @@ extern int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int extern int durable_rename(const char *oldfile, const char *newfile, int elevel); extern int durable_unlink(const char *fname, int elevel); extern void SyncDataDirectory(void); +extern int GetFsyncConcurrencyLimit(void); extern int data_sync_elevel(int elevel); static inline ssize_t diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 656f1f60862..4a05abff273 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -636,7 +636,9 @@ DataChecksumsStateStruct DataChecksumsWorkerDatabase DataChecksumsWorkerOperation DataChecksumsWorkerResult +DataDirSyncEntry DataDirSyncMethod +DataDirSyncState DataDumperPtr DataPageDeleteStack DataTypesUsageChecks -- 2.47.3
v3-0005-aio-Allow-AIO-reopen-callbacks-to-return-errors.patch (text/x-patch, 9.2K) download From 5b85edd65f66bb407cc419bcacc70b6cceadd151 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 16 Sep 2026 10:53:05 +0300 Subject: [PATCH v3 5/8] aio: Allow AIO reopen callbacks to return errors Allow target reopen callbacks to return -errno for ordinary failures. IO workers pass these results through completion so the issuer can apply its error policy. Exceptions retain the existing worker recovery path, and relation read/write descriptor lookup keeps its existing error reporting. This prepares for asynchronous checkpoint fsyncs, where the issuer needs to distinguish potentially deleted files from other failures when deciding whether to retry or report a sync failure. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- src/backend/storage/aio/aio_target.c | 8 +- src/backend/storage/aio/method_worker.c | 99 ++++++++++++++----------- src/backend/storage/smgr/smgr.c | 20 +++-- src/include/storage/aio.h | 7 +- src/include/storage/aio_internal.h | 2 +- 5 files changed, 81 insertions(+), 55 deletions(-) diff --git a/src/backend/storage/aio/aio_target.c b/src/backend/storage/aio/aio_target.c index 82b24b0026d..1a0088fa382 100644 --- a/src/backend/storage/aio/aio_target.c +++ b/src/backend/storage/aio/aio_target.c @@ -136,11 +136,15 @@ pgaio_io_can_reopen(PgAioHandle *ioh) * IO has been staged in, the file descriptor has to be reopened - any FD * referenced in the IO itself, won't be valid in the separate process. */ -void +int pgaio_io_reopen(PgAioHandle *ioh) { + int result; + Assert(ioh->target > PGAIO_TID_INVALID && ioh->target < PGAIO_TID_COUNT); Assert(ioh->op > PGAIO_OP_INVALID && ioh->op < PGAIO_OP_COUNT); - pgaio_target_info[ioh->target]->reopen(ioh); + result = pgaio_target_info[ioh->target]->reopen(ioh); + + return result; } diff --git a/src/backend/storage/aio/method_worker.c b/src/backend/storage/aio/method_worker.c index a2271393179..5ed11cb5513 100644 --- a/src/backend/storage/aio/method_worker.c +++ b/src/backend/storage/aio/method_worker.c @@ -874,6 +874,7 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len) if (io_index != -1) { PgAioHandle *ioh = NULL; + int reopen_result; /* Cancel timeout and update wakeup:work ratio. */ idle_timeout_abs = 0; @@ -899,62 +900,72 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len) HOLD_INTERRUPTS(); /* - * It's very unlikely, but possible, that reopen fails. E.g. due - * to memory allocations failing or file permissions changing or - * such. In that case we need to fail the IO. - * - * There's not really a good errno we can report here. + * Ordinary reopen failures can return -errno below. If the + * callback instead raises an error, use the existing worker-exit + * recovery path, which has no reliable errno to report. */ error_errno = ENOENT; - pgaio_io_reopen(ioh); + reopen_result = pgaio_io_reopen(ioh); - /* - * To be able to exercise the reopen-fails path, allow injection - * points to trigger a failure at this point. - */ - INJECTION_POINT("aio-worker-after-reopen", ioh); + if (reopen_result < 0) + { + error_errno = 0; + error_ioh = NULL; + + START_CRIT_SECTION(); + pgaio_io_process_completion(ioh, reopen_result); + END_CRIT_SECTION(); + } + else + { + /* + * To be able to exercise the reopen-fails path, allow + * injection points to trigger a failure at this point. + */ + INJECTION_POINT("aio-worker-after-reopen", ioh); - error_errno = 0; - error_ioh = NULL; + error_errno = 0; + error_ioh = NULL; - /* - * As part of IO completion the buffer will be marked as NOACCESS, - * until the buffer is pinned again - which never happens in io - * workers. Therefore the next time there is IO for the same - * buffer, the memory will be considered inaccessible. To avoid - * that, explicitly allow access to the memory before reading data - * into it. - */ + /* + * As part of IO completion the buffer will be marked as + * NOACCESS, until the buffer is pinned again - which never + * happens in io workers. Therefore the next time there is IO + * for the same buffer, the memory will be considered + * inaccessible. To avoid that, explicitly allow access to the + * memory before reading data into it. + */ #ifdef USE_VALGRIND - { - struct iovec *iov; - uint16 iov_length = pgaio_io_get_iovec_length(ioh, &iov); + { + struct iovec *iov; + uint16 iov_length = pgaio_io_get_iovec_length(ioh, &iov); - for (int i = 0; i < iov_length; i++) - VALGRIND_MAKE_MEM_UNDEFINED(iov[i].iov_base, iov[i].iov_len); - } + for (int i = 0; i < iov_length; i++) + VALGRIND_MAKE_MEM_UNDEFINED(iov[i].iov_base, iov[i].iov_len); + } #endif #ifdef PGAIO_WORKER_SHOW_PS_INFO - { - char *description = pgaio_io_get_target_description(ioh); - - sprintf(cmd, "%d: [%s] %s", - MyIoWorkerId, - pgaio_io_get_op_name(ioh), - description); - pfree(description); - set_ps_display(cmd); - } + { + char *description = pgaio_io_get_target_description(ioh); + + sprintf(cmd, "%d: [%s] %s", + MyIoWorkerId, + pgaio_io_get_op_name(ioh), + description); + pfree(description); + set_ps_display(cmd); + } #endif - /* - * We don't expect this to ever fail with ERROR or FATAL, no need - * to keep error_ioh set to the IO. - * pgaio_io_perform_synchronously() contains a critical section to - * ensure we don't accidentally fail. - */ - pgaio_io_perform_synchronously(ioh); + /* + * We don't expect this to ever fail with ERROR or FATAL, no + * need to keep error_ioh set to the IO. + * pgaio_io_perform_synchronously() contains a critical + * section to ensure we don't accidentally fail. + */ + pgaio_io_perform_synchronously(ioh); + } RESUME_INTERRUPTS(); errcallback.arg = NULL; diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c index 1eeedb0931e..eb8636ba4a9 100644 --- a/src/backend/storage/smgr/smgr.c +++ b/src/backend/storage/smgr/smgr.c @@ -165,7 +165,7 @@ static dlist_head unpinned_relns; static void smgrshutdown(int code, Datum arg); static void smgrdestroy(SMgrRelation reln); -static void smgr_aio_reopen(PgAioHandle *ioh); +static int smgr_aio_reopen(PgAioHandle *ioh); static char *smgr_aio_describe_identity(const PgAioTargetData *sd); @@ -1071,9 +1071,11 @@ pgaio_io_set_target_smgr(PgAioHandle *ioh, /* * Callback for the smgr AIO target, to reopen the file (e.g. because the IO - * is executed in a worker). + * is executed in a worker). Returns 0 on success. Failures can return + * -errno, but relation read/write descriptor lookup retains its existing + * error reporting and may raise an error instead. */ -static void +static int smgr_aio_reopen(PgAioHandle *ioh) { PgAioTargetData *sd = pgaio_io_get_target_data(ioh); @@ -1081,6 +1083,7 @@ smgr_aio_reopen(PgAioHandle *ioh) SMgrRelation reln; ProcNumber procno; uint32 off; + int fd; /* * The caller needs to prevent interrupts from being processed, otherwise @@ -1102,15 +1105,18 @@ smgr_aio_reopen(PgAioHandle *ioh) case PGAIO_OP_READV: od->read.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); Assert(off == od->read.offset); - break; + return 0; case PGAIO_OP_WRITEV: od->write.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); Assert(off == od->write.offset); - break; + return 0; case PGAIO_OP_FSYNC: - od->fsync.fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); - break; + fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); + od->fsync.fd = fd; + return 0; } + + pg_unreachable(); } /* diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index 81d7632536d..01f0f8ccccf 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -170,8 +170,13 @@ struct PgAioTargetInfo /* * To support executing using worker processes, the file descriptor for an * IO may need to be reopened in a different process. + * + * Returns 0 on success. Callbacks can return -errno for an ordinary + * failure to reopen, allowing the issuer to handle the failure without + * terminating the worker. Callbacks that raise an error instead use the + * worker's exception-recovery path, which does not preserve errno. */ - void (*reopen) (PgAioHandle *ioh); + int (*reopen) (PgAioHandle *ioh); /* describe the target of the IO, used for log messages and views */ char *(*describe_identity) (const PgAioTargetData *sd); diff --git a/src/include/storage/aio_internal.h b/src/include/storage/aio_internal.h index 9ca4087aa7f..35d4f3f310d 100644 --- a/src/include/storage/aio_internal.h +++ b/src/include/storage/aio_internal.h @@ -359,7 +359,7 @@ extern int pgaio_io_get_iovec_length(PgAioHandle *ioh, struct iovec **iov); /* aio_target.c */ extern bool pgaio_io_can_reopen(PgAioHandle *ioh); -extern void pgaio_io_reopen(PgAioHandle *ioh); +extern int pgaio_io_reopen(PgAioHandle *ioh); extern const char *pgaio_io_get_target_name(PgAioHandle *ioh); -- 2.47.3
v3-0006-aio-Issue-checkpointer-fsyncs-asynchronously.patch (text/x-patch, 59.5K) download From 929a061e6d59b35912becd1430f3fac142f6eaec Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 16 Sep 2026 13:30:15 +0300 Subject: [PATCH v3 6/8] aio: Issue checkpointer fsyncs asynchronously ProcessSyncRequests() previously fsynced pending files one at a time. For checkpoints with many files, this serialized I/O that storage could perform concurrently. Submit the fsyncs through AIO, keeping a bounded set in flight and reaping completions in submission order. Relation requests may use all io_max_concurrency slots. For SLRU requests, apply a transient-descriptor limit to the total in-flight count so their open files do not exhaust the descriptor reserve. Reshape the sync handler API so handlers open the file, assign an AIO target, start the fsync, and record how to close it. sync.c manages the in-flight operations, errors, retries, and pendingOps bookkeeping. Absorbing requests while fsyncs are in flight requires some care: - Recheck cancellation when an operation is reaped because a request can be canceled after its fsync starts. - Defer completion bookkeeping until the pendingOps scan ends because dynahash permits removing only the entry most recently returned. - Keep a new request for a file already in flight until the next checkpoint cycle because the running fsync might not cover its write. Error cleanup drains and closes all outstanding operations while preserving the first durability error that requires PANIC. Otherwise, preserve the original error and leave retries to the next checkpoint. Do not reinterpret an already-handled deletion failure as a failed retry during cleanup. Relation files can be reopened through the smgr target, allowing I/O workers to perform their fsyncs. Open the exact segment path so inactive segments following a truncated partial segment remain syncable. Add a target close callback to release transient worker-side descriptors after execution. SLRU files use the generic sync target and execute synchronously with the worker I/O method, although io_uring can still overlap them. Measure time spent starting each request and waiting for operations that are not already complete. Include only successful attempts in checkpoint longest and aggregate statistics. Add a pgstat helper that accepts an end timestamp. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- src/backend/access/transam/clog.c | 6 +- src/backend/access/transam/commit_ts.c | 6 +- src/backend/access/transam/multixact.c | 12 +- src/backend/access/transam/slru.c | 35 +- src/backend/storage/aio/aio_callback.c | 1 + src/backend/storage/aio/aio_io.c | 8 + src/backend/storage/aio/aio_target.c | 39 +- src/backend/storage/file/fd.c | 39 +- src/backend/storage/smgr/md.c | 134 +++++- src/backend/storage/smgr/smgr.c | 46 +- src/backend/storage/sync/sync.c | 638 ++++++++++++++++++++----- src/backend/utils/activity/pgstat_io.c | 47 +- src/include/access/clog.h | 2 +- src/include/access/commit_ts.h | 2 +- src/include/access/multixact.h | 4 +- src/include/access/slru.h | 2 +- src/include/pgstat.h | 4 + src/include/storage/aio.h | 7 + src/include/storage/aio_internal.h | 1 + src/include/storage/fd.h | 3 +- src/include/storage/md.h | 4 +- src/include/storage/sync.h | 55 +++ src/test/modules/test_slru/test_slru.c | 45 +- src/tools/pgindent/typedefs.list | 3 + 24 files changed, 952 insertions(+), 191 deletions(-) diff --git a/src/backend/access/transam/clog.c b/src/backend/access/transam/clog.c index 6f7f6b86eb6..89fb77ea5da 100644 --- a/src/backend/access/transam/clog.c +++ b/src/backend/access/transam/clog.c @@ -1117,8 +1117,8 @@ clog_redo(XLogReaderState *record) /* * Entrypoint for sync.c to sync clog files. */ -int -clogsyncfiletag(const FileTag *ftag, char *path) +void +clogsyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(XactCtl, ftag, path); + SlruSyncFileTag(XactCtl, ioh, entry); } diff --git a/src/backend/access/transam/commit_ts.c b/src/backend/access/transam/commit_ts.c index 9e6fd5d4657..7cbbad383b2 100644 --- a/src/backend/access/transam/commit_ts.c +++ b/src/backend/access/transam/commit_ts.c @@ -1028,8 +1028,8 @@ commit_ts_redo(XLogReaderState *record) /* * Entrypoint for sync.c to sync commit_ts files. */ -int -committssyncfiletag(const FileTag *ftag, char *path) +void +committssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(CommitTsCtl, ftag, path); + SlruSyncFileTag(CommitTsCtl, ioh, entry); } diff --git a/src/backend/access/transam/multixact.c b/src/backend/access/transam/multixact.c index 3caedb54850..1166e2a2114 100644 --- a/src/backend/access/transam/multixact.c +++ b/src/backend/access/transam/multixact.c @@ -2975,17 +2975,17 @@ multixact_redo(XLogReaderState *record) /* * Entrypoint for sync.c to sync offsets files. */ -int -multixactoffsetssyncfiletag(const FileTag *ftag, char *path) +void +multixactoffsetssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(MultiXactOffsetCtl, ftag, path); + SlruSyncFileTag(MultiXactOffsetCtl, ioh, entry); } /* * Entrypoint for sync.c to sync members files. */ -int -multixactmemberssyncfiletag(const FileTag *ftag, char *path) +void +multixactmemberssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { - return SlruSyncFileTag(MultiXactMemberCtl, ftag, path); + SlruSyncFileTag(MultiXactMemberCtl, ioh, entry); } diff --git a/src/backend/access/transam/slru.c b/src/backend/access/transam/slru.c index 885fd068535..b1e513ac3b6 100644 --- a/src/backend/access/transam/slru.c +++ b/src/backend/access/transam/slru.c @@ -68,6 +68,7 @@ #include "access/xlogutils.h" #include "miscadmin.h" #include "pgstat.h" +#include "storage/aio.h" #include "storage/fd.h" #include "storage/shmem.h" #include "storage/shmem_internal.h" @@ -1880,26 +1881,32 @@ SlruScanDirectory(SlruDesc *ctl, SlruScanCallback callback, void *data) * build the path), but they just forward to this common implementation that * performs the fsync. */ -int -SlruSyncFileTag(SlruDesc *ctl, const FileTag *ftag, char *path) +void +SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, InflightSyncEntry *entry) { int fd; - int save_errno; - int result; - SlruFileName(ctl, path, ftag->segno); + SlruFileName(ctl, entry->path, entry->tag.segno); - fd = OpenTransientFile(path, O_RDWR | PG_BINARY); + fd = OpenTransientFile(entry->path, O_RDWR | PG_BINARY); if (fd < 0) - return -1; + { + entry->started = false; + entry->open_errno = errno; + return; + } - pgstat_report_wait_start(WAIT_EVENT_SLRU_FLUSH_SYNC); - result = pg_fsync(fd); - pgstat_report_wait_end(); - save_errno = errno; + /* + * Use the generic sync target. SLRU segments are not smgr relations and + * cannot be reopened from a FileTag in another process, so this fsync + * will run synchronously in worker mode. + */ + pgaio_io_set_target(ioh, PGAIO_TID_SYNC); - CloseTransientFile(fd); + /* Start the asynchronous fsync; the fd is closed once it completes. */ + pgaio_io_start_fsync(ioh, fd, false, WAIT_EVENT_SLRU_FLUSH_SYNC); - errno = save_errno; - return result; + entry->started = true; + entry->close_method = SYNC_CLOSE_TRANSIENT; + entry->close_file = fd; } diff --git a/src/backend/storage/aio/aio_callback.c b/src/backend/storage/aio/aio_callback.c index 206b81f5028..7140af78a34 100644 --- a/src/backend/storage/aio/aio_callback.c +++ b/src/backend/storage/aio/aio_callback.c @@ -41,6 +41,7 @@ static const PgAioHandleCallbacksEntry aio_handle_cbs[] = { CALLBACK_ENTRY(PGAIO_HCB_INVALID, aio_invalid_cb), CALLBACK_ENTRY(PGAIO_HCB_MD_READV, aio_md_readv_cb), + CALLBACK_ENTRY(PGAIO_HCB_MD_FSYNC, aio_md_fsync_cb), CALLBACK_ENTRY(PGAIO_HCB_SHARED_BUFFER_READV, aio_shared_buffer_readv_cb), diff --git a/src/backend/storage/aio/aio_io.c b/src/backend/storage/aio/aio_io.c index 72c43ee54e4..5200514d0b6 100644 --- a/src/backend/storage/aio/aio_io.c +++ b/src/backend/storage/aio/aio_io.c @@ -189,6 +189,14 @@ pgaio_io_perform_synchronously(PgAioHandle *ioh) Assert(result <= INT_MAX); ioh->result = result < 0 ? -errno : result; + /* + * If we, rather than the process that staged the IO, opened the file, + * close it again. Has to happen after the result has been determined, as + * closing may clobber errno, and before the completion is processed, as + * that can recycle the handle. + */ + pgaio_io_close_reopened(ioh); + pgaio_io_process_completion(ioh, ioh->result); END_CRIT_SECTION(); diff --git a/src/backend/storage/aio/aio_target.c b/src/backend/storage/aio/aio_target.c index 1a0088fa382..534382b423b 100644 --- a/src/backend/storage/aio/aio_target.c +++ b/src/backend/storage/aio/aio_target.c @@ -41,6 +41,13 @@ static const PgAioTargetInfo *pgaio_target_info[] = { [PGAIO_TID_SYNC] = &aio_sync_target_info, }; +/* + * The IO whose descriptor this process reopened and whose target requires the + * descriptor to be released after execution. Only set between + * pgaio_io_reopen() and pgaio_io_close_reopened(). + */ +static PgAioHandle *pgaio_reopened_ioh = NULL; + /* * describe_identity callback for PGAIO_TID_SYNC. As we do not store the path @@ -143,8 +150,38 @@ pgaio_io_reopen(PgAioHandle *ioh) Assert(ioh->target > PGAIO_TID_INVALID && ioh->target < PGAIO_TID_COUNT); Assert(ioh->op > PGAIO_OP_INVALID && ioh->op < PGAIO_OP_COUNT); + Assert(pgaio_reopened_ioh == NULL); result = pgaio_target_info[ioh->target]->reopen(ioh); - return result; + if (result < 0) + return result; + + /* + * Remember that this process, rather than the one that staged the IO, + * owns the file descriptor now, so that pgaio_io_close_reopened() can + * release it once the IO has been executed. + */ + if (pgaio_target_info[ioh->target]->close != NULL) + pgaio_reopened_ioh = ioh; + + return 0; +} + +/* + * Internal: Counterpart to pgaio_io_reopen(), releasing the file descriptor it + * acquired. Does nothing unless this process reopened this very IO and its + * target needs the descriptor to be released. + * + * This has to be called before the IO's completion is processed, as that can + * make the handle be reused for an unrelated IO. + */ +void +pgaio_io_close_reopened(PgAioHandle *ioh) +{ + if (pgaio_reopened_ioh != ioh) + return; + + pgaio_reopened_ioh = NULL; + pgaio_target_info[ioh->target]->close(ioh); } diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index cb3927f814c..22733c80903 100644 --- a/src/backend/storage/file/fd.c +++ b/src/backend/storage/file/fd.c @@ -2302,6 +2302,29 @@ FileStartReadV(PgAioHandle *ioh, File file, return 0; } +int +FileStartSync(PgAioHandle *ioh, File file, bool datasync, + uint32 wait_event_info) +{ + int returnCode; + Vfd *vfdP; + + Assert(FileIsValid(file)); + + DO_DB(elog(LOG, "FileStartSync: %d (%s)", + file, VfdCache[file].fileName)); + + returnCode = FileAccess(file); + if (returnCode < 0) + return returnCode; + + vfdP = &VfdCache[file]; + + pgaio_io_start_fsync(ioh, vfdP->fd, datasync, wait_event_info); + + return 0; +} + ssize_t FileWriteV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info) @@ -3646,14 +3669,18 @@ do_syncfs(const char *path) * * Callers that fsync files opened with OpenTransientFile() hold one * AllocateDesc for each in-flight IO. At most max_safe_fds / 3 of those can - * be allocated at a time (see reserveAllocatedDesc()), and the callers of - * interest also traverse directories (see walkdir()), which needs - * AllocateDescs of its own. So, hand out at most half of the budget. + * be allocated at a time (see reserveAllocatedDesc()). Keep half of that + * budget available for directory traversal and other AllocateDesc users. + * + * Other callers only need to respect the AIO handle limit. */ int -GetFsyncConcurrencyLimit(void) +GetFsyncConcurrencyLimit(bool uses_transient_fd) { - return Max(1, Min(io_max_concurrency, max_safe_fds / 6)); + if (uses_transient_fd) + return Max(1, Min(io_max_concurrency, max_safe_fds / 6)); + + return io_max_concurrency; } /* @@ -3764,7 +3791,7 @@ SyncDataDirectory(void) begin_startup_progress_phase(); sync_state_data.elevel = LOG; - sync_state_data.max_inflight = GetFsyncConcurrencyLimit(); + sync_state_data.max_inflight = GetFsyncConcurrencyLimit(true); sync_state_data.head = 0; sync_state_data.count = 0; sync_state_data.entries = palloc0(sizeof(DataDirSyncEntry) * diff --git a/src/backend/storage/smgr/md.c b/src/backend/storage/smgr/md.c index 780c88c0630..3d923841f71 100644 --- a/src/backend/storage/smgr/md.c +++ b/src/backend/storage/smgr/md.c @@ -165,12 +165,19 @@ static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum, static PgAioResult md_readv_complete(PgAioHandle *ioh, PgAioResult prior_result, uint8 cb_data); static void md_readv_report(PgAioResult result, const PgAioTargetData *td, int elevel); +static PgAioResult md_fsync_complete(PgAioHandle *ioh, PgAioResult prior_result, uint8 cb_data); +static void md_fsync_report(PgAioResult result, const PgAioTargetData *td, int elevel); const PgAioHandleCallbacks aio_md_readv_cb = { .complete_shared = md_readv_complete, .report = md_readv_report, }; +const PgAioHandleCallbacks aio_md_fsync_cb = { + .complete_shared = md_fsync_complete, + .report = md_fsync_report, +}; + static inline int _mdfd_open_flags(void) @@ -1505,6 +1512,22 @@ mdfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, uint32 *off) return FileGetRawDesc(v->mdfd_vfd); } +/* + * Open the exact segment containing blocknum for fsync, or return -1 with + * errno set. + */ +int +mdfsyncfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum) +{ + MdPathStr path; + BlockNumber segno; + + segno = blocknum / ((BlockNumber) RELSEG_SIZE); + path = _mdfd_segpath(reln, forknum, segno); + + return OpenTransientFile(path.str, _mdfd_open_flags()); +} + /* * register_dirty_segment() -- Mark a relation segment as needing fsync * @@ -1896,26 +1919,27 @@ _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg) } /* - * Sync a file to disk, given a file tag. Write the path into an output - * buffer so the caller can use it in error messages. + * Sync a file to disk, given a file tag. * - * Return 0 on success, -1 on failure, with errno set. + * Starts an asynchronous fsync on the given AIO handle and records in "entry" + * the path (for error messages), whether an IO was started, and how the file + * is to be closed once the fsync has completed. */ -int -mdsyncfiletag(const FileTag *ftag, char *path) +void +mdsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry) { + FileTag *ftag = &entry->tag; SMgrRelation reln = smgropen(ftag->rlocator, INVALID_PROC_NUMBER); + BlockNumber segfirstblock = ftag->segno * ((BlockNumber) RELSEG_SIZE); File file; - instr_time io_start; bool need_to_close; - int result, - save_errno; + instr_time io_start; /* See if we already have the file open, or need to open it. */ if (ftag->segno < reln->md_num_open_segs[ftag->forknum]) { file = reln->md_seg_fds[ftag->forknum][ftag->segno].mdfd_vfd; - strlcpy(path, FilePathName(file), MAXPGPATH); + strlcpy(entry->path, FilePathName(file), MAXPGPATH); need_to_close = false; } else @@ -1923,28 +1947,54 @@ mdsyncfiletag(const FileTag *ftag, char *path) MdPathStr p; p = _mdfd_segpath(reln, ftag->forknum, ftag->segno); - strlcpy(path, p.str, MD_PATH_STR_MAXLEN); + strlcpy(entry->path, p.str, MD_PATH_STR_MAXLEN); - file = PathNameOpenFile(path, _mdfd_open_flags()); + file = PathNameOpenFile(entry->path, _mdfd_open_flags()); if (file < 0) - return -1; + { + entry->started = false; + entry->open_errno = errno; + return; + } need_to_close = true; } + pgaio_io_set_target_smgr(ioh, reln, ftag->forknum, segfirstblock, + 0, false); + pgaio_io_register_callbacks(ioh, PGAIO_HCB_MD_FSYNC, 0); + + /* + * As with asynchronous reads, measure the time spent starting the IO. + * Synchronous execution includes the fsync itself; otherwise this only + * measures submission. + */ io_start = pgstat_prepare_io_time(track_io_timing); - /* Sync the file. */ - result = FileSync(file, WAIT_EVENT_DATA_FILE_SYNC); - save_errno = errno; + if (FileStartSync(ioh, file, false, WAIT_EVENT_DATA_FILE_SYNC) < 0) + { + entry->started = false; + entry->open_errno = errno; + if (need_to_close) + FileClose(file); + return; + } - if (need_to_close) - FileClose(file); + pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL, IOOP_FSYNC, + io_start, 1, 0); - pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL, - IOOP_FSYNC, io_start, 1, 0); + entry->started = true; - errno = save_errno; - return result; + /* + * If we opened the segment ourselves it has to be closed once the fsync + * has completed; segments owned by smgr are left to smgr to manage. + */ + if (need_to_close) + { + entry->close_method = SYNC_CLOSE_VFD; + entry->close_file = (int) file; + } + else + entry->close_method = SYNC_CLOSE_NONE; } /* @@ -1986,6 +2036,48 @@ mdfiletagmatches(const FileTag *ftag, const FileTag *candidate) return ftag->rlocator.dbOid == candidate->rlocator.dbOid; } +/* + * Relation fsync completion and error reporting. Leave reporting to the + * issuer: a missing file can be an expected consequence of a concurrent drop + * or truncation, and checkpoint fsyncs must apply their retry policy first. + */ +static PgAioResult +md_fsync_complete(PgAioHandle *ioh, PgAioResult prior_result, uint8 cb_data) +{ + PgAioResult result = prior_result; + + Assert(prior_result.result <= 0); + if (prior_result.result < 0) + { + result.status = PGAIO_RS_ERROR; + result.id = PGAIO_HCB_MD_FSYNC; + result.error_data = -prior_result.result; + } + + /* Keep the raw result for callers applying their own error policy. */ + return result; +} + +static void +md_fsync_report(PgAioResult result, const PgAioTargetData *td, int elevel) +{ + RelPathStr relpath; + MdPathStr path; + BlockNumber segno = td->smgr.blockNum / ((BlockNumber) RELSEG_SIZE); + + Assert(!td->smgr.is_temp); + relpath = relpathperm(td->smgr.rlocator, td->smgr.forkNum); + if (segno == 0) + strlcpy(path.str, relpath.str, sizeof(path.str)); + else + snprintf(path.str, sizeof(path.str), "%s.%u", relpath.str, segno); + + errno = result.error_data; + ereport(elevel, + (errcode_for_file_access(), + errmsg("could not fsync file \"%s\": %m", path.str))); +} + /* * AIO completion callback for mdstartreadv(). */ diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c index eb8636ba4a9..ae62b79fd19 100644 --- a/src/backend/storage/smgr/smgr.c +++ b/src/backend/storage/smgr/smgr.c @@ -68,6 +68,7 @@ #include "miscadmin.h" #include "storage/aio.h" #include "storage/bufmgr.h" +#include "storage/fd.h" #include "storage/ipc.h" #include "storage/md.h" #include "storage/smgr.h" @@ -123,6 +124,7 @@ typedef struct f_smgr void (*smgr_immedsync) (SMgrRelation reln, ForkNumber forknum); void (*smgr_registersync) (SMgrRelation reln, ForkNumber forknum); int (*smgr_fd) (SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, uint32 *off); + int (*smgr_fsync_fd) (SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum); } f_smgr; static const f_smgr smgrsw[] = { @@ -148,6 +150,7 @@ static const f_smgr smgrsw[] = { .smgr_immedsync = mdimmedsync, .smgr_registersync = mdregistersync, .smgr_fd = mdfd, + .smgr_fsync_fd = mdfsyncfd, } }; @@ -166,12 +169,14 @@ static void smgrshutdown(int code, Datum arg); static void smgrdestroy(SMgrRelation reln); static int smgr_aio_reopen(PgAioHandle *ioh); +static void smgr_aio_close(PgAioHandle *ioh); static char *smgr_aio_describe_identity(const PgAioTargetData *sd); const PgAioTargetInfo aio_smgr_target_info = { .name = "smgr", .reopen = smgr_aio_reopen, + .close = smgr_aio_close, .describe_identity = smgr_aio_describe_identity, }; @@ -1014,6 +1019,18 @@ smgrfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, uint32 *off) return fd; } +/* + * Open the exact segment containing blocknum for fsync, returning a transient + * descriptor, or -1 with errno set if the file cannot be opened. + */ +static int +smgrfsyncfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum) +{ + Assert(!INTERRUPTS_CAN_BE_PROCESSED()); + + return smgrsw[reln->smgr_which].smgr_fsync_fd(reln, forknum, blocknum); +} + /* * AtEOXact_SMgr * @@ -1111,7 +1128,10 @@ smgr_aio_reopen(PgAioHandle *ioh) Assert(off == od->write.offset); return 0; case PGAIO_OP_FSYNC: - fd = smgrfd(reln, sd->smgr.forkNum, sd->smgr.blockNum, &off); + fd = smgrfsyncfd(reln, sd->smgr.forkNum, sd->smgr.blockNum); + /* We need errno for only checkpointer fsyncs for now */ + if (fd < 0) + return -errno; od->fsync.fd = fd; return 0; } @@ -1119,6 +1139,21 @@ smgr_aio_reopen(PgAioHandle *ioh) pg_unreachable(); } +/* + * Release a transient descriptor opened for a worker-executed fsync. + */ +static void +smgr_aio_close(PgAioHandle *ioh) +{ + PgAioOpData *od = pgaio_io_get_op_data(ioh); + + if (pgaio_io_get_op(ioh) == PGAIO_OP_FSYNC) + { + (void) CloseTransientFile(od->fsync.fd); + od->fsync.fd = -1; + } +} + /* * Callback for the smgr AIO target, describing the target of the IO. */ @@ -1134,7 +1169,14 @@ smgr_aio_describe_identity(const PgAioTargetData *sd) sd->smgr.forkNum); if (sd->smgr.nblocks == 0) - desc = psprintf(_("file \"%s\""), path.str); + { + BlockNumber segno = sd->smgr.blockNum / ((BlockNumber) RELSEG_SIZE); + + if (segno > 0) + desc = psprintf(_("file \"%s.%u\""), path.str, segno); + else + desc = psprintf(_("file \"%s\""), path.str); + } else if (sd->smgr.nblocks == 1) desc = psprintf(_("block %u in file \"%s\""), sd->smgr.blockNum, diff --git a/src/backend/storage/sync/sync.c b/src/backend/storage/sync/sync.c index 2c964b6f3d9..c40c79258a2 100644 --- a/src/backend/storage/sync/sync.c +++ b/src/backend/storage/sync/sync.c @@ -26,7 +26,10 @@ #include "pgstat.h" #include "portability/instr_time.h" #include "postmaster/bgwriter.h" +#include "storage/aio.h" +#include "storage/bufmgr.h" #include "storage/fd.h" +#include "storage/ipc.h" #include "storage/latch.h" #include "storage/md.h" #include "utils/hsearch.h" @@ -54,11 +57,22 @@ */ typedef uint16 CycleCtr; /* can be any convenient integer size */ -typedef struct +typedef struct PendingFsyncEntry { FileTag tag; /* identifies handler and file */ CycleCtr cycle_ctr; /* sync_cycle_ctr of oldest request */ bool canceled; /* canceled is true if we canceled "recently" */ + + /* + * Set when a request arrives for a tag that already has an entry, and + * cleared whenever an fsync for it is started. If it is set once that + * fsync completes, the request came in while the fsync was in flight, so + * the fsync cannot be assumed to have covered it. + */ + bool re_requested; + + /* fsync is done, pending hash-table bookkeeping */ + bool sync_completed; } PendingFsyncEntry; typedef struct @@ -68,10 +82,43 @@ typedef struct bool canceled; /* true if request has been canceled */ } PendingUnlinkEntry; +/* + * Transient state used while processing a batch of fsync requests. A single + * SyncState instance lives on the stack of ProcessSyncRequests() so that no + * partial state survives across calls. + */ +typedef struct SyncState +{ + dlist_head inflight; /* InflightSyncEntry being fsync'd right now */ + dlist_head retry; /* InflightSyncEntry to be retried */ + int inflight_count; /* number of entries in "inflight" */ + int absorb_counter; + + /* stats */ + int processed; + instr_time longest; + instr_time total_elapsed; +} SyncState; + static HTAB *pendingOps = NULL; static List *pendingUnlinks = NIL; static MemoryContext pendingOpsCxt; /* context for the above */ +/* + * Context for the InflightSyncEntry structs allocated while a batch of fsync + * requests is being processed. It is kept separate from pendingOpsCxt (which + * must survive for the lifetime of the process, as it holds pendingOps + * itself), so that it can be reset between batches. + */ +static MemoryContext inflightSyncCxt; + +/* + * All InflightSyncEntry structs that have not yet been freed. Unlike the + * lists in SyncState, this survives an error so that handler-owned files can + * be closed before their entries are discarded. + */ +static dlist_head activeSyncEntries = DLIST_STATIC_INIT(activeSyncEntries); + static CycleCtr sync_cycle_ctr = 0; static CycleCtr checkpoint_cycle_ctr = 0; @@ -84,10 +131,11 @@ static CycleCtr checkpoint_cycle_ctr = 0; */ typedef struct SyncOps { - int (*sync_syncfiletag) (const FileTag *ftag, char *path); + void (*sync_syncfiletag) (PgAioHandle *ioh, InflightSyncEntry *entry); int (*sync_unlinkfiletag) (const FileTag *ftag, char *path); bool (*sync_filetagmatches) (const FileTag *ftag, const FileTag *candidate); + bool uses_transient_fd; } SyncOps; /* @@ -98,23 +146,28 @@ static const SyncOps syncsw[] = { [SYNC_HANDLER_MD] = { .sync_syncfiletag = mdsyncfiletag, .sync_unlinkfiletag = mdunlinkfiletag, - .sync_filetagmatches = mdfiletagmatches + .sync_filetagmatches = mdfiletagmatches, + .uses_transient_fd = false }, /* pg_xact */ [SYNC_HANDLER_CLOG] = { - .sync_syncfiletag = clogsyncfiletag + .sync_syncfiletag = clogsyncfiletag, + .uses_transient_fd = true }, /* pg_commit_ts */ [SYNC_HANDLER_COMMIT_TS] = { - .sync_syncfiletag = committssyncfiletag + .sync_syncfiletag = committssyncfiletag, + .uses_transient_fd = true }, /* pg_multixact/offsets */ [SYNC_HANDLER_MULTIXACT_OFFSET] = { - .sync_syncfiletag = multixactoffsetssyncfiletag + .sync_syncfiletag = multixactoffsetssyncfiletag, + .uses_transient_fd = true }, /* pg_multixact/members */ [SYNC_HANDLER_MULTIXACT_MEMBER] = { - .sync_syncfiletag = multixactmemberssyncfiletag + .sync_syncfiletag = multixactmemberssyncfiletag, + .uses_transient_fd = true } }; @@ -155,6 +208,10 @@ InitSync(void) &hash_ctl, HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); pendingUnlinks = NIL; + + inflightSyncCxt = AllocSetContextCreate(TopMemoryContext, + "Inflight sync context", + ALLOCSET_DEFAULT_SIZES); } } @@ -281,25 +338,379 @@ SyncPostCheckpoint(void) } /* - * ProcessSyncRequests() -- Process queued fsync requests. + * Close the file that a sync handler opened for an in-flight fsync. */ -void -ProcessSyncRequests(void) +static void +sync_close_file(InflightSyncEntry *entry) { - static bool sync_in_progress = false; + switch (entry->close_method) + { + case SYNC_CLOSE_NONE: + break; + case SYNC_CLOSE_TRANSIENT: + CloseTransientFile(entry->close_file); + break; + case SYNC_CLOSE_VFD: + FileClose((File) entry->close_file); + break; + default: + pg_unreachable(); + } + + entry->close_method = SYNC_CLOSE_NONE; +} + +static void +sync_free_entry(InflightSyncEntry *entry) +{ + dlist_delete_from(&activeSyncEntries, &entry->cleanup_node); + pfree(entry); +} + +/* + * Error cleanup callback for ProcessSyncRequests(). + */ +static void +sync_cleanup_inflight(int code, Datum arg) +{ + int save_errno = 0; + char path[MAXPGPATH]; + + /* Do not let an interrupt abandon the remaining IOs during cleanup. */ + HOLD_INTERRUPTS(); + + while (!dlist_is_empty(&activeSyncEntries)) + { + dlist_node *node = dlist_pop_head_node(&activeSyncEntries); + InflightSyncEntry *entry; + int result; + + entry = dlist_container(InflightSyncEntry, cleanup_node, node); + + if (entry->started) + { + pgaio_wref_wait(&entry->iow); + result = -entry->ioret.result.result; + } + else + result = entry->open_errno; + + /* + * Completion callbacks leave error reporting to us. Even though the + * checkpoint has already failed, we must not discard a durability + * error that requires PANIC, including a recorded failure to open the + * file. As in sync_drain_one(), ignore canceled requests and allow a + * first failure that could be due to deletion. Leave retries to the + * next checkpoint. + * + * Save the first such error without allocating memory or raising + * another ERROR, so that all outstanding IOs are cleaned up. + */ + if (result != 0 && save_errno == 0 && + !entry->hash_entry->canceled && + (!FILE_POSSIBLY_DELETED(result) || entry->retry_count > 0) && + data_sync_elevel(ERROR) == PANIC) + { + save_errno = result; + strlcpy(path, entry->path, sizeof(path)); + } + + sync_close_file(entry); + pfree(entry); + } + RESUME_INTERRUPTS(); + + if (save_errno != 0) + { + errno = save_errno; + ereport(data_sync_elevel(ERROR), + (errcode_for_file_access(), + errmsg("could not fsync file \"%s\": %m", path))); + } +} + +static void +sync_start_one(SyncState *sync_state, InflightSyncEntry *entry) +{ + struct PgAioHandle *ioh; + instr_time io_start; + + entry->started = false; + entry->open_errno = 0; + entry->close_method = SYNC_CLOSE_NONE; + INSTR_TIME_SET_ZERO(entry->io_time); + pgaio_wref_clear(&entry->iow); + + /* + * Any request that arrives from here on may cover data that the fsync + * started below does not, so start out with a clean slate. This has to + * happen before the IO is submitted; requests absorbed in between are + * covered by the fsync, so treating them as newer is merely conservative. + */ + entry->hash_entry->re_requested = false; + + ioh = pgaio_io_acquire(CurrentResourceOwner, &entry->ioret); + pgaio_io_get_wref(ioh, &entry->iow); + + /* + * The handler opens the file, assigns the target and stages the fsync. + * Hold interrupts so that the referenced descriptor cannot be closed + * during submission. + */ + HOLD_INTERRUPTS(); + INSTR_TIME_SET_CURRENT(io_start); + syncsw[entry->tag.handler].sync_syncfiletag(ioh, entry); + INSTR_TIME_SET_CURRENT(entry->io_time); + RESUME_INTERRUPTS(); + INSTR_TIME_SUBTRACT(entry->io_time, io_start); + + if (!entry->started) + pgaio_io_release(ioh); + + Assert(!entry->started || + (entry->close_method == SYNC_CLOSE_TRANSIENT) == + syncsw[entry->tag.handler].uses_transient_fd); + + dlist_push_tail(&sync_state->inflight, &entry->node); + sync_state->inflight_count++; + + Assert(sync_state->inflight_count <= io_max_concurrency); +} + +static void +sync_drain_one(SyncState *sync_state) +{ + dlist_node *node; + InflightSyncEntry *entry; + int result; + instr_time io_time; + + Assert(sync_state->inflight_count > 0); + + node = dlist_pop_head_node(&sync_state->inflight); + entry = dlist_container(InflightSyncEntry, node, node); + sync_state->inflight_count--; + + if (entry->started) + { + if (entry->ioret.result.status == PGAIO_RS_UNKNOWN && + !pgaio_wref_check_done(&entry->iow)) + { + instr_time io_start; + instr_time io_end; + bool track_stat_time; + + track_stat_time = entry->tag.handler == SYNC_HANDLER_MD && + track_io_timing; + INSTR_TIME_SET_CURRENT(io_start); + pgaio_wref_wait(&entry->iow); + INSTR_TIME_SET_CURRENT(io_end); + + /* + * The operation itself was counted when it was started. Add only + * time actually spent waiting for relation IO to complete. + */ + if (track_stat_time) + pgstat_count_io_op_time_end(IOOBJECT_RELATION, + IOCONTEXT_NORMAL, IOOP_FSYNC, + io_start, io_end, 0, 0); + + INSTR_TIME_ACCUM_DIFF(entry->io_time, io_end, io_start); + } + + /* + * The raw fsync result (0 on success, -errno on failure) is preserved + * by completion callbacks so we can apply our cancellation/retry + * policy. + */ + result = -entry->ioret.result.result; + } + else + result = entry->open_errno; + + sync_close_file(entry); + io_time = entry->io_time; + + if (!result) + { + if (INSTR_TIME_GT(io_time, sync_state->longest)) + sync_state->longest = io_time; + INSTR_TIME_ADD(sync_state->total_elapsed, io_time); + + sync_state->processed++; + + if (log_checkpoints) + elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f ms", + sync_state->processed, + entry->path, + INSTR_TIME_GET_MILLISEC(io_time)); + + entry->hash_entry->sync_completed = true; + sync_free_entry(entry); + } + else + { + /* + * The request may have been canceled after we started the fsync, e.g. + * because the relation was dropped in the meantime and an intervening + * AbsorbSyncRequests() picked up the cancel message. Since + * mdunlink() queues the "cancel" before actually unlinking, a + * cancellation means the failure is expected and the entry can simply + * be dropped. + * + * The upstream, synchronous code checked this at the top of its retry + * loop; because the fsync is now in flight while requests are being + * absorbed, we have to re-check it here. + */ + if (entry->hash_entry->canceled) + { + entry->hash_entry->sync_completed = true; + sync_free_entry(entry); + return; + } + + /* + * It is possible that the relation has been dropped or truncated + * since the fsync request was entered. Therefore, allow ENOENT, but + * only if we didn't fail already on this file. + */ + errno = result; + if (!FILE_POSSIBLY_DELETED(errno) || entry->retry_count > 0) + { + if (entry->started && entry->ioret.result.status == PGAIO_RS_ERROR) + pgaio_result_report(entry->ioret.result, + &entry->ioret.target_data, + data_sync_elevel(ERROR)); + ereport(data_sync_elevel(ERROR), + (errcode_for_file_access(), + errmsg("could not fsync file \"%s\": %m", + entry->path))); + } + else + ereport(DEBUG1, + (errcode_for_file_access(), + errmsg_internal("could not fsync file \"%s\" but retrying: %m", + entry->path))); + + /* Cleanup must not check this already-handled result as a retry. */ + entry->started = false; + entry->open_errno = 0; + entry->retry_count++; + dlist_push_tail(&sync_state->retry, &entry->node); + } +} + +static void +sync_drain_all(SyncState *sync_state) +{ + while (sync_state->inflight_count) + sync_drain_one(sync_state); +} + +/* + * Make room for another fsync using the limit appropriate for its handler. + */ +static void +sync_ensure_room(SyncState *sync_state, const FileTag *tag) +{ + int max_inflight; + + max_inflight = + GetFsyncConcurrencyLimit(syncsw[tag->handler].uses_transient_fd); + while (sync_state->inflight_count >= max_inflight) + sync_drain_one(sync_state); +} + +/* + * Finish requests whose fsyncs have completed. + * + * The main hash scan may only remove the entry it most recently returned, so + * completion processing is deferred until it ends. This second scan can then + * remove each completed entry as the current entry. Recheck the hash entry + * now because requests absorbed since the fsync completed may require it to + * remain for the next checkpoint cycle. + */ +static void +sync_process_completed(void) +{ HASH_SEQ_STATUS hstat; PendingFsyncEntry *entry; - int absorb_counter; - /* Statistics on sync times */ - int processed = 0; - instr_time sync_start, - sync_end, - sync_diff; - uint64 elapsed; - uint64 longest = 0; - uint64 total_elapsed = 0; + hash_seq_init(&hstat, pendingOps); + while ((entry = (PendingFsyncEntry *) hash_seq_search(&hstat)) != NULL) + { + if (!entry->sync_completed) + continue; + + /* + * We are done with this entry, unless a request for it arrived while + * the fsync was in flight. A cancel supersedes any such request, as + * RememberSyncRequest() clears "canceled" when it records a new one. + */ + if (!entry->re_requested || entry->canceled) + { + if (hash_search(pendingOps, &entry->tag, HASH_REMOVE, NULL) == NULL) + elog(ERROR, "pendingOps corrupted"); + } + else + entry->sync_completed = false; + } +} + +/* + * Reissue any fsync requests that previously failed with an ignorable error. + * + * The fsync table could contain requests to fsync segments that have been + * deleted (unlinked) by the time we get to them. Rather than just hoping an + * ENOENT (or EACCES on Windows) error can be ignored, what we do on error is + * absorb pending requests and then retry. Since mdunlink() queues a "cancel" + * message before actually unlinking, the fsync request is guaranteed to be + * marked canceled after the absorb if it really was this case. + */ +static void +sync_process_retries(SyncState *sync_state) +{ + if (dlist_is_empty(&sync_state->retry)) + return; + + AbsorbSyncRequests(); + + while (!dlist_is_empty(&sync_state->retry)) + { + dlist_node *node = dlist_pop_head_node(&sync_state->retry); + InflightSyncEntry *entry = dlist_container(InflightSyncEntry, node, node); + + if (entry->hash_entry->canceled) + { + /* Safe to remove here, the scan has already finished. */ + if (hash_search(pendingOps, &entry->hash_entry->tag, + HASH_REMOVE, NULL) == NULL) + elog(ERROR, "pendingOps corrupted"); + sync_free_entry(entry); + continue; + } + + sync_ensure_room(sync_state, &entry->tag); + sync_start_one(sync_state, entry); + } + + sync_drain_all(sync_state); + sync_process_completed(); +} + +/* + * Process queued fsync requests. The public wrapper ensures that any error + * closes files owned by in-flight entries. + */ +static void +ProcessSyncRequestsInternal(void) +{ + static bool sync_in_progress = false; + + HASH_SEQ_STATUS hstat; + PendingFsyncEntry *entry; + SyncState sync_state; /* * This is only called during checkpoints, and checkpoints should only @@ -350,6 +761,7 @@ ProcessSyncRequests(void) while ((entry = (PendingFsyncEntry *) hash_seq_search(&hstat)) != NULL) { entry->cycle_ctr = sync_cycle_ctr; + entry->sync_completed = false; } } @@ -359,17 +771,27 @@ ProcessSyncRequests(void) /* Set flag to detect failure if we don't reach the end of the loop */ sync_in_progress = true; + /* + * The limit for each request depends on whether its handler holds a + * transient descriptor until completion. + */ + dlist_init(&sync_state.inflight); + dlist_init(&sync_state.retry); + sync_state.inflight_count = 0; + sync_state.processed = 0; + INSTR_TIME_SET_ZERO(sync_state.longest); + INSTR_TIME_SET_ZERO(sync_state.total_elapsed); + + Assert(dlist_is_empty(&activeSyncEntries)); + MemoryContextReset(inflightSyncCxt); + /* Now scan the hashtable for fsync requests to process */ - absorb_counter = FSYNCS_PER_ABSORB; + sync_state.absorb_counter = FSYNCS_PER_ABSORB; hash_seq_init(&hstat, pendingOps); while ((entry = (PendingFsyncEntry *) hash_seq_search(&hstat)) != NULL) { - int failures; - /* - * If the entry is new then don't process it this time; it is new. - * Note "continue" bypasses the hash-remove call at the bottom of the - * loop. + * Leave requests added in this cycle for the next checkpoint. */ if (entry->cycle_ctr == sync_cycle_ctr) continue; @@ -378,103 +800,92 @@ ProcessSyncRequests(void) Assert((CycleCtr) (entry->cycle_ctr + 1) == sync_cycle_ctr); /* - * If fsync is off then we don't have to bother opening the file at - * all. (We delay checking until this point so that changing fsync on - * the fly behaves sensibly.) + * If in checkpointer, we want to absorb pending requests every so + * often to prevent overflow of the fsync request queue. It is + * unspecified whether newly-added entries will be visited by + * hash_seq_search, but we don't care since we don't need to process + * them anyway. */ - if (enableFsync) + if (enableFsync && --sync_state.absorb_counter <= 0) { - /* - * If in checkpointer, we want to absorb pending requests every so - * often to prevent overflow of the fsync request queue. It is - * unspecified whether newly-added entries will be visited by - * hash_seq_search, but we don't care since we don't need to - * process them anyway. - */ - if (--absorb_counter <= 0) - { - AbsorbSyncRequests(); - absorb_counter = FSYNCS_PER_ABSORB; - } + AbsorbSyncRequests(); + sync_state.absorb_counter = FSYNCS_PER_ABSORB; + } + + if (!enableFsync || entry->canceled) + { + /* We are done with this entry, remove it */ + if (hash_search(pendingOps, &entry->tag, HASH_REMOVE, NULL) == NULL) + elog(ERROR, "pendingOps corrupted"); + } + else + { + InflightSyncEntry *inflight_entry; + + sync_ensure_room(&sync_state, &entry->tag); /* - * The fsync table could contain requests to fsync segments that - * have been deleted (unlinked) by the time we get to them. Rather - * than just hoping an ENOENT (or EACCES on Windows) error can be - * ignored, what we do on error is absorb pending requests and - * then retry. Since mdunlink() queues a "cancel" message before - * actually unlinking, the fsync request is guaranteed to be - * marked canceled after the absorb if it really was this case. - * DROP DATABASE likewise has to tell us to forget fsync requests - * before it starts deletions. + * Mark the entry as already dealt with in this cycle. It must + * remain in the hash table until its fsync completes and the scan + * ends. If a new request arrives meanwhile, this cycle counter + * leaves the entry to be processed by the next checkpoint. */ - for (failures = 0; !entry->canceled; failures++) - { - char path[MAXPGPATH]; - - INSTR_TIME_SET_CURRENT(sync_start); - if (syncsw[entry->tag.handler].sync_syncfiletag(&entry->tag, - path) == 0) - { - /* Success; update statistics about sync timing */ - INSTR_TIME_SET_CURRENT(sync_end); - sync_diff = sync_end; - INSTR_TIME_SUBTRACT(sync_diff, sync_start); - elapsed = INSTR_TIME_GET_MICROSEC(sync_diff); - if (elapsed > longest) - longest = elapsed; - total_elapsed += elapsed; - processed++; - - if (log_checkpoints) - elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f ms", - processed, - path, - (double) elapsed / 1000); - - break; /* out of retry loop */ - } - - /* - * It is possible that the relation has been dropped or - * truncated since the fsync request was entered. Therefore, - * allow ENOENT, but only if we didn't fail already on this - * file. - */ - if (!FILE_POSSIBLY_DELETED(errno) || failures > 0) - ereport(data_sync_elevel(ERROR), - (errcode_for_file_access(), - errmsg("could not fsync file \"%s\": %m", - path))); - else - ereport(DEBUG1, - (errcode_for_file_access(), - errmsg_internal("could not fsync file \"%s\" but retrying: %m", - path))); - - /* - * Absorb incoming requests and check to see if a cancel - * arrived for this relation fork. - */ - AbsorbSyncRequests(); - absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */ - } /* end retry loop */ + entry->cycle_ctr = sync_cycle_ctr; + + inflight_entry = MemoryContextAllocZero(inflightSyncCxt, + sizeof(InflightSyncEntry)); + inflight_entry->tag = entry->tag; + inflight_entry->hash_entry = entry; + dlist_push_tail(&activeSyncEntries, + &inflight_entry->cleanup_node); + + sync_start_one(&sync_state, inflight_entry); } + } - /* We are done with this entry, remove it */ - if (hash_search(pendingOps, &entry->tag, HASH_REMOVE, NULL) == NULL) - elog(ERROR, "pendingOps corrupted"); - } /* end loop over hashtable entries */ + sync_drain_all(&sync_state); + sync_process_completed(); + + /* + * A second failure raises an error, so normally one retry pass is enough. + * Keep an explicit bound in case that changes. + */ + for (int failures = 0; failures < 5; failures++) + { + if (dlist_is_empty(&sync_state.retry)) + break; + + sync_process_retries(&sync_state); + } + + if (!dlist_is_empty(&sync_state.inflight) || + !dlist_is_empty(&sync_state.retry)) + elog(PANIC, "in-flight sync requests remain after ProcessSyncRequests"); /* Return sync performance metrics for report at checkpoint end */ - CheckpointStats.ckpt_sync_rels = processed; - CheckpointStats.ckpt_longest_sync = longest; - CheckpointStats.ckpt_agg_sync_time = total_elapsed; + CheckpointStats.ckpt_sync_rels = sync_state.processed; + CheckpointStats.ckpt_longest_sync = INSTR_TIME_GET_MICROSEC(sync_state.longest); + CheckpointStats.ckpt_agg_sync_time = INSTR_TIME_GET_MICROSEC(sync_state.total_elapsed); /* Flag successful completion of ProcessSyncRequests */ sync_in_progress = false; } +/* + * ProcessSyncRequests() -- Process queued fsync requests. + */ +void +ProcessSyncRequests(void) +{ + PG_ENSURE_ERROR_CLEANUP(sync_cleanup_inflight, (Datum) 0); + { + ProcessSyncRequestsInternal(); + } + PG_END_ENSURE_ERROR_CLEANUP(sync_cleanup_inflight, (Datum) 0); + + Assert(dlist_is_empty(&activeSyncEntries)); +} + /* * RememberSyncRequest() -- callback from checkpointer side of sync request * @@ -554,11 +965,20 @@ RememberSyncRequest(const FileTag *ftag, SyncRequestType type) ftag, HASH_ENTER, &found); + + /* + * If an entry already existed, an fsync for it may be in flight right + * now, in which case it cannot be assumed to cover this request; see + * sync_drain_one(). + */ + entry->re_requested = found; + /* if new entry, or was previously canceled, initialize it */ if (!found || entry->canceled) { entry->cycle_ctr = sync_cycle_ctr; entry->canceled = false; + entry->sync_completed = false; } /* diff --git a/src/backend/utils/activity/pgstat_io.c b/src/backend/utils/activity/pgstat_io.c index 8ec1aad5078..761847fac05 100644 --- a/src/backend/utils/activity/pgstat_io.c +++ b/src/backend/utils/activity/pgstat_io.c @@ -99,6 +99,26 @@ pgstat_prepare_io_time(bool track_io_guc) return io_start; } +/* + * Like pgstat_count_io_op_time_end() except IO end time is not supplied, it + * is calculated inside of the function. + */ +void +pgstat_count_io_op_time(IOObject io_object, IOContext io_context, IOOp io_op, + instr_time start_time, uint32 cnt, uint64 bytes) +{ + if (!INSTR_TIME_IS_ZERO(start_time)) + { + instr_time cur_time; + + INSTR_TIME_SET_CURRENT(cur_time); + pgstat_count_io_op_time_end(io_object, io_context, io_op, + start_time, cur_time, cnt, bytes); + } + else + pgstat_count_io_op(io_object, io_context, io_op, cnt, bytes); +} + /* * Like pgstat_count_io_op() except it also accumulates time. * @@ -111,42 +131,41 @@ pgstat_prepare_io_time(bool track_io_guc) * activity of temporary blocks, so these are ignored here. */ void -pgstat_count_io_op_time(IOObject io_object, IOContext io_context, IOOp io_op, - instr_time start_time, uint32 cnt, uint64 bytes) +pgstat_count_io_op_time_end(IOObject io_object, IOContext io_context, IOOp io_op, + instr_time start_time, instr_time end_time, uint32 cnt, + uint64 bytes) { if (!INSTR_TIME_IS_ZERO(start_time)) { - instr_time io_time; - - INSTR_TIME_SET_CURRENT(io_time); - INSTR_TIME_SUBTRACT(io_time, start_time); + Assert(!INSTR_TIME_GT(start_time, end_time)); + INSTR_TIME_SUBTRACT(end_time, start_time); if (io_object != IOOBJECT_WAL) { if (io_op == IOOP_WRITE || io_op == IOOP_EXTEND) { - pgstat_count_buffer_write_time(INSTR_TIME_GET_MICROSEC(io_time)); + pgstat_count_buffer_write_time(INSTR_TIME_GET_MICROSEC(end_time)); if (io_object == IOOBJECT_RELATION) - INSTR_TIME_ADD(pgBufferUsage.shared_blk_write_time, io_time); + INSTR_TIME_ADD(pgBufferUsage.shared_blk_write_time, end_time); else if (io_object == IOOBJECT_TEMP_RELATION) - INSTR_TIME_ADD(pgBufferUsage.local_blk_write_time, io_time); + INSTR_TIME_ADD(pgBufferUsage.local_blk_write_time, end_time); } else if (io_op == IOOP_READ) { - pgstat_count_buffer_read_time(INSTR_TIME_GET_MICROSEC(io_time)); + pgstat_count_buffer_read_time(INSTR_TIME_GET_MICROSEC(end_time)); if (io_object == IOOBJECT_RELATION) - INSTR_TIME_ADD(pgBufferUsage.shared_blk_read_time, io_time); + INSTR_TIME_ADD(pgBufferUsage.shared_blk_read_time, end_time); else if (io_object == IOOBJECT_TEMP_RELATION) - INSTR_TIME_ADD(pgBufferUsage.local_blk_read_time, io_time); + INSTR_TIME_ADD(pgBufferUsage.local_blk_read_time, end_time); } } INSTR_TIME_ADD(PendingIOStats.pending_times[io_object][io_context][io_op], - io_time); + end_time); /* Add the per-backend count */ pgstat_count_backend_io_op_time(io_object, io_context, io_op, - io_time); + end_time); } pgstat_count_io_op(io_object, io_context, io_op, cnt, bytes); diff --git a/src/include/access/clog.h b/src/include/access/clog.h index 7894998c763..e089106f7fe 100644 --- a/src/include/access/clog.h +++ b/src/include/access/clog.h @@ -47,7 +47,7 @@ extern void CheckPointCLOG(void); extern void ExtendCLOG(TransactionId newestXact); extern void TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid); -extern int clogsyncfiletag(const FileTag *ftag, char *path); +extern void clogsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); /* XLOG stuff */ #define CLOG_ZEROPAGE 0x00 diff --git a/src/include/access/commit_ts.h b/src/include/access/commit_ts.h index 825ccda90ed..fa4880e0d03 100644 --- a/src/include/access/commit_ts.h +++ b/src/include/access/commit_ts.h @@ -38,7 +38,7 @@ extern void SetCommitTsLimit(TransactionId oldestXact, TransactionId newestXact); extern void AdvanceOldestCommitTsXid(TransactionId oldestXact); -extern int committssyncfiletag(const FileTag *ftag, char *path); +extern void committssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); /* XLOG stuff */ #define COMMIT_TS_ZEROPAGE 0x00 diff --git a/src/include/access/multixact.h b/src/include/access/multixact.h index 97df1d805af..b1f3594761c 100644 --- a/src/include/access/multixact.h +++ b/src/include/access/multixact.h @@ -139,8 +139,8 @@ extern void GetMultiXactInfo(uint32 *multixacts, MultiXactOffset *nextOffset, MultiXactId *oldestMultiXactId, MultiXactOffset *oldestOffset); -extern int multixactoffsetssyncfiletag(const FileTag *ftag, char *path); -extern int multixactmemberssyncfiletag(const FileTag *ftag, char *path); +extern void multixactoffsetssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern void multixactmemberssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); extern void AtEOXact_MultiXact(void); extern void AtPrepare_MultiXact(void); diff --git a/src/include/access/slru.h b/src/include/access/slru.h index b4adb1789c7..0e91df5609c 100644 --- a/src/include/access/slru.h +++ b/src/include/access/slru.h @@ -240,7 +240,7 @@ typedef bool (*SlruScanCallback) (SlruDesc *ctl, char *filename, int64 segpage, extern bool SlruScanDirectory(SlruDesc *ctl, SlruScanCallback callback, void *data); extern void SlruDeleteSegment(SlruDesc *ctl, int64 segno); -extern int SlruSyncFileTag(SlruDesc *ctl, const FileTag *ftag, char *path); +extern void SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, struct InflightSyncEntry *entry); /* SlruScanDirectory public callbacks */ extern bool SlruScanDirCbReportPresence(SlruDesc *ctl, char *filename, diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 187d82c96fe..8c91aa4ef85 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -703,6 +703,10 @@ extern instr_time pgstat_prepare_io_time(bool track_io_guc); extern void pgstat_count_io_op_time(IOObject io_object, IOContext io_context, IOOp io_op, instr_time start_time, uint32 cnt, uint64 bytes); +extern void pgstat_count_io_op_time_end(IOObject io_object, IOContext io_context, + IOOp io_op, instr_time start_time, + instr_time end_time, uint32 cnt, + uint64 bytes); extern PgStat_IO *pgstat_fetch_stat_io(void); extern const char *pgstat_get_io_context_name(IOContext io_context); diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index 01f0f8ccccf..05ff261a41c 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -178,6 +178,12 @@ struct PgAioTargetInfo */ int (*reopen) (PgAioHandle *ioh); + /* + * Optional counterpart to reopen, releasing the file descriptor it + * acquired once the IO has been executed. + */ + void (*close) (PgAioHandle *ioh); + /* describe the target of the IO, used for log messages and views */ char *(*describe_identity) (const PgAioTargetData *sd); @@ -209,6 +215,7 @@ typedef enum PgAioHandleCallbackID PGAIO_HCB_INVALID = 0, PGAIO_HCB_MD_READV, + PGAIO_HCB_MD_FSYNC, PGAIO_HCB_SHARED_BUFFER_READV, diff --git a/src/include/storage/aio_internal.h b/src/include/storage/aio_internal.h index 35d4f3f310d..ccf0fe4c7bf 100644 --- a/src/include/storage/aio_internal.h +++ b/src/include/storage/aio_internal.h @@ -360,6 +360,7 @@ extern int pgaio_io_get_iovec_length(PgAioHandle *ioh, struct iovec **iov); /* aio_target.c */ extern bool pgaio_io_can_reopen(PgAioHandle *ioh); extern int pgaio_io_reopen(PgAioHandle *ioh); +extern void pgaio_io_close_reopened(PgAioHandle *ioh); extern const char *pgaio_io_get_target_name(PgAioHandle *ioh); diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h index c20b74cd9c3..8010f33ad77 100644 --- a/src/include/storage/fd.h +++ b/src/include/storage/fd.h @@ -138,6 +138,7 @@ extern int FilePrefetch(File file, pgoff_t offset, pgoff_t amount, uint32 wait_e extern ssize_t FileReadV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info); extern ssize_t FileWriteV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info); extern int FileStartReadV(struct PgAioHandle *ioh, File file, int iovcnt, pgoff_t offset, uint32 wait_event_info); +extern int FileStartSync(struct PgAioHandle *ioh, File file, bool datasync, uint32 wait_event_info); extern int FileSync(File file, uint32 wait_event_info); extern int FileZero(File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info); extern int FileFallocate(File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info); @@ -221,7 +222,7 @@ extern int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int extern int durable_rename(const char *oldfile, const char *newfile, int elevel); extern int durable_unlink(const char *fname, int elevel); extern void SyncDataDirectory(void); -extern int GetFsyncConcurrencyLimit(void); +extern int GetFsyncConcurrencyLimit(bool uses_transient_fd); extern int data_sync_elevel(int elevel); static inline ssize_t diff --git a/src/include/storage/md.h b/src/include/storage/md.h index b8d10329eb8..c3ff4fa7c16 100644 --- a/src/include/storage/md.h +++ b/src/include/storage/md.h @@ -21,6 +21,7 @@ #include "storage/sync.h" extern PGDLLIMPORT const PgAioHandleCallbacks aio_md_readv_cb; +extern PGDLLIMPORT const PgAioHandleCallbacks aio_md_fsync_cb; /* md storage manager functionality */ extern void mdinit(void); @@ -53,12 +54,13 @@ extern void mdtruncate(SMgrRelation reln, ForkNumber forknum, extern void mdimmedsync(SMgrRelation reln, ForkNumber forknum); extern void mdregistersync(SMgrRelation reln, ForkNumber forknum); extern int mdfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, uint32 *off); +extern int mdfsyncfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum); extern void ForgetDatabaseSyncRequests(Oid dbid); extern void DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo); /* md sync callbacks */ -extern int mdsyncfiletag(const FileTag *ftag, char *path); +extern void mdsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); extern int mdunlinkfiletag(const FileTag *ftag, char *path); extern bool mdfiletagmatches(const FileTag *ftag, const FileTag *candidate); diff --git a/src/include/storage/sync.h b/src/include/storage/sync.h index 88290500bc9..8d48151730f 100644 --- a/src/include/storage/sync.h +++ b/src/include/storage/sync.h @@ -13,6 +13,9 @@ #ifndef SYNC_H #define SYNC_H +#include "lib/ilist.h" +#include "portability/instr_time.h" +#include "storage/aio_types.h" #include "storage/relfilelocator.h" /* @@ -55,6 +58,58 @@ typedef struct FileTag uint64 segno; } FileTag; +struct PendingFsyncEntry; +struct PgAioHandle; + +/* + * How the file opened by a sync handler must be closed once its asynchronous + * fsync has completed. + */ +typedef enum SyncFileCloseMethod +{ + SYNC_CLOSE_NONE = 0, /* nothing to close */ + SYNC_CLOSE_TRANSIENT, /* CloseTransientFile(close_file) */ + SYNC_CLOSE_VFD, /* FileClose((File) close_file) */ +} SyncFileCloseMethod; + +/* + * State for a single in-flight asynchronous fsync request. A sync handler + * opens the file to be synced, fills in the fields it is responsible for, and + * starts an asynchronous fsync on the AIO handle it is given. + */ +typedef struct InflightSyncEntry +{ + FileTag tag; /* identifies handler and file */ + + char path[MAXPGPATH]; + + /* + * Set by the handler: whether it started an asynchronous fsync on the + * passed-in AIO handle. If the file could not be opened, the handler + * sets started = false and open_errno to the errno of the failed open. + */ + bool started; + int open_errno; + + /* set by the handler: how to close the opened file after completion */ + SyncFileCloseMethod close_method; + int close_file; /* fd, or File, depending on close_method */ + + struct PendingFsyncEntry *hash_entry; + + int retry_count; + instr_time io_time; /* time spent starting and waiting */ + + PgAioReturn ioret; + PgAioWaitRef iow; + + /* membership in the inflight / retry lists */ + dlist_node node; + + /* membership in the error-cleanup list */ + dlist_node cleanup_node; +} InflightSyncEntry; + extern void InitSync(void); extern void SyncPreCheckpoint(void); extern void SyncPostCheckpoint(void); diff --git a/src/test/modules/test_slru/test_slru.c b/src/test/modules/test_slru/test_slru.c index 40efffdbf62..ccac09a9285 100644 --- a/src/test/modules/test_slru/test_slru.c +++ b/src/test/modules/test_slru/test_slru.c @@ -17,10 +17,13 @@ #include "access/slru.h" #include "access/transam.h" #include "miscadmin.h" +#include "storage/aio.h" #include "storage/fd.h" #include "storage/ipc.h" #include "storage/shmem.h" +#include "storage/sync.h" #include "utils/builtins.h" +#include "utils/resowner.h" PG_MODULE_MAGIC; @@ -152,15 +155,47 @@ Datum test_slru_page_sync(PG_FUNCTION_ARGS) { int64 pageno = PG_GETARG_INT64(0); - FileTag ftag; - char path[MAXPGPATH]; + InflightSyncEntry entry = {0}; + PgAioHandle *ioh; + int result; /* note that this flushes the full file a segment is located in */ - ftag.segno = pageno / SLRU_PAGES_PER_SEGMENT; - SlruSyncFileTag(TestSlruCtl, &ftag, path); + entry.tag.segno = pageno / SLRU_PAGES_PER_SEGMENT; + + /* + * SlruSyncFileTag() now performs the fsync asynchronously. Drive it the + * same way sync.c does: acquire an AIO handle, let the handler start the + * fsync, wait for its completion and close the file it opened. + */ + ioh = pgaio_io_acquire(CurrentResourceOwner, &entry.ioret); + pgaio_io_get_wref(ioh, &entry.iow); + + HOLD_INTERRUPTS(); + SlruSyncFileTag(TestSlruCtl, ioh, &entry); + RESUME_INTERRUPTS(); + + if (entry.started) + { + pgaio_wref_wait(&entry.iow); + result = -entry.ioret.result.result; + CloseTransientFile(entry.close_file); + } + else + { + pgaio_io_release(ioh); + result = entry.open_errno; + } + + if (result != 0) + { + errno = result; + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not fsync file \"%s\": %m", entry.path))); + } elog(NOTICE, "Called SlruSyncFileTag() for segment %" PRIu64 " on path %s", - ftag.segno, path); + entry.tag.segno, entry.path); PG_RETURN_VOID(); } diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 4a05abff273..4fef7675f2f 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -1338,6 +1338,7 @@ IndexVacuumInfo IndxInfo InferClause InferenceElem +InflightSyncEntry InfoItem InhInfo InheritableSocket @@ -3050,12 +3051,14 @@ SupportRequestSimplify SupportRequestSimplifyAggref SupportRequestWFuncMonotonic Syn +SyncFileCloseMethod SyncOps SyncRepConfigData SyncRepStandbyData SyncRequestHandler SyncRequestType SyncStandbySlotsConfigData +SyncState SyncingRelationsState SysCacheIdentifier SysFKRelationship -- 2.47.3
v3-0007-aio-Allow-IO-workers-to-execute-SLRU-fsyncs.patch (text/x-patch, 17.7K) download From 8236203f5678b618a3bdc327d3e0c4f2dfbf10ad Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Tue, 25 Aug 2026 15:00:40 +0300 Subject: [PATCH v3 7/8] aio: Allow IO workers to execute SLRU fsyncs The SLRU fsyncs introduced by the preceding commit use the generic PGAIO_TID_SYNC target. It does not store paths in shared memory, so I/O workers cannot reopen the files and the checkpointer must perform the operations itself. Add PGAIO_TID_SYNC_FILETAG, which identifies a file by the FileTag registered with sync.c. A FileTag contains enough information to reopen the file in another process. Dispatch reopening through an optional SyncOps callback, implemented for SLRUs using the new SlruOpenFileTag(). SLRUs that are not registered with sync.c continue to use PGAIO_TID_SYNC. Define the shared FileTag representation in storage/aio_types.h so PgAioTargetData can store it directly without duplicating its layout. Describe the target using the SLRU name and segment number, and return worker-side open failures to the checkpointer as negative errno values. Like relation fsyncs, the FileTag target opens a transient descriptor for each operation. Use the existing PgAioTargetInfo close callback to release it after execution, and document that the callback runs in a critical section. SLRU_FLUSH_SYNC is now reported by the I/O worker rather than the checkpointer, as for relation fsyncs. SyncDataDirectory() continues to use PGAIO_TID_SYNC because its files have no FileTag. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- src/backend/access/transam/clog.c | 8 +- src/backend/access/transam/commit_ts.c | 8 +- src/backend/access/transam/multixact.c | 16 +++- src/backend/access/transam/slru.c | 32 ++++++- src/backend/storage/aio/aio_target.c | 2 + src/backend/storage/sync/sync.c | 123 ++++++++++++++++++++++++- src/include/access/clog.h | 1 + src/include/access/commit_ts.h | 1 + src/include/access/multixact.h | 2 + src/include/access/slru.h | 1 + src/include/storage/aio.h | 9 +- src/include/storage/aio_types.h | 14 +++ src/include/storage/sync.h | 19 ++-- src/tools/pgindent/typedefs.list | 1 + 14 files changed, 213 insertions(+), 24 deletions(-) diff --git a/src/backend/access/transam/clog.c b/src/backend/access/transam/clog.c index 89fb77ea5da..0fe0491d877 100644 --- a/src/backend/access/transam/clog.c +++ b/src/backend/access/transam/clog.c @@ -1115,10 +1115,16 @@ clog_redo(XLogReaderState *record) } /* - * Entrypoint for sync.c to sync clog files. + * Entrypoints for sync.c to sync and reopen clog files. */ void clogsyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { SlruSyncFileTag(XactCtl, ioh, entry); } + +int +clogopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(XactCtl, ftag); +} diff --git a/src/backend/access/transam/commit_ts.c b/src/backend/access/transam/commit_ts.c index 7cbbad383b2..4bb95e415ac 100644 --- a/src/backend/access/transam/commit_ts.c +++ b/src/backend/access/transam/commit_ts.c @@ -1026,10 +1026,16 @@ commit_ts_redo(XLogReaderState *record) } /* - * Entrypoint for sync.c to sync commit_ts files. + * Entrypoints for sync.c to sync and reopen commit_ts files. */ void committssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { SlruSyncFileTag(CommitTsCtl, ioh, entry); } + +int +committsopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(CommitTsCtl, ftag); +} diff --git a/src/backend/access/transam/multixact.c b/src/backend/access/transam/multixact.c index 1166e2a2114..188af32efc6 100644 --- a/src/backend/access/transam/multixact.c +++ b/src/backend/access/transam/multixact.c @@ -2973,7 +2973,7 @@ multixact_redo(XLogReaderState *record) } /* - * Entrypoint for sync.c to sync offsets files. + * Entrypoints for sync.c to sync and reopen offsets files. */ void multixactoffsetssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) @@ -2981,11 +2981,23 @@ multixactoffsetssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) SlruSyncFileTag(MultiXactOffsetCtl, ioh, entry); } +int +multixactoffsetsopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(MultiXactOffsetCtl, ftag); +} + /* - * Entrypoint for sync.c to sync members files. + * Entrypoints for sync.c to sync and reopen members files. */ void multixactmemberssyncfiletag(struct PgAioHandle *ioh, InflightSyncEntry *entry) { SlruSyncFileTag(MultiXactMemberCtl, ioh, entry); } + +int +multixactmembersopenfiletag(const FileTag *ftag) +{ + return SlruOpenFileTag(MultiXactMemberCtl, ftag); +} diff --git a/src/backend/access/transam/slru.c b/src/backend/access/transam/slru.c index b1e513ac3b6..058a58baa52 100644 --- a/src/backend/access/transam/slru.c +++ b/src/backend/access/transam/slru.c @@ -1897,11 +1897,16 @@ SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, InflightSyncEntry *entry } /* - * Use the generic sync target. SLRU segments are not smgr relations and - * cannot be reopened from a FileTag in another process, so this fsync - * will run synchronously in worker mode. + * If this SLRU is registered with sync.c, identify the file by its + * FileTag, so that the fsync can be executed by an IO worker, which will + * reopen the file with SlruOpenFileTag(). Otherwise there is no handler + * to reopen the file through, so use the generic sync target, whose IOs + * cannot be handed off to a worker. */ - pgaio_io_set_target(ioh, PGAIO_TID_SYNC); + if (ctl->options.sync_handler != SYNC_HANDLER_NONE) + pgaio_io_set_target_sync_filetag(ioh, &entry->tag); + else + pgaio_io_set_target(ioh, PGAIO_TID_SYNC); /* Start the asynchronous fsync; the fd is closed once it completes. */ pgaio_io_start_fsync(ioh, fd, false, WAIT_EVENT_SLRU_FLUSH_SYNC); @@ -1910,3 +1915,22 @@ SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, InflightSyncEntry *entry entry->close_method = SYNC_CLOSE_TRANSIENT; entry->close_file = fd; } + +/* + * Counterpart to SlruSyncFileTag(), opening the segment identified by ftag in + * a process that did not stage the IO. As with SlruSyncFileTag(), individual + * SLRUs have to provide the handler function, so that the correct SlruDesc + * is used. + * + * Returns a file descriptor opened with OpenTransientFile(), or -1 with errno + * set. + */ +int +SlruOpenFileTag(SlruDesc *ctl, const FileTag *ftag) +{ + char path[MAXPGPATH]; + + SlruFileName(ctl, path, ftag->segno); + + return OpenTransientFile(path, O_RDWR | PG_BINARY); +} diff --git a/src/backend/storage/aio/aio_target.c b/src/backend/storage/aio/aio_target.c index 534382b423b..a62c194c8f2 100644 --- a/src/backend/storage/aio/aio_target.c +++ b/src/backend/storage/aio/aio_target.c @@ -17,6 +17,7 @@ #include "storage/aio.h" #include "storage/aio_internal.h" #include "storage/smgr.h" +#include "storage/sync.h" static char *pgaio_sync_describe_identity(const PgAioTargetData *sd); @@ -39,6 +40,7 @@ static const PgAioTargetInfo *pgaio_target_info[] = { }, [PGAIO_TID_SMGR] = &aio_smgr_target_info, [PGAIO_TID_SYNC] = &aio_sync_target_info, + [PGAIO_TID_SYNC_FILETAG] = &aio_sync_filetag_target_info, }; /* diff --git a/src/backend/storage/sync/sync.c b/src/backend/storage/sync/sync.c index c40c79258a2..f8049b9f48b 100644 --- a/src/backend/storage/sync/sync.c +++ b/src/backend/storage/sync/sync.c @@ -132,10 +132,20 @@ static CycleCtr checkpoint_cycle_ctr = 0; typedef struct SyncOps { void (*sync_syncfiletag) (PgAioHandle *ioh, InflightSyncEntry *entry); + + /* + * Optional. Reopen the file identified by ftag, so that an fsync started + * by sync_syncfiletag() can be executed in a different process, e.g. an + * IO worker. Returns a file descriptor opened with OpenTransientFile(), + * or -1 with errno set. Handlers that provide this must use the + * PGAIO_TID_SYNC_FILETAG target (see pgaio_io_set_target_sync_filetag()). + */ + int (*sync_openfiletag) (const FileTag *ftag); int (*sync_unlinkfiletag) (const FileTag *ftag, char *path); bool (*sync_filetagmatches) (const FileTag *ftag, const FileTag *candidate); bool uses_transient_fd; + const char *sync_target_name; } SyncOps; /* @@ -152,25 +162,130 @@ static const SyncOps syncsw[] = { /* pg_xact */ [SYNC_HANDLER_CLOG] = { .sync_syncfiletag = clogsyncfiletag, - .uses_transient_fd = true + .sync_openfiletag = clogopenfiletag, + .uses_transient_fd = true, + .sync_target_name = "pg_xact" }, /* pg_commit_ts */ [SYNC_HANDLER_COMMIT_TS] = { .sync_syncfiletag = committssyncfiletag, - .uses_transient_fd = true + .sync_openfiletag = committsopenfiletag, + .uses_transient_fd = true, + .sync_target_name = "pg_commit_ts" }, /* pg_multixact/offsets */ [SYNC_HANDLER_MULTIXACT_OFFSET] = { .sync_syncfiletag = multixactoffsetssyncfiletag, - .uses_transient_fd = true + .sync_openfiletag = multixactoffsetsopenfiletag, + .uses_transient_fd = true, + .sync_target_name = "pg_multixact/offsets" }, /* pg_multixact/members */ [SYNC_HANDLER_MULTIXACT_MEMBER] = { .sync_syncfiletag = multixactmemberssyncfiletag, - .uses_transient_fd = true + .sync_openfiletag = multixactmembersopenfiletag, + .uses_transient_fd = true, + .sync_target_name = "pg_multixact/members" } }; +static int sync_aio_reopen(PgAioHandle *ioh); +static void sync_aio_close(PgAioHandle *ioh); +static char *sync_aio_describe_identity(const PgAioTargetData *sd); + +/* + * Target info for files identified by a FileTag (see PGAIO_TID_SYNC_FILETAG). + * Unlike PGAIO_TID_SYNC, a FileTag contains everything needed to find the + * file again in another process, so such IOs can be executed by IO workers. + */ +const PgAioTargetInfo aio_sync_filetag_target_info = { + .name = "sync_filetag", + .reopen = sync_aio_reopen, + .close = sync_aio_close, + .describe_identity = sync_aio_describe_identity, +}; + +/* + * Set up ioh to operate on the file identified by ftag. + */ +void +pgaio_io_set_target_sync_filetag(PgAioHandle *ioh, const FileTag *ftag) +{ + PgAioTargetData *sd = pgaio_io_get_target_data(ioh); + + Assert(syncsw[ftag->handler].sync_openfiletag != NULL); + Assert(syncsw[ftag->handler].sync_target_name != NULL); + + pgaio_io_set_target(ioh, PGAIO_TID_SYNC_FILETAG); + + sd->sync_filetag = *ftag; +} + +static FileTag +sync_aio_filetag(const PgAioTargetData *sd) +{ + return sd->sync_filetag; +} + +/* + * reopen callback for PGAIO_TID_SYNC_FILETAG, to open the file in the process + * executing the IO. + */ +static int +sync_aio_reopen(PgAioHandle *ioh) +{ + PgAioTargetData *sd = pgaio_io_get_target_data(ioh); + PgAioOpData *od = pgaio_io_get_op_data(ioh); + FileTag ftag = sync_aio_filetag(sd); + int fd; + + /* + * The caller needs to prevent interrupts from being processed, otherwise + * the FD could be closed again before we get to executing the IO. + */ + Assert(!INTERRUPTS_CAN_BE_PROCESSED()); + + Assert(pgaio_io_get_op(ioh) == PGAIO_OP_FSYNC); + + fd = syncsw[ftag.handler].sync_openfiletag(&ftag); + if (fd < 0) + return -errno; + + od->fsync.fd = fd; + + return 0; +} + +/* + * close callback for PGAIO_TID_SYNC_FILETAG, releasing the descriptor + * acquired by sync_aio_reopen(). + * + * Called in a critical section after the fsync result has been saved for + * the issuer. Do not report close failures here: this descriptor was only + * used for fsync, and any fsync failure is handled by the issuer. + */ +static void +sync_aio_close(PgAioHandle *ioh) +{ + PgAioOpData *od = pgaio_io_get_op_data(ioh); + + (void) CloseTransientFile(od->fsync.fd); + od->fsync.fd = -1; +} + +/* + * describe_identity callback for PGAIO_TID_SYNC_FILETAG. + */ +static char * +sync_aio_describe_identity(const PgAioTargetData *sd) +{ + FileTag ftag = sync_aio_filetag(sd); + + return psprintf(_("segment " UINT64_FORMAT " of SLRU \"%s\""), + ftag.segno, + syncsw[ftag.handler].sync_target_name); +} + /* * Initialize data structures for the file sync tracking. */ diff --git a/src/include/access/clog.h b/src/include/access/clog.h index e089106f7fe..fc06794d186 100644 --- a/src/include/access/clog.h +++ b/src/include/access/clog.h @@ -48,6 +48,7 @@ extern void ExtendCLOG(TransactionId newestXact); extern void TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid); extern void clogsyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int clogopenfiletag(const FileTag *ftag); /* XLOG stuff */ #define CLOG_ZEROPAGE 0x00 diff --git a/src/include/access/commit_ts.h b/src/include/access/commit_ts.h index fa4880e0d03..ebb87d9534e 100644 --- a/src/include/access/commit_ts.h +++ b/src/include/access/commit_ts.h @@ -39,6 +39,7 @@ extern void SetCommitTsLimit(TransactionId oldestXact, extern void AdvanceOldestCommitTsXid(TransactionId oldestXact); extern void committssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int committsopenfiletag(const FileTag *ftag); /* XLOG stuff */ #define COMMIT_TS_ZEROPAGE 0x00 diff --git a/src/include/access/multixact.h b/src/include/access/multixact.h index b1f3594761c..037437eaae7 100644 --- a/src/include/access/multixact.h +++ b/src/include/access/multixact.h @@ -140,7 +140,9 @@ extern void GetMultiXactInfo(uint32 *multixacts, MultiXactOffset *nextOffset, MultiXactOffset *oldestOffset); extern void multixactoffsetssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int multixactoffsetsopenfiletag(const FileTag *ftag); extern void multixactmemberssyncfiletag(PgAioHandle *ioh, InflightSyncEntry *entry); +extern int multixactmembersopenfiletag(const FileTag *ftag); extern void AtEOXact_MultiXact(void); extern void AtPrepare_MultiXact(void); diff --git a/src/include/access/slru.h b/src/include/access/slru.h index 0e91df5609c..43429392c7d 100644 --- a/src/include/access/slru.h +++ b/src/include/access/slru.h @@ -241,6 +241,7 @@ extern bool SlruScanDirectory(SlruDesc *ctl, SlruScanCallback callback, void *da extern void SlruDeleteSegment(SlruDesc *ctl, int64 segno); extern void SlruSyncFileTag(SlruDesc *ctl, struct PgAioHandle *ioh, struct InflightSyncEntry *entry); +extern int SlruOpenFileTag(SlruDesc *ctl, const FileTag *ftag); /* SlruScanDirectory public callbacks */ extern bool SlruScanDirCbReportPresence(SlruDesc *ctl, char *filename, diff --git a/src/include/storage/aio.h b/src/include/storage/aio.h index 05ff261a41c..fe8349cb429 100644 --- a/src/include/storage/aio.h +++ b/src/include/storage/aio.h @@ -119,9 +119,10 @@ typedef enum PgAioTargetID PGAIO_TID_INVALID = 0, PGAIO_TID_SMGR, PGAIO_TID_SYNC, + PGAIO_TID_SYNC_FILETAG, } PgAioTargetID; -#define PGAIO_TID_COUNT (PGAIO_TID_SYNC + 1) +#define PGAIO_TID_COUNT (PGAIO_TID_SYNC_FILETAG + 1) /* @@ -180,7 +181,11 @@ struct PgAioTargetInfo /* * Optional counterpart to reopen, releasing the file descriptor it - * acquired once the IO has been executed. + * acquired. Called in the process that reopened the IO, after the IO has + * been executed. Targets whose reopen callback reuses a cached + * descriptor do not need this. + * + * This is called in a critical section, so it must not raise errors. */ void (*close) (PgAioHandle *ioh); diff --git a/src/include/storage/aio_types.h b/src/include/storage/aio_types.h index 17b59aeed7c..90bc4c73989 100644 --- a/src/include/storage/aio_types.h +++ b/src/include/storage/aio_types.h @@ -23,6 +23,18 @@ typedef struct PgAioHandle PgAioHandle; typedef struct PgAioHandleCallbacks PgAioHandleCallbacks; typedef struct PgAioTargetInfo PgAioTargetInfo; +/* + * A tag identifying a file handled by sync.c. This is defined here so that + * PgAioTargetData can store it without duplicating its representation. + */ +typedef struct PgAioSyncFileTag +{ + int16 handler; /* SyncRequestHandler value */ + int16 forknum; /* ForkNumber */ + RelFileLocator rlocator; /* physical relation identifier */ + uint64 segno; +} PgAioSyncFileTag; + /* * A reference to an IO that can be used to wait for the IO (using * pgaio_wref_wait()) to complete. @@ -69,6 +81,8 @@ typedef union PgAioTargetData bool is_temp:1; /* proc can be inferred by owning AIO */ bool skip_fsync:1; } smgr; + + PgAioSyncFileTag sync_filetag; } PgAioTargetData; diff --git a/src/include/storage/sync.h b/src/include/storage/sync.h index 8d48151730f..e85c97c2ba4 100644 --- a/src/include/storage/sync.h +++ b/src/include/storage/sync.h @@ -46,17 +46,11 @@ typedef enum SyncRequestHandler } SyncRequestHandler; /* - * A tag identifying a file. Currently it has the members required for md.c's - * usage, but sync.c has no knowledge of the internal structure, and it is - * liable to change as required by future handlers. + * A tag identifying a file. Its representation is shared with AIO target + * data, so changes are automatically visible to processes that reopen files + * on behalf of sync.c. */ -typedef struct FileTag -{ - int16 handler; /* SyncRequestHandler value, saving space */ - int16 forknum; /* ForkNumber, saving space */ - RelFileLocator rlocator; - uint64 segno; -} FileTag; +typedef PgAioSyncFileTag FileTag; struct PendingFsyncEntry; struct PgAioHandle; @@ -118,4 +112,9 @@ extern void RememberSyncRequest(const FileTag *ftag, SyncRequestType type); extern bool RegisterSyncRequest(const FileTag *ftag, SyncRequestType type, bool retryOnError); +/* AIO support */ +extern PGDLLIMPORT const PgAioTargetInfo aio_sync_filetag_target_info; +extern void pgaio_io_set_target_sync_filetag(PgAioHandle *ioh, + const FileTag *ftag); + #endif /* SYNC_H */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 4fef7675f2f..6fcd8dc1f09 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2261,6 +2261,7 @@ PgAioOpData PgAioResult PgAioResultStatus PgAioReturn +PgAioSyncFileTag PgAioTargetData PgAioTargetID PgAioTargetInfo -- 2.47.3
v3-0008-aio-doc-Document-AIO-fsync.patch (text/x-patch, 3.6K) download From 0f85b25415c36c1249faed2c2c3bbe1af3b11de4 Mon Sep 17 00:00:00 2001 From: Nazir Bilal Yavuz <byavuz81@gmail.com> Date: Wed, 30 Sep 2026 10:56:23 +0300 Subject: [PATCH v3 8/8] aio: doc: Document AIO fsync Describe the fsync operation and sync and sync_filetag targets exposed by pg_aios, including the NULL offset and length for synchronization operations. Explain that crash-recovery file synchronization can overlap with io_uring but runs synchronously with the worker method because workers cannot reopen these path-only targets. Distinguish this fallback from relation and SLRU synchronization during checkpoints. Discussion: https://postgr.es/m/CAN55FZ0vLWJQNB%3DHuHXG2wabFjXJd6OWTa3%3DkRzwObdZD9poHQ%40mail.gmail.com --- doc/src/sgml/config.sgml | 10 ++++++++++ doc/src/sgml/system-views.sgml | 21 +++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml index f36fbb60101..9e609a4302d 100644 --- a/doc/src/sgml/config.sgml +++ b/doc/src/sgml/config.sgml @@ -12293,6 +12293,16 @@ dynamic_library_path = '/usr/local/lib/postgresql:$libdir' starting a database cluster that did not shut down cleanly, including copies created with <application>pg_basebackup</application>. </para> + <para> + When this parameter is set to <literal>fsync</literal> and + <xref linkend="guc-io-method"/> is set to <literal>io_uring</literal>, + multiple file synchronization operations can run concurrently. + With <literal>worker</literal> or <literal>sync</literal>, these + operations run synchronously in the startup process. Unlike relation + and SLRU synchronization during checkpoints, data-directory + synchronization does not provide the information needed for I/O + workers to reopen the files. + </para> <para> On Linux, <literal>syncfs</literal> may be used instead, to ask the operating system to synchronize the file systems that contain the diff --git a/doc/src/sgml/system-views.sgml b/doc/src/sgml/system-views.sgml index 77202e2c765..ffe08235fe5 100644 --- a/doc/src/sgml/system-views.sgml +++ b/doc/src/sgml/system-views.sgml @@ -387,6 +387,11 @@ <literal>writev</literal>, a vectored write </para> </listitem> + <listitem> + <para> + <literal>fsync</literal>, file synchronization + </para> + </listitem> </itemizedlist> </para></entry> </row> @@ -396,7 +401,7 @@ <structfield>off</structfield> <type>int8</type> </para> <para> - Offset of the I/O operation. + Offset of the I/O operation, or NULL for <literal>fsync</literal>. </para></entry> </row> @@ -405,7 +410,7 @@ <structfield>length</structfield> <type>int8</type> </para> <para> - Length of the I/O operation. + Length of the I/O operation, or NULL for <literal>fsync</literal>. </para></entry> </row> @@ -421,6 +426,18 @@ <literal>smgr</literal>, I/O on relations </para> </listitem> + <listitem> + <para> + <literal>sync</literal>, file synchronization using a process-local + file descriptor + </para> + </listitem> + <listitem> + <para> + <literal>sync_filetag</literal>, file synchronization identified by + a file tag, currently used for SLRU segments + </para> + </listitem> </itemizedlist> </para></entry> </row> -- 2.47.3
^ permalink raw reply [nested|flat] 9+ messages in thread

* Re: aio: Async fsyncs for crash recovery and checkpointer
@ 2026-09-30 08:43  Nazir Bilal Yavuz <byavuz81@gmail.com>
  parent: Nitin Jadhav <nitinjadhavpostgres@gmail.com>
  0 siblings, 0 replies; 9+ messages in thread

From: Nazir Bilal Yavuz @ 2026-09-30 08:43 UTC (permalink / raw)
  To: Nitin Jadhav <nitinjadhavpostgres@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Andres Freund <andres@anarazel.de>; iamqyh@gmail.com

Hi,

On Tue, 22 Sept 2026 at 18:21, Nitin Jadhav
<nitinjadhavpostgres@gmail.com> wrote:
>
> I found two further points, and the worker-side SLRU test-coverage
> question from v1 still appears applicable.
>
> An I/O worker can skip a required fsync after fsync is enabled. As
> Yuhang noted, there appears to be a race when reloading fsync from off
> to on. pgaio_io_start_fsync()  makes the dispatch decision using the
> issuing process's enableFsync.

You are right, that is fixed in v3 [1]. I used the issuing process's enableFsync


> Worker SMGR cleanup appears dependent on the worker becoming idle.
> Patch 0002 calls smgrdestroyall() only after the worker finds that no
> request is available. This means a continuously busy worker may never
> perform the cleanup. Worker-side relation reopening calls smgropen(),
> and those unpinned SMgrRelation objects remain in the worker's SMGR
> hash until smgrdestroyall() is called. With sustained I/O over many
> distinct relations, a worker whose queue never becomes empty could
> therefore retain an increasing number of SMGR entries, including
> entries for relations that have since been dropped. Would it be safer
> to check FirstCallSinceLastCheckpoint() at a safe point after
> completing each request, before consuming the next request, rather
> than only on the idle path? At that point any descriptor reopened for
> the completed operation has already been released.

We have created another thread for this. Now, we have a dedicated SMGR
entry limits, and the worker can't surpass this limit. For more
information you can look [2], but briefly, SMGR entries can't surpass
this limit when the worker is busy; they are cleaned when we reach
this limit. Also, SMGR entries are cleaned before the worker goes to
idle. These should solve the problem.


> The worker-side SLRU path does not appear to have targeted test
> coverage. The test_slru_page_sync() still registers the test SLRU with
> SYNC_HANDLER_NONE. Consequently, SlruSyncFileTag() selects
> PGAIO_TID_SYNC, which has no reopen callback and is executed
> synchronously in the submitting process under io_method=worker.

Yes, that is not tested. I will add that.

[1] https://postgr.es/m/CAN55FZ2NT6529QhB_dcrZ5LaSL20aayhP33ZisZVFSg2hOqLXg%40mail.gmail.com
[2] https://postgr.es/m/CAN55FZ2BesKUnajdgpw1fPSe3S6_CHOugryaUEtD7vdP%3DdRKEQ%40mail.gmail.com

--
Regards,
Nazir Bilal Yavuz
Microsoft






^ permalink  raw  reply  [nested|flat] 9+ messages in thread


end of thread, other threads:[~2026-09-30 08:43 UTC | newest]

Thread overview: 9+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-08-25 12:48 aio: Async fsyncs for crash recovery and checkpointer Nazir Bilal Yavuz <byavuz81@gmail.com>
2026-08-31 15:19 ` Nitin Jadhav <nitinjadhavpostgres@gmail.com>
2026-09-01 11:50   ` Nazir Bilal Yavuz <byavuz81@gmail.com>
2026-09-03 13:15     ` Yuhang Qiu <iamqyh@gmail.com>
2026-09-18 10:54       ` Nazir Bilal Yavuz <byavuz81@gmail.com>
2026-09-22 04:03         ` Yuhang Qiu <iamqyh@gmail.com>
2026-09-22 15:20           ` Nitin Jadhav <nitinjadhavpostgres@gmail.com>
2026-09-30 08:43             ` Nazir Bilal Yavuz <byavuz81@gmail.com>
2026-09-30 08:42           ` Nazir Bilal Yavuz <byavuz81@gmail.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox