PostgreSQL Source Code  git master
latch.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <unistd.h>
#include <poll.h>
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "port/atomics.h"
#include "portability/instr_time.h"
#include "postmaster/postmaster.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/pmsignal.h"
#include "storage/shmem.h"
#include "utils/memutils.h"
Include dependency graph for latch.c:

Go to the source code of this file.

Data Structures

struct  WaitEventSet
 

Macros

#define WAIT_USE_POLL
 
#define WAIT_USE_SELF_PIPE
 
#define LatchWaitSetLatchPos   0
 

Functions

static void latch_sigurg_handler (SIGNAL_ARGS)
 
static void sendSelfPipeByte (void)
 
static void drain (void)
 
static void WaitEventAdjustPoll (WaitEventSet *set, WaitEvent *event)
 
static int WaitEventSetWaitBlock (WaitEventSet *set, int cur_timeout, WaitEvent *occurred_events, int nevents)
 
void InitializeLatchSupport (void)
 
void InitializeLatchWaitSet (void)
 
void ShutdownLatchSupport (void)
 
void InitLatch (Latch *latch)
 
void InitSharedLatch (Latch *latch)
 
void OwnLatch (Latch *latch)
 
void DisownLatch (Latch *latch)
 
int WaitLatch (Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
 
int WaitLatchOrSocket (Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
 
void SetLatch (Latch *latch)
 
void ResetLatch (Latch *latch)
 
WaitEventSetCreateWaitEventSet (MemoryContext context, int nevents)
 
void FreeWaitEventSet (WaitEventSet *set)
 
void FreeWaitEventSetAfterFork (WaitEventSet *set)
 
int AddWaitEventToSet (WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
 
void ModifyWaitEvent (WaitEventSet *set, int pos, uint32 events, Latch *latch)
 
int WaitEventSetWait (WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
 
bool WaitEventSetCanReportClosed (void)
 
int GetNumRegisteredWaitEvents (WaitEventSet *set)
 

Variables

static WaitEventSetLatchWaitSet
 
static volatile sig_atomic_t waiting = false
 
static int selfpipe_readfd = -1
 
static int selfpipe_writefd = -1
 
static int selfpipe_owner_pid = 0
 

Macro Definition Documentation

◆ LatchWaitSetLatchPos

#define LatchWaitSetLatchPos   0

Definition at line 158 of file latch.c.

◆ WAIT_USE_POLL

#define WAIT_USE_POLL

Definition at line 80 of file latch.c.

◆ WAIT_USE_SELF_PIPE

#define WAIT_USE_SELF_PIPE

Definition at line 99 of file latch.c.

Function Documentation

◆ AddWaitEventToSet()

int AddWaitEventToSet ( WaitEventSet set,
uint32  events,
pgsocket  fd,
Latch latch,
void *  user_data 
)

Definition at line 922 of file latch.c.

924 {
925  WaitEvent *event;
926 
927  /* not enough space */
928  Assert(set->nevents < set->nevents_space);
929 
930  if (events == WL_EXIT_ON_PM_DEATH)
931  {
932  events = WL_POSTMASTER_DEATH;
933  set->exit_on_postmaster_death = true;
934  }
935 
936  if (latch)
937  {
938  if (latch->owner_pid != MyProcPid)
939  elog(ERROR, "cannot wait on a latch owned by another process");
940  if (set->latch)
941  elog(ERROR, "cannot wait on more than one latch");
942  if ((events & WL_LATCH_SET) != WL_LATCH_SET)
943  elog(ERROR, "latch events only support being set");
944  }
945  else
946  {
947  if (events & WL_LATCH_SET)
948  elog(ERROR, "cannot wait on latch without a specified latch");
949  }
950 
951  /* waiting for socket readiness without a socket indicates a bug */
952  if (fd == PGINVALID_SOCKET && (events & WL_SOCKET_MASK))
953  elog(ERROR, "cannot wait on socket event without a socket");
954 
955  event = &set->events[set->nevents];
956  event->pos = set->nevents++;
957  event->fd = fd;
958  event->events = events;
959  event->user_data = user_data;
960 #ifdef WIN32
961  event->reset = false;
962 #endif
963 
964  if (events == WL_LATCH_SET)
965  {
966  set->latch = latch;
967  set->latch_pos = event->pos;
968 #if defined(WAIT_USE_SELF_PIPE)
969  event->fd = selfpipe_readfd;
970 #elif defined(WAIT_USE_SIGNALFD)
971  event->fd = signal_fd;
972 #else
973  event->fd = PGINVALID_SOCKET;
974 #ifdef WAIT_USE_EPOLL
975  return event->pos;
976 #endif
977 #endif
978  }
979  else if (events == WL_POSTMASTER_DEATH)
980  {
981 #ifndef WIN32
983 #endif
984  }
985 
986  /* perform wait primitive specific initialization, if needed */
987 #if defined(WAIT_USE_EPOLL)
988  WaitEventAdjustEpoll(set, event, EPOLL_CTL_ADD);
989 #elif defined(WAIT_USE_KQUEUE)
990  WaitEventAdjustKqueue(set, event, 0);
991 #elif defined(WAIT_USE_POLL)
992  WaitEventAdjustPoll(set, event);
993 #elif defined(WAIT_USE_WIN32)
994  WaitEventAdjustWin32(set, event);
995 #endif
996 
997  return event->pos;
998 }
#define ERROR
Definition: elog.h:39
int MyProcPid
Definition: globals.c:44
static int selfpipe_readfd
Definition: latch.c:172
static void WaitEventAdjustPoll(WaitEventSet *set, WaitEvent *event)
Definition: latch.c:1135
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_LATCH_SET
Definition: latch.h:125
#define WL_POSTMASTER_DEATH
Definition: latch.h:129
#define WL_SOCKET_MASK
Definition: latch.h:144
Assert(fmt[strlen(fmt) - 1] !='\n')
#define PGINVALID_SOCKET
Definition: port.h:31
int postmaster_alive_fds[2]
Definition: postmaster.c:576
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:46
static int fd(const char *x, int i)
Definition: preproc-init.c:105
int owner_pid
Definition: latch.h:115
Latch * latch
Definition: latch.c:121
bool exit_on_postmaster_death
Definition: latch.c:129
int nevents
Definition: latch.c:106
int latch_pos
Definition: latch.c:122
int nevents_space
Definition: latch.c:107
WaitEvent * events
Definition: latch.c:113
int pos
Definition: latch.h:152

References Assert(), elog(), ERROR, WaitEventSet::events, WaitEventSet::exit_on_postmaster_death, fd(), WaitEventSet::latch, WaitEventSet::latch_pos, MyProcPid, WaitEventSet::nevents, WaitEventSet::nevents_space, Latch::owner_pid, PGINVALID_SOCKET, WaitEvent::pos, postmaster_alive_fds, POSTMASTER_FD_WATCH, selfpipe_readfd, WaitEventAdjustPoll(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_POSTMASTER_DEATH, and WL_SOCKET_MASK.

Referenced by ConfigurePostmasterWaitSet(), ExecAppendAsyncEventWait(), InitializeLatchWaitSet(), postgresForeignAsyncConfigureWait(), pq_init(), SysLoggerMain(), and WaitLatchOrSocket().

◆ CreateWaitEventSet()

WaitEventSet* CreateWaitEventSet ( MemoryContext  context,
int  nevents 
)

Definition at line 723 of file latch.c.

724 {
725  WaitEventSet *set;
726  char *data;
727  Size sz = 0;
728 
729  /*
730  * Use MAXALIGN size/alignment to guarantee that later uses of memory are
731  * aligned correctly. E.g. epoll_event might need 8 byte alignment on some
732  * platforms, but earlier allocations like WaitEventSet and WaitEvent
733  * might not be sized to guarantee that when purely using sizeof().
734  */
735  sz += MAXALIGN(sizeof(WaitEventSet));
736  sz += MAXALIGN(sizeof(WaitEvent) * nevents);
737 
738 #if defined(WAIT_USE_EPOLL)
739  sz += MAXALIGN(sizeof(struct epoll_event) * nevents);
740 #elif defined(WAIT_USE_KQUEUE)
741  sz += MAXALIGN(sizeof(struct kevent) * nevents);
742 #elif defined(WAIT_USE_POLL)
743  sz += MAXALIGN(sizeof(struct pollfd) * nevents);
744 #elif defined(WAIT_USE_WIN32)
745  /* need space for the pgwin32_signal_event */
746  sz += MAXALIGN(sizeof(HANDLE) * (nevents + 1));
747 #endif
748 
749  data = (char *) MemoryContextAllocZero(context, sz);
750 
751  set = (WaitEventSet *) data;
752  data += MAXALIGN(sizeof(WaitEventSet));
753 
754  set->events = (WaitEvent *) data;
755  data += MAXALIGN(sizeof(WaitEvent) * nevents);
756 
757 #if defined(WAIT_USE_EPOLL)
758  set->epoll_ret_events = (struct epoll_event *) data;
759  data += MAXALIGN(sizeof(struct epoll_event) * nevents);
760 #elif defined(WAIT_USE_KQUEUE)
761  set->kqueue_ret_events = (struct kevent *) data;
762  data += MAXALIGN(sizeof(struct kevent) * nevents);
763 #elif defined(WAIT_USE_POLL)
764  set->pollfds = (struct pollfd *) data;
765  data += MAXALIGN(sizeof(struct pollfd) * nevents);
766 #elif defined(WAIT_USE_WIN32)
767  set->handles = (HANDLE) data;
768  data += MAXALIGN(sizeof(HANDLE) * nevents);
769 #endif
770 
771  set->latch = NULL;
772  set->nevents_space = nevents;
773  set->exit_on_postmaster_death = false;
774 
775 #if defined(WAIT_USE_EPOLL)
776  if (!AcquireExternalFD())
777  {
778  /* treat this as though epoll_create1 itself returned EMFILE */
779  elog(ERROR, "epoll_create1 failed: %m");
780  }
781  set->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
782  if (set->epoll_fd < 0)
783  {
785  elog(ERROR, "epoll_create1 failed: %m");
786  }
787 #elif defined(WAIT_USE_KQUEUE)
788  if (!AcquireExternalFD())
789  {
790  /* treat this as though kqueue itself returned EMFILE */
791  elog(ERROR, "kqueue failed: %m");
792  }
793  set->kqueue_fd = kqueue();
794  if (set->kqueue_fd < 0)
795  {
797  elog(ERROR, "kqueue failed: %m");
798  }
799  if (fcntl(set->kqueue_fd, F_SETFD, FD_CLOEXEC) == -1)
800  {
801  int save_errno = errno;
802 
803  close(set->kqueue_fd);
805  errno = save_errno;
806  elog(ERROR, "fcntl(F_SETFD) failed on kqueue descriptor: %m");
807  }
808  set->report_postmaster_not_running = false;
809 #elif defined(WAIT_USE_WIN32)
810 
811  /*
812  * To handle signals while waiting, we need to add a win32 specific event.
813  * We accounted for the additional event at the top of this routine. See
814  * port/win32/signal.c for more details.
815  *
816  * Note: pgwin32_signal_event should be first to ensure that it will be
817  * reported when multiple events are set. We want to guarantee that
818  * pending signals are serviced.
819  */
820  set->handles[0] = pgwin32_signal_event;
821  StaticAssertStmt(WSA_INVALID_EVENT == NULL, "");
822 #endif
823 
824  return set;
825 }
#define MAXALIGN(LEN)
Definition: c.h:795
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:922
size_t Size
Definition: c.h:589
void ReleaseExternalFD(void)
Definition: fd.c:1145
bool AcquireExternalFD(void)
Definition: fd.c:1092
#define close(a)
Definition: win32.h:12
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1048
const void * data
HANDLE pgwin32_signal_event
Definition: signal.c:27
struct pollfd * pollfds
Definition: latch.c:142

References AcquireExternalFD(), close, data, elog(), ERROR, WaitEventSet::events, WaitEventSet::exit_on_postmaster_death, WaitEventSet::latch, MAXALIGN, MemoryContextAllocZero(), WaitEventSet::nevents_space, pgwin32_signal_event, WaitEventSet::pollfds, ReleaseExternalFD(), and StaticAssertStmt.

Referenced by ConfigurePostmasterWaitSet(), ExecAppendAsyncEventWait(), InitializeLatchWaitSet(), pq_init(), SysLoggerMain(), and WaitLatchOrSocket().

◆ DisownLatch()

void DisownLatch ( Latch latch)

Definition at line 464 of file latch.c.

465 {
466  Assert(latch->is_shared);
467  Assert(latch->owner_pid == MyProcPid);
468 
469  latch->owner_pid = 0;
470 }
bool is_shared
Definition: latch.h:114

References Assert(), Latch::is_shared, MyProcPid, and Latch::owner_pid.

Referenced by AuxiliaryProcKill(), ProcKill(), and ShutdownWalRecovery().

◆ drain()

static void drain ( void  )
static

Definition at line 2219 of file latch.c.

2220 {
2221  char buf[1024];
2222  int rc;
2223  int fd;
2224 
2225 #ifdef WAIT_USE_SELF_PIPE
2226  fd = selfpipe_readfd;
2227 #else
2228  fd = signal_fd;
2229 #endif
2230 
2231  for (;;)
2232  {
2233  rc = read(fd, buf, sizeof(buf));
2234  if (rc < 0)
2235  {
2236  if (errno == EAGAIN || errno == EWOULDBLOCK)
2237  break; /* the descriptor is empty */
2238  else if (errno == EINTR)
2239  continue; /* retry */
2240  else
2241  {
2242  waiting = false;
2243 #ifdef WAIT_USE_SELF_PIPE
2244  elog(ERROR, "read() on self-pipe failed: %m");
2245 #else
2246  elog(ERROR, "read() on signalfd failed: %m");
2247 #endif
2248  }
2249  }
2250  else if (rc == 0)
2251  {
2252  waiting = false;
2253 #ifdef WAIT_USE_SELF_PIPE
2254  elog(ERROR, "unexpected EOF on self-pipe");
2255 #else
2256  elog(ERROR, "unexpected EOF on signalfd");
2257 #endif
2258  }
2259  else if (rc < sizeof(buf))
2260  {
2261  /* we successfully drained the pipe; no need to read() again */
2262  break;
2263  }
2264  /* else buffer wasn't big enough, so read again */
2265  }
2266 }
#define read(a, b, c)
Definition: win32.h:13
static volatile sig_atomic_t waiting
Definition: latch.c:162
static char * buf
Definition: pg_test_fsync.c:67
#define EINTR
Definition: win32_port.h:376
#define EWOULDBLOCK
Definition: win32_port.h:382
#define EAGAIN
Definition: win32_port.h:374

References buf, EAGAIN, EINTR, elog(), ERROR, EWOULDBLOCK, fd(), read, selfpipe_readfd, and waiting.

Referenced by WaitEventSetWaitBlock().

◆ FreeWaitEventSet()

void FreeWaitEventSet ( WaitEventSet set)

Definition at line 837 of file latch.c.

838 {
839 #if defined(WAIT_USE_EPOLL)
840  close(set->epoll_fd);
842 #elif defined(WAIT_USE_KQUEUE)
843  close(set->kqueue_fd);
845 #elif defined(WAIT_USE_WIN32)
846  WaitEvent *cur_event;
847 
848  for (cur_event = set->events;
849  cur_event < (set->events + set->nevents);
850  cur_event++)
851  {
852  if (cur_event->events & WL_LATCH_SET)
853  {
854  /* uses the latch's HANDLE */
855  }
856  else if (cur_event->events & WL_POSTMASTER_DEATH)
857  {
858  /* uses PostmasterHandle */
859  }
860  else
861  {
862  /* Clean up the event object we created for the socket */
863  WSAEventSelect(cur_event->fd, NULL, 0);
864  WSACloseEvent(set->handles[cur_event->pos + 1]);
865  }
866  }
867 #endif
868 
869  pfree(set);
870 }
void pfree(void *pointer)
Definition: mcxt.c:1436
pgsocket fd
Definition: latch.h:154
uint32 events
Definition: latch.h:153

References close, WaitEventSet::events, WaitEvent::events, WaitEvent::fd, WaitEventSet::nevents, pfree(), WaitEvent::pos, ReleaseExternalFD(), WL_LATCH_SET, and WL_POSTMASTER_DEATH.

Referenced by ConfigurePostmasterWaitSet(), ExecAppendAsyncEventWait(), ShutdownLatchSupport(), and WaitLatchOrSocket().

◆ FreeWaitEventSetAfterFork()

void FreeWaitEventSetAfterFork ( WaitEventSet set)

Definition at line 876 of file latch.c.

877 {
878 #if defined(WAIT_USE_EPOLL)
879  close(set->epoll_fd);
881 #elif defined(WAIT_USE_KQUEUE)
882  /* kqueues are not normally inherited by child processes */
884 #endif
885 
886  pfree(set);
887 }

References close, pfree(), and ReleaseExternalFD().

Referenced by ClosePostmasterPorts().

◆ GetNumRegisteredWaitEvents()

int GetNumRegisteredWaitEvents ( WaitEventSet set)

Definition at line 2153 of file latch.c.

2154 {
2155  return set->nevents;
2156 }

References WaitEventSet::nevents.

Referenced by ExecAppendAsyncEventWait(), and postgresForeignAsyncConfigureWait().

◆ InitializeLatchSupport()

void InitializeLatchSupport ( void  )

Definition at line 207 of file latch.c.

208 {
209 #if defined(WAIT_USE_SELF_PIPE)
210  int pipefd[2];
211 
212  if (IsUnderPostmaster)
213  {
214  /*
215  * We might have inherited connections to a self-pipe created by the
216  * postmaster. It's critical that child processes create their own
217  * self-pipes, of course, and we really want them to close the
218  * inherited FDs for safety's sake.
219  */
220  if (selfpipe_owner_pid != 0)
221  {
222  /* Assert we go through here but once in a child process */
224  /* Release postmaster's pipe FDs; ignore any error */
225  (void) close(selfpipe_readfd);
226  (void) close(selfpipe_writefd);
227  /* Clean up, just for safety's sake; we'll set these below */
229  selfpipe_owner_pid = 0;
230  /* Keep fd.c's accounting straight */
233  }
234  else
235  {
236  /*
237  * Postmaster didn't create a self-pipe ... or else we're in an
238  * EXEC_BACKEND build, in which case it doesn't matter since the
239  * postmaster's pipe FDs were closed by the action of FD_CLOEXEC.
240  * fd.c won't have state to clean up, either.
241  */
242  Assert(selfpipe_readfd == -1);
243  }
244  }
245  else
246  {
247  /* In postmaster or standalone backend, assert we do this but once */
248  Assert(selfpipe_readfd == -1);
250  }
251 
252  /*
253  * Set up the self-pipe that allows a signal handler to wake up the
254  * poll()/epoll_wait() in WaitLatch. Make the write-end non-blocking, so
255  * that SetLatch won't block if the event has already been set many times
256  * filling the kernel buffer. Make the read-end non-blocking too, so that
257  * we can easily clear the pipe by reading until EAGAIN or EWOULDBLOCK.
258  * Also, make both FDs close-on-exec, since we surely do not want any
259  * child processes messing with them.
260  */
261  if (pipe(pipefd) < 0)
262  elog(FATAL, "pipe() failed: %m");
263  if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) == -1)
264  elog(FATAL, "fcntl(F_SETFL) failed on read-end of self-pipe: %m");
265  if (fcntl(pipefd[1], F_SETFL, O_NONBLOCK) == -1)
266  elog(FATAL, "fcntl(F_SETFL) failed on write-end of self-pipe: %m");
267  if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) == -1)
268  elog(FATAL, "fcntl(F_SETFD) failed on read-end of self-pipe: %m");
269  if (fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) == -1)
270  elog(FATAL, "fcntl(F_SETFD) failed on write-end of self-pipe: %m");
271 
272  selfpipe_readfd = pipefd[0];
273  selfpipe_writefd = pipefd[1];
275 
276  /* Tell fd.c about these two long-lived FDs */
279 
281 #endif
282 
283 #ifdef WAIT_USE_SIGNALFD
284  sigset_t signalfd_mask;
285 
286  if (IsUnderPostmaster)
287  {
288  /*
289  * It would probably be safe to re-use the inherited signalfd since
290  * signalfds only see the current process's pending signals, but it
291  * seems less surprising to close it and create our own.
292  */
293  if (signal_fd != -1)
294  {
295  /* Release postmaster's signal FD; ignore any error */
296  (void) close(signal_fd);
297  signal_fd = -1;
299  }
300  }
301 
302  /* Block SIGURG, because we'll receive it through a signalfd. */
303  sigaddset(&UnBlockSig, SIGURG);
304 
305  /* Set up the signalfd to receive SIGURG notifications. */
306  sigemptyset(&signalfd_mask);
307  sigaddset(&signalfd_mask, SIGURG);
308  signal_fd = signalfd(-1, &signalfd_mask, SFD_NONBLOCK | SFD_CLOEXEC);
309  if (signal_fd < 0)
310  elog(FATAL, "signalfd() failed");
312 #endif
313 
314 #ifdef WAIT_USE_KQUEUE
315  /* Ignore SIGURG, because we'll receive it via kqueue. */
316  pqsignal(SIGURG, SIG_IGN);
317 #endif
318 }
sigset_t UnBlockSig
Definition: pqsignal.c:22
#define FATAL
Definition: elog.h:41
void ReserveExternalFD(void)
Definition: fd.c:1127
bool IsUnderPostmaster
Definition: globals.c:113
static void latch_sigurg_handler(SIGNAL_ARGS)
Definition: latch.c:2166
static int selfpipe_owner_pid
Definition: latch.c:176
static int selfpipe_writefd
Definition: latch.c:173
pqsigfunc pqsignal(int signo, pqsigfunc func)
#define SIG_IGN
Definition: win32_port.h:173

