PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
latch.h File Reference
#include <signal.h>
Include dependency graph for latch.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  Latch
 
struct  WaitEvent
 

Macros

#define WL_LATCH_SET   (1 << 0)
 
#define WL_SOCKET_READABLE   (1 << 1)
 
#define WL_SOCKET_WRITEABLE   (1 << 2)
 
#define WL_TIMEOUT   (1 << 3) /* not for WaitEventSetWait() */
 
#define WL_POSTMASTER_DEATH   (1 << 4)
 
#define WL_SOCKET_CONNECTED   WL_SOCKET_WRITEABLE
 
#define WL_SOCKET_MASK
 

Typedefs

typedef struct Latch Latch
 
typedef struct WaitEvent WaitEvent
 
typedef struct WaitEventSet WaitEventSet
 

Functions

void InitializeLatchSupport (void)
 
void InitLatch (volatile Latch *latch)
 
void InitSharedLatch (volatile Latch *latch)
 
void OwnLatch (volatile Latch *latch)
 
void DisownLatch (volatile Latch *latch)
 
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)
 
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 latch_sigusr1_handler (void)
 

Macro Definition Documentation

#define WL_SOCKET_CONNECTED   WL_SOCKET_WRITEABLE

Definition at line 133 of file latch.h.

Referenced by libpqrcv_connect().

#define WL_SOCKET_MASK
Value:
#define WL_SOCKET_WRITEABLE
Definition: latch.h:126
#define WL_SOCKET_READABLE
Definition: latch.h:125
#define WL_SOCKET_CONNECTED
Definition: latch.h:133

Definition at line 136 of file latch.h.

Referenced by AddWaitEventToSet(), and WaitLatchOrSocket().

#define WL_SOCKET_WRITEABLE   (1 << 2)

Typedef Documentation

Definition at line 152 of file latch.h.

Function Documentation

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

Definition at line 666 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, and WL_SOCKET_MASK.

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

668 {
669  WaitEvent *event;
670 
671  /* not enough space */
672  Assert(set->nevents < set->nevents_space);
673 
674  if (latch)
675  {
676  if (latch->owner_pid != MyProcPid)
677  elog(ERROR, "cannot wait on a latch owned by another process");
678  if (set->latch)
679  elog(ERROR, "cannot wait on more than one latch");
680  if ((events & WL_LATCH_SET) != WL_LATCH_SET)
681  elog(ERROR, "latch events only support being set");
682  }
683  else
684  {
685  if (events & WL_LATCH_SET)
686  elog(ERROR, "cannot wait on latch without a specified latch");
687  }
688 
689  /* waiting for socket readiness without a socket indicates a bug */
690  if (fd == PGINVALID_SOCKET && (events & WL_SOCKET_MASK))
691  elog(ERROR, "cannot wait on socket event without a socket");
692 
693  event = &set->events[set->nevents];
694  event->pos = set->nevents++;
695  event->fd = fd;
696  event->events = events;
697  event->user_data = user_data;
698 #ifdef WIN32
699  event->reset = false;
700 #endif
701 
702  if (events == WL_LATCH_SET)
703  {
704  set->latch = latch;
705  set->latch_pos = event->pos;
706 #ifndef WIN32
707  event->fd = selfpipe_readfd;
708 #endif
709  }
710  else if (events == WL_POSTMASTER_DEATH)
711  {
712 #ifndef WIN32
714 #endif
715  }
716 
717  /* perform wait primitive specific initialization, if needed */
718 #if defined(WAIT_USE_EPOLL)
719  WaitEventAdjustEpoll(set, event, EPOLL_CTL_ADD);
720 #elif defined(WAIT_USE_POLL)
721  WaitEventAdjustPoll(set, event);
722 #elif defined(WAIT_USE_WIN32)
723  WaitEventAdjustWin32(set, event);
724 #endif
725 
726  return event->pos;
727 }
int latch_pos
Definition: latch.c:93
int MyProcPid
Definition: globals.c:39
int pos
Definition: latch.h:142
#define WL_SOCKET_MASK
Definition: latch.h:136
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:118
int nevents
Definition: latch.c:77
int postmaster_alive_fds[2]
Definition: postmaster.c:563
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
#define PGINVALID_SOCKET
Definition: port.h:24
#define Assert(condition)
Definition: c.h:676
WaitEvent * events
Definition: latch.c:84
int nevents_space
Definition: latch.c:78
int owner_pid
Definition: latch.h:114
#define elog
Definition: elog.h:219
Latch * latch
Definition: latch.c:92
#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 520 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().

