]> granicus.if.org Git - postgresql/blob - src/backend/port/unix_latch.c
pgindent run for 9.4
[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-2014, 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, WL_SOCKET_READABLE *must* be included in
204  * 'wakeEvents'; WL_SOCKET_WRITEABLE is optional.  The reason for this is
205  * that EOF and error conditions are reported only via WL_SOCKET_READABLE.
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         /* Cannot specify WL_SOCKET_WRITEABLE without WL_SOCKET_READABLE */
234         Assert((wakeEvents & (WL_SOCKET_READABLE | WL_SOCKET_WRITEABLE)) != WL_SOCKET_WRITEABLE);
235
236         if ((wakeEvents & WL_LATCH_SET) && latch->owner_pid != MyProcPid)
237                 elog(ERROR, "cannot wait on a latch owned by another process");
238
239         /*
240          * Initialize timeout if requested.  We must record the current time so
241          * that we can determine the remaining timeout if the poll() or select()
242          * is interrupted.  (On some platforms, select() will update the contents
243          * of "tv" for us, but unfortunately we can't rely on that.)
244          */
245         if (wakeEvents & WL_TIMEOUT)
246         {
247                 INSTR_TIME_SET_CURRENT(start_time);
248                 Assert(timeout >= 0 && timeout <= INT_MAX);
249                 cur_timeout = timeout;
250
251 #ifndef HAVE_POLL
252                 tv.tv_sec = cur_timeout / 1000L;
253                 tv.tv_usec = (cur_timeout % 1000L) * 1000L;
254                 tvp = &tv;
255 #endif
256         }
257         else
258         {
259                 cur_timeout = -1;
260
261 #ifndef HAVE_POLL
262                 tvp = NULL;
263 #endif
264         }
265
266         waiting = true;
267         do
268         {
269                 /*
270                  * Clear the pipe, then check if the latch is set already. If someone
271                  * sets the latch between this and the poll()/select() below, the
272                  * setter will write a byte to the pipe (or signal us and the signal
273                  * handler will do that), and the poll()/select() will return
274                  * immediately.
275                  *
276                  * Note: we assume that the kernel calls involved in drainSelfPipe()
277                  * and SetLatch() will provide adequate synchronization on machines
278                  * with weak memory ordering, so that we cannot miss seeing is_set if
279                  * the signal byte is already in the pipe when we drain it.
280                  */
281                 drainSelfPipe();
282
283                 if ((wakeEvents & WL_LATCH_SET) && latch->is_set)
284                 {
285                         result |= WL_LATCH_SET;
286
287                         /*
288                          * Leave loop immediately, avoid blocking again. We don't attempt
289                          * to report any other events that might also be satisfied.
290                          */
291                         break;
292                 }
293
294                 /* Must wait ... we use poll(2) if available, otherwise select(2) */
295 #ifdef HAVE_POLL
296                 nfds = 0;
297                 if (wakeEvents & (WL_SOCKET_READABLE | WL_SOCKET_WRITEABLE))
298                 {
299                         /* socket, if used, is always in pfds[0] */
300                         pfds[0].fd = sock;
301                         pfds[0].events = 0;
302                         if (wakeEvents & WL_SOCKET_READABLE)
303                                 pfds[0].events |= POLLIN;
304                         if (wakeEvents & WL_SOCKET_WRITEABLE)
305                                 pfds[0].events |= POLLOUT;
306                         pfds[0].revents = 0;
307                         nfds++;
308                 }
309
310                 pfds[nfds].fd = selfpipe_readfd;
311                 pfds[nfds].events = POLLIN;
312                 pfds[nfds].revents = 0;
313                 nfds++;
314
315                 if (wakeEvents & WL_POSTMASTER_DEATH)
316                 {
317                         /* postmaster fd, if used, is always in pfds[nfds - 1] */
318                         pfds[nfds].fd = postmaster_alive_fds[POSTMASTER_FD_WATCH];
319                         pfds[nfds].events = POLLIN;
320                         pfds[nfds].revents = 0;
321                         nfds++;
322                 }
323
324                 /* Sleep */
325                 rc = poll(pfds, nfds, (int) cur_timeout);
326
327                 /* Check return code */
328                 if (rc < 0)
329                 {
330                         /* EINTR is okay, otherwise complain */
331                         if (errno != EINTR)
332                         {
333                                 waiting = false;
334                                 ereport(ERROR,
335                                                 (errcode_for_socket_access(),
336                                                  errmsg("poll() failed: %m")));
337                         }
338                 }
339                 else if (rc == 0)
340                 {
341                         /* timeout exceeded */
342                         if (wakeEvents & WL_TIMEOUT)
343                                 result |= WL_TIMEOUT;
344                 }
345                 else
346                 {
347                         /* at least one event occurred, so check revents values */
348                         if ((wakeEvents & WL_SOCKET_READABLE) &&
349                                 (pfds[0].revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL)))
350                         {
351                                 /* data available in socket, or EOF/error condition */
352                                 result |= WL_SOCKET_READABLE;
353                         }
354                         if ((wakeEvents & WL_SOCKET_WRITEABLE) &&
355                                 (pfds[0].revents & POLLOUT))
356                         {
357                                 result |= WL_SOCKET_WRITEABLE;
358                         }
359
360                         /*
361                          * We expect a POLLHUP when the remote end is closed, but because
362                          * we don't expect the pipe to become readable or to have any
363                          * errors either, treat those cases as postmaster death, too.
364                          */
365                         if ((wakeEvents & WL_POSTMASTER_DEATH) &&
366                                 (pfds[nfds - 1].revents & (POLLHUP | POLLIN | POLLERR | POLLNVAL)))
367                         {
368                                 /*
369                                  * According to the select(2) man page on Linux, select(2) may
370                                  * spuriously return and report a file descriptor as readable,
371                                  * when it's not; and presumably so can poll(2).  It's not
372                                  * clear that the relevant cases would ever apply to the
373                                  * postmaster pipe, but since the consequences of falsely
374                                  * returning WL_POSTMASTER_DEATH could be pretty unpleasant,
375                                  * we take the trouble to positively verify EOF with
376                                  * PostmasterIsAlive().
377                                  */
378                                 if (!PostmasterIsAlive())
379                                         result |= WL_POSTMASTER_DEATH;
380                         }
381                 }
382 #else                                                   /* !HAVE_POLL */
383
384                 FD_ZERO(&input_mask);
385                 FD_ZERO(&output_mask);
386
387                 FD_SET(selfpipe_readfd, &input_mask);
388                 hifd = selfpipe_readfd;
389
390                 if (wakeEvents & WL_POSTMASTER_DEATH)
391                 {
392                         FD_SET(postmaster_alive_fds[POSTMASTER_FD_WATCH], &input_mask);
393                         if (postmaster_alive_fds[POSTMASTER_FD_WATCH] > hifd)
394                                 hifd = postmaster_alive_fds[POSTMASTER_FD_WATCH];
395                 }
396
397                 if (wakeEvents & WL_SOCKET_READABLE)
398                 {
399                         FD_SET(sock, &input_mask);
400                         if (sock > hifd)
401                                 hifd = sock;
402                 }
403
404                 if (wakeEvents & WL_SOCKET_WRITEABLE)
405                 {
406                         FD_SET(sock, &output_mask);
407                         if (sock > hifd)
408                                 hifd = sock;
409                 }
410
411                 /* Sleep */
412                 rc = select(hifd + 1, &input_mask, &output_mask, NULL, tvp);
413
414                 /* Check return code */
415                 if (rc < 0)
416                 {
417                         /* EINTR is okay, otherwise complain */
418                         if (errno != EINTR)
419                         {
420                                 waiting = false;
421                                 ereport(ERROR,
422                                                 (errcode_for_socket_access(),
423                                                  errmsg("select() failed: %m")));
424                         }
425                 }
426                 else if (rc == 0)
427                 {
428                         /* timeout exceeded */
429                         if (wakeEvents & WL_TIMEOUT)
430                                 result |= WL_TIMEOUT;
431                 }
432                 else
433                 {
434                         /* at least one event occurred, so check masks */
435                         if ((wakeEvents & WL_SOCKET_READABLE) && FD_ISSET(sock, &input_mask))
436                         {
437                                 /* data available in socket, or EOF */
438                                 result |= WL_SOCKET_READABLE;
439                         }
440                         if ((wakeEvents & WL_SOCKET_WRITEABLE) && FD_ISSET(sock, &output_mask))
441                         {
442                                 result |= WL_SOCKET_WRITEABLE;
443                         }
444                         if ((wakeEvents & WL_POSTMASTER_DEATH) &&
445                         FD_ISSET(postmaster_alive_fds[POSTMASTER_FD_WATCH], &input_mask))
446                         {
447                                 /*
448                                  * According to the select(2) man page on Linux, select(2) may
449                                  * spuriously return and report a file descriptor as readable,
450                                  * when it's not; and presumably so can poll(2).  It's not
451                                  * clear that the relevant cases would ever apply to the
452                                  * postmaster pipe, but since the consequences of falsely
453                                  * returning WL_POSTMASTER_DEATH could be pretty unpleasant,
454                                  * we take the trouble to positively verify EOF with
455                                  * PostmasterIsAlive().
456                                  */
457                                 if (!PostmasterIsAlive())
458                                         result |= WL_POSTMASTER_DEATH;
459                         }
460                 }
461 #endif   /* HAVE_POLL */
462
463                 /* If we're not done, update cur_timeout for next iteration */
464                 if (result == 0 && cur_timeout >= 0)
465                 {
466                         INSTR_TIME_SET_CURRENT(cur_time);
467                         INSTR_TIME_SUBTRACT(cur_time, start_time);
468                         cur_timeout = timeout - (long) INSTR_TIME_GET_MILLISEC(cur_time);
469                         if (cur_timeout < 0)
470                                 cur_timeout = 0;
471
472 #ifndef HAVE_POLL
473                         tv.tv_sec = cur_timeout / 1000L;
474                         tv.tv_usec = (cur_timeout % 1000L) * 1000L;
475 #endif
476                 }
477         } while (result == 0);
478         waiting = false;
479
480         return result;
481 }
482
483 /*
484  * Sets a latch and wakes up anyone waiting on it.
485  *
486  * This is cheap if the latch is already set, otherwise not so much.
487  *
488  * NB: when calling this in a signal handler, be sure to save and restore
489  * errno around it.  (That's standard practice in most signal handlers, of
490  * course, but we used to omit it in handlers that only set a flag.)
491  *
492  * NB: this function is called from critical sections and signal handlers so
493  * throwing an error is not a good idea.
494  */
495 void
496 SetLatch(volatile Latch *latch)
497 {
498         pid_t           owner_pid;
499
500         /*
501          * XXX there really ought to be a memory barrier operation right here, to
502          * ensure that any flag variables we might have changed get flushed to
503          * main memory before we check/set is_set.  Without that, we have to
504          * require that callers provide their own synchronization for machines
505          * with weak memory ordering (see latch.h).
506          */
507
508         /* Quick exit if already set */
509         if (latch->is_set)
510                 return;
511
512         latch->is_set = true;
513
514         /*
515          * See if anyone's waiting for the latch. It can be the current process if
516          * we're in a signal handler. We use the self-pipe to wake up the select()
517          * in that case. If it's another process, send a signal.
518          *
519          * Fetch owner_pid only once, in case the latch is concurrently getting
520          * owned or disowned. XXX: This assumes that pid_t is atomic, which isn't
521          * guaranteed to be true! In practice, the effective range of pid_t fits
522          * in a 32 bit integer, and so should be atomic. In the worst case, we
523          * might end up signaling the wrong process. Even then, you're very
524          * unlucky if a process with that bogus pid exists and belongs to
525          * Postgres; and PG database processes should handle excess SIGUSR1
526          * interrupts without a problem anyhow.
527          *
528          * Another sort of race condition that's possible here is for a new
529          * process to own the latch immediately after we look, so we don't signal
530          * it. This is okay so long as all callers of ResetLatch/WaitLatch follow
531          * the standard coding convention of waiting at the bottom of their loops,
532          * not the top, so that they'll correctly process latch-setting events
533          * that happen before they enter the loop.
534          */
535         owner_pid = latch->owner_pid;
536         if (owner_pid == 0)
537                 return;
538         else if (owner_pid == MyProcPid)
539         {
540                 if (waiting)
541                         sendSelfPipeByte();
542         }
543         else
544                 kill(owner_pid, SIGUSR1);
545 }
546
547 /*
548  * Clear the latch. Calling WaitLatch after this will sleep, unless
549  * the latch is set again before the WaitLatch call.
550  */
551 void
552 ResetLatch(volatile Latch *latch)
553 {
554         /* Only the owner should reset the latch */
555         Assert(latch->owner_pid == MyProcPid);
556
557         latch->is_set = false;
558
559         /*
560          * XXX there really ought to be a memory barrier operation right here, to
561          * ensure that the write to is_set gets flushed to main memory before we
562          * examine any flag variables.  Otherwise a concurrent SetLatch might
563          * falsely conclude that it needn't signal us, even though we have missed
564          * seeing some flag updates that SetLatch was supposed to inform us of.
565          * For the moment, callers must supply their own synchronization of flag
566          * variables (see latch.h).
567          */
568 }
569
570 /*
571  * SetLatch uses SIGUSR1 to wake up the process waiting on the latch.
572  *
573  * Wake up WaitLatch, if we're waiting.  (We might not be, since SIGUSR1 is
574  * overloaded for multiple purposes; or we might not have reached WaitLatch
575  * yet, in which case we don't need to fill the pipe either.)
576  *
577  * NB: when calling this in a signal handler, be sure to save and restore
578  * errno around it.
579  */
580 void
581 latch_sigusr1_handler(void)
582 {
583         if (waiting)
584                 sendSelfPipeByte();
585 }
586
587 /* Send one byte to the self-pipe, to wake up WaitLatch */
588 static void
589 sendSelfPipeByte(void)
590 {
591         int                     rc;
592         char            dummy = 0;
593
594 retry:
595         rc = write(selfpipe_writefd, &dummy, 1);
596         if (rc < 0)
597         {
598                 /* If interrupted by signal, just retry */
599                 if (errno == EINTR)
600                         goto retry;
601
602                 /*
603                  * If the pipe is full, we don't need to retry, the data that's there
604                  * already is enough to wake up WaitLatch.
605                  */
606                 if (errno == EAGAIN || errno == EWOULDBLOCK)
607                         return;
608
609                 /*
610                  * Oops, the write() failed for some other reason. We might be in a
611                  * signal handler, so it's not safe to elog(). We have no choice but
612                  * silently ignore the error.
613                  */
614                 return;
615         }
616 }
617
618 /*
619  * Read all available data from the self-pipe
620  *
621  * Note: this is only called when waiting = true.  If it fails and doesn't
622  * return, it must reset that flag first (though ideally, this will never
623  * happen).
624  */
625 static void
626 drainSelfPipe(void)
627 {
628         /*
629          * There shouldn't normally be more than one byte in the pipe, or maybe a
630          * few bytes if multiple processes run SetLatch at the same instant.
631          */
632         char            buf[16];
633         int                     rc;
634
635         for (;;)
636         {
637                 rc = read(selfpipe_readfd, buf, sizeof(buf));
638                 if (rc < 0)
639                 {
640                         if (errno == EAGAIN || errno == EWOULDBLOCK)
641                                 break;                  /* the pipe is empty */
642                         else if (errno == EINTR)
643                                 continue;               /* retry */
644                         else
645                         {
646                                 waiting = false;
647                                 elog(ERROR, "read() on self-pipe failed: %m");
648                         }
649                 }
650                 else if (rc == 0)
651                 {
652                         waiting = false;
653                         elog(ERROR, "unexpected EOF on self-pipe");
654                 }
655                 else if (rc < sizeof(buf))
656                 {
657                         /* we successfully drained the pipe; no need to read() again */
658                         break;
659                 }
660                 /* else buffer wasn't big enough, so read again */
661         }
662 }