PostgreSQL Source Code git master
Loading...
Searching...
No Matches
async.h File Reference
#include <signal.h>
Include dependency graph for async.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

Size AsyncShmemSize (void)
 
void AsyncShmemInit (void)
 
void NotifyMyFrontEnd (const char *channel, const char *payload, int32 srcPid)
 
void Async_Notify (const char *channel, const char *payload)
 
void Async_Listen (const char *channel)
 
void Async_Unlisten (const char *channel)
 
void Async_UnlistenAll (void)
 
void PreCommit_Notify (void)
 
void AtCommit_Notify (void)
 
void AtAbort_Notify (void)
 
void AtSubCommit_Notify (void)
 
void AtSubAbort_Notify (void)
 
void AtPrepare_Notify (void)
 
void HandleNotifyInterrupt (void)
 
void ProcessNotifyInterrupt (bool flush)
 
void AsyncNotifyFreezeXids (TransactionId newFrozenXid)
 

Variables

PGDLLIMPORT bool Trace_notify
 
PGDLLIMPORT int max_notify_queue_pages
 
PGDLLIMPORT volatile sig_atomic_t notifyInterruptPending
 

Function Documentation

◆ Async_Listen()

void Async_Listen ( const char channel)
extern

Definition at line 1046 of file async.c.

1047{
1048 if (Trace_notify)
1049 elog(DEBUG1, "Async_Listen(%s,%d)", channel, MyProcPid);
1050
1051 queue_listen(LISTEN_LISTEN, channel);
1052}
@ LISTEN_LISTEN
Definition async.c:426
bool Trace_notify
Definition async.c:567
static void queue_listen(ListenActionKind action, const char *channel)
Definition async.c:999
#define DEBUG1
Definition elog.h:30
#define elog(elevel,...)
Definition elog.h:226
int MyProcPid
Definition globals.c:47

References DEBUG1, elog, LISTEN_LISTEN, MyProcPid, queue_listen(), and Trace_notify.

Referenced by standard_ProcessUtility().

◆ Async_Notify()

void Async_Notify ( const char channel,
const char payload 
)
extern

Definition at line 897 of file async.c.

898{
899 int my_level = GetCurrentTransactionNestLevel();
900 size_t channel_len;
901 size_t payload_len;
902 Notification *n;
903 MemoryContext oldcontext;
904
905 if (IsParallelWorker())
906 elog(ERROR, "cannot send notifications from a parallel worker");
907
908 if (Trace_notify)
909 elog(DEBUG1, "Async_Notify(%s)", channel);
910
911 channel_len = channel ? strlen(channel) : 0;
912 payload_len = payload ? strlen(payload) : 0;
913
914 /* a channel name must be specified */
915 if (channel_len == 0)
918 errmsg("channel name cannot be empty")));
919
920 /* enforce length limits */
921 if (channel_len >= NAMEDATALEN)
924 errmsg("channel name too long")));
925
926 if (payload_len >= NOTIFY_PAYLOAD_MAX_LENGTH)
929 errmsg("payload string too long")));
930
931 /*
932 * We must construct the Notification entry, even if we end up not using
933 * it, in order to compare it cheaply to existing list entries.
934 *
935 * The notification list needs to live until end of transaction, so store
936 * it in the transaction context.
937 */
939
941 channel_len + payload_len + 2);
942 n->channel_len = channel_len;
943 n->payload_len = payload_len;
944 strcpy(n->data, channel);
945 if (payload)
946 strcpy(n->data + channel_len + 1, payload);
947 else
948 n->data[channel_len + 1] = '\0';
949
950 if (pendingNotifies == NULL || my_level > pendingNotifies->nestingLevel)
951 {
953
954 /*
955 * First notify event in current (sub)xact. Note that we allocate the
956 * NotificationList in TopTransactionContext; the nestingLevel might
957 * get changed later by AtSubCommit_Notify.
958 */
961 sizeof(NotificationList));
962 notifies->nestingLevel = my_level;
963 notifies->events = list_make1(n);
964 /* We certainly don't need a hashtable yet */
965 notifies->hashtab = NULL;
966 /* We won't build uniqueChannelNames/Hash till later, either */
967 notifies->uniqueChannelNames = NIL;
968 notifies->uniqueChannelHash = NULL;
969 notifies->upper = pendingNotifies;
971 }
972 else
973 {
974 /* Now check for duplicates */
976 {
977 /* It's a dup, so forget it */
978 pfree(n);
979 MemoryContextSwitchTo(oldcontext);
980 return;
981 }
982
983 /* Append more events to existing list */
985 }
986
987 MemoryContextSwitchTo(oldcontext);
988}
static bool AsyncExistsPendingNotify(Notification *n)
Definition async.c:3125
static NotificationList * pendingNotifies
Definition async.c:520
static void AddEventToPendingNotifies(Notification *n)
Definition async.c:3166
#define NOTIFY_PAYLOAD_MAX_LENGTH
Definition async.c:200
int errcode(int sqlerrcode)
Definition elog.c:874
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:150
#define IsParallelWorker()
Definition parallel.h:62
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
MemoryContext TopTransactionContext
Definition mcxt.c:171
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc(Size size)
Definition mcxt.c:1387
MemoryContext CurTransactionContext
Definition mcxt.c:172
static char * errmsg
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
#define NAMEDATALEN
const void * data
#define NIL
Definition pg_list.h:68
#define list_make1(x1)
Definition pg_list.h:212
static int fb(int x)
uint16 payload_len
Definition async.c:498
char data[FLEXIBLE_ARRAY_MEMBER]
Definition async.c:500
uint16 channel_len
Definition async.c:497
int GetCurrentTransactionNestLevel(void)
Definition xact.c:931