References Assert(), close, elog(), FATAL, IsUnderPostmaster, latch_sigurg_handler(), MyProcPid, pqsignal(), ReleaseExternalFD(), ReserveExternalFD(), selfpipe_owner_pid, selfpipe_readfd, selfpipe_writefd, SIG_IGN, and UnBlockSig.

Referenced by InitPostmasterChild(), InitStandaloneProcess(), and PostmasterMain().

◆ InitializeLatchWaitSet()

void InitializeLatchWaitSet ( void  )

Definition at line 321 of file latch.c.

322 {
323  int latch_pos PG_USED_FOR_ASSERTS_ONLY;
324 
325  Assert(LatchWaitSet == NULL);
326 
327  /* Set up the WaitEventSet used by WaitLatch(). */
330  MyLatch, NULL);
331  if (IsUnderPostmaster)
333  PGINVALID_SOCKET, NULL, NULL);
334 
335  Assert(latch_pos == LatchWaitSetLatchPos);
336 }
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:166
struct Latch * MyLatch
Definition: globals.c:58
#define LatchWaitSetLatchPos
Definition: latch.c:158
WaitEventSet * CreateWaitEventSet(MemoryContext context, int nevents)
Definition: latch.c:723
static WaitEventSet * LatchWaitSet
Definition: latch.c:155
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:922
MemoryContext TopMemoryContext
Definition: mcxt.c:141

