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)
 

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

Typedef Documentation

Definition at line 142 of file latch.h.

Function Documentation

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

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

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

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

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

609 {
610 #if defined(WAIT_USE_EPOLL)
611  close(set->epoll_fd);
612 #elif defined(WAIT_USE_WIN32)
613  WaitEvent *cur_event;
614 
615  for (cur_event = set->events;
616  cur_event < (set->events + set->nevents);
617  cur_event++)
618  {
619  if (cur_event->events & WL_LATCH_SET)
620  {
621  /* uses the latch's HANDLE */
622  }
623  else if (cur_event->events & WL_POSTMASTER_DEATH)
624  {
625  /* uses PostmasterHandle */
626  }
627  else
628  {
629  /* Clean up the event object we created for the socket */
630  WSAEventSelect(cur_event->fd, NULL, 0);
631  WSACloseEvent(set->handles[cur_event->pos + 1]);
632  }
633  }
634 #endif
635 
636  pfree(set);
637 }
pgsocket fd
Definition: latch.h:134
int pos
Definition: latch.h:132
void pfree(void *pointer)
Definition: mcxt.c:950
uint32 events
Definition: latch.h:133
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:675
#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:675
#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 1467 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().

1468 {
1469  if (waiting)
1470  sendSelfPipeByte();
1471 }
static void sendSelfPipeByte(void)
Definition: latch.c:1477
static volatile sig_atomic_t waiting
Definition: latch.c:115
void ModifyWaitEvent ( WaitEventSet set,
int  pos,
uint32  events,
Latch latch 
)

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

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

Definition at line 498 of file latch.c.

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

Referenced by ApplyLauncherMain(), 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().

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

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

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

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