]> granicus.if.org Git - postgresql/blob - src/backend/port/unix_latch.c
92ae78015832b69f5f8250e3790c65c3ab50e90d
[postgresql] / src / backend / port / unix_latch.c
1 /*-------------------------------------------------------------------------
2  *
3  * unix_latch.c
4  *        Routines for inter-process latches
5  *
6  * The Unix implementation uses the so-called self-pipe trick to overcome
7  * the race condition involved with select() and setting a global flag
8  * in the signal handler. When a latch is set and the current process
9  * is waiting for it, the signal handler wakes up the select() in
10  * WaitLatch by writing a byte to a pipe. A signal by itself doesn't
11  * interrupt select() on all platforms, and even on platforms where it
12  * does, a signal that arrives just before the select() call does not
13  * prevent the select() from entering sleep. An incoming byte on a pipe
14  * however reliably interrupts the sleep, and causes select() to return
15  * immediately even if the signal arrives before select() begins.
16  *
17  * (Actually, we prefer poll() over select() where available, but the
18  * same comments apply to it.)
19  *
20  * When SetLatch is called from the same process that owns the latch,
21  * SetLatch writes the byte directly to the pipe. If it's owned by another
22  * process, SIGUSR1 is sent and the signal handler in the waiting process
23  * writes the byte to the pipe on behalf of the signaling process.
24  *
25  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
26  * Portions Copyright (c) 1994, Regents of the University of California
27  *
28  * IDENTIFICATION
29  *        src/backend/port/unix_latch.c
30  *
31  *-------------------------------------------------------------------------
32  */
33 #include "postgres.h"
34
35 #include <fcntl.h>
36 #include <limits.h>
37 #include <signal.h>
38 #include <unistd.h>
39 #include <sys/time.h>
40 #include <sys/types.h>
41 #ifdef HAVE_POLL_H
42 #include <poll.h>
43 #endif
44 #ifdef HAVE_SYS_POLL_H
45 #include <sys/poll.h>
46 #endif
47 #ifdef HAVE_SYS_SELECT_H
48 #include <sys/select.h>
49 #endif
50
51 #include "miscadmin.h"
52 #include "portability/instr_time.h"
53 #include "postmaster/postmaster.h"
54 #include "storage/latch.h"
55 #include "storage/pmsignal.h"
56 #include "storage/shmem.h"
57
58 /* Are we currently in WaitLatch? The signal handler would like to know. */
59 static volatile sig_atomic_t waiting = false;
60
61 /* Read and write ends of the self-pipe */
62 static int      selfpipe_readfd = -1;
63 static int      selfpipe_writefd = -1;
64
65 /* Private function prototypes */
66 static void sendSelfPipeByte(void);
67 static void drainSelfPipe(void);
68
69
70 /*
71  * Initialize the process-local latch infrastructure.
72  *
73  * This must be called once during startup of any process that can wait on
74  * latches, before it issues any InitLatch() or OwnLatch() calls.
75  */
76 void
77 InitializeLatchSupport(void)
78 {
79         int                     pipefd[2];
80
81         Assert(selfpipe_readfd == -1);
82
83         /*
84          * Set up the self-pipe that allows a signal handler to wake up the
85          * select() in WaitLatch. Make the write-end non-blocking, so that
86          * SetLatch won't block if the event has already been set many times
87          * filling the kernel buffer. Make the read-end non-blocking too, so that
88          * we can easily clear the pipe by reading until EAGAIN or EWOULDBLOCK.
89          */
90         if (pipe(pipefd) < 0)
91                 elog(FATAL, "pipe() failed: %m");
92         if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) < 0)
93                 elog(FATAL, "fcntl() failed on read-end of self-pipe: %m");
94         if (fcntl(pipefd[1], F_SETFL, O_NONBLOCK) < 0)
95                 elog(FATAL, "fcntl() failed on write-end of self-pipe: %m");
96
97         selfpipe_readfd = pipefd[0];
98         selfpipe_writefd = pipefd[1];
99 }
100
101 /*
102  * Initialize a backend-local latch.
103  */
104 void
105 InitLatch(volatile Latch *latch)
106 {
107         /* Assert InitializeLatchSupport has been called in this process */
108         Assert(selfpipe_readfd >= 0);
109
110         latch->is_set = false;
111         latch->owner_pid = MyProcPid;
112         latch->is_shared = false;
113 }
114
115 /*
116  * Initialize a shared latch that can be set from other processes. The latch
117  * is initially owned by no-one; use OwnLatch to associate it with the
118  * current process.
119  *
120  * InitSharedLatch needs to be called in postmaster before forking child
121  * processes, usually right after allocating the shared memory block
122  * containing the latch with ShmemInitStruct. (The Unix implementation
123  * doesn't actually require that, but the Windows one does.) Because of
124  * this restriction, we have no concurrency issues to worry about here.
125  */
126 void
127 InitSharedLatch(volatile Latch *latch)
128 {
129         latch->is_set = false;
130         latch->owner_pid = 0;
131         latch->is_shared = true;
132 }
133
134 /*
135  * Associate a shared latch with the current process, allowing it to
136  * wait on the latch.
137  *
138  * Although there is a sanity check for latch-already-owned, we don't do
139  * any sort of locking here, meaning that we could fail to detect the error
140  * if two processes try to own the same latch at about the same time.  If
141  * there is any risk of that, caller must provide an interlock to prevent it.
142  *
143  * In any process that calls OwnLatch(), make sure that
144  * latch_sigusr1_handler() is called from the SIGUSR1 signal handler,
145  * as shared latches use SIGUSR1 for inter-process communication.
146  */
147 void
148 OwnLatch(volatile Latch *latch)
149 {
150         /* Assert InitializeLatchSupport has been called in this process */
151         Assert(selfpipe_readfd >= 0);
152
153         Assert(latch->is_shared);
154
155         /* sanity check */
156         if (latch->owner_pid != 0)
157                 elog(ERROR, "latch already owned");
158
159         latch->owner_pid = MyProcPid;
160 }
161
162 /*
163  * Disown a shared latch currently owned by the current process.
164  */
165 void
166 DisownLatch(volatile Latch *latch)
167 {
168         Assert(latch->is_shared);
169         Assert(latch->owner_pid == MyProcPid);
170
171         latch->owner_pid = 0;
172 }
173
174 /*
175  * Wait for a given latch to be set, or for postmaster death, or until timeout
176  * is exceeded. 'wakeEvents' is a bitmask that specifies which of those events
177  * to wait for. If the latch is already set (and WL_LATCH_SET is given), the
178  * function returns immediately.
179  *
180  * The "timeout" is given in milliseconds. It must be >= 0 if WL_TIMEOUT flag
181  * is given.  Although it is declared as "long", we don't actually support
182  * timeouts longer than INT_MAX milliseconds.  Note that some extra overhead
183  * is incurred when WL_TIMEOUT is given, so avoid using a timeout if possible.
184  *
185  * The latch must be owned by the current process, ie. it must be a
186  * backend-local latch initialized with InitLatch, or a shared latch
187  * associated with the current process by calling OwnLatch.
188  *
189  * Returns bit mask indicating which condition(s) caused the wake-up. Note
190  * that if multiple wake-up conditions are true, there is no guarantee that
191  * we return all of them in one call, but we will return at least one.
192  */
193 int
194 WaitLatch(volatile Latch *latch, int wakeEvents, long timeout)
195 {
196         return WaitLatchOrSocket(latch, wakeEvents, PGINVALID_SOCKET, timeout);
197 }
198
199 /*
200  * Like WaitLatch, but with an extra socket argument for WL_SOCKET_*
201  * conditions.
202  *
203  * When waiting on a socket, EOF and error conditions are reported by
204  * returning the socket as readable/writable or both, depending on
205  * WL_SOCKET_READABLE/WL_SOCKET_WRITEABLE being specified.
206  */
207 int
208 WaitLatchOrSocket(volatile Latch *latch, int wakeEvents, pgsocket sock,
209                                   long timeout)
210 {
211         int                     result = 0;
212         int                     rc;
213         instr_time      start_time,
214                                 cur_time;
215         long            cur_timeout;
216
217 #ifdef HAVE_POLL
218         struct pollfd pfds[3];
219         int                     nfds;
220 #else
221         struct timeval tv,
222                            *tvp;
223         fd_set          input_mask;
224         fd_set          output_mask;
225         int                     hifd;
226 #endif
227
228         /* Ignore WL_SOCKET_* events if no valid socket is given */
229         if (sock == PGINVALID_SOCKET)
230                 wakeEvents &= ~(WL_SOCKET_READABLE | WL_SOCKET_WRITEABLE);
231
232         Assert(wakeEvents != 0);        /* must have at least one wake event */
233
234         if ((wakeEvents & WL_LATCH_SET) && latch->owner_pid != MyProcPid)
235                 elog(ERROR, "cannot wait on a latch owned by another process");
236
237         /*
238          * Initialize timeout if requested.  We must record the current time so
239          * that we can determine the remaining timeout if the poll() or select()
240          * is interrupted.  (On some platforms, select() will update the contents
241          * of "tv" for us, but unfortunately we can't rely on that.)
242          */
243         if (wakeEvents & WL_TIMEOUT)
244         {
245                 INSTR_TIME_SET_CURRENT(start_time);
246                 Assert(timeout >= 0 && timeout <= INT_MAX);
247                 cur_timeout = timeout;
248
249 #ifndef HAVE_POLL
250                 tv.tv_sec = cur_timeout / 1000L;
251                 tv.tv_usec = (cur_timeout % 1000L) * 1000L;
252                 tvp = &tv;
253 #endif
254         }
255         else
256         {
257                 cur_timeout = -1;
258
259 #ifndef HAVE_POLL
260                 tvp = NULL;
261 #endif
262         }
263
264         waiting = true;
265         do
266         {
267                 /*
268                  * Clear the pipe, then check if the latch is set already. If someone
269                  * sets the latch between this and the poll()/select() below, the
270                  * setter will write a byte to the pipe (or signal us and the signal
271                  * handler will do that), and the poll()/select() will return
272                  * immediately.
273                  *
274                  * Note: we assume that the kernel calls involved in drainSelfPipe()
275                  * and SetLatch() will provide adequate synchronization on machines
276                  * with weak memory ordering, so that we cannot miss seeing is_set if
277                  * the signal byte is already in the pipe when we drain it.
278                  */
279                 drainSelfPipe();
280
281                 if ((wakeEvents & WL_LATCH_SET) && latch->is_set)
282                 {
283                         result |= WL_LATCH_SET;
284
285                         /*
286                          * Leave loop immediately, avoid blocking again. We don't attempt
287                          * to report any other events that might also be satisfied.
288                          */
289                         break;
290                 }
291
292                 /*
293                  * Must wait ... we use poll(2) if available, otherwise select(2).
294                  *
295                  * On at least older linux kernels select(), in violation of POSIX,
296                  * doesn't reliably return a socket as writable if closed - but we
297                  * rely on that. So far all the known cases of this problem are on
298                  * platforms that also provide a poll() implementation without that
299                  * bug.  If we find one where that's not the case, we'll need to add a
300                  * workaround.
301                  */
302 #ifdef HAVE_POLL
303                 nfds = 0;
304                 if (wakeEvents & (WL_SOCKET_READABLE | WL_SOCKET_WRITEABLE))
305                 {
306                         /* socket, if used, is always in pfds[0] */
307                         pfds[0].fd = sock;
308                         pfds[0].events = 0;
309                         if (wakeEvents & WL_SOCKET_READABLE)
310                                 pfds[0].events |= POLLIN;
311                         if (wakeEvents & WL_SOCKET_WRITEABLE)
312                                 pfds[0].events |= POLLOUT;
313                         pfds[0].revents = 0;
314                         nfds++;
315                 }
316
317                 pfds[nfds].fd = selfpipe_readfd;
318                 pfds[nfds].events = POLLIN;
319                 pfds[nfds].revents = 0;
320                 nfds++;
321
322                 if (wakeEvents & WL_POSTMASTER_DEATH)
323                 {
324                         /* postmaster fd, if used, is always in pfds[nfds - 1] */
325                         pfds[nfds].fd = postmaster_alive_fds[POSTMASTER_FD_WATCH];
326                         pfds[nfds].events = POLLIN;
327                         pfds[nfds].revents = 0;
328                         nfds++;
329                 }
330
331                 /* Sleep */
332                 rc = poll(pfds, nfds, (int) cur_timeout);
333
334                 /* Check return code */
335                 if (rc < 0)
336                 {
337                         /* EINTR is okay, otherwise complain */
338                         if (errno != EINTR)
339                         {
340                                 waiting = false;
341                                 ereport(ERROR,
342                                                 (errcode_for_socket_access(),
343                                                  errmsg("poll() failed: %m")));
344                         }
345                 }
346                 else if (rc == 0)
347                 {
348                         /* timeout exceeded */
349                         if (wakeEvents & WL_TIMEOUT)
350                                 result |= WL_TIMEOUT;
351                 }
352                 else
353                 {
354                         /* at least one event occurred, so check revents values */
355                         if ((wakeEvents & WL_SOCKET_READABLE) &&
356                                 (pfds[0].revents & POLLIN))
357                         {
358                                 /* data available in socket, or EOF/error condition */
359                                 result |= WL_SOCKET_READABLE;
360                         }
361                         if ((wakeEvents & WL_SOCKET_WRITEABLE) &&
362                                 (pfds[0].revents & POLLOUT))
363                         {
364                                 /* socket is writable */
365                                 result |= WL_SOCKET_WRITEABLE;
366                         }
367                         if (pfds[0].revents & (POLLHUP | POLLERR | POLLNVAL))
368                         {
369                                 /* EOF/error condition */
370                                 if (wakeEvents & WL_SOCKET_READABLE)
371                                         result |= WL_SOCKET_READABLE;
372                                 if (wakeEvents & WL_SOCKET_WRITEABLE)
373                                         result |= WL_SOCKET_WRITEABLE;
374                         }
375
376                         /*
377                          * We expect a POLLHUP when the remote end is closed, but because
378                          * we don't expect the pipe to become readable or to have any
379                          * errors either, treat those cases as postmaster death, too.
380                          */
381                         if ((wakeEvents & WL_POSTMASTER_DEATH) &&
382                                 (pfds[nfds - 1].revents & (POLLHUP | POLLIN | POLLERR | POLLNVAL)))
383                         {
384                                 /*
385                                  * According to the select(2) man page on Linux, select(2) may
386                                  * spuriously return and report a file descriptor as readable,
387                                  * when it's not; and presumably so can poll(2).  It's not
388                                  * clear that the relevant cases would ever apply to the
389                                  * postmaster pipe, but since the consequences of falsely
390                                  * returning WL_POSTMASTER_DEATH could be pretty unpleasant,
391                                  * we take the trouble to positively verify EOF with
392                                  * PostmasterIsAlive().
393                                  */
394                                 if (!PostmasterIsAlive())
395                                         result |= WL_POSTMASTER_DEATH;
396                         }
397                 }
398 #else                                                   /* !HAVE_POLL */
399
400                 FD_ZERO(&input_mask);
401                 FD_ZERO(&output_mask);
402
403                 FD_SET(selfpipe_readfd, &input_mask);
404                 hifd = selfpipe_readfd;
405
406                 if (wakeEvents & WL_POSTMASTER_DEATH)
407                 {
408                         FD_SET(postmaster_alive_fds[POSTMASTER_FD_WATCH], &input_mask);
409                         if (postmaster_alive_fds[POSTMASTER_FD_WATCH] > hifd)
410                                 hifd = postmaster_alive_fds[POSTMASTER_FD_WATCH];
411                 }
412
413                 if (wakeEvents & WL_SOCKET_READABLE)
414                 {
415                         FD_SET(sock, &input_mask);
416                         if (sock > hifd)
417                                 hifd = sock;
418                 }
419
420                 if (wakeEvents & WL_SOCKET_WRITEABLE)
421                 {
422                         FD_SET(sock, &output_mask);
423                         if (sock > hifd)
424                                 hifd = sock;
425                 }
426
427                 /* Sleep */
428                 rc = select(hifd + 1, &input_mask, &output_mask, NULL, tvp);
429
430                 /* Check return code */
431                 if (rc < 0)
432                 {
433                         /* EINTR is okay, otherwise complain */
434                         if (errno != EINTR)
435                         {
436                                 waiting = false;
437                                 ereport(ERROR,
438                                                 (errcode_for_socket_access(),
439                                                  errmsg("select() failed: %m")));
440                         }
441                 }
442                 else if (rc == 0)
443                 {
444                         /* timeout exceeded */
445                         if (wakeEvents & WL_TIMEOUT)
446                                 result |= WL_TIMEOUT;
447                 }
448                 else
449                 {
450                         /* at least one event occurred, so check masks */
451                         if ((wakeEvents & WL_SOCKET_READABLE) && FD_ISSET(sock, &input_mask))
452                         {
453                                 /* data available in socket, or EOF */
454                                 result |= WL_SOCKET_READABLE;
455                         }
456                         if ((wakeEvents & WL_SOCKET_WRITEABLE) && FD_ISSET(sock, &output_mask))
457                         {
458                                 /* socket is writable, or EOF */
459                                 result |= WL_SOCKET_WRITEABLE;
460                         }
461                         if ((wakeEvents & WL_POSTMASTER_DEATH) &&
462                         FD_ISSET(postmaster_alive_fds[POSTMASTER_FD_WATCH], &input_mask))
463                         {
464                                 /*
465                                  * According to the select(2) man page on Linux, select(2) may
466                                  * spuriously return and report a file descriptor as readable,
467                                  * when it's not; and presumably so can poll(2).  It's not
468                                  * clear that the relevant cases would ever apply to the
469                                  * postmaster pipe, but since the consequences of falsely
470                                  * returning WL_POSTMASTER_DEATH could be pretty unpleasant,
471                                  * we take the trouble to positively verify EOF with
472                                  * PostmasterIsAlive().
473                                  */
474                                 if (!PostmasterIsAlive())
475                                         result |= WL_POSTMASTER_DEATH;
476                         }
477                 }
478 #endif   /* HAVE_POLL */
479
480                 /* If we're not done, update cur_timeout for next iteration */
481                 if (result == 0 && cur_timeout >= 0)
482                 {
483                         INSTR_TIME_SET_CURRENT(cur_time);
484                         INSTR_TIME_SUBTRACT(cur_time, start_time);
485                         cur_timeout = timeout - (long) INSTR_TIME_GET_MILLISEC(cur_time);
486                         if (cur_timeout < 0)
487                                 cur_timeout = 0;
488
489 #ifndef HAVE_POLL
490                         tv.tv_sec = cur_timeout / 1000L;
491                         tv.tv_usec = (cur_timeout % 1000L) * 1000L;
492 #endif
493                 }
494         } while (result == 0);
495         waiting = false;
496
497         return result;
498 }
499
500 /*
501  * Sets a latch and wakes up anyone waiting on it.
502  *
503  * This is cheap if the latch is already set, otherwise not so much.
504  *
505  * NB: when calling this in a signal handler, be sure to save and restore
506  * errno around it.  (That's standard practice in most signal handlers, of
507  * course, but we used to omit it in handlers that only set a flag.)
508  *
509  * NB: this function is called from critical sections and signal handlers so
510  * throwing an error is not a good idea.
511  */
512 void
513 SetLatch(volatile Latch *latch)
514 {
515         pid_t           owner_pid;
516
517         /*
518          * XXX there really ought to be a memory barrier operation right here, to
519          * ensure that any flag variables we might have changed get flushed to
520          * main memory before we check/set is_set.  Without that, we have to
521          * require that callers provide their own synchronization for machines
522          * with weak memory ordering (see latch.h).
523          */
524
525         /* Quick exit if already set */
526         if (latch->is_set)
527                 return;
528
529         latch->is_set = true;
530
531         /*
532          * See if anyone's waiting for the latch. It can be the current process if
533          * we're in a signal handler. We use the self-pipe to wake up the select()
534          * in that case. If it's another process, send a signal.
535          *
536          * Fetch owner_pid only once, in case the latch is concurrently getting
537          * owned or disowned. XXX: This assumes that pid_t is atomic, which isn't
538          * guaranteed to be true! In practice, the effective range of pid_t fits
539          * in a 32 bit integer, and so should be atomic. In the worst case, we
540          * might end up signaling the wrong process. Even then, you're very
541          * unlucky if a process with that bogus pid exists and belongs to
542          * Postgres; and PG database processes should handle excess SIGUSR1
543          * interrupts without a problem anyhow.
544          *
545          * Another sort of race condition that's possible here is for a new
546          * process to own the latch immediately after we look, so we don't signal
547          * it. This is okay so long as all callers of ResetLatch/WaitLatch follow
548          * the standard coding convention of waiting at the bottom of their loops,
549          * not the top, so that they'll correctly process latch-setting events
550          * that happen before they enter the loop.
551          */
552         owner_pid = latch->owner_pid;
553         if (owner_pid == 0)
554                 return;
555         else if (owner_pid == MyProcPid)
556         {
557                 if (waiting)
558                         sendSelfPipeByte();
559         }
560         else
561                 kill(owner_pid, SIGUSR1);
562 }
563
564 /*
565  * Clear the latch. Calling WaitLatch after this will sleep, unless
566  * the latch is set again before the WaitLatch call.
567  */
568 void
569 ResetLatch(volatile Latch *latch)
570 {
571         /* Only the owner should reset the latch */
572         Assert(latch->owner_pid == MyProcPid);
573
574         latch->is_set = false;
575
576         /*
577          * XXX there really ought to be a memory barrier operation right here, to
578          * ensure that the write to is_set gets flushed to main memory before we
579          * examine any flag variables.  Otherwise a concurrent SetLatch might
580          * falsely conclude that it needn't signal us, even though we have missed
581          * seeing some flag updates that SetLatch was supposed to inform us of.
582          * For the moment, callers must supply their own synchronization of flag
583          * variables (see latch.h).
584          */
585 }
586
587 /*
588  * SetLatch uses SIGUSR1 to wake up the process waiting on the latch.
589  *
590  * Wake up WaitLatch, if we're waiting.  (We might not be, since SIGUSR1 is
591  * overloaded for multiple purposes; or we might not have reached WaitLatch
592  * yet, in which case we don't need to fill the pipe either.)
593  *
594  * NB: when calling this in a signal handler, be sure to save and restore
595  * errno around it.
596  */
597 void
598 latch_sigusr1_handler(void)
599 {
600         if (waiting)
601                 sendSelfPipeByte();
602 }
603
604 /* Send one byte to the self-pipe, to wake up WaitLatch */
605 static void
606 sendSelfPipeByte(void)
607 {
608         int                     rc;
609         char            dummy = 0;
610
611 retry:
612         rc = write(selfpipe_writefd, &dummy, 1);
613         if (rc < 0)
614         {
615                 /* If interrupted by signal, just retry */
616                 if (errno == EINTR)
617                         goto retry;
618
619                 /*
620                  * If the pipe is full, we don't need to retry, the data that's there
621                  * already is enough to wake up WaitLatch.
622                  */
623                 if (errno == EAGAIN || errno == EWOULDBLOCK)
624                         return;
625
626                 /*
627                  * Oops, the write() failed for some other reason. We might be in a
628                  * signal handler, so it's not safe to elog(). We have no choice but
629                  * silently ignore the error.
630                  */
631                 return;
632         }
633 }
634
635 /*
636  * Read all available data from the self-pipe
637  *
638  * Note: this is only called when waiting = true.  If it fails and doesn't
639  * return, it must reset that flag first (though ideally, this will never
640  * happen).
641  */
642 static void
643 drainSelfPipe(void)
644 {
645         /*
646          * There shouldn't normally be more than one byte in the pipe, or maybe a
647          * few bytes if multiple processes run SetLatch at the same instant.
648          */
649         char            buf[16];
650         int                     rc;
651
652         for (;;)
653         {
654                 rc = read(selfpipe_readfd, buf, sizeof(buf));
655                 if (rc < 0)
656                 {
657                         if (errno == EAGAIN || errno == EWOULDBLOCK)
658                                 break;                  /* the pipe is empty */
659                         else if (errno == EINTR)
660                                 continue;               /* retry */
661                         else
662                         {
663                                 waiting = false;
664                                 elog(ERROR, "read() on self-pipe failed: %m");
665                         }
666                 }
667                 else if (rc == 0)
668                 {
669                         waiting = false;
670                         elog(ERROR, "unexpected EOF on self-pipe");
671                 }
672                 else if (rc < sizeof(buf))
673                 {
674                         /* we successfully drained the pipe; no need to read() again */
675                         break;
676                 }
677                 /* else buffer wasn't big enough, so read again */
678         }
679 }