521 {
522  WaitEventSet *set;
523  char *data;
524  Size sz = 0;
525 
526  /*
527  * Use MAXALIGN size/alignment to guarantee that later uses of memory are
528  * aligned correctly. E.g. epoll_event might need 8 byte alignment on some
529  * platforms, but earlier allocations like WaitEventSet and WaitEvent
530  * might not sized to guarantee that when purely using sizeof().
531  */
532  sz += MAXALIGN(sizeof(WaitEventSet));
533  sz += MAXALIGN(sizeof(WaitEvent) * nevents);
534 
535 #if defined(WAIT_USE_EPOLL)
536  sz += MAXALIGN(sizeof(struct epoll_event) * nevents);
537 #elif defined(WAIT_USE_POLL)
538  sz += MAXALIGN(sizeof(struct pollfd) * nevents);
539 #elif defined(WAIT_USE_WIN32)
540  /* need space for the pgwin32_signal_event */
541  sz += MAXALIGN(sizeof(HANDLE) * (nevents + 1));
542 #endif
543 
544  data = (char *) MemoryContextAllocZero(context, sz);
545 
546  set = (WaitEventSet *) data;
547  data += MAXALIGN(sizeof(WaitEventSet));
548 
549  set->events = (WaitEvent *) data;
550  data += MAXALIGN(sizeof(WaitEvent) * nevents);
551 
552 #if defined(WAIT_USE_EPOLL)
553  set->epoll_ret_events = (struct epoll_event *) data;
554  data += MAXALIGN(sizeof(struct epoll_event) * nevents);
555 #elif defined(WAIT_USE_POLL)
556  set->pollfds = (struct pollfd *) data;
557  data += MAXALIGN(sizeof(struct pollfd) * nevents);
558 #elif defined(WAIT_USE_WIN32)
559  set->handles = (HANDLE) data;
560  data += MAXALIGN(sizeof(HANDLE) * nevents);
561 #endif
562 
563  set->latch = NULL;
564  set->nevents_space = nevents;
565 
566 #if defined(WAIT_USE_EPOLL)
567 #ifdef EPOLL_CLOEXEC
568  set->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
569  if (set->epoll_fd < 0)
570  elog(ERROR, "epoll_create1 failed: %m");
571 #else
572  /* cope with ancient glibc lacking epoll_create1 (e.g., RHEL5) */
573  set->epoll_fd = epoll_create(nevents);
574  if (set->epoll_fd < 0)
575  elog(ERROR, "epoll_create failed: %m");
576  if (fcntl(set->epoll_fd, F_SETFD, FD_CLOEXEC) == -1)
577  elog(ERROR, "fcntl(F_SETFD) failed on epoll descriptor: %m");
578 #endif /* EPOLL_CLOEXEC */
579 #elif defined(WAIT_USE_WIN32)
580 
581  /*
582  * To handle signals while waiting, we need to add a win32 specific event.
583  * We accounted for the additional event at the top of this routine. See
584  * port/win32/signal.c for more details.
585  *
586  * Note: pgwin32_signal_event should be first to ensure that it will be
587  * reported when multiple events are set. We want to guarantee that
588  * pending signals are serviced.
589  */
590  set->handles[0] = pgwin32_signal_event;
591  StaticAssertStmt(WSA_INVALID_EVENT == NULL, "");
592 #endif
593 
594  return set;
595 }
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:758
HANDLE pgwin32_signal_event
Definition: signal.c:27
#define ERROR
Definition: elog.h:43
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:742
#define NULL
Definition: c.h:229
WaitEvent * events
Definition: latch.c:84
size_t Size
Definition: c.h:356
#define MAXALIGN(LEN)
Definition: c.h:588
int nevents_space
Definition: latch.c:78
#define elog
Definition: elog.h:219
Latch * latch
Definition: latch.c:92
void DisownLatch ( volatile Latch latch)

Definition at line 308 of file latch.c.

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

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

309 {
310  Assert(latch->is_shared);
311  Assert(latch->owner_pid == MyProcPid);
312 
313  latch->owner_pid = 0;
314 }
int MyProcPid
Definition: globals.c:39
#define Assert(condition)
Definition: c.h:676
void FreeWaitEventSet ( WaitEventSet set)

