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