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