PostgreSQL Source Code git master
proc.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * proc.c
4 * routines to manage per-process shared memory data structure
5 *
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/storage/lmgr/proc.c
12 *
13 *-------------------------------------------------------------------------
14 */
15/*
16 * Interface (a):
17 * JoinWaitQueue(), ProcSleep(), ProcWakeup()
18 *
19 * Waiting for a lock causes the backend to be put to sleep. Whoever releases
20 * the lock wakes the process up again (and gives it an error code so it knows
21 * whether it was awoken on an error condition).
22 *
23 * Interface (b):
24 *
25 * ProcReleaseLocks -- frees the locks associated with current transaction
26 *
27 * ProcKill -- destroys the shared memory state (and locks)
28 * associated with the process.
29 */
30#include "postgres.h"
31
32#include <signal.h>
33#include <unistd.h>
34#include <sys/time.h>
35
36#include "access/transam.h"
37#include "access/twophase.h"
38#include "access/xlogutils.h"
39#include "miscadmin.h"
40#include "pgstat.h"
43#include "replication/syncrep.h"
45#include "storage/ipc.h"
46#include "storage/lmgr.h"
47#include "storage/pmsignal.h"
48#include "storage/proc.h"
49#include "storage/procarray.h"
50#include "storage/procsignal.h"
51#include "storage/spin.h"
52#include "storage/standby.h"
53#include "utils/timeout.h"
54#include "utils/timestamp.h"
55
56/* GUC variables */
57int DeadlockTimeout = 1000;
63bool log_lock_waits = false;
64
65/* Pointer to this process's PGPROC struct, if any */
66PGPROC *MyProc = NULL;
67
68/*
69 * This spinlock protects the freelist of recycled PGPROC structures.
70 * We cannot use an LWLock because the LWLock manager depends on already
71 * having a PGPROC and a wait semaphore! But these structures are touched
72 * relatively infrequently (only at backend startup or shutdown) and not for
73 * very long, so a spinlock is okay.
74 */
76
77/* Pointers to shared-memory structures */
81
83
84/* Is a deadlock check pending? */
85static volatile sig_atomic_t got_deadlock_timeout;
86
87static void RemoveProcFromArray(int code, Datum arg);
88static void ProcKill(int code, Datum arg);
89static void AuxiliaryProcKill(int code, Datum arg);
90static void CheckDeadLock(void);
91
92
93/*
94 * Report shared-memory space needed by PGPROC.
95 */
96static Size
98{
99 Size size = 0;
100 Size TotalProcs =
102
103 size = add_size(size, mul_size(TotalProcs, sizeof(PGPROC)));
104 size = add_size(size, mul_size(TotalProcs, sizeof(*ProcGlobal->xids)));
105 size = add_size(size, mul_size(TotalProcs, sizeof(*ProcGlobal->subxidStates)));
106 size = add_size(size, mul_size(TotalProcs, sizeof(*ProcGlobal->statusFlags)));
107
108 return size;
109}
110
111/*
112 * Report shared-memory space needed by Fast-Path locks.
113 */
114static Size
116{
117 Size size = 0;
118 Size TotalProcs =
120 Size fpLockBitsSize,
121 fpRelIdSize;
122
123 /*
124 * Memory needed for PGPROC fast-path lock arrays. Make sure the sizes are
125 * nicely aligned in each backend.
126 */
127 fpLockBitsSize = MAXALIGN(FastPathLockGroupsPerBackend * sizeof(uint64));
128 fpRelIdSize = MAXALIGN(FastPathLockSlotsPerBackend() * sizeof(Oid));
129
130 size = add_size(size, mul_size(TotalProcs, (fpLockBitsSize + fpRelIdSize)));
131
132 return size;
133}
134
135/*
136 * Report shared-memory space needed by InitProcGlobal.
137 */
138Size
140{
141 Size size = 0;
142
143 /* ProcGlobal */
144 size = add_size(size, sizeof(PROC_HDR));
145 size = add_size(size, sizeof(slock_t));
146
147 size = add_size(size, PGProcShmemSize());
148 size = add_size(size, FastPathLockShmemSize());
149
150 return size;
151}
152
153/*
154 * Report number of semaphores needed by InitProcGlobal.
155 */
156int
158{
159 /*
160 * We need a sema per backend (including autovacuum), plus one for each
161 * auxiliary process.
162 */
164}
165
166/*
167 * InitProcGlobal -
168 * Initialize the global process table during postmaster or standalone
169 * backend startup.
170 *
171 * We also create all the per-process semaphores we will need to support
172 * the requested number of backends. We used to allocate semaphores
173 * only when backends were actually started up, but that is bad because
174 * it lets Postgres fail under load --- a lot of Unix systems are
175 * (mis)configured with small limits on the number of semaphores, and
176 * running out when trying to start another backend is a common failure.
177 * So, now we grab enough semaphores to support the desired max number
178 * of backends immediately at initialization --- if the sysadmin has set
179 * MaxConnections, max_worker_processes, max_wal_senders, or
180 * autovacuum_worker_slots higher than his kernel will support, he'll
181 * find out sooner rather than later.
182 *
183 * Another reason for creating semaphores here is that the semaphore
184 * implementation typically requires us to create semaphores in the
185 * postmaster, not in backends.
186 *
187 * Note: this is NOT called by individual backends under a postmaster,
188 * not even in the EXEC_BACKEND case. The ProcGlobal and AuxiliaryProcs
189 * pointers must be propagated specially for EXEC_BACKEND operation.
190 */
191void
193{
194 PGPROC *procs;
195 int i,
196 j;
197 bool found;
199
200 /* Used for setup of per-backend fast-path slots. */
201 char *fpPtr,
202 *fpEndPtr PG_USED_FOR_ASSERTS_ONLY;
203 Size fpLockBitsSize,
204 fpRelIdSize;
205 Size requestSize;
206 char *ptr;
207
208 /* Create the ProcGlobal shared structure */
209 ProcGlobal = (PROC_HDR *)
210 ShmemInitStruct("Proc Header", sizeof(PROC_HDR), &found);
211 Assert(!found);
212
213 /*
214 * Initialize the data structures.
215 */
226
227 /*
228 * Create and initialize all the PGPROC structures we'll need. There are
229 * six separate consumers: (1) normal backends, (2) autovacuum workers and
230 * special workers, (3) background workers, (4) walsenders, (5) auxiliary
231 * processes, and (6) prepared transactions. (For largely-historical
232 * reasons, we combine autovacuum and special workers into one category
233 * with a single freelist.) Each PGPROC structure is dedicated to exactly
234 * one of these purposes, and they do not move between groups.
235 */
236 requestSize = PGProcShmemSize();
237
238 ptr = ShmemInitStruct("PGPROC structures",
239 requestSize,
240 &found);
241
242 MemSet(ptr, 0, requestSize);
243
244 procs = (PGPROC *) ptr;
245 ptr = (char *) ptr + TotalProcs * sizeof(PGPROC);
246
247 ProcGlobal->allProcs = procs;
248 /* XXX allProcCount isn't really all of them; it excludes prepared xacts */
250
251 /*
252 * Allocate arrays mirroring PGPROC fields in a dense manner. See
253 * PROC_HDR.
254 *
255 * XXX: It might make sense to increase padding for these arrays, given
256 * how hotly they are accessed.
257 */
258 ProcGlobal->xids = (TransactionId *) ptr;
259 ptr = (char *) ptr + (TotalProcs * sizeof(*ProcGlobal->xids));
260
262 ptr = (char *) ptr + (TotalProcs * sizeof(*ProcGlobal->subxidStates));
263
264 ProcGlobal->statusFlags = (uint8 *) ptr;
265 ptr = (char *) ptr + (TotalProcs * sizeof(*ProcGlobal->statusFlags));
266
267 /* make sure wer didn't overflow */
268 Assert((ptr > (char *) procs) && (ptr <= (char *) procs + requestSize));
269
270 /*
271 * Allocate arrays for fast-path locks. Those are variable-length, so
272 * can't be included in PGPROC directly. We allocate a separate piece of
273 * shared memory and then divide that between backends.
274 */
275 fpLockBitsSize = MAXALIGN(FastPathLockGroupsPerBackend * sizeof(uint64));
276 fpRelIdSize = MAXALIGN(FastPathLockSlotsPerBackend() * sizeof(Oid));
277
278 requestSize = FastPathLockShmemSize();
279
280 fpPtr = ShmemInitStruct("Fast-Path Lock Array",
281 requestSize,
282 &found);
283
284 MemSet(fpPtr, 0, requestSize);
285
286 /* For asserts checking we did not overflow. */
287 fpEndPtr = fpPtr + requestSize;
288
289 for (i = 0; i < TotalProcs; i++)
290 {
291 PGPROC *proc = &procs[i];
292
293 /* Common initialization for all PGPROCs, regardless of type. */
294
295 /*
296 * Set the fast-path lock arrays, and move the pointer. We interleave
297 * the two arrays, to (hopefully) get some locality for each backend.
298 */
299 proc->fpLockBits = (uint64 *) fpPtr;
300 fpPtr += fpLockBitsSize;
301
302 proc->fpRelId = (Oid *) fpPtr;
303 fpPtr += fpRelIdSize;
304
305 Assert(fpPtr <= fpEndPtr);
306
307 /*
308 * Set up per-PGPROC semaphore, latch, and fpInfoLock. Prepared xact
309 * dummy PGPROCs don't need these though - they're never associated
310 * with a real process
311 */
313 {
314 proc->sem = PGSemaphoreCreate();
315 InitSharedLatch(&(proc->procLatch));
317 }
318
319 /*
320 * Newly created PGPROCs for normal backends, autovacuum workers,
321 * special workers, bgworkers, and walsenders must be queued up on the
322 * appropriate free list. Because there can only ever be a small,
323 * fixed number of auxiliary processes, no free list is used in that
324 * case; InitAuxiliaryProcess() instead uses a linear search. PGPROCs
325 * for prepared transactions are added to a free list by
326 * TwoPhaseShmemInit().
327 */
328 if (i < MaxConnections)
329 {
330 /* PGPROC for normal backend, add to freeProcs list */
333 }
335 {
336 /* PGPROC for AV or special worker, add to autovacFreeProcs list */
339 }
341 {
342 /* PGPROC for bgworker, add to bgworkerFreeProcs list */
345 }
346 else if (i < MaxBackends)
347 {
348 /* PGPROC for walsender, add to walsenderFreeProcs list */
351 }
352
353 /* Initialize myProcLocks[] shared memory queues. */
354 for (j = 0; j < NUM_LOCK_PARTITIONS; j++)
355 dlist_init(&(proc->myProcLocks[j]));
356
357 /* Initialize lockGroupMembers list. */
359
360 /*
361 * Initialize the atomic variables, otherwise, it won't be safe to
362 * access them for backends that aren't currently in use.
363 */
366 pg_atomic_init_u64(&(proc->waitStart), 0);
367 }
368
369 /* Should have consumed exactly the expected amount of fast-path memory. */
370 Assert(fpPtr == fpEndPtr);
371
372 /*
373 * Save pointers to the blocks of PGPROC structures reserved for auxiliary
374 * processes and prepared transactions.
375 */
376 AuxiliaryProcs = &procs[MaxBackends];
378
379 /* Create ProcStructLock spinlock, too */
380 ProcStructLock = (slock_t *) ShmemInitStruct("ProcStructLock spinlock",
381 sizeof(slock_t),
382 &found);
384}
385
386/*
387 * InitProcess -- initialize a per-process PGPROC entry for this backend
388 */
389void
391{
392 dlist_head *procgloballist;
393
394 /*
395 * ProcGlobal should be set up already (if we are a backend, we inherit
396 * this by fork() or EXEC_BACKEND mechanism from the postmaster).
397 */
398 if (ProcGlobal == NULL)
399 elog(PANIC, "proc header uninitialized");
400
401 if (MyProc != NULL)
402 elog(ERROR, "you already exist");
403
404 /*
405 * Before we start accessing the shared memory in a serious way, mark
406 * ourselves as an active postmaster child; this is so that the postmaster
407 * can detect it if we exit without cleaning up.
408 */
411
412 /*
413 * Decide which list should supply our PGPROC. This logic must match the
414 * way the freelists were constructed in InitProcGlobal().
415 */
417 procgloballist = &ProcGlobal->autovacFreeProcs;
418 else if (AmBackgroundWorkerProcess())
419 procgloballist = &ProcGlobal->bgworkerFreeProcs;
420 else if (AmWalSenderProcess())
421 procgloballist = &ProcGlobal->walsenderFreeProcs;
422 else
423 procgloballist = &ProcGlobal->freeProcs;
424
425 /*
426 * Try to get a proc struct from the appropriate free list. If this
427 * fails, we must be out of PGPROC structures (not to mention semaphores).
428 *
429 * While we are holding the ProcStructLock, also copy the current shared
430 * estimate of spins_per_delay to local storage.
431 */
433
435
436 if (!dlist_is_empty(procgloballist))
437 {
440 }
441 else
442 {
443 /*
444 * If we reach here, all the PGPROCs are in use. This is one of the
445 * possible places to detect "too many backends", so give the standard
446 * error message. XXX do we need to give a different failure message
447 * in the autovacuum case?
448 */
450 if (AmWalSenderProcess())
452 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
453 errmsg("number of requested standby connections exceeds \"max_wal_senders\" (currently %d)",
456 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
457 errmsg("sorry, too many clients already")));
458 }
460
461 /*
462 * Cross-check that the PGPROC is of the type we expect; if this were not
463 * the case, it would get returned to the wrong list.
464 */
465 Assert(MyProc->procgloballist == procgloballist);
466
467 /*
468 * Initialize all fields of MyProc, except for those previously
469 * initialized by InitProcGlobal.
470 */
473 MyProc->fpVXIDLock = false;
480 /* databaseId and roleId will be filled in later */
486 MyProc->statusFlags = 0;
487 /* NB -- autovac launcher intentionally does not set IS_AUTOVACUUM */
491 MyProc->lwWaitMode = 0;
492 MyProc->waitLock = NULL;
493 MyProc->waitProcLock = NULL;
495#ifdef USE_ASSERT_CHECKING
496 {
497 int i;
498
499 /* Last process should have released all locks. */
500 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
502 }
503#endif
505
506 /* Initialize fields for sync rep */
507 MyProc->waitLSN = 0;
510
511 /* Initialize fields for group XID clearing. */
515
516 /* Check that group locking fields are in a proper initial state. */
517 Assert(MyProc->lockGroupLeader == NULL);
519
520 /* Initialize wait event information. */
522
523 /* Initialize fields for group transaction status update. */
524 MyProc->clogGroupMember = false;
530
531 /*
532 * Acquire ownership of the PGPROC's latch, so that we can use WaitLatch
533 * on it. That allows us to repoint the process latch, which so far
534 * points to process local one, to the shared one.
535 */
538
539 /* now that we have a proc, report wait events to shared memory */
541
542 /*
543 * We might be reusing a semaphore that belonged to a failed process. So
544 * be careful and reinitialize its value here. (This is not strictly
545 * necessary anymore, but seems like a good idea for cleanliness.)
546 */
548
549 /*
550 * Arrange to clean up at backend exit.
551 */
553
554 /*
555 * Now that we have a PGPROC, we could try to acquire locks, so initialize
556 * local state needed for LWLocks, and the deadlock checker.
557 */
560
561#ifdef EXEC_BACKEND
562
563 /*
564 * Initialize backend-local pointers to all the shared data structures.
565 * (We couldn't do this until now because it needs LWLocks.)
566 */
568 AttachSharedMemoryStructs();
569#endif
570}
571
572/*
573 * InitProcessPhase2 -- make MyProc visible in the shared ProcArray.
574 *
575 * This is separate from InitProcess because we can't acquire LWLocks until
576 * we've created a PGPROC, but in the EXEC_BACKEND case ProcArrayAdd won't
577 * work until after we've done AttachSharedMemoryStructs.
578 */
579void
581{
582 Assert(MyProc != NULL);
583
584 /*
585 * Add our PGPROC to the PGPROC array in shared memory.
586 */
588
589 /*
590 * Arrange to clean that up at backend exit.
591 */
593}
594
595/*
596 * InitAuxiliaryProcess -- create a PGPROC entry for an auxiliary process
597 *
598 * This is called by bgwriter and similar processes so that they will have a
599 * MyProc value that's real enough to let them wait for LWLocks. The PGPROC
600 * and sema that are assigned are one of the extra ones created during
601 * InitProcGlobal.
602 *
603 * Auxiliary processes are presently not expected to wait for real (lockmgr)
604 * locks, so we need not set up the deadlock checker. They are never added
605 * to the ProcArray or the sinval messaging mechanism, either. They also
606 * don't get a VXID assigned, since this is only useful when we actually
607 * hold lockmgr locks.
608 *
609 * Startup process however uses locks but never waits for them in the
610 * normal backend sense. Startup process also takes part in sinval messaging
611 * as a sendOnly process, so never reads messages from sinval queue. So
612 * Startup process does have a VXID and does show up in pg_locks.
613 */
614void
616{
617 PGPROC *auxproc;
618 int proctype;
619
620 /*
621 * ProcGlobal should be set up already (if we are a backend, we inherit
622 * this by fork() or EXEC_BACKEND mechanism from the postmaster).
623 */
624 if (ProcGlobal == NULL || AuxiliaryProcs == NULL)
625 elog(PANIC, "proc header uninitialized");
626
627 if (MyProc != NULL)
628 elog(ERROR, "you already exist");
629
632
633 /*
634 * We use the ProcStructLock to protect assignment and releasing of
635 * AuxiliaryProcs entries.
636 *
637 * While we are holding the ProcStructLock, also copy the current shared
638 * estimate of spins_per_delay to local storage.
639 */
641
643
644 /*
645 * Find a free auxproc ... *big* trouble if there isn't one ...
646 */
647 for (proctype = 0; proctype < NUM_AUXILIARY_PROCS; proctype++)
648 {
649 auxproc = &AuxiliaryProcs[proctype];
650 if (auxproc->pid == 0)
651 break;
652 }
653 if (proctype >= NUM_AUXILIARY_PROCS)
654 {
656 elog(FATAL, "all AuxiliaryProcs are in use");
657 }
658
659 /* Mark auxiliary proc as in use by me */
660 /* use volatile pointer to prevent code rearrangement */
661 ((volatile PGPROC *) auxproc)->pid = MyProcPid;
662
664
665 MyProc = auxproc;
667
668 /*
669 * Initialize all fields of MyProc, except for those previously
670 * initialized by InitProcGlobal.
671 */
674 MyProc->fpVXIDLock = false;
683 MyProc->isRegularBackend = false;
685 MyProc->statusFlags = 0;
687 MyProc->lwWaitMode = 0;
688 MyProc->waitLock = NULL;
689 MyProc->waitProcLock = NULL;
691#ifdef USE_ASSERT_CHECKING
692 {
693 int i;
694
695 /* Last process should have released all locks. */
696 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
698 }
699#endif
700
701 /*
702 * Acquire ownership of the PGPROC's latch, so that we can use WaitLatch
703 * on it. That allows us to repoint the process latch, which so far
704 * points to process local one, to the shared one.
705 */
708
709 /* now that we have a proc, report wait events to shared memory */
711
712 /* Check that group locking fields are in a proper initial state. */
713 Assert(MyProc->lockGroupLeader == NULL);
715
716 /*
717 * We might be reusing a semaphore that belonged to a failed process. So
718 * be careful and reinitialize its value here. (This is not strictly
719 * necessary anymore, but seems like a good idea for cleanliness.)
720 */
722
723 /*
724 * Arrange to clean up at process exit.
725 */
727
728 /*
729 * Now that we have a PGPROC, we could try to acquire lightweight locks.
730 * Initialize local state needed for them. (Heavyweight locks cannot be
731 * acquired in aux processes.)
732 */
734
735#ifdef EXEC_BACKEND
736
737 /*
738 * Initialize backend-local pointers to all the shared data structures.
739 * (We couldn't do this until now because it needs LWLocks.)
740 */
742 AttachSharedMemoryStructs();
743#endif
744}
745
746/*
747 * Used from bufmgr to share the value of the buffer that Startup waits on,
748 * or to reset the value to "not waiting" (-1). This allows processing
749 * of recovery conflicts for buffer pins. Set is made before backends look
750 * at this value, so locking not required, especially since the set is
751 * an atomic integer set operation.
752 */
753void
755{
756 /* use volatile pointer to prevent code rearrangement */
757 volatile PROC_HDR *procglobal = ProcGlobal;
758
759 procglobal->startupBufferPinWaitBufId = bufid;
760}
761
762/*
763 * Used by backends when they receive a request to check for buffer pin waits.
764 */
765int
767{
768 /* use volatile pointer to prevent code rearrangement */
769 volatile PROC_HDR *procglobal = ProcGlobal;
770
771 return procglobal->startupBufferPinWaitBufId;
772}
773
774/*
775 * Check whether there are at least N free PGPROC objects. If false is
776 * returned, *nfree will be set to the number of free PGPROC objects.
777 * Otherwise, *nfree will be set to n.
778 *
779 * Note: this is designed on the assumption that N will generally be small.
780 */
781bool
782HaveNFreeProcs(int n, int *nfree)
783{
784 dlist_iter iter;
785
786 Assert(n > 0);
787 Assert(nfree);
788
790
791 *nfree = 0;
793 {
794 (*nfree)++;
795 if (*nfree == n)
796 break;
797 }
798
800
801 return (*nfree == n);
802}
803
804/*
805 * Cancel any pending wait for lock, when aborting a transaction, and revert
806 * any strong lock count acquisition for a lock being acquired.
807 *
808 * (Normally, this would only happen if we accept a cancel/die
809 * interrupt while waiting; but an ereport(ERROR) before or during the lock
810 * wait is within the realm of possibility, too.)
811 */
812void
814{
815 LOCALLOCK *lockAwaited;
816 LWLock *partitionLock;
817 DisableTimeoutParams timeouts[2];
818
820
822
823 /* Nothing to do if we weren't waiting for a lock */
824 lockAwaited = GetAwaitedLock();
825 if (lockAwaited == NULL)
826 {
828 return;
829 }
830
831 /*
832 * Turn off the deadlock and lock timeout timers, if they are still
833 * running (see ProcSleep). Note we must preserve the LOCK_TIMEOUT
834 * indicator flag, since this function is executed before
835 * ProcessInterrupts when responding to SIGINT; else we'd lose the
836 * knowledge that the SIGINT came from a lock timeout and not an external
837 * source.
838 */
839 timeouts[0].id = DEADLOCK_TIMEOUT;
840 timeouts[0].keep_indicator = false;
841 timeouts[1].id = LOCK_TIMEOUT;
842 timeouts[1].keep_indicator = true;
843 disable_timeouts(timeouts, 2);
844
845 /* Unlink myself from the wait queue, if on it (might not be anymore!) */
846 partitionLock = LockHashPartitionLock(lockAwaited->hashcode);
847 LWLockAcquire(partitionLock, LW_EXCLUSIVE);
848
850 {
851 /* We could not have been granted the lock yet */
852 RemoveFromWaitQueue(MyProc, lockAwaited->hashcode);
853 }
854 else
855 {
856 /*
857 * Somebody kicked us off the lock queue already. Perhaps they
858 * granted us the lock, or perhaps they detected a deadlock. If they
859 * did grant us the lock, we'd better remember it in our local lock
860 * table.
861 */
864 }
865
867
868 LWLockRelease(partitionLock);
869
871}
872
873
874/*
875 * ProcReleaseLocks() -- release locks associated with current transaction
876 * at main transaction commit or abort
877 *
878 * At main transaction commit, we release standard locks except session locks.
879 * At main transaction abort, we release all locks including session locks.
880 *
881 * Advisory locks are released only if they are transaction-level;
882 * session-level holds remain, whether this is a commit or not.
883 *
884 * At subtransaction commit, we don't release any locks (so this func is not
885 * needed at all); we will defer the releasing to the parent transaction.
886 * At subtransaction abort, we release all locks held by the subtransaction;
887 * this is implemented by retail releasing of the locks under control of
888 * the ResourceOwner mechanism.
889 */
890void
891ProcReleaseLocks(bool isCommit)
892{
893 if (!MyProc)
894 return;
895 /* If waiting, get off wait queue (should only be needed after error) */
897 /* Release standard locks, including session-level if aborting */
899 /* Release transaction-level advisory locks */
901}
902
903
904/*
905 * RemoveProcFromArray() -- Remove this process from the shared ProcArray.
906 */
907static void
909{
910 Assert(MyProc != NULL);
912}
913
914/*
915 * ProcKill() -- Destroy the per-proc data structure for
916 * this process. Release any of its held LW locks.
917 */
918static void
920{
921 PGPROC *proc;
922 dlist_head *procgloballist;
923
924 Assert(MyProc != NULL);
925
926 /* not safe if forked by system(), etc. */
927 if (MyProc->pid != (int) getpid())
928 elog(PANIC, "ProcKill() called in child process");
929
930 /* Make sure we're out of the sync rep lists */
932
933#ifdef USE_ASSERT_CHECKING
934 {
935 int i;
936
937 /* Last process should have released all locks. */
938 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
940 }
941#endif
942
943 /*
944 * Release any LW locks I am holding. There really shouldn't be any, but
945 * it's cheap to check again before we cut the knees off the LWLock
946 * facility by releasing our PGPROC ...
947 */
949
950 /* Cancel any pending condition variable sleep, too */
952
953 /*
954 * Detach from any lock group of which we are a member. If the leader
955 * exits before all other group members, its PGPROC will remain allocated
956 * until the last group process exits; that process must return the
957 * leader's PGPROC to the appropriate list.
958 */
959 if (MyProc->lockGroupLeader != NULL)
960 {
961 PGPROC *leader = MyProc->lockGroupLeader;
962 LWLock *leader_lwlock = LockHashPartitionLockByProc(leader);
963
964 LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
967 if (dlist_is_empty(&leader->lockGroupMembers))
968 {
969 leader->lockGroupLeader = NULL;
970 if (leader != MyProc)
971 {
972 procgloballist = leader->procgloballist;
973
974 /* Leader exited first; return its PGPROC. */
976 dlist_push_head(procgloballist, &leader->links);
978 }
979 }
980 else if (leader != MyProc)
981 MyProc->lockGroupLeader = NULL;
982 LWLockRelease(leader_lwlock);
983 }
984
985 /*
986 * Reset MyLatch to the process local one. This is so that signal
987 * handlers et al can continue using the latch after the shared latch
988 * isn't ours anymore.
989 *
990 * Similarly, stop reporting wait events to MyProc->wait_event_info.
991 *
992 * After that clear MyProc and disown the shared latch.
993 */
996
997 proc = MyProc;
998 MyProc = NULL;
1000 DisownLatch(&proc->procLatch);
1001
1002 /* Mark the proc no longer in use */
1003 proc->pid = 0;
1006
1007 procgloballist = proc->procgloballist;
1009
1010 /*
1011 * If we're still a member of a locking group, that means we're a leader
1012 * which has somehow exited before its children. The last remaining child
1013 * will release our PGPROC. Otherwise, release it now.
1014 */
1015 if (proc->lockGroupLeader == NULL)
1016 {
1017 /* Since lockGroupLeader is NULL, lockGroupMembers should be empty. */
1019
1020 /* Return PGPROC structure (and semaphore) to appropriate freelist */
1021 dlist_push_tail(procgloballist, &proc->links);
1022 }
1023
1024 /* Update shared estimate of spins_per_delay */
1026
1028
1029 /* wake autovac launcher if needed -- see comments in FreeWorkerInfo */
1030 if (AutovacuumLauncherPid != 0)
1032}
1033
1034/*
1035 * AuxiliaryProcKill() -- Cut-down version of ProcKill for auxiliary
1036 * processes (bgwriter, etc). The PGPROC and sema are not released, only
1037 * marked as not-in-use.
1038 */
1039static void
1041{
1042 int proctype = DatumGetInt32(arg);
1044 PGPROC *proc;
1045
1046 Assert(proctype >= 0 && proctype < NUM_AUXILIARY_PROCS);
1047
1048 /* not safe if forked by system(), etc. */
1049 if (MyProc->pid != (int) getpid())
1050 elog(PANIC, "AuxiliaryProcKill() called in child process");
1051
1052 auxproc = &AuxiliaryProcs[proctype];
1053
1054 Assert(MyProc == auxproc);
1055
1056 /* Release any LW locks I am holding (see notes above) */
1058
1059 /* Cancel any pending condition variable sleep, too */
1061
1062 /* look at the equivalent ProcKill() code for comments */
1065
1066 proc = MyProc;
1067 MyProc = NULL;
1069 DisownLatch(&proc->procLatch);
1070
1072
1073 /* Mark auxiliary proc no longer in use */
1074 proc->pid = 0;
1077
1078 /* Update shared estimate of spins_per_delay */
1080
1082}
1083
1084/*
1085 * AuxiliaryPidGetProc -- get PGPROC for an auxiliary process
1086 * given its PID
1087 *
1088 * Returns NULL if not found.
1089 */
1090PGPROC *
1092{
1093 PGPROC *result = NULL;
1094 int index;
1095
1096 if (pid == 0) /* never match dummy PGPROCs */
1097 return NULL;
1098
1099 for (index = 0; index < NUM_AUXILIARY_PROCS; index++)
1100 {
1101 PGPROC *proc = &AuxiliaryProcs[index];
1102
1103 if (proc->pid == pid)
1104 {
1105 result = proc;
1106 break;
1107 }
1108 }
1109 return result;
1110}
1111
1112
1113/*
1114 * JoinWaitQueue -- join the wait queue on the specified lock
1115 *
1116 * It's not actually guaranteed that we need to wait when this function is
1117 * called, because it could be that when we try to find a position at which
1118 * to insert ourself into the wait queue, we discover that we must be inserted
1119 * ahead of everyone who wants a lock that conflict with ours. In that case,
1120 * we get the lock immediately. Because of this, it's sensible for this function
1121 * to have a dontWait argument, despite the name.
1122 *
1123 * On entry, the caller has already set up LOCK and PROCLOCK entries to
1124 * reflect that we have "requested" the lock. The caller is responsible for
1125 * cleaning that up, if we end up not joining the queue after all.
1126 *
1127 * The lock table's partition lock must be held at entry, and is still held
1128 * at exit. The caller must release it before calling ProcSleep().
1129 *
1130 * Result is one of the following:
1131 *
1132 * PROC_WAIT_STATUS_OK - lock was immediately granted
1133 * PROC_WAIT_STATUS_WAITING - joined the wait queue; call ProcSleep()
1134 * PROC_WAIT_STATUS_ERROR - immediate deadlock was detected, or would
1135 * need to wait and dontWait == true
1136 *
1137 * NOTES: The process queue is now a priority queue for locking.
1138 */
1140JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
1141{
1142 LOCKMODE lockmode = locallock->tag.mode;
1143 LOCK *lock = locallock->lock;
1144 PROCLOCK *proclock = locallock->proclock;
1145 uint32 hashcode = locallock->hashcode;
1146 LWLock *partitionLock PG_USED_FOR_ASSERTS_ONLY = LockHashPartitionLock(hashcode);
1147 dclist_head *waitQueue = &lock->waitProcs;
1148 PGPROC *insert_before = NULL;
1149 LOCKMASK myProcHeldLocks;
1150 LOCKMASK myHeldLocks;
1151 bool early_deadlock = false;
1152 PGPROC *leader = MyProc->lockGroupLeader;
1153
1154 Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
1155
1156 /*
1157 * Set bitmask of locks this process already holds on this object.
1158 */
1159 myHeldLocks = MyProc->heldLocks = proclock->holdMask;
1160
1161 /*
1162 * Determine which locks we're already holding.
1163 *
1164 * If group locking is in use, locks held by members of my locking group
1165 * need to be included in myHeldLocks. This is not required for relation
1166 * extension lock which conflict among group members. However, including
1167 * them in myHeldLocks will give group members the priority to get those
1168 * locks as compared to other backends which are also trying to acquire
1169 * those locks. OTOH, we can avoid giving priority to group members for
1170 * that kind of locks, but there doesn't appear to be a clear advantage of
1171 * the same.
1172 */
1173 myProcHeldLocks = proclock->holdMask;
1174 myHeldLocks = myProcHeldLocks;
1175 if (leader != NULL)
1176 {
1177 dlist_iter iter;
1178
1179 dlist_foreach(iter, &lock->procLocks)
1180 {
1181 PROCLOCK *otherproclock;
1182
1183 otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
1184
1185 if (otherproclock->groupLeader == leader)
1186 myHeldLocks |= otherproclock->holdMask;
1187 }
1188 }
1189
1190 /*
1191 * Determine where to add myself in the wait queue.
1192 *
1193 * Normally I should go at the end of the queue. However, if I already
1194 * hold locks that conflict with the request of any previous waiter, put
1195 * myself in the queue just in front of the first such waiter. This is not
1196 * a necessary step, since deadlock detection would move me to before that
1197 * waiter anyway; but it's relatively cheap to detect such a conflict
1198 * immediately, and avoid delaying till deadlock timeout.
1199 *
1200 * Special case: if I find I should go in front of some waiter, check to
1201 * see if I conflict with already-held locks or the requests before that
1202 * waiter. If not, then just grant myself the requested lock immediately.
1203 * This is the same as the test for immediate grant in LockAcquire, except
1204 * we are only considering the part of the wait queue before my insertion
1205 * point.
1206 */
1207 if (myHeldLocks != 0 && !dclist_is_empty(waitQueue))
1208 {
1209 LOCKMASK aheadRequests = 0;
1210 dlist_iter iter;
1211
1212 dclist_foreach(iter, waitQueue)
1213 {
1214 PGPROC *proc = dlist_container(PGPROC, links, iter.cur);
1215
1216 /*
1217 * If we're part of the same locking group as this waiter, its
1218 * locks neither conflict with ours nor contribute to
1219 * aheadRequests.
1220 */
1221 if (leader != NULL && leader == proc->lockGroupLeader)
1222 continue;
1223
1224 /* Must he wait for me? */
1225 if (lockMethodTable->conflictTab[proc->waitLockMode] & myHeldLocks)
1226 {
1227 /* Must I wait for him ? */
1228 if (lockMethodTable->conflictTab[lockmode] & proc->heldLocks)
1229 {
1230 /*
1231 * Yes, so we have a deadlock. Easiest way to clean up
1232 * correctly is to call RemoveFromWaitQueue(), but we
1233 * can't do that until we are *on* the wait queue. So, set
1234 * a flag to check below, and break out of loop. Also,
1235 * record deadlock info for later message.
1236 */
1237 RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
1238 early_deadlock = true;
1239 break;
1240 }
1241 /* I must go before this waiter. Check special case. */
1242 if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
1243 !LockCheckConflicts(lockMethodTable, lockmode, lock,
1244 proclock))
1245 {
1246 /* Skip the wait and just grant myself the lock. */
1247 GrantLock(lock, proclock, lockmode);
1248 return PROC_WAIT_STATUS_OK;
1249 }
1250
1251 /* Put myself into wait queue before conflicting process */
1252 insert_before = proc;
1253 break;
1254 }
1255 /* Nope, so advance to next waiter */
1256 aheadRequests |= LOCKBIT_ON(proc->waitLockMode);
1257 }
1258 }
1259
1260 /*
1261 * If we detected deadlock, give up without waiting. This must agree with
1262 * CheckDeadLock's recovery code.
1263 */
1264 if (early_deadlock)
1266
1267 /*
1268 * At this point we know that we'd really need to sleep. If we've been
1269 * commanded not to do that, bail out.
1270 */
1271 if (dontWait)
1273
1274 /*
1275 * Insert self into queue, at the position determined above.
1276 */
1277 if (insert_before)
1278 dclist_insert_before(waitQueue, &insert_before->links, &MyProc->links);
1279 else
1280 dclist_push_tail(waitQueue, &MyProc->links);
1281
1282 lock->waitMask |= LOCKBIT_ON(lockmode);
1283
1284 /* Set up wait information in PGPROC object, too */
1285 MyProc->heldLocks = myProcHeldLocks;
1286 MyProc->waitLock = lock;
1287 MyProc->waitProcLock = proclock;
1288 MyProc->waitLockMode = lockmode;
1289
1291
1293}
1294
1295/*
1296 * ProcSleep -- put process to sleep waiting on lock
1297 *
1298 * This must be called when JoinWaitQueue() returns PROC_WAIT_STATUS_WAITING.
1299 * Returns after the lock has been granted, or if a deadlock is detected. Can
1300 * also bail out with ereport(ERROR), if some other error condition, or a
1301 * timeout or cancellation is triggered.
1302 *
1303 * Result is one of the following:
1304 *
1305 * PROC_WAIT_STATUS_OK - lock was granted
1306 * PROC_WAIT_STATUS_ERROR - a deadlock was detected
1307 */
1310{
1311 LOCKMODE lockmode = locallock->tag.mode;
1312 LOCK *lock = locallock->lock;
1313 uint32 hashcode = locallock->hashcode;
1314 LWLock *partitionLock = LockHashPartitionLock(hashcode);
1315 TimestampTz standbyWaitStart = 0;
1316 bool allow_autovacuum_cancel = true;
1317 bool logged_recovery_conflict = false;
1318 ProcWaitStatus myWaitStatus;
1319
1320 /* The caller must've armed the on-error cleanup mechanism */
1321 Assert(GetAwaitedLock() == locallock);
1322 Assert(!LWLockHeldByMe(partitionLock));
1323
1324 /*
1325 * Now that we will successfully clean up after an ereport, it's safe to
1326 * check to see if there's a buffer pin deadlock against the Startup
1327 * process. Of course, that's only necessary if we're doing Hot Standby
1328 * and are not the Startup process ourselves.
1329 */
1332
1333 /* Reset deadlock_state before enabling the timeout handler */
1335 got_deadlock_timeout = false;
1336
1337 /*
1338 * Set timer so we can wake up after awhile and check for a deadlock. If a
1339 * deadlock is detected, the handler sets MyProc->waitStatus =
1340 * PROC_WAIT_STATUS_ERROR, allowing us to know that we must report failure
1341 * rather than success.
1342 *
1343 * By delaying the check until we've waited for a bit, we can avoid
1344 * running the rather expensive deadlock-check code in most cases.
1345 *
1346 * If LockTimeout is set, also enable the timeout for that. We can save a
1347 * few cycles by enabling both timeout sources in one call.
1348 *
1349 * If InHotStandby we set lock waits slightly later for clarity with other
1350 * code.
1351 */
1352 if (!InHotStandby)
1353 {
1354 if (LockTimeout > 0)
1355 {
1356 EnableTimeoutParams timeouts[2];
1357
1358 timeouts[0].id = DEADLOCK_TIMEOUT;
1359 timeouts[0].type = TMPARAM_AFTER;
1360 timeouts[0].delay_ms = DeadlockTimeout;
1361 timeouts[1].id = LOCK_TIMEOUT;
1362 timeouts[1].type = TMPARAM_AFTER;
1363 timeouts[1].delay_ms = LockTimeout;
1364 enable_timeouts(timeouts, 2);
1365 }
1366 else
1368
1369 /*
1370 * Use the current time obtained for the deadlock timeout timer as
1371 * waitStart (i.e., the time when this process started waiting for the
1372 * lock). Since getting the current time newly can cause overhead, we
1373 * reuse the already-obtained time to avoid that overhead.
1374 *
1375 * Note that waitStart is updated without holding the lock table's
1376 * partition lock, to avoid the overhead by additional lock
1377 * acquisition. This can cause "waitstart" in pg_locks to become NULL
1378 * for a very short period of time after the wait started even though
1379 * "granted" is false. This is OK in practice because we can assume
1380 * that users are likely to look at "waitstart" when waiting for the
1381 * lock for a long time.
1382 */
1385 }
1387 {
1388 /*
1389 * Set the wait start timestamp if logging is enabled and in hot
1390 * standby.
1391 */
1392 standbyWaitStart = GetCurrentTimestamp();
1393 }
1394
1395 /*
1396 * If somebody wakes us between LWLockRelease and WaitLatch, the latch
1397 * will not wait. But a set latch does not necessarily mean that the lock
1398 * is free now, as there are many other sources for latch sets than
1399 * somebody releasing the lock.
1400 *
1401 * We process interrupts whenever the latch has been set, so cancel/die
1402 * interrupts are processed quickly. This means we must not mind losing
1403 * control to a cancel/die interrupt here. We don't, because we have no
1404 * shared-state-change work to do after being granted the lock (the
1405 * grantor did it all). We do have to worry about canceling the deadlock
1406 * timeout and updating the locallock table, but if we lose control to an
1407 * error, LockErrorCleanup will fix that up.
1408 */
1409 do
1410 {
1411 if (InHotStandby)
1412 {
1413 bool maybe_log_conflict =
1414 (standbyWaitStart != 0 && !logged_recovery_conflict);
1415
1416 /* Set a timer and wait for that or for the lock to be granted */
1418 maybe_log_conflict);
1419
1420 /*
1421 * Emit the log message if the startup process is waiting longer
1422 * than deadlock_timeout for recovery conflict on lock.
1423 */
1424 if (maybe_log_conflict)
1425 {
1427
1428 if (TimestampDifferenceExceeds(standbyWaitStart, now,
1430 {
1431 VirtualTransactionId *vxids;
1432 int cnt;
1433
1434 vxids = GetLockConflicts(&locallock->tag.lock,
1435 AccessExclusiveLock, &cnt);
1436
1437 /*
1438 * Log the recovery conflict and the list of PIDs of
1439 * backends holding the conflicting lock. Note that we do
1440 * logging even if there are no such backends right now
1441 * because the startup process here has already waited
1442 * longer than deadlock_timeout.
1443 */
1445 standbyWaitStart, now,
1446 cnt > 0 ? vxids : NULL, true);
1447 logged_recovery_conflict = true;
1448 }
1449 }
1450 }
1451 else
1452 {
1454 PG_WAIT_LOCK | locallock->tag.lock.locktag_type);
1456 /* check for deadlocks first, as that's probably log-worthy */
1458 {
1459 CheckDeadLock();
1460 got_deadlock_timeout = false;
1461 }
1463 }
1464
1465 /*
1466 * waitStatus could change from PROC_WAIT_STATUS_WAITING to something
1467 * else asynchronously. Read it just once per loop to prevent
1468 * surprising behavior (such as missing log messages).
1469 */
1470 myWaitStatus = *((volatile ProcWaitStatus *) &MyProc->waitStatus);
1471
1472 /*
1473 * If we are not deadlocked, but are waiting on an autovacuum-induced
1474 * task, send a signal to interrupt it.
1475 */
1476 if (deadlock_state == DS_BLOCKED_BY_AUTOVACUUM && allow_autovacuum_cancel)
1477 {
1479 uint8 statusFlags;
1480 uint8 lockmethod_copy;
1481 LOCKTAG locktag_copy;
1482
1483 /*
1484 * Grab info we need, then release lock immediately. Note this
1485 * coding means that there is a tiny chance that the process
1486 * terminates its current transaction and starts a different one
1487 * before we have a change to send the signal; the worst possible
1488 * consequence is that a for-wraparound vacuum is canceled. But
1489 * that could happen in any case unless we were to do kill() with
1490 * the lock held, which is much more undesirable.
1491 */
1492 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
1493 statusFlags = ProcGlobal->statusFlags[autovac->pgxactoff];
1494 lockmethod_copy = lock->tag.locktag_lockmethodid;
1495 locktag_copy = lock->tag;
1496 LWLockRelease(ProcArrayLock);
1497
1498 /*
1499 * Only do it if the worker is not working to protect against Xid
1500 * wraparound.
1501 */
1502 if ((statusFlags & PROC_IS_AUTOVACUUM) &&
1503 !(statusFlags & PROC_VACUUM_FOR_WRAPAROUND))
1504 {
1505 int pid = autovac->pid;
1506
1507 /* report the case, if configured to do so */
1509 {
1510 StringInfoData locktagbuf;
1511 StringInfoData logbuf; /* errdetail for server log */
1512
1513 initStringInfo(&locktagbuf);
1514 initStringInfo(&logbuf);
1515 DescribeLockTag(&locktagbuf, &locktag_copy);
1516 appendStringInfo(&logbuf,
1517 "Process %d waits for %s on %s.",
1518 MyProcPid,
1519 GetLockmodeName(lockmethod_copy, lockmode),
1520 locktagbuf.data);
1521
1523 (errmsg_internal("sending cancel to blocking autovacuum PID %d",
1524 pid),
1525 errdetail_log("%s", logbuf.data)));
1526
1527 pfree(locktagbuf.data);
1528 pfree(logbuf.data);
1529 }
1530
1531 /* send the autovacuum worker Back to Old Kent Road */
1532 if (kill(pid, SIGINT) < 0)
1533 {
1534 /*
1535 * There's a race condition here: once we release the
1536 * ProcArrayLock, it's possible for the autovac worker to
1537 * close up shop and exit before we can do the kill().
1538 * Therefore, we do not whinge about no-such-process.
1539 * Other errors such as EPERM could conceivably happen if
1540 * the kernel recycles the PID fast enough, but such cases
1541 * seem improbable enough that it's probably best to issue
1542 * a warning if we see some other errno.
1543 */
1544 if (errno != ESRCH)
1546 (errmsg("could not send signal to process %d: %m",
1547 pid)));
1548 }
1549 }
1550
1551 /* prevent signal from being sent again more than once */
1552 allow_autovacuum_cancel = false;
1553 }
1554
1555 /*
1556 * If awoken after the deadlock check interrupt has run, and
1557 * log_lock_waits is on, then report about the wait.
1558 */
1560 {
1562 lock_waiters_sbuf,
1563 lock_holders_sbuf;
1564 const char *modename;
1565 long secs;
1566 int usecs;
1567 long msecs;
1568 int lockHoldersNum = 0;
1569
1571 initStringInfo(&lock_waiters_sbuf);
1572 initStringInfo(&lock_holders_sbuf);
1573
1574 DescribeLockTag(&buf, &locallock->tag.lock);
1575 modename = GetLockmodeName(locallock->tag.lock.locktag_lockmethodid,
1576 lockmode);
1579 &secs, &usecs);
1580 msecs = secs * 1000 + usecs / 1000;
1581 usecs = usecs % 1000;
1582
1583 /* Gather a list of all lock holders and waiters */
1584 LWLockAcquire(partitionLock, LW_SHARED);
1585 GetLockHoldersAndWaiters(locallock, &lock_holders_sbuf,
1586 &lock_waiters_sbuf, &lockHoldersNum);
1587 LWLockRelease(partitionLock);
1588
1590 ereport(LOG,
1591 (errmsg("process %d avoided deadlock for %s on %s by rearranging queue order after %ld.%03d ms",
1592 MyProcPid, modename, buf.data, msecs, usecs),
1593 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1594 "Processes holding the lock: %s. Wait queue: %s.",
1595 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1596 else if (deadlock_state == DS_HARD_DEADLOCK)
1597 {
1598 /*
1599 * This message is a bit redundant with the error that will be
1600 * reported subsequently, but in some cases the error report
1601 * might not make it to the log (eg, if it's caught by an
1602 * exception handler), and we want to ensure all long-wait
1603 * events get logged.
1604 */
1605 ereport(LOG,
1606 (errmsg("process %d detected deadlock while waiting for %s on %s after %ld.%03d ms",
1607 MyProcPid, modename, buf.data, msecs, usecs),
1608 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1609 "Processes holding the lock: %s. Wait queue: %s.",
1610 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1611 }
1612
1613 if (myWaitStatus == PROC_WAIT_STATUS_WAITING)
1614 ereport(LOG,
1615 (errmsg("process %d still waiting for %s on %s after %ld.%03d ms",
1616 MyProcPid, modename, buf.data, msecs, usecs),
1617 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1618 "Processes holding the lock: %s. Wait queue: %s.",
1619 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1620 else if (myWaitStatus == PROC_WAIT_STATUS_OK)
1621 ereport(LOG,
1622 (errmsg("process %d acquired %s on %s after %ld.%03d ms",
1623 MyProcPid, modename, buf.data, msecs, usecs)));
1624 else
1625 {
1626 Assert(myWaitStatus == PROC_WAIT_STATUS_ERROR);
1627
1628 /*
1629 * Currently, the deadlock checker always kicks its own
1630 * process, which means that we'll only see
1631 * PROC_WAIT_STATUS_ERROR when deadlock_state ==
1632 * DS_HARD_DEADLOCK, and there's no need to print redundant
1633 * messages. But for completeness and future-proofing, print
1634 * a message if it looks like someone else kicked us off the
1635 * lock.
1636 */
1638 ereport(LOG,
1639 (errmsg("process %d failed to acquire %s on %s after %ld.%03d ms",
1640 MyProcPid, modename, buf.data, msecs, usecs),
1641 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1642 "Processes holding the lock: %s. Wait queue: %s.",
1643 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1644 }
1645
1646 /*
1647 * At this point we might still need to wait for the lock. Reset
1648 * state so we don't print the above messages again.
1649 */
1651
1652 pfree(buf.data);
1653 pfree(lock_holders_sbuf.data);
1654 pfree(lock_waiters_sbuf.data);
1655 }
1656 } while (myWaitStatus == PROC_WAIT_STATUS_WAITING);
1657
1658 /*
1659 * Disable the timers, if they are still running. As in LockErrorCleanup,
1660 * we must preserve the LOCK_TIMEOUT indicator flag: if a lock timeout has
1661 * already caused QueryCancelPending to become set, we want the cancel to
1662 * be reported as a lock timeout, not a user cancel.
1663 */
1664 if (!InHotStandby)
1665 {
1666 if (LockTimeout > 0)
1667 {
1668 DisableTimeoutParams timeouts[2];
1669
1670 timeouts[0].id = DEADLOCK_TIMEOUT;
1671 timeouts[0].keep_indicator = false;
1672 timeouts[1].id = LOCK_TIMEOUT;
1673 timeouts[1].keep_indicator = true;
1674 disable_timeouts(timeouts, 2);
1675 }
1676 else
1678 }
1679
1680 /*
1681 * Emit the log message if recovery conflict on lock was resolved but the
1682 * startup process waited longer than deadlock_timeout for it.
1683 */
1684 if (InHotStandby && logged_recovery_conflict)
1686 standbyWaitStart, GetCurrentTimestamp(),
1687 NULL, false);
1688
1689 /*
1690 * We don't have to do anything else, because the awaker did all the
1691 * necessary updates of the lock table and MyProc. (The caller is
1692 * responsible for updating the local lock table.)
1693 */
1694 return myWaitStatus;
1695}
1696
1697
1698/*
1699 * ProcWakeup -- wake up a process by setting its latch.
1700 *
1701 * Also remove the process from the wait queue and set its links invalid.
1702 *
1703 * The appropriate lock partition lock must be held by caller.
1704 *
1705 * XXX: presently, this code is only used for the "success" case, and only
1706 * works correctly for that case. To clean up in failure case, would need
1707 * to twiddle the lock's request counts too --- see RemoveFromWaitQueue.
1708 * Hence, in practice the waitStatus parameter must be PROC_WAIT_STATUS_OK.
1709 */
1710void
1712{
1713 if (dlist_node_is_detached(&proc->links))
1714 return;
1715
1717
1718 /* Remove process from wait queue */
1720
1721 /* Clean up process' state and pass it the ok/fail signal */
1722 proc->waitLock = NULL;
1723 proc->waitProcLock = NULL;
1724 proc->waitStatus = waitStatus;
1726
1727 /* And awaken it */
1728 SetLatch(&proc->procLatch);
1729}
1730
1731/*
1732 * ProcLockWakeup -- routine for waking up processes when a lock is
1733 * released (or a prior waiter is aborted). Scan all waiters
1734 * for lock, waken any that are no longer blocked.
1735 *
1736 * The appropriate lock partition lock must be held by caller.
1737 */
1738void
1739ProcLockWakeup(LockMethod lockMethodTable, LOCK *lock)
1740{
1741 dclist_head *waitQueue = &lock->waitProcs;
1742 LOCKMASK aheadRequests = 0;
1743 dlist_mutable_iter miter;
1744
1745 if (dclist_is_empty(waitQueue))
1746 return;
1747
1748 dclist_foreach_modify(miter, waitQueue)
1749 {
1750 PGPROC *proc = dlist_container(PGPROC, links, miter.cur);
1751 LOCKMODE lockmode = proc->waitLockMode;
1752
1753 /*
1754 * Waken if (a) doesn't conflict with requests of earlier waiters, and
1755 * (b) doesn't conflict with already-held locks.
1756 */
1757 if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
1758 !LockCheckConflicts(lockMethodTable, lockmode, lock,
1759 proc->waitProcLock))
1760 {
1761 /* OK to waken */
1762 GrantLock(lock, proc->waitProcLock, lockmode);
1763 /* removes proc from the lock's waiting process queue */
1765 }
1766 else
1767 {
1768 /*
1769 * Lock conflicts: Don't wake, but remember requested mode for
1770 * later checks.
1771 */
1772 aheadRequests |= LOCKBIT_ON(lockmode);
1773 }
1774 }
1775}
1776
1777/*
1778 * CheckDeadLock
1779 *
1780 * We only get to this routine, if DEADLOCK_TIMEOUT fired while waiting for a
1781 * lock to be released by some other process. Check if there's a deadlock; if
1782 * not, just return. (But signal ProcSleep to log a message, if
1783 * log_lock_waits is true.) If we have a real deadlock, remove ourselves from
1784 * the lock's wait queue and signal an error to ProcSleep.
1785 */
1786static void
1788{
1789 int i;
1790
1791 /*
1792 * Acquire exclusive lock on the entire shared lock data structures. Must
1793 * grab LWLocks in partition-number order to avoid LWLock deadlock.
1794 *
1795 * Note that the deadlock check interrupt had better not be enabled
1796 * anywhere that this process itself holds lock partition locks, else this
1797 * will wait forever. Also note that LWLockAcquire creates a critical
1798 * section, so that this routine cannot be interrupted by cancel/die
1799 * interrupts.
1800 */
1801 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
1803
1804 /*
1805 * Check to see if we've been awoken by anyone in the interim.
1806 *
1807 * If we have, we can return and resume our transaction -- happy day.
1808 * Before we are awoken the process releasing the lock grants it to us so
1809 * we know that we don't have to wait anymore.
1810 *
1811 * We check by looking to see if we've been unlinked from the wait queue.
1812 * This is safe because we hold the lock partition lock.
1813 */
1814 if (MyProc->links.prev == NULL ||
1815 MyProc->links.next == NULL)
1816 goto check_done;
1817
1818#ifdef LOCK_DEBUG
1819 if (Debug_deadlocks)
1820 DumpAllLocks();
1821#endif
1822
1823 /* Run the deadlock check, and set deadlock_state for use by ProcSleep */
1825
1827 {
1828 /*
1829 * Oops. We have a deadlock.
1830 *
1831 * Get this process out of wait state. (Note: we could do this more
1832 * efficiently by relying on lockAwaited, but use this coding to
1833 * preserve the flexibility to kill some other transaction than the
1834 * one detecting the deadlock.)
1835 *
1836 * RemoveFromWaitQueue sets MyProc->waitStatus to
1837 * PROC_WAIT_STATUS_ERROR, so ProcSleep will report an error after we
1838 * return from the signal handler.
1839 */
1840 Assert(MyProc->waitLock != NULL);
1842
1843 /*
1844 * We're done here. Transaction abort caused by the error that
1845 * ProcSleep will raise will cause any other locks we hold to be
1846 * released, thus allowing other processes to wake up; we don't need
1847 * to do that here. NOTE: an exception is that releasing locks we
1848 * hold doesn't consider the possibility of waiters that were blocked
1849 * behind us on the lock we just failed to get, and might now be
1850 * wakable because we're not in front of them anymore. However,
1851 * RemoveFromWaitQueue took care of waking up any such processes.
1852 */
1853 }
1854
1855 /*
1856 * And release locks. We do this in reverse order for two reasons: (1)
1857 * Anyone else who needs more than one of the locks will be trying to lock
1858 * them in increasing order; we don't want to release the other process
1859 * until it can get all the locks it needs. (2) This avoids O(N^2)
1860 * behavior inside LWLockRelease.
1861 */
1862check_done:
1863 for (i = NUM_LOCK_PARTITIONS; --i >= 0;)
1865}
1866
1867/*
1868 * CheckDeadLockAlert - Handle the expiry of deadlock_timeout.
1869 *
1870 * NB: Runs inside a signal handler, be careful.
1871 */
1872void
1874{
1875 int save_errno = errno;
1876
1877 got_deadlock_timeout = true;
1878
1879 /*
1880 * Have to set the latch again, even if handle_sig_alarm already did. Back
1881 * then got_deadlock_timeout wasn't yet set... It's unlikely that this
1882 * ever would be a problem, but setting a set latch again is cheap.
1883 *
1884 * Note that, when this function runs inside procsignal_sigusr1_handler(),
1885 * the handler function sets the latch again after the latch is set here.
1886 */
1888 errno = save_errno;
1889}
1890
1891/*
1892 * GetLockHoldersAndWaiters - get lock holders and waiters for a lock
1893 *
1894 * Fill lock_holders_sbuf and lock_waiters_sbuf with the PIDs of processes holding
1895 * and waiting for the lock, and set lockHoldersNum to the number of lock holders.
1896 *
1897 * The lock table's partition lock must be held on entry and remains held on exit.
1898 */
1899void
1900GetLockHoldersAndWaiters(LOCALLOCK *locallock, StringInfo lock_holders_sbuf,
1901 StringInfo lock_waiters_sbuf, int *lockHoldersNum)
1902{
1903 dlist_iter proc_iter;
1904 PROCLOCK *curproclock;
1905 LOCK *lock = locallock->lock;
1906 bool first_holder = true,
1907 first_waiter = true;
1908
1909#ifdef USE_ASSERT_CHECKING
1910 {
1911 uint32 hashcode = locallock->hashcode;
1912 LWLock *partitionLock = LockHashPartitionLock(hashcode);
1913
1914 Assert(LWLockHeldByMe(partitionLock));
1915 }
1916#endif
1917
1918 *lockHoldersNum = 0;
1919
1920 /*
1921 * Loop over the lock's procLocks to gather a list of all holders and
1922 * waiters. Thus we will be able to provide more detailed information for
1923 * lock debugging purposes.
1924 *
1925 * lock->procLocks contains all processes which hold or wait for this
1926 * lock.
1927 */
1928 dlist_foreach(proc_iter, &lock->procLocks)
1929 {
1930 curproclock =
1931 dlist_container(PROCLOCK, lockLink, proc_iter.cur);
1932
1933 /*
1934 * We are a waiter if myProc->waitProcLock == curproclock; we are a
1935 * holder if it is NULL or something different.
1936 */
1937 if (curproclock->tag.myProc->waitProcLock == curproclock)
1938 {
1939 if (first_waiter)
1940 {
1941 appendStringInfo(lock_waiters_sbuf, "%d",
1942 curproclock->tag.myProc->pid);
1943 first_waiter = false;
1944 }
1945 else
1946 appendStringInfo(lock_waiters_sbuf, ", %d",
1947 curproclock->tag.myProc->pid);
1948 }
1949 else
1950 {
1951 if (first_holder)
1952 {
1953 appendStringInfo(lock_holders_sbuf, "%d",
1954 curproclock->tag.myProc->pid);
1955 first_holder = false;
1956 }
1957 else
1958 appendStringInfo(lock_holders_sbuf, ", %d",
1959 curproclock->tag.myProc->pid);
1960
1961 (*lockHoldersNum)++;
1962 }
1963 }
1964}
1965
1966/*
1967 * ProcWaitForSignal - wait for a signal from another backend.
1968 *
1969 * As this uses the generic process latch the caller has to be robust against
1970 * unrelated wakeups: Always check that the desired state has occurred, and
1971 * wait again if not.
1972 */
1973void
1975{
1977 wait_event_info);
1980}
1981
1982/*
1983 * ProcSendSignal - set the latch of a backend identified by ProcNumber
1984 */
1985void
1987{
1988 if (procNumber < 0 || procNumber >= ProcGlobal->allProcCount)
1989 elog(ERROR, "procNumber out of range");
1990
1991 SetLatch(&ProcGlobal->allProcs[procNumber].procLatch);
1992}
1993
1994/*
1995 * BecomeLockGroupLeader - designate process as lock group leader
1996 *
1997 * Once this function has returned, other processes can join the lock group
1998 * by calling BecomeLockGroupMember.
1999 */
2000void
2002{
2003 LWLock *leader_lwlock;
2004
2005 /* If we already did it, we don't need to do it again. */
2007 return;
2008
2009 /* We had better not be a follower. */
2010 Assert(MyProc->lockGroupLeader == NULL);
2011
2012 /* Create single-member group, containing only ourselves. */
2013 leader_lwlock = LockHashPartitionLockByProc(MyProc);
2014 LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
2017 LWLockRelease(leader_lwlock);
2018}
2019
2020/*
2021 * BecomeLockGroupMember - designate process as lock group member
2022 *
2023 * This is pretty straightforward except for the possibility that the leader
2024 * whose group we're trying to join might exit before we manage to do so;
2025 * and the PGPROC might get recycled for an unrelated process. To avoid
2026 * that, we require the caller to pass the PID of the intended PGPROC as
2027 * an interlock. Returns true if we successfully join the intended lock
2028 * group, and false if not.
2029 */
2030bool
2032{
2033 LWLock *leader_lwlock;
2034 bool ok = false;
2035
2036 /* Group leader can't become member of group */
2037 Assert(MyProc != leader);
2038
2039 /* Can't already be a member of a group */
2040 Assert(MyProc->lockGroupLeader == NULL);
2041
2042 /* PID must be valid. */
2043 Assert(pid != 0);
2044
2045 /*
2046 * Get lock protecting the group fields. Note LockHashPartitionLockByProc
2047 * calculates the proc number based on the PGPROC slot without looking at
2048 * its contents, so we will acquire the correct lock even if the leader
2049 * PGPROC is in process of being recycled.
2050 */
2051 leader_lwlock = LockHashPartitionLockByProc(leader);
2052 LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
2053
2054 /* Is this the leader we're looking for? */
2055 if (leader->pid == pid && leader->lockGroupLeader == leader)
2056 {
2057 /* OK, join the group */
2058 ok = true;
2059 MyProc->lockGroupLeader = leader;
2061 }
2062 LWLockRelease(leader_lwlock);
2063
2064 return ok;
2065}
static void pg_atomic_write_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:485
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:221
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:239
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:453
int autovacuum_worker_slots
Definition: autovacuum.c:119
int AutovacuumLauncherPid
Definition: autovacuum.c:317
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1721
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1781
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1609
#define MAXALIGN(LEN)
Definition: c.h:782
uint8_t uint8
Definition: c.h:500
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:224
uint64_t uint64
Definition: c.h:503
uint32_t uint32
Definition: c.h:502
#define MemSet(start, val, len)
Definition: c.h:991
uint32 TransactionId
Definition: c.h:623
size_t Size
Definition: c.h:576
#define TRANSACTION_STATUS_IN_PROGRESS
Definition: clog.h:27
bool ConditionVariableCancelSleep(void)
int64 TimestampTz
Definition: timestamp.h:39
PGPROC * GetBlockingAutoVacuumPgproc(void)
Definition: deadlock.c:290
void RememberSimpleDeadLock(PGPROC *proc1, LOCKMODE lockmode, LOCK *lock, PGPROC *proc2)
Definition: deadlock.c:1147
void InitDeadLockChecking(void)
Definition: deadlock.c:144
DeadLockState DeadLockCheck(PGPROC *proc)
Definition: deadlock.c:220
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1158
bool message_level_is_interesting(int elevel)
Definition: elog.c:273
int errcode(int sqlerrcode)
Definition: elog.c:854
int errdetail_log_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1273
int errmsg(const char *fmt,...)
Definition: elog.c:1071
int errdetail_log(const char *fmt,...)
Definition: elog.c:1252
#define LOG
Definition: elog.h:31
#define FATAL
Definition: elog.h:41
#define WARNING
Definition: elog.h:36
#define PANIC
Definition: elog.h:42
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
int MyProcPid
Definition: globals.c:47
ProcNumber MyProcNumber
Definition: globals.c:90
bool IsUnderPostmaster
Definition: globals.c:120
int MaxConnections
Definition: globals.c:143
int MaxBackends
Definition: globals.c:146
struct Latch * MyLatch
Definition: globals.c:63
int max_worker_processes
Definition: globals.c:144
Assert(PointerIsAligned(start, uint64))
static dlist_node * dlist_pop_head_node(dlist_head *head)
Definition: ilist.h:450
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
static void dlist_init(dlist_head *head)
Definition: ilist.h:314
static void dclist_push_tail(dclist_head *head, dlist_node *node)
Definition: ilist.h:709
static void dlist_delete(dlist_node *node)
Definition: ilist.h:405
static bool dclist_is_empty(const dclist_head *head)
Definition: ilist.h:682
static bool dlist_node_is_detached(const dlist_node *node)
Definition: ilist.h:525
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:347
static bool dlist_is_empty(const dlist_head *head)
Definition: ilist.h:336
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition: ilist.h:364
static void dclist_delete_from_thoroughly(dclist_head *head, dlist_node *node)
Definition: ilist.h:776
static void dclist_insert_before(dclist_head *head, dlist_node *before, dlist_node *node)
Definition: ilist.h:745
#define dclist_foreach_modify(iter, lhead)
Definition: ilist.h:973
static void dlist_node_init(dlist_node *node)
Definition: ilist.h:325
#define dlist_container(type, membername, ptr)
Definition: ilist.h:593
#define dclist_foreach(iter, lhead)
Definition: ilist.h:970
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:365
int j
Definition: isn.c:78
int i
Definition: isn.c:77
void OwnLatch(Latch *latch)
Definition: latch.c:126
void DisownLatch(Latch *latch)
Definition: latch.c:144
void InitSharedLatch(Latch *latch)
Definition: latch.c:93
void SetLatch(Latch *latch)
Definition: latch.c:288
void ResetLatch(Latch *latch)
Definition: latch.c:372
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:172
void DescribeLockTag(StringInfo buf, const LOCKTAG *tag)
Definition: lmgr.c:1243
void GrantAwaitedLock(void)
Definition: lock.c:1888
void GrantLock(LOCK *lock, PROCLOCK *proclock, LOCKMODE lockmode)
Definition: lock.c:1657
VirtualTransactionId * GetLockConflicts(const LOCKTAG *locktag, LOCKMODE lockmode, int *countp)
Definition: lock.c:3037
void RemoveFromWaitQueue(PGPROC *proc, uint32 hashcode)
Definition: lock.c:2014
void LockReleaseAll(LOCKMETHODID lockmethodid, bool allLocks)
Definition: lock.c:2275
void ResetAwaitedLock(void)
Definition: lock.c:1906
void AbortStrongLockAcquire(void)
Definition: lock.c:1859
const char * GetLockmodeName(LOCKMETHODID lockmethodid, LOCKMODE mode)
Definition: lock.c:4223
LOCALLOCK * GetAwaitedLock(void)
Definition: lock.c:1897
int FastPathLockGroupsPerBackend
Definition: lock.c:202
uint32 LockTagHashCode(const LOCKTAG *locktag)
Definition: lock.c:556
bool LockCheckConflicts(LockMethod lockMethodTable, LOCKMODE lockmode, LOCK *lock, PROCLOCK *proclock)
Definition: lock.c:1528
#define DEFAULT_LOCKMETHOD
Definition: lock.h:126
#define LockHashPartitionLock(hashcode)
Definition: lock.h:527
#define USER_LOCKMETHOD
Definition: lock.h:127
#define InvalidLocalTransactionId
Definition: lock.h:66
DeadLockState
Definition: lock.h:510
@ DS_HARD_DEADLOCK
Definition: lock.h:514
@ DS_BLOCKED_BY_AUTOVACUUM
Definition: lock.h:515
@ DS_NO_DEADLOCK
Definition: lock.h:512
@ DS_NOT_YET_CHECKED
Definition: lock.h:511
@ DS_SOFT_DEADLOCK
Definition: lock.h:513
#define LOCKBIT_ON(lockmode)
Definition: lock.h:85
#define LockHashPartitionLockByProc(leader_pgproc)
Definition: lock.h:542
#define LockHashPartitionLockByIndex(i)
Definition: lock.h:530
int LOCKMODE
Definition: lockdefs.h:26
#define AccessExclusiveLock
Definition: lockdefs.h:43
int LOCKMASK
Definition: lockdefs.h:25
bool LWLockHeldByMe(LWLock *lock)
Definition: lwlock.c:1983
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1180
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:2027
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1900
void LWLockReleaseAll(void)
Definition: lwlock.c:1951
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:719
void InitLWLockAccess(void)
Definition: lwlock.c:569
@ LW_WS_NOT_WAITING
Definition: lwlock.h:30
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:97
@ LWTRANCHE_LOCK_FASTPATH
Definition: lwlock.h:194
@ LW_SHARED
Definition: lwlock.h:115
@ LW_EXCLUSIVE
Definition: lwlock.h:114
void pfree(void *pointer)
Definition: mcxt.c:1528
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:382
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:383
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define AmWalSenderProcess()
Definition: miscadmin.h:384
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define AmSpecialWorkerProcess()
Definition: miscadmin.h:395
#define AmRegularBackendProcess()
Definition: miscadmin.h:380
void SwitchToSharedLatch(void)
Definition: miscinit.c:215
void SwitchBackToLocalLatch(void)
Definition: miscinit.c:242
void * arg
static char * buf
Definition: pg_test_fsync.c:72
void RegisterPostmasterChildActive(void)
Definition: pmsignal.c:290
void PGSemaphoreReset(PGSemaphore sema)
Definition: posix_sema.c:294
PGSemaphore PGSemaphoreCreate(void)
Definition: posix_sema.c:261
uintptr_t Datum
Definition: postgres.h:69
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:217
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:207
#define NON_EXEC_STATIC
Definition: postgres.h:581
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30
#define NUM_AUXILIARY_PROCS
Definition: proc.h:455
#define FastPathLockSlotsPerBackend()
Definition: proc.h:93
#define PROC_VACUUM_FOR_WRAPAROUND
Definition: proc.h:60
#define GetNumberFromPGProc(proc)
Definition: proc.h:433
#define NUM_SPECIAL_WORKER_PROCS
Definition: proc.h:442
ProcWaitStatus
Definition: proc.h:132
@ PROC_WAIT_STATUS_OK
Definition: proc.h:133
@ PROC_WAIT_STATUS_WAITING
Definition: proc.h:134
@ PROC_WAIT_STATUS_ERROR
Definition: proc.h:135
#define PROC_IS_AUTOVACUUM
Definition: proc.h:57
void ProcArrayAdd(PGPROC *proc)
Definition: procarray.c:468
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:565
#define INVALID_PROC_NUMBER
Definition: procnumber.h:26
int ProcNumber
Definition: procnumber.h:24
@ PROCSIG_RECOVERY_CONFLICT_LOCK
Definition: procsignal.h:44
void set_spins_per_delay(int shared_spins_per_delay)
Definition: s_lock.c:207
int update_spins_per_delay(int shared_spins_per_delay)
Definition: s_lock.c:218
#define DEFAULT_SPINS_PER_DELAY
Definition: s_lock.h:720
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387
#define SpinLockInit(lock)
Definition: spin.h:57
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59
ProcWaitStatus JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
Definition: proc.c:1140
void ProcSendSignal(ProcNumber procNumber)
Definition: proc.c:1986
bool log_lock_waits
Definition: proc.c:63
int IdleSessionTimeout
Definition: proc.c:62
PGPROC * MyProc
Definition: proc.c:66
Size ProcGlobalShmemSize(void)
Definition: proc.c:139
void ProcWakeup(PGPROC *proc, ProcWaitStatus waitStatus)
Definition: proc.c:1711
int StatementTimeout
Definition: proc.c:58
bool HaveNFreeProcs(int n, int *nfree)
Definition: proc.c:782
static void RemoveProcFromArray(int code, Datum arg)
Definition: proc.c:908
void InitAuxiliaryProcess(void)
Definition: proc.c:615
PGPROC * PreparedXactProcs
Definition: proc.c:80
static DeadLockState deadlock_state
Definition: proc.c:82
int IdleInTransactionSessionTimeout
Definition: proc.c:60
void GetLockHoldersAndWaiters(LOCALLOCK *locallock, StringInfo lock_holders_sbuf, StringInfo lock_waiters_sbuf, int *lockHoldersNum)
Definition: proc.c:1900
NON_EXEC_STATIC PGPROC * AuxiliaryProcs
Definition: proc.c:79
int GetStartupBufferPinWaitBufId(void)
Definition: proc.c:766
ProcWaitStatus ProcSleep(LOCALLOCK *locallock)
Definition: proc.c:1309
int DeadlockTimeout
Definition: proc.c:57
static Size PGProcShmemSize(void)
Definition: proc.c:97
int TransactionTimeout
Definition: proc.c:61
void ProcLockWakeup(LockMethod lockMethodTable, LOCK *lock)
Definition: proc.c:1739
PROC_HDR * ProcGlobal
Definition: proc.c:78
static Size FastPathLockShmemSize(void)
Definition: proc.c:115
static void CheckDeadLock(void)
Definition: proc.c:1787
NON_EXEC_STATIC slock_t * ProcStructLock
Definition: proc.c:75
int ProcGlobalSemas(void)
Definition: proc.c:157
void ProcReleaseLocks(bool isCommit)
Definition: proc.c:891
void LockErrorCleanup(void)
Definition: proc.c:813
bool BecomeLockGroupMember(PGPROC *leader, int pid)
Definition: proc.c:2031
void BecomeLockGroupLeader(void)
Definition: proc.c:2001
static void ProcKill(int code, Datum arg)
Definition: proc.c:919
void InitProcess(void)
Definition: proc.c:390
void CheckDeadLockAlert(void)
Definition: proc.c:1873
void InitProcessPhase2(void)
Definition: proc.c:580
void InitProcGlobal(void)
Definition: proc.c:192
static volatile sig_atomic_t got_deadlock_timeout
Definition: proc.c:85
PGPROC * AuxiliaryPidGetProc(int pid)
Definition: proc.c:1091
void SetStartupBufferPinWaitBufId(int bufid)
Definition: proc.c:754
void ProcWaitForSignal(uint32 wait_event_info)
Definition: proc.c:1974
int LockTimeout
Definition: proc.c:59
static void AuxiliaryProcKill(int code, Datum arg)
Definition: proc.c:1040
void CheckRecoveryConflictDeadlock(void)
Definition: standby.c:905
bool log_recovery_conflict_waits
Definition: standby.c:42
void LogRecoveryConflict(ProcSignalReason reason, TimestampTz wait_start, TimestampTz now, VirtualTransactionId *wait_list, bool still_waiting)
Definition: standby.c:274
void ResolveRecoveryConflictWithLock(LOCKTAG locktag, bool logging_conflict)
Definition: standby.c:623
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
TimeoutId id
Definition: timeout.h:71
TimeoutType type
Definition: timeout.h:61
TimeoutId id
Definition: timeout.h:60
LOCKTAG lock
Definition: lock.h:411
LOCKMODE mode
Definition: lock.h:412
uint32 hashcode
Definition: lock.h:433
LOCK * lock
Definition: lock.h:434
PROCLOCK * proclock
Definition: lock.h:435
LOCALLOCKTAG tag
Definition: lock.h:430
Definition: lock.h:166
uint8 locktag_type
Definition: lock.h:171
uint8 locktag_lockmethodid
Definition: lock.h:172
Definition: lock.h:310
LOCKTAG tag
Definition: lock.h:312
dclist_head waitProcs
Definition: lock.h:318
LOCKMASK waitMask
Definition: lock.h:316
dlist_head procLocks
Definition: lock.h:317
Definition: lwlock.h:42
const LOCKMASK * conflictTab
Definition: lock.h:112
Definition: proc.h:171
LWLock fpInfoLock
Definition: proc.h:302
bool isRegularBackend
Definition: proc.h:222
TransactionId xmin
Definition: proc.h:186
struct PGPROC::@127 vxid
bool procArrayGroupMember
Definition: proc.h:278
LocalTransactionId lxid
Definition: proc.h:209
PROCLOCK * waitProcLock
Definition: proc.h:242
XLogRecPtr clogGroupMemberLsn
Definition: proc.h:298
pg_atomic_uint32 procArrayGroupNext
Definition: proc.h:280
uint8 lwWaitMode
Definition: proc.h:233
dlist_head lockGroupMembers
Definition: proc.h:314
uint32 wait_event_info
Definition: proc.h:288
dlist_head * procgloballist
Definition: proc.h:173
Oid * fpRelId
Definition: proc.h:304
uint8 statusFlags
Definition: proc.h:251
bool recoveryConflictPending
Definition: proc.h:229
TransactionId clogGroupMemberXid
Definition: proc.h:293
Oid databaseId
Definition: proc.h:216
int64 clogGroupMemberPage
Definition: proc.h:296
bool clogGroupMember
Definition: proc.h:291
uint64 * fpLockBits
Definition: proc.h:303
pg_atomic_uint64 waitStart
Definition: proc.h:246
bool fpVXIDLock
Definition: proc.h:305
ProcNumber procNumber
Definition: proc.h:204
int pid
Definition: proc.h:191
XLogRecPtr waitLSN
Definition: proc.h:261
dlist_node syncRepLinks
Definition: proc.h:263
int syncRepState
Definition: proc.h:262
pg_atomic_uint32 clogGroupNext
Definition: proc.h:292
dlist_node lockGroupLink
Definition: proc.h:315
XidStatus clogGroupMemberXidStatus
Definition: proc.h:294
int pgxactoff
Definition: proc.h:193
LOCK * waitLock
Definition: proc.h:241
TransactionId xid
Definition: proc.h:181
LOCKMODE waitLockMode
Definition: proc.h:243
int delayChkptFlags
Definition: proc.h:249
PGPROC * lockGroupLeader
Definition: proc.h:313
LocalTransactionId fpLocalTransactionId
Definition: proc.h:306
TransactionId procArrayGroupMemberXid
Definition: proc.h:286
LOCKMASK heldLocks
Definition: proc.h:244
PGSemaphore sem
Definition: proc.h:175
dlist_head myProcLocks[NUM_LOCK_PARTITIONS]
Definition: proc.h:270
Oid roleId
Definition: proc.h:217
ProcWaitStatus waitStatus
Definition: proc.h:176
Oid tempNamespaceId
Definition: proc.h:219
dlist_node links
Definition: proc.h:172
uint8 lwWaiting
Definition: proc.h:232
Latch procLatch
Definition: proc.h:178
PGPROC * myProc
Definition: lock.h:367
Definition: lock.h:371
LOCKMASK holdMask
Definition: lock.h:377
PGPROC * groupLeader
Definition: lock.h:376
PROCLOCKTAG tag
Definition: lock.h:373
Definition: proc.h:378
uint8 * statusFlags
Definition: proc.h:395
XidCacheStatus * subxidStates
Definition: proc.h:389
dlist_head autovacFreeProcs
Definition: proc.h:402
dlist_head freeProcs
Definition: proc.h:400
ProcNumber checkpointerProc
Definition: proc.h:417
int startupBufferPinWaitBufId
Definition: proc.h:422
PGPROC * allProcs
Definition: proc.h:380
pg_atomic_uint32 clogGroupFirst
Definition: proc.h:410
int spins_per_delay
Definition: proc.h:420
TransactionId * xids
Definition: proc.h:383
dlist_head walsenderFreeProcs
Definition: proc.h:406
dlist_head bgworkerFreeProcs
Definition: proc.h:404
ProcNumber walwriterProc
Definition: proc.h:416
pg_atomic_uint32 procArrayGroupFirst
Definition: proc.h:408
uint32 allProcCount
Definition: proc.h:398
dlist_node * cur
Definition: ilist.h:179
dlist_node * cur
Definition: ilist.h:200
dlist_node * next
Definition: ilist.h:140
dlist_node * prev
Definition: ilist.h:139
Definition: type.h:96
void SyncRepCleanupAtProcExit(void)
Definition: syncrep.c:416
#define SYNC_REP_NOT_WAITING
Definition: syncrep.h:30
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
TimestampTz get_timeout_start_time(TimeoutId id)
Definition: timeout.c:813
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685
void enable_timeouts(const EnableTimeoutParams *timeouts, int count)
Definition: timeout.c:630
void disable_timeouts(const DisableTimeoutParams *timeouts, int count)
Definition: timeout.c:718
@ LOCK_TIMEOUT
Definition: timeout.h:28
@ DEADLOCK_TIMEOUT
Definition: timeout.h:27
@ TMPARAM_AFTER
Definition: timeout.h:53
#define InvalidTransactionId
Definition: transam.h:31
int max_prepared_xacts
Definition: twophase.c:115
#define PG_WAIT_LOCK
Definition: wait_classes.h:19
void pgstat_set_wait_event_storage(uint32 *wait_event_info)
Definition: wait_event.c:349
void pgstat_reset_wait_event_storage(void)
Definition: wait_event.c:361
#define WL_EXIT_ON_PM_DEATH
Definition: waiteventset.h:39
#define WL_LATCH_SET
Definition: waiteventset.h:34
int max_wal_senders
Definition: walsender.c:126
#define kill(pid, sig)
Definition: win32_port.h:493
#define SIGUSR2
Definition: win32_port.h:171
bool RecoveryInProgress(void)
Definition: xlog.c:6522
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
bool InRecovery
Definition: xlogutils.c:50
#define InHotStandby
Definition: xlogutils.h:60
static struct link * links
Definition: zic.c:299