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