References AddEventToPendingNotifies(), AsyncExistsPendingNotify(), Notification::channel_len, CurTransactionContext, Notification::data, data, DEBUG1, elog, ereport, errcode(), errmsg, ERROR, fb(), GetCurrentTransactionNestLevel(), IsParallelWorker, list_make1, MemoryContextAlloc(), MemoryContextSwitchTo(), NAMEDATALEN, NotificationList::nestingLevel, NIL, NOTIFY_PAYLOAD_MAX_LENGTH, palloc(), Notification::payload_len, pendingNotifies, pfree(), TopTransactionContext, and Trace_notify.

Referenced by pg_notify(), standard_ProcessUtility(), and triggered_change_notification().

◆ Async_Unlisten()

void Async_Unlisten ( const char channel)
extern

Definition at line 1060 of file async.c.

1061{
1062 if (Trace_notify)
1063 elog(DEBUG1, "Async_Unlisten(%s,%d)", channel, MyProcPid);
1064
1065 /* If we couldn't possibly be listening, no need to queue anything */
1067 return;
1068
1069 queue_listen(LISTEN_UNLISTEN, channel);
1070}
static ActionList * pendingActions
Definition async.c:444
@ LISTEN_UNLISTEN
Definition async.c:427
static bool unlistenExitRegistered
Definition async.c:541

References DEBUG1, elog, fb(), LISTEN_UNLISTEN, MyProcPid, pendingActions, queue_listen(), Trace_notify, and unlistenExitRegistered.

Referenced by standard_ProcessUtility().

◆ Async_UnlistenAll()

void Async_UnlistenAll ( void  )
extern

Definition at line 1078 of file async.c.

1079{
1080 if (Trace_notify)
1081 elog(DEBUG1, "Async_UnlistenAll(%d)", MyProcPid);
1082
1083 /* If we couldn't possibly be listening, no need to queue anything */
1085 return;
1086
1088}
@ LISTEN_UNLISTEN_ALL
Definition async.c:428

References DEBUG1, elog, fb(), LISTEN_UNLISTEN_ALL, MyProcPid, pendingActions, queue_listen(), Trace_notify, and unlistenExitRegistered.

Referenced by DiscardAll(), and standard_ProcessUtility().

◆ AsyncNotifyFreezeXids()

void AsyncNotifyFreezeXids ( TransactionId  newFrozenXid)
extern

Definition at line 2954 of file async.c.