References AddWaitEventToSet(), Assert(), CreateWaitEventSet(), IsUnderPostmaster, LatchWaitSet, LatchWaitSetLatchPos, MyLatch, PG_USED_FOR_ASSERTS_ONLY, PGINVALID_SOCKET, TopMemoryContext, WL_EXIT_ON_PM_DEATH, and WL_LATCH_SET.

Referenced by InitPostmasterChild(), and InitStandaloneProcess().

◆ InitLatch()

void InitLatch ( Latch latch)

Definition at line 369 of file latch.c.

370 {
371  latch->is_set = false;
372  latch->maybe_sleeping = false;
373  latch->owner_pid = MyProcPid;
374  latch->is_shared = false;
375 
376 #if defined(WAIT_USE_SELF_PIPE)
377  /* Assert InitializeLatchSupport has been called in this process */
379 #elif defined(WAIT_USE_SIGNALFD)
380  /* Assert InitializeLatchSupport has been called in this process */
381  Assert(signal_fd >= 0);
382 #elif defined(WAIT_USE_WIN32)
383  latch->event = CreateEvent(NULL, TRUE, FALSE, NULL);
384  if (latch->event == NULL)
385  elog(ERROR, "CreateEvent failed: error code %lu", GetLastError());
386 #endif /* WIN32 */
387 }
sig_atomic_t is_set
Definition: latch.h:112
sig_atomic_t maybe_sleeping
Definition: latch.h:113

