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