2955{
2956 QueuePosition pos;
2957 QueuePosition head;
2958 int64 curpage = -1;
2959 int slotno = -1;
2960 char *page_buffer = NULL;
2961 bool page_dirty = false;
2962
2963 /*
2964 * Acquire locks in the correct order to avoid deadlocks. As per the
2965 * locking protocol: NotifyQueueTailLock, then NotifyQueueLock, then SLRU
2966 * bank locks.
2967 *
2968 * We only need SHARED mode since we're just reading the head/tail
2969 * positions, not modifying them.
2970 */
2973
2974 pos = QUEUE_TAIL;
2975 head = QUEUE_HEAD;
2976
2977 /* Release NotifyQueueLock early, we only needed to read the positions */
2979
2980 /*
2981 * Scan the queue from tail to head, freezing XIDs as needed. We hold
2982 * NotifyQueueTailLock throughout to ensure the tail doesn't move while
2983 * we're working.
2984 */
2985 while (!QUEUE_POS_EQUAL(pos, head))
2986 {
2988 TransactionId xid;
2989 int64 pageno = QUEUE_POS_PAGE(pos);
2990 int offset = QUEUE_POS_OFFSET(pos);
2991
2992 /* If we need a different page, release old lock and get new one */
2993 if (pageno != curpage)
2994 {
2995 LWLock *lock;
2996
2997 /* Release previous page if any */
2998 if (slotno >= 0)
2999 {
3000 if (page_dirty)
3001 {
3002 NotifyCtl->shared->page_dirty[slotno] = true;
3003 page_dirty = false;
3004 }
3006 }
3007
3008 lock = SimpleLruGetBankLock(NotifyCtl, pageno);
3010 slotno = SimpleLruReadPage(NotifyCtl, pageno, true, &pos);
3011 page_buffer = NotifyCtl->shared->page_buffer[slotno];
3012 curpage = pageno;
3013 }
3014
3015 qe = (AsyncQueueEntry *) (page_buffer + offset);
3016 xid = qe->xid;
3017
3018 if (TransactionIdIsNormal(xid) &&
3020 {
3021 if (TransactionIdDidCommit(xid))
3022 {
3023 qe->xid = FrozenTransactionId;
3024 page_dirty = true;
3025 }
3026 else
3027 {
3028 qe->xid = InvalidTransactionId;
3029 page_dirty = true;
3030 }
3031 }
3032
3033 /* Advance to next entry */
3034 asyncQueueAdvance(&pos, qe->length);
3035 }
3036
3037 /* Release final page lock if we acquired one */
3038 if (slotno >= 0)
3039 {
3040 if (page_dirty)
3041 NotifyCtl->shared->page_dirty[slotno] = true;
3043 }
3044
3046}
#define QUEUE_POS_OFFSET(x)
Definition async.c:238
static bool asyncQueueAdvance(volatile QueuePosition *position, int entryLength)
Definition async.c:1977
#define QUEUE_TAIL
Definition async.c:349
#define QUEUE_POS_PAGE(x)
Definition async.c:237
#define NotifyCtl
Definition async.c:364
#define QUEUE_HEAD
Definition async.c:348
#define QUEUE_POS_EQUAL(x, y)
Definition async.c:246
int64_t int64
Definition c.h:615
uint32 TransactionId
Definition c.h:738
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1177
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1794
@ LW_SHARED
Definition lwlock.h:113
@ LW_EXCLUSIVE
Definition lwlock.h:112
int SimpleLruReadPage(SlruCtl ctl, int64 pageno, bool write_ok, const void *opaque_data)
Definition slru.c:533
static LWLock * SimpleLruGetBankLock(SlruCtl ctl, int64 pageno)
Definition slru.h:171
bool TransactionIdDidCommit(TransactionId transactionId)
Definition transam.c:126
#define FrozenTransactionId
Definition transam.h:33
#define InvalidTransactionId
Definition transam.h:31
#define TransactionIdIsNormal(xid)
Definition transam.h:42
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263

References asyncQueueAdvance(), fb(), FrozenTransactionId, InvalidTransactionId, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), NotifyCtl, QUEUE_HEAD, QUEUE_POS_EQUAL, QUEUE_POS_OFFSET, QUEUE_POS_PAGE, QUEUE_TAIL, SimpleLruGetBankLock(), SimpleLruReadPage(), TransactionIdDidCommit(), TransactionIdIsNormal, and TransactionIdPrecedes().

Referenced by vac_truncate_clog().

◆ AsyncShmemInit()

void AsyncShmemInit ( void  )
extern

Definition at line 803 of file async.c.

