From 9344b4889cec7362658d7445109f649b125776cc Mon Sep 17 00:00:00 2001
From: Yura Sokolov <y.sokolov@postgrespro.ru>
Date: Sun, 6 Dec 2026 17:16:48 +0300
Subject: [PATCH v1 3/8] pgbench: add epoll-based wait backend, selectable at
 runtime

Unify the three wait backends (epoll, ppoll, select) in a single
socket_set struct: backend-specific fields are gathered in a union, and
every operation (alloc/free/add/remove/wait_on_socket_set) dispatches at
runtime on sa->method, chosen by choose_socket_wait_backend().  Which
backends are compiled in is still decided at build time.

The epoll backend keeps a persistent epoll descriptor created once per
set: add_socket_to_set() registers the client's descriptor with
epoll_ctl(EPOLL_CTL_ADD), and wait_on_socket_set() collects ready
descriptors in a single epoll_pwait2(), enqueuing their clients with
ready_add() like the ppoll and select backends.  configure and meson
probe for epoll_pwait2() (HAVE_EPOLL_PWAIT2).

For compile-time testing, PGBENCH_USE_SELECT, PGBENCH_USE_EPOLL and
PGBENCH_USE_PPOLL override the automatic ppoll/epoll/select selection,
and the backend selection macros (POLL_USING_*) are kept separate from
the capability checks, so that the #include blocks mirror the choice.

At runtime, the backend is also selectable with the --socket-wait option
or the PGBENCH_SOCKET_WAIT environment variable ("epoll", "ppoll", or
"select"); the option takes precedence.  By default ppoll is used if
compiled in.
---
 configure                        |   2 +-
 configure.ac                     |   1 +
 doc/src/sgml/ref/pgbench.sgml    |  26 ++
 meson.build                      |   1 +
 src/bin/pgbench/pgbench.c        | 566 +++++++++++++++++++++----------
 src/include/pg_config.h.in       |   3 +
 src/tools/pgindent/typedefs.list |   1 +
 7 files changed, 421 insertions(+), 179 deletions(-)

diff --git a/configure b/configure
index f3b135c95ca..c7cd4cadecb 100755
--- a/configure
+++ b/configure
@@ -15963,7 +15963,7 @@ fi
 LIBS_including_readline="$LIBS"
 LIBS=`echo "$LIBS" | sed -e 's/-ledit//g' -e 's/-lreadline//g'`
 
-for ac_func in backtrace_symbols copyfile copy_file_range elf_aux_info explicit_memset getauxval getifaddrs getpeerucred inet_pton kqueue localeconv_l mbstowcs_l memset_explicit posix_fallocate ppoll pthread_is_threaded_np setproctitle setproctitle_fast strsignal syncfs sync_file_range uselocale wcstombs_l
+for ac_func in backtrace_symbols copyfile copy_file_range elf_aux_info epoll_pwait2 explicit_memset getauxval getifaddrs getpeerucred inet_pton kqueue localeconv_l mbstowcs_l memset_explicit posix_fallocate ppoll pthread_is_threaded_np setproctitle setproctitle_fast strsignal syncfs sync_file_range uselocale wcstombs_l
 do :
   as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
 ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
