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 1034 of file async.c.

1035{
1036 if (Trace_notify)
1037 elog(DEBUG1, "Async_Listen(%s,%d)", channel, MyProcPid);
1038
1039 queue_listen(LISTEN_LISTEN, channel);
1040}
@ LISTEN_LISTEN
Definition async.c:425
bool Trace_notify
Definition async.c:566
static void queue_listen(ListenActionKind action, const char *channel)
Definition async.c:987
#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 885 of file async.c.

886{
887 int my_level = GetCurrentTransactionNestLevel();
888 size_t channel_len;
889 size_t payload_len;
890 Notification *n;
891 MemoryContext oldcontext;
892
893 if (IsParallelWorker())
894 elog(ERROR, "cannot send notifications from a parallel worker");
895
896 if (Trace_notify)
897 elog(DEBUG1, "Async_Notify(%s)", channel);
898
899 channel_len = channel ? strlen(channel) : 0;
900 payload_len = payload ? strlen(payload) : 0;
901
902 /* a channel name must be specified */
903 if (channel_len == 0)
906 errmsg("channel name cannot be empty")));
907
908 /* enforce length limits */
909 if (channel_len >= NAMEDATALEN)
912 errmsg("channel name too long")));
913
914 if (payload_len >= NOTIFY_PAYLOAD_MAX_LENGTH)
917 errmsg("payload string too long")));
918
919 /*
920 * We must construct the Notification entry, even if we end up not using
921 * it, in order to compare it cheaply to existing list entries.
922 *
923 * The notification list needs to live until end of transaction, so store
924 * it in the transaction context.
925 */
927
929 channel_len + payload_len + 2);
930 n->channel_len = channel_len;
931 n->payload_len = payload_len;
932 strcpy(n->data, channel);
933 if (payload)
934 strcpy(n->data + channel_len + 1, payload);
935 else
936 n->data[channel_len + 1] = '\0';
937
938 if (pendingNotifies == NULL || my_level > pendingNotifies->nestingLevel)
939 {
941
942 /*
943 * First notify event in current (sub)xact. Note that we allocate the
944 * NotificationList in TopTransactionContext; the nestingLevel might
945 * get changed later by AtSubCommit_Notify.
946 */
949 sizeof(NotificationList));
950 notifies->nestingLevel = my_level;
951 notifies->events = list_make1(n);
952 /* We certainly don't need a hashtable yet */
953 notifies->hashtab = NULL;
954 /* We won't build uniqueChannelNames/Hash till later, either */
955 notifies->uniqueChannelNames = NIL;
956 notifies->uniqueChannelHash = NULL;
957 notifies->upper = pendingNotifies;
959 }
960 else
961 {
962 /* Now check for duplicates */
964 {
965 /* It's a dup, so forget it */
966 pfree(n);
967 MemoryContextSwitchTo(oldcontext);
968 return;
969 }
970
971 /* Append more events to existing list */
973 }
974
975 MemoryContextSwitchTo(oldcontext);
976}
static bool AsyncExistsPendingNotify(Notification *n)
Definition async.c:3116
static NotificationList * pendingNotifies
Definition async.c:519
static void AddEventToPendingNotifies(Notification *n)
Definition async.c:3157
#define NOTIFY_PAYLOAD_MAX_LENGTH
Definition async.c:199
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:150
#define IsParallelWorker()
Definition parallel.h:60
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 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:497
char data[FLEXIBLE_ARRAY_MEMBER]
Definition async.c:499
uint16 channel_len
Definition async.c:496
int GetCurrentTransactionNestLevel(void)
Definition xact.c:930

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 1048 of file async.c.

1049{
1050 if (Trace_notify)
1051 elog(DEBUG1, "Async_Unlisten(%s,%d)", channel, MyProcPid);
1052
1053 /* If we couldn't possibly be listening, no need to queue anything */
1055 return;
1056
1057 queue_listen(LISTEN_UNLISTEN, channel);
1058}
static ActionList * pendingActions
Definition async.c:443
@ LISTEN_UNLISTEN
Definition async.c:426
static bool unlistenExitRegistered
Definition async.c:540

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 1066 of file async.c.

1067{
1068 if (Trace_notify)
1069 elog(DEBUG1, "Async_UnlistenAll(%d)", MyProcPid);
1070
1071 /* If we couldn't possibly be listening, no need to queue anything */
1073 return;
1074
1076}
@ LISTEN_UNLISTEN_ALL
Definition async.c:427

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 2944 of file async.c.