804{
805 bool found;
806 Size size;
807
808 /*
809 * Create or attach to the AsyncQueueControl structure.
810 */
811 size = mul_size(MaxBackends, sizeof(QueueBackendStatus));
812 size = add_size(size, offsetof(AsyncQueueControl, backend));
813
815 ShmemInitStruct("Async Queue Control", size, &found);
816
817 if (!found)
818 {
819 /* First time through, so initialize it */
822 QUEUE_STOP_PAGE = 0;
827 for (int i = 0; i < MaxBackends; i++)
828 {
835 }
836 }
837
838 /*
839 * Set up SLRU management of the pg_notify data. Note that long segment
840 * names are used in order to avoid wraparound.
841 */
842 NotifyCtl->PagePrecedes = asyncQueuePagePrecedes;
843 NotifyCtl->errdetail_for_io_error = asyncQueueErrdetailForIoError;
846 SYNC_HANDLER_NONE, true);
847
848 if (!found)
849 {
850 /*
851 * During start or reboot, clean out the pg_notify directory.
852 */
854 }
855}
#define QUEUE_FIRST_LISTENER
Definition async.c:351
#define QUEUE_BACKEND_IS_ADVANCING(i)
Definition async.c:357
#define QUEUE_BACKEND_POS(i)
Definition async.c:355
#define SET_QUEUE_POS(x, y, z)
Definition async.c:240
static int asyncQueueErrdetailForIoError(const void *opaque_data)
Definition async.c:615
static AsyncQueueControl * asyncQueueControl
Definition async.c:346
static bool asyncQueuePagePrecedes(int64 p, int64 q)
Definition async.c:638
#define QUEUE_BACKEND_PID(i)
Definition async.c:352
#define QUEUE_BACKEND_WAKEUP_PENDING(i)
Definition async.c:356
#define QUEUE_NEXT_LISTENER(i)
Definition async.c:354
#define QUEUE_BACKEND_DBOID(i)
Definition async.c:353
#define QUEUE_STOP_PAGE
Definition async.c:350
size_t Size
Definition c.h:691
#define DSA_HANDLE_INVALID
Definition dsa.h:139
#define DSHASH_HANDLE_INVALID
Definition dshash.h:27
int MaxBackends
Definition globals.c:146
int notify_buffers
Definition globals.c:164
int i
Definition isn.c:77
#define InvalidPid
Definition miscadmin.h:32
#define InvalidOid
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
Size add_size(Size s1, Size s2)
Definition shmem.c:485
Size mul_size(Size s1, Size s2)
Definition shmem.c:500
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:381
void SimpleLruInit(SlruCtl ctl, const char *name, int nslots, int nlsns, const char *subdir, int buffer_tranche_id, int bank_tranche_id, SyncRequestHandler sync_handler, bool long_segment_names)
Definition slru.c:254
bool SlruScanDirectory(SlruCtl ctl, SlruScanCallback callback, void *data)
Definition slru.c:1824
bool SlruScanDirCbDeleteAll(SlruCtl ctl, char *filename, int64 segpage, void *data)
Definition slru.c:1777
dshash_table_handle globalChannelTableDSH
Definition async.c:341
TimestampTz lastQueueFillWarn
Definition async.c:339
dsa_handle globalChannelTableDSA
Definition async.c:340
@ SYNC_HANDLER_NONE
Definition sync.h:42

References add_size(), asyncQueueControl, asyncQueueErrdetailForIoError(), asyncQueuePagePrecedes(), DSA_HANDLE_INVALID, DSHASH_HANDLE_INVALID, fb(), AsyncQueueControl::globalChannelTableDSA, AsyncQueueControl::globalChannelTableDSH, i, INVALID_PROC_NUMBER, InvalidOid, InvalidPid, AsyncQueueControl::lastQueueFillWarn, MaxBackends, mul_size(), notify_buffers, NotifyCtl, QUEUE_BACKEND_DBOID, QUEUE_BACKEND_IS_ADVANCING, QUEUE_BACKEND_PID, QUEUE_BACKEND_POS, QUEUE_BACKEND_WAKEUP_PENDING, QUEUE_FIRST_LISTENER, QUEUE_HEAD, QUEUE_NEXT_LISTENER, QUEUE_STOP_PAGE, QUEUE_TAIL, SET_QUEUE_POS, ShmemInitStruct(), SimpleLruInit(), SlruScanDirCbDeleteAll(), SlruScanDirectory(), and SYNC_HANDLER_NONE.

Referenced by CreateOrAttachShmemStructs().

◆ AsyncShmemSize()

Size AsyncShmemSize ( void  )
extern

Definition at line 786 of file async.c.

787{
788 Size size;
789
790 /* This had better match AsyncShmemInit */
791 size = mul_size(MaxBackends, sizeof(QueueBackendStatus));
792 size = add_size(size, offsetof(AsyncQueueControl, backend));
793
795
796 return size;
797}
Size SimpleLruShmemSize(int nslots, int nlsns)
Definition slru.c:200

References add_size(), fb(), MaxBackends, mul_size(), notify_buffers, and SimpleLruShmemSize().

Referenced by CalculateShmemSize().

◆ AtAbort_Notify()

void AtAbort_Notify ( void  )
extern

Definition at line 2421 of file async.c.

