From 6481080dbc914cf2fb73fa1062f7040664c02443 Mon Sep 17 00:00:00 2001
From: Seongjun Shin <shinsj4653@gmail.com>
Date: Fri, 13 Nov 2026 00:03:35 +0900
Subject: [PATCH v10 1/3] Add pgstat_report_wait_swap()

pgstat_report_wait_swap() sets a wait event like
pgstat_report_wait_start(), and returns the wait event that was set
before.  Calling it again with the returned value puts the previous
wait event back, rather than clearing it as pgstat_report_wait_end()
does:

    old = pgstat_report_wait_swap(new);
    /* wait */
    pgstat_report_wait_swap(old);

This is useful for code that can wait while a caller has already set a
wait event of its own.  The first user is added in a follow-up commit.

Author: Seongjun Shin <shinsj4653@gmail.com>
Suggested-by: Michael Paquier <michael@paquier.xyz>
Discussion: https://postgr.es/m/CACdN0M78U+GvpqA7oey-GA7fFSYM636aDp6H9FVvCztv9zXxSA@mail.gmail.com
---
 src/include/utils/wait_event.h | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/src/include/utils/wait_event.h b/src/include/utils/wait_event.h
index 86ee348220d..373cf7b955e 100644
--- a/src/include/utils/wait_event.h
+++ b/src/include/utils/wait_event.h
@@ -17,6 +17,7 @@ extern const char *pgstat_get_wait_event(uint32 wait_event_info);
 extern const char *pgstat_get_wait_event_type(uint32 wait_event_info);
 static inline void pgstat_report_wait_start(uint32 wait_event_info);
 static inline void pgstat_report_wait_end(void);
+static inline uint32 pgstat_report_wait_swap(uint32 wait_event_info);
 extern void pgstat_set_wait_event_storage(uint32 *wait_event_info);
 extern void pgstat_reset_wait_event_storage(void);
 
@@ -86,5 +87,24 @@ pgstat_report_wait_end(void)
 	*(volatile uint32 *) my_wait_event_info = 0;
 }
 
+/* ----------
+ * pgstat_report_wait_swap() -
+ *
+ *	Like pgstat_report_wait_start(), but returns the wait event that was
+ *	set before, so that the caller can put it back with a second call once
+ *	its own wait is over.
+ * ----------
+ */
+static inline uint32
+pgstat_report_wait_swap(uint32 wait_event_info)
+{
+	uint32		old_wait_event_info;
+
+	/* see pgstat_report_wait_start() */
+	old_wait_event_info = *(volatile uint32 *) my_wait_event_info;
+	*(volatile uint32 *) my_wait_event_info = wait_event_info;
+
+	return old_wait_event_info;
+}
 
 #endif							/* WAIT_EVENT_H */
-- 
2.50.1 (Apple Git-155)

