1 /*-------------------------------------------------------------------------
4 * Routines for inter-process latches
6 * A latch is a boolean variable, with operations that let you to sleep
7 * until it is set. A latch can be set from another process, or a signal
8 * handler within the same process.
10 * The latch interface is a reliable replacement for the common pattern of
11 * using pg_usleep() or select() to wait until a signal arrives, where the
12 * signal handler sets a global variable. Because on some platforms, an
13 * incoming signal doesn't interrupt sleep, and even on platforms where it
14 * does there is a race condition if the signal arrives just before
15 * entering the sleep, the common pattern must periodically wake up and
16 * poll the global variable. pselect() system call was invented to solve
17 * the problem, but it is not portable enough. Latches are designed to
18 * overcome these limitations, allowing you to sleep without polling and
19 * ensuring a quick response to signals from other processes.
21 * There are two kinds of latches: local and shared. A local latch is
22 * initialized by InitLatch, and can only be set from the same process.
23 * A local latch can be used to wait for a signal to arrive, by calling
24 * SetLatch in the signal handler. A shared latch resides in shared memory,
25 * and must be initialized at postmaster startup by InitSharedLatch. Before
26 * a shared latch can be waited on, it must be associated with a process
27 * with OwnLatch. Only the process owning the latch can wait on it, but any
30 * There are three basic operations on a latch:
32 * SetLatch - Sets the latch
33 * ResetLatch - Clears the latch, allowing it to be set again
34 * WaitLatch - Waits for the latch to become set
36 * The correct pattern to wait for an event is:
47 * It's important to reset the latch *before* checking if there's work to
48 * do. Otherwise, if someone sets the latch between the check and the
49 * ResetLatch call, you will miss it and Wait will block.
51 * To wake up the waiter, you must first set a global flag or something
52 * else that the main loop tests in the "if (work to do)" part, and call
53 * SetLatch *after* that. SetLatch is designed to return quickly if the
54 * latch is already set.
60 * The Unix implementation uses the so-called self-pipe trick to overcome
61 * the race condition involved with select() and setting a global flag
62 * in the signal handler. When a latch is set and the current process
63 * is waiting for it, the signal handler wakes up the select() in
64 * WaitLatch by writing a byte to a pipe. A signal by itself doesn't
65 * interrupt select() on all platforms, and even on platforms where it
66 * does, a signal that arrives just before the select() call does not
67 * prevent the select() from entering sleep. An incoming byte on a pipe
68 * however reliably interrupts the sleep, and makes select() to return
69 * immediately if the signal arrives just before select() begins.
71 * When SetLatch is called from the same process that owns the latch,
72 * SetLatch writes the byte directly to the pipe. If it's owned by another
73 * process, SIGUSR1 is sent and the signal handler in the waiting process
74 * writes the byte to the pipe on behalf of the signaling process.
76 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
77 * Portions Copyright (c) 1994, Regents of the University of California
80 * $PostgreSQL: pgsql/src/backend/port/unix_latch.c,v 1.1 2010/09/11 15:48:04 heikki Exp $
82 *-------------------------------------------------------------------------
90 #include "miscadmin.h"
91 #include "storage/latch.h"
92 #include "storage/shmem.h"
94 /* Are we currently in WaitLatch? The signal handler would like to know. */
95 static volatile sig_atomic_t waiting = false;
97 /* Read and write end of the self-pipe */
98 static int selfpipe_readfd = -1;
99 static int selfpipe_writefd = -1;
101 /* private function prototypes */
102 static void initSelfPipe(void);
103 static void drainSelfPipe(void);
104 static void sendSelfPipeByte(void);
108 * Initialize a backend-local latch.
111 InitLatch(volatile Latch *latch)
113 /* Initialize the self pipe if this is our first latch in the process */
114 if (selfpipe_readfd == -1)
117 latch->is_set = false;
118 latch->owner_pid = MyProcPid;
119 latch->is_shared = false;
123 * Initialize a shared latch that can be set from other processes. The latch
124 * is initially owned by no-one, use OwnLatch to associate it with the
127 * NB: When you introduce a new shared latch, you must increase the shared
128 * latch count in NumSharedLatches in win32_latch.c!
131 InitSharedLatch(volatile Latch *latch)
133 latch->is_set = false;
134 latch->owner_pid = 0;
135 latch->is_shared = true;
139 * Associate a shared latch with the current process, allowing it to
142 * Make sure that latch_sigusr1_handler() is called from the SIGUSR1 signal
143 * handler, as shared latches use SIGUSR1 to for inter-process communication.
146 OwnLatch(volatile Latch *latch)
148 Assert(latch->is_shared);
150 /* Initialize the self pipe if this is our first latch in the process */
151 if (selfpipe_readfd == -1)
154 if (latch->owner_pid != 0)
155 elog(ERROR, "latch already owned");
156 latch->owner_pid = MyProcPid;
160 * Disown a shared latch currently owned by the current process.
163 DisownLatch(volatile Latch *latch)
165 Assert(latch->is_shared);
166 Assert(latch->owner_pid == MyProcPid);
167 latch->owner_pid = 0;
171 * Wait for given latch to be set or until timeout is exceeded.
172 * If the latch is already set, the function returns immediately.
174 * The 'timeout' is given in microseconds, and -1 means wait forever.
175 * On some platforms, signals cause the timeout to be restarted, so beware
176 * that the function can sleep for several times longer than the specified
179 * The latch must be owned by the current process, ie. it must be a
180 * backend-local latch initialized with InitLatch, or a shared latch
181 * associated with the current process by calling OwnLatch.
183 * Returns 'true' if the latch was set, or 'false' if timeout was reached.
186 WaitLatch(volatile Latch *latch, long timeout)
188 return WaitLatchOrSocket(latch, PGINVALID_SOCKET, timeout) > 0;
192 * Like WaitLatch, but will also return when there's data available in
193 * 'sock' for reading. Returns 0 if timeout was reached, 1 if the latch
194 * was set, or 2 if the scoket became readable.
197 WaitLatchOrSocket(volatile Latch *latch, pgsocket sock, long timeout)
199 struct timeval tv, *tvp = NULL;
204 if (latch->owner_pid != MyProcPid)
205 elog(ERROR, "cannot wait on a latch owned by another process");
207 /* Initialize timeout */
210 tv.tv_sec = timeout / 1000000L;
211 tv.tv_usec = timeout % 1000000L;
221 * Clear the pipe, and check if the latch is set already. If someone
222 * sets the latch between this and the select() below, the setter
223 * will write a byte to the pipe (or signal us and the signal handler
224 * will do that), and the select() will return immediately.
233 FD_ZERO(&input_mask);
234 FD_SET(selfpipe_readfd, &input_mask);
235 hifd = selfpipe_readfd;
236 if (sock != PGINVALID_SOCKET)
238 FD_SET(sock, &input_mask);
243 rc = select(hifd + 1, &input_mask, NULL, NULL, tvp);
249 (errcode_for_socket_access(),
250 errmsg("select() failed: %m")));
254 /* timeout exceeded */
258 if (sock != PGINVALID_SOCKET && FD_ISSET(sock, &input_mask))
261 break; /* data available in socket */
270 * Sets a latch and wakes up anyone waiting on it. Returns quickly if the
271 * latch is already set.
274 SetLatch(volatile Latch *latch)
278 /* Quick exit if already set */
282 latch->is_set = true;
285 * See if anyone's waiting for the latch. It can be the current process
286 * if we're in a signal handler. We use the self-pipe to wake up the
287 * select() in that case. If it's another process, send a signal.
289 * Fetch owner_pid only once, in case the owner simultaneously disowns
290 * the latch and clears owner_pid. XXX: This assumes that pid_t is
291 * atomic, which isn't guaranteed to be true! In practice, the effective
292 * range of pid_t fits in a 32 bit integer, and so should be atomic. In
293 * the worst case, we might end up signaling wrong process if the right
294 * one disowns the latch just as we fetch owner_pid. Even then, you're
295 * very unlucky if a process with that bogus pid exists.
297 owner_pid = latch->owner_pid;
300 else if (owner_pid == MyProcPid)
303 kill(owner_pid, SIGUSR1);
307 * Clear the latch. Calling WaitLatch after this will sleep, unless
308 * the latch is set again before the WaitLatch call.
311 ResetLatch(volatile Latch *latch)
313 /* Only the owner should reset the latch */
314 Assert(latch->owner_pid == MyProcPid);
316 latch->is_set = false;
321 * Compute space needed for latch's shared memory
323 * Not needed for Unix implementation.
333 * Allocate and initialize shared memory needed for latches
335 * Not needed for Unix implementation.
343 * SetLatch uses SIGUSR1 to wake up the process waiting on the latch. Wake
347 latch_sigusr1_handler(void)
353 /* initialize the self-pipe */
360 * Set up the self-pipe that allows a signal handler to wake up the
361 * select() in WaitLatch. Make the write-end non-blocking, so that
362 * SetLatch won't block if the event has already been set many times
363 * filling the kernel buffer. Make the read-end non-blocking too, so
364 * that we can easily clear the pipe by reading until EAGAIN or
367 if (pipe(pipefd) < 0)
368 elog(FATAL, "pipe() failed: %m");
369 if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) < 0)
370 elog(FATAL, "fcntl() failed on read-end of self-pipe: %m");
371 if (fcntl(pipefd[1], F_SETFL, O_NONBLOCK) < 0)
372 elog(FATAL, "fcntl() failed on write-end of self-pipe: %m");
374 selfpipe_readfd = pipefd[0];
375 selfpipe_writefd = pipefd[1];
378 /* Send one byte to the self-pipe, to wake up WaitLatch */
380 sendSelfPipeByte(void)
386 rc = write(selfpipe_writefd, &dummy, 1);
389 /* If interrupted by signal, just retry */
394 * If the pipe is full, we don't need to retry, the data that's
395 * there already is enough to wake up WaitLatch.
397 if (errno == EAGAIN || errno == EWOULDBLOCK)
401 * Oops, the write() failed for some other reason. We might be in
402 * a signal handler, so it's not safe to elog(). We have no choice
403 * but silently ignore the error.
409 /* Read all available data from the self-pipe */
414 * There shouldn't normally be more than one byte in the pipe, or maybe
415 * a few more if multiple processes run SetLatch at the same instant.
422 rc = read(selfpipe_readfd, buf, sizeof(buf));
425 if (errno == EAGAIN || errno == EWOULDBLOCK)
426 break; /* the pipe is empty */
427 else if (errno == EINTR)
428 continue; /* retry */
430 elog(ERROR, "read() on self-pipe failed: %m");
433 elog(ERROR, "unexpected EOF on self-pipe");