Definition at line 607 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().

608 {
609 #if defined(WAIT_USE_EPOLL)
610  close(set->epoll_fd);
611 #elif defined(WAIT_USE_WIN32)
612  WaitEvent *cur_event;
613 
614  for (cur_event = set->events;
615  cur_event < (set->events + set->nevents);
616  cur_event++)
617  {
618  if (cur_event->events & WL_LATCH_SET)
619  {
620  /* uses the latch's HANDLE */
621  }
622  else if (cur_event->events & WL_POSTMASTER_DEATH)
623  {
624  /* uses PostmasterHandle */
625  }
626  else
627  {
628  /* Clean up the event object we created for the socket */
629  WSAEventSelect(cur_event->fd, NULL, 0);
630  WSACloseEvent(set->handles[cur_event->pos + 1]);
631  }
632  }
633 #endif
634 
635  pfree(set);
636 }
pgsocket fd
Definition: latch.h:144
int pos
Definition: latch.h:142
void pfree(void *pointer)
Definition: mcxt.c:950
uint32 events
Definition: latch.h:143
int nevents
Definition: latch.c:77
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
#define NULL
Definition: c.h:229
WaitEvent * events
Definition: latch.c:84
#define close(a)
Definition: win32.h:12
#define WL_LATCH_SET
Definition: latch.h:124
void InitializeLatchSupport ( void  )

Definition at line 147 of file latch.c.

References Assert, close, elog, FATAL, IsUnderPostmaster, MyProcPid, selfpipe_owner_pid, selfpipe_readfd, and selfpipe_writefd.

Referenced by InitPostmasterChild(), and InitStandaloneProcess().

148 {
149 #ifndef WIN32
150  int pipefd[2];
151 
152  if (IsUnderPostmaster)
153  {
154  /*
155  * We might have inherited connections to a self-pipe created by the
156  * postmaster. It's critical that child processes create their own
157  * self-pipes, of course, and we really want them to close the
158  * inherited FDs for safety's sake.
159  */
160  if (selfpipe_owner_pid != 0)
161  {
162  /* Assert we go through here but once in a child process */
164  /* Release postmaster's pipe FDs; ignore any error */
165  (void) close(selfpipe_readfd);
166  (void) close(selfpipe_writefd);
167  /* Clean up, just for safety's sake; we'll set these below */
169  selfpipe_owner_pid = 0;
170  }
171  else
172  {
173  /*
174  * Postmaster didn't create a self-pipe ... or else we're in an
175  * EXEC_BACKEND build, in which case it doesn't matter since the
176  * postmaster's pipe FDs were closed by the action of FD_CLOEXEC.
177  */
178  Assert(selfpipe_readfd == -1);
179  }
180  }
181  else
182  {
183  /* In postmaster or standalone backend, assert we do this but once */
184  Assert(selfpipe_readfd == -1);
186  }
187 
188  /*
189  * Set up the self-pipe that allows a signal handler to wake up the
190  * poll()/epoll_wait() in WaitLatch. Make the write-end non-blocking, so
191  * that SetLatch won't block if the event has already been set many times
192  * filling the kernel buffer. Make the read-end non-blocking too, so that
193  * we can easily clear the pipe by reading until EAGAIN or EWOULDBLOCK.
194  * Also, make both FDs close-on-exec, since we surely do not want any
195  * child processes messing with them.
196  */
197  if (pipe(pipefd) < 0)
198  elog(FATAL, "pipe() failed: %m");
199  if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) == -1)
200  elog(FATAL, "fcntl(F_SETFL) failed on read-end of self-pipe: %m");
201  if (fcntl(pipefd[1], F_SETFL, O_NONBLOCK) == -1)
202  elog(FATAL, "fcntl(F_SETFL) failed on write-end of self-pipe: %m");
203  if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) == -1)
204  elog(FATAL, "fcntl(F_SETFD) failed on read-end of self-pipe: %m");
205  if (fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) == -1)
206  elog(FATAL, "fcntl(F_SETFD) failed on write-end of self-pipe: %m");
207 
208  selfpipe_readfd = pipefd[0];
209  selfpipe_writefd = pipefd[1];
211 #else
212  /* currently, nothing to do here for Windows */
213 #endif
214 }
int MyProcPid
Definition: globals.c:39
static int selfpipe_writefd
Definition: latch.c:119
#define FATAL
Definition: elog.h:52
static int selfpipe_readfd
Definition: latch.c:118
bool IsUnderPostmaster
Definition: globals.c:101
#define Assert(condition)
Definition: c.h:676
#define elog
Definition: elog.h:219
#define close(a)
Definition: win32.h:12
static int selfpipe_owner_pid
Definition: latch.c:122
void InitLatch ( volatile Latch latch)