References Assert(), elog(), ERROR, Latch::is_set, Latch::is_shared, Latch::maybe_sleeping, MyProcPid, Latch::owner_pid, selfpipe_owner_pid, and selfpipe_readfd.

Referenced by InitProcessLocalLatch().

◆ InitSharedLatch()

void InitSharedLatch ( Latch latch)

Definition at line 405 of file latch.c.

406 {
407 #ifdef WIN32
408  SECURITY_ATTRIBUTES sa;
409 
410  /*
411  * Set up security attributes to specify that the events are inherited.
412  */
413  ZeroMemory(&sa, sizeof(sa));
414  sa.nLength = sizeof(sa);
415  sa.bInheritHandle = TRUE;
416 
417  latch->event = CreateEvent(&sa, TRUE, FALSE, NULL);
418  if (latch->event == NULL)
419  elog(ERROR, "CreateEvent failed: error code %lu", GetLastError());
420 #endif
421 
422  latch->is_set = false;
423  latch->maybe_sleeping = false;
424  latch->owner_pid = 0;
425  latch->is_shared = true;
426 }

References elog(), ERROR, Latch::is_set, Latch::is_shared, Latch::maybe_sleeping, and Latch::owner_pid.

Referenced by InitProcGlobal(), and XLogRecoveryShmemInit().

◆ latch_sigurg_handler()

static void latch_sigurg_handler ( SIGNAL_ARGS  )
static

Definition at line 2166 of file latch.c.

2167 {
2168  int save_errno = errno;
2169 
2170  if (waiting)
2171  sendSelfPipeByte();
2172 
2173  errno = save_errno;
2174 }
static void sendSelfPipeByte(void)
Definition: latch.c:2178

References sendSelfPipeByte(), and waiting.

Referenced by InitializeLatchSupport().

◆ ModifyWaitEvent()

void ModifyWaitEvent ( WaitEventSet set,
int  pos,
uint32  events,
Latch latch 
)

Definition at line 1008 of file latch.c.

1009 {
1010  WaitEvent *event;
1011 #if defined(WAIT_USE_KQUEUE)
1012  int old_events;
1013 #endif
1014 
1015  Assert(pos < set->nevents);
1016 
1017  event = &set->events[pos];
1018 #if defined(WAIT_USE_KQUEUE)
1019  old_events = event->events;
1020 #endif
1021 
1022  /*
1023  * If neither the event mask nor the associated latch changes, return
1024  * early. That's an important optimization for some sockets, where
1025  * ModifyWaitEvent is frequently used to switch from waiting for reads to
1026  * waiting on writes.
1027  */
1028  if (events == event->events &&
1029  (!(event->events & WL_LATCH_SET) || set->latch == latch))
1030  return;
1031 
1032  if (event->events & WL_LATCH_SET &&
1033  events != event->events)
1034  {
1035  elog(ERROR, "cannot modify latch event");
1036  }
1037 
1038  if (event->events & WL_POSTMASTER_DEATH)
1039  {
1040  elog(ERROR, "cannot modify postmaster death event");
1041  }
1042 
1043  /* FIXME: validate event mask */
1044  event->events = events;
1045 
1046  if (events == WL_LATCH_SET)
1047  {
1048  if (latch && latch->owner_pid != MyProcPid)
1049  elog(ERROR, "cannot wait on a latch owned by another process");
1050  set->latch = latch;
1051 
1052  /*
1053  * On Unix, we don't need to modify the kernel object because the
1054  * underlying pipe (if there is one) is the same for all latches so we
1055  * can return immediately. On Windows, we need to update our array of
1056  * handles, but we leave the old one in place and tolerate spurious
1057  * wakeups if the latch is disabled.
1058  */
1059 #if defined(WAIT_USE_WIN32)
1060  if (!latch)
1061  return;
1062 #else
1063  return;
1064 #endif
1065  }
1066 
1067 #if defined(WAIT_USE_EPOLL)
1068  WaitEventAdjustEpoll(set, event, EPOLL_CTL_MOD);
1069 #elif defined(WAIT_USE_KQUEUE)
1070  WaitEventAdjustKqueue(set, event, old_events);
1071 #elif defined(WAIT_USE_POLL)
1072  WaitEventAdjustPoll(set, event);
1073 #elif defined(WAIT_USE_WIN32)
1074  WaitEventAdjustWin32(set, event);
1075 #endif
1076 }