diff --git a/configure.ac b/configure.ac
index 18bbe596612..51b769850c1 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1868,6 +1868,7 @@ AC_CHECK_FUNCS(m4_normalize([
 	copyfile
 	copy_file_range
 	elf_aux_info
+	epoll_pwait2
 	explicit_memset
 	getauxval
 	getifaddrs
diff --git a/doc/src/sgml/ref/pgbench.sgml b/doc/src/sgml/ref/pgbench.sgml
index fb6e1d4a516..f7e044f82ff 100644
--- a/doc/src/sgml/ref/pgbench.sgml
+++ b/doc/src/sgml/ref/pgbench.sgml
@@ -930,6 +930,19 @@ pgbench <optional> <replaceable>options</replaceable> </optional> <replaceable>d
       </listitem>
      </varlistentry>
 
+     <varlistentry id="pgbench-option-socket-wait">
+      <term><option>--socket-wait=</option><replaceable>method</replaceable></term>
+      <listitem>
+       <para>
+        Select the method that <application>pgbench</application> uses to
+        wait for client socket input: <literal>epoll</literal>,
+        <literal>ppoll</literal>, or <literal>select</literal>.  By default,
+        <literal>ppoll</literal> is used. It is an error to request a method
+        that is not supported on the current platform.
+       </para>
+      </listitem>
+     </varlistentry>
+
      <varlistentry id="pgbench-option-verbose-errors">
       <term><option>--verbose-errors</option></term>
       <listitem>
@@ -1052,6 +1065,19 @@ pgbench <optional> <replaceable>options</replaceable> </optional> <replaceable>d
      </para>
     </listitem>
    </varlistentry>
+
+   <varlistentry id="pgbench-environment-pgbenchsocketwait">
+    <term><envar>PGBENCH_SOCKET_WAIT</envar></term>
+    <listitem>
+     <para>
+      Behaves the same as the <option>--socket-wait</option> option, in
+      that it selects the method used to wait for client socket input
+      (<literal>epoll</literal>, <literal>ppoll</literal>, or
+      <literal>select</literal>).  The option takes precedence over the
+      environment variable.
+     </para>
+    </listitem>
+   </varlistentry>
   </variablelist>
 
   <para>
diff --git a/meson.build b/meson.build
index 3238c849e1b..610a37b78ed 100644
--- a/meson.build
+++ b/meson.build
@@ -3206,6 +3206,7 @@ func_checks = [
   # required. Just checking for dlsym() ought to suffice.
   ['dlsym', {'dependencies': [dl_dep], 'define': false}],
   ['elf_aux_info'],
+  ['epoll_pwait2'],
   ['explicit_bzero'],
   ['explicit_memset'],
   ['getauxval'],
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 2b1c7a6dd12..419341ee2fe 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -42,14 +42,47 @@
 #include <sys/time.h>
 #include <sys/resource.h>		/* for getrlimit */
 
-/* For testing, PGBENCH_USE_SELECT can be defined to force use of that code */
-#if defined(HAVE_PPOLL) && !defined(PGBENCH_USE_SELECT)
+/*
+ * For testing, PGBENCH_USE_SELECT, PGBENCH_USE_EPOLL, or PGBENCH_USE_PPOLL
+ * can be defined to force use of that backend at compile time.
+ *
+ * At runtime, the backend is chosen by the --socket-wait option or by the
+ * PGBENCH_SOCKET_WAIT environment variable (value "epoll", "ppoll", or
+ * "select").  If not set, a default is chosen in
+ * choose_socket_wait_backend() from the number of clients and the backends
+ * compiled in.
+ */
+
+/* Determine which backends are compiled in. */
+#if defined(PGBENCH_USE_EPOLL)
+#if !defined(HAVE_SYS_EPOLL_H) || !defined(HAVE_EPOLL_PWAIT2)
+#error "epoll_pwait2 function is not found"
+#endif
+#define POLL_USING_EPOLL
+#elif defined(PGBENCH_USE_PPOLL)
 #define POLL_USING_PPOLL
+#elif defined(PGBENCH_USE_SELECT)
+#define POLL_USING_SELECT
+#else
+#if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_PWAIT2)
+#define POLL_USING_EPOLL
+#endif
+#ifdef HAVE_PPOLL
+#define POLL_USING_PPOLL
+#endif
+/* select() is POSIX and always available */
+#define POLL_USING_SELECT
+#endif
+
+#if defined(POLL_USING_EPOLL)
+#include <sys/epoll.h>
+#endif
+#if defined(POLL_USING_PPOLL)
 #ifdef HAVE_POLL_H
 #include <poll.h>
 #endif
-#else							/* no ppoll(), so use select() */
-#define POLL_USING_SELECT
+#endif
+#if defined(POLL_USING_SELECT)
 #include <sys/select.h>
 #endif
 
@@ -94,34 +127,55 @@
 
 typedef struct CState CState;
 
-#ifdef POLL_USING_PPOLL
-#define SOCKET_WAIT_METHOD "ppoll"
+typedef enum
+{
+	SOCKET_WAIT_EPOLL,
+	SOCKET_WAIT_PPOLL,
+	SOCKET_WAIT_SELECT
+} socket_wait_method;
 
+/*
+ * socket_set: the client sockets that a thread is waiting on.  All wait
+ * backends share this struct, their specific fields gathered in a union,
+ * so that the backend can be selected at runtime (see
+ * choose_socket_wait_backend()).  Fields are grouped into #if blocks, as
+ * they depend on types from headers that may not be available.
+ */
 typedef struct socket_set
 {
-	int			maxfds;			/* allocated length of pollfds[] array */
+	int			maxfds;			/* allocated length of states[] array */
 	int			curfds;			/* number currently in use */
-	CState	  **states;			/* same length as pollfds; states[i] is the
-								 * CState whose socket is in pollfds[i] */
-	struct pollfd *pollfds;
-} socket_set;
+	CState	  **states;			/* maps slot index (0..curfds-1) to CState */
+	socket_wait_method method;	/* wait backend, chosen at runtime */
+	bool		batch;			/* wait backend is batch based */
 
-#endif							/* POLL_USING_PPOLL */
+	union
+	{
+#ifdef POLL_USING_EPOLL
+		struct
+		{
+			int			epfd;	/* epoll file descriptor */
+			struct epoll_event *revents;	/* received events */
+		}			epoll;
+#endif
+
+#ifdef POLL_USING_PPOLL
+		struct
+		{
+			struct pollfd *pollfds; /* poll descriptor array, maxfds entries */
+		}			ppoll;
+#endif
 
 #ifdef POLL_USING_SELECT
-#define SOCKET_WAIT_METHOD "select"
-
-typedef struct socket_set
-{
-	int			maxfd;			/* largest FD currently set in fds */
-	int			maxfds;			/* allocated length of states[] array */
-	int			curfds;			/* number of sockets currently in the set */
-	fd_set		fds;			/* registration set: sockets we are waiting on */
-	CState	  **states;			/* maps slot index (0..curfds-1) to CState */
+		struct
+		{
+			int			maxfd;	/* largest FD currently set in fds */
+			fd_set		fds;	/* registration set: sockets we wait on */
+		}			select;
+#endif
+	}			u;
 } socket_set;
 
-#endif							/* POLL_USING_SELECT */
-
 /*
  * Multi-platform thread implementations
  */
@@ -822,6 +876,7 @@ static bool verbose_errors = false; /* print verbose messages of all errors */
 
 static bool exit_on_abort = false;	/* exit when any client is aborted */
 static bool continue_on_error = false;	/* continue after errors */
+static char *socket_wait_opt = NULL;	/* --socket-wait option */
 
 /* Builtin test scripts */
 typedef struct BuiltinScript
@@ -890,6 +945,8 @@ static void free_socket_set(socket_set *sa);
 static void add_socket_to_set(socket_set *sa, CState *st);
 static void remove_socket_from_set(socket_set *sa, CState *st);
 static int	wait_on_socket_set(RunState *run, int64 usecs);
+static socket_wait_method choose_socket_wait_backend(int count);
+static const char *socket_wait_backend_name(socket_wait_method method);
 
 static int	wakeup_heap_compare(const pairingheap_node *a, const pairingheap_node *b, void *arg);
 static void wakeup_heap_insert(pairingheap *heap, CState *st, pg_time_usec_t when);
@@ -1015,6 +1072,7 @@ usage(void)
 		   "  --random-seed=SEED       set random seed (\"time\", \"rand\", integer)\n"
 		   "  --sampling-rate=NUM      fraction of transactions to log (e.g., 0.01 for 1%%)\n"
 		   "  --show-script=NAME       show builtin script code, then exit\n"
+		   "  --socket-wait=METHOD     socket wait method (\"epoll\", \"ppoll\", \"select\")\n"
 		   "  --verbose-errors         print messages of all errors\n"
 		   "\nCommon options:\n"
 		   "  --debug                  print debugging output\n"
@@ -3908,7 +3966,8 @@ advanceConnectionState(RunState *run, CState *st)
 				{
 					st->state = CSTATE_THROTTLE;
 					wakeup_heap_insert(&run->wakeup_heap, st, st->txn_scheduled);
-					remove_socket_from_set(run->sockets, st);
+					if (run->sockets->batch)
+						remove_socket_from_set(run->sockets, st);
 					return;
 				}
 				break;
@@ -4000,7 +4059,8 @@ advanceConnectionState(RunState *run, CState *st)
 					if (st->state == CSTATE_SLEEP)
 					{
 						wakeup_heap_insert(&run->wakeup_heap, st, st->sleep_until);
-						remove_socket_from_set(run->sockets, st);
+						if (run->sockets->batch)
+							remove_socket_from_set(run->sockets, st);
 						return;
 					}
 					if (st->state == CSTATE_ABORTED)
@@ -6900,6 +6960,7 @@ main(int argc, char **argv)
 		{"exit-on-abort", no_argument, NULL, 16},
 		{"debug", no_argument, NULL, 17},
 		{"continue-on-error", no_argument, NULL, 18},
+		{"socket-wait", required_argument, NULL, 19},
 		{NULL, 0, NULL, 0}
 	};
 
@@ -7260,6 +7321,10 @@ main(int argc, char **argv)
 				benchmarking_option_set = true;
 				continue_on_error = true;
 				break;
+			case 19:			/* socket-wait */
+				benchmarking_option_set = true;
+				socket_wait_opt = pg_strdup(optarg);
+				break;
 			default:
 				/* getopt_long already emitted a complaint */
 				pg_log_error_hint("Try \"%s --help\" for more information.", progname);
@@ -7802,7 +7867,8 @@ threadRun(void *arg)
 					continue;
 				}
 				/* must be something wrong */
-				pg_log_error("%s() failed: %m", SOCKET_WAIT_METHOD);
+				pg_log_error("%s() failed: %m",
+							 socket_wait_backend_name(run.sockets->method));
 				goto done;
 			}
 
@@ -8033,7 +8099,8 @@ setalarm(int seconds)
  * These functions provide an abstraction layer that hides the syscall
  * we use to wait for input on a set of sockets.
  *
- * Currently there are two implementations, based on ppoll(2) and select(2).
+ * Currently there are three implementations, based on ppoll(2), select(2)
+ * and epoll(7).
  * ppoll() is preferred where available due to its typically higher ceiling
  * on the number of usable sockets.  We do not use the more-widely-available
  * poll(2) because it only offers millisecond timeout resolution, which could
@@ -8062,25 +8129,145 @@ setalarm(int seconds)
  * in the set, and -1 otherwise.
  */
 
+/*
+ * Runtime selection of the socket-wait backend.  The chosen backend is
+ * stored in each socket_set.  The --socket-wait option and the
+ * PGBENCH_SOCKET_WAIT environment variable override the default chosen
+ * below, which never selects a backend that is not compiled in.
+ */
+
+static socket_wait_method
+choose_socket_wait_backend(int count)
+{
+	const char *sel;
+
+	/* the --socket-wait option takes priority over the environment variable */
+	if (socket_wait_opt != NULL)
+		sel = socket_wait_opt;
+	else
+		sel = getenv("PGBENCH_SOCKET_WAIT");
+
+	if (sel != NULL)
+	{
+		if (strcmp(sel, "epoll") == 0)
+		{
+#ifdef POLL_USING_EPOLL
+			return SOCKET_WAIT_EPOLL;
+#else
+			pg_fatal("epoll wait backend is not available in this build");
+#endif
+		}
+		else if (strcmp(sel, "ppoll") == 0)
+		{
 #ifdef POLL_USING_PPOLL
+			return SOCKET_WAIT_PPOLL;
+#else
+			pg_fatal("ppoll wait backend is not available in this build");
+#endif
+		}
+		else if (strcmp(sel, "select") == 0)
+		{
+#ifdef POLL_USING_SELECT
+			return SOCKET_WAIT_SELECT;
+#else
+			pg_fatal("select wait backend is not available in this build");
+#endif
+		}
+		else
+			pg_fatal("invalid socket wait method: \"%s\" "
+					 "(expected \"epoll\", \"ppoll\", or \"select\")",
+					 sel);
+	}
+
+	/* prefer ppoll, then epoll, then select */
+#if defined(POLL_USING_PPOLL)
+	return SOCKET_WAIT_PPOLL;
+#elif defined(POLL_USING_EPOLL)
+	return SOCKET_WAIT_EPOLL;
+#else
+	return SOCKET_WAIT_SELECT;
+#endif
+}
+
+static const char *
+socket_wait_backend_name(socket_wait_method method)
+{
+	switch (method)
+	{
+		case SOCKET_WAIT_EPOLL:
+			return "epoll";
+		case SOCKET_WAIT_PPOLL:
+			return "ppoll";
+		case SOCKET_WAIT_SELECT:
+			return "select";
+	}
+
+	return "unknown";
+}
 
 static socket_set *
 alloc_socket_set(int count)
 {
 	socket_set *sa;
+	socket_wait_method method = choose_socket_wait_backend(count);
 
 	sa = pg_malloc0_object(socket_set);
 	sa->maxfds = count;
 	sa->curfds = 0;
-	sa->pollfds = pg_malloc0_array(struct pollfd, count);
+	sa->method = method;
 	sa->states = pg_malloc0_array(CState *, count);
+
+	if (method == SOCKET_WAIT_EPOLL)
+	{
+#ifdef POLL_USING_EPOLL
+		sa->u.epoll.epfd = epoll_create1(EPOLL_CLOEXEC);
+		if (sa->u.epoll.epfd < 0)
+			pg_fatal("could not create epoll set: %m");
+		sa->u.epoll.revents = pg_malloc0_array(struct epoll_event, count);
+		sa->batch = false;
+#else
+		pg_fatal("epoll wait backend is not available in this build");
+#endif
+	}
+	else if (method == SOCKET_WAIT_PPOLL)
+	{
+#ifdef POLL_USING_PPOLL
+		sa->u.ppoll.pollfds = pg_malloc0_array(struct pollfd, count);
+		sa->batch = true;
+#else
+		pg_fatal("ppoll wait backend is not available in this build");
+#endif
+	}
+	else
+	{
+#ifdef POLL_USING_SELECT
+		sa->u.select.maxfd = -1;
+		sa->batch = true;
+#else
+		pg_fatal("select wait backend is not available in this build");
+#endif
+	}
+
 	return sa;
 }
 
 static void
 free_socket_set(socket_set *sa)
 {
-	pg_free(sa->pollfds);
+	if (sa->method == SOCKET_WAIT_EPOLL)
+	{
+#ifdef POLL_USING_EPOLL
+		close(sa->u.epoll.epfd);
+		pg_free(sa->u.epoll.revents);
+#endif
+	}
+	else if (sa->method == SOCKET_WAIT_PPOLL)
+	{
+#ifdef POLL_USING_PPOLL
+		pg_free(sa->u.ppoll.pollfds);
+#endif
+	}
+
 	pg_free(sa->states);
 	pg_free(sa);
 }
@@ -8096,15 +8283,63 @@ add_socket_to_set(socket_set *sa, CState *st)
 	 */
 	if (st->sockidx >= 0)
 	{
-		Assert(st->sockidx < sa->curfds &&
-			   sa->pollfds[st->sockidx].events == POLLIN);
+		Assert(st->sockidx < sa->curfds && sa->states[st->sockidx] == st);
 		return;
 	}
 
 	Assert(sa->curfds < sa->maxfds);
-	sa->pollfds[sa->curfds].fd = fd;
-	sa->pollfds[sa->curfds].events = POLLIN;
-	sa->pollfds[sa->curfds].revents = 0;
+
+	if (sa->method == SOCKET_WAIT_EPOLL)
+	{
+#ifdef POLL_USING_EPOLL
+		struct epoll_event ev;
+
+		ev.events = EPOLLIN;
+		ev.data.ptr = st;
+		if (epoll_ctl(sa->u.epoll.epfd, EPOLL_CTL_ADD, fd, &ev) < 0)
+			pg_fatal("epoll_ctl(EPOLL_CTL_ADD) failed: %m");
+#else
+		pg_fatal("epoll wait backend is not available in this build");
+#endif
+	}
+	else if (sa->method == SOCKET_WAIT_PPOLL)
+	{
+#ifdef POLL_USING_PPOLL
+		sa->u.ppoll.pollfds[sa->curfds].fd = fd;
+		sa->u.ppoll.pollfds[sa->curfds].events = POLLIN;
+		sa->u.ppoll.pollfds[sa->curfds].revents = 0;
+#else
+		pg_fatal("ppoll wait backend is not available in this build");
+#endif
+	}
+	else
+	{
+#ifdef POLL_USING_SELECT
+#ifdef WIN32
+		if (sa->u.select.fds.fd_count + 1 >= FD_SETSIZE)
+		{
+			pg_log_error("too many concurrent database clients for this platform: %d",
+						 sa->u.select.fds.fd_count + 1);
+			exit(1);
+		}
+#else
+		if (fd < 0 || fd >= FD_SETSIZE)
+		{
+			pg_log_error("socket file descriptor out of range for select(): %d",
+						 fd);
+			pg_log_error_hint("Try fewer concurrent database clients.");
+			exit(1);
+		}
+#endif
+
+		FD_SET(fd, &sa->u.select.fds);
+		if (fd > sa->u.select.maxfd)
+			sa->u.select.maxfd = fd;
+#else
+		pg_fatal("select wait backend is not available in this build");
+#endif
+	}
+
 	sa->states[sa->curfds] = st;
 	st->sockidx = sa->curfds;
 	sa->curfds++;
@@ -8125,10 +8360,38 @@ remove_socket_from_set(socket_set *sa, CState *st)
 	Assert(idx < sa->curfds);
 	st->sockidx = -1;
 
-	/* Compact the arrays by swapping with the last element */
+	if (sa->method == SOCKET_WAIT_EPOLL)
+	{
+#ifdef POLL_USING_EPOLL
+		if (epoll_ctl(sa->u.epoll.epfd, EPOLL_CTL_DEL, PQsocket(st->con),
+					  NULL) < 0)
+			pg_fatal("epoll_ctl(EPOLL_CTL_DEL) failed: %m");
+#else
+		pg_fatal("epoll wait backend is not available in this build");
+#endif
+	}
+	else if (sa->method == SOCKET_WAIT_PPOLL)
+	{
+#ifdef POLL_USING_PPOLL
+		/* Compact the pollfds by swapping with the last element */
+		if (idx != sa->curfds - 1)
+			sa->u.ppoll.pollfds[idx] = sa->u.ppoll.pollfds[sa->curfds - 1];
+#else
+		pg_fatal("ppoll wait backend is not available in this build");
+#endif
+	}
+	else
+	{
+#ifdef POLL_USING_SELECT
+		FD_CLR(PQsocket(st->con), &sa->u.select.fds);
+#else
+		pg_fatal("select wait backend is not available in this build");
+#endif
+	}
+
+	/* Compact the states array by swapping with the last element */
 	if (idx != sa->curfds - 1)
 	{
-		sa->pollfds[idx] = sa->pollfds[sa->curfds - 1];
 		sa->states[idx] = sa->states[sa->curfds - 1];
 		sa->states[idx]->sockidx = idx;
 	}
@@ -8144,168 +8407,115 @@ wait_on_socket_set(RunState *run, int64 usecs)
 	if (sa->curfds == 0)
 		return 0;
 
-	if (usecs > 0)
+	if (sa->method == SOCKET_WAIT_EPOLL)
 	{
-		struct timespec timeout;
+#ifdef POLL_USING_EPOLL
+		struct epoll_event *events = sa->u.epoll.revents;
 
-		timeout.tv_sec = usecs / 1000000;
-		timeout.tv_nsec = (usecs % 1000000) * 1000;
-		n = ppoll(sa->pollfds, sa->curfds, &timeout, NULL);
-	}
-	else
-	{
-		n = ppoll(sa->pollfds, sa->curfds, NULL, NULL);
-	}
-
-	if (n == 0)
-		return 0;
-
-	for (int i = 0; i < sa->curfds; i++)
-	{
-		if ((sa->pollfds[i].revents & POLLIN) != 0)
+		if (usecs > 0)
 		{
-			CState	   *st = sa->states[i];
+			struct timespec timeout;
+
+			timeout.tv_sec = usecs / 1000000;
+			timeout.tv_nsec = (usecs % 1000000) * 1000;
+			n = epoll_pwait2(sa->u.epoll.epfd, events, sa->curfds,
+							 &timeout, NULL);
+		}
+		else
+		{
+			n = epoll_pwait2(sa->u.epoll.epfd, events, sa->curfds,
+							 NULL, NULL);
+		}
+
+		if (n == 0)
+			return 0;
+
+		for (int i = 0; i < n; i++)
+		{
+			CState	   *st = (CState *) events[i].data.ptr;
 
 			if (st != NULL)
 				ready_add(run, st);
 		}
-	}
-
-	return n;
-}
-
-#endif							/* POLL_USING_PPOLL */
-
-#ifdef POLL_USING_SELECT
-
-static socket_set *
-alloc_socket_set(int count)
-{
-	socket_set *sa;
-
-	sa = pg_malloc0_object(socket_set);
-	sa->curfds = 0;
-	sa->maxfd = -1;
-	sa->maxfds = count;
-	sa->states = pg_malloc0_array(CState *, count);
-	return sa;
-}
-
-static void
-free_socket_set(socket_set *sa)
-{
-	pg_free(sa->states);
-	pg_free(sa);
-}
-
-static void
-add_socket_to_set(socket_set *sa, CState *st)
-{
-	int			fd = PQsocket(st->con);
-
-	/*
-	 * Adding a client that is already in the set (sockidx >= 0) is a no-op,
-	 * so callers can invoke it unconditionally.
-	 */
-	if (st->sockidx >= 0)
-	{
-		Assert(st->sockidx < sa->curfds && FD_ISSET(fd, &sa->fds));
-		return;
-	}
-
-	/* See connect_slot() for background on this code. */
-#ifdef WIN32
-	if (sa->fds.fd_count + 1 >= FD_SETSIZE)
-	{
-		pg_log_error("too many concurrent database clients for this platform: %d",
-					 sa->fds.fd_count + 1);
-		exit(1);
-	}
 #else
-	if (fd < 0 || fd >= FD_SETSIZE)
-	{
-		pg_log_error("socket file descriptor out of range for select(): %d",
-					 fd);
-		pg_log_error_hint("Try fewer concurrent database clients.");
-		exit(1);
-	}
+		pg_fatal("epoll wait backend is not available in this build");
 #endif
-
-	Assert(sa->curfds < sa->maxfds);
-	FD_SET(fd, &sa->fds);
-	if (fd > sa->maxfd)
-		sa->maxfd = fd;
-	sa->states[sa->curfds] = st;
-	st->sockidx = sa->curfds;
-	sa->curfds++;
-}
-
-static void
-remove_socket_from_set(socket_set *sa, CState *st)
-{
-	int			idx = st->sockidx;
-
-	/*
-	 * Removing a client that is not in the set (sockidx == -1) is a no-op, so
-	 * callers can invoke it unconditionally.
-	 */
-	if (idx < 0)
-		return;
-
-	Assert(idx < sa->curfds);
-	st->sockidx = -1;
-	FD_CLR(PQsocket(st->con), &sa->fds);
-
-	/* Compact the arrays by swapping with the last element */
-	if (idx != sa->curfds - 1)
-	{
-		sa->states[idx] = sa->states[sa->curfds - 1];
-		sa->states[idx]->sockidx = idx;
 	}
-	sa->curfds--;
-}
-
-static int
-wait_on_socket_set(TState *thread, socket_set *sa, int64 usecs)
-{
-	int			n;
-	fd_set		rfds;
-
-	if (sa->curfds == 0)
-		return 0;
-
-	/*
-	 * select() destructively modifies its input set, clearing bits for
-	 * sockets that are not ready.  So we pass a copy of our registration set
-	 * (sa->fds) as the input, and store the result in sa->rfds.
-	 */
-	memcpy(&rfds, &sa->fds, sizeof(fd_set));
-	if (usecs > 0)
+	else if (sa->method == SOCKET_WAIT_PPOLL)
 	{
-		struct timeval timeout;
+#ifdef POLL_USING_PPOLL
+		if (usecs > 0)
+		{
+			struct timespec timeout;
 
-		timeout.tv_sec = usecs / 1000000;
-		timeout.tv_usec = usecs % 1000000;
+			timeout.tv_sec = usecs / 1000000;
+			timeout.tv_nsec = (usecs % 1000000) * 1000;
+			n = ppoll(sa->u.ppoll.pollfds, sa->curfds, &timeout, NULL);
+		}
+		else
+		{
+			n = ppoll(sa->u.ppoll.pollfds, sa->curfds, NULL, NULL);
+		}
 
-		n = select(sa->maxfd + 1, &rfds, NULL, NULL, &timeout);
+		if (n == 0)
+			return 0;
+
+		for (int i = 0; i < sa->curfds; i++)
+		{
+			if ((sa->u.ppoll.pollfds[i].revents & POLLIN) != 0)
+			{
+				CState	   *st = (CState *) sa->states[i];
+
+				if (st != NULL)
+					ready_add(run, st);
+			}
+		}
+#else
+		pg_fatal("ppoll wait backend is not available in this build");
+#endif
 	}
 	else
 	{
-		n = select(sa->maxfd + 1, &rfds, NULL, NULL, NULL);
-	}
+#ifdef POLL_USING_SELECT
+		fd_set		rfds;
 
-	if (n == 0)
-		return 0;
+		/*
+		 * select() destructively modifies its input set, clearing bits for
+		 * sockets that are not ready.  So we pass a copy of our registration
+		 * set (sa->u.select.fds) as the input, and store the result in
+		 * sa->u.select.rfds.
+		 */
+		memcpy(&rfds, &sa->u.select.fds, sizeof(fd_set));
+		if (usecs > 0)
+		{
+			struct timeval timeout;
 
-	for (int i = 0; i < sa->curfds; i++)
-	{
-		CState	   *st = sa->states[i];
+			timeout.tv_sec = usecs / 1000000;
+			timeout.tv_usec = usecs % 1000000;
 
-		if (FD_ISSET(PQsocket(st->con), &rfds) != 0)
-			ready_add(thread, st);
+			n = select(sa->u.select.maxfd + 1, &rfds, NULL, NULL,
+					   &timeout);
+		}
+		else
+		{
+			n = select(sa->u.select.maxfd + 1, &rfds, NULL, NULL,
+					   NULL);
+		}
+
+		if (n == 0)
+			return 0;
+
+		for (int i = 0; i < sa->curfds; i++)
+		{
+			CState	   *st = sa->states[i];
+
+			if (FD_ISSET(PQsocket(st->con), &rfds) != 0)
+				ready_add(run, st);
+		}
+#else
+		pg_fatal("select wait backend is not available in this build");
+#endif
 	}
 
 	return n;
 }
-
-#endif							/* POLL_USING_SELECT */
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index 2e5ed6f5693..f09dd007617 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -130,6 +130,9 @@
 /* Define to 1 if you have the `elf_aux_info' function. */
 #undef HAVE_ELF_AUX_INFO
 
+/* Define to 1 if you have the `epoll_pwait2' function. */
+#undef HAVE_EPOLL_PWAIT2
+
 /* Define to 1 if you have the <execinfo.h> header file. */
 #undef HAVE_EXECINFO_H
 
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 75f07706a79..3d89d2c4a82 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -4298,6 +4298,7 @@ slist_mutable_iter
 slist_node
 slock_t
 socket_set
+socket_wait_method
 socklen_t
 spgBulkDeleteState
 spgChooseIn
-- 
2.43.0