2945{
2946 QueuePosition pos;
2947 QueuePosition head;
2948 int64 curpage = -1;
2949 int slotno = -1;
2950 char *page_buffer = NULL;
2951 bool page_dirty = false;
2952
2953 /*
2954 * Acquire locks in the correct order to avoid deadlocks. As per the
2955 * locking protocol: NotifyQueueTailLock, then NotifyQueueLock, then SLRU
2956 * bank locks.
2957 *
2958 * We only need SHARED mode since we're just reading the head/tail
2959 * positions, not modifying them.
2960 */
2963
2964 pos = QUEUE_TAIL;
2965 head = QUEUE_HEAD;
2966
2967 /* Release NotifyQueueLock early, we only needed to read the positions */
2969
2970 /*
2971 * Scan the queue from tail to head, freezing XIDs as needed. We hold
2972 * NotifyQueueTailLock throughout to ensure the tail doesn't move while
2973 * we're working.
2974 */
2975 while (!QUEUE_POS_EQUAL(pos, head))
2976 {
2978 TransactionId xid;
2979 int64 pageno = QUEUE_POS_PAGE(pos);
2980 int offset = QUEUE_POS_OFFSET(pos);
2981
2982 /* If we need a different page, release old lock and get new one */
2983 if (pageno != curpage)
2984 {
2985 LWLock *lock;
2986
2987 /* Release previous page if any */
2988 if (slotno >= 0)
2989 {
2990 if (page_dirty)
2991 {
2992 NotifyCtl->shared->page_dirty[slotno] = true;
2993 page_dirty = false;
2994 }
2996 }
2997
2998 lock = SimpleLruGetBankLock(NotifyCtl, pageno);
3000 slotno = SimpleLruReadPage(NotifyCtl, pageno, true,
3002 page_buffer = NotifyCtl->shared->page_buffer[slotno];
3003 curpage = pageno;
3004 }
3005
3006 qe = (AsyncQueueEntry *) (page_buffer + offset);
3007 xid = qe->xid;
3008
3009 if (TransactionIdIsNormal(xid) &&
3011 {
3012 if (TransactionIdDidCommit(xid))
3013 {
3014 qe->xid = FrozenTransactionId;
3015 page_dirty = true;
3016 }
3017 else
3018 {
3019 qe->xid = InvalidTransactionId;
3020 page_dirty = true;
3021 }
3022 }
3023
3024 /* Advance to next entry */
3025 asyncQueueAdvance(&pos, qe->length);
3026 }
3027
3028 /* Release final page lock if we acquired one */
3029 if (slotno >= 0)
3030 {
3031 if (page_dirty)
3032 NotifyCtl->shared->page_dirty[slotno] = true;
3034 }
3035
3037}
#define QUEUE_POS_OFFSET(x)
Definition async.c:237
static bool asyncQueueAdvance(volatile QueuePosition *position, int entryLength)
Definition async.c:1965
#define QUEUE_TAIL
Definition async.c:348
#define QUEUE_POS_PAGE(x)
Definition async.c:236
#define NotifyCtl
Definition async.c:363
#define QUEUE_HEAD
Definition async.c:347
#define QUEUE_POS_EQUAL(x, y)
Definition async.c:245
int64_t int64
Definition c.h:543
uint32 TransactionId
Definition c.h:666
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1176
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1793
@ LW_SHARED
Definition lwlock.h:113
@ LW_EXCLUSIVE
Definition lwlock.h:112
int SimpleLruReadPage(SlruCtl ctl, int64 pageno, bool write_ok, TransactionId xid)
Definition slru.c:527
static LWLock * SimpleLruGetBankLock(SlruCtl ctl, int64 pageno)
Definition slru.h:160
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 792 of file async.c.

793{
794 bool found;
795 Size size;
796
797 /*
798 * Create or attach to the AsyncQueueControl structure.
799 */
800 size = mul_size(MaxBackends, sizeof(QueueBackendStatus));
801 size = add_size(size, offsetof(AsyncQueueControl, backend));
802
804 ShmemInitStruct("Async Queue Control", size, &found);
805
806 if (!found)
807 {
808 /* First time through, so initialize it */
811 QUEUE_STOP_PAGE = 0;
816 for (int i = 0; i < MaxBackends; i++)
817 {
824 }
825 }
826
827 /*
828 * Set up SLRU management of the pg_notify data. Note that long segment
829 * names are used in order to avoid wraparound.
830 */
831 NotifyCtl->PagePrecedes = asyncQueuePagePrecedes;
834 SYNC_HANDLER_NONE, true);
835
836 if (!found)
837 {
838 /*
839 * During start or reboot, clean out the pg_notify directory.
840 */
842 }
843}
#define QUEUE_FIRST_LISTENER
Definition async.c:350
#define QUEUE_BACKEND_IS_ADVANCING(i)
Definition async.c:356
#define QUEUE_BACKEND_POS(i)
Definition async.c:354
#define SET_QUEUE_POS(x, y, z)
Definition async.c:239
static AsyncQueueControl * asyncQueueControl
Definition async.c:345
static bool asyncQueuePagePrecedes(int64 p, int64 q)
Definition async.c:627
#define QUEUE_BACKEND_PID(i)
Definition async.c:351
#define QUEUE_BACKEND_WAKEUP_PENDING(i)
Definition async.c:355
#define QUEUE_NEXT_LISTENER(i)
Definition async.c:353
#define QUEUE_BACKEND_DBOID(i)
Definition async.c:352
#define QUEUE_STOP_PAGE
Definition async.c:349
size_t Size
Definition c.h:619
#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:482
Size mul_size(Size s1, Size s2)
Definition shmem.c:497
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:378
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:252
bool SlruScanDirectory(SlruCtl ctl, SlruScanCallback callback, void *data)
Definition slru.c:1816
bool SlruScanDirCbDeleteAll(SlruCtl ctl, char *filename, int64 segpage, void *data)
Definition slru.c:1769
dshash_table_handle globalChannelTableDSH
Definition async.c:340
TimestampTz lastQueueFillWarn
Definition async.c:338
dsa_handle globalChannelTableDSA
Definition async.c:339
@ SYNC_HANDLER_NONE
Definition sync.h:42

References add_size(), asyncQueueControl, 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 775 of file async.c.

776{
777 Size size;
778
779 /* This had better match AsyncShmemInit */
780 size = mul_size(MaxBackends, sizeof(QueueBackendStatus));
781 size = add_size(size, offsetof(AsyncQueueControl, backend));
782
784
785 return size;
786}
Size SimpleLruShmemSize(int nslots, int nlsns)
Definition slru.c:198

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

Referenced by CalculateShmemSize().

◆ AtAbort_Notify()

void AtAbort_Notify ( void  )
extern

Definition at line 2410 of file async.c.

2411{
2412 /* Revert staged listen/unlisten changes */
2414
2415 /* If we're no longer listening on anything, unregister */
2418
2419 /* And clean up */
2421}
static void ApplyPendingListenActions(bool isCommit)
Definition async.c:1712
static void ClearPendingActionsAndNotifies(void)
Definition async.c:3271
static bool amRegisteredListener
Definition async.c:543
static void asyncQueueUnregister(void)
Definition async.c:1907
#define LocalChannelTableIsEmpty()
Definition async.c:410

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

Referenced by AbortTransaction().

◆ AtCommit_Notify()

void AtCommit_Notify ( void  )
extern

Definition at line 1369 of file async.c.

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

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 1151 of file async.c.

1152{
1153 /* It's not allowed to have any pending LISTEN/UNLISTEN/NOTIFY actions */
1155 ereport(ERROR,
1157 errmsg("cannot PREPARE a transaction that has executed LISTEN, UNLISTEN, or NOTIFY")));
1158}

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