Definition at line 220 of file latch.c.

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

Referenced by InitPostmasterChild(), and InitStandaloneProcess().

221 {
222  latch->is_set = false;
223  latch->owner_pid = MyProcPid;
224  latch->is_shared = false;
225 
226 #ifndef WIN32
227  /* Assert InitializeLatchSupport has been called in this process */
229 #else
230  latch->event = CreateEvent(NULL, TRUE, FALSE, NULL);
231  if (latch->event == NULL)
232  elog(ERROR, "CreateEvent failed: error code %lu", GetLastError());
233 #endif /* WIN32 */
234 }
int MyProcPid
Definition: globals.c:39
#define ERROR
Definition: elog.h:43
#define FALSE
Definition: c.h:221
static int selfpipe_readfd
Definition: latch.c:118
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define TRUE
Definition: c.h:217
#define elog
Definition: elog.h:219
static int selfpipe_owner_pid
Definition: latch.c:122
void InitSharedLatch ( volatile Latch latch)

Definition at line 252 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().

253 {
254 #ifdef WIN32
255  SECURITY_ATTRIBUTES sa;
256 
257  /*
258  * Set up security attributes to specify that the events are inherited.
259  */
260  ZeroMemory(&sa, sizeof(sa));
261  sa.nLength = sizeof(sa);
262  sa.bInheritHandle = TRUE;
263 
264  latch->event = CreateEvent(&sa, TRUE, FALSE, NULL);
265  if (latch->event == NULL)
266  elog(ERROR, "CreateEvent failed: error code %lu", GetLastError());
267 #endif
268 
269  latch->is_set = false;
270  latch->owner_pid = 0;
271  latch->is_shared = true;
272 }
#define ERROR
Definition: elog.h:43
#define FALSE
Definition: c.h:221
#define NULL
Definition: c.h:229
#define TRUE
Definition: c.h:217
#define elog
Definition: elog.h:219
void latch_sigusr1_handler ( void  )

Definition at line 1473 of file latch.c.

References sendSelfPipeByte(), and waiting.

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

1474 {
1475  if (waiting)
1476  sendSelfPipeByte();
1477 }
static void sendSelfPipeByte(void)
Definition: latch.c:1483
static volatile sig_atomic_t waiting
Definition: latch.c:115
void ModifyWaitEvent ( WaitEventSet set,
int  pos,
uint32  events,
Latch latch 
)

Definition at line 736 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().

737 {
738  WaitEvent *event;
739 
740  Assert(pos < set->nevents);
741 
742  event = &set->events[pos];
743 
744  /*
745  * If neither the event mask nor the associated latch changes, return
746  * early. That's an important optimization for some sockets, where
747  * ModifyWaitEvent is frequently used to switch from waiting for reads to
748  * waiting on writes.
749  */
750  if (events == event->events &&
751  (!(event->events & WL_LATCH_SET) || set->latch == latch))
752  return;
753 
754  if (event->events & WL_LATCH_SET &&
755  events != event->events)
756  {
757  /* we could allow to disable latch events for a while */
758  elog(ERROR, "cannot modify latch event");
759  }
760 
761  if (event->events & WL_POSTMASTER_DEATH)
762  {
763  elog(ERROR, "cannot modify postmaster death event");
764  }
765 
766  /* FIXME: validate event mask */
767  event->events = events;
768 
769  if (events == WL_LATCH_SET)
770  {
771  set->latch = latch;
772  }
773 
774 #if defined(WAIT_USE_EPOLL)
775  WaitEventAdjustEpoll(set, event, EPOLL_CTL_MOD);
776 #elif defined(WAIT_USE_POLL)
777  WaitEventAdjustPoll(set, event);
778 #elif defined(WAIT_USE_WIN32)
779  WaitEventAdjustWin32(set, event);
780 #endif
781 }
#define ERROR
Definition: elog.h:43
uint32 events
Definition: latch.h:143
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
#define Assert(condition)
Definition: c.h:676
WaitEvent * events
Definition: latch.c:84
#define elog
Definition: elog.h:219
Latch * latch
Definition: latch.c:92
#define WL_LATCH_SET
Definition: latch.h:124
void OwnLatch ( volatile Latch latch)