2422{
2423 /* Revert staged listen/unlisten changes */
2425
2426 /* If we're no longer listening on anything, unregister */
2429
2430 /* And clean up */
2432}
static void ApplyPendingListenActions(bool isCommit)
Definition async.c:1724
static void ClearPendingActionsAndNotifies(void)
Definition async.c:3280
static bool amRegisteredListener
Definition async.c:544
static void asyncQueueUnregister(void)
Definition async.c:1919
#define LocalChannelTableIsEmpty()
Definition async.c:411

References amRegisteredListener, ApplyPendingListenActions(), asyncQueueUnregister(), ClearPendingActionsAndNotifies(), and LocalChannelTableIsEmpty.

Referenced by AbortTransaction().

◆ AtCommit_Notify()

void AtCommit_Notify ( void  )
extern

Definition at line 1381 of file async.c.

1382{
1383 /*
1384 * Allow transactions that have not executed LISTEN/UNLISTEN/NOTIFY to
1385 * return as soon as possible
1386 */
1388 return;
1389
1390 if (Trace_notify)
1391 elog(DEBUG1, "AtCommit_Notify");
1392
1393 /* Apply staged listen/unlisten changes */
1395
1396 /* If no longer listening to anything, get out of listener array */
1399
1400 /*
1401 * Send signals to listening backends. We need do this only if there are
1402 * pending notifies, which were previously added to the shared queue by
1403 * PreCommit_Notify().
1404 */
1405 if (pendingNotifies != NULL)
1407
1408 /*
1409 * If it's time to try to advance the global tail pointer, do that.
1410 *
1411 * (It might seem odd to do this in the sender, when more than likely the
1412 * listeners won't yet have read the messages we just sent. However,
1413 * there's less contention if only the sender does it, and there is little
1414 * need for urgency in advancing the global tail. So this typically will
1415 * be clearing out messages that were sent some time ago.)
1416 */
1417 if (tryAdvanceTail)
1418 {
1419 tryAdvanceTail = false;
1421 }
1422
1423 /* And clean up */
1425}
static void SignalBackends(void)
Definition async.c:2269
static bool tryAdvanceTail
Definition async.c:564
static void asyncQueueAdvanceTail(void)
Definition async.c:2872

References amRegisteredListener, ApplyPendingListenActions(), asyncQueueAdvanceTail(), asyncQueueUnregister(), ClearPendingActionsAndNotifies(), DEBUG1, elog, fb(), LocalChannelTableIsEmpty, pendingActions, pendingNotifies, SignalBackends(), Trace_notify, and tryAdvanceTail.

Referenced by CommitTransaction().

◆ AtPrepare_Notify()

void AtPrepare_Notify ( void  )
extern

Definition at line 1163 of file async.c.

1164{
1165 /* It's not allowed to have any pending LISTEN/UNLISTEN/NOTIFY actions */
1167 ereport(ERROR,
1169 errmsg("cannot PREPARE a transaction that has executed LISTEN, UNLISTEN, or NOTIFY")));
1170}

References ereport, errcode(), errmsg, ERROR, fb(), pendingActions, and pendingNotifies.

Referenced by PrepareTransaction().

◆ AtSubAbort_Notify()

void AtSubAbort_Notify ( void  )
extern

Definition at line 2510 of file async.c.

2511{
2512 int my_level = GetCurrentTransactionNestLevel();
2513
2514 /*
2515 * All we have to do is pop the stack --- the actions/notifies made in
2516 * this subxact are no longer interesting, and the space will be freed
2517 * when CurTransactionContext is recycled. We still have to free the
2518 * ActionList and NotificationList objects themselves, though, because
2519 * those are allocated in TopTransactionContext.
2520 *
2521 * Note that there might be no entries at all, or no entries for the
2522 * current subtransaction level, either because none were ever created, or
2523 * because we reentered this routine due to trouble during subxact abort.
2524 */
2525 while (pendingActions != NULL &&
2526 pendingActions->nestingLevel >= my_level)
2527 {
2529
2532 }
2533
2534 while (pendingNotifies != NULL &&
2535 pendingNotifies->nestingLevel >= my_level)
2536 {
2538
2541 }
2542}
int nestingLevel
Definition async.c:439
struct ActionList * upper
Definition async.c:441
struct NotificationList * upper
Definition async.c:510

References fb(), GetCurrentTransactionNestLevel(), ActionList::nestingLevel, NotificationList::nestingLevel, pendingActions, pendingNotifies, pfree(), ActionList::upper, and NotificationList::upper.

