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