Definition at line 288 of file latch.c.

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

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

289 {
290  /* Sanity checks */
291  Assert(latch->is_shared);
292 
293 #ifndef WIN32
294  /* Assert InitializeLatchSupport has been called in this process */
296 #endif
297 
298  if (latch->owner_pid != 0)
299  elog(ERROR, "latch already owned");
300 
301  latch->owner_pid = MyProcPid;
302 }
int MyProcPid
Definition: globals.c:39
#define ERROR
Definition: elog.h:43
static int selfpipe_readfd
Definition: latch.c:118
#define Assert(condition)
Definition: c.h:676
#define elog
Definition: elog.h:219
static int selfpipe_owner_pid
Definition: latch.c:122
void ResetLatch ( volatile Latch latch)

Definition at line 497 of file latch.c.

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

Referenced by ApplyLauncherMain(), autoprewarm_main(), AutoVacLauncherMain(), BackgroundWriterMain(), CheckpointerMain(), ConditionVariablePrepareToSleep(), ConditionVariableSleep(), copy_read_data(), gather_readnext(), libpqrcv_connect(), libpqrcv_PQexec(), logicalrep_worker_stop(), LogicalRepApplyLoop(), mq_putmessage(), pg_sleep(), pgarch_MainLoop(), pgfdw_get_cleanup_result(), 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_relation_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), WaitForWALToBecomeAvailable(), WalRcvWaitForStartPosition(), WalReceiverMain(), WalSndLoop(), WalSndWaitForWal(), WalSndWriteData(), and WalWriterMain().

498 {
499  /* Only the owner should reset the latch */
500  Assert(latch->owner_pid == MyProcPid);
501 
502  latch->is_set = false;
503 
504  /*
505  * Ensure that the write to is_set gets flushed to main memory before we
506  * examine any flag variables. Otherwise a concurrent SetLatch might
507  * falsely conclude that it needn't signal us, even though we have missed
508  * seeing some flag updates that SetLatch was supposed to inform us of.
509  */
511 }
int MyProcPid
Definition: globals.c:39
#define pg_memory_barrier()
Definition: atomics.h:148
#define Assert(condition)
Definition: c.h:676
void SetLatch ( volatile Latch latch)

Definition at line 414 of file latch.c.

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

Referenced by apw_sighup_handler(), apw_sigterm_handler(), 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_launcher_sighup(), logicalrep_worker_sighup(), logicalrep_worker_wakeup_ptr(), pgarch_waken(), pgarch_waken_stop(), pgstat_exit(), pgstat_sighup_handler(), PostgresSigHupHandler(), 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(), sigUsr1Handler(), StatementCancelHandler(), StrategyGetBuffer(), SwitchBackToLocalLatch(), SwitchToSharedLatch(), SyncRepWakeQueue(), test_shm_mq_main(), WakeupRecovery(), WalRcvForceReply(), WalRcvShutdownHandler(), WalShutdownHandler(), WalSigHupHandler(), WalSndLastCycleHandler(), WalSndWaitForWal(), WalSndWakeup(), WalSndWriteData(), worker_spi_sighup(), worker_spi_sigterm(), and XLogSetAsyncXactLSN().

