From 9ff64b3e1b3af5b70c054877c26065afb654b4cd Mon Sep 17 00:00:00 2001 From: Dmitry Fomin Date: Sat, 28 Nov 2026 15:14:52 +0100 Subject: [PATCH 1/3] v18 0001: core local wait-event buffer and safe-point drain Add the infrastructure for timing wait events without running any third-party code inside a wait site, and without touching the hot path: pgstat_report_wait_start() and pgstat_report_wait_end() are left exactly as on master in this patch, so it has zero effect on an uninstrumented build. Patch 0002 turns the timing on. A process that wants wait timing enables a small, fixed-size, backend-local ring buffer (wait_event_report_state.buf; the struct is in the new utils/wait_event_timing.h). Core writes one 24-byte record per completed wait into it from fixed C code only -- no hook, no allocation, no lock, no error report. The records are handed to registered consumer callbacks later, at safe points, where a consumer may do anything ordinary backend code may. The buffer carries one opaque uint32 context tag that core copies into each record but never interprets. Delivery model. A finished wait asks for a drain (sets WaitEventDrainPending and InterruptPending) once the buffer passes its high-water mark or the drain interval has elapsed; the timestamp already taken for the record is reused, so there is no extra clock read. The request is served at the next interrupt hub: every per-iteration Process*Interrupts() calls pgstat_drain_wait_events_if_pending(), which drains only at a genuine safe point (InterruptHoldoffCount == 0 && CritSectionCount == 0). The drain wraps the consumer callbacks in PG_TRY/PG_FINALLY, so the buffer is emptied and recording resumes even if a consumer raises an error. A wait-event reporting function must never arm MyLatch: doing so would make the very next WaitLatch() return at once and would distort latch-paced loops (the bgwriter control loop and its hibernation, walwriter pacing, the IO workers' wakeup accounting). So the slow path only raises InterruptPending. A process that does buffered work and then enters a long or unbounded sleep before the next hub would otherwise leave records undelivered for the length of that sleep; such sites drain explicitly just before sleeping, through the same helper: the IO worker idle loop (method_worker.c), the bgwriter hibernation sleep, and the archiver's idle sleep. pgstat_report_wait_end_abort() is added here and used at the ten genuine error-recovery cleanup ends (xact.c, autovacuum.c, auxprocess.c, bgwriter.c, checkpointer.c, pgarch.c, walsummarizer.c, walwriter.c, walsender.c): it clears the reported event and forgets any in-flight timing without appending a record, so the long gap until error unwind is not mistaken for a wait. In this patch the reporting inlines are not yet timed, so this is behavior-neutral. InitPostmasterChild() resets the per-process timing state so a child never inherits the postmaster's buffer or registry. s_lock.c gets stubs so the standalone s_lock_test still links. ABI note: my_wait_event_info is now a macro over wait_event_report_state.info; it was previously an exported PGDLLIMPORT uint32 * symbol. This is a normal major-version ABI change. The usual lvalue use through utils/wait_event.h stays source-compatible, but an out-of-tree extension that hand-declared its own extern uint32 *my_wait_event_info; instead of including the header would no longer link. --- src/backend/access/transam/xact.c | 4 +- src/backend/postmaster/autovacuum.c | 10 +- src/backend/postmaster/auxprocess.c | 2 +- src/backend/postmaster/bgwriter.c | 16 +- src/backend/postmaster/checkpointer.c | 9 +- src/backend/postmaster/interrupt.c | 8 + src/backend/postmaster/pgarch.c | 18 +- src/backend/postmaster/startup.c | 8 + src/backend/postmaster/walsummarizer.c | 10 +- src/backend/postmaster/walwriter.c | 11 +- src/backend/replication/walsender.c | 2 +- src/backend/storage/aio/method_worker.c | 9 + src/backend/storage/lmgr/s_lock.c | 18 +- src/backend/tcop/postgres.c | 8 + src/backend/utils/activity/wait_event.c | 523 +++++++++++++++++++++++- src/backend/utils/init/miscinit.c | 3 + src/include/utils/wait_event.h | 138 ++++++- src/include/utils/wait_event_timing.h | 47 +++ 18 files changed, 829 insertions(+), 15 deletions(-) create mode 100644 src/include/utils/wait_event_timing.h diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c index 1227e3fbe24..97993f5a9e7 100644 --- a/src/backend/access/transam/xact.c +++ b/src/backend/access/transam/xact.c @@ -2898,7 +2898,7 @@ AbortTransaction(void) WaitLSNCleanup(); /* Clear wait information and command progress indicator */ - pgstat_report_wait_end(); + pgstat_report_wait_end_abort(); pgstat_progress_end_command(); pgaio_error_cleanup(); @@ -5342,7 +5342,7 @@ AbortSubTransaction(void) */ WaitLSNCleanup(); - pgstat_report_wait_end(); + pgstat_report_wait_end_abort(); pgstat_progress_end_command(); pgaio_error_cleanup(); diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c index c4c44c9187b..dc34a13fca8 100644 --- a/src/backend/postmaster/autovacuum.c +++ b/src/backend/postmaster/autovacuum.c @@ -501,7 +501,7 @@ AutoVacLauncherMain(const void *startup_data, size_t startup_data_len) * transaction. */ LWLockReleaseAll(); - pgstat_report_wait_end(); + pgstat_report_wait_end_abort(); pgaio_error_cleanup(); UnlockBuffers(); /* this is probably dead code, but let's be safe: */ @@ -817,6 +817,14 @@ ProcessAutoVacLauncherInterrupts(void) /* Process sinval catchup interrupts that happened while sleeping */ ProcessCatchupInterrupt(); + + /* + * Deliver buffered wait event records, if a drain was requested. The + * launcher's main loop has no CHECK_FOR_INTERRUPTS(), so this handler is + * its only per-iteration safe point; without this the buffer would only be + * drained at process exit. + */ + pgstat_drain_wait_events_if_pending(); } /* diff --git a/src/backend/postmaster/auxprocess.c b/src/backend/postmaster/auxprocess.c index ad4bf4bd2a8..ccd590d691e 100644 --- a/src/backend/postmaster/auxprocess.c +++ b/src/backend/postmaster/auxprocess.c @@ -137,5 +137,5 @@ ShutdownAuxiliaryProcess(int code, Datum arg) { LWLockReleaseAll(); ConditionVariableCancelSleep(); - pgstat_report_wait_end(); + pgstat_report_wait_end_abort(); } diff --git a/src/backend/postmaster/bgwriter.c b/src/backend/postmaster/bgwriter.c index d6121f2b4fe..2c71e3c1fa0 100644 --- a/src/backend/postmaster/bgwriter.c +++ b/src/backend/postmaster/bgwriter.c @@ -196,7 +196,7 @@ BackgroundWriterMain(const void *startup_data, size_t startup_data_len) pg_usleep(1000000L); /* Report wait end here, when there is no further possibility of wait */ - pgstat_report_wait_end(); + pgstat_report_wait_end_abort(); } /* We can now handle ereport(ERROR) */ @@ -323,8 +323,22 @@ BackgroundWriterMain(const void *startup_data, size_t startup_data_len) */ if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate) { + /* + * The hibernation sleep can last many times BgWriterDelay, and + * the next ProcessMainLoopInterrupts() is only at the top of the + * loop after it. Deliver any wait records buffered this cycle + * before sleeping so the consumer's view does not go stale for + * the whole hibernation. This is a safe point. + * + * Drain before arming bgwprocno: bgwriter's sigsetjmp handler + * does not call StrategyNotifyBgWriter(-1), so a consumer ERROR + * during the drain while it is armed would leave it armed. + */ + pgstat_drain_wait_events_if_pending(); + /* Ask for notification at next buffer allocation */ StrategyNotifyBgWriter(MyProcNumber); + /* Sleep ... */ (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH, diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c index 96eca76d9f2..48e27fb08bf 100644 --- a/src/backend/postmaster/checkpointer.c +++ b/src/backend/postmaster/checkpointer.c @@ -297,7 +297,7 @@ CheckpointerMain(const void *startup_data, size_t startup_data_len) */ LWLockReleaseAll(); ConditionVariableCancelSleep(); - pgstat_report_wait_end(); + pgstat_report_wait_end_abort(); pgaio_error_cleanup(); UnlockBuffers(); ReleaseAuxProcessResources(false); @@ -684,6 +684,13 @@ ProcessCheckpointerInterrupts(void) /* Perform logging of memory contexts of this process */ if (LogMemoryContextPending) ProcessLogMemoryContextInterrupt(); + + /* + * Deliver buffered wait event records, if a drain was requested. Done + * last, so that a consumer error cannot cause other pending interrupts + * to be missed. + */ + pgstat_drain_wait_events_if_pending(); } /* diff --git a/src/backend/postmaster/interrupt.c b/src/backend/postmaster/interrupt.c index a2c0ff012c5..c62f0a0694d 100644 --- a/src/backend/postmaster/interrupt.c +++ b/src/backend/postmaster/interrupt.c @@ -23,6 +23,7 @@ #include "storage/procsignal.h" #include "utils/guc.h" #include "utils/memutils.h" +#include "utils/wait_event.h" volatile sig_atomic_t ConfigReloadPending = false; volatile sig_atomic_t ShutdownRequestPending = false; @@ -48,6 +49,13 @@ ProcessMainLoopInterrupts(void) /* Perform logging of memory contexts of this process */ if (LogMemoryContextPending) ProcessLogMemoryContextInterrupt(); + + /* + * Deliver buffered wait event records, if a drain was requested. Done + * last, so that a consumer error cannot cause other pending interrupts + * to be missed. + */ + pgstat_drain_wait_events_if_pending(); } /* diff --git a/src/backend/postmaster/pgarch.c b/src/backend/postmaster/pgarch.c index a3fd4f83201..7519613f4c2 100644 --- a/src/backend/postmaster/pgarch.c +++ b/src/backend/postmaster/pgarch.c @@ -356,6 +356,14 @@ pgarch_MainLoop(void) { int rc; + /* + * This sleep can last up to PGARCH_AUTOWAKE_INTERVAL seconds, and + * ProcessPgArchInterrupts() only runs at the top of the loop, + * after it. Deliver any records buffered during the archive + * cycle before sleeping. This is a safe point. + */ + pgstat_drain_wait_events_if_pending(); + rc = WaitLatch(MyLatch, WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH, PGARCH_AUTOWAKE_INTERVAL * 1000L, @@ -568,7 +576,7 @@ pgarch_archiveXlog(char *xlog) disable_all_timeouts(false); LWLockReleaseAll(); ConditionVariableCancelSleep(); - pgstat_report_wait_end(); + pgstat_report_wait_end_abort(); pgaio_error_cleanup(); ReleaseAuxProcessResources(false); AtEOXact_Files(false); @@ -902,6 +910,14 @@ ProcessPgArchInterrupts(void) proc_exit(0); } } + + /* + * Deliver buffered wait event records, if a drain was requested. The + * archiver has no CHECK_FOR_INTERRUPTS() in its loops, so this handler is + * its only per-iteration safe point; without this the buffer would only be + * drained at process exit. + */ + pgstat_drain_wait_events_if_pending(); } /* diff --git a/src/backend/postmaster/startup.c b/src/backend/postmaster/startup.c index 63624e8caa1..aac83a6f295 100644 --- a/src/backend/postmaster/startup.c +++ b/src/backend/postmaster/startup.c @@ -33,6 +33,7 @@ #include "utils/guc.h" #include "utils/memutils.h" #include "utils/timeout.h" +#include "utils/wait_event.h" #ifndef USE_POSTMASTER_DEATH_SIGNAL @@ -192,6 +193,13 @@ ProcessStartupProcInterrupts(void) /* Perform logging of memory contexts of this process */ if (LogMemoryContextPending) ProcessLogMemoryContextInterrupt(); + + /* + * Deliver buffered wait event records, if a drain was requested. Done + * last, so that a consumer error cannot cause other pending interrupts + * to be missed. + */ + pgstat_drain_wait_events_if_pending(); } diff --git a/src/backend/postmaster/walsummarizer.c b/src/backend/postmaster/walsummarizer.c index 4aed794bf51..64eb8a92f75 100644 --- a/src/backend/postmaster/walsummarizer.c +++ b/src/backend/postmaster/walsummarizer.c @@ -293,7 +293,7 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len) /* Release resources we might have acquired. */ LWLockReleaseAll(); ConditionVariableCancelSleep(); - pgstat_report_wait_end(); + pgstat_report_wait_end_abort(); pgaio_error_cleanup(); ReleaseAuxProcessResources(false); AtEOXact_Files(false); @@ -967,6 +967,14 @@ ProcessWalSummarizerInterrupts(void) /* Perform logging of memory contexts of this process */ if (LogMemoryContextPending) ProcessLogMemoryContextInterrupt(); + + /* + * Deliver buffered wait event records, if a drain was requested. The WAL + * summarizer's loops have no CHECK_FOR_INTERRUPTS(), so this handler is its + * only per-iteration safe point; without this the buffer would only be + * drained at process exit. + */ + pgstat_drain_wait_events_if_pending(); } /* diff --git a/src/backend/postmaster/walwriter.c b/src/backend/postmaster/walwriter.c index 55ecaa6277a..6462b3906e7 100644 --- a/src/backend/postmaster/walwriter.c +++ b/src/backend/postmaster/walwriter.c @@ -157,7 +157,7 @@ WalWriterMain(const void *startup_data, size_t startup_data_len) */ LWLockReleaseAll(); ConditionVariableCancelSleep(); - pgstat_report_wait_end(); + pgstat_report_wait_end_abort(); pgaio_error_cleanup(); UnlockBuffers(); ReleaseAuxProcessResources(false); @@ -254,6 +254,15 @@ WalWriterMain(const void *startup_data, size_t startup_data_len) else cur_timeout = WalWriterDelay * HIBERNATE_FACTOR; + /* + * Mirror bgwriter's hibernation drain: on the hibernation path, where + * the sleep lasts WalWriterDelay * HIBERNATE_FACTOR, deliver any + * buffered wait records first so the consumer's view stays fresh + * across the long sleep. The top of this pacing loop is a safe point. + */ + if (left_till_hibernate == 0) + pgstat_drain_wait_events_if_pending(); + (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH, cur_timeout, diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c index d0e335629e7..de6ce92ed83 100644 --- a/src/backend/replication/walsender.c +++ b/src/backend/replication/walsender.c @@ -378,7 +378,7 @@ WalSndErrorCleanup(void) { LWLockReleaseAll(); ConditionVariableCancelSleep(); - pgstat_report_wait_end(); + pgstat_report_wait_end_abort(); pgaio_error_cleanup(); if (xlogreader != NULL && xlogreader->seg.ws_file >= 0) diff --git a/src/backend/storage/aio/method_worker.c b/src/backend/storage/aio/method_worker.c index cf75b2816b7..e92a3e11718 100644 --- a/src/backend/storage/aio/method_worker.c +++ b/src/backend/storage/aio/method_worker.c @@ -1009,6 +1009,15 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len) set_ps_display(cmd); #endif + /* + * About to sleep, possibly unbounded (timeout_ms may be -1), and + * CHECK_FOR_INTERRUPTS() runs only after we wake. This is a safe + * point (top of the loop, no lock or critical section held), so + * deliver any wait records buffered during the previous round of + * IO before we block. + */ + pgstat_drain_wait_events_if_pending(); + if (WaitLatch(MyLatch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH | WL_TIMEOUT, timeout_ms, WAIT_EVENT_IO_WORKER_MAIN) == WL_TIMEOUT) diff --git a/src/backend/storage/lmgr/s_lock.c b/src/backend/storage/lmgr/s_lock.c index 795aeed1028..2c87752e746 100644 --- a/src/backend/storage/lmgr/s_lock.c +++ b/src/backend/storage/lmgr/s_lock.c @@ -62,11 +62,23 @@ #ifdef S_LOCK_TEST /* - * These are needed by pgstat_report_wait_start in the standalone compile of - * s_lock_test. + * These are needed by pgstat_report_wait_start()/pgstat_report_wait_end() in + * the standalone compile of s_lock_test. Timing is never enabled there, so + * the wait-timing slow paths are empty stubs; they exist only to satisfy the + * linker. */ static uint32 local_my_wait_event_info; -uint32 *my_wait_event_info = &local_my_wait_event_info; +WaitEventReportState wait_event_report_state = {&local_my_wait_event_info, NULL}; + +void +pgstat_wait_timing_begin_slow(uint32 wait_event_info) +{ +} + +void +pgstat_wait_timing_end_slow(void) +{ +} #endif static int spins_per_delay = DEFAULT_SPINS_PER_DELAY; diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index d6761aeea9f..3498364bfe4 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -86,6 +86,7 @@ #include "utils/timeout.h" #include "utils/timestamp.h" #include "utils/varlena.h" +#include "utils/wait_event.h" /* ---------------- * global variables @@ -3711,6 +3712,13 @@ ProcessInterrupts(void) if (RepackMessagePending) ProcessRepackMessages(); + + /* + * Deliver buffered wait event records, if a drain was requested. Done + * last, so that a consumer error cannot cause other pending interrupts + * to be missed. + */ + pgstat_drain_wait_events_if_pending(); } /* diff --git a/src/backend/utils/activity/wait_event.c b/src/backend/utils/activity/wait_event.c index e36a740a888..bf3f45e353a 100644 --- a/src/backend/utils/activity/wait_event.c +++ b/src/backend/utils/activity/wait_event.c @@ -22,11 +22,17 @@ */ #include "postgres.h" +#include + +#include "miscadmin.h" +#include "storage/ipc.h" #include "storage/lmgr.h" #include "storage/lwlock.h" #include "storage/shmem.h" #include "storage/subsystems.h" +#include "utils/memutils.h" #include "utils/wait_event.h" +#include "utils/wait_event_timing.h" static const char *pgstat_get_wait_activity(WaitEventActivity w); @@ -38,7 +44,31 @@ static const char *pgstat_get_wait_io(WaitEventIO w); static uint32 local_my_wait_event_info; -uint32 *my_wait_event_info = &local_my_wait_event_info; +WaitEventReportState wait_event_report_state = {&local_my_wait_event_info, NULL}; + +bool WaitEventDrainPending = false; + +/* + * Backend-local wait event timing state: the registered consumers, and the + * settings that decide whether, and how large, the local buffer is. The + * buffer (wait_event_report_state.buf) exists exactly while timing is enabled + * and at least one consumer is registered; see wait_event_sync_buffer(). + */ +typedef struct WaitEventConsumer +{ + wait_event_drain_callback callback; + void *arg; +} WaitEventConsumer; + +static WaitEventConsumer wait_event_consumers[WAIT_EVENT_MAX_CONSUMERS]; +static int wait_event_num_consumers = 0; +static bool wait_event_timing_enabled = false; +static int wait_event_timing_capacity = WAIT_EVENT_BUF_DEFAULT_CAP; +static int64 wait_event_drain_interval_ns = WAIT_EVENT_DRAIN_INTERVAL_NS; +static bool wait_event_shutdown_registered = false; + +static void wait_event_sync_buffer(void); +static void wait_event_timing_shutdown(int code, Datum arg); #define WAIT_EVENT_CLASS_MASK 0xFF000000 #define WAIT_EVENT_ID_MASK 0x0000FFFF @@ -333,6 +363,497 @@ pgstat_reset_wait_event_storage(void) my_wait_event_info = &local_my_wait_event_info; } +/* + * Slow paths for pgstat_report_wait_start() and + * pgstat_report_wait_end() in wait_event.h, reached only once timing has + * been enabled in this process. Keeping them out of line and marked cold + * lets the inline callers stay down to a single hinted pointer test when + * timing is disabled. + * + * Each function re-reads the buffer pointer rather than being handed the value + * the inline caller already loaded. It cannot change in between, but + * re-reading it keeps that assumption local to this file. + * + * These functions run inside arbitrary wait sites, possibly in critical + * sections or with spinlocks or LWLocks held, so they must not allocate, + * lock, wait or report errors. They only read the clock and write to the + * preallocated buffer. They save and restore errno around the clock read: + * callers look at errno after pgstat_report_wait_end() (for example to + * retry on EINTR), and while the usual clock sources do not set errno, a + * fallback may. + * + * While a consumer callback is running, recording is suppressed so that the + * drain cannot disturb the records it is reading or distort what it measures. + * A wait that starts during a drain and ends after it is not recorded, since + * current_event was never set. + */ +pg_noinline pg_attribute_cold void +pgstat_wait_timing_begin_slow(uint32 wait_event_info) +{ + WaitEventLocalBuffer *buf = wait_event_report_state.buf; + int save_errno; + + if (buf == NULL || buf->draining) + return; + + save_errno = errno; + INSTR_TIME_SET_CURRENT(buf->wait_start); + errno = save_errno; + + /* A wait that never ended (error unwind) is simply overwritten here. */ + buf->current_event = wait_event_info; + buf->current_context = buf->context; +} + +pg_noinline pg_attribute_cold void +pgstat_wait_timing_end_slow(void) +{ + WaitEventLocalBuffer *buf = wait_event_report_state.buf; + instr_time now; + int64 end_ns; + int64 dur_ns; + int save_errno; + + if (buf == NULL || buf->draining) + return; + + /* No matching start (timing was enabled mid-wait, or wait was aborted) */ + if (buf->current_event == 0 || INSTR_TIME_IS_ZERO(buf->wait_start)) + return; + + save_errno = errno; + INSTR_TIME_SET_CURRENT(now); + errno = save_errno; + + end_ns = INSTR_TIME_GET_NANOSEC(now); + dur_ns = end_ns - INSTR_TIME_GET_NANOSEC(buf->wait_start); + if (dur_ns < 0) + dur_ns = 0; + + if (buf->count < buf->capacity) + { + WaitEventRecord *rec = &buf->records[buf->count++]; + + rec->wait_event_info = buf->current_event; + rec->context = buf->current_context; + rec->end_ns = end_ns; + rec->duration_ns = dur_ns; + } + else + { + /* Full: keep the total time even though the detail is lost. */ + buf->dropped_count++; + buf->dropped_ns += (uint64) dur_ns; + } + + INSTR_TIME_SET_ZERO(buf->wait_start); + buf->current_event = 0; + + /* + * Ask for a drain at the next safe point if the buffer is getting full or + * it has been a while. Reuses the timestamp taken above, so the time + * trigger costs no extra clock read. + * + * Only InterruptPending is raised here; MyLatch is deliberately left + * alone. A wait-event reporting function runs inside arbitrary wait + * sites, and must not arm the latch: doing so would make the very next + * WaitLatch() return at once and would distort latch-paced loops (the + * bgwriter control loop and its hibernation, walwriter pacing, the IO + * workers' wakeup accounting, ...). The request is instead served at the + * next interrupt hub (every per-iteration Process*Interrupts() calls + * pgstat_drain_wait_events_if_pending()); a process that is about to enter + * a long or unbounded sleep drains explicitly just before it, through the + * same helper. + * + * Do nothing if a drain is already pending: the interrupt has been raised + * already, so re-arming on every wait-end would add nothing. + */ + if (!WaitEventDrainPending && + (buf->count >= buf->high_water || + (end_ns - buf->last_drain_ns) >= buf->drain_interval_ns)) + { + WaitEventDrainPending = true; + InterruptPending = true; + } +} + +/* + * Bring the existence of the local buffer in line with the settings: it + * exists if and only if timing is enabled and at least one consumer is + * registered. Allocates in TopMemoryContext, so this must be called from a + * safe point, never from a wait site. A buffer whose consumer callbacks are + * running is left alone; pgstat_drain_wait_events() calls this again when + * they finish. + */ +static void +wait_event_sync_buffer(void) +{ + WaitEventLocalBuffer *buf = wait_event_report_state.buf; + bool want = wait_event_timing_enabled && wait_event_num_consumers > 0; + + if (want && buf == NULL) + { + instr_time now; + int cap = wait_event_timing_capacity; + + buf = (WaitEventLocalBuffer *) + MemoryContextAllocZero(TopMemoryContext, + offsetof(WaitEventLocalBuffer, records) + + cap * sizeof(WaitEventRecord)); + buf->capacity = cap; + buf->high_water = WAIT_EVENT_BUF_HIGH_WATER(cap); + buf->drain_interval_ns = wait_event_drain_interval_ns; + INSTR_TIME_SET_CURRENT(now); + buf->last_drain_ns = INSTR_TIME_GET_NANOSEC(now); + + /* Make sure remaining records are delivered at process exit. */ + if (!wait_event_shutdown_registered) + { + before_shmem_exit(wait_event_timing_shutdown, 0); + wait_event_shutdown_registered = true; + } + + wait_event_report_state.buf = buf; + } + else if (!want && buf != NULL && !buf->draining) + { + wait_event_report_state.buf = NULL; + WaitEventDrainPending = false; + pfree(buf); + } +} + +/* + * Register a callback to receive drained wait records in this process. Up to + * WAIT_EVENT_MAX_CONSUMERS callbacks may be registered; registering the same + * (callback, arg) pair twice has no further effect. Must be called from a + * safe point. The buffer is created once timing is also enabled. + */ +void +pgstat_register_wait_event_consumer(wait_event_drain_callback cb, void *arg) +{ + Assert(cb != NULL); + + for (int i = 0; i < wait_event_num_consumers; i++) + { + if (wait_event_consumers[i].callback == cb && + wait_event_consumers[i].arg == arg) + return; + } + + if (wait_event_num_consumers >= WAIT_EVENT_MAX_CONSUMERS) + ereport(ERROR, + (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), + errmsg("too many wait event consumers"), + errdetail("At most %d consumers can be registered in one process.", + WAIT_EVENT_MAX_CONSUMERS))); + + wait_event_consumers[wait_event_num_consumers].callback = cb; + wait_event_consumers[wait_event_num_consumers].arg = arg; + wait_event_num_consumers++; + + wait_event_sync_buffer(); +} + +/* + * Unregister a consumer. Records still buffered are delivered first, so the + * departing consumer sees everything up to this point. Consumers may be + * unregistered in any order, including from their own callback. When the last + * consumer goes, the buffer is released. + */ +void +pgstat_unregister_wait_event_consumer(wait_event_drain_callback cb, void *arg) +{ + int i; + + for (i = 0; i < wait_event_num_consumers; i++) + { + if (wait_event_consumers[i].callback == cb && + wait_event_consumers[i].arg == arg) + break; + } + if (i == wait_event_num_consumers) + return; + + pgstat_drain_wait_events(); + + /* the drain may have changed the registry; look again */ + for (i = 0; i < wait_event_num_consumers; i++) + { + if (wait_event_consumers[i].callback == cb && + wait_event_consumers[i].arg == arg) + { + memmove(&wait_event_consumers[i], &wait_event_consumers[i + 1], + (wait_event_num_consumers - i - 1) * + sizeof(WaitEventConsumer)); + wait_event_num_consumers--; + break; + } + } + + wait_event_sync_buffer(); +} + +/* + * Enable or disable local wait event timing in this process. Enabling with + * no consumer registered only records the setting; the buffer appears when a + * consumer registers. capacity is in records; zero selects the default, and + * other values are clamped to the supported range. Disabling delivers any + * buffered records first. Must be called from a safe point, and not from a + * consumer callback. + */ +void +pgstat_set_wait_event_timing_enabled(bool enabled, int capacity) +{ + WaitEventLocalBuffer *buf = wait_event_report_state.buf; + uint32 saved_context = 0; + bool restore_context = false; + + if (buf != NULL && buf->draining) + ereport(ERROR, + (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("cannot change wait event timing from a drain callback"))); + + if (enabled) + { + if (capacity <= 0) + capacity = WAIT_EVENT_BUF_DEFAULT_CAP; + capacity = Max(capacity, WAIT_EVENT_BUF_MIN_CAP); + capacity = Min(capacity, WAIT_EVENT_BUF_MAX_CAP); + + /* resizing: flush what we have, then start over with a new buffer */ + if (buf != NULL && buf->capacity != capacity) + { + /* + * The reallocation drops and re-creates the buffer, which would + * reset the consumer's context tag to zero. Carry it across so a + * resize is transparent to the consumer. + */ + saved_context = buf->context; + restore_context = true; + + pgstat_drain_wait_events(); + wait_event_timing_enabled = false; + wait_event_sync_buffer(); + } + + wait_event_timing_enabled = true; + wait_event_timing_capacity = capacity; + } + else + { + pgstat_drain_wait_events(); + wait_event_timing_enabled = false; + } + + wait_event_sync_buffer(); + + /* a resize made a fresh buffer above; put the context tag back on it */ + if (restore_context && wait_event_report_state.buf != NULL) + wait_event_report_state.buf->context = saved_context; +} + +/* + * Set the time-based drain trigger, in nanoseconds: a drain is requested when + * a wait ends and at least this long has passed since the last drain. Applies + * to the current buffer, if any, and to buffers created later. + */ +void +pgstat_set_wait_event_drain_interval(int64 interval_ns) +{ + wait_event_drain_interval_ns = Max(interval_ns, 0); + + if (wait_event_report_state.buf != NULL) + wait_event_report_state.buf->drain_interval_ns = wait_event_drain_interval_ns; +} + +/* + * Deliver the buffered wait records to the registered consumers, then empty + * the buffer. + * + * Must be called at a safe point: outside critical sections, spinlocks and + * LWLock acquisition, and with ordinary error handling available. The + * interrupt-processing hubs call it when WaitEventDrainPending is set; a + * consumer may also call it directly to get exact ordering. + * + * Recording is suppressed while consumers run. Whatever a consumer does, + * including raising an error, the buffer is emptied and recording resumes: + * the PG_FINALLY block runs on every exit, so a failing consumer cannot leave + * the buffer stuck. If a consumer raises an error, consumers after it do not + * see this batch, and the batch is discarded (see the consumer contract in + * wait_event.h). + */ +void +pgstat_drain_wait_events(void) +{ + WaitEventLocalBuffer *buf = wait_event_report_state.buf; + WaitEventConsumer consumers[WAIT_EVENT_MAX_CONSUMERS]; + int nconsumers; + instr_time now; + + if (buf == NULL || buf->draining) + return; + + Assert(CritSectionCount == 0); + /* Interrupts are held off during proc_exit(), where the final drain runs */ + Assert(InterruptHoldoffCount == 0 || proc_exit_inprogress); + + WaitEventDrainPending = false; + + if (buf->count == 0 && buf->dropped_count == 0) + { + INSTR_TIME_SET_CURRENT(now); + buf->last_drain_ns = INSTR_TIME_GET_NANOSEC(now); + return; + } + + /* + * Work from a copy of the registry, so that a callback may register or + * unregister consumers without disturbing this loop. + */ + nconsumers = wait_event_num_consumers; + /* (buf stays valid below: wait_event_sync_buffer never frees while draining) */ + memcpy(consumers, wait_event_consumers, + nconsumers * sizeof(WaitEventConsumer)); + + buf->draining = true; + + PG_TRY(); + { + for (int i = 0; i < nconsumers; i++) + consumers[i].callback(buf->records, buf->count, + buf->dropped_count, buf->dropped_ns, + consumers[i].arg); + } + PG_FINALLY(); + { + buf->count = 0; + buf->dropped_count = 0; + buf->dropped_ns = 0; + buf->draining = false; + INSTR_TIME_SET_CURRENT(now); + buf->last_drain_ns = INSTR_TIME_GET_NANOSEC(now); + + /* a callback may have unregistered the last consumer */ + wait_event_sync_buffer(); + } + PG_END_TRY(); +} + +/* + * Drain the buffered wait records if a drain was requested and we are at a + * safe point to do so. + * + * This is the body shared by every per-iteration interrupt handler that can + * reach a safe point: the backend's ProcessInterrupts(), the auxiliary-process + * handlers, and the background-process main-loop handler. Keeping it out of + * line lets those handlers invoke the drain without wait_event.h having to + * expose InterruptHoldoffCount and CritSectionCount (that is, without pulling + * miscadmin.h into every wait site that includes wait_event.h). + * + * The guard matches pgstat_drain_wait_events()'s own safe-point assertions: a + * drain runs consumer callbacks, which may allocate and raise errors, so it + * must not happen inside a critical section or while interrupts are held off. + */ +void +pgstat_drain_wait_events_if_pending(void) +{ + if (WaitEventDrainPending && InterruptHoldoffCount == 0 && + CritSectionCount == 0) + { + WaitEventDrainPending = false; + pgstat_drain_wait_events(); + } +} + +/* + * before_shmem_exit callback: deliver what is left and detach the buffer + * before shared memory goes away. An error from a consumer at this point is + * reported but cannot be allowed to interfere with the exit. + */ +static void +wait_event_timing_shutdown(int code, Datum arg) +{ + if (wait_event_report_state.buf != NULL && + !wait_event_report_state.buf->draining) + { + MemoryContext oldcxt = CurrentMemoryContext; + + PG_TRY(); + { + pgstat_drain_wait_events(); + } + PG_CATCH(); + { + /* + * Switch to ErrorContext before reporting: the consumer may have + * failed because of OOM, or inside a context that is about to go + * away, and EmitErrorReport() allocates. + */ + MemoryContextSwitchTo(ErrorContext); + EmitErrorReport(); + FlushErrorState(); + MemoryContextSwitchTo(oldcxt); + } + PG_END_TRY(); + } + + /* From here on nothing may be recorded or delivered. */ + wait_event_report_state.buf = NULL; + WaitEventDrainPending = false; + wait_event_timing_enabled = false; + wait_event_num_consumers = 0; +} + +/* + * Set the opaque tag copied into the records of waits that start from now on. + * Does nothing unless timing is enabled in this process. + */ +void +pgstat_set_wait_event_context(uint32 ctx) +{ + WaitEventLocalBuffer *buf = wait_event_report_state.buf; + + if (buf != NULL) + buf->context = ctx; +} + +/* + * Report the end of a timed wait that was cut short by an error. This is for + * error-recovery cleanup, where the wait's start may be a long time past and + * a record of the elapsed time would be misleading. Clears the reported wait + * event and forgets any in-flight timing, without appending a record. + */ +void +pgstat_report_wait_end_abort(void) +{ + WaitEventLocalBuffer *buf = wait_event_report_state.buf; + + *(volatile uint32 *) my_wait_event_info = 0; + + if (buf != NULL) + { + buf->current_event = 0; + INSTR_TIME_SET_ZERO(buf->wait_start); + } +} + +/* + * Called early in every postmaster child. A child must not inherit the + * postmaster's buffer, pending-drain flag or consumer registry; it enables + * timing for itself if it wants it. (The memory inherited via fork() is + * simply abandoned; with EXEC_BACKEND there is nothing to inherit.) + */ +void +pgstat_wait_event_timing_child_init(void) +{ + wait_event_report_state.buf = NULL; + WaitEventDrainPending = false; + wait_event_num_consumers = 0; + wait_event_timing_enabled = false; + wait_event_shutdown_registered = false; +} + /* ---------- * pgstat_get_wait_event_type() - * diff --git a/src/backend/utils/init/miscinit.c b/src/backend/utils/init/miscinit.c index 27bafafcd86..ae10b389178 100644 --- a/src/backend/utils/init/miscinit.c +++ b/src/backend/utils/init/miscinit.c @@ -98,6 +98,9 @@ InitPostmasterChild(void) { IsUnderPostmaster = true; /* we are a postmaster subprocess now */ + /* don't inherit the postmaster's wait event timing state */ + pgstat_wait_event_timing_child_init(); + /* * Start our win32 signal implementation. This has to be done after we * read the backend variables, because we need to pick up the signal pipe diff --git a/src/include/utils/wait_event.h b/src/include/utils/wait_event.h index 86ee348220d..b579e99e910 100644 --- a/src/include/utils/wait_event.h +++ b/src/include/utils/wait_event.h @@ -20,7 +20,143 @@ static inline void pgstat_report_wait_end(void); extern void pgstat_set_wait_event_storage(uint32 *wait_event_info); extern void pgstat_reset_wait_event_storage(void); -extern PGDLLIMPORT uint32 *my_wait_event_info; +/* + * Local wait event timing buffer. + * + * A process that wants to know how long its waits took can enable a small, + * backend-local buffer. Once it is enabled, pgstat_report_wait_start() and + * pgstat_report_wait_end() (below) append one fixed-size record per completed + * wait to that buffer. Only fixed core code runs inside a wait site: no hook, + * no allocation, no lock, no error report. The buffered records are handed to + * registered consumer callbacks later, at safe points (see + * pgstat_drain_wait_events()), where a consumer may do anything ordinary + * backend code may do. + * + * The buffer carries one opaque 32-bit context tag, set by the consumer with + * pgstat_set_wait_event_context() and copied into each record when its wait + * starts. Core attaches no meaning to it; it lets a consumer recover state + * that has changed by the time a batch is drained (for example, whether the + * wait started inside a transaction). + */ +typedef struct WaitEventRecord +{ + uint32 wait_event_info; /* full 32-bit wait event code */ + uint32 context; /* opaque consumer tag, copied at wait start */ + int64 end_ns; /* monotonic nanoseconds at wait end */ + int64 duration_ns; /* wait duration, clamped to >= 0 */ +} WaitEventRecord; + +StaticAssertDecl(sizeof(WaitEventRecord) == 24, + "WaitEventRecord must stay 24 bytes"); + +/* + * Default buffer capacity, in records. 2048 records are 48 KiB per process + * that enables timing. The buffer must absorb every wait that completes + * between two safe points, and some stretches (a long write loop that holds + * off interrupts, say) complete well over a thousand waits; 1024 would make + * overflow, which loses per-event detail, too easy to reach, while the extra + * 24 KiB is negligible next to other per-backend memory. Records are written + * sequentially, so only the part currently in use occupies cache. + */ +#define WAIT_EVENT_BUF_DEFAULT_CAP 2048 +#define WAIT_EVENT_BUF_MIN_CAP 16 +#define WAIT_EVENT_BUF_MAX_CAP 16384 + +/* Request a drain once this many records are buffered */ +#define WAIT_EVENT_BUF_HIGH_WATER(cap) (((cap) * 3) / 4) + +/* + * Default time-based drain trigger: request a drain when a wait ends and this + * long has passed since the last drain. This bounds how stale the consumer's + * view of a slow process can get without an extra clock read: the wait-end + * timestamp is already in hand. 10 ms makes the drain cost (one batch call + * per consumer) negligible even for a process that waits continuously. + */ +#define WAIT_EVENT_DRAIN_INTERVAL_NS INT64CONST(10000000) + +/* + * The buffer itself is private to wait_event.c; see utils/wait_event_timing.h + * for the few places (tests) that need to look inside it. Everything else + * only needs to know whether a buffer exists. + */ +typedef struct WaitEventLocalBuffer WaitEventLocalBuffer; +/* + * The wait event reporting pointer and the buffer pointer live in one struct, + * so that the compiler can address both of them from one base register. + * info must stay the first member. + */ +typedef struct WaitEventReportState +{ + uint32 *info; /* where wait events are reported */ + WaitEventLocalBuffer *buf; /* NULL unless timing is enabled here */ +} WaitEventReportState; + +extern PGDLLIMPORT WaitEventReportState wait_event_report_state; + +/* old name kept so existing code and extensions compile unchanged */ +#define my_wait_event_info (wait_event_report_state.info) + +/* + * Out-of-line, cold slow paths for the timing-enabled branch of + * pgstat_report_wait_start() and pgstat_report_wait_end() below. + * + * Every backend reaches those two inlines at every wait, but only a process + * that has enabled local wait event timing ever takes the timing branch. That + * branch is hinted unlikely() so the disabled case is laid out as the + * fall-through; without the hint GCC puts the enabled path there instead, as + * it treats a pointer compared with NULL as probably non-NULL. The work + * lives here, out of line and marked cold, rather than inlined at every wait + * site, and is reached by a direct call: with timing disabled the inline + * costs one compare of the buffer pointer against NULL and one conditional + * branch; with it enabled, that branch, the call and the jump back. The + * buffer pointer sits in wait_event_report_state next to the reported-event + * pointer, so both live in one cache line and, in position-independent code, + * are addressed from one base register. + */ +extern pg_noinline pg_attribute_cold void pgstat_wait_timing_begin_slow(uint32 wait_event_info); +extern pg_noinline pg_attribute_cold void pgstat_wait_timing_end_slow(void); + +/* + * Drain callback. Called at a safe point with the records buffered since the + * previous drain, plus the number and total duration of waits that did not + * fit in the buffer. The callback may allocate, take locks and report errors; + * waits it performs itself are not recorded. The records array is valid only + * for the duration of the call. + */ +typedef void (*wait_event_drain_callback) (const WaitEventRecord *records, + int nrecords, + uint64 dropped_count, + uint64 dropped_ns, + void *arg); + +/* + * Consumer contract: + * + * - Drain callbacks are meant for a single consumer per process. If a + * callback throws an error, the batch is NOT delivered to consumers later in + * the registry, and it is discarded: the buffer is emptied exactly once per + * drain, whatever happens. Several consumers may be registered, but they + * share each batch's fate. + * + * - Core registers a before_shmem_exit callback, the first time timing is + * enabled, that makes a final drain. Callbacks run in LIFO order, so a + * consumer's own before_shmem_exit cleanup registered after that point runs + * BEFORE the final drain, which would then deliver into freed consumer + * state. A consumer must therefore either unregister itself in its cleanup + * (pgstat_unregister_wait_event_consumer drains first), or register that + * cleanup before enabling timing. + */ +#define WAIT_EVENT_MAX_CONSUMERS 8 + +extern void pgstat_register_wait_event_consumer(wait_event_drain_callback cb, void *arg); +extern void pgstat_unregister_wait_event_consumer(wait_event_drain_callback cb, void *arg); +extern void pgstat_set_wait_event_timing_enabled(bool enabled, int capacity); +extern void pgstat_set_wait_event_drain_interval(int64 interval_ns); +extern void pgstat_drain_wait_events(void); +extern void pgstat_drain_wait_events_if_pending(void); +extern void pgstat_set_wait_event_context(uint32 ctx); +extern void pgstat_report_wait_end_abort(void); +extern void pgstat_wait_event_timing_child_init(void); /* diff --git a/src/include/utils/wait_event_timing.h b/src/include/utils/wait_event_timing.h new file mode 100644 index 00000000000..9e512918197 --- /dev/null +++ b/src/include/utils/wait_event_timing.h @@ -0,0 +1,47 @@ +/*------------------------------------------------------------------------- + * wait_event_timing.h + * Internals of the backend-local wait event timing buffer + * + * Only wait_event.c and tests need this; consumers use the API in + * utils/wait_event.h. + * + * Copyright (c) 2026, PostgreSQL Global Development Group + * + * src/include/utils/wait_event_timing.h + * ---------- + */ +#ifndef WAIT_EVENT_TIMING_H +#define WAIT_EVENT_TIMING_H + +#include "portability/instr_time.h" +#include "utils/wait_event.h" + +struct WaitEventLocalBuffer +{ + instr_time wait_start; /* zero when no wait is in flight */ + uint32 current_event; /* wait_event_info of the in-flight wait */ + uint32 current_context; /* context captured at wait start */ + uint32 context; /* consumer-set tag for upcoming waits */ + + int64 last_drain_ns; /* time of the last drain */ + int64 drain_interval_ns; /* time-based drain trigger */ + + int capacity; /* allocated slots in records[] */ + int high_water; /* count at which a drain is requested */ + int count; /* completed records currently buffered */ + uint64 dropped_count; /* records dropped while full */ + uint64 dropped_ns; /* total duration of the dropped waits */ + bool draining; /* a consumer callback is running */ + + WaitEventRecord records[FLEXIBLE_ARRAY_MEMBER]; +}; + +/* + * Set when buffered records should be drained at the next safe point. Nothing + * in core outside wait_event.c needs this: the interrupt-processing hubs reach + * the drain through pgstat_drain_wait_events_if_pending(). It lives here, with + * the buffer internals, rather than in the public wait_event.h. + */ +extern PGDLLIMPORT bool WaitEventDrainPending; + +#endif /* WAIT_EVENT_TIMING_H */ -- 2.49.0