LCOV - code coverage report
Current view: top level - src/backend/storage/ipc - procsignal.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 84.3 % 197 166
Test Date: 2026-02-17 17:20:33 Functions: 92.3 % 13 12
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /*-------------------------------------------------------------------------
       2              :  *
       3              :  * procsignal.c
       4              :  *    Routines for interprocess signaling
       5              :  *
       6              :  *
       7              :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       8              :  * Portions Copyright (c) 1994, Regents of the University of California
       9              :  *
      10              :  * IDENTIFICATION
      11              :  *    src/backend/storage/ipc/procsignal.c
      12              :  *
      13              :  *-------------------------------------------------------------------------
      14              :  */
      15              : #include "postgres.h"
      16              : 
      17              : #include <signal.h>
      18              : #include <unistd.h>
      19              : 
      20              : #include "access/parallel.h"
      21              : #include "commands/async.h"
      22              : #include "miscadmin.h"
      23              : #include "pgstat.h"
      24              : #include "port/pg_bitutils.h"
      25              : #include "replication/logicalworker.h"
      26              : #include "replication/walsender.h"
      27              : #include "storage/condition_variable.h"
      28              : #include "storage/ipc.h"
      29              : #include "storage/latch.h"
      30              : #include "storage/shmem.h"
      31              : #include "storage/sinval.h"
      32              : #include "storage/smgr.h"
      33              : #include "tcop/tcopprot.h"
      34              : #include "utils/memutils.h"
      35              : 
      36              : /*
      37              :  * The SIGUSR1 signal is multiplexed to support signaling multiple event
      38              :  * types. The specific reason is communicated via flags in shared memory.
      39              :  * We keep a boolean flag for each possible "reason", so that different
      40              :  * reasons can be signaled to a process concurrently.  (However, if the same
      41              :  * reason is signaled more than once nearly simultaneously, the process may
      42              :  * observe it only once.)
      43              :  *
      44              :  * Each process that wants to receive signals registers its process ID
      45              :  * in the ProcSignalSlots array. The array is indexed by ProcNumber to make
      46              :  * slot allocation simple, and to avoid having to search the array when you
      47              :  * know the ProcNumber of the process you're signaling.  (We do support
      48              :  * signaling without ProcNumber, but it's a bit less efficient.)
      49              :  *
      50              :  * The fields in each slot are protected by a spinlock, pss_mutex. pss_pid can
      51              :  * also be read without holding the spinlock, as a quick preliminary check
      52              :  * when searching for a particular PID in the array.
      53              :  *
      54              :  * pss_signalFlags are intended to be set in cases where we don't need to
      55              :  * keep track of whether or not the target process has handled the signal,
      56              :  * but sometimes we need confirmation, as when making a global state change
      57              :  * that cannot be considered complete until all backends have taken notice
      58              :  * of it. For such use cases, we set a bit in pss_barrierCheckMask and then
      59              :  * increment the current "barrier generation"; when the new barrier generation
      60              :  * (or greater) appears in the pss_barrierGeneration flag of every process,
      61              :  * we know that the message has been received everywhere.
      62              :  */
      63              : typedef struct
      64              : {
      65              :     pg_atomic_uint32 pss_pid;
      66              :     int         pss_cancel_key_len; /* 0 means no cancellation is possible */
      67              :     uint8       pss_cancel_key[MAX_CANCEL_KEY_LENGTH];
      68              :     volatile sig_atomic_t pss_signalFlags[NUM_PROCSIGNALS];
      69              :     slock_t     pss_mutex;      /* protects the above fields */
      70              : 
      71              :     /* Barrier-related fields (not protected by pss_mutex) */
      72              :     pg_atomic_uint64 pss_barrierGeneration;
      73              :     pg_atomic_uint32 pss_barrierCheckMask;
      74              :     ConditionVariable pss_barrierCV;
      75              : } ProcSignalSlot;
      76              : 
      77              : /*
      78              :  * Information that is global to the entire ProcSignal system can be stored
      79              :  * here.
      80              :  *
      81              :  * psh_barrierGeneration is the highest barrier generation in existence.
      82              :  */
      83              : struct ProcSignalHeader
      84              : {
      85              :     pg_atomic_uint64 psh_barrierGeneration;
      86              :     ProcSignalSlot psh_slot[FLEXIBLE_ARRAY_MEMBER];
      87              : };
      88              : 
      89              : /*
      90              :  * We reserve a slot for each possible ProcNumber, plus one for each
      91              :  * possible auxiliary process type.  (This scheme assumes there is not
      92              :  * more than one of any auxiliary process type at a time, except for
      93              :  * IO workers.)
      94              :  */
      95              : #define NumProcSignalSlots  (MaxBackends + NUM_AUXILIARY_PROCS)
      96              : 
      97              : /* Check whether the relevant type bit is set in the flags. */
      98              : #define BARRIER_SHOULD_CHECK(flags, type) \
      99              :     (((flags) & (((uint32) 1) << (uint32) (type))) != 0)
     100              : 
     101              : /* Clear the relevant type bit from the flags. */
     102              : #define BARRIER_CLEAR_BIT(flags, type) \
     103              :     ((flags) &= ~(((uint32) 1) << (uint32) (type)))
     104              : 
     105              : NON_EXEC_STATIC ProcSignalHeader *ProcSignal = NULL;
     106              : static ProcSignalSlot *MyProcSignalSlot = NULL;
     107              : 
     108              : static bool CheckProcSignal(ProcSignalReason reason);
     109              : static void CleanupProcSignalState(int status, Datum arg);
     110              : static void ResetProcSignalBarrierBits(uint32 flags);
     111              : 
     112              : /*
     113              :  * ProcSignalShmemSize
     114              :  *      Compute space needed for ProcSignal's shared memory
     115              :  */
     116              : Size
     117         3267 : ProcSignalShmemSize(void)
     118              : {
     119              :     Size        size;
     120              : 
     121         3267 :     size = mul_size(NumProcSignalSlots, sizeof(ProcSignalSlot));
     122         3267 :     size = add_size(size, offsetof(ProcSignalHeader, psh_slot));
     123         3267 :     return size;
     124              : }
     125              : 
     126              : /*
     127              :  * ProcSignalShmemInit
     128              :  *      Allocate and initialize ProcSignal's shared memory
     129              :  */
     130              : void
     131         1140 : ProcSignalShmemInit(void)
     132              : {
     133         1140 :     Size        size = ProcSignalShmemSize();
     134              :     bool        found;
     135              : 
     136         1140 :     ProcSignal = (ProcSignalHeader *)
     137         1140 :         ShmemInitStruct("ProcSignal", size, &found);
     138              : 
     139              :     /* If we're first, initialize. */
     140         1140 :     if (!found)
     141              :     {
     142              :         int         i;
     143              : 
     144         1140 :         pg_atomic_init_u64(&ProcSignal->psh_barrierGeneration, 0);
     145              : 
     146       149060 :         for (i = 0; i < NumProcSignalSlots; ++i)
     147              :         {
     148       147920 :             ProcSignalSlot *slot = &ProcSignal->psh_slot[i];
     149              : 
     150       147920 :             SpinLockInit(&slot->pss_mutex);
     151       147920 :             pg_atomic_init_u32(&slot->pss_pid, 0);
     152       147920 :             slot->pss_cancel_key_len = 0;
     153       739600 :             MemSet(slot->pss_signalFlags, 0, sizeof(slot->pss_signalFlags));
     154       147920 :             pg_atomic_init_u64(&slot->pss_barrierGeneration, PG_UINT64_MAX);
     155       147920 :             pg_atomic_init_u32(&slot->pss_barrierCheckMask, 0);
     156       147920 :             ConditionVariableInit(&slot->pss_barrierCV);
     157              :         }
     158              :     }
     159         1140 : }
     160              : 
     161              : /*
     162              :  * ProcSignalInit
     163              :  *      Register the current process in the ProcSignal array
     164              :  */
     165              : void
     166        22972 : ProcSignalInit(const uint8 *cancel_key, int cancel_key_len)
     167              : {
     168              :     ProcSignalSlot *slot;
     169              :     uint64      barrier_generation;
     170              :     uint32      old_pss_pid;
     171              : 
     172              :     Assert(cancel_key_len >= 0 && cancel_key_len <= MAX_CANCEL_KEY_LENGTH);
     173        22972 :     if (MyProcNumber < 0)
     174            0 :         elog(ERROR, "MyProcNumber not set");
     175        22972 :     if (MyProcNumber >= NumProcSignalSlots)
     176            0 :         elog(ERROR, "unexpected MyProcNumber %d in ProcSignalInit (max %d)", MyProcNumber, NumProcSignalSlots);
     177        22972 :     slot = &ProcSignal->psh_slot[MyProcNumber];
     178              : 
     179        22972 :     SpinLockAcquire(&slot->pss_mutex);
     180              : 
     181              :     /* Value used for sanity check below */
     182        22972 :     old_pss_pid = pg_atomic_read_u32(&slot->pss_pid);
     183              : 
     184              :     /* Clear out any leftover signal reasons */
     185       114860 :     MemSet(slot->pss_signalFlags, 0, NUM_PROCSIGNALS * sizeof(sig_atomic_t));
     186              : 
     187              :     /*
     188              :      * Initialize barrier state. Since we're a brand-new process, there
     189              :      * shouldn't be any leftover backend-private state that needs to be
     190              :      * updated. Therefore, we can broadcast the latest barrier generation and
     191              :      * disregard any previously-set check bits.
     192              :      *
     193              :      * NB: This only works if this initialization happens early enough in the
     194              :      * startup sequence that we haven't yet cached any state that might need
     195              :      * to be invalidated. That's also why we have a memory barrier here, to be
     196              :      * sure that any later reads of memory happen strictly after this.
     197              :      */
     198        22972 :     pg_atomic_write_u32(&slot->pss_barrierCheckMask, 0);
     199              :     barrier_generation =
     200        22972 :         pg_atomic_read_u64(&ProcSignal->psh_barrierGeneration);
     201        22972 :     pg_atomic_write_u64(&slot->pss_barrierGeneration, barrier_generation);
     202              : 
     203        22972 :     if (cancel_key_len > 0)
     204        13682 :         memcpy(slot->pss_cancel_key, cancel_key, cancel_key_len);
     205        22972 :     slot->pss_cancel_key_len = cancel_key_len;
     206        22972 :     pg_atomic_write_u32(&slot->pss_pid, MyProcPid);
     207              : 
     208        22972 :     SpinLockRelease(&slot->pss_mutex);
     209              : 
     210              :     /* Spinlock is released, do the check */
     211        22972 :     if (old_pss_pid != 0)
     212            0 :         elog(LOG, "process %d taking over ProcSignal slot %d, but it's not empty",
     213              :              MyProcPid, MyProcNumber);
     214              : 
     215              :     /* Remember slot location for CheckProcSignal */
     216        22972 :     MyProcSignalSlot = slot;
     217              : 
     218              :     /* Set up to release the slot on process exit */
     219        22972 :     on_shmem_exit(CleanupProcSignalState, (Datum) 0);
     220        22972 : }
     221              : 
     222              : /*
     223              :  * CleanupProcSignalState
     224              :  *      Remove current process from ProcSignal mechanism
     225              :  *
     226              :  * This function is called via on_shmem_exit() during backend shutdown.
     227              :  */
     228              : static void
     229        22972 : CleanupProcSignalState(int status, Datum arg)
     230              : {
     231              :     pid_t       old_pid;
     232        22972 :     ProcSignalSlot *slot = MyProcSignalSlot;
     233              : 
     234              :     /*
     235              :      * Clear MyProcSignalSlot, so that a SIGUSR1 received after this point
     236              :      * won't try to access it after it's no longer ours (and perhaps even
     237              :      * after we've unmapped the shared memory segment).
     238              :      */
     239              :     Assert(MyProcSignalSlot != NULL);
     240        22972 :     MyProcSignalSlot = NULL;
     241              : 
     242              :     /* sanity check */
     243        22972 :     SpinLockAcquire(&slot->pss_mutex);
     244        22972 :     old_pid = pg_atomic_read_u32(&slot->pss_pid);
     245        22972 :     if (old_pid != MyProcPid)
     246              :     {
     247              :         /*
     248              :          * don't ERROR here. We're exiting anyway, and don't want to get into
     249              :          * infinite loop trying to exit
     250              :          */
     251            0 :         SpinLockRelease(&slot->pss_mutex);
     252            0 :         elog(LOG, "process %d releasing ProcSignal slot %d, but it contains %d",
     253              :              MyProcPid, (int) (slot - ProcSignal->psh_slot), (int) old_pid);
     254            0 :         return;                 /* XXX better to zero the slot anyway? */
     255              :     }
     256              : 
     257              :     /* Mark the slot as unused */
     258        22972 :     pg_atomic_write_u32(&slot->pss_pid, 0);
     259        22972 :     slot->pss_cancel_key_len = 0;
     260              : 
     261              :     /*
     262              :      * Make this slot look like it's absorbed all possible barriers, so that
     263              :      * no barrier waits block on it.
     264              :      */
     265        22972 :     pg_atomic_write_u64(&slot->pss_barrierGeneration, PG_UINT64_MAX);
     266              : 
     267        22972 :     SpinLockRelease(&slot->pss_mutex);
     268              : 
     269        22972 :     ConditionVariableBroadcast(&slot->pss_barrierCV);
     270              : }
     271              : 
     272              : /*
     273              :  * SendProcSignal
     274              :  *      Send a signal to a Postgres process
     275              :  *
     276              :  * Providing procNumber is optional, but it will speed up the operation.
     277              :  *
     278              :  * On success (a signal was sent), zero is returned.
     279              :  * On error, -1 is returned, and errno is set (typically to ESRCH or EPERM).
     280              :  *
     281              :  * Not to be confused with ProcSendSignal
     282              :  */
     283              : int
     284         5940 : SendProcSignal(pid_t pid, ProcSignalReason reason, ProcNumber procNumber)
     285              : {
     286              :     volatile ProcSignalSlot *slot;
     287              : 
     288         5940 :     if (procNumber != INVALID_PROC_NUMBER)
     289              :     {
     290              :         Assert(procNumber < NumProcSignalSlots);
     291         5881 :         slot = &ProcSignal->psh_slot[procNumber];
     292              : 
     293         5881 :         SpinLockAcquire(&slot->pss_mutex);
     294         5881 :         if (pg_atomic_read_u32(&slot->pss_pid) == pid)
     295              :         {
     296              :             /* Atomically set the proper flag */
     297         5881 :             slot->pss_signalFlags[reason] = true;
     298         5881 :             SpinLockRelease(&slot->pss_mutex);
     299              :             /* Send signal */
     300         5881 :             return kill(pid, SIGUSR1);
     301              :         }
     302            0 :         SpinLockRelease(&slot->pss_mutex);
     303              :     }
     304              :     else
     305              :     {
     306              :         /*
     307              :          * procNumber not provided, so search the array using pid.  We search
     308              :          * the array back to front so as to reduce search overhead.  Passing
     309              :          * INVALID_PROC_NUMBER means that the target is most likely an
     310              :          * auxiliary process, which will have a slot near the end of the
     311              :          * array.
     312              :          */
     313              :         int         i;
     314              : 
     315         2657 :         for (i = NumProcSignalSlots - 1; i >= 0; i--)
     316              :         {
     317         2657 :             slot = &ProcSignal->psh_slot[i];
     318              : 
     319         2657 :             if (pg_atomic_read_u32(&slot->pss_pid) == pid)
     320              :             {
     321           59 :                 SpinLockAcquire(&slot->pss_mutex);
     322           59 :                 if (pg_atomic_read_u32(&slot->pss_pid) == pid)
     323              :                 {
     324              :                     /* Atomically set the proper flag */
     325           59 :                     slot->pss_signalFlags[reason] = true;
     326           59 :                     SpinLockRelease(&slot->pss_mutex);
     327              :                     /* Send signal */
     328           59 :                     return kill(pid, SIGUSR1);
     329              :                 }
     330            0 :                 SpinLockRelease(&slot->pss_mutex);
     331              :             }
     332              :         }
     333              :     }
     334              : 
     335            0 :     errno = ESRCH;
     336            0 :     return -1;
     337              : }
     338              : 
     339              : /*
     340              :  * EmitProcSignalBarrier
     341              :  *      Send a signal to every Postgres process
     342              :  *
     343              :  * The return value of this function is the barrier "generation" created
     344              :  * by this operation. This value can be passed to WaitForProcSignalBarrier
     345              :  * to wait until it is known that every participant in the ProcSignal
     346              :  * mechanism has absorbed the signal (or started afterwards).
     347              :  *
     348              :  * Note that it would be a bad idea to use this for anything that happens
     349              :  * frequently, as interrupting every backend could cause a noticeable
     350              :  * performance hit.
     351              :  *
     352              :  * Callers are entitled to assume that this function will not throw ERROR
     353              :  * or FATAL.
     354              :  */
     355              : uint64
     356          593 : EmitProcSignalBarrier(ProcSignalBarrierType type)
     357              : {
     358          593 :     uint32      flagbit = 1 << (uint32) type;
     359              :     uint64      generation;
     360              : 
     361              :     /*
     362              :      * Set all the flags.
     363              :      *
     364              :      * Note that pg_atomic_fetch_or_u32 has full barrier semantics, so this is
     365              :      * totally ordered with respect to anything the caller did before, and
     366              :      * anything that we do afterwards. (This is also true of the later call to
     367              :      * pg_atomic_add_fetch_u64.)
     368              :      */
     369        61721 :     for (int i = 0; i < NumProcSignalSlots; i++)
     370              :     {
     371        61128 :         volatile ProcSignalSlot *slot = &ProcSignal->psh_slot[i];
     372              : 
     373        61128 :         pg_atomic_fetch_or_u32(&slot->pss_barrierCheckMask, flagbit);
     374              :     }
     375              : 
     376              :     /*
     377              :      * Increment the generation counter.
     378              :      */
     379              :     generation =
     380          593 :         pg_atomic_add_fetch_u64(&ProcSignal->psh_barrierGeneration, 1);
     381              : 
     382              :     /*
     383              :      * Signal all the processes, so that they update their advertised barrier
     384              :      * generation.
     385              :      *
     386              :      * Concurrency is not a problem here. Backends that have exited don't
     387              :      * matter, and new backends that have joined since we entered this
     388              :      * function must already have current state, since the caller is
     389              :      * responsible for making sure that the relevant state is entirely visible
     390              :      * before calling this function in the first place. We still have to wake
     391              :      * them up - because we can't distinguish between such backends and older
     392              :      * backends that need to update state - but they won't actually need to
     393              :      * change any state.
     394              :      */
     395        61721 :     for (int i = NumProcSignalSlots - 1; i >= 0; i--)
     396              :     {
     397        61128 :         volatile ProcSignalSlot *slot = &ProcSignal->psh_slot[i];
     398        61128 :         pid_t       pid = pg_atomic_read_u32(&slot->pss_pid);
     399              : 
     400        61128 :         if (pid != 0)
     401              :         {
     402         3503 :             SpinLockAcquire(&slot->pss_mutex);
     403         3503 :             pid = pg_atomic_read_u32(&slot->pss_pid);
     404         3503 :             if (pid != 0)
     405              :             {
     406              :                 /* see SendProcSignal for details */
     407         3503 :                 slot->pss_signalFlags[PROCSIG_BARRIER] = true;
     408         3503 :                 SpinLockRelease(&slot->pss_mutex);
     409         3503 :                 kill(pid, SIGUSR1);
     410              :             }
     411              :             else
     412            0 :                 SpinLockRelease(&slot->pss_mutex);
     413              :         }
     414              :     }
     415              : 
     416          593 :     return generation;
     417              : }
     418              : 
     419              : /*
     420              :  * WaitForProcSignalBarrier - wait until it is guaranteed that all changes
     421              :  * requested by a specific call to EmitProcSignalBarrier() have taken effect.
     422              :  */
     423              : void
     424          577 : WaitForProcSignalBarrier(uint64 generation)
     425              : {
     426              :     Assert(generation <= pg_atomic_read_u64(&ProcSignal->psh_barrierGeneration));
     427              : 
     428          577 :     elog(DEBUG1,
     429              :          "waiting for all backends to process ProcSignalBarrier generation "
     430              :          UINT64_FORMAT,
     431              :          generation);
     432              : 
     433        60575 :     for (int i = NumProcSignalSlots - 1; i >= 0; i--)
     434              :     {
     435        59998 :         ProcSignalSlot *slot = &ProcSignal->psh_slot[i];
     436              :         uint64      oldval;
     437              : 
     438              :         /*
     439              :          * It's important that we check only pss_barrierGeneration here and
     440              :          * not pss_barrierCheckMask. Bits in pss_barrierCheckMask get cleared
     441              :          * before the barrier is actually absorbed, but pss_barrierGeneration
     442              :          * is updated only afterward.
     443              :          */
     444        59998 :         oldval = pg_atomic_read_u64(&slot->pss_barrierGeneration);
     445        62853 :         while (oldval < generation)
     446              :         {
     447         2855 :             if (ConditionVariableTimedSleep(&slot->pss_barrierCV,
     448              :                                             5000,
     449              :                                             WAIT_EVENT_PROC_SIGNAL_BARRIER))
     450            0 :                 ereport(LOG,
     451              :                         (errmsg("still waiting for backend with PID %d to accept ProcSignalBarrier",
     452              :                                 (int) pg_atomic_read_u32(&slot->pss_pid))));
     453         2855 :             oldval = pg_atomic_read_u64(&slot->pss_barrierGeneration);
     454              :         }
     455        59998 :         ConditionVariableCancelSleep();
     456              :     }
     457              : 
     458          577 :     elog(DEBUG1,
     459              :          "finished waiting for all backends to process ProcSignalBarrier generation "
     460              :          UINT64_FORMAT,
     461              :          generation);
     462              : 
     463              :     /*
     464              :      * The caller is probably calling this function because it wants to read
     465              :      * the shared state or perform further writes to shared state once all
     466              :      * backends are known to have absorbed the barrier. However, the read of
     467              :      * pss_barrierGeneration was performed unlocked; insert a memory barrier
     468              :      * to separate it from whatever follows.
     469              :      */
     470          577 :     pg_memory_barrier();
     471          577 : }
     472              : 
     473              : /*
     474              :  * Handle receipt of an interrupt indicating a global barrier event.
     475              :  *
     476              :  * All the actual work is deferred to ProcessProcSignalBarrier(), because we
     477              :  * cannot safely access the barrier generation inside the signal handler as
     478              :  * 64bit atomics might use spinlock based emulation, even for reads. As this
     479              :  * routine only gets called when PROCSIG_BARRIER is sent that won't cause a
     480              :  * lot of unnecessary work.
     481              :  */
     482              : static void
     483         2516 : HandleProcSignalBarrierInterrupt(void)
     484              : {
     485         2516 :     InterruptPending = true;
     486         2516 :     ProcSignalBarrierPending = true;
     487              :     /* latch will be set by procsignal_sigusr1_handler */
     488         2516 : }
     489              : 
     490              : /*
     491              :  * Perform global barrier related interrupt checking.
     492              :  *
     493              :  * Any backend that participates in ProcSignal signaling must arrange to
     494              :  * call this function periodically. It is called from CHECK_FOR_INTERRUPTS(),
     495              :  * which is enough for normal backends, but not necessarily for all types of
     496              :  * background processes.
     497              :  */
     498              : void
     499         2514 : ProcessProcSignalBarrier(void)
     500              : {
     501              :     uint64      local_gen;
     502              :     uint64      shared_gen;
     503              :     volatile uint32 flags;
     504              : 
     505              :     Assert(MyProcSignalSlot);
     506              : 
     507              :     /* Exit quickly if there's no work to do. */
     508         2514 :     if (!ProcSignalBarrierPending)
     509            0 :         return;
     510         2514 :     ProcSignalBarrierPending = false;
     511              : 
     512              :     /*
     513              :      * It's not unlikely to process multiple barriers at once, before the
     514              :      * signals for all the barriers have arrived. To avoid unnecessary work in
     515              :      * response to subsequent signals, exit early if we already have processed
     516              :      * all of them.
     517              :      */
     518         2514 :     local_gen = pg_atomic_read_u64(&MyProcSignalSlot->pss_barrierGeneration);
     519         2514 :     shared_gen = pg_atomic_read_u64(&ProcSignal->psh_barrierGeneration);
     520              : 
     521              :     Assert(local_gen <= shared_gen);
     522              : 
     523         2514 :     if (local_gen == shared_gen)
     524            0 :         return;
     525              : 
     526              :     /*
     527              :      * Get and clear the flags that are set for this backend. Note that
     528              :      * pg_atomic_exchange_u32 is a full barrier, so we're guaranteed that the
     529              :      * read of the barrier generation above happens before we atomically
     530              :      * extract the flags, and that any subsequent state changes happen
     531              :      * afterward.
     532              :      *
     533              :      * NB: In order to avoid race conditions, we must zero
     534              :      * pss_barrierCheckMask first and only afterwards try to do barrier
     535              :      * processing. If we did it in the other order, someone could send us
     536              :      * another barrier of some type right after we called the
     537              :      * barrier-processing function but before we cleared the bit. We would
     538              :      * have no way of knowing that the bit needs to stay set in that case, so
     539              :      * the need to call the barrier-processing function again would just get
     540              :      * forgotten. So instead, we tentatively clear all the bits and then put
     541              :      * back any for which we don't manage to successfully absorb the barrier.
     542              :      */
     543         2514 :     flags = pg_atomic_exchange_u32(&MyProcSignalSlot->pss_barrierCheckMask, 0);
     544              : 
     545              :     /*
     546              :      * If there are no flags set, then we can skip doing any real work.
     547              :      * Otherwise, establish a PG_TRY block, so that we don't lose track of
     548              :      * which types of barrier processing are needed if an ERROR occurs.
     549              :      */
     550         2514 :     if (flags != 0)
     551              :     {
     552         2514 :         bool        success = true;
     553              : 
     554         2514 :         PG_TRY();
     555              :         {
     556              :             /*
     557              :              * Process each type of barrier. The barrier-processing functions
     558              :              * should normally return true, but may return false if the
     559              :              * barrier can't be absorbed at the current time. This should be
     560              :              * rare, because it's pretty expensive.  Every single
     561              :              * CHECK_FOR_INTERRUPTS() will return here until we manage to
     562              :              * absorb the barrier, and that cost will add up in a hurry.
     563              :              *
     564              :              * NB: It ought to be OK to call the barrier-processing functions
     565              :              * unconditionally, but it's more efficient to call only the ones
     566              :              * that might need us to do something based on the flags.
     567              :              */
     568         7542 :             while (flags != 0)
     569              :             {
     570              :                 ProcSignalBarrierType type;
     571         2514 :                 bool        processed = true;
     572              : 
     573         2514 :                 type = (ProcSignalBarrierType) pg_rightmost_one_pos32(flags);
     574         2514 :                 switch (type)
     575              :                 {
     576          664 :                     case PROCSIGNAL_BARRIER_SMGRRELEASE:
     577          664 :                         processed = ProcessBarrierSmgrRelease();
     578          664 :                         break;
     579         1850 :                     case PROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO:
     580         1850 :                         processed = ProcessBarrierUpdateXLogLogicalInfo();
     581         1850 :                         break;
     582              :                 }
     583              : 
     584              :                 /*
     585              :                  * To avoid an infinite loop, we must always unset the bit in
     586              :                  * flags.
     587              :                  */
     588         2514 :                 BARRIER_CLEAR_BIT(flags, type);
     589              : 
     590              :                 /*
     591              :                  * If we failed to process the barrier, reset the shared bit
     592              :                  * so we try again later, and set a flag so that we don't bump
     593              :                  * our generation.
     594              :                  */
     595         2514 :                 if (!processed)
     596              :                 {
     597            0 :                     ResetProcSignalBarrierBits(((uint32) 1) << type);
     598            0 :                     success = false;
     599              :                 }
     600              :             }
     601              :         }
     602            0 :         PG_CATCH();
     603              :         {
     604              :             /*
     605              :              * If an ERROR occurred, we'll need to try again later to handle
     606              :              * that barrier type and any others that haven't been handled yet
     607              :              * or weren't successfully absorbed.
     608              :              */
     609            0 :             ResetProcSignalBarrierBits(flags);
     610            0 :             PG_RE_THROW();
     611              :         }
     612         2514 :         PG_END_TRY();
     613              : 
     614              :         /*
     615              :          * If some barrier types were not successfully absorbed, we will have
     616              :          * to try again later.
     617              :          */
     618         2514 :         if (!success)
     619            0 :             return;
     620              :     }
     621              : 
     622              :     /*
     623              :      * State changes related to all types of barriers that might have been
     624              :      * emitted have now been handled, so we can update our notion of the
     625              :      * generation to the one we observed before beginning the updates. If
     626              :      * things have changed further, it'll get fixed up when this function is
     627              :      * next called.
     628              :      */
     629         2514 :     pg_atomic_write_u64(&MyProcSignalSlot->pss_barrierGeneration, shared_gen);
     630         2514 :     ConditionVariableBroadcast(&MyProcSignalSlot->pss_barrierCV);
     631              : }
     632              : 
     633              : /*
     634              :  * If it turns out that we couldn't absorb one or more barrier types, either
     635              :  * because the barrier-processing functions returned false or due to an error,
     636              :  * arrange for processing to be retried later.
     637              :  */
     638              : static void
     639            0 : ResetProcSignalBarrierBits(uint32 flags)
     640              : {
     641            0 :     pg_atomic_fetch_or_u32(&MyProcSignalSlot->pss_barrierCheckMask, flags);
     642            0 :     ProcSignalBarrierPending = true;
     643            0 :     InterruptPending = true;
     644            0 : }
     645              : 
     646              : /*
     647              :  * CheckProcSignal - check to see if a particular reason has been
     648              :  * signaled, and clear the signal flag.  Should be called after receiving
     649              :  * SIGUSR1.
     650              :  */
     651              : static bool
     652        88904 : CheckProcSignal(ProcSignalReason reason)
     653              : {
     654        88904 :     volatile ProcSignalSlot *slot = MyProcSignalSlot;
     655              : 
     656        88904 :     if (slot != NULL)
     657              :     {
     658              :         /*
     659              :          * Careful here --- don't clear flag if we haven't seen it set.
     660              :          * pss_signalFlags is of type "volatile sig_atomic_t" to allow us to
     661              :          * read it here safely, without holding the spinlock.
     662              :          */
     663        88808 :         if (slot->pss_signalFlags[reason])
     664              :         {
     665         7027 :             slot->pss_signalFlags[reason] = false;
     666         7027 :             return true;
     667              :         }
     668              :     }
     669              : 
     670        81877 :     return false;
     671              : }
     672              : 
     673              : /*
     674              :  * procsignal_sigusr1_handler - handle SIGUSR1 signal.
     675              :  */
     676              : void
     677        11113 : procsignal_sigusr1_handler(SIGNAL_ARGS)
     678              : {
     679        11113 :     if (CheckProcSignal(PROCSIG_CATCHUP_INTERRUPT))
     680         2854 :         HandleCatchupInterrupt();
     681              : 
     682        11113 :     if (CheckProcSignal(PROCSIG_NOTIFY_INTERRUPT))
     683            7 :         HandleNotifyInterrupt();
     684              : 
     685        11113 :     if (CheckProcSignal(PROCSIG_PARALLEL_MESSAGE))
     686         1567 :         HandleParallelMessageInterrupt();
     687              : 
     688        11113 :     if (CheckProcSignal(PROCSIG_WALSND_INIT_STOPPING))
     689           40 :         HandleWalSndInitStopping();
     690              : 
     691        11113 :     if (CheckProcSignal(PROCSIG_BARRIER))
     692         2516 :         HandleProcSignalBarrierInterrupt();
     693              : 
     694        11113 :     if (CheckProcSignal(PROCSIG_LOG_MEMORY_CONTEXT))
     695            9 :         HandleLogMemoryContextInterrupt();
     696              : 
     697        11113 :     if (CheckProcSignal(PROCSIG_PARALLEL_APPLY_MESSAGE))
     698           16 :         HandleParallelApplyMessageInterrupt();
     699              : 
     700        11113 :     if (CheckProcSignal(PROCSIG_RECOVERY_CONFLICT))
     701           18 :         HandleRecoveryConflictInterrupt();
     702              : 
     703        11113 :     SetLatch(MyLatch);
     704        11113 : }
     705              : 
     706              : /*
     707              :  * Send a query cancellation signal to backend.
     708              :  *
     709              :  * Note: This is called from a backend process before authentication.  We
     710              :  * cannot take LWLocks yet, but that's OK; we rely on atomic reads of the
     711              :  * fields in the ProcSignal slots.
     712              :  */
     713              : void
     714           15 : SendCancelRequest(int backendPID, const uint8 *cancel_key, int cancel_key_len)
     715              : {
     716           15 :     if (backendPID == 0)
     717              :     {
     718            0 :         ereport(LOG, (errmsg("invalid cancel request with PID 0")));
     719            0 :         return;
     720              :     }
     721              : 
     722              :     /*
     723              :      * See if we have a matching backend. Reading the pss_pid and
     724              :      * pss_cancel_key fields is racy, a backend might die and remove itself
     725              :      * from the array at any time.  The probability of the cancellation key
     726              :      * matching wrong process is miniscule, however, so we can live with that.
     727              :      * PIDs are reused too, so sending the signal based on PID is inherently
     728              :      * racy anyway, although OS's avoid reusing PIDs too soon.
     729              :      */
     730          214 :     for (int i = 0; i < NumProcSignalSlots; i++)
     731              :     {
     732          214 :         ProcSignalSlot *slot = &ProcSignal->psh_slot[i];
     733              :         bool        match;
     734              : 
     735          214 :         if (pg_atomic_read_u32(&slot->pss_pid) != backendPID)
     736          199 :             continue;
     737              : 
     738              :         /* Acquire the spinlock and re-check */
     739           15 :         SpinLockAcquire(&slot->pss_mutex);
     740           15 :         if (pg_atomic_read_u32(&slot->pss_pid) != backendPID)
     741              :         {
     742            0 :             SpinLockRelease(&slot->pss_mutex);
     743            0 :             continue;
     744              :         }
     745              :         else
     746              :         {
     747           30 :             match = slot->pss_cancel_key_len == cancel_key_len &&
     748           15 :                 timingsafe_bcmp(slot->pss_cancel_key, cancel_key, cancel_key_len) == 0;
     749              : 
     750           15 :             SpinLockRelease(&slot->pss_mutex);
     751              : 
     752           15 :             if (match)
     753              :             {
     754              :                 /* Found a match; signal that backend to cancel current op */
     755           15 :                 ereport(DEBUG2,
     756              :                         (errmsg_internal("processing cancel request: sending SIGINT to process %d",
     757              :                                          backendPID)));
     758              : 
     759              :                 /*
     760              :                  * If we have setsid(), signal the backend's whole process
     761              :                  * group
     762              :                  */
     763              : #ifdef HAVE_SETSID
     764           15 :                 kill(-backendPID, SIGINT);
     765              : #else
     766              :                 kill(backendPID, SIGINT);
     767              : #endif
     768              :             }
     769              :             else
     770              :             {
     771              :                 /* Right PID, wrong key: no way, Jose */
     772            0 :                 ereport(LOG,
     773              :                         (errmsg("wrong key in cancel request for process %d",
     774              :                                 backendPID)));
     775              :             }
     776           15 :             return;
     777              :         }
     778              :     }
     779              : 
     780              :     /* No matching backend */
     781            0 :     ereport(LOG,
     782              :             (errmsg("PID %d in cancel request did not match any process",
     783              :                     backendPID)));
     784              : }
        

Generated by: LCOV version 2.0-1