Referenced by AbortSubTransaction().

◆ AtSubCommit_Notify()

void AtSubCommit_Notify ( void  )
extern

Definition at line 2440 of file async.c.

2441{
2442 int my_level = GetCurrentTransactionNestLevel();
2443
2444 /* If there are actions at our nesting level, we must reparent them. */
2445 if (pendingActions != NULL &&
2446 pendingActions->nestingLevel >= my_level)
2447 {
2448 if (pendingActions->upper == NULL ||
2449 pendingActions->upper->nestingLevel < my_level - 1)
2450 {
2451 /* nothing to merge; give the whole thing to the parent */
2453 }
2454 else
2455 {
2457
2459
2460 /*
2461 * Mustn't try to eliminate duplicates here --- see queue_listen()
2462 */
2465 childPendingActions->actions);
2467 }
2468 }
2469
2470 /* If there are notifies at our nesting level, we must reparent them. */
2471 if (pendingNotifies != NULL &&
2472 pendingNotifies->nestingLevel >= my_level)
2473 {
2474 Assert(pendingNotifies->nestingLevel == my_level);
2475
2476 if (pendingNotifies->upper == NULL ||
2477 pendingNotifies->upper->nestingLevel < my_level - 1)
2478 {
2479 /* nothing to merge; give the whole thing to the parent */
2481 }
2482 else
2483 {
2484 /*
2485 * Formerly, we didn't bother to eliminate duplicates here, but
2486 * now we must, else we fall foul of "Assert(!found)", either here
2487 * or during a later attempt to build the parent-level hashtable.
2488 */
2490 ListCell *l;
2491
2493 /* Insert all the subxact's events into parent, except for dups */
2494 foreach(l, childPendingNotifies->events)
2495 {
2497
2500 }
2502 }
2503 }
2504}
#define Assert(condition)
Definition c.h:945
List * list_concat(List *list1, const List *list2)
Definition list.c:561
#define lfirst(lc)
Definition pg_list.h:172
List * actions
Definition async.c:440

References ActionList::actions, AddEventToPendingNotifies(), Assert, AsyncExistsPendingNotify(), fb(), GetCurrentTransactionNestLevel(), lfirst, list_concat(), ActionList::nestingLevel, NotificationList::nestingLevel, pendingActions, pendingNotifies, pfree(), ActionList::upper, and NotificationList::upper.

Referenced by CommitSubTransaction().

◆ HandleNotifyInterrupt()

void HandleNotifyInterrupt ( void  )
extern

Definition at line 2553 of file async.c.

2554{
2555 /*
2556 * Note: this is called by a SIGNAL HANDLER. You must be very wary what
2557 * you do here.
2558 */
2559
2560 /* signal that work needs to be done */
2562
2563 /* make sure the event is processed in due course */
2565}
volatile sig_atomic_t notifyInterruptPending
Definition async.c:538
struct Latch * MyLatch
Definition globals.c:63
void SetLatch(Latch *latch)
Definition latch.c:290

References MyLatch, notifyInterruptPending, and SetLatch().

Referenced by procsignal_sigusr1_handler().

◆ NotifyMyFrontEnd()

void NotifyMyFrontEnd ( const char channel,
const char payload,
int32  srcPid 
)
extern

Definition at line 3101 of file async.c.

3102{
3104 {
3106
3108 pq_sendint32(&buf, srcPid);
3109 pq_sendstring(&buf, channel);
3110 pq_sendstring(&buf, payload);
3112
3113 /*
3114 * NOTE: we do not do pq_flush() here. Some level of caller will
3115 * handle it later, allowing this message to be combined into a packet
3116 * with other ones.
3117 */
3118 }
3119 else
3120 elog(INFO, "NOTIFY for \"%s\" payload \"%s\"", channel, payload);
3121}
@ DestRemote
Definition dest.h:89
#define INFO
Definition elog.h:34
static char buf[DEFAULT_XLOG_SEG_SIZE]
CommandDest whereToSendOutput
Definition postgres.c:94
void pq_sendstring(StringInfo buf, const char *str)
Definition pqformat.c:195
void pq_endmessage(StringInfo buf)
Definition pqformat.c:296
void pq_beginmessage(StringInfo buf, char msgtype)
Definition pqformat.c:88
static void pq_sendint32(StringInfo buf, uint32 i)
Definition pqformat.h:144
#define PqMsg_NotificationResponse
Definition protocol.h:41