References Assert(), elog(), ERROR, WaitEventSet::events, WaitEvent::events, WaitEventSet::latch, MyProcPid, Latch::owner_pid, WaitEventAdjustPoll(), WL_LATCH_SET, and WL_POSTMASTER_DEATH.

Referenced by pq_check_connection(), secure_read(), secure_write(), SwitchBackToLocalLatch(), SwitchToSharedLatch(), WaitLatch(), and WalSndWait().

◆ OwnLatch()

void OwnLatch ( Latch latch)

Definition at line 438 of file latch.c.

439 {
440  int owner_pid;
441 
442  /* Sanity checks */
443  Assert(latch->is_shared);
444 
445 #if defined(WAIT_USE_SELF_PIPE)
446  /* Assert InitializeLatchSupport has been called in this process */
448 #elif defined(WAIT_USE_SIGNALFD)
449  /* Assert InitializeLatchSupport has been called in this process */
450  Assert(signal_fd >= 0);
451 #endif
452 
453  owner_pid = latch->owner_pid;
454  if (owner_pid != 0)
455  elog(PANIC, "latch already owned by PID %d", owner_pid);
456 
457  latch->owner_pid = MyProcPid;
458 }
#define PANIC
Definition: elog.h:42

References Assert(), elog(), Latch::is_shared, MyProcPid, Latch::owner_pid, PANIC, selfpipe_owner_pid, and selfpipe_readfd.

Referenced by InitAuxiliaryProcess(), InitProcess(), and InitWalRecovery().

◆ ResetLatch()

void ResetLatch ( Latch latch)

Definition at line 699 of file latch.c.

700 {
701  /* Only the owner should reset the latch */
702  Assert(latch->owner_pid == MyProcPid);
703  Assert(latch->maybe_sleeping == false);
704 
705  latch->is_set = false;
706 
707  /*
708  * Ensure that the write to is_set gets flushed to main memory before we
709  * examine any flag variables. Otherwise a concurrent SetLatch might
710  * falsely conclude that it needn't signal us, even though we have missed
711  * seeing some flag updates that SetLatch was supposed to inform us of.
712  */
714 }
#define pg_memory_barrier()
Definition: atomics.h:140

References Assert(), Latch::is_set, Latch::maybe_sleeping, MyProcPid, Latch::owner_pid, and pg_memory_barrier.

Referenced by ApplyLauncherMain(), autoprewarm_main(), AutoVacLauncherMain(), BackgroundWriterMain(), CheckpointerMain(), CheckpointWriteDelay(), ConditionVariableTimedSleep(), copy_read_data(), do_pg_backup_stop(), gather_readnext(), lazy_truncate_heap(), libpqrcv_PQgetResult(), libpqsrv_connect_internal(), LogicalParallelApplyLoop(), logicalrep_worker_stop_internal(), LogicalRepApplyLoop(), mq_putmessage(), pa_send_data(), pa_wait_for_xact_state(), pg_promote(), pg_sleep(), pg_wait_until_termination(), pgarch_MainLoop(), pgfdw_get_cleanup_result(), pgfdw_get_result(), pq_check_connection(), ProcessPendingWrites(), ProcSleep(), ProcWaitForSignal(), recoveryApplyDelay(), secure_read(), secure_write(), ServerLoop(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), SyncRepWaitForLSN(), SysLoggerMain(), test_shm_mq_pipelined(), throttle(), wait_for_relation_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), WaitForWALToBecomeAvailable(), WalRcvWaitForStartPosition(), WalReceiverMain(), WalSndLoop(), WalSndWaitForWal(), and WalWriterMain().

◆ sendSelfPipeByte()

static void sendSelfPipeByte ( void  )
static

Definition at line 2178 of file latch.c.

2179 {
2180  int rc;
2181  char dummy = 0;
2182 
2183 retry:
2184  rc = write(selfpipe_writefd, &dummy, 1);
2185  if (rc < 0)
2186  {
2187  /* If interrupted by signal, just retry */
2188  if (errno == EINTR)
2189  goto retry;
2190 
2191  /*
2192  * If the pipe is full, we don't need to retry, the data that's there
2193  * already is enough to wake up WaitLatch.
2194  */
2195  if (errno == EAGAIN || errno == EWOULDBLOCK)
2196  return;
2197 
2198  /*
2199  * Oops, the write() failed for some other reason. We might be in a
2200  * signal handler, so it's not safe to elog(). We have no choice but
2201  * silently ignore the error.
2202  */
2203  return;
2204  }
2205 }
#define write(a, b, c)
Definition: win32.h:14

References EAGAIN, EINTR, EWOULDBLOCK, selfpipe_writefd, and write.

Referenced by latch_sigurg_handler(), and SetLatch().

◆ SetLatch()

void SetLatch ( Latch latch)

Definition at line 607 of file latch.c.

608 {
609 #ifndef WIN32
610  pid_t owner_pid;
611 #else
612  HANDLE handle;
613 #endif
614 
615  /*
616  * The memory barrier has to be placed here to ensure that any flag
617  * variables possibly changed by this process have been flushed to main
618  * memory, before we check/set is_set.
619  */
621 
622  /* Quick exit if already set */
623  if (latch->is_set)
624  return;
625 
626  latch->is_set = true;
627 
629  if (!latch->maybe_sleeping)
630  return;
631 
632 #ifndef WIN32
633 
634  /*
635  * See if anyone's waiting for the latch. It can be the current process if
636  * we're in a signal handler. We use the self-pipe or SIGURG to ourselves
637  * to wake up WaitEventSetWaitBlock() without races in that case. If it's
638  * another process, send a signal.
639  *
640  * Fetch owner_pid only once, in case the latch is concurrently getting
641  * owned or disowned. XXX: This assumes that pid_t is atomic, which isn't
642  * guaranteed to be true! In practice, the effective range of pid_t fits
643  * in a 32 bit integer, and so should be atomic. In the worst case, we
644  * might end up signaling the wrong process. Even then, you're very
645  * unlucky if a process with that bogus pid exists and belongs to
646  * Postgres; and PG database processes should handle excess SIGUSR1
647  * interrupts without a problem anyhow.
648  *
649  * Another sort of race condition that's possible here is for a new
650  * process to own the latch immediately after we look, so we don't signal
651  * it. This is okay so long as all callers of ResetLatch/WaitLatch follow
652  * the standard coding convention of waiting at the bottom of their loops,
653  * not the top, so that they'll correctly process latch-setting events
654  * that happen before they enter the loop.
655  */
656  owner_pid = latch->owner_pid;
657  if (owner_pid == 0)
658  return;
659  else if (owner_pid == MyProcPid)
660  {
661 #if defined(WAIT_USE_SELF_PIPE)
662  if (waiting)
664 #else
665  if (waiting)
666  kill(MyProcPid, SIGURG);
667 #endif
668  }
669  else
670  kill(owner_pid, SIGURG);
671 
672 #else
673 
674  /*
675  * See if anyone's waiting for the latch. It can be the current process if
676  * we're in a signal handler.
677  *
678  * Use a local variable here just in case somebody changes the event field
679  * concurrently (which really should not happen).
680  */
681  handle = latch->event;
682  if (handle)
683  {
684  SetEvent(handle);
685 
686  /*
687  * Note that we silently ignore any errors. We might be in a signal
688  * handler or other critical path where it's not safe to call elog().
689  */
690  }
691 #endif
692 }
#define kill(pid, sig)
Definition: win32_port.h:489