Referenced by PrepareTransaction().

◆ AtSubAbort_Notify()

void AtSubAbort_Notify ( void  )
extern

Definition at line 2499 of file async.c.

2500{
2501 int my_level = GetCurrentTransactionNestLevel();
2502
2503 /*
2504 * All we have to do is pop the stack --- the actions/notifies made in
2505 * this subxact are no longer interesting, and the space will be freed
2506 * when CurTransactionContext is recycled. We still have to free the
2507 * ActionList and NotificationList objects themselves, though, because
2508 * those are allocated in TopTransactionContext.
2509 *
2510 * Note that there might be no entries at all, or no entries for the
2511 * current subtransaction level, either because none were ever created, or
2512 * because we reentered this routine due to trouble during subxact abort.
2513 */
2514 while (pendingActions != NULL &&
2515 pendingActions->nestingLevel >= my_level)
2516 {
2518
2521 }
2522
2523 while (pendingNotifies != NULL &&
2524 pendingNotifies->nestingLevel >= my_level)
2525 {
2527
2530 }
2531}
int nestingLevel
Definition async.c:438
struct ActionList * upper
Definition async.c:440
struct NotificationList * upper
Definition async.c:509

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 2429 of file async.c.

2430{
2431 int my_level = GetCurrentTransactionNestLevel();
2432
2433 /* If there are actions at our nesting level, we must reparent them. */
2434 if (pendingActions != NULL &&
2435 pendingActions->nestingLevel >= my_level)
2436 {
2437 if (pendingActions->upper == NULL ||
2438 pendingActions->upper->nestingLevel < my_level - 1)
2439 {
2440 /* nothing to merge; give the whole thing to the parent */
2442 }
2443 else
2444 {
2446
2448
2449 /*
2450 * Mustn't try to eliminate duplicates here --- see queue_listen()
2451 */
2454 childPendingActions->actions);
2456 }
2457 }
2458
2459 /* If there are notifies at our nesting level, we must reparent them. */
2460 if (pendingNotifies != NULL &&
2461 pendingNotifies->nestingLevel >= my_level)
2462 {
2463 Assert(pendingNotifies->nestingLevel == my_level);
2464
2465 if (pendingNotifies->upper == NULL ||
2466 pendingNotifies->upper->nestingLevel < my_level - 1)
2467 {
2468 /* nothing to merge; give the whole thing to the parent */
2470 }
2471 else
2472 {
2473 /*
2474 * Formerly, we didn't bother to eliminate duplicates here, but
2475 * now we must, else we fall foul of "Assert(!found)", either here
2476 * or during a later attempt to build the parent-level hashtable.
2477 */
2479 ListCell *l;
2480
2482 /* Insert all the subxact's events into parent, except for dups */
2483 foreach(l, childPendingNotifies->events)
2484 {
2486
2489 }
2491 }
2492 }
2493}
#define Assert(condition)
Definition c.h:873
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:439

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 2542 of file async.c.

