PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
latch.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <unistd.h>
#include <sys/time.h>
#include "miscadmin.h"
#include "pgstat.h"
#include "port/atomics.h"
#include "portability/instr_time.h"
#include "postmaster/postmaster.h"
#include "storage/latch.h"
#include "storage/pmsignal.h"
#include "storage/shmem.h"
Include dependency graph for latch.c:

Go to the source code of this file.

Data Structures

struct  WaitEventSet
 

Functions

static void sendSelfPipeByte (void)
 
static void drainSelfPipe (void)
 
static int WaitEventSetWaitBlock (WaitEventSet *set, int cur_timeout, WaitEvent *occurred_events, int nevents)
 
void InitializeLatchSupport (void)
 
void InitLatch (volatile Latch *latch)
 
void InitSharedLatch (volatile Latch *latch)
 
void OwnLatch (volatile Latch *latch)
 
void DisownLatch (volatile Latch *latch)
 
int WaitLatch (volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
 
int WaitLatchOrSocket (volatile Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
 
void SetLatch (volatile Latch *latch)
 
void ResetLatch (volatile Latch *latch)
 
WaitEventSetCreateWaitEventSet (MemoryContext context, int nevents)
 
void FreeWaitEventSet (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)
 
void latch_sigusr1_handler (void)
 

Variables

static volatile sig_atomic_t waiting = false
 
static int selfpipe_readfd = -1
 
static int selfpipe_writefd = -1
 

Function Documentation

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

Definition at line 612 of file latch.c.

References Assert, elog, ERROR, WaitEventSet::events, 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, WL_LATCH_SET, WL_POSTMASTER_DEATH, WL_SOCKET_READABLE, and WL_SOCKET_WRITEABLE.

Referenced by ConditionVariablePrepareToSleep(), pq_init(), and WaitLatchOrSocket().

614 {
615  WaitEvent *event;
616 
617  /* not enough space */
618  Assert(set->nevents < set->nevents_space);
619 
620  if (latch)
621  {
622  if (latch->owner_pid != MyProcPid)
623  elog(ERROR, "cannot wait on a latch owned by another process");
624  if (set->latch)
625  elog(ERROR, "cannot wait on more than one latch");
626  if ((events & WL_LATCH_SET) != WL_LATCH_SET)
627  elog(ERROR, "latch events only support being set");
628  }
629  else
630  {
631  if (events & WL_LATCH_SET)
632  elog(ERROR, "cannot wait on latch without a specified latch");
633  }
634 
635  /* waiting for socket readiness without a socket indicates a bug */
636  if (fd == PGINVALID_SOCKET &&
638  elog(ERROR, "cannot wait on socket event without a socket");
639 
640  event = &set->events[set->nevents];
641  event->pos = set->nevents++;
642  event->fd = fd;
643  event->events = events;
644  event->user_data = user_data;
645 #ifdef WIN32
646  event->reset = false;
647 #endif
648 
649  if (events == WL_LATCH_SET)
650  {
651  set->latch = latch;
652  set->latch_pos = event->pos;
653 #ifndef WIN32
654  event->fd = selfpipe_readfd;
655 #endif
656  }
657  else if (events == WL_POSTMASTER_DEATH)
658  {
659 #ifndef WIN32
661 #endif
662  }
663 
664  /* perform wait primitive specific initialization, if needed */
665 #if defined(WAIT_USE_EPOLL)
666  WaitEventAdjustEpoll(set, event, EPOLL_CTL_ADD);
667 #elif defined(WAIT_USE_POLL)
668  WaitEventAdjustPoll(set, event);
669 #elif defined(WAIT_USE_SELECT)
670  /* nothing to do */
671 #elif defined(WAIT_USE_WIN32)
672  WaitEventAdjustWin32(set, event);
673 #endif
674 
675  return event->pos;
676 }
int latch_pos
Definition: latch.c:105
#define WL_SOCKET_WRITEABLE
Definition: latch.h:126
int MyProcPid
Definition: globals.c:38
int pos
Definition: latch.h:132
#define WL_SOCKET_READABLE
Definition: latch.h:125
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define ERROR
Definition: elog.h:43
static int selfpipe_readfd
Definition: latch.c:130
int nevents
Definition: latch.c:89
int postmaster_alive_fds[2]
Definition: postmaster.c:556
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
#define PGINVALID_SOCKET
Definition: port.h:24
#define Assert(condition)
Definition: c.h:671
WaitEvent * events
Definition: latch.c:96
int nevents_space
Definition: latch.c:90
int owner_pid
Definition: latch.h:114
#define elog
Definition: elog.h:219
Latch * latch
Definition: latch.c:104
#define WL_LATCH_SET
Definition: latch.h:124
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:42
WaitEventSet* CreateWaitEventSet ( MemoryContext  context,
int  nevents 
)

Definition at line 484 of file latch.c.

References elog, ERROR, WaitEventSet::events, WaitEventSet::latch, MAXALIGN, MemoryContextAllocZero(), WaitEventSet::nevents_space, NULL, pgwin32_signal_event, and StaticAssertStmt.

Referenced by ConditionVariablePrepareToSleep(), pq_init(), and WaitLatchOrSocket().

485 {
486  WaitEventSet *set;
487  char *data;
488  Size sz = 0;
489 
490  /*
491  * Use MAXALIGN size/alignment to guarantee that later uses of memory are
492  * aligned correctly. E.g. epoll_event might need 8 byte alignment on some
493  * platforms, but earlier allocations like WaitEventSet and WaitEvent
494  * might not sized to guarantee that when purely using sizeof().
495  */
496  sz += MAXALIGN(sizeof(WaitEventSet));
497  sz += MAXALIGN(sizeof(WaitEvent) * nevents);
498 
499 #if defined(WAIT_USE_EPOLL)
500  sz += MAXALIGN(sizeof(struct epoll_event) * nevents);
501 #elif defined(WAIT_USE_POLL)
502  sz += MAXALIGN(sizeof(struct pollfd) * nevents);
503 #elif defined(WAIT_USE_WIN32)
504  /* need space for the pgwin32_signal_event */
505  sz += MAXALIGN(sizeof(HANDLE) * (nevents + 1));
506 #endif
507 
508  data = (char *) MemoryContextAllocZero(context, sz);
509 
510  set = (WaitEventSet *) data;
511  data += MAXALIGN(sizeof(WaitEventSet));
512 
513  set->events = (WaitEvent *) data;
514  data += MAXALIGN(sizeof(WaitEvent) * nevents);
515 
516 #if defined(WAIT_USE_EPOLL)
517  set->epoll_ret_events = (struct epoll_event *) data;
518  data += MAXALIGN(sizeof(struct epoll_event) * nevents);
519 #elif defined(WAIT_USE_POLL)
520  set->pollfds = (struct pollfd *) data;
521  data += MAXALIGN(sizeof(struct pollfd) * nevents);
522 #elif defined(WAIT_USE_WIN32)
523  set->handles = (HANDLE) data;
524  data += MAXALIGN(sizeof(HANDLE) * nevents);
525 #endif
526 
527  set->latch = NULL;
528  set->nevents_space = nevents;
529 
530 #if defined(WAIT_USE_EPOLL)
531  set->epoll_fd = epoll_create(nevents);
532  if (set->epoll_fd < 0)
533  elog(ERROR, "epoll_create failed: %m");
534 #elif defined(WAIT_USE_WIN32)
535 
536  /*
537  * To handle signals while waiting, we need to add a win32 specific event.
538  * We accounted for the additional event at the top of this routine. See
539  * port/win32/signal.c for more details.
540  *
541  * Note: pgwin32_signal_event should be first to ensure that it will be
542  * reported when multiple events are set. We want to guarantee that
543  * pending signals are serviced.
544  */
545  set->handles[0] = pgwin32_signal_event;
546  StaticAssertStmt(WSA_INVALID_EVENT == NULL, "");
547 #endif
548 
549  return set;
550 }
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:753
HANDLE pgwin32_signal_event
Definition: signal.c:27
#define ERROR
Definition: elog.h:43
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:784
#define NULL
Definition: c.h:226
WaitEvent * events
Definition: latch.c:96
size_t Size
Definition: c.h:353
#define MAXALIGN(LEN)
Definition: c.h:584
int nevents_space
Definition: latch.c:90
#define elog
Definition: elog.h:219
Latch * latch
Definition: latch.c:104
void DisownLatch ( volatile Latch latch)

Definition at line 272 of file latch.c.

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

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

273 {
274  Assert(latch->is_shared);
275  Assert(latch->owner_pid == MyProcPid);
276 
277  latch->owner_pid = 0;
278 }
int MyProcPid
Definition: globals.c:38
#define Assert(condition)
Definition: c.h:671
static void drainSelfPipe ( void  )
static

Definition at line 1589 of file latch.c.

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

1590 {
1591  /*
1592  * There shouldn't normally be more than one byte in the pipe, or maybe a
1593  * few bytes if multiple processes run SetLatch at the same instant.
1594  */
1595  char buf[16];
1596  int rc;
1597 
1598  for (;;)
1599  {
1600  rc = read(selfpipe_readfd, buf, sizeof(buf));
1601  if (rc < 0)
1602  {
1603  if (errno == EAGAIN || errno == EWOULDBLOCK)
1604  break; /* the pipe is empty */
1605  else if (errno == EINTR)
1606  continue; /* retry */
1607  else
1608  {
1609  waiting = false;
1610  elog(ERROR, "read() on self-pipe failed: %m");
1611  }
1612  }
1613  else if (rc == 0)
1614  {
1615  waiting = false;
1616  elog(ERROR, "unexpected EOF on self-pipe");
1617  }
1618  else if (rc < sizeof(buf))
1619  {
1620  /* we successfully drained the pipe; no need to read() again */
1621  break;
1622  }
1623  /* else buffer wasn't big enough, so read again */
1624  }
1625 }
#define EWOULDBLOCK
Definition: win32.h:301
#define EAGAIN
Definition: win32.h:293
#define ERROR
Definition: elog.h:43
static int selfpipe_readfd
Definition: latch.c:130
static char * buf
Definition: pg_test_fsync.c:65
#define EINTR
Definition: win32.h:295
#define elog
Definition: elog.h:219
static volatile sig_atomic_t waiting
Definition: latch.c:127
#define read(a, b, c)
Definition: win32.h:18
void FreeWaitEventSet ( WaitEventSet set)

Definition at line 556 of file latch.c.

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

Referenced by WaitLatchOrSocket().

557 {
558 #if defined(WAIT_USE_EPOLL)
559  close(set->epoll_fd);
560 #elif defined(WAIT_USE_WIN32)
561  WaitEvent *cur_event;
562 
563  for (cur_event = set->events;
564  cur_event < (set->events + set->nevents);
565  cur_event++)
566  {
567  if (cur_event->events & WL_LATCH_SET)
568  {
569  /* uses the latch's HANDLE */
570  }
571  else if (cur_event->events & WL_POSTMASTER_DEATH)
572  {
573  /* uses PostmasterHandle */
574  }
575  else
576  {
577  /* Clean up the event object we created for the socket */
578  WSAEventSelect(cur_event->fd, NULL, 0);
579  WSACloseEvent(set->handles[cur_event->pos + 1]);
580  }
581  }
582 #endif
583 
584  pfree(set);
585 }
pgsocket fd
Definition: latch.h:134
int pos
Definition: latch.h:132
void pfree(void *pointer)
Definition: mcxt.c:992
uint32 events
Definition: latch.h:133
int nevents
Definition: latch.c:89
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
#define NULL
Definition: c.h:226
WaitEvent * events
Definition: latch.c:96
#define close(a)
Definition: win32.h:17
#define WL_LATCH_SET
Definition: latch.h:124
void InitializeLatchSupport ( void  )

Definition at line 156 of file latch.c.

References Assert, elog, FATAL, selfpipe_readfd, and selfpipe_writefd.

Referenced by InitPostmasterChild(), and InitStandaloneProcess().

157 {
158 #ifndef WIN32
159  int pipefd[2];
160 
161  Assert(selfpipe_readfd == -1);
162 
163  /*
164  * Set up the self-pipe that allows a signal handler to wake up the
165  * select() in WaitLatch. Make the write-end non-blocking, so that
166  * SetLatch won't block if the event has already been set many times
167  * filling the kernel buffer. Make the read-end non-blocking too, so that
168  * we can easily clear the pipe by reading until EAGAIN or EWOULDBLOCK.
169  */
170  if (pipe(pipefd) < 0)
171  elog(FATAL, "pipe() failed: %m");
172  if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) < 0)
173  elog(FATAL, "fcntl() failed on read-end of self-pipe: %m");
174  if (fcntl(pipefd[1], F_SETFL, O_NONBLOCK) < 0)
175  elog(FATAL, "fcntl() failed on write-end of self-pipe: %m");
176 
177  selfpipe_readfd = pipefd[0];
178  selfpipe_writefd = pipefd[1];
179 #else
180  /* currently, nothing to do here for Windows */
181 #endif
182 }
static int selfpipe_writefd
Definition: latch.c:131
#define FATAL
Definition: elog.h:52
static int selfpipe_readfd
Definition: latch.c:130
#define Assert(condition)
Definition: c.h:671
#define elog
Definition: elog.h:219
void InitLatch ( volatile Latch latch)

Definition at line 188 of file latch.c.

References Assert, elog, ERROR, FALSE, Latch::is_set, Latch::is_shared, MyProcPid, NULL, Latch::owner_pid, selfpipe_readfd, and TRUE.

Referenced by InitPostmasterChild(), and InitStandaloneProcess().

189 {
190  latch->is_set = false;
191  latch->owner_pid = MyProcPid;
192  latch->is_shared = false;
193 
194 #ifndef WIN32
195  /* Assert InitializeLatchSupport has been called in this process */
196  Assert(selfpipe_readfd >= 0);
197 #else
198  latch->event = CreateEvent(NULL, TRUE, FALSE, NULL);
199  if (latch->event == NULL)
200  elog(ERROR, "CreateEvent failed: error code %lu", GetLastError());
201 #endif /* WIN32 */
202 }
int MyProcPid
Definition: globals.c:38
#define ERROR
Definition: elog.h:43
#define FALSE
Definition: c.h:218
static int selfpipe_readfd
Definition: latch.c:130
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define TRUE
Definition: c.h:214
#define elog
Definition: elog.h:219
void InitSharedLatch ( volatile Latch latch)

Definition at line 216 of file latch.c.

References elog, ERROR, FALSE, Latch::is_set, Latch::is_shared, NULL, Latch::owner_pid, and TRUE.

Referenced by InitProcGlobal(), and XLOGShmemInit().

217 {
218 #ifdef WIN32
219  SECURITY_ATTRIBUTES sa;
220 
221  /*
222  * Set up security attributes to specify that the events are inherited.
223  */
224  ZeroMemory(&sa, sizeof(sa));
225  sa.nLength = sizeof(sa);
226  sa.bInheritHandle = TRUE;
227 
228  latch->event = CreateEvent(&sa, TRUE, FALSE, NULL);
229  if (latch->event == NULL)
230  elog(ERROR, "CreateEvent failed: error code %lu", GetLastError());
231 #endif
232 
233  latch->is_set = false;
234  latch->owner_pid = 0;
235  latch->is_shared = true;
236 }
#define ERROR
Definition: elog.h:43
#define FALSE
Definition: c.h:218
#define NULL
Definition: c.h:226
#define TRUE
Definition: c.h:214
#define elog
Definition: elog.h:219
void latch_sigusr1_handler ( void  )

Definition at line 1540 of file latch.c.

References sendSelfPipeByte(), and waiting.

Referenced by bgworker_sigusr1_handler(), bgwriter_sigusr1_handler(), chkpt_sigusr1_handler(), procsignal_sigusr1_handler(), StartupProcSigUsr1Handler(), WalRcvSigUsr1Handler(), WalSndXLogSendHandler(), and walwriter_sigusr1_handler().

1541 {
1542  if (waiting)
1543  sendSelfPipeByte();
1544 }
static void sendSelfPipeByte(void)
Definition: latch.c:1550
static volatile sig_atomic_t waiting
Definition: latch.c:127
void ModifyWaitEvent ( WaitEventSet set,
int  pos,
uint32  events,
Latch latch 
)

Definition at line 685 of file latch.c.

References Assert, elog, ERROR, WaitEventSet::events, WaitEvent::events, WaitEventSet::latch, WL_LATCH_SET, and WL_POSTMASTER_DEATH.

Referenced by secure_read(), secure_write(), SwitchBackToLocalLatch(), and SwitchToSharedLatch().

686 {
687  WaitEvent *event;
688 
689  Assert(pos < set->nevents);
690 
691  event = &set->events[pos];
692 
693  /*
694  * If neither the event mask nor the associated latch changes, return
695  * early. That's an important optimization for some sockets, where
696  * ModifyWaitEvent is frequently used to switch from waiting for reads to
697  * waiting on writes.
698  */
699  if (events == event->events &&
700  (!(event->events & WL_LATCH_SET) || set->latch == latch))
701  return;
702 
703  if (event->events & WL_LATCH_SET &&
704  events != event->events)
705  {
706  /* we could allow to disable latch events for a while */
707  elog(ERROR, "cannot modify latch event");
708  }
709 
710  if (event->events & WL_POSTMASTER_DEATH)
711  {
712  elog(ERROR, "cannot modify postmaster death event");
713  }
714 
715  /* FIXME: validate event mask */
716  event->events = events;
717 
718  if (events == WL_LATCH_SET)
719  {
720  set->latch = latch;
721  }
722 
723 #if defined(WAIT_USE_EPOLL)
724  WaitEventAdjustEpoll(set, event, EPOLL_CTL_MOD);
725 #elif defined(WAIT_USE_POLL)
726  WaitEventAdjustPoll(set, event);
727 #elif defined(WAIT_USE_SELECT)
728  /* nothing to do */
729 #elif defined(WAIT_USE_WIN32)
730  WaitEventAdjustWin32(set, event);
731 #endif
732 }
#define ERROR
Definition: elog.h:43
uint32 events
Definition: latch.h:133
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
#define Assert(condition)
Definition: c.h:671
WaitEvent * events
Definition: latch.c:96
#define elog
Definition: elog.h:219
Latch * latch
Definition: latch.c:104
#define WL_LATCH_SET
Definition: latch.h:124
void OwnLatch ( volatile Latch latch)

Definition at line 252 of file latch.c.

References Assert, elog, ERROR, Latch::is_shared, MyProcPid, Latch::owner_pid, and selfpipe_readfd.

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

253 {
254  /* Sanity checks */
255  Assert(latch->is_shared);
256 
257 #ifndef WIN32
258  /* Assert InitializeLatchSupport has been called in this process */
259  Assert(selfpipe_readfd >= 0);
260 #endif
261 
262  if (latch->owner_pid != 0)
263  elog(ERROR, "latch already owned");
264 
265  latch->owner_pid = MyProcPid;
266 }
int MyProcPid
Definition: globals.c:38
#define ERROR
Definition: elog.h:43
static int selfpipe_readfd
Definition: latch.c:130
#define Assert(condition)
Definition: c.h:671
#define elog
Definition: elog.h:219
void ResetLatch ( volatile Latch latch)

Definition at line 461 of file latch.c.

References Assert, Latch::is_set, MyProcPid, Latch::owner_pid, and pg_memory_barrier.

Referenced by ApplyLauncherMain(), ApplyLoop(), AutoVacLauncherMain(), BackgroundWriterMain(), CheckpointerMain(), ConditionVariablePrepareToSleep(), ConditionVariableSleep(), gather_readnext(), libpqrcv_PQexec(), logicalrep_worker_stop(), mq_putmessage(), pg_sleep(), pgarch_MainLoop(), pgfdw_get_result(), PgstatCollectorMain(), ProcSleep(), ProcWaitForSignal(), recoveryApplyDelay(), secure_read(), secure_write(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), SyncRepWaitForLSN(), SysLoggerMain(), test_shm_mq_pipelined(), throttle(), wait_for_workers_to_become_ready(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), WaitForWALToBecomeAvailable(), WalRcvWaitForStartPosition(), WalReceiverMain(), WalSndLoop(), WalSndWaitForWal(), WalSndWriteData(), and WalWriterMain().

462 {
463  /* Only the owner should reset the latch */
464  Assert(latch->owner_pid == MyProcPid);
465 
466  latch->is_set = false;
467 
468  /*
469  * Ensure that the write to is_set gets flushed to main memory before we
470  * examine any flag variables. Otherwise a concurrent SetLatch might
471  * falsely conclude that it needn't signal us, even though we have missed
472  * seeing some flag updates that SetLatch was supposed to inform us of.
473  */
475 }
int MyProcPid
Definition: globals.c:38
#define pg_memory_barrier()
Definition: atomics.h:147
#define Assert(condition)
Definition: c.h:671
static void sendSelfPipeByte ( void  )
static

Definition at line 1550 of file latch.c.

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

Referenced by latch_sigusr1_handler(), and SetLatch().

1551 {
1552  int rc;
1553  char dummy = 0;
1554 
1555 retry:
1556  rc = write(selfpipe_writefd, &dummy, 1);
1557  if (rc < 0)
1558  {
1559  /* If interrupted by signal, just retry */
1560  if (errno == EINTR)
1561  goto retry;
1562 
1563  /*
1564  * If the pipe is full, we don't need to retry, the data that's there
1565  * already is enough to wake up WaitLatch.
1566  */
1567  if (errno == EAGAIN || errno == EWOULDBLOCK)
1568  return;
1569 
1570  /*
1571  * Oops, the write() failed for some other reason. We might be in a
1572  * signal handler, so it's not safe to elog(). We have no choice but
1573  * silently ignore the error.
1574  */
1575  return;
1576  }
1577 }
#define EWOULDBLOCK
Definition: win32.h:301
static int selfpipe_writefd
Definition: latch.c:131
#define write(a, b, c)
Definition: win32.h:19
#define EAGAIN
Definition: win32.h:293
#define EINTR
Definition: win32.h:295
void SetLatch ( volatile Latch latch)

Definition at line 379 of file latch.c.

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

Referenced by ArchSigHupHandler(), ArchSigTermHandler(), av_sighup_handler(), avl_sigterm_handler(), avl_sigusr2_handler(), BgSigHupHandler(), CheckDeadLockAlert(), ChkptSigHupHandler(), ConditionVariableSignal(), die(), ForwardFsyncRequest(), handle_sig_alarm(), handle_sigterm(), HandleCatchupInterrupt(), HandleNotifyInterrupt(), HandleParallelMessageInterrupt(), IdleInTransactionSessionTimeoutHandler(), logicalrep_worker_sigterm(), pgarch_waken(), pgarch_waken_stop(), pgstat_exit(), pgstat_sighup_handler(), ProcSendSignal(), procsignal_sigusr1_handler(), ProcWakeup(), RecoveryConflictInterrupt(), ReqCheckpointHandler(), ReqShutdownHandler(), RequestXLogStreaming(), shm_mq_detach(), shm_mq_inc_bytes_read(), shm_mq_notify_receiver(), shm_mq_set_receiver(), shm_mq_set_sender(), sigHupHandler(), SigHupHandler(), sigUsr1Handler(), StatementCancelHandler(), StrategyGetBuffer(), SwitchBackToLocalLatch(), SwitchToSharedLatch(), SyncRepWakeQueue(), test_shm_mq_main(), WakeupRecovery(), WalRcvForceReply(), WalRcvShutdownHandler(), WalShutdownHandler(), WalSigHupHandler(), WalSndLastCycleHandler(), WalSndSigHupHandler(), WalSndWaitForWal(), WalSndWakeup(), WalSndWriteData(), worker_spi_sighup(), worker_spi_sigterm(), and XLogSetAsyncXactLSN().

380 {
381 #ifndef WIN32
382  pid_t owner_pid;
383 #else
384  HANDLE handle;
385 #endif
386 
387  /*
388  * The memory barrier has to be placed here to ensure that any flag
389  * variables possibly changed by this process have been flushed to main
390  * memory, before we check/set is_set.
391  */
393 
394  /* Quick exit if already set */
395  if (latch->is_set)
396  return;
397 
398  latch->is_set = true;
399 
400 #ifndef WIN32
401 
402  /*
403  * See if anyone's waiting for the latch. It can be the current process if
404  * we're in a signal handler. We use the self-pipe to wake up the select()
405  * in that case. If it's another process, send a signal.
406  *
407  * Fetch owner_pid only once, in case the latch is concurrently getting
408  * owned or disowned. XXX: This assumes that pid_t is atomic, which isn't
409  * guaranteed to be true! In practice, the effective range of pid_t fits
410  * in a 32 bit integer, and so should be atomic. In the worst case, we
411  * might end up signaling the wrong process. Even then, you're very
412  * unlucky if a process with that bogus pid exists and belongs to
413  * Postgres; and PG database processes should handle excess SIGUSR1
414  * interrupts without a problem anyhow.
415  *
416  * Another sort of race condition that's possible here is for a new
417  * process to own the latch immediately after we look, so we don't signal
418  * it. This is okay so long as all callers of ResetLatch/WaitLatch follow
419  * the standard coding convention of waiting at the bottom of their loops,
420  * not the top, so that they'll correctly process latch-setting events
421  * that happen before they enter the loop.
422  */
423  owner_pid = latch->owner_pid;
424  if (owner_pid == 0)
425  return;
426  else if (owner_pid == MyProcPid)
427  {
428  if (waiting)
430  }
431  else
432  kill(owner_pid, SIGUSR1);
433 #else
434 
435  /*
436  * See if anyone's waiting for the latch. It can be the current process if
437  * we're in a signal handler.
438  *
439  * Use a local variable here just in case somebody changes the event field
440  * concurrently (which really should not happen).
441  */
442  handle = latch->event;
443  if (handle)
444  {
445  SetEvent(handle);
446 
447  /*
448  * Note that we silently ignore any errors. We might be in a signal
449  * handler or other critical path where it's not safe to call elog().
450  */
451  }
452 #endif
453 
454 }
#define SIGUSR1
Definition: win32.h:211
int MyProcPid
Definition: globals.c:38
static void sendSelfPipeByte(void)
Definition: latch.c:1550
#define pg_memory_barrier()
Definition: atomics.h:147
static volatile sig_atomic_t waiting
Definition: latch.c:127
int WaitEventSetWait ( WaitEventSet set,
long  timeout,
WaitEvent occurred_events,
int  nevents,
uint32  wait_event_info 
)

Definition at line 870 of file latch.c.

References Assert, WaitEventSet::events, WaitEvent::events, WaitEvent::fd, INSTR_TIME_GET_MILLISEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, Latch::is_set, WaitEventSet::latch, WaitEventSet::latch_pos, 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 ConditionVariableSleep(), secure_read(), secure_write(), and WaitLatchOrSocket().

873 {
874  int returned_events = 0;
876  instr_time cur_time;
877  long cur_timeout = -1;
878 
879  Assert(nevents > 0);
880 
881  /*
882  * Initialize timeout if requested. We must record the current time so
883  * that we can determine the remaining timeout if interrupted.
884  */
885  if (timeout >= 0)
886  {
887  INSTR_TIME_SET_CURRENT(start_time);
888  Assert(timeout >= 0 && timeout <= INT_MAX);
889  cur_timeout = timeout;
890  }
891 
892  pgstat_report_wait_start(wait_event_info);
893 
894 #ifndef WIN32
895  waiting = true;
896 #else
897  /* Ensure that signals are serviced even if latch is already set */
899 #endif
900  while (returned_events == 0)
901  {
902  int rc;
903 
904  /*
905  * Check if the latch is set already. If so, leave the loop
906  * immediately, avoid blocking again. We don't attempt to report any
907  * other events that might also be satisfied.
908  *
909  * If someone sets the latch between this and the
910  * WaitEventSetWaitBlock() below, the setter will write a byte to the
911  * pipe (or signal us and the signal handler will do that), and the
912  * readiness routine will return immediately.
913  *
914  * On unix, If there's a pending byte in the self pipe, we'll notice
915  * whenever blocking. Only clearing the pipe in that case avoids
916  * having to drain it every time WaitLatchOrSocket() is used. Should
917  * the pipe-buffer fill up we're still ok, because the pipe is in
918  * nonblocking mode. It's unlikely for that to happen, because the
919  * self pipe isn't filled unless we're blocking (waiting = true), or
920  * from inside a signal handler in latch_sigusr1_handler().
921  *
922  * On windows, we'll also notice if there's a pending event for the
923  * latch when blocking, but there's no danger of anything filling up,
924  * as "Setting an event that is already set has no effect.".
925  *
926  * Note: we assume that the kernel calls involved in latch management
927  * will provide adequate synchronization on machines with weak memory
928  * ordering, so that we cannot miss seeing is_set if a notification
929  * has already been queued.
930  */
931  if (set->latch && set->latch->is_set)
932  {
933  occurred_events->fd = PGINVALID_SOCKET;
934  occurred_events->pos = set->latch_pos;
935  occurred_events->user_data =
936  set->events[set->latch_pos].user_data;
937  occurred_events->events = WL_LATCH_SET;
938  occurred_events++;
939  returned_events++;
940 
941  break;
942  }
943 
944  /*
945  * Wait for events using the readiness primitive chosen at the top of
946  * this file. If -1 is returned, a timeout has occurred, if 0 we have
947  * to retry, everything >= 1 is the number of returned events.
948  */
949  rc = WaitEventSetWaitBlock(set, cur_timeout,
950  occurred_events, nevents);
951 
952  if (rc == -1)
953  break; /* timeout occurred */
954  else
955  returned_events = rc;
956 
957  /* If we're not done, update cur_timeout for next iteration */
958  if (returned_events == 0 && timeout >= 0)
959  {
960  INSTR_TIME_SET_CURRENT(cur_time);
961  INSTR_TIME_SUBTRACT(cur_time, start_time);
962  cur_timeout = timeout - (long) INSTR_TIME_GET_MILLISEC(cur_time);
963  if (cur_timeout <= 0)
964  break;
965  }
966  }
967 #ifndef WIN32
968  waiting = false;
969 #endif
970 
972 
973  return returned_events;
974 }
int latch_pos
Definition: latch.c:105
pgsocket fd
Definition: latch.h:134
int pos
Definition: latch.h:132
#define INSTR_TIME_GET_MILLISEC(t)
Definition: instr_time.h:199
struct timeval instr_time
Definition: instr_time.h:147
static time_t start_time
Definition: pg_ctl.c:91
void pgwin32_dispatch_queued_signals(void)
Definition: signal.c:107
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:167
uint32 events
Definition: latch.h:133
static int WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout, WaitEvent *occurred_events, int nevents)
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1124
#define PGINVALID_SOCKET
Definition: port.h:24
#define Assert(condition)
Definition: c.h:671
WaitEvent * events
Definition: latch.c:96
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1100
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
void * user_data
Definition: latch.h:135
sig_atomic_t is_set
Definition: latch.h:112
Latch * latch
Definition: latch.c:104
#define WL_LATCH_SET
Definition: latch.h:124
static volatile sig_atomic_t waiting
Definition: latch.c:127
static int WaitEventSetWaitBlock ( WaitEventSet set,
int  cur_timeout,
WaitEvent occurred_events,
int  nevents 
)
inlinestatic