References Latch::is_set, kill, Latch::maybe_sleeping, MyProcPid, Latch::owner_pid, pg_memory_barrier, sendSelfPipeByte(), and waiting.

Referenced by avl_sigusr2_handler(), CheckDeadLockAlert(), ClientCheckTimeoutHandler(), ConditionVariableBroadcast(), ConditionVariableSignal(), die(), ForwardSyncRequest(), handle_pm_child_exit_signal(), handle_pm_pmsignal_signal(), handle_pm_reload_request_signal(), handle_pm_shutdown_request_signal(), handle_sig_alarm(), HandleCatchupInterrupt(), HandleNotifyInterrupt(), HandleParallelApplyMessageInterrupt(), HandleParallelMessageInterrupt(), IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), IdleStatsUpdateTimeoutHandler(), logicalrep_worker_wakeup_ptr(), pgarch_waken_stop(), PgArchWakeup(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), ProcessPendingWrites(), ProcSendSignal(), procsignal_sigusr1_handler(), ProcWakeup(), RecoveryConflictInterrupt(), ReqCheckpointHandler(), RequestXLogStreaming(), shm_mq_detach_internal(), shm_mq_inc_bytes_read(), shm_mq_send_bytes(), shm_mq_sendv(), shm_mq_set_receiver(), shm_mq_set_sender(), SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), sigUsr1Handler(), StatementCancelHandler(), StrategyGetBuffer(), SwitchBackToLocalLatch(), SwitchToSharedLatch(), SyncRepWakeQueue(), test_shm_mq_main(), WakeupRecovery(), WalRcvForceReply(), WalSndLastCycleHandler(), WalSndWaitForWal(), WalSndWakeup(), and XLogSetAsyncXactLSN().

◆ ShutdownLatchSupport()

void ShutdownLatchSupport ( void  )

Definition at line 339 of file latch.c.

340 {
341 #if defined(WAIT_USE_POLL)
342  pqsignal(SIGURG, SIG_IGN);
343 #endif
344 
345  if (LatchWaitSet)
346  {
348  LatchWaitSet = NULL;
349  }
350 
351 #if defined(WAIT_USE_SELF_PIPE)
354  selfpipe_readfd = -1;
355  selfpipe_writefd = -1;
357 #endif
358 
359 #if defined(WAIT_USE_SIGNALFD)
360  close(signal_fd);
361  signal_fd = -1;
362 #endif
363 }
void FreeWaitEventSet(WaitEventSet *set)
Definition: latch.c:837
#define InvalidPid
Definition: miscadmin.h:32

References close, FreeWaitEventSet(), InvalidPid, LatchWaitSet, pqsignal(), selfpipe_owner_pid, selfpipe_readfd, selfpipe_writefd, and SIG_IGN.

◆ WaitEventAdjustPoll()

static void WaitEventAdjustPoll ( WaitEventSet set,
WaitEvent event 
)
static

Definition at line 1135 of file latch.c.

1136 {
1137  struct pollfd *pollfd = &set->pollfds[event->pos];
1138 
1139  pollfd->revents = 0;
1140  pollfd->fd = event->fd;
1141 
1142  /* prepare pollfd entry once */
1143  if (event->events == WL_LATCH_SET)
1144  {
1145  Assert(set->latch != NULL);
1146  pollfd->events = POLLIN;
1147  }
1148  else if (event->events == WL_POSTMASTER_DEATH)
1149  {
1150  pollfd->events = POLLIN;
1151  }
1152  else
1153  {
1154  Assert(event->events & (WL_SOCKET_READABLE |
1156  WL_SOCKET_CLOSED));
1157  pollfd->events = 0;
1158  if (event->events & WL_SOCKET_READABLE)
1159  pollfd->events |= POLLIN;
1160  if (event->events & WL_SOCKET_WRITEABLE)
1161  pollfd->events |= POLLOUT;
1162 #ifdef POLLRDHUP
1163  if (event->events & WL_SOCKET_CLOSED)
1164  pollfd->events |= POLLRDHUP;
1165 #endif
1166  }
1167 
1168  Assert(event->fd != PGINVALID_SOCKET);
1169 }
#define WL_SOCKET_READABLE
Definition: latch.h:126
#define WL_SOCKET_CLOSED
Definition: latch.h:137
#define WL_SOCKET_WRITEABLE
Definition: latch.h:127

References Assert(), WaitEvent::events, WaitEvent::fd, WaitEventSet::latch, PGINVALID_SOCKET, WaitEventSet::pollfds, WL_LATCH_SET, WL_POSTMASTER_DEATH, WL_SOCKET_CLOSED, WL_SOCKET_READABLE, and WL_SOCKET_WRITEABLE.

Referenced by AddWaitEventToSet(), and ModifyWaitEvent().

◆ WaitEventSetCanReportClosed()

bool WaitEventSetCanReportClosed ( void  )

Definition at line 2138 of file latch.c.

2139 {
2140 #if (defined(WAIT_USE_POLL) && defined(POLLRDHUP)) || \
2141  defined(WAIT_USE_EPOLL) || \
2142  defined(WAIT_USE_KQUEUE)
2143  return true;
2144 #else
2145  return false;
2146 #endif
2147 }

Referenced by check_client_connection_check_interval().

◆ WaitEventSetWait()

int WaitEventSetWait ( WaitEventSet set,
long  timeout,
WaitEvent occurred_events,
int  nevents,
uint32  wait_event_info 
)

Definition at line 1383 of file latch.c.