2543{
2544 /*
2545 * Note: this is called by a SIGNAL HANDLER. You must be very wary what
2546 * you do here.
2547 */
2548
2549 /* signal that work needs to be done */
2551
2552 /* make sure the event is processed in due course */
2554}
volatile sig_atomic_t notifyInterruptPending
Definition async.c:537
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 3092 of file async.c.

3093{
3095 {
3097
3099 pq_sendint32(&buf, srcPid);
3100 pq_sendstring(&buf, channel);
3101 pq_sendstring(&buf, payload);
3103
3104 /*
3105 * NOTE: we do not do pq_flush() here. Some level of caller will
3106 * handle it later, allowing this message to be combined into a packet
3107 * with other ones.
3108 */
3109 }
3110 else
3111 elog(INFO, "NOTIFY for \"%s\" payload \"%s\"", channel, payload);
3112}
@ DestRemote
Definition dest.h:89
#define INFO
Definition elog.h:34
static char buf[DEFAULT_XLOG_SEG_SIZE]
CommandDest whereToSendOutput
Definition postgres.c:92
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 1176 of file async.c.

1177{
1178 ListCell *p;
1179
1181 return; /* no relevant statements in this xact */
1182
1183 if (Trace_notify)
1184 elog(DEBUG1, "PreCommit_Notify");
1185
1186 /* Preflight for any pending listen/unlisten actions */
1188
1189 if (pendingActions != NULL)
1190 {
1191 /* Ensure we have a local channel table */
1193 /* Create pendingListenActions hash table for this transaction */
1195
1196 /* Stage all the actions this transaction wants to perform */
1197 foreach(p, pendingActions->actions)
1198 {
1200
1201 switch (actrec->action)
1202 {
1203 case LISTEN_LISTEN:
1206 break;
1207 case LISTEN_UNLISTEN:
1209 break;
1212 break;
1213 }
1214 }
1215 }
1216
1217 /* Queue any pending notifies (must happen after the above) */
1218 if (pendingNotifies)
1219 {
1221 bool firstIteration = true;
1222
1223 /*
1224 * Build list of unique channel names being notified for use by
1225 * SignalBackends().
1226 *
1227 * If uniqueChannelHash is available, use it to efficiently get the
1228 * unique channels. Otherwise, fall back to the O(N^2) approach.
1229 */
1232 {
1233 HASH_SEQ_STATUS status;
1235
1237 while ((channelEntry = (ChannelName *) hash_seq_search(&status)) != NULL)
1240 channelEntry->channel);
1241 }
1242 else
1243 {
1244 /* O(N^2) approach is better for small number of notifications */
1246 {
1247 char *channel = n->data;
1248 bool found = false;
1249
1250 /* Name present in list? */
1252 {
1253 if (strcmp(oldchan, channel) == 0)
1254 {
1255 found = true;
1256 break;
1257 }
1258 }
1259 /* Add if not already in list */
1260 if (!found)
1263 channel);
1264 }
1265 }
1266
1267 /* Preallocate workspace that will be needed by SignalBackends() */
1268 if (signalPids == NULL)
1270 MaxBackends * sizeof(int32));
1271
1272 if (signalProcnos == NULL)
1274 MaxBackends * sizeof(ProcNumber));
1275
1276 /*
1277 * Make sure that we have an XID assigned to the current transaction.
1278 * GetCurrentTransactionId is cheap if we already have an XID, but not
1279 * so cheap if we don't, and we'd prefer not to do that work while
1280 * holding NotifyQueueLock.
1281 */
1283
1284 /*
1285 * Serialize writers by acquiring a special lock that we hold till
1286 * after commit. This ensures that queue entries appear in commit
1287 * order, and in particular that there are never uncommitted queue
1288 * entries ahead of committed ones, so an uncommitted transaction
1289 * can't block delivery of deliverable notifications.
1290 *
1291 * We use a heavyweight lock so that it'll automatically be released
1292 * after either commit or abort. This also allows deadlocks to be
1293 * detected, though really a deadlock shouldn't be possible here.
1294 *
1295 * The lock is on "database 0", which is pretty ugly but it doesn't
1296 * seem worth inventing a special locktag category just for this.
1297 * (Historical note: before PG 9.0, a similar lock on "database 0" was
1298 * used by the flatfiles mechanism.)
1299 */
1302
1303 /*
1304 * For the direct advancement optimization in SignalBackends(), we
1305 * need to ensure that no other backend can insert queue entries
1306 * between queueHeadBeforeWrite and queueHeadAfterWrite. The
1307 * heavyweight lock above provides this guarantee, since it serializes
1308 * all writers.
1309 *
1310 * Note: if the heavyweight lock were ever removed for scalability
1311 * reasons, we could achieve the same guarantee by holding
1312 * NotifyQueueLock in EXCLUSIVE mode across all our insertions, rather
1313 * than releasing and reacquiring it for each page as we do below.
1314 */
1315
1316 /* Initialize values to a safe default in case list is empty */
1319
1320 /* Now push the notifications into the queue */
1322 while (nextNotify != NULL)
1323 {
1324 /*
1325 * Add the pending notifications to the queue. We acquire and
1326 * release NotifyQueueLock once per page, which might be overkill
1327 * but it does allow readers to get in while we're doing this.
1328 *
1329 * A full queue is very uncommon and should really not happen,
1330 * given that we have so much space available in the SLRU pages.
1331 * Nevertheless we need to deal with this possibility. Note that
1332 * when we get here we are in the process of committing our
1333 * transaction, but we have not yet committed to clog, so at this
1334 * point in time we can still roll the transaction back.
1335 */
1337 if (firstIteration)
1338 {
1340 firstIteration = false;
1341 }
1343 if (asyncQueueIsFull())
1344 ereport(ERROR,
1346 errmsg("too many notifications in the NOTIFY queue")));
1350 }
1351
1352 /* Note that we don't clear pendingNotifies; AtCommit_Notify will. */
1353 }
1354}
static void PrepareTableEntriesForListen(const char *channel)
Definition async.c:1522
static void BecomeRegisteredListener(void)
Definition async.c:1421
static int32 * signalPids
Definition async.c:559
static void PrepareTableEntriesForUnlisten(const char *channel)
Definition async.c:1625
static ProcNumber * signalProcnos
Definition async.c:560
static QueuePosition queueHeadAfterWrite
Definition async.c:552
static ListCell * asyncQueueAddEntries(ListCell *nextNotify)
Definition async.c:2034
static void PrepareTableEntriesForUnlistenAll(void)
Definition async.c:1655
static void asyncQueueFillWarning(void)
Definition async.c:2206
static void initGlobalChannelTable(void)
Definition async.c:676
static bool asyncQueueIsFull(void)
Definition async.c:1950
static void initLocalChannelTable(void)
Definition async.c:727
static void initPendingListenActions(void)
Definition async.c:753
static QueuePosition queueHeadBeforeWrite
Definition async.c:551
int32_t int32
Definition c.h:542
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:507
HTAB * uniqueChannelHash
Definition async.c:508
List * events
Definition async.c:505
TransactionId GetCurrentTransactionId(void)
Definition xact.c:455

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 2572 of file async.c.

2573{
2575 return; /* not really idle */
2576
2577 /* Loop in case another signal arrives while sending messages */
2579 ProcessIncomingNotify(flush);
2580}
static void ProcessIncomingNotify(bool flush)
Definition async.c:3051
bool IsTransactionOrTransactionBlock(void)
Definition xact.c:5011

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 569 of file async.c.

Referenced by asyncQueueIsFull(), and asyncQueueUsage().

◆ notifyInterruptPending

◆ Trace_notify