References buf, DestRemote, elog, INFO, pq_beginmessage(), pq_endmessage(), pq_sendint32(), pq_sendstring(), PqMsg_NotificationResponse, and whereToSendOutput.

Referenced by asyncQueueProcessPageEntries(), and ProcessParallelMessage().

◆ PreCommit_Notify()

void PreCommit_Notify ( void  )
extern

Definition at line 1188 of file async.c.

1189{
1190 ListCell *p;
1191
1193 return; /* no relevant statements in this xact */
1194
1195 if (Trace_notify)
1196 elog(DEBUG1, "PreCommit_Notify");
1197
1198 /* Preflight for any pending listen/unlisten actions */
1200
1201 if (pendingActions != NULL)
1202 {
1203 /* Ensure we have a local channel table */
1205 /* Create pendingListenActions hash table for this transaction */
1207
1208 /* Stage all the actions this transaction wants to perform */
1209 foreach(p, pendingActions->actions)
1210 {
1212
1213 switch (actrec->action)
1214 {
1215 case LISTEN_LISTEN:
1218 break;
1219 case LISTEN_UNLISTEN:
1221 break;
1224 break;
1225 }
1226 }
1227 }
1228
1229 /* Queue any pending notifies (must happen after the above) */
1230 if (pendingNotifies)
1231 {
1233 bool firstIteration = true;
1234
1235 /*
1236 * Build list of unique channel names being notified for use by
1237 * SignalBackends().
1238 *
1239 * If uniqueChannelHash is available, use it to efficiently get the
1240 * unique channels. Otherwise, fall back to the O(N^2) approach.
1241 */
1244 {
1245 HASH_SEQ_STATUS status;
1247
1249 while ((channelEntry = (ChannelName *) hash_seq_search(&status)) != NULL)
1252 channelEntry->channel);
1253 }
1254 else
1255 {
1256 /* O(N^2) approach is better for small number of notifications */
1258 {
1259 char *channel = n->data;
1260 bool found = false;
1261
1262 /* Name present in list? */
1264 {
1265 if (strcmp(oldchan, channel) == 0)
1266 {
1267 found = true;
1268 break;
1269 }
1270 }
1271 /* Add if not already in list */
1272 if (!found)
1275 channel);
1276 }
1277 }
1278
1279 /* Preallocate workspace that will be needed by SignalBackends() */
1280 if (signalPids == NULL)
1282 MaxBackends * sizeof(int32));
1283
1284 if (signalProcnos == NULL)
1286 MaxBackends * sizeof(ProcNumber));
1287
1288 /*
1289 * Make sure that we have an XID assigned to the current transaction.
1290 * GetCurrentTransactionId is cheap if we already have an XID, but not
1291 * so cheap if we don't, and we'd prefer not to do that work while
1292 * holding NotifyQueueLock.
1293 */
1295
1296 /*
1297 * Serialize writers by acquiring a special lock that we hold till
1298 * after commit. This ensures that queue entries appear in commit
1299 * order, and in particular that there are never uncommitted queue
1300 * entries ahead of committed ones, so an uncommitted transaction
1301 * can't block delivery of deliverable notifications.
1302 *
1303 * We use a heavyweight lock so that it'll automatically be released
1304 * after either commit or abort. This also allows deadlocks to be
1305 * detected, though really a deadlock shouldn't be possible here.
1306 *
1307 * The lock is on "database 0", which is pretty ugly but it doesn't
1308 * seem worth inventing a special locktag category just for this.
1309 * (Historical note: before PG 9.0, a similar lock on "database 0" was
1310 * used by the flatfiles mechanism.)
1311 */
1314
1315 /*
1316 * For the direct advancement optimization in SignalBackends(), we
1317 * need to ensure that no other backend can insert queue entries
1318 * between queueHeadBeforeWrite and queueHeadAfterWrite. The
1319 * heavyweight lock above provides this guarantee, since it serializes
1320 * all writers.
1321 *
1322 * Note: if the heavyweight lock were ever removed for scalability
1323 * reasons, we could achieve the same guarantee by holding
1324 * NotifyQueueLock in EXCLUSIVE mode across all our insertions, rather
1325 * than releasing and reacquiring it for each page as we do below.
1326 */
1327
1328 /* Initialize values to a safe default in case list is empty */
1331
1332 /* Now push the notifications into the queue */
1334 while (nextNotify != NULL)
1335 {
1336 /*
1337 * Add the pending notifications to the queue. We acquire and
1338 * release NotifyQueueLock once per page, which might be overkill
1339 * but it does allow readers to get in while we're doing this.
1340 *
1341 * A full queue is very uncommon and should really not happen,
1342 * given that we have so much space available in the SLRU pages.
1343 * Nevertheless we need to deal with this possibility. Note that
1344 * when we get here we are in the process of committing our
1345 * transaction, but we have not yet committed to clog, so at this
1346 * point in time we can still roll the transaction back.
1347 */
1349 if (firstIteration)
1350 {
1352 firstIteration = false;
1353 }
1355 if (asyncQueueIsFull())
1356 ereport(ERROR,
1358 errmsg("too many notifications in the NOTIFY queue")));
1362 }
1363
1364 /* Note that we don't clear pendingNotifies; AtCommit_Notify will. */
1365 }
1366}
static void PrepareTableEntriesForListen(const char *channel)
Definition async.c:1534
static void BecomeRegisteredListener(void)
Definition async.c:1433
static int32 * signalPids
Definition async.c:560
static void PrepareTableEntriesForUnlisten(const char *channel)
Definition async.c:1637
static ProcNumber * signalProcnos
Definition async.c:561
static QueuePosition queueHeadAfterWrite
Definition async.c:553
static ListCell * asyncQueueAddEntries(ListCell *nextNotify)
Definition async.c:2046
static void PrepareTableEntriesForUnlistenAll(void)
Definition async.c:1667
static void asyncQueueFillWarning(void)
Definition async.c:2217
static void initGlobalChannelTable(void)
Definition async.c:687
static bool asyncQueueIsFull(void)
Definition async.c:1962
static void initLocalChannelTable(void)
Definition async.c:738
static void initPendingListenActions(void)
Definition async.c:764
static QueuePosition queueHeadBeforeWrite
Definition async.c:552
int32_t int32
Definition c.h:614
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1415
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1380
List * lappend(List *list, void *datum)
Definition list.c:339
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1088
#define AccessExclusiveLock
Definition lockdefs.h:43
MemoryContext TopMemoryContext
Definition mcxt.c:166
#define foreach_ptr(type, var, lst)
Definition pg_list.h:469
static ListCell * list_head(const List *l)
Definition pg_list.h:128
int ProcNumber
Definition procnumber.h:24
List * uniqueChannelNames
Definition async.c:508
HTAB * uniqueChannelHash
Definition async.c:509
List * events
Definition async.c:506
TransactionId GetCurrentTransactionId(void)
Definition xact.c:456