Referenced by WaitEventSetWait().

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

Definition at line 320 of file latch.c.

References AddWaitEventToSet(), Assert, CreateWaitEventSet(), CurrentMemoryContext, FreeWaitEventSet(), NULL, PGINVALID_SOCKET, WaitEventSetWait(), WL_LATCH_SET, WL_POSTMASTER_DEATH, WL_SOCKET_READABLE, WL_SOCKET_WRITEABLE, and WL_TIMEOUT.

Referenced by ApplyLoop(), be_tls_open_server(), libpqrcv_PQexec(), pgfdw_get_result(), PgstatCollectorMain(), SysLoggerMain(), WaitLatch(), WalReceiverMain(), WalSndLoop(), WalSndWaitForWal(), and WalSndWriteData().

322 {
323  int ret = 0;
324  int rc;
325  WaitEvent event;
327 
328  if (wakeEvents & WL_TIMEOUT)
329  Assert(timeout >= 0);
330  else
331  timeout = -1;
332 
333  if (wakeEvents & WL_LATCH_SET)
334  AddWaitEventToSet(set, WL_LATCH_SET, PGINVALID_SOCKET,
335  (Latch *) latch, NULL);
336 
337  if (wakeEvents & WL_POSTMASTER_DEATH)
338  AddWaitEventToSet(set, WL_POSTMASTER_DEATH, PGINVALID_SOCKET,
339  NULL, NULL);
340 
341  if (wakeEvents & (WL_SOCKET_READABLE | WL_SOCKET_WRITEABLE))
342  {
343  int ev;
344 
345  ev = wakeEvents & (WL_SOCKET_READABLE | WL_SOCKET_WRITEABLE);
346  AddWaitEventToSet(set, ev, sock, NULL, NULL);
347  }
348 
349  rc = WaitEventSetWait(set, timeout, &event, 1, wait_event_info);
350 
351  if (rc == 0)
352  ret |= WL_TIMEOUT;
353  else
354  {
355  ret |= event.events & (WL_LATCH_SET |
356  WL_POSTMASTER_DEATH |
359  }
360 
361  FreeWaitEventSet(set);
362 
363  return ret;
364 }
#define WL_SOCKET_WRITEABLE
Definition: latch.h:126
void FreeWaitEventSet(WaitEventSet *set)
Definition: latch.c:556
#define WL_TIMEOUT
Definition: latch.h:127
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:612
#define WL_SOCKET_READABLE
Definition: latch.h:125
WaitEventSet * CreateWaitEventSet(MemoryContext context, int nevents)
Definition: latch.c:484
Definition: latch.h:110
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
#define PGINVALID_SOCKET
Definition: port.h:24
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define WL_LATCH_SET
Definition: latch.h:124
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:870

Variable Documentation

int selfpipe_readfd = -1
static
int selfpipe_writefd = -1
static

Definition at line 131 of file latch.c.

Referenced by InitializeLatchSupport(), and sendSelfPipeByte().

volatile sig_atomic_t waiting = false
static