]> granicus.if.org Git - postgresql/blob - src/backend/commands/async.c
Move Timestamp/Interval typedefs and basic macros into datatype/timestamp.h.
[postgresql] / src / backend / commands / async.c
1 /*-------------------------------------------------------------------------
2  *
3  * async.c
4  *        Asynchronous notification: NOTIFY, LISTEN, UNLISTEN
5  *
6  * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  *        src/backend/commands/async.c
11  *
12  *-------------------------------------------------------------------------
13  */
14
15 /*-------------------------------------------------------------------------
16  * Async Notification Model as of 9.0:
17  *
18  * 1. Multiple backends on same machine. Multiple backends listening on
19  *        several channels. (Channels are also called "conditions" in other
20  *        parts of the code.)
21  *
22  * 2. There is one central queue in disk-based storage (directory pg_notify/),
23  *        with actively-used pages mapped into shared memory by the slru.c module.
24  *        All notification messages are placed in the queue and later read out
25  *        by listening backends.
26  *
27  *        There is no central knowledge of which backend listens on which channel;
28  *        every backend has its own list of interesting channels.
29  *
30  *        Although there is only one queue, notifications are treated as being
31  *        database-local; this is done by including the sender's database OID
32  *        in each notification message.  Listening backends ignore messages
33  *        that don't match their database OID.  This is important because it
34  *        ensures senders and receivers have the same database encoding and won't
35  *        misinterpret non-ASCII text in the channel name or payload string.
36  *
37  *        Since notifications are not expected to survive database crashes,
38  *        we can simply clean out the pg_notify data at any reboot, and there
39  *        is no need for WAL support or fsync'ing.
40  *
41  * 3. Every backend that is listening on at least one channel registers by
42  *        entering its PID into the array in AsyncQueueControl. It then scans all
43  *        incoming notifications in the central queue and first compares the
44  *        database OID of the notification with its own database OID and then
45  *        compares the notified channel with the list of channels that it listens
46  *        to. In case there is a match it delivers the notification event to its
47  *        frontend.  Non-matching events are simply skipped.
48  *
49  * 4. The NOTIFY statement (routine Async_Notify) stores the notification in
50  *        a backend-local list which will not be processed until transaction end.
51  *
52  *        Duplicate notifications from the same transaction are sent out as one
53  *        notification only. This is done to save work when for example a trigger
54  *        on a 2 million row table fires a notification for each row that has been
55  *        changed. If the application needs to receive every single notification
56  *        that has been sent, it can easily add some unique string into the extra
57  *        payload parameter.
58  *
59  *        When the transaction is ready to commit, PreCommit_Notify() adds the
60  *        pending notifications to the head of the queue. The head pointer of the
61  *        queue always points to the next free position and a position is just a
62  *        page number and the offset in that page. This is done before marking the
63  *        transaction as committed in clog. If we run into problems writing the
64  *        notifications, we can still call elog(ERROR, ...) and the transaction
65  *        will roll back.
66  *
67  *        Once we have put all of the notifications into the queue, we return to
68  *        CommitTransaction() which will then do the actual transaction commit.
69  *
70  *        After commit we are called another time (AtCommit_Notify()). Here we
71  *        make the actual updates to the effective listen state (listenChannels).
72  *
73  *        Finally, after we are out of the transaction altogether, we check if
74  *        we need to signal listening backends.  In SignalBackends() we scan the
75  *        list of listening backends and send a PROCSIG_NOTIFY_INTERRUPT signal
76  *        to every listening backend (we don't know which backend is listening on
77  *        which channel so we must signal them all). We can exclude backends that
78  *        are already up to date, though.  We don't bother with a self-signal
79  *        either, but just process the queue directly.
80  *
81  * 5. Upon receipt of a PROCSIG_NOTIFY_INTERRUPT signal, the signal handler
82  *        can call inbound-notify processing immediately if this backend is idle
83  *        (ie, it is waiting for a frontend command and is not within a transaction
84  *        block).  Otherwise the handler may only set a flag, which will cause the
85  *        processing to occur just before we next go idle.
86  *
87  *        Inbound-notify processing consists of reading all of the notifications
88  *        that have arrived since scanning last time. We read every notification
89  *        until we reach either a notification from an uncommitted transaction or
90  *        the head pointer's position. Then we check if we were the laziest
91  *        backend: if our pointer is set to the same position as the global tail
92  *        pointer is set, then we move the global tail pointer ahead to where the
93  *        second-laziest backend is (in general, we take the MIN of the current
94  *        head position and all active backends' new tail pointers). Whenever we
95  *        move the global tail pointer we also truncate now-unused pages (i.e.,
96  *        delete files in pg_notify/ that are no longer used).
97  *
98  * An application that listens on the same channel it notifies will get
99  * NOTIFY messages for its own NOTIFYs.  These can be ignored, if not useful,
100  * by comparing be_pid in the NOTIFY message to the application's own backend's
101  * PID.  (As of FE/BE protocol 2.0, the backend's PID is provided to the
102  * frontend during startup.)  The above design guarantees that notifies from
103  * other backends will never be missed by ignoring self-notifies.
104  *
105  * The amount of shared memory used for notify management (NUM_ASYNC_BUFFERS)
106  * can be varied without affecting anything but performance.  The maximum
107  * amount of notification data that can be queued at one time is determined
108  * by slru.c's wraparound limit; see QUEUE_MAX_PAGE below.
109  *-------------------------------------------------------------------------
110  */
111
112 #include "postgres.h"
113
114 #include <limits.h>
115 #include <unistd.h>
116 #include <signal.h>
117
118 #include "access/slru.h"
119 #include "access/transam.h"
120 #include "access/xact.h"
121 #include "catalog/pg_database.h"
122 #include "commands/async.h"
123 #include "funcapi.h"
124 #include "libpq/libpq.h"
125 #include "libpq/pqformat.h"
126 #include "miscadmin.h"
127 #include "storage/ipc.h"
128 #include "storage/lmgr.h"
129 #include "storage/procsignal.h"
130 #include "storage/sinval.h"
131 #include "tcop/tcopprot.h"
132 #include "utils/builtins.h"
133 #include "utils/memutils.h"
134 #include "utils/ps_status.h"
135 #include "utils/timestamp.h"
136
137
138 /*
139  * Maximum size of a NOTIFY payload, including terminating NULL.  This
140  * must be kept small enough so that a notification message fits on one
141  * SLRU page.  The magic fudge factor here is noncritical as long as it's
142  * more than AsyncQueueEntryEmptySize --- we make it significantly bigger
143  * than that, so changes in that data structure won't affect user-visible
144  * restrictions.
145  */
146 #define NOTIFY_PAYLOAD_MAX_LENGTH       (BLCKSZ - NAMEDATALEN - 128)
147
148 /*
149  * Struct representing an entry in the global notify queue
150  *
151  * This struct declaration has the maximal length, but in a real queue entry
152  * the data area is only big enough for the actual channel and payload strings
153  * (each null-terminated).      AsyncQueueEntryEmptySize is the minimum possible
154  * entry size, if both channel and payload strings are empty (but note it
155  * doesn't include alignment padding).
156  *
157  * The "length" field should always be rounded up to the next QUEUEALIGN
158  * multiple so that all fields are properly aligned.
159  */
160 typedef struct AsyncQueueEntry
161 {
162         int                     length;                 /* total allocated length of entry */
163         Oid                     dboid;                  /* sender's database OID */
164         TransactionId xid;                      /* sender's XID */
165         int32           srcPid;                 /* sender's PID */
166         char            data[NAMEDATALEN + NOTIFY_PAYLOAD_MAX_LENGTH];
167 } AsyncQueueEntry;
168
169 /* Currently, no field of AsyncQueueEntry requires more than int alignment */
170 #define QUEUEALIGN(len)         INTALIGN(len)
171
172 #define AsyncQueueEntryEmptySize        (offsetof(AsyncQueueEntry, data) + 2)
173
174 /*
175  * Struct describing a queue position, and assorted macros for working with it
176  */
177 typedef struct QueuePosition
178 {
179         int                     page;                   /* SLRU page number */
180         int                     offset;                 /* byte offset within page */
181 } QueuePosition;
182
183 #define QUEUE_POS_PAGE(x)               ((x).page)
184 #define QUEUE_POS_OFFSET(x)             ((x).offset)
185
186 #define SET_QUEUE_POS(x,y,z) \
187         do { \
188                 (x).page = (y); \
189                 (x).offset = (z); \
190         } while (0)
191
192 #define QUEUE_POS_EQUAL(x,y) \
193          ((x).page == (y).page && (x).offset == (y).offset)
194
195 /* choose logically smaller QueuePosition */
196 #define QUEUE_POS_MIN(x,y) \
197         (asyncQueuePagePrecedesLogically((x).page, (y).page) ? (x) : \
198          (x).page != (y).page ? (y) : \
199          (x).offset < (y).offset ? (x) : (y))
200
201 /*
202  * Struct describing a listening backend's status
203  */
204 typedef struct QueueBackendStatus
205 {
206         int32           pid;                    /* either a PID or InvalidPid */
207         QueuePosition pos;                      /* backend has read queue up to here */
208 } QueueBackendStatus;
209
210 #define InvalidPid                              (-1)
211
212 /*
213  * Shared memory state for LISTEN/NOTIFY (excluding its SLRU stuff)
214  *
215  * The AsyncQueueControl structure is protected by the AsyncQueueLock.
216  *
217  * When holding the lock in SHARED mode, backends may only inspect their own
218  * entries as well as the head and tail pointers. Consequently we can allow a
219  * backend to update its own record while holding only SHARED lock (since no
220  * other backend will inspect it).
221  *
222  * When holding the lock in EXCLUSIVE mode, backends can inspect the entries
223  * of other backends and also change the head and tail pointers.
224  *
225  * In order to avoid deadlocks, whenever we need both locks, we always first
226  * get AsyncQueueLock and then AsyncCtlLock.
227  *
228  * Each backend uses the backend[] array entry with index equal to its
229  * BackendId (which can range from 1 to MaxBackends).  We rely on this to make
230  * SendProcSignal fast.
231  */
232 typedef struct AsyncQueueControl
233 {
234         QueuePosition head;                     /* head points to the next free location */
235         QueuePosition tail;                     /* the global tail is equivalent to the tail
236                                                                  * of the "slowest" backend */
237         TimestampTz lastQueueFillWarn;          /* time of last queue-full msg */
238         QueueBackendStatus backend[1];          /* actually of length MaxBackends+1 */
239         /* DO NOT ADD FURTHER STRUCT MEMBERS HERE */
240 } AsyncQueueControl;
241
242 static AsyncQueueControl *asyncQueueControl;
243
244 #define QUEUE_HEAD                                      (asyncQueueControl->head)
245 #define QUEUE_TAIL                                      (asyncQueueControl->tail)
246 #define QUEUE_BACKEND_PID(i)            (asyncQueueControl->backend[i].pid)
247 #define QUEUE_BACKEND_POS(i)            (asyncQueueControl->backend[i].pos)
248
249 /*
250  * The SLRU buffer area through which we access the notification queue
251  */
252 static SlruCtlData AsyncCtlData;
253
254 #define AsyncCtl                                        (&AsyncCtlData)
255 #define QUEUE_PAGESIZE                          BLCKSZ
256 #define QUEUE_FULL_WARN_INTERVAL        5000            /* warn at most once every 5s */
257
258 /*
259  * slru.c currently assumes that all filenames are four characters of hex
260  * digits. That means that we can use segments 0000 through FFFF.
261  * Each segment contains SLRU_PAGES_PER_SEGMENT pages which gives us
262  * the pages from 0 to SLRU_PAGES_PER_SEGMENT * 0x10000 - 1.
263  *
264  * It's of course possible to enhance slru.c, but this gives us so much
265  * space already that it doesn't seem worth the trouble.
266  *
267  * The most data we can have in the queue at a time is QUEUE_MAX_PAGE/2
268  * pages, because more than that would confuse slru.c into thinking there
269  * was a wraparound condition.  With the default BLCKSZ this means there
270  * can be up to 8GB of queued-and-not-read data.
271  *
272  * Note: it's possible to redefine QUEUE_MAX_PAGE with a smaller multiple of
273  * SLRU_PAGES_PER_SEGMENT, for easier testing of queue-full behaviour.
274  */
275 #define QUEUE_MAX_PAGE                  (SLRU_PAGES_PER_SEGMENT * 0x10000 - 1)
276
277 /*
278  * listenChannels identifies the channels we are actually listening to
279  * (ie, have committed a LISTEN on).  It is a simple list of channel names,
280  * allocated in TopMemoryContext.
281  */
282 static List *listenChannels = NIL;              /* list of C strings */
283
284 /*
285  * State for pending LISTEN/UNLISTEN actions consists of an ordered list of
286  * all actions requested in the current transaction.  As explained above,
287  * we don't actually change listenChannels until we reach transaction commit.
288  *
289  * The list is kept in CurTransactionContext.  In subtransactions, each
290  * subtransaction has its own list in its own CurTransactionContext, but
291  * successful subtransactions attach their lists to their parent's list.
292  * Failed subtransactions simply discard their lists.
293  */
294 typedef enum
295 {
296         LISTEN_LISTEN,
297         LISTEN_UNLISTEN,
298         LISTEN_UNLISTEN_ALL
299 } ListenActionKind;
300
301 typedef struct
302 {
303         ListenActionKind action;
304         char            channel[1];             /* actually, as long as needed */
305 } ListenAction;
306
307 static List *pendingActions = NIL;              /* list of ListenAction */
308
309 static List *upperPendingActions = NIL; /* list of upper-xact lists */
310
311 /*
312  * State for outbound notifies consists of a list of all channels+payloads
313  * NOTIFYed in the current transaction. We do not actually perform a NOTIFY
314  * until and unless the transaction commits.  pendingNotifies is NIL if no
315  * NOTIFYs have been done in the current transaction.
316  *
317  * The list is kept in CurTransactionContext.  In subtransactions, each
318  * subtransaction has its own list in its own CurTransactionContext, but
319  * successful subtransactions attach their lists to their parent's list.
320  * Failed subtransactions simply discard their lists.
321  *
322  * Note: the action and notify lists do not interact within a transaction.
323  * In particular, if a transaction does NOTIFY and then LISTEN on the same
324  * condition name, it will get a self-notify at commit.  This is a bit odd
325  * but is consistent with our historical behavior.
326  */
327 typedef struct Notification
328 {
329         char       *channel;            /* channel name */
330         char       *payload;            /* payload string (can be empty) */
331 } Notification;
332
333 static List *pendingNotifies = NIL;             /* list of Notifications */
334
335 static List *upperPendingNotifies = NIL;                /* list of upper-xact lists */
336
337 /*
338  * State for inbound notifications consists of two flags: one saying whether
339  * the signal handler is currently allowed to call ProcessIncomingNotify
340  * directly, and one saying whether the signal has occurred but the handler
341  * was not allowed to call ProcessIncomingNotify at the time.
342  *
343  * NB: the "volatile" on these declarations is critical!  If your compiler
344  * does not grok "volatile", you'd be best advised to compile this file
345  * with all optimization turned off.
346  */
347 static volatile sig_atomic_t notifyInterruptEnabled = 0;
348 static volatile sig_atomic_t notifyInterruptOccurred = 0;
349
350 /* True if we've registered an on_shmem_exit cleanup */
351 static bool unlistenExitRegistered = false;
352
353 /* has this backend sent notifications in the current transaction? */
354 static bool backendHasSentNotifications = false;
355
356 /* has this backend executed its first LISTEN in the current transaction? */
357 static bool backendHasExecutedInitialListen = false;
358
359 /* GUC parameter */
360 bool            Trace_notify = false;
361
362 /* local function prototypes */
363 static bool asyncQueuePagePrecedesPhysically(int p, int q);
364 static bool asyncQueuePagePrecedesLogically(int p, int q);
365 static void queue_listen(ListenActionKind action, const char *channel);
366 static void Async_UnlistenOnExit(int code, Datum arg);
367 static void Exec_ListenPreCommit(void);
368 static void Exec_ListenCommit(const char *channel);
369 static void Exec_UnlistenCommit(const char *channel);
370 static void Exec_UnlistenAllCommit(void);
371 static bool IsListeningOn(const char *channel);
372 static void asyncQueueUnregister(void);
373 static bool asyncQueueIsFull(void);
374 static bool asyncQueueAdvance(QueuePosition *position, int entryLength);
375 static void asyncQueueNotificationToEntry(Notification *n, AsyncQueueEntry *qe);
376 static ListCell *asyncQueueAddEntries(ListCell *nextNotify);
377 static void asyncQueueFillWarning(void);
378 static bool SignalBackends(void);
379 static void asyncQueueReadAllNotifications(void);
380 static bool asyncQueueProcessPageEntries(QueuePosition *current,
381                                                          QueuePosition stop,
382                                                          char *page_buffer);
383 static void asyncQueueAdvanceTail(void);
384 static void ProcessIncomingNotify(void);
385 static void NotifyMyFrontEnd(const char *channel,
386                                  const char *payload,
387                                  int32 srcPid);
388 static bool AsyncExistsPendingNotify(const char *channel, const char *payload);
389 static void ClearPendingActionsAndNotifies(void);
390
391
392 /*
393  * We will work on the page range of 0..QUEUE_MAX_PAGE.
394  *
395  * asyncQueuePagePrecedesPhysically just checks numerically without any magic
396  * if one page precedes another one.  This is wrong for normal operation but
397  * is helpful when clearing pg_notify/ during startup.
398  *
399  * asyncQueuePagePrecedesLogically compares using wraparound logic, as is
400  * required by slru.c.
401  */
402 static bool
403 asyncQueuePagePrecedesPhysically(int p, int q)
404 {
405         return p < q;
406 }
407
408 static bool
409 asyncQueuePagePrecedesLogically(int p, int q)
410 {
411         int                     diff;
412
413         /*
414          * We have to compare modulo (QUEUE_MAX_PAGE+1)/2.      Both inputs should be
415          * in the range 0..QUEUE_MAX_PAGE.
416          */
417         Assert(p >= 0 && p <= QUEUE_MAX_PAGE);
418         Assert(q >= 0 && q <= QUEUE_MAX_PAGE);
419
420         diff = p - q;
421         if (diff >= ((QUEUE_MAX_PAGE + 1) / 2))
422                 diff -= QUEUE_MAX_PAGE + 1;
423         else if (diff < -((QUEUE_MAX_PAGE + 1) / 2))
424                 diff += QUEUE_MAX_PAGE + 1;
425         return diff < 0;
426 }
427
428 /*
429  * Report space needed for our shared memory area
430  */
431 Size
432 AsyncShmemSize(void)
433 {
434         Size            size;
435
436         /* This had better match AsyncShmemInit */
437         size = mul_size(MaxBackends, sizeof(QueueBackendStatus));
438         size = add_size(size, sizeof(AsyncQueueControl));
439
440         size = add_size(size, SimpleLruShmemSize(NUM_ASYNC_BUFFERS, 0));
441
442         return size;
443 }
444
445 /*
446  * Initialize our shared memory area
447  */
448 void
449 AsyncShmemInit(void)
450 {
451         bool            found;
452         int                     slotno;
453         Size            size;
454
455         /*
456          * Create or attach to the AsyncQueueControl structure.
457          *
458          * The used entries in the backend[] array run from 1 to MaxBackends.
459          * sizeof(AsyncQueueControl) already includes space for the unused zero'th
460          * entry, but we need to add on space for the used entries.
461          */
462         size = mul_size(MaxBackends, sizeof(QueueBackendStatus));
463         size = add_size(size, sizeof(AsyncQueueControl));
464
465         asyncQueueControl = (AsyncQueueControl *)
466                 ShmemInitStruct("Async Queue Control", size, &found);
467
468         if (!found)
469         {
470                 /* First time through, so initialize it */
471                 int                     i;
472
473                 SET_QUEUE_POS(QUEUE_HEAD, 0, 0);
474                 SET_QUEUE_POS(QUEUE_TAIL, 0, 0);
475                 asyncQueueControl->lastQueueFillWarn = 0;
476                 /* zero'th entry won't be used, but let's initialize it anyway */
477                 for (i = 0; i <= MaxBackends; i++)
478                 {
479                         QUEUE_BACKEND_PID(i) = InvalidPid;
480                         SET_QUEUE_POS(QUEUE_BACKEND_POS(i), 0, 0);
481                 }
482         }
483
484         /*
485          * Set up SLRU management of the pg_notify data.
486          */
487         AsyncCtl->PagePrecedes = asyncQueuePagePrecedesLogically;
488         SimpleLruInit(AsyncCtl, "Async Ctl", NUM_ASYNC_BUFFERS, 0,
489                                   AsyncCtlLock, "pg_notify");
490         /* Override default assumption that writes should be fsync'd */
491         AsyncCtl->do_fsync = false;
492
493         if (!found)
494         {
495                 /*
496                  * During start or reboot, clean out the pg_notify directory.
497                  *
498                  * Since we want to remove every file, we temporarily use
499                  * asyncQueuePagePrecedesPhysically() and pass INT_MAX as the
500                  * comparison value; every file in the directory should therefore
501                  * appear to be less than that.
502                  */
503                 AsyncCtl->PagePrecedes = asyncQueuePagePrecedesPhysically;
504                 (void) SlruScanDirectory(AsyncCtl, INT_MAX, true);
505                 AsyncCtl->PagePrecedes = asyncQueuePagePrecedesLogically;
506
507                 /* Now initialize page zero to empty */
508                 LWLockAcquire(AsyncCtlLock, LW_EXCLUSIVE);
509                 slotno = SimpleLruZeroPage(AsyncCtl, QUEUE_POS_PAGE(QUEUE_HEAD));
510                 /* This write is just to verify that pg_notify/ is writable */
511                 SimpleLruWritePage(AsyncCtl, slotno);
512                 LWLockRelease(AsyncCtlLock);
513         }
514 }
515
516
517 /*
518  * pg_notify -
519  *        SQL function to send a notification event
520  */
521 Datum
522 pg_notify(PG_FUNCTION_ARGS)
523 {
524         const char *channel;
525         const char *payload;
526
527         if (PG_ARGISNULL(0))
528                 channel = "";
529         else
530                 channel = text_to_cstring(PG_GETARG_TEXT_PP(0));
531
532         if (PG_ARGISNULL(1))
533                 payload = "";
534         else
535                 payload = text_to_cstring(PG_GETARG_TEXT_PP(1));
536
537         /* For NOTIFY as a statement, this is checked in ProcessUtility */
538         PreventCommandDuringRecovery("NOTIFY");
539
540         Async_Notify(channel, payload);
541
542         PG_RETURN_VOID();
543 }
544
545
546 /*
547  * Async_Notify
548  *
549  *              This is executed by the SQL notify command.
550  *
551  *              Adds the message to the list of pending notifies.
552  *              Actual notification happens during transaction commit.
553  *              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
554  */
555 void
556 Async_Notify(const char *channel, const char *payload)
557 {
558         Notification *n;
559         MemoryContext oldcontext;
560
561         if (Trace_notify)
562                 elog(DEBUG1, "Async_Notify(%s)", channel);
563
564         /* a channel name must be specified */
565         if (!channel || !strlen(channel))
566                 ereport(ERROR,
567                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
568                                  errmsg("channel name cannot be empty")));
569
570         if (strlen(channel) >= NAMEDATALEN)
571                 ereport(ERROR,
572                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
573                                  errmsg("channel name too long")));
574
575         if (payload)
576         {
577                 if (strlen(payload) >= NOTIFY_PAYLOAD_MAX_LENGTH)
578                         ereport(ERROR,
579                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
580                                          errmsg("payload string too long")));
581         }
582
583         /* no point in making duplicate entries in the list ... */
584         if (AsyncExistsPendingNotify(channel, payload))
585                 return;
586
587         /*
588          * The notification list needs to live until end of transaction, so store
589          * it in the transaction context.
590          */
591         oldcontext = MemoryContextSwitchTo(CurTransactionContext);
592
593         n = (Notification *) palloc(sizeof(Notification));
594         n->channel = pstrdup(channel);
595         if (payload)
596                 n->payload = pstrdup(payload);
597         else
598                 n->payload = "";
599
600         /*
601          * We want to preserve the order so we need to append every notification.
602          * See comments at AsyncExistsPendingNotify().
603          */
604         pendingNotifies = lappend(pendingNotifies, n);
605
606         MemoryContextSwitchTo(oldcontext);
607 }
608
609 /*
610  * queue_listen
611  *              Common code for listen, unlisten, unlisten all commands.
612  *
613  *              Adds the request to the list of pending actions.
614  *              Actual update of the listenChannels list happens during transaction
615  *              commit.
616  */
617 static void
618 queue_listen(ListenActionKind action, const char *channel)
619 {
620         MemoryContext oldcontext;
621         ListenAction *actrec;
622
623         /*
624          * Unlike Async_Notify, we don't try to collapse out duplicates. It would
625          * be too complicated to ensure we get the right interactions of
626          * conflicting LISTEN/UNLISTEN/UNLISTEN_ALL, and it's unlikely that there
627          * would be any performance benefit anyway in sane applications.
628          */
629         oldcontext = MemoryContextSwitchTo(CurTransactionContext);
630
631         /* space for terminating null is included in sizeof(ListenAction) */
632         actrec = (ListenAction *) palloc(sizeof(ListenAction) + strlen(channel));
633         actrec->action = action;
634         strcpy(actrec->channel, channel);
635
636         pendingActions = lappend(pendingActions, actrec);
637
638         MemoryContextSwitchTo(oldcontext);
639 }
640
641 /*
642  * Async_Listen
643  *
644  *              This is executed by the SQL listen command.
645  */
646 void
647 Async_Listen(const char *channel)
648 {
649         if (Trace_notify)
650                 elog(DEBUG1, "Async_Listen(%s,%d)", channel, MyProcPid);
651
652         queue_listen(LISTEN_LISTEN, channel);
653 }
654
655 /*
656  * Async_Unlisten
657  *
658  *              This is executed by the SQL unlisten command.
659  */
660 void
661 Async_Unlisten(const char *channel)
662 {
663         if (Trace_notify)
664                 elog(DEBUG1, "Async_Unlisten(%s,%d)", channel, MyProcPid);
665
666         /* If we couldn't possibly be listening, no need to queue anything */
667         if (pendingActions == NIL && !unlistenExitRegistered)
668                 return;
669
670         queue_listen(LISTEN_UNLISTEN, channel);
671 }
672
673 /*
674  * Async_UnlistenAll
675  *
676  *              This is invoked by UNLISTEN * command, and also at backend exit.
677  */
678 void
679 Async_UnlistenAll(void)
680 {
681         if (Trace_notify)
682                 elog(DEBUG1, "Async_UnlistenAll(%d)", MyProcPid);
683
684         /* If we couldn't possibly be listening, no need to queue anything */
685         if (pendingActions == NIL && !unlistenExitRegistered)
686                 return;
687
688         queue_listen(LISTEN_UNLISTEN_ALL, "");
689 }
690
691 /*
692  * SQL function: return a set of the channel names this backend is actively
693  * listening to.
694  *
695  * Note: this coding relies on the fact that the listenChannels list cannot
696  * change within a transaction.
697  */
698 Datum
699 pg_listening_channels(PG_FUNCTION_ARGS)
700 {
701         FuncCallContext *funcctx;
702         ListCell  **lcp;
703
704         /* stuff done only on the first call of the function */
705         if (SRF_IS_FIRSTCALL())
706         {
707                 MemoryContext oldcontext;
708
709                 /* create a function context for cross-call persistence */
710                 funcctx = SRF_FIRSTCALL_INIT();
711
712                 /* switch to memory context appropriate for multiple function calls */
713                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
714
715                 /* allocate memory for user context */
716                 lcp = (ListCell **) palloc(sizeof(ListCell *));
717                 *lcp = list_head(listenChannels);
718                 funcctx->user_fctx = (void *) lcp;
719
720                 MemoryContextSwitchTo(oldcontext);
721         }
722
723         /* stuff done on every call of the function */
724         funcctx = SRF_PERCALL_SETUP();
725         lcp = (ListCell **) funcctx->user_fctx;
726
727         while (*lcp != NULL)
728         {
729                 char       *channel = (char *) lfirst(*lcp);
730
731                 *lcp = lnext(*lcp);
732                 SRF_RETURN_NEXT(funcctx, CStringGetTextDatum(channel));
733         }
734
735         SRF_RETURN_DONE(funcctx);
736 }
737
738 /*
739  * Async_UnlistenOnExit
740  *
741  * This is executed at backend exit if we have done any LISTENs in this
742  * backend.  It might not be necessary anymore, if the user UNLISTENed
743  * everything, but we don't try to detect that case.
744  */
745 static void
746 Async_UnlistenOnExit(int code, Datum arg)
747 {
748         Exec_UnlistenAllCommit();
749 }
750
751 /*
752  * AtPrepare_Notify
753  *
754  *              This is called at the prepare phase of a two-phase
755  *              transaction.  Save the state for possible commit later.
756  */
757 void
758 AtPrepare_Notify(void)
759 {
760         /* It's not allowed to have any pending LISTEN/UNLISTEN/NOTIFY actions */
761         if (pendingActions || pendingNotifies)
762                 ereport(ERROR,
763                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
764                                  errmsg("cannot PREPARE a transaction that has executed LISTEN, UNLISTEN or NOTIFY")));
765 }
766
767 /*
768  * PreCommit_Notify
769  *
770  *              This is called at transaction commit, before actually committing to
771  *              clog.
772  *
773  *              If there are pending LISTEN actions, make sure we are listed in the
774  *              shared-memory listener array.  This must happen before commit to
775  *              ensure we don't miss any notifies from transactions that commit
776  *              just after ours.
777  *
778  *              If there are outbound notify requests in the pendingNotifies list,
779  *              add them to the global queue.  We do that before commit so that
780  *              we can still throw error if we run out of queue space.
781  */
782 void
783 PreCommit_Notify(void)
784 {
785         ListCell   *p;
786
787         if (pendingActions == NIL && pendingNotifies == NIL)
788                 return;                                 /* no relevant statements in this xact */
789
790         if (Trace_notify)
791                 elog(DEBUG1, "PreCommit_Notify");
792
793         Assert(backendHasExecutedInitialListen == false);
794
795         /* Preflight for any pending listen/unlisten actions */
796         foreach(p, pendingActions)
797         {
798                 ListenAction *actrec = (ListenAction *) lfirst(p);
799
800                 switch (actrec->action)
801                 {
802                         case LISTEN_LISTEN:
803                                 Exec_ListenPreCommit();
804                                 break;
805                         case LISTEN_UNLISTEN:
806                                 /* there is no Exec_UnlistenPreCommit() */
807                                 break;
808                         case LISTEN_UNLISTEN_ALL:
809                                 /* there is no Exec_UnlistenAllPreCommit() */
810                                 break;
811                 }
812         }
813
814         /* Queue any pending notifies */
815         if (pendingNotifies)
816         {
817                 ListCell   *nextNotify;
818
819                 /*
820                  * Make sure that we have an XID assigned to the current transaction.
821                  * GetCurrentTransactionId is cheap if we already have an XID, but not
822                  * so cheap if we don't, and we'd prefer not to do that work while
823                  * holding AsyncQueueLock.
824                  */
825                 (void) GetCurrentTransactionId();
826
827                 /*
828                  * Serialize writers by acquiring a special lock that we hold till
829                  * after commit.  This ensures that queue entries appear in commit
830                  * order, and in particular that there are never uncommitted queue
831                  * entries ahead of committed ones, so an uncommitted transaction
832                  * can't block delivery of deliverable notifications.
833                  *
834                  * We use a heavyweight lock so that it'll automatically be released
835                  * after either commit or abort.  This also allows deadlocks to be
836                  * detected, though really a deadlock shouldn't be possible here.
837                  *
838                  * The lock is on "database 0", which is pretty ugly but it doesn't
839                  * seem worth inventing a special locktag category just for this.
840                  * (Historical note: before PG 9.0, a similar lock on "database 0" was
841                  * used by the flatfiles mechanism.)
842                  */
843                 LockSharedObject(DatabaseRelationId, InvalidOid, 0,
844                                                  AccessExclusiveLock);
845
846                 /* Now push the notifications into the queue */
847                 backendHasSentNotifications = true;
848
849                 nextNotify = list_head(pendingNotifies);
850                 while (nextNotify != NULL)
851                 {
852                         /*
853                          * Add the pending notifications to the queue.  We acquire and
854                          * release AsyncQueueLock once per page, which might be overkill
855                          * but it does allow readers to get in while we're doing this.
856                          *
857                          * A full queue is very uncommon and should really not happen,
858                          * given that we have so much space available in the SLRU pages.
859                          * Nevertheless we need to deal with this possibility. Note that
860                          * when we get here we are in the process of committing our
861                          * transaction, but we have not yet committed to clog, so at this
862                          * point in time we can still roll the transaction back.
863                          */
864                         LWLockAcquire(AsyncQueueLock, LW_EXCLUSIVE);
865                         asyncQueueFillWarning();
866                         if (asyncQueueIsFull())
867                                 ereport(ERROR,
868                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
869                                           errmsg("too many notifications in the NOTIFY queue")));
870                         nextNotify = asyncQueueAddEntries(nextNotify);
871                         LWLockRelease(AsyncQueueLock);
872                 }
873         }
874 }
875
876 /*
877  * AtCommit_Notify
878  *
879  *              This is called at transaction commit, after committing to clog.
880  *
881  *              Update listenChannels and clear transaction-local state.
882  */
883 void
884 AtCommit_Notify(void)
885 {
886         ListCell   *p;
887
888         /*
889          * Allow transactions that have not executed LISTEN/UNLISTEN/NOTIFY to
890          * return as soon as possible
891          */
892         if (!pendingActions && !pendingNotifies)
893                 return;
894
895         if (Trace_notify)
896                 elog(DEBUG1, "AtCommit_Notify");
897
898         /* Perform any pending listen/unlisten actions */
899         foreach(p, pendingActions)
900         {
901                 ListenAction *actrec = (ListenAction *) lfirst(p);
902
903                 switch (actrec->action)
904                 {
905                         case LISTEN_LISTEN:
906                                 Exec_ListenCommit(actrec->channel);
907                                 break;
908                         case LISTEN_UNLISTEN:
909                                 Exec_UnlistenCommit(actrec->channel);
910                                 break;
911                         case LISTEN_UNLISTEN_ALL:
912                                 Exec_UnlistenAllCommit();
913                                 break;
914                 }
915         }
916
917         /*
918          * If we did an initial LISTEN, listenChannels now has the entry, so we no
919          * longer need or want the flag to be set.
920          */
921         backendHasExecutedInitialListen = false;
922
923         /* And clean up */
924         ClearPendingActionsAndNotifies();
925 }
926
927 /*
928  * Exec_ListenPreCommit --- subroutine for PreCommit_Notify
929  *
930  * This function must make sure we are ready to catch any incoming messages.
931  */
932 static void
933 Exec_ListenPreCommit(void)
934 {
935         /*
936          * Nothing to do if we are already listening to something, nor if we
937          * already ran this routine in this transaction.
938          */
939         if (listenChannels != NIL || backendHasExecutedInitialListen)
940                 return;
941
942         if (Trace_notify)
943                 elog(DEBUG1, "Exec_ListenPreCommit(%d)", MyProcPid);
944
945         /*
946          * We need this variable to detect an aborted initial LISTEN. In that case
947          * we would set up our pointer but not listen on any channel. This flag
948          * gets cleared in AtCommit_Notify or AtAbort_Notify().
949          */
950         backendHasExecutedInitialListen = true;
951
952         /*
953          * Before registering, make sure we will unlisten before dying. (Note:
954          * this action does not get undone if we abort later.)
955          */
956         if (!unlistenExitRegistered)
957         {
958                 on_shmem_exit(Async_UnlistenOnExit, 0);
959                 unlistenExitRegistered = true;
960         }
961
962         /*
963          * This is our first LISTEN, so establish our pointer.
964          *
965          * We set our pointer to the global tail pointer and then move it forward
966          * over already-committed notifications.  This ensures we cannot miss any
967          * not-yet-committed notifications.  We might get a few more but that
968          * doesn't hurt.
969          */
970         LWLockAcquire(AsyncQueueLock, LW_SHARED);
971         QUEUE_BACKEND_POS(MyBackendId) = QUEUE_TAIL;
972         QUEUE_BACKEND_PID(MyBackendId) = MyProcPid;
973         LWLockRelease(AsyncQueueLock);
974
975         /*
976          * Try to move our pointer forward as far as possible. This will skip over
977          * already-committed notifications. Still, we could get notifications that
978          * have already committed before we started to LISTEN.
979          *
980          * Note that we are not yet listening on anything, so we won't deliver any
981          * notification to the frontend.
982          *
983          * This will also advance the global tail pointer if possible.
984          */
985         asyncQueueReadAllNotifications();
986 }
987
988 /*
989  * Exec_ListenCommit --- subroutine for AtCommit_Notify
990  *
991  * Add the channel to the list of channels we are listening on.
992  */
993 static void
994 Exec_ListenCommit(const char *channel)
995 {
996         MemoryContext oldcontext;
997
998         /* Do nothing if we are already listening on this channel */
999         if (IsListeningOn(channel))
1000                 return;
1001
1002         /*
1003          * Add the new channel name to listenChannels.
1004          *
1005          * XXX It is theoretically possible to get an out-of-memory failure here,
1006          * which would be bad because we already committed.  For the moment it
1007          * doesn't seem worth trying to guard against that, but maybe improve this
1008          * later.
1009          */
1010         oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1011         listenChannels = lappend(listenChannels, pstrdup(channel));
1012         MemoryContextSwitchTo(oldcontext);
1013 }
1014
1015 /*
1016  * Exec_UnlistenCommit --- subroutine for AtCommit_Notify
1017  *
1018  * Remove the specified channel name from listenChannels.
1019  */
1020 static void
1021 Exec_UnlistenCommit(const char *channel)
1022 {
1023         ListCell   *q;
1024         ListCell   *prev;
1025
1026         if (Trace_notify)
1027                 elog(DEBUG1, "Exec_UnlistenCommit(%s,%d)", channel, MyProcPid);
1028
1029         prev = NULL;
1030         foreach(q, listenChannels)
1031         {
1032                 char       *lchan = (char *) lfirst(q);
1033
1034                 if (strcmp(lchan, channel) == 0)
1035                 {
1036                         listenChannels = list_delete_cell(listenChannels, q, prev);
1037                         pfree(lchan);
1038                         break;
1039                 }
1040                 prev = q;
1041         }
1042
1043         /*
1044          * We do not complain about unlistening something not being listened;
1045          * should we?
1046          */
1047
1048         /* If no longer listening to anything, get out of listener array */
1049         if (listenChannels == NIL)
1050                 asyncQueueUnregister();
1051 }
1052
1053 /*
1054  * Exec_UnlistenAllCommit --- subroutine for AtCommit_Notify
1055  *
1056  *              Unlisten on all channels for this backend.
1057  */
1058 static void
1059 Exec_UnlistenAllCommit(void)
1060 {
1061         if (Trace_notify)
1062                 elog(DEBUG1, "Exec_UnlistenAllCommit(%d)", MyProcPid);
1063
1064         list_free_deep(listenChannels);
1065         listenChannels = NIL;
1066
1067         asyncQueueUnregister();
1068 }
1069
1070 /*
1071  * ProcessCompletedNotifies --- send out signals and self-notifies
1072  *
1073  * This is called from postgres.c just before going idle at the completion
1074  * of a transaction.  If we issued any notifications in the just-completed
1075  * transaction, send signals to other backends to process them, and also
1076  * process the queue ourselves to send messages to our own frontend.
1077  *
1078  * The reason that this is not done in AtCommit_Notify is that there is
1079  * a nonzero chance of errors here (for example, encoding conversion errors
1080  * while trying to format messages to our frontend).  An error during
1081  * AtCommit_Notify would be a PANIC condition.  The timing is also arranged
1082  * to ensure that a transaction's self-notifies are delivered to the frontend
1083  * before it gets the terminating ReadyForQuery message.
1084  *
1085  * Note that we send signals and process the queue even if the transaction
1086  * eventually aborted.  This is because we need to clean out whatever got
1087  * added to the queue.
1088  *
1089  * NOTE: we are outside of any transaction here.
1090  */
1091 void
1092 ProcessCompletedNotifies(void)
1093 {
1094         MemoryContext caller_context;
1095         bool            signalled;
1096
1097         /* Nothing to do if we didn't send any notifications */
1098         if (!backendHasSentNotifications)
1099                 return;
1100
1101         /*
1102          * We reset the flag immediately; otherwise, if any sort of error occurs
1103          * below, we'd be locked up in an infinite loop, because control will come
1104          * right back here after error cleanup.
1105          */
1106         backendHasSentNotifications = false;
1107
1108         /*
1109          * We must preserve the caller's memory context (probably MessageContext)
1110          * across the transaction we do here.
1111          */
1112         caller_context = CurrentMemoryContext;
1113
1114         if (Trace_notify)
1115                 elog(DEBUG1, "ProcessCompletedNotifies");
1116
1117         /*
1118          * We must run asyncQueueReadAllNotifications inside a transaction, else
1119          * bad things happen if it gets an error.
1120          */
1121         StartTransactionCommand();
1122
1123         /* Send signals to other backends */
1124         signalled = SignalBackends();
1125
1126         if (listenChannels != NIL)
1127         {
1128                 /* Read the queue ourselves, and send relevant stuff to the frontend */
1129                 asyncQueueReadAllNotifications();
1130         }
1131         else if (!signalled)
1132         {
1133                 /*
1134                  * If we found no other listening backends, and we aren't listening
1135                  * ourselves, then we must execute asyncQueueAdvanceTail to flush the
1136                  * queue, because ain't nobody else gonna do it.  This prevents queue
1137                  * overflow when we're sending useless notifies to nobody. (A new
1138                  * listener could have joined since we looked, but if so this is
1139                  * harmless.)
1140                  */
1141                 asyncQueueAdvanceTail();
1142         }
1143
1144         CommitTransactionCommand();
1145
1146         MemoryContextSwitchTo(caller_context);
1147
1148         /* We don't need pq_flush() here since postgres.c will do one shortly */
1149 }
1150
1151 /*
1152  * Test whether we are actively listening on the given channel name.
1153  *
1154  * Note: this function is executed for every notification found in the queue.
1155  * Perhaps it is worth further optimization, eg convert the list to a sorted
1156  * array so we can binary-search it.  In practice the list is likely to be
1157  * fairly short, though.
1158  */
1159 static bool
1160 IsListeningOn(const char *channel)
1161 {
1162         ListCell   *p;
1163
1164         foreach(p, listenChannels)
1165         {
1166                 char       *lchan = (char *) lfirst(p);
1167
1168                 if (strcmp(lchan, channel) == 0)
1169                         return true;
1170         }
1171         return false;
1172 }
1173
1174 /*
1175  * Remove our entry from the listeners array when we are no longer listening
1176  * on any channel.      NB: must not fail if we're already not listening.
1177  */
1178 static void
1179 asyncQueueUnregister(void)
1180 {
1181         bool            advanceTail;
1182
1183         Assert(listenChannels == NIL);          /* else caller error */
1184
1185         LWLockAcquire(AsyncQueueLock, LW_SHARED);
1186         /* check if entry is valid and oldest ... */
1187         advanceTail = (MyProcPid == QUEUE_BACKEND_PID(MyBackendId)) &&
1188                 QUEUE_POS_EQUAL(QUEUE_BACKEND_POS(MyBackendId), QUEUE_TAIL);
1189         /* ... then mark it invalid */
1190         QUEUE_BACKEND_PID(MyBackendId) = InvalidPid;
1191         LWLockRelease(AsyncQueueLock);
1192
1193         /* If we were the laziest backend, try to advance the tail pointer */
1194         if (advanceTail)
1195                 asyncQueueAdvanceTail();
1196 }
1197
1198 /*
1199  * Test whether there is room to insert more notification messages.
1200  *
1201  * Caller must hold at least shared AsyncQueueLock.
1202  */
1203 static bool
1204 asyncQueueIsFull(void)
1205 {
1206         int                     nexthead;
1207         int                     boundary;
1208
1209         /*
1210          * The queue is full if creating a new head page would create a page that
1211          * logically precedes the current global tail pointer, ie, the head
1212          * pointer would wrap around compared to the tail.      We cannot create such
1213          * a head page for fear of confusing slru.c.  For safety we round the tail
1214          * pointer back to a segment boundary (compare the truncation logic in
1215          * asyncQueueAdvanceTail).
1216          *
1217          * Note that this test is *not* dependent on how much space there is on
1218          * the current head page.  This is necessary because asyncQueueAddEntries
1219          * might try to create the next head page in any case.
1220          */
1221         nexthead = QUEUE_POS_PAGE(QUEUE_HEAD) + 1;
1222         if (nexthead > QUEUE_MAX_PAGE)
1223                 nexthead = 0;                   /* wrap around */
1224         boundary = QUEUE_POS_PAGE(QUEUE_TAIL);
1225         boundary -= boundary % SLRU_PAGES_PER_SEGMENT;
1226         return asyncQueuePagePrecedesLogically(nexthead, boundary);
1227 }
1228
1229 /*
1230  * Advance the QueuePosition to the next entry, assuming that the current
1231  * entry is of length entryLength.      If we jump to a new page the function
1232  * returns true, else false.
1233  */
1234 static bool
1235 asyncQueueAdvance(QueuePosition *position, int entryLength)
1236 {
1237         int                     pageno = QUEUE_POS_PAGE(*position);
1238         int                     offset = QUEUE_POS_OFFSET(*position);
1239         bool            pageJump = false;
1240
1241         /*
1242          * Move to the next writing position: First jump over what we have just
1243          * written or read.
1244          */
1245         offset += entryLength;
1246         Assert(offset <= QUEUE_PAGESIZE);
1247
1248         /*
1249          * In a second step check if another entry can possibly be written to the
1250          * page. If so, stay here, we have reached the next position. If not, then
1251          * we need to move on to the next page.
1252          */
1253         if (offset + QUEUEALIGN(AsyncQueueEntryEmptySize) > QUEUE_PAGESIZE)
1254         {
1255                 pageno++;
1256                 if (pageno > QUEUE_MAX_PAGE)
1257                         pageno = 0;                     /* wrap around */
1258                 offset = 0;
1259                 pageJump = true;
1260         }
1261
1262         SET_QUEUE_POS(*position, pageno, offset);
1263         return pageJump;
1264 }
1265
1266 /*
1267  * Fill the AsyncQueueEntry at *qe with an outbound notification message.
1268  */
1269 static void
1270 asyncQueueNotificationToEntry(Notification *n, AsyncQueueEntry *qe)
1271 {
1272         size_t          channellen = strlen(n->channel);
1273         size_t          payloadlen = strlen(n->payload);
1274         int                     entryLength;
1275
1276         Assert(channellen < NAMEDATALEN);
1277         Assert(payloadlen < NOTIFY_PAYLOAD_MAX_LENGTH);
1278
1279         /* The terminators are already included in AsyncQueueEntryEmptySize */
1280         entryLength = AsyncQueueEntryEmptySize + payloadlen + channellen;
1281         entryLength = QUEUEALIGN(entryLength);
1282         qe->length = entryLength;
1283         qe->dboid = MyDatabaseId;
1284         qe->xid = GetCurrentTransactionId();
1285         qe->srcPid = MyProcPid;
1286         memcpy(qe->data, n->channel, channellen + 1);
1287         memcpy(qe->data + channellen + 1, n->payload, payloadlen + 1);
1288 }
1289
1290 /*
1291  * Add pending notifications to the queue.
1292  *
1293  * We go page by page here, i.e. we stop once we have to go to a new page but
1294  * we will be called again and then fill that next page. If an entry does not
1295  * fit into the current page, we write a dummy entry with an InvalidOid as the
1296  * database OID in order to fill the page. So every page is always used up to
1297  * the last byte which simplifies reading the page later.
1298  *
1299  * We are passed the list cell containing the next notification to write
1300  * and return the first still-unwritten cell back.      Eventually we will return
1301  * NULL indicating all is done.
1302  *
1303  * We are holding AsyncQueueLock already from the caller and grab AsyncCtlLock
1304  * locally in this function.
1305  */
1306 static ListCell *
1307 asyncQueueAddEntries(ListCell *nextNotify)
1308 {
1309         AsyncQueueEntry qe;
1310         int                     pageno;
1311         int                     offset;
1312         int                     slotno;
1313
1314         /* We hold both AsyncQueueLock and AsyncCtlLock during this operation */
1315         LWLockAcquire(AsyncCtlLock, LW_EXCLUSIVE);
1316
1317         /* Fetch the current page */
1318         pageno = QUEUE_POS_PAGE(QUEUE_HEAD);
1319         slotno = SimpleLruReadPage(AsyncCtl, pageno, true, InvalidTransactionId);
1320         /* Note we mark the page dirty before writing in it */
1321         AsyncCtl->shared->page_dirty[slotno] = true;
1322
1323         while (nextNotify != NULL)
1324         {
1325                 Notification *n = (Notification *) lfirst(nextNotify);
1326
1327                 /* Construct a valid queue entry in local variable qe */
1328                 asyncQueueNotificationToEntry(n, &qe);
1329
1330                 offset = QUEUE_POS_OFFSET(QUEUE_HEAD);
1331
1332                 /* Check whether the entry really fits on the current page */
1333                 if (offset + qe.length <= QUEUE_PAGESIZE)
1334                 {
1335                         /* OK, so advance nextNotify past this item */
1336                         nextNotify = lnext(nextNotify);
1337                 }
1338                 else
1339                 {
1340                         /*
1341                          * Write a dummy entry to fill up the page. Actually readers will
1342                          * only check dboid and since it won't match any reader's database
1343                          * OID, they will ignore this entry and move on.
1344                          */
1345                         qe.length = QUEUE_PAGESIZE - offset;
1346                         qe.dboid = InvalidOid;
1347                         qe.data[0] = '\0';      /* empty channel */
1348                         qe.data[1] = '\0';      /* empty payload */
1349                 }
1350
1351                 /* Now copy qe into the shared buffer page */
1352                 memcpy(AsyncCtl->shared->page_buffer[slotno] + offset,
1353                            &qe,
1354                            qe.length);
1355
1356                 /* Advance QUEUE_HEAD appropriately, and note if page is full */
1357                 if (asyncQueueAdvance(&(QUEUE_HEAD), qe.length))
1358                 {
1359                         /*
1360                          * Page is full, so we're done here, but first fill the next page
1361                          * with zeroes.  The reason to do this is to ensure that slru.c's
1362                          * idea of the head page is always the same as ours, which avoids
1363                          * boundary problems in SimpleLruTruncate.      The test in
1364                          * asyncQueueIsFull() ensured that there is room to create this
1365                          * page without overrunning the queue.
1366                          */
1367                         slotno = SimpleLruZeroPage(AsyncCtl, QUEUE_POS_PAGE(QUEUE_HEAD));
1368                         /* And exit the loop */
1369                         break;
1370                 }
1371         }
1372
1373         LWLockRelease(AsyncCtlLock);
1374
1375         return nextNotify;
1376 }
1377
1378 /*
1379  * Check whether the queue is at least half full, and emit a warning if so.
1380  *
1381  * This is unlikely given the size of the queue, but possible.
1382  * The warnings show up at most once every QUEUE_FULL_WARN_INTERVAL.
1383  *
1384  * Caller must hold exclusive AsyncQueueLock.
1385  */
1386 static void
1387 asyncQueueFillWarning(void)
1388 {
1389         int                     headPage = QUEUE_POS_PAGE(QUEUE_HEAD);
1390         int                     tailPage = QUEUE_POS_PAGE(QUEUE_TAIL);
1391         int                     occupied;
1392         double          fillDegree;
1393         TimestampTz t;
1394
1395         occupied = headPage - tailPage;
1396
1397         if (occupied == 0)
1398                 return;                                 /* fast exit for common case */
1399
1400         if (occupied < 0)
1401         {
1402                 /* head has wrapped around, tail not yet */
1403                 occupied += QUEUE_MAX_PAGE + 1;
1404         }
1405
1406         fillDegree = (double) occupied / (double) ((QUEUE_MAX_PAGE + 1) / 2);
1407
1408         if (fillDegree < 0.5)
1409                 return;
1410
1411         t = GetCurrentTimestamp();
1412
1413         if (TimestampDifferenceExceeds(asyncQueueControl->lastQueueFillWarn,
1414                                                                    t, QUEUE_FULL_WARN_INTERVAL))
1415         {
1416                 QueuePosition min = QUEUE_HEAD;
1417                 int32           minPid = InvalidPid;
1418                 int                     i;
1419
1420                 for (i = 1; i <= MaxBackends; i++)
1421                 {
1422                         if (QUEUE_BACKEND_PID(i) != InvalidPid)
1423                         {
1424                                 min = QUEUE_POS_MIN(min, QUEUE_BACKEND_POS(i));
1425                                 if (QUEUE_POS_EQUAL(min, QUEUE_BACKEND_POS(i)))
1426                                         minPid = QUEUE_BACKEND_PID(i);
1427                         }
1428                 }
1429
1430                 ereport(WARNING,
1431                                 (errmsg("NOTIFY queue is %.0f%% full", fillDegree * 100),
1432                                  (minPid != InvalidPid ?
1433                                   errdetail("The server process with PID %d is among those with the oldest transactions.", minPid)
1434                                   : 0),
1435                                  (minPid != InvalidPid ?
1436                                   errhint("The NOTIFY queue cannot be emptied until that process ends its current transaction.")
1437                                   : 0)));
1438
1439                 asyncQueueControl->lastQueueFillWarn = t;
1440         }
1441 }
1442
1443 /*
1444  * Send signals to all listening backends (except our own).
1445  *
1446  * Returns true if we sent at least one signal.
1447  *
1448  * Since we need EXCLUSIVE lock anyway we also check the position of the other
1449  * backends and in case one is already up-to-date we don't signal it.
1450  * This can happen if concurrent notifying transactions have sent a signal and
1451  * the signaled backend has read the other notifications and ours in the same
1452  * step.
1453  *
1454  * Since we know the BackendId and the Pid the signalling is quite cheap.
1455  */
1456 static bool
1457 SignalBackends(void)
1458 {
1459         bool            signalled = false;
1460         int32      *pids;
1461         BackendId  *ids;
1462         int                     count;
1463         int                     i;
1464         int32           pid;
1465
1466         /*
1467          * Identify all backends that are listening and not already up-to-date. We
1468          * don't want to send signals while holding the AsyncQueueLock, so we just
1469          * build a list of target PIDs.
1470          *
1471          * XXX in principle these pallocs could fail, which would be bad. Maybe
1472          * preallocate the arrays?      But in practice this is only run in trivial
1473          * transactions, so there should surely be space available.
1474          */
1475         pids = (int32 *) palloc(MaxBackends * sizeof(int32));
1476         ids = (BackendId *) palloc(MaxBackends * sizeof(BackendId));
1477         count = 0;
1478
1479         LWLockAcquire(AsyncQueueLock, LW_EXCLUSIVE);
1480         for (i = 1; i <= MaxBackends; i++)
1481         {
1482                 pid = QUEUE_BACKEND_PID(i);
1483                 if (pid != InvalidPid && pid != MyProcPid)
1484                 {
1485                         QueuePosition pos = QUEUE_BACKEND_POS(i);
1486
1487                         if (!QUEUE_POS_EQUAL(pos, QUEUE_HEAD))
1488                         {
1489                                 pids[count] = pid;
1490                                 ids[count] = i;
1491                                 count++;
1492                         }
1493                 }
1494         }
1495         LWLockRelease(AsyncQueueLock);
1496
1497         /* Now send signals */
1498         for (i = 0; i < count; i++)
1499         {
1500                 pid = pids[i];
1501
1502                 /*
1503                  * Note: assuming things aren't broken, a signal failure here could
1504                  * only occur if the target backend exited since we released
1505                  * AsyncQueueLock; which is unlikely but certainly possible. So we
1506                  * just log a low-level debug message if it happens.
1507                  */
1508                 if (SendProcSignal(pid, PROCSIG_NOTIFY_INTERRUPT, ids[i]) < 0)
1509                         elog(DEBUG3, "could not signal backend with PID %d: %m", pid);
1510                 else
1511                         signalled = true;
1512         }
1513
1514         pfree(pids);
1515         pfree(ids);
1516
1517         return signalled;
1518 }
1519
1520 /*
1521  * AtAbort_Notify
1522  *
1523  *      This is called at transaction abort.
1524  *
1525  *      Gets rid of pending actions and outbound notifies that we would have
1526  *      executed if the transaction got committed.
1527  */
1528 void
1529 AtAbort_Notify(void)
1530 {
1531         /*
1532          * If we LISTEN but then roll back the transaction we have set our pointer
1533          * but have not made any entry in listenChannels. In that case, remove our
1534          * pointer again.
1535          */
1536         if (backendHasExecutedInitialListen)
1537         {
1538                 /*
1539                  * Checking listenChannels should be redundant but it can't hurt doing
1540                  * it for safety reasons.
1541                  */
1542                 if (listenChannels == NIL)
1543                         asyncQueueUnregister();
1544
1545                 backendHasExecutedInitialListen = false;
1546         }
1547
1548         /* And clean up */
1549         ClearPendingActionsAndNotifies();
1550 }
1551
1552 /*
1553  * AtSubStart_Notify() --- Take care of subtransaction start.
1554  *
1555  * Push empty state for the new subtransaction.
1556  */
1557 void
1558 AtSubStart_Notify(void)
1559 {
1560         MemoryContext old_cxt;
1561
1562         /* Keep the list-of-lists in TopTransactionContext for simplicity */
1563         old_cxt = MemoryContextSwitchTo(TopTransactionContext);
1564
1565         upperPendingActions = lcons(pendingActions, upperPendingActions);
1566
1567         Assert(list_length(upperPendingActions) ==
1568                    GetCurrentTransactionNestLevel() - 1);
1569
1570         pendingActions = NIL;
1571
1572         upperPendingNotifies = lcons(pendingNotifies, upperPendingNotifies);
1573
1574         Assert(list_length(upperPendingNotifies) ==
1575                    GetCurrentTransactionNestLevel() - 1);
1576
1577         pendingNotifies = NIL;
1578
1579         MemoryContextSwitchTo(old_cxt);
1580 }
1581
1582 /*
1583  * AtSubCommit_Notify() --- Take care of subtransaction commit.
1584  *
1585  * Reassign all items in the pending lists to the parent transaction.
1586  */
1587 void
1588 AtSubCommit_Notify(void)
1589 {
1590         List       *parentPendingActions;
1591         List       *parentPendingNotifies;
1592
1593         parentPendingActions = (List *) linitial(upperPendingActions);
1594         upperPendingActions = list_delete_first(upperPendingActions);
1595
1596         Assert(list_length(upperPendingActions) ==
1597                    GetCurrentTransactionNestLevel() - 2);
1598
1599         /*
1600          * Mustn't try to eliminate duplicates here --- see queue_listen()
1601          */
1602         pendingActions = list_concat(parentPendingActions, pendingActions);
1603
1604         parentPendingNotifies = (List *) linitial(upperPendingNotifies);
1605         upperPendingNotifies = list_delete_first(upperPendingNotifies);
1606
1607         Assert(list_length(upperPendingNotifies) ==
1608                    GetCurrentTransactionNestLevel() - 2);
1609
1610         /*
1611          * We could try to eliminate duplicates here, but it seems not worthwhile.
1612          */
1613         pendingNotifies = list_concat(parentPendingNotifies, pendingNotifies);
1614 }
1615
1616 /*
1617  * AtSubAbort_Notify() --- Take care of subtransaction abort.
1618  */
1619 void
1620 AtSubAbort_Notify(void)
1621 {
1622         int                     my_level = GetCurrentTransactionNestLevel();
1623
1624         /*
1625          * All we have to do is pop the stack --- the actions/notifies made in
1626          * this subxact are no longer interesting, and the space will be freed
1627          * when CurTransactionContext is recycled.
1628          *
1629          * This routine could be called more than once at a given nesting level if
1630          * there is trouble during subxact abort.  Avoid dumping core by using
1631          * GetCurrentTransactionNestLevel as the indicator of how far we need to
1632          * prune the list.
1633          */
1634         while (list_length(upperPendingActions) > my_level - 2)
1635         {
1636                 pendingActions = (List *) linitial(upperPendingActions);
1637                 upperPendingActions = list_delete_first(upperPendingActions);
1638         }
1639
1640         while (list_length(upperPendingNotifies) > my_level - 2)
1641         {
1642                 pendingNotifies = (List *) linitial(upperPendingNotifies);
1643                 upperPendingNotifies = list_delete_first(upperPendingNotifies);
1644         }
1645 }
1646
1647 /*
1648  * HandleNotifyInterrupt
1649  *
1650  *              This is called when PROCSIG_NOTIFY_INTERRUPT is received.
1651  *
1652  *              If we are idle (notifyInterruptEnabled is set), we can safely invoke
1653  *              ProcessIncomingNotify directly.  Otherwise, just set a flag
1654  *              to do it later.
1655  */
1656 void
1657 HandleNotifyInterrupt(void)
1658 {
1659         /*
1660          * Note: this is called by a SIGNAL HANDLER. You must be very wary what
1661          * you do here. Some helpful soul had this routine sprinkled with
1662          * TPRINTFs, which would likely lead to corruption of stdio buffers if
1663          * they were ever turned on.
1664          */
1665
1666         /* Don't joggle the elbow of proc_exit */
1667         if (proc_exit_inprogress)
1668                 return;
1669
1670         if (notifyInterruptEnabled)
1671         {
1672                 bool            save_ImmediateInterruptOK = ImmediateInterruptOK;
1673
1674                 /*
1675                  * We may be called while ImmediateInterruptOK is true; turn it off
1676                  * while messing with the NOTIFY state.  (We would have to save and
1677                  * restore it anyway, because PGSemaphore operations inside
1678                  * ProcessIncomingNotify() might reset it.)
1679                  */
1680                 ImmediateInterruptOK = false;
1681
1682                 /*
1683                  * I'm not sure whether some flavors of Unix might allow another
1684                  * SIGUSR1 occurrence to recursively interrupt this routine. To cope
1685                  * with the possibility, we do the same sort of dance that
1686                  * EnableNotifyInterrupt must do --- see that routine for comments.
1687                  */
1688                 notifyInterruptEnabled = 0;             /* disable any recursive signal */
1689                 notifyInterruptOccurred = 1;    /* do at least one iteration */
1690                 for (;;)
1691                 {
1692                         notifyInterruptEnabled = 1;
1693                         if (!notifyInterruptOccurred)
1694                                 break;
1695                         notifyInterruptEnabled = 0;
1696                         if (notifyInterruptOccurred)
1697                         {
1698                                 /* Here, it is finally safe to do stuff. */
1699                                 if (Trace_notify)
1700                                         elog(DEBUG1, "HandleNotifyInterrupt: perform async notify");
1701
1702                                 ProcessIncomingNotify();
1703
1704                                 if (Trace_notify)
1705                                         elog(DEBUG1, "HandleNotifyInterrupt: done");
1706                         }
1707                 }
1708
1709                 /*
1710                  * Restore ImmediateInterruptOK, and check for interrupts if needed.
1711                  */
1712                 ImmediateInterruptOK = save_ImmediateInterruptOK;
1713                 if (save_ImmediateInterruptOK)
1714                         CHECK_FOR_INTERRUPTS();
1715         }
1716         else
1717         {
1718                 /*
1719                  * In this path it is NOT SAFE to do much of anything, except this:
1720                  */
1721                 notifyInterruptOccurred = 1;
1722         }
1723 }
1724
1725 /*
1726  * EnableNotifyInterrupt
1727  *
1728  *              This is called by the PostgresMain main loop just before waiting
1729  *              for a frontend command.  If we are truly idle (ie, *not* inside
1730  *              a transaction block), then process any pending inbound notifies,
1731  *              and enable the signal handler to process future notifies directly.
1732  *
1733  *              NOTE: the signal handler starts out disabled, and stays so until
1734  *              PostgresMain calls this the first time.
1735  */
1736 void
1737 EnableNotifyInterrupt(void)
1738 {
1739         if (IsTransactionOrTransactionBlock())
1740                 return;                                 /* not really idle */
1741
1742         /*
1743          * This code is tricky because we are communicating with a signal handler
1744          * that could interrupt us at any point.  If we just checked
1745          * notifyInterruptOccurred and then set notifyInterruptEnabled, we could
1746          * fail to respond promptly to a signal that happens in between those two
1747          * steps.  (A very small time window, perhaps, but Murphy's Law says you
1748          * can hit it...)  Instead, we first set the enable flag, then test the
1749          * occurred flag.  If we see an unserviced interrupt has occurred, we
1750          * re-clear the enable flag before going off to do the service work. (That
1751          * prevents re-entrant invocation of ProcessIncomingNotify() if another
1752          * interrupt occurs.) If an interrupt comes in between the setting and
1753          * clearing of notifyInterruptEnabled, then it will have done the service
1754          * work and left notifyInterruptOccurred zero, so we have to check again
1755          * after clearing enable.  The whole thing has to be in a loop in case
1756          * another interrupt occurs while we're servicing the first. Once we get
1757          * out of the loop, enable is set and we know there is no unserviced
1758          * interrupt.
1759          *
1760          * NB: an overenthusiastic optimizing compiler could easily break this
1761          * code. Hopefully, they all understand what "volatile" means these days.
1762          */
1763         for (;;)
1764         {
1765                 notifyInterruptEnabled = 1;
1766                 if (!notifyInterruptOccurred)
1767                         break;
1768                 notifyInterruptEnabled = 0;
1769                 if (notifyInterruptOccurred)
1770                 {
1771                         if (Trace_notify)
1772                                 elog(DEBUG1, "EnableNotifyInterrupt: perform async notify");
1773
1774                         ProcessIncomingNotify();
1775
1776                         if (Trace_notify)
1777                                 elog(DEBUG1, "EnableNotifyInterrupt: done");
1778                 }
1779         }
1780 }
1781
1782 /*
1783  * DisableNotifyInterrupt
1784  *
1785  *              This is called by the PostgresMain main loop just after receiving
1786  *              a frontend command.  Signal handler execution of inbound notifies
1787  *              is disabled until the next EnableNotifyInterrupt call.
1788  *
1789  *              The PROCSIG_CATCHUP_INTERRUPT signal handler also needs to call this,
1790  *              so as to prevent conflicts if one signal interrupts the other.  So we
1791  *              must return the previous state of the flag.
1792  */
1793 bool
1794 DisableNotifyInterrupt(void)
1795 {
1796         bool            result = (notifyInterruptEnabled != 0);
1797
1798         notifyInterruptEnabled = 0;
1799
1800         return result;
1801 }
1802
1803 /*
1804  * Read all pending notifications from the queue, and deliver appropriate
1805  * ones to my frontend.  Stop when we reach queue head or an uncommitted
1806  * notification.
1807  */
1808 static void
1809 asyncQueueReadAllNotifications(void)
1810 {
1811         QueuePosition pos;
1812         QueuePosition oldpos;
1813         QueuePosition head;
1814         bool            advanceTail;
1815
1816         /* page_buffer must be adequately aligned, so use a union */
1817         union
1818         {
1819                 char            buf[QUEUE_PAGESIZE];
1820                 AsyncQueueEntry align;
1821         }                       page_buffer;
1822
1823         /* Fetch current state */
1824         LWLockAcquire(AsyncQueueLock, LW_SHARED);
1825         /* Assert checks that we have a valid state entry */
1826         Assert(MyProcPid == QUEUE_BACKEND_PID(MyBackendId));
1827         pos = oldpos = QUEUE_BACKEND_POS(MyBackendId);
1828         head = QUEUE_HEAD;
1829         LWLockRelease(AsyncQueueLock);
1830
1831         if (QUEUE_POS_EQUAL(pos, head))
1832         {
1833                 /* Nothing to do, we have read all notifications already. */
1834                 return;
1835         }
1836
1837         /*----------
1838          * Note that we deliver everything that we see in the queue and that
1839          * matches our _current_ listening state.
1840          * Especially we do not take into account different commit times.
1841          * Consider the following example:
1842          *
1843          * Backend 1:                                    Backend 2:
1844          *
1845          * transaction starts
1846          * NOTIFY foo;
1847          * commit starts
1848          *                                                               transaction starts
1849          *                                                               LISTEN foo;
1850          *                                                               commit starts
1851          * commit to clog
1852          *                                                               commit to clog
1853          *
1854          * It could happen that backend 2 sees the notification from backend 1 in
1855          * the queue.  Even though the notifying transaction committed before
1856          * the listening transaction, we still deliver the notification.
1857          *
1858          * The idea is that an additional notification does not do any harm, we
1859          * just need to make sure that we do not miss a notification.
1860          *
1861          * It is possible that we fail while trying to send a message to our
1862          * frontend (for example, because of encoding conversion failure).
1863          * If that happens it is critical that we not try to send the same
1864          * message over and over again.  Therefore, we place a PG_TRY block
1865          * here that will forcibly advance our backend position before we lose
1866          * control to an error.  (We could alternatively retake AsyncQueueLock
1867          * and move the position before handling each individual message, but
1868          * that seems like too much lock traffic.)
1869          *----------
1870          */
1871         PG_TRY();
1872         {
1873                 bool            reachedStop;
1874
1875                 do
1876                 {
1877                         int                     curpage = QUEUE_POS_PAGE(pos);
1878                         int                     curoffset = QUEUE_POS_OFFSET(pos);
1879                         int                     slotno;
1880                         int                     copysize;
1881
1882                         /*
1883                          * We copy the data from SLRU into a local buffer, so as to avoid
1884                          * holding the AsyncCtlLock while we are examining the entries and
1885                          * possibly transmitting them to our frontend.  Copy only the part
1886                          * of the page we will actually inspect.
1887                          */
1888                         slotno = SimpleLruReadPage_ReadOnly(AsyncCtl, curpage,
1889                                                                                                 InvalidTransactionId);
1890                         if (curpage == QUEUE_POS_PAGE(head))
1891                         {
1892                                 /* we only want to read as far as head */
1893                                 copysize = QUEUE_POS_OFFSET(head) - curoffset;
1894                                 if (copysize < 0)
1895                                         copysize = 0;           /* just for safety */
1896                         }
1897                         else
1898                         {
1899                                 /* fetch all the rest of the page */
1900                                 copysize = QUEUE_PAGESIZE - curoffset;
1901                         }
1902                         memcpy(page_buffer.buf + curoffset,
1903                                    AsyncCtl->shared->page_buffer[slotno] + curoffset,
1904                                    copysize);
1905                         /* Release lock that we got from SimpleLruReadPage_ReadOnly() */
1906                         LWLockRelease(AsyncCtlLock);
1907
1908                         /*
1909                          * Process messages up to the stop position, end of page, or an
1910                          * uncommitted message.
1911                          *
1912                          * Our stop position is what we found to be the head's position
1913                          * when we entered this function. It might have changed already.
1914                          * But if it has, we will receive (or have already received and
1915                          * queued) another signal and come here again.
1916                          *
1917                          * We are not holding AsyncQueueLock here! The queue can only
1918                          * extend beyond the head pointer (see above) and we leave our
1919                          * backend's pointer where it is so nobody will truncate or
1920                          * rewrite pages under us. Especially we don't want to hold a lock
1921                          * while sending the notifications to the frontend.
1922                          */
1923                         reachedStop = asyncQueueProcessPageEntries(&pos, head,
1924                                                                                                            page_buffer.buf);
1925                 } while (!reachedStop);
1926         }
1927         PG_CATCH();
1928         {
1929                 /* Update shared state */
1930                 LWLockAcquire(AsyncQueueLock, LW_SHARED);
1931                 QUEUE_BACKEND_POS(MyBackendId) = pos;
1932                 advanceTail = QUEUE_POS_EQUAL(oldpos, QUEUE_TAIL);
1933                 LWLockRelease(AsyncQueueLock);
1934
1935                 /* If we were the laziest backend, try to advance the tail pointer */
1936                 if (advanceTail)
1937                         asyncQueueAdvanceTail();
1938
1939                 PG_RE_THROW();
1940         }
1941         PG_END_TRY();
1942
1943         /* Update shared state */
1944         LWLockAcquire(AsyncQueueLock, LW_SHARED);
1945         QUEUE_BACKEND_POS(MyBackendId) = pos;
1946         advanceTail = QUEUE_POS_EQUAL(oldpos, QUEUE_TAIL);
1947         LWLockRelease(AsyncQueueLock);
1948
1949         /* If we were the laziest backend, try to advance the tail pointer */
1950         if (advanceTail)
1951                 asyncQueueAdvanceTail();
1952 }
1953
1954 /*
1955  * Fetch notifications from the shared queue, beginning at position current,
1956  * and deliver relevant ones to my frontend.
1957  *
1958  * The current page must have been fetched into page_buffer from shared
1959  * memory.      (We could access the page right in shared memory, but that
1960  * would imply holding the AsyncCtlLock throughout this routine.)
1961  *
1962  * We stop if we reach the "stop" position, or reach a notification from an
1963  * uncommitted transaction, or reach the end of the page.
1964  *
1965  * The function returns true once we have reached the stop position or an
1966  * uncommitted notification, and false if we have finished with the page.
1967  * In other words: once it returns true there is no need to look further.
1968  * The QueuePosition *current is advanced past all processed messages.
1969  */
1970 static bool
1971 asyncQueueProcessPageEntries(QueuePosition *current,
1972                                                          QueuePosition stop,
1973                                                          char *page_buffer)
1974 {
1975         bool            reachedStop = false;
1976         bool            reachedEndOfPage;
1977         AsyncQueueEntry *qe;
1978
1979         do
1980         {
1981                 QueuePosition thisentry = *current;
1982
1983                 if (QUEUE_POS_EQUAL(thisentry, stop))
1984                         break;
1985
1986                 qe = (AsyncQueueEntry *) (page_buffer + QUEUE_POS_OFFSET(thisentry));
1987
1988                 /*
1989                  * Advance *current over this message, possibly to the next page. As
1990                  * noted in the comments for asyncQueueReadAllNotifications, we must
1991                  * do this before possibly failing while processing the message.
1992                  */
1993                 reachedEndOfPage = asyncQueueAdvance(current, qe->length);
1994
1995                 /* Ignore messages destined for other databases */
1996                 if (qe->dboid == MyDatabaseId)
1997                 {
1998                         if (TransactionIdDidCommit(qe->xid))
1999                         {
2000                                 /* qe->data is the null-terminated channel name */
2001                                 char       *channel = qe->data;
2002
2003                                 if (IsListeningOn(channel))
2004                                 {
2005                                         /* payload follows channel name */
2006                                         char       *payload = qe->data + strlen(channel) + 1;
2007
2008                                         NotifyMyFrontEnd(channel, payload, qe->srcPid);
2009                                 }
2010                         }
2011                         else if (TransactionIdDidAbort(qe->xid))
2012                         {
2013                                 /*
2014                                  * If the source transaction aborted, we just ignore its
2015                                  * notifications.
2016                                  */
2017                         }
2018                         else
2019                         {
2020                                 /*
2021                                  * The transaction has neither committed nor aborted so far,
2022                                  * so we can't process its message yet.  Break out of the
2023                                  * loop, but first back up *current so we will reprocess the
2024                                  * message next time.  (Note: it is unlikely but not
2025                                  * impossible for TransactionIdDidCommit to fail, so we can't
2026                                  * really avoid this advance-then-back-up behavior when
2027                                  * dealing with an uncommitted message.)
2028                                  */
2029                                 *current = thisentry;
2030                                 reachedStop = true;
2031                                 break;
2032                         }
2033                 }
2034
2035                 /* Loop back if we're not at end of page */
2036         } while (!reachedEndOfPage);
2037
2038         if (QUEUE_POS_EQUAL(*current, stop))
2039                 reachedStop = true;
2040
2041         return reachedStop;
2042 }
2043
2044 /*
2045  * Advance the shared queue tail variable to the minimum of all the
2046  * per-backend tail pointers.  Truncate pg_notify space if possible.
2047  */
2048 static void
2049 asyncQueueAdvanceTail(void)
2050 {
2051         QueuePosition min;
2052         int                     i;
2053         int                     oldtailpage;
2054         int                     newtailpage;
2055         int                     boundary;
2056
2057         LWLockAcquire(AsyncQueueLock, LW_EXCLUSIVE);
2058         min = QUEUE_HEAD;
2059         for (i = 1; i <= MaxBackends; i++)
2060         {
2061                 if (QUEUE_BACKEND_PID(i) != InvalidPid)
2062                         min = QUEUE_POS_MIN(min, QUEUE_BACKEND_POS(i));
2063         }
2064         oldtailpage = QUEUE_POS_PAGE(QUEUE_TAIL);
2065         QUEUE_TAIL = min;
2066         LWLockRelease(AsyncQueueLock);
2067
2068         /*
2069          * We can truncate something if the global tail advanced across an SLRU
2070          * segment boundary.
2071          *
2072          * XXX it might be better to truncate only once every several segments, to
2073          * reduce the number of directory scans.
2074          */
2075         newtailpage = QUEUE_POS_PAGE(min);
2076         boundary = newtailpage - (newtailpage % SLRU_PAGES_PER_SEGMENT);
2077         if (asyncQueuePagePrecedesLogically(oldtailpage, boundary))
2078         {
2079                 /*
2080                  * SimpleLruTruncate() will ask for AsyncCtlLock but will also release
2081                  * the lock again.
2082                  */
2083                 SimpleLruTruncate(AsyncCtl, newtailpage);
2084         }
2085 }
2086
2087 /*
2088  * ProcessIncomingNotify
2089  *
2090  *              Deal with arriving NOTIFYs from other backends.
2091  *              This is called either directly from the PROCSIG_NOTIFY_INTERRUPT
2092  *              signal handler, or the next time control reaches the outer idle loop.
2093  *              Scan the queue for arriving notifications and report them to my front
2094  *              end.
2095  *
2096  *              NOTE: since we are outside any transaction, we must create our own.
2097  */
2098 static void
2099 ProcessIncomingNotify(void)
2100 {
2101         bool            catchup_enabled;
2102
2103         /* We *must* reset the flag */
2104         notifyInterruptOccurred = 0;
2105
2106         /* Do nothing else if we aren't actively listening */
2107         if (listenChannels == NIL)
2108                 return;
2109
2110         /* Must prevent catchup interrupt while I am running */
2111         catchup_enabled = DisableCatchupInterrupt();
2112
2113         if (Trace_notify)
2114                 elog(DEBUG1, "ProcessIncomingNotify");
2115
2116         set_ps_display("notify interrupt", false);
2117
2118         /*
2119          * We must run asyncQueueReadAllNotifications inside a transaction, else
2120          * bad things happen if it gets an error.
2121          */
2122         StartTransactionCommand();
2123
2124         asyncQueueReadAllNotifications();
2125
2126         CommitTransactionCommand();
2127
2128         /*
2129          * Must flush the notify messages to ensure frontend gets them promptly.
2130          */
2131         pq_flush();
2132
2133         set_ps_display("idle", false);
2134
2135         if (Trace_notify)
2136                 elog(DEBUG1, "ProcessIncomingNotify: done");
2137
2138         if (catchup_enabled)
2139                 EnableCatchupInterrupt();
2140 }
2141
2142 /*
2143  * Send NOTIFY message to my front end.
2144  */
2145 static void
2146 NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid)
2147 {
2148         if (whereToSendOutput == DestRemote)
2149         {
2150                 StringInfoData buf;
2151
2152                 pq_beginmessage(&buf, 'A');
2153                 pq_sendint(&buf, srcPid, sizeof(int32));
2154                 pq_sendstring(&buf, channel);
2155                 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2156                         pq_sendstring(&buf, payload);
2157                 pq_endmessage(&buf);
2158
2159                 /*
2160                  * NOTE: we do not do pq_flush() here.  For a self-notify, it will
2161                  * happen at the end of the transaction, and for incoming notifies
2162                  * ProcessIncomingNotify will do it after finding all the notifies.
2163                  */
2164         }
2165         else
2166                 elog(INFO, "NOTIFY for \"%s\" payload \"%s\"", channel, payload);
2167 }
2168
2169 /* Does pendingNotifies include the given channel/payload? */
2170 static bool
2171 AsyncExistsPendingNotify(const char *channel, const char *payload)
2172 {
2173         ListCell   *p;
2174         Notification *n;
2175
2176         if (pendingNotifies == NIL)
2177                 return false;
2178
2179         if (payload == NULL)
2180                 payload = "";
2181
2182         /*----------
2183          * We need to append new elements to the end of the list in order to keep
2184          * the order. However, on the other hand we'd like to check the list
2185          * backwards in order to make duplicate-elimination a tad faster when the
2186          * same condition is signaled many times in a row. So as a compromise we
2187          * check the tail element first which we can access directly. If this
2188          * doesn't match, we check the whole list.
2189          *
2190          * As we are not checking our parents' lists, we can still get duplicates
2191          * in combination with subtransactions, like in:
2192          *
2193          * begin;
2194          * notify foo '1';
2195          * savepoint foo;
2196          * notify foo '1';
2197          * commit;
2198          *----------
2199          */
2200         n = (Notification *) llast(pendingNotifies);
2201         if (strcmp(n->channel, channel) == 0 &&
2202                 strcmp(n->payload, payload) == 0)
2203                 return true;
2204
2205         foreach(p, pendingNotifies)
2206         {
2207                 n = (Notification *) lfirst(p);
2208
2209                 if (strcmp(n->channel, channel) == 0 &&
2210                         strcmp(n->payload, payload) == 0)
2211                         return true;
2212         }
2213
2214         return false;
2215 }
2216
2217 /* Clear the pendingActions and pendingNotifies lists. */
2218 static void
2219 ClearPendingActionsAndNotifies(void)
2220 {
2221         /*
2222          * We used to have to explicitly deallocate the list members and nodes,
2223          * because they were malloc'd.  Now, since we know they are palloc'd in
2224          * CurTransactionContext, we need not do that --- they'll go away
2225          * automatically at transaction exit.  We need only reset the list head
2226          * pointers.
2227          */
2228         pendingActions = NIL;
2229         pendingNotifies = NIL;
2230 }