415 {
416 #ifndef WIN32
417  pid_t owner_pid;
418 #else
419  HANDLE handle;
420 #endif
421 
422  /*
423  * The memory barrier has to be placed here to ensure that any flag
424  * variables possibly changed by this process have been flushed to main
425  * memory, before we check/set is_set.
426  */
428 
429  /* Quick exit if already set */
430  if (latch->is_set)
431  return;
432 
433  latch->is_set = true;
434 
435 #ifndef WIN32
436 
437  /*
438  * See if anyone's waiting for the latch. It can be the current process if
439  * we're in a signal handler. We use the self-pipe to wake up the
440  * poll()/epoll_wait() in that case. If it's another process, send a
441  * signal.
442  *
443  * Fetch owner_pid only once, in case the latch is concurrently getting
444  * owned or disowned. XXX: This assumes that pid_t is atomic, which isn't
445  * guaranteed to be true! In practice, the effective range of pid_t fits
446  * in a 32 bit integer, and so should be atomic. In the worst case, we
447  * might end up signaling the wrong process. Even then, you're very
448  * unlucky if a process with that bogus pid exists and belongs to
449  * Postgres; and PG database processes should handle excess SIGUSR1
450  * interrupts without a problem anyhow.
451  *
452  * Another sort of race condition that's possible here is for a new
453  * process to own the latch immediately after we look, so we don't signal
454  * it. This is okay so long as all callers of ResetLatch/WaitLatch follow
455  * the standard coding convention of waiting at the bottom of their loops,
456  * not the top, so that they'll correctly process latch-setting events
457  * that happen before they enter the loop.
458  */
459  owner_pid = latch->owner_pid;
460  if (owner_pid == 0)
461  return;
462  else if (owner_pid == MyProcPid)
463  {
464  if (waiting)
466  }
467  else
468  kill(owner_pid, SIGUSR1);
469 #else
470 
471  /*
472  * See if anyone's waiting for the latch. It can be the current process if
473  * we're in a signal handler.
474  *
475  * Use a local variable here just in case somebody changes the event field
476  * concurrently (which really should not happen).
477  */
478  handle = latch->event;
479  if (handle)
480  {
481  SetEvent(handle);
482 
483  /*
484  * Note that we silently ignore any errors. We might be in a signal
485  * handler or other critical path where it's not safe to call elog().
486  */
487  }
488 #endif
489 
490 }
#define SIGUSR1
Definition: win32.h:202
int MyProcPid
Definition: globals.c:39
static void sendSelfPipeByte(void)
Definition: latch.c:1483
#define pg_memory_barrier()
Definition: atomics.h:148
static volatile sig_atomic_t waiting
Definition: latch.c:115
int WaitEventSetWait ( WaitEventSet set,
long  timeout,
WaitEvent occurred_events,
int  nevents,
uint32  wait_event_info 
)

Definition at line 921 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().