1386 {
1387  int returned_events = 0;
1389  instr_time cur_time;
1390  long cur_timeout = -1;
1391 
1392  Assert(nevents > 0);
1393 
1394  /*
1395  * Initialize timeout if requested. We must record the current time so
1396  * that we can determine the remaining timeout if interrupted.
1397  */
1398  if (timeout >= 0)
1399  {
1401  Assert(timeout >= 0 && timeout <= INT_MAX);
1402  cur_timeout = timeout;
1403  }
1404  else
1406 
1407  pgstat_report_wait_start(wait_event_info);
1408 
1409 #ifndef WIN32
1410  waiting = true;
1411 #else
1412  /* Ensure that signals are serviced even if latch is already set */
1414 #endif
1415  while (returned_events == 0)
1416  {
1417  int rc;
1418 
1419  /*
1420  * Check if the latch is set already. If so, leave the loop
1421  * immediately, avoid blocking again. We don't attempt to report any
1422  * other events that might also be satisfied.
1423  *
1424  * If someone sets the latch between this and the
1425  * WaitEventSetWaitBlock() below, the setter will write a byte to the
1426  * pipe (or signal us and the signal handler will do that), and the
1427  * readiness routine will return immediately.
1428  *
1429  * On unix, If there's a pending byte in the self pipe, we'll notice
1430  * whenever blocking. Only clearing the pipe in that case avoids
1431  * having to drain it every time WaitLatchOrSocket() is used. Should
1432  * the pipe-buffer fill up we're still ok, because the pipe is in
1433  * nonblocking mode. It's unlikely for that to happen, because the
1434  * self pipe isn't filled unless we're blocking (waiting = true), or
1435  * from inside a signal handler in latch_sigurg_handler().
1436  *
1437  * On windows, we'll also notice if there's a pending event for the
1438  * latch when blocking, but there's no danger of anything filling up,
1439  * as "Setting an event that is already set has no effect.".
1440  *
1441  * Note: we assume that the kernel calls involved in latch management
1442  * will provide adequate synchronization on machines with weak memory
1443  * ordering, so that we cannot miss seeing is_set if a notification
1444  * has already been queued.
1445  */
1446  if (set->latch && !set->latch->is_set)
1447  {
1448  /* about to sleep on a latch */
1449  set->latch->maybe_sleeping = true;
1451  /* and recheck */
1452  }
1453 
1454  if (set->latch && set->latch->is_set)
1455  {
1456  occurred_events->fd = PGINVALID_SOCKET;
1457  occurred_events->pos = set->latch_pos;
1458  occurred_events->user_data =
1459  set->events[set->latch_pos].user_data;
1460  occurred_events->events = WL_LATCH_SET;
1461  occurred_events++;
1462  returned_events++;
1463 
1464  /* could have been set above */
1465  set->latch->maybe_sleeping = false;
1466 
1467  break;
1468  }
1469 
1470  /*
1471  * Wait for events using the readiness primitive chosen at the top of
1472  * this file. If -1 is returned, a timeout has occurred, if 0 we have
1473  * to retry, everything >= 1 is the number of returned events.
1474  */
1475  rc = WaitEventSetWaitBlock(set, cur_timeout,
1476  occurred_events, nevents);
1477 
1478  if (set->latch)
1479  {
1480  Assert(set->latch->maybe_sleeping);
1481  set->latch->maybe_sleeping = false;
1482  }
1483 
1484  if (rc == -1)
1485  break; /* timeout occurred */
1486  else
1487  returned_events = rc;
1488 
1489  /* If we're not done, update cur_timeout for next iteration */
1490  if (returned_events == 0 && timeout >= 0)
1491  {
1492  INSTR_TIME_SET_CURRENT(cur_time);
1493  INSTR_TIME_SUBTRACT(cur_time, start_time);
1494  cur_timeout = timeout - (long) INSTR_TIME_GET_MILLISEC(cur_time);
1495  if (cur_timeout <= 0)
1496  break;
1497  }
1498  }
1499 #ifndef WIN32
1500  waiting = false;
1501 #endif
1502 
1504 
1505  return returned_events;
1506 }
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:122
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:181
#define INSTR_TIME_GET_MILLISEC(t)
Definition: instr_time.h:191
#define INSTR_TIME_SET_ZERO(t)
Definition: instr_time.h:172
static int WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout, WaitEvent *occurred_events, int nevents)
Definition: latch.c:1809
static time_t start_time
Definition: pg_ctl.c:94
void pgwin32_dispatch_queued_signals(void)
Definition: signal.c:120
void * user_data
Definition: latch.h:155
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:271
static void pgstat_report_wait_end(void)
Definition: wait_event.h:287

References Assert(), WaitEventSet::events, WaitEvent::events, WaitEvent::fd, INSTR_TIME_GET_MILLISEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SET_ZERO, INSTR_TIME_SUBTRACT, Latch::is_set, WaitEventSet::latch, WaitEventSet::latch_pos, Latch::maybe_sleeping, pg_memory_barrier, PGINVALID_SOCKET, pgstat_report_wait_end(), pgstat_report_wait_start(), pgwin32_dispatch_queued_signals(), WaitEvent::pos, start_time, WaitEvent::user_data, WaitEventSetWaitBlock(), waiting, and WL_LATCH_SET.

Referenced by ExecAppendAsyncEventWait(), pq_check_connection(), secure_read(), secure_write(), ServerLoop(), SysLoggerMain(), WaitLatch(), WaitLatchOrSocket(), and WalSndWait().

◆ WaitEventSetWaitBlock()

static int WaitEventSetWaitBlock ( WaitEventSet set,
int  cur_timeout,
WaitEvent occurred_events,
int  nevents 
)
inlinestatic

Definition at line 1809 of file latch.c.

1811 {
1812  int returned_events = 0;
1813  int rc;
1814  WaitEvent *cur_event;
1815  struct pollfd *cur_pollfd;
1816 
1817  /* Sleep */
1818  rc = poll(set->pollfds, set->nevents, (int) cur_timeout);
1819 
1820  /* Check return code */
1821  if (rc < 0)
1822  {
1823  /* EINTR is okay, otherwise complain */
1824  if (errno != EINTR)
1825  {
1826  waiting = false;
1827  ereport(ERROR,
1829  errmsg("%s() failed: %m",
1830  "poll")));
1831  }
1832  return 0;
1833  }
1834  else if (rc == 0)
1835  {
1836  /* timeout exceeded */
1837  return -1;
1838  }
1839 
1840  for (cur_event = set->events, cur_pollfd = set->pollfds;
1841  cur_event < (set->events + set->nevents) &&
1842  returned_events < nevents;
1843  cur_event++, cur_pollfd++)
1844  {
1845  /* no activity on this FD, skip */
1846  if (cur_pollfd->revents == 0)
1847  continue;
1848 
1849  occurred_events->pos = cur_event->pos;
1850  occurred_events->user_data = cur_event->user_data;
1851  occurred_events->events = 0;
1852 
1853  if (cur_event->events == WL_LATCH_SET &&
1854  (cur_pollfd->revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL)))
1855  {
1856  /* There's data in the self-pipe, clear it. */
1857  drain();
1858 
1859  if (set->latch && set->latch->is_set)
1860  {
1861  occurred_events->fd = PGINVALID_SOCKET;
1862  occurred_events->events = WL_LATCH_SET;
1863  occurred_events++;
1864  returned_events++;
1865  }
1866  }
1867  else if (cur_event->events == WL_POSTMASTER_DEATH &&
1868  (cur_pollfd->revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL)))
1869  {
1870  /*
1871  * We expect an POLLHUP when the remote end is closed, but because
1872  * we don't expect the pipe to become readable or to have any
1873  * errors either, treat those cases as postmaster death, too.
1874  *
1875  * Be paranoid about a spurious event signaling the postmaster as
1876  * being dead. There have been reports about that happening with
1877  * older primitives (select(2) to be specific), and a spurious
1878  * WL_POSTMASTER_DEATH event would be painful. Re-checking doesn't
1879  * cost much.
1880  */
1882  {
1883  if (set->exit_on_postmaster_death)
1884  proc_exit(1);
1885  occurred_events->fd = PGINVALID_SOCKET;
1886  occurred_events->events = WL_POSTMASTER_DEATH;
1887  occurred_events++;
1888  returned_events++;
1889  }
1890  }
1891  else if (cur_event->events & (WL_SOCKET_READABLE |
1894  {
1895  int errflags = POLLHUP | POLLERR | POLLNVAL;
1896 
1897  Assert(cur_event->fd >= PGINVALID_SOCKET);
1898 
1899  if ((cur_event->events & WL_SOCKET_READABLE) &&
1900  (cur_pollfd->revents & (POLLIN | errflags)))
1901  {
1902  /* data available in socket, or EOF */
1903  occurred_events->events |= WL_SOCKET_READABLE;
1904  }
1905 
1906  if ((cur_event->events & WL_SOCKET_WRITEABLE) &&
1907  (cur_pollfd->revents & (POLLOUT | errflags)))
1908  {
1909  /* writeable, or EOF */
1910  occurred_events->events |= WL_SOCKET_WRITEABLE;
1911  }
1912 
1913 #ifdef POLLRDHUP
1914  if ((cur_event->events & WL_SOCKET_CLOSED) &&
1915  (cur_pollfd->revents & (POLLRDHUP | errflags)))
1916  {
1917  /* remote peer closed, or error */
1918  occurred_events->events |= WL_SOCKET_CLOSED;
1919  }
1920 #endif
1921 
1922  if (occurred_events->events != 0)
1923  {
1924  occurred_events->fd = cur_event->fd;
1925  occurred_events++;
1926  returned_events++;
1927  }
1928  }
1929  }
1930  return returned_events;
1931 }
int errcode_for_socket_access(void)
Definition: elog.c:952
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ereport(elevel,...)
Definition: elog.h:149
void proc_exit(int code)
Definition: ipc.c:104
static void drain(void)
Definition: latch.c:2219
bool PostmasterIsAliveInternal(void)
Definition: pmsignal.c:376