References AccessExclusiveLock, ActionList::actions, asyncQueueAddEntries(), asyncQueueFillWarning(), asyncQueueIsFull(), BecomeRegisteredListener(), DEBUG1, elog, ereport, errcode(), errmsg, ERROR, NotificationList::events, fb(), foreach_ptr, GetCurrentTransactionId(), hash_seq_init(), hash_seq_search(), initGlobalChannelTable(), initLocalChannelTable(), initPendingListenActions(), InvalidOid, lappend(), lfirst, list_head(), LISTEN_LISTEN, LISTEN_UNLISTEN, LISTEN_UNLISTEN_ALL, LockSharedObject(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MaxBackends, MemoryContextAlloc(), NIL, pendingActions, pendingNotifies, PrepareTableEntriesForListen(), PrepareTableEntriesForUnlisten(), PrepareTableEntriesForUnlistenAll(), QUEUE_HEAD, queueHeadAfterWrite, queueHeadBeforeWrite, SET_QUEUE_POS, signalPids, signalProcnos, TopMemoryContext, Trace_notify, NotificationList::uniqueChannelHash, and NotificationList::uniqueChannelNames.

Referenced by CommitTransaction().

◆ ProcessNotifyInterrupt()

void ProcessNotifyInterrupt ( bool  flush)
extern

Definition at line 2583 of file async.c.

2584{
2586 return; /* not really idle */
2587
2588 /* Loop in case another signal arrives while sending messages */
2590 ProcessIncomingNotify(flush);
2591}
static void ProcessIncomingNotify(bool flush)
Definition async.c:3060
bool IsTransactionOrTransactionBlock(void)
Definition xact.c:5012

References IsTransactionOrTransactionBlock(), notifyInterruptPending, and ProcessIncomingNotify().

Referenced by PostgresMain(), and ProcessClientReadInterrupt().

Variable Documentation

◆ max_notify_queue_pages

PGDLLIMPORT int max_notify_queue_pages
extern

Definition at line 570 of file async.c.

Referenced by asyncQueueIsFull(), and asyncQueueUsage().

◆ notifyInterruptPending

◆ Trace_notify