924 {
925  int returned_events = 0;
927  instr_time cur_time;
928  long cur_timeout = -1;
929 
930  Assert(nevents > 0);
931 
932  /*
933  * Initialize timeout if requested. We must record the current time so
934  * that we can determine the remaining timeout if interrupted.
935  */
936  if (timeout >= 0)
937  {
938  INSTR_TIME_SET_CURRENT(start_time);
939  Assert(timeout >= 0 && timeout <= INT_MAX);
940  cur_timeout = timeout;
941  }
942 
943  pgstat_report_wait_start(wait_event_info);
944 
945 #ifndef WIN32
946  waiting = true;
947 #else
948  /* Ensure that signals are serviced even if latch is already set */
950 #endif
951  while (returned_events == 0)
952  {
953  int rc;
954 
955  /*
956  * Check if the latch is set already. If so, leave the loop
957  * immediately, avoid blocking again. We don't attempt to report any
958  * other events that might also be satisfied.
959  *
960  * If someone sets the latch between this and the
961  * WaitEventSetWaitBlock() below, the setter will write a byte to the
962  * pipe (or signal us and the signal handler will do that), and the
963  * readiness routine will return immediately.
964  *
965  * On unix, If there's a pending byte in the self pipe, we'll notice
966  * whenever blocking. Only clearing the pipe in that case avoids
967  * having to drain it every time WaitLatchOrSocket() is used. Should
968  * the pipe-buffer fill up we're still ok, because the pipe is in
969  * nonblocking mode. It's unlikely for that to happen, because the
970  * self pipe isn't filled unless we're blocking (waiting = true), or
971  * from inside a signal handler in latch_sigusr1_handler().
972  *
973  * On windows, we'll also notice if there's a pending event for the
974  * latch when blocking, but there's no danger of anything filling up,
975  * as "Setting an event that is already set has no effect.".
976  *
977  * Note: we assume that the kernel calls involved in latch management
978  * will provide adequate synchronization on machines with weak memory
979  * ordering, so that we cannot miss seeing is_set if a notification
980  * has already been queued.
981  */
982  if (set->latch && set->latch->is_set)
983  {
984  occurred_events->fd = PGINVALID_SOCKET;
985  occurred_events->pos = set->latch_pos;
986  occurred_events->user_data =
987  set->events[set->latch_pos].user_data;
988  occurred_events->events = WL_LATCH_SET;
989  occurred_events++;
990  returned_events++;
991 
992  break;
993  }
994 
995  /*
996  * Wait for events using the readiness primitive chosen at the top of
997  * this file. If -1 is returned, a timeout has occurred, if 0 we have
998  * to retry, everything >= 1 is the number of returned events.
999  */
1000  rc = WaitEventSetWaitBlock(set, cur_timeout,
1001  occurred_events, nevents);
1002 
1003  if (rc == -1)
1004  break; /* timeout occurred */
1005  else
1006  returned_events = rc;
1007 
1008  /* If we're not done, update cur_timeout for next iteration */
1009  if (returned_events == 0 && timeout >= 0)
1010  {
1011  INSTR_TIME_SET_CURRENT(cur_time);
1012  INSTR_TIME_SUBTRACT(cur_time, start_time);
1013  cur_timeout = timeout - (long) INSTR_TIME_GET_MILLISEC(cur_time);
1014  if (cur_timeout <= 0)
1015  break;
1016  }
1017  }
1018 #ifndef WIN32
1019  waiting = false;
1020 #endif
1021 
1023 
1024  return returned_events;
1025 }
int latch_pos
Definition: latch.c:93
pgsocket fd
Definition: latch.h:144
int pos
Definition: latch.h:142
#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:103
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:143
static int WaitEventSetWaitBlock(WaitEventSet *set, int cur_timeout, WaitEvent *occurred_events, int nevents)
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1235
#define PGINVALID_SOCKET
Definition: port.h:24
#define Assert(condition)
Definition: c.h:676
WaitEvent * events
Definition: latch.c:84
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1211
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
void * user_data
Definition: latch.h:145
sig_atomic_t is_set
Definition: latch.h:112
Latch * latch
Definition: latch.c:92
#define WL_LATCH_SET
Definition: latch.h:124
static volatile sig_atomic_t waiting
Definition: latch.c:115
int WaitLatchOrSocket ( volatile Latch latch,
int  wakeEvents,
pgsocket  sock,
long  timeout,
uint32  wait_event_info 
)

Definition at line 356 of file latch.c.

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

Referenced by be_tls_open_server(), copy_read_data(), libpqrcv_connect(), libpqrcv_PQexec(), LogicalRepApplyLoop(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PgstatCollectorMain(), SysLoggerMain(), WaitLatch(), WalReceiverMain(), WalSndLoop(), WalSndWaitForWal(), and WalSndWriteData().

358 {
359  int ret = 0;
360  int rc;
361  WaitEvent event;
363 
364  if (wakeEvents & WL_TIMEOUT)
365  Assert(timeout >= 0);
366  else
367  timeout = -1;
368 
369  if (wakeEvents & WL_LATCH_SET)
370  AddWaitEventToSet(set, WL_LATCH_SET, PGINVALID_SOCKET,
371  (Latch *) latch, NULL);
372 
373  if (wakeEvents & WL_POSTMASTER_DEATH && IsUnderPostmaster)
375  NULL, NULL);
376 
377  if (wakeEvents & WL_SOCKET_MASK)
378  {
379  int ev;
380 
381  ev = wakeEvents & WL_SOCKET_MASK;
382  AddWaitEventToSet(set, ev, sock, NULL, NULL);
383  }
384 
385  rc = WaitEventSetWait(set, timeout, &event, 1, wait_event_info);
386 
387  if (rc == 0)
388  ret |= WL_TIMEOUT;
389  else
390  {
391  ret |= event.events & (WL_LATCH_SET |
394  }
395 
396  FreeWaitEventSet(set);
397 
398  return ret;
399 }
void FreeWaitEventSet(WaitEventSet *set)
Definition: latch.c:607
#define WL_TIMEOUT
Definition: latch.h:127
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:666
#define WL_SOCKET_MASK
Definition: latch.h:136
WaitEventSet * CreateWaitEventSet(MemoryContext context, int nevents)
Definition: latch.c:520
Definition: latch.h:110
bool IsUnderPostmaster
Definition: globals.c:101
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:229
#define Assert(condition)
Definition: c.h:676
#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:921