References Assert(), drain(), EINTR, ereport, errcode_for_socket_access(), errmsg(), ERROR, WaitEventSet::events, WaitEvent::events, WaitEventSet::exit_on_postmaster_death, WaitEvent::fd, Latch::is_set, WaitEventSet::latch, WaitEventSet::nevents, PGINVALID_SOCKET, WaitEventSet::pollfds, WaitEvent::pos, PostmasterIsAliveInternal(), proc_exit(), WaitEvent::user_data, waiting, WL_LATCH_SET, WL_POSTMASTER_DEATH, WL_SOCKET_CLOSED, WL_SOCKET_READABLE, and WL_SOCKET_WRITEABLE.

Referenced by WaitEventSetWait().

◆ WaitLatch()

int WaitLatch ( Latch latch,
int  wakeEvents,
long  timeout,
uint32  wait_event_info 
)

Definition at line 492 of file latch.c.

494 {
495  WaitEvent event;
496 
497  /* Postmaster-managed callers must handle postmaster death somehow. */
499  (wakeEvents & WL_EXIT_ON_PM_DEATH) ||
500  (wakeEvents & WL_POSTMASTER_DEATH));
501 
502  /*
503  * Some callers may have a latch other than MyLatch, or no latch at all,
504  * or want to handle postmaster death differently. It's cheap to assign
505  * those, so just do it every time.
506  */
507  if (!(wakeEvents & WL_LATCH_SET))
508  latch = NULL;
511  ((wakeEvents & WL_EXIT_ON_PM_DEATH) != 0);
512 
514  (wakeEvents & WL_TIMEOUT) ? timeout : -1,
515  &event, 1,
516  wait_event_info) == 0)
517  return WL_TIMEOUT;
518  else
519  return event.events;
520 }
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:1008
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:1383
#define WL_TIMEOUT
Definition: latch.h:128

References Assert(), WaitEventSet::exit_on_postmaster_death, IsUnderPostmaster, LatchWaitSet, LatchWaitSetLatchPos, ModifyWaitEvent(), WaitEventSetWait(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_POSTMASTER_DEATH, and WL_TIMEOUT.

Referenced by ApplyLauncherMain(), autoprewarm_main(), AutoVacLauncherMain(), BackgroundWriterMain(), CheckpointerMain(), CheckpointWriteDelay(), ConditionVariableTimedSleep(), do_pg_backup_stop(), gather_readnext(), lazy_truncate_heap(), LogicalParallelApplyLoop(), logicalrep_worker_stop_internal(), mq_putmessage(), pa_send_data(), pa_wait_for_xact_state(), pg_promote(), pg_sleep(), pg_wait_until_termination(), pgarch_MainLoop(), ProcSleep(), ProcWaitForSignal(), recoveryApplyDelay(), RegisterSyncRequest(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), SyncRepWaitForLSN(), test_shm_mq_pipelined(), throttle(), wait_for_relation_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), WaitForWALToBecomeAvailable(), WalRcvWaitForStartPosition(), and WalWriterMain().

◆ WaitLatchOrSocket()

int WaitLatchOrSocket ( Latch latch,
int  wakeEvents,
pgsocket  sock,
long  timeout,
uint32  wait_event_info 
)

Definition at line 540 of file latch.c.

542 {
543  int ret = 0;
544  int rc;
545  WaitEvent event;
547 
548  if (wakeEvents & WL_TIMEOUT)
549  Assert(timeout >= 0);
550  else
551  timeout = -1;
552 
553  if (wakeEvents & WL_LATCH_SET)
555  latch, NULL);
556 
557  /* Postmaster-managed callers must handle postmaster death somehow. */
559  (wakeEvents & WL_EXIT_ON_PM_DEATH) ||
560  (wakeEvents & WL_POSTMASTER_DEATH));
561 
562  if ((wakeEvents & WL_POSTMASTER_DEATH) && IsUnderPostmaster)
564  NULL, NULL);
565 
566  if ((wakeEvents & WL_EXIT_ON_PM_DEATH) && IsUnderPostmaster)
568  NULL, NULL);
569 
570  if (wakeEvents & WL_SOCKET_MASK)
571  {
572  int ev;
573 
574  ev = wakeEvents & WL_SOCKET_MASK;
575  AddWaitEventToSet(set, ev, sock, NULL, NULL);
576  }
577 
578  rc = WaitEventSetWait(set, timeout, &event, 1, wait_event_info);
579 
580  if (rc == 0)
581  ret |= WL_TIMEOUT;
582  else
583  {
584  ret |= event.events & (WL_LATCH_SET |
587  }
588 
589  FreeWaitEventSet(set);
590 
591  return ret;
592 }
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135

References AddWaitEventToSet(), Assert(), CreateWaitEventSet(), CurrentMemoryContext, FreeWaitEventSet(), IsUnderPostmaster, PGINVALID_SOCKET, WaitEventSetWait(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_POSTMASTER_DEATH, WL_SOCKET_MASK, and WL_TIMEOUT.

Referenced by be_tls_open_server(), copy_read_data(), libpqrcv_PQgetResult(), libpqsrv_connect_internal(), LogicalRepApplyLoop(), pgfdw_get_cleanup_result(), pgfdw_get_result(), read_or_wait(), secure_open_gssapi(), and WalReceiverMain().

Variable Documentation

◆ LatchWaitSet

WaitEventSet* LatchWaitSet
static

Definition at line 155 of file latch.c.

Referenced by InitializeLatchWaitSet(), ShutdownLatchSupport(), and WaitLatch().

◆ selfpipe_owner_pid

int selfpipe_owner_pid = 0
static

Definition at line 176 of file latch.c.

Referenced by InitializeLatchSupport(), InitLatch(), OwnLatch(), and ShutdownLatchSupport().

◆ selfpipe_readfd

int selfpipe_readfd = -1
static

◆ selfpipe_writefd

int selfpipe_writefd = -1
static

Definition at line 173 of file latch.c.

Referenced by InitializeLatchSupport(), sendSelfPipeByte(), and ShutdownLatchSupport().

◆ waiting