Debian Codegraph @

src/backend/storage/lmgr/proc.c

raw
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"
41 #include "postmaster/autovacuum.h"
42 #include "replication/slotsync.h"
43 #include "replication/syncrep.h"
44 #include "storage/condition_variable.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 */
57 int DeadlockTimeout = 1000;
58 int StatementTimeout = 0;
59 int LockTimeout = 0;
60 int IdleInTransactionSessionTimeout = 0;
61 int TransactionTimeout = 0;
62 int IdleSessionTimeout = 0;
63 bool log_lock_waits = false;
64
65 /* Pointer to this process's PGPROC struct, if any */
66 PGPROC *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 */
75 NON_EXEC_STATIC slock_t *ProcStructLock = NULL;
76
77 /* Pointers to shared-memory structures */
78 PROC_HDR *ProcGlobal = NULL;
79 NON_EXEC_STATIC PGPROC *AuxiliaryProcs = NULL;
80 PGPROC *PreparedXactProcs = NULL;
81
82 static DeadLockState deadlock_state = DS_NOT_YET_CHECKED;
83
84 /* Is a deadlock check pending? */
85 static volatile sig_atomic_t got_deadlock_timeout;
86
87 static void RemoveProcFromArray(int code, Datum arg);
88 static void ProcKill(int code, Datum arg);
89 static void AuxiliaryProcKill(int code, Datum arg);
90 static void CheckDeadLock(void);
91
92
93 /*
94 * Report shared-memory space needed by PGPROC.
95 */
96 static Size
97 PGProcShmemSize(void)
98 {
99 Size size = 0;
100 Size TotalProcs =
101 add_size(MaxBackends, add_size(NUM_AUXILIARY_PROCS, max_prepared_xacts));
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 */
114 static Size
115 FastPathLockShmemSize(void)
116 {
117 Size size = 0;
118 Size TotalProcs =
119 add_size(MaxBackends, add_size(NUM_AUXILIARY_PROCS, max_prepared_xacts));
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 */
138 Size
139 ProcGlobalShmemSize(void)
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 */
156 int
157 ProcGlobalSemas(void)
158 {
159 /*
160 * We need a sema per backend (including autovacuum), plus one for each
161 * auxiliary process.
162 */
163 return MaxBackends + NUM_AUXILIARY_PROCS;
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 */
191 void
192 InitProcGlobal(void)
193 {
194 PGPROC *procs;
195 int i,
196 j;
197 bool found;
198 uint32 TotalProcs = MaxBackends + NUM_AUXILIARY_PROCS + max_prepared_xacts;
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 */
216 ProcGlobal->spins_per_delay = DEFAULT_SPINS_PER_DELAY;
217 dlist_init(&ProcGlobal->freeProcs);
218 dlist_init(&ProcGlobal->autovacFreeProcs);
219 dlist_init(&ProcGlobal->bgworkerFreeProcs);
220 dlist_init(&ProcGlobal->walsenderFreeProcs);
221 ProcGlobal->startupBufferPinWaitBufId = -1;
222 ProcGlobal->walwriterProc = INVALID_PROC_NUMBER;
223 ProcGlobal->checkpointerProc = INVALID_PROC_NUMBER;
224 pg_atomic_init_u32(&ProcGlobal->procArrayGroupFirst, INVALID_PROC_NUMBER);
225 pg_atomic_init_u32(&ProcGlobal->clogGroupFirst, INVALID_PROC_NUMBER);
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 */
249 ProcGlobal->allProcCount = MaxBackends + NUM_AUXILIARY_PROCS;
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
261 ProcGlobal->subxidStates = (XidCacheStatus *) ptr;
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 */
312 if (i < FIRST_PREPARED_XACT_PROC_NUMBER)
313 {
314 proc->sem = PGSemaphoreCreate();
315 InitSharedLatch(&(proc->procLatch));
316 LWLockInitialize(&(proc->fpInfoLock), LWTRANCHE_LOCK_FASTPATH);
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 */
331 dlist_push_tail(&ProcGlobal->freeProcs, &proc->links);
332 proc->procgloballist = &ProcGlobal->freeProcs;
333 }
334 else if (i < MaxConnections + autovacuum_worker_slots + NUM_SPECIAL_WORKER_PROCS)
335 {
336 /* PGPROC for AV or special worker, add to autovacFreeProcs list */
337 dlist_push_tail(&ProcGlobal->autovacFreeProcs, &proc->links);
338 proc->procgloballist = &ProcGlobal->autovacFreeProcs;
339 }
340 else if (i < MaxConnections + autovacuum_worker_slots + NUM_SPECIAL_WORKER_PROCS + max_worker_processes)
341 {
342 /* PGPROC for bgworker, add to bgworkerFreeProcs list */
343 dlist_push_tail(&ProcGlobal->bgworkerFreeProcs, &proc->links);
344 proc->procgloballist = &ProcGlobal->bgworkerFreeProcs;
345 }
346 else if (i < MaxBackends)
347 {
348 /* PGPROC for walsender, add to walsenderFreeProcs list */
349 dlist_push_tail(&ProcGlobal->walsenderFreeProcs, &proc->links);
350 proc->procgloballist = &ProcGlobal->walsenderFreeProcs;
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. */
358 dlist_init(&proc->lockGroupMembers);
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 */
364 pg_atomic_init_u32(&(proc->procArrayGroupNext), INVALID_PROC_NUMBER);
365 pg_atomic_init_u32(&(proc->clogGroupNext), INVALID_PROC_NUMBER);
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];
377 PreparedXactProcs = &procs[FIRST_PREPARED_XACT_PROC_NUMBER];
378
379 /* Create ProcStructLock spinlock, too */
380 ProcStructLock = (slock_t *) ShmemInitStruct("ProcStructLock spinlock",
381 sizeof(slock_t),
382 &found);
383 SpinLockInit(ProcStructLock);
384 }
385
386 /*
387 * InitProcess -- initialize a per-process PGPROC entry for this backend
388 */
389 void
390 InitProcess(void)
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 */
409 if (IsUnderPostmaster)
410 RegisterPostmasterChildActive();
411
412 /*
413 * Decide which list should supply our PGPROC. This logic must match the
414 * way the freelists were constructed in InitProcGlobal().
415 */
416 if (AmAutoVacuumWorkerProcess() || AmSpecialWorkerProcess())
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 */
432 SpinLockAcquire(ProcStructLock);
433
434 set_spins_per_delay(ProcGlobal->spins_per_delay);
435
436 if (!dlist_is_empty(procgloballist))
437 {
438 MyProc = dlist_container(PGPROC, links, dlist_pop_head_node(procgloballist));
439 SpinLockRelease(ProcStructLock);
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 */
449 SpinLockRelease(ProcStructLock);
450 if (AmWalSenderProcess())
451 ereport(FATAL,
452 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
453 errmsg("number of requested standby connections exceeds \"max_wal_senders\" (currently %d)",
454 max_wal_senders)));
455 ereport(FATAL,
456 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
457 errmsg("sorry, too many clients already")));
458 }
459 MyProcNumber = GetNumberFromPGProc(MyProc);
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 */
471 dlist_node_init(&MyProc->links);
472 MyProc->waitStatus = PROC_WAIT_STATUS_OK;
473 MyProc->fpVXIDLock = false;
474 MyProc->fpLocalTransactionId = InvalidLocalTransactionId;
475 MyProc->xid = InvalidTransactionId;
476 MyProc->xmin = InvalidTransactionId;
477 MyProc->pid = MyProcPid;
478 MyProc->vxid.procNumber = MyProcNumber;
479 MyProc->vxid.lxid = InvalidLocalTransactionId;
480 /* databaseId and roleId will be filled in later */
481 MyProc->databaseId = InvalidOid;
482 MyProc->roleId = InvalidOid;
483 MyProc->tempNamespaceId = InvalidOid;
484 MyProc->isRegularBackend = AmRegularBackendProcess();
485 MyProc->delayChkptFlags = 0;
486 MyProc->statusFlags = 0;
487 /* NB -- autovac launcher intentionally does not set IS_AUTOVACUUM */
488 if (AmAutoVacuumWorkerProcess())
489 MyProc->statusFlags |= PROC_IS_AUTOVACUUM;
490 MyProc->lwWaiting = LW_WS_NOT_WAITING;
491 MyProc->lwWaitMode = 0;
492 MyProc->waitLock = NULL;
493 MyProc->waitProcLock = NULL;
494 pg_atomic_write_u64(&MyProc->waitStart, 0);
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++)
501 Assert(dlist_is_empty(&(MyProc->myProcLocks[i])));
502 }
503 #endif
504 MyProc->recoveryConflictPending = false;
505
506 /* Initialize fields for sync rep */
507 MyProc->waitLSN = 0;
508 MyProc->syncRepState = SYNC_REP_NOT_WAITING;
509 dlist_node_init(&MyProc->syncRepLinks);
510
511 /* Initialize fields for group XID clearing. */
512 MyProc->procArrayGroupMember = false;
513 MyProc->procArrayGroupMemberXid = InvalidTransactionId;
514 Assert(pg_atomic_read_u32(&MyProc->procArrayGroupNext) == INVALID_PROC_NUMBER);
515
516 /* Check that group locking fields are in a proper initial state. */
517 Assert(MyProc->lockGroupLeader == NULL);
518 Assert(dlist_is_empty(&MyProc->lockGroupMembers));
519
520 /* Initialize wait event information. */
521 MyProc->wait_event_info = 0;
522
523 /* Initialize fields for group transaction status update. */
524 MyProc->clogGroupMember = false;
525 MyProc->clogGroupMemberXid = InvalidTransactionId;
526 MyProc->clogGroupMemberXidStatus = TRANSACTION_STATUS_IN_PROGRESS;
527 MyProc->clogGroupMemberPage = -1;
528 MyProc->clogGroupMemberLsn = InvalidXLogRecPtr;
529 Assert(pg_atomic_read_u32(&MyProc->clogGroupNext) == INVALID_PROC_NUMBER);
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 */
536 OwnLatch(&MyProc->procLatch);
537 SwitchToSharedLatch();
538
539 /* now that we have a proc, report wait events to shared memory */
540 pgstat_set_wait_event_storage(&MyProc->wait_event_info);
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 */
547 PGSemaphoreReset(MyProc->sem);
548
549 /*
550 * Arrange to clean up at backend exit.
551 */
552 on_shmem_exit(ProcKill, 0);
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 */
558 InitLWLockAccess();
559 InitDeadLockChecking();
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 */
567 if (IsUnderPostmaster)
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 */
579 void
580 InitProcessPhase2(void)
581 {
582 Assert(MyProc != NULL);
583
584 /*
585 * Add our PGPROC to the PGPROC array in shared memory.
586 */
587 ProcArrayAdd(MyProc);
588
589 /*
590 * Arrange to clean that up at backend exit.
591 */
592 on_shmem_exit(RemoveProcFromArray, 0);
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 */
614 void
615 InitAuxiliaryProcess(void)
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
630 if (IsUnderPostmaster)
631 RegisterPostmasterChildActive();
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 */
640 SpinLockAcquire(ProcStructLock);
641
642 set_spins_per_delay(ProcGlobal->spins_per_delay);
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 {
655 SpinLockRelease(ProcStructLock);
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
663 SpinLockRelease(ProcStructLock);
664
665 MyProc = auxproc;
666 MyProcNumber = GetNumberFromPGProc(MyProc);
667
668 /*
669 * Initialize all fields of MyProc, except for those previously
670 * initialized by InitProcGlobal.
671 */
672 dlist_node_init(&MyProc->links);
673 MyProc->waitStatus = PROC_WAIT_STATUS_OK;
674 MyProc->fpVXIDLock = false;
675 MyProc->fpLocalTransactionId = InvalidLocalTransactionId;
676 MyProc->xid = InvalidTransactionId;
677 MyProc->xmin = InvalidTransactionId;
678 MyProc->vxid.procNumber = INVALID_PROC_NUMBER;
679 MyProc->vxid.lxid = InvalidLocalTransactionId;
680 MyProc->databaseId = InvalidOid;
681 MyProc->roleId = InvalidOid;
682 MyProc->tempNamespaceId = InvalidOid;
683 MyProc->isRegularBackend = false;
684 MyProc->delayChkptFlags = 0;
685 MyProc->statusFlags = 0;
686 MyProc->lwWaiting = LW_WS_NOT_WAITING;
687 MyProc->lwWaitMode = 0;
688 MyProc->waitLock = NULL;
689 MyProc->waitProcLock = NULL;
690 pg_atomic_write_u64(&MyProc->waitStart, 0);
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++)
697 Assert(dlist_is_empty(&(MyProc->myProcLocks[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 */
706 OwnLatch(&MyProc->procLatch);
707 SwitchToSharedLatch();
708
709 /* now that we have a proc, report wait events to shared memory */
710 pgstat_set_wait_event_storage(&MyProc->wait_event_info);
711
712 /* Check that group locking fields are in a proper initial state. */
713 Assert(MyProc->lockGroupLeader == NULL);
714 Assert(dlist_is_empty(&MyProc->lockGroupMembers));
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 */
721 PGSemaphoreReset(MyProc->sem);
722
723 /*
724 * Arrange to clean up at process exit.
725 */
726 on_shmem_exit(AuxiliaryProcKill, Int32GetDatum(proctype));
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 */
733 InitLWLockAccess();
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 */
741 if (IsUnderPostmaster)
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 */
753 void
754 SetStartupBufferPinWaitBufId(int bufid)
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 */
765 int
766 GetStartupBufferPinWaitBufId(void)
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 */
781 bool
782 HaveNFreeProcs(int n, int *nfree)
783 {
784 dlist_iter iter;
785
786 Assert(n > 0);
787 Assert(nfree);
788
789 SpinLockAcquire(ProcStructLock);
790
791 *nfree = 0;
792 dlist_foreach(iter, &ProcGlobal->freeProcs)
793 {
794 (*nfree)++;
795 if (*nfree == n)
796 break;
797 }
798
799 SpinLockRelease(ProcStructLock);
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 */
812 void
813 LockErrorCleanup(void)
814 {
815 LOCALLOCK *lockAwaited;
816 LWLock *partitionLock;
817 DisableTimeoutParams timeouts[2];
818
819 HOLD_INTERRUPTS();
820
821 AbortStrongLockAcquire();
822
823 /* Nothing to do if we weren't waiting for a lock */
824 lockAwaited = GetAwaitedLock();
825 if (lockAwaited == NULL)
826 {
827 RESUME_INTERRUPTS();
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
849 if (!dlist_node_is_detached(&MyProc->links))
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 */
862 if (MyProc->waitStatus == PROC_WAIT_STATUS_OK)
863 GrantAwaitedLock();
864 }
865
866 ResetAwaitedLock();
867
868 LWLockRelease(partitionLock);
869
870 RESUME_INTERRUPTS();
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 */
890 void
891 ProcReleaseLocks(bool isCommit)
892 {
893 if (!MyProc)
894 return;
895 /* If waiting, get off wait queue (should only be needed after error) */
896 LockErrorCleanup();
897 /* Release standard locks, including session-level if aborting */
898 LockReleaseAll(DEFAULT_LOCKMETHOD, !isCommit);
899 /* Release transaction-level advisory locks */
900 LockReleaseAll(USER_LOCKMETHOD, false);
901 }
902
903
904 /*
905 * RemoveProcFromArray() -- Remove this process from the shared ProcArray.
906 */
907 static void
908 RemoveProcFromArray(int code, Datum arg)
909 {
910 Assert(MyProc != NULL);
911 ProcArrayRemove(MyProc, InvalidTransactionId);
912 }
913
914 /*
915 * ProcKill() -- Destroy the per-proc data structure for
916 * this process. Release any of its held LW locks.
917 */
918 static void
919 ProcKill(int code, Datum arg)
920 {
921 PGPROC *proc;
922 PGPROC *leader;
923 dlist_head *procgloballist;
924 bool push_leader;
925 bool push_self;
926
927 Assert(MyProc != NULL);
928
929 /* not safe if forked by system(), etc. */
930 if (MyProc->pid != (int) getpid())
931 elog(PANIC, "ProcKill() called in child process");
932
933 /* Make sure we're out of the sync rep lists */
934 SyncRepCleanupAtProcExit();
935
936 #ifdef USE_ASSERT_CHECKING
937 {
938 int i;
939
940 /* Last process should have released all locks. */
941 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
942 Assert(dlist_is_empty(&(MyProc->myProcLocks[i])));
943 }
944 #endif
945
946 /*
947 * Release any LW locks I am holding. There really shouldn't be any, but
948 * it's cheap to check again before we cut the knees off the LWLock
949 * facility by releasing our PGPROC ...
950 */
951 LWLockReleaseAll();
952
953 /* Cancel any pending condition variable sleep, too */
954 ConditionVariableCancelSleep();
955
956 /*
957 * Reset MyLatch to the process local one and disown the shared latch, so
958 * that signal handlers et al can continue using the latch after the
959 * shared latch isn't ours anymore.
960 *
961 * DisownLatch() must happen before our PGPROC can appear on a freelist: a
962 * newly-forked backend that pops our slot and calls OwnLatch() would
963 * PANIC on a still-owned latch.
964 *
965 * pgstat_reset_wait_event_storage() is intentionally deferred until after
966 * the lock-group block so that wait_event_info remains visible in our
967 * PGPROC slot while we may be observed there. It is safe to defer
968 * because our slot is not yet on any freelist at this point, and useful
969 * for testing purposes.
970 */
971 SwitchBackToLocalLatch();
972 DisownLatch(&MyProc->procLatch);
973
974 proc = MyProc;
975 procgloballist = proc->procgloballist;
976
977 /*
978 * Detach from any lock group of which we are a member, deciding under
979 * leader_lwlock whether we (via push_self) and/or the leader (via
980 * push_leader) need to be pushed onto a freelist. The actual pushes
981 * happen after evaluating if any of these are required, under a single
982 * ProcGlobal->freeProcsLock.
983 *
984 * The decision whether any of the freelists needs to be updated is taken
985 * under a single leader_lwlock.
986 */
987 push_leader = false;
988 push_self = true;
989 leader = NULL;
990
991 if (proc->lockGroupLeader != NULL)
992 {
993 LWLock *leader_lwlock;
994
995 leader = proc->lockGroupLeader;
996 leader_lwlock = LockHashPartitionLockByProc(leader);
997
998 LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
999 Assert(!dlist_is_empty(&leader->lockGroupMembers));
1000 dlist_delete(&proc->lockGroupLink);
1001 if (dlist_is_empty(&leader->lockGroupMembers))
1002 {
1003 leader->lockGroupLeader = NULL;
1004 if (leader != proc)
1005 {
1006 /*
1007 * We are the last follower and the leader exited earlier; its
1008 * PGPROC is still allocated and must be pushed here.
1009 */
1010 push_leader = true;
1011 proc->lockGroupLeader = NULL;
1012 }
1013 }
1014 else if (leader != proc)
1015 {
1016 /* Non-last follower; leader still present in the group. */
1017 proc->lockGroupLeader = NULL;
1018 }
1019 else
1020 {
1021 /*
1022 * We are the leader and followers remain. Skip our own push; the
1023 * last follower to exit will push us back to the freelist.
1024 */
1025 push_self = false;
1026 }
1027 LWLockRelease(leader_lwlock);
1028 }
1029
1030 /* See comment above, close to DisownLatch() */
1031 pgstat_reset_wait_event_storage();
1032
1033 MyProc = NULL;
1034 MyProcNumber = INVALID_PROC_NUMBER;
1035
1036 /* Mark the proc no longer in use */
1037 proc->pid = 0;
1038 proc->vxid.procNumber = INVALID_PROC_NUMBER;
1039 proc->vxid.lxid = InvalidTransactionId;
1040
1041 SpinLockAcquire(ProcStructLock);
1042 if (push_leader)
1043 {
1044 /* Return leader PGPROC (and semaphore) to appropriate freelist */
1045 dlist_push_head(leader->procgloballist, &leader->links);
1046 }
1047 if (push_self)
1048 {
1049 Assert(proc->lockGroupLeader == NULL);
1050 /* Since lockGroupLeader is NULL, lockGroupMembers should be empty. */
1051 Assert(dlist_is_empty(&proc->lockGroupMembers));
1052
1053 /* Return PGPROC structure (and semaphore) to appropriate freelist */
1054 dlist_push_tail(procgloballist, &proc->links);
1055 }
1056
1057 /* Update shared estimate of spins_per_delay */
1058 ProcGlobal->spins_per_delay = update_spins_per_delay(ProcGlobal->spins_per_delay);
1059
1060 SpinLockRelease(ProcStructLock);
1061
1062 /* wake autovac launcher if needed -- see comments in FreeWorkerInfo */
1063 if (AutovacuumLauncherPid != 0)
1064 kill(AutovacuumLauncherPid, SIGUSR2);
1065 }
1066
1067 /*
1068 * AuxiliaryProcKill() -- Cut-down version of ProcKill for auxiliary
1069 * processes (bgwriter, etc). The PGPROC and sema are not released, only
1070 * marked as not-in-use.
1071 */
1072 static void
1073 AuxiliaryProcKill(int code, Datum arg)
1074 {
1075 int proctype = DatumGetInt32(arg);
1076 PGPROC *auxproc PG_USED_FOR_ASSERTS_ONLY;
1077 PGPROC *proc;
1078
1079 Assert(proctype >= 0 && proctype < NUM_AUXILIARY_PROCS);
1080
1081 /* not safe if forked by system(), etc. */
1082 if (MyProc->pid != (int) getpid())
1083 elog(PANIC, "AuxiliaryProcKill() called in child process");
1084
1085 auxproc = &AuxiliaryProcs[proctype];
1086
1087 Assert(MyProc == auxproc);
1088
1089 /* Release any LW locks I am holding (see notes above) */
1090 LWLockReleaseAll();
1091
1092 /* Cancel any pending condition variable sleep, too */
1093 ConditionVariableCancelSleep();
1094
1095 /* look at the equivalent ProcKill() code for comments */
1096 SwitchBackToLocalLatch();
1097 pgstat_reset_wait_event_storage();
1098
1099 proc = MyProc;
1100 MyProc = NULL;
1101 MyProcNumber = INVALID_PROC_NUMBER;
1102 DisownLatch(&proc->procLatch);
1103
1104 SpinLockAcquire(ProcStructLock);
1105
1106 /* Mark auxiliary proc no longer in use */
1107 proc->pid = 0;
1108 proc->vxid.procNumber = INVALID_PROC_NUMBER;
1109 proc->vxid.lxid = InvalidTransactionId;
1110
1111 /* Update shared estimate of spins_per_delay */
1112 ProcGlobal->spins_per_delay = update_spins_per_delay(ProcGlobal->spins_per_delay);
1113
1114 SpinLockRelease(ProcStructLock);
1115 }
1116
1117 /*
1118 * AuxiliaryPidGetProc -- get PGPROC for an auxiliary process
1119 * given its PID
1120 *
1121 * Returns NULL if not found.
1122 */
1123 PGPROC *
1124 AuxiliaryPidGetProc(int pid)
1125 {
1126 PGPROC *result = NULL;
1127 int index;
1128
1129 if (pid == 0) /* never match dummy PGPROCs */
1130 return NULL;
1131
1132 for (index = 0; index < NUM_AUXILIARY_PROCS; index++)
1133 {
1134 PGPROC *proc = &AuxiliaryProcs[index];
1135
1136 if (proc->pid == pid)
1137 {
1138 result = proc;
1139 break;
1140 }
1141 }
1142 return result;
1143 }
1144
1145
1146 /*
1147 * JoinWaitQueue -- join the wait queue on the specified lock
1148 *
1149 * It's not actually guaranteed that we need to wait when this function is
1150 * called, because it could be that when we try to find a position at which
1151 * to insert ourself into the wait queue, we discover that we must be inserted
1152 * ahead of everyone who wants a lock that conflict with ours. In that case,
1153 * we get the lock immediately. Because of this, it's sensible for this function
1154 * to have a dontWait argument, despite the name.
1155 *
1156 * On entry, the caller has already set up LOCK and PROCLOCK entries to
1157 * reflect that we have "requested" the lock. The caller is responsible for
1158 * cleaning that up, if we end up not joining the queue after all.
1159 *
1160 * The lock table's partition lock must be held at entry, and is still held
1161 * at exit. The caller must release it before calling ProcSleep().
1162 *
1163 * Result is one of the following:
1164 *
1165 * PROC_WAIT_STATUS_OK - lock was immediately granted
1166 * PROC_WAIT_STATUS_WAITING - joined the wait queue; call ProcSleep()
1167 * PROC_WAIT_STATUS_ERROR - immediate deadlock was detected, or would
1168 * need to wait and dontWait == true
1169 *
1170 * NOTES: The process queue is now a priority queue for locking.
1171 */
1172 ProcWaitStatus
1173 JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
1174 {
1175 LOCKMODE lockmode = locallock->tag.mode;
1176 LOCK *lock = locallock->lock;
1177 PROCLOCK *proclock = locallock->proclock;
1178 uint32 hashcode = locallock->hashcode;
1179 LWLock *partitionLock PG_USED_FOR_ASSERTS_ONLY = LockHashPartitionLock(hashcode);
1180 dclist_head *waitQueue = &lock->waitProcs;
1181 PGPROC *insert_before = NULL;
1182 LOCKMASK myProcHeldLocks;
1183 LOCKMASK myHeldLocks;
1184 bool early_deadlock = false;
1185 PGPROC *leader = MyProc->lockGroupLeader;
1186
1187 Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
1188
1189 /*
1190 * Set bitmask of locks this process already holds on this object.
1191 */
1192 myHeldLocks = MyProc->heldLocks = proclock->holdMask;
1193
1194 /*
1195 * Determine which locks we're already holding.
1196 *
1197 * If group locking is in use, locks held by members of my locking group
1198 * need to be included in myHeldLocks. This is not required for relation
1199 * extension lock which conflict among group members. However, including
1200 * them in myHeldLocks will give group members the priority to get those
1201 * locks as compared to other backends which are also trying to acquire
1202 * those locks. OTOH, we can avoid giving priority to group members for
1203 * that kind of locks, but there doesn't appear to be a clear advantage of
1204 * the same.
1205 */
1206 myProcHeldLocks = proclock->holdMask;
1207 myHeldLocks = myProcHeldLocks;
1208 if (leader != NULL)
1209 {
1210 dlist_iter iter;
1211
1212 dlist_foreach(iter, &lock->procLocks)
1213 {
1214 PROCLOCK *otherproclock;
1215
1216 otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
1217
1218 if (otherproclock->groupLeader == leader)
1219 myHeldLocks |= otherproclock->holdMask;
1220 }
1221 }
1222
1223 /*
1224 * Determine where to add myself in the wait queue.
1225 *
1226 * Normally I should go at the end of the queue. However, if I already
1227 * hold locks that conflict with the request of any previous waiter, put
1228 * myself in the queue just in front of the first such waiter. This is not
1229 * a necessary step, since deadlock detection would move me to before that
1230 * waiter anyway; but it's relatively cheap to detect such a conflict
1231 * immediately, and avoid delaying till deadlock timeout.
1232 *
1233 * Special case: if I find I should go in front of some waiter, check to
1234 * see if I conflict with already-held locks or the requests before that
1235 * waiter. If not, then just grant myself the requested lock immediately.
1236 * This is the same as the test for immediate grant in LockAcquire, except
1237 * we are only considering the part of the wait queue before my insertion
1238 * point.
1239 */
1240 if (myHeldLocks != 0 && !dclist_is_empty(waitQueue))
1241 {
1242 LOCKMASK aheadRequests = 0;
1243 dlist_iter iter;
1244
1245 dclist_foreach(iter, waitQueue)
1246 {
1247 PGPROC *proc = dlist_container(PGPROC, links, iter.cur);
1248
1249 /*
1250 * If we're part of the same locking group as this waiter, its
1251 * locks neither conflict with ours nor contribute to
1252 * aheadRequests.
1253 */
1254 if (leader != NULL && leader == proc->lockGroupLeader)
1255 continue;
1256
1257 /* Must he wait for me? */
1258 if (lockMethodTable->conflictTab[proc->waitLockMode] & myHeldLocks)
1259 {
1260 /* Must I wait for him ? */
1261 if (lockMethodTable->conflictTab[lockmode] & proc->heldLocks)
1262 {
1263 /*
1264 * Yes, so we have a deadlock. Easiest way to clean up
1265 * correctly is to call RemoveFromWaitQueue(), but we
1266 * can't do that until we are *on* the wait queue. So, set
1267 * a flag to check below, and break out of loop. Also,
1268 * record deadlock info for later message.
1269 */
1270 RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
1271 early_deadlock = true;
1272 break;
1273 }
1274 /* I must go before this waiter. Check special case. */
1275 if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
1276 !LockCheckConflicts(lockMethodTable, lockmode, lock,
1277 proclock))
1278 {
1279 /* Skip the wait and just grant myself the lock. */
1280 GrantLock(lock, proclock, lockmode);
1281 return PROC_WAIT_STATUS_OK;
1282 }
1283
1284 /* Put myself into wait queue before conflicting process */
1285 insert_before = proc;
1286 break;
1287 }
1288 /* Nope, so advance to next waiter */
1289 aheadRequests |= LOCKBIT_ON(proc->waitLockMode);
1290 }
1291 }
1292
1293 /*
1294 * If we detected deadlock, give up without waiting. This must agree with
1295 * CheckDeadLock's recovery code.
1296 */
1297 if (early_deadlock)
1298 return PROC_WAIT_STATUS_ERROR;
1299
1300 /*
1301 * At this point we know that we'd really need to sleep. If we've been
1302 * commanded not to do that, bail out.
1303 */
1304 if (dontWait)
1305 return PROC_WAIT_STATUS_ERROR;
1306
1307 /*
1308 * Insert self into queue, at the position determined above.
1309 */
1310 if (insert_before)
1311 dclist_insert_before(waitQueue, &insert_before->links, &MyProc->links);
1312 else
1313 dclist_push_tail(waitQueue, &MyProc->links);
1314
1315 lock->waitMask |= LOCKBIT_ON(lockmode);
1316
1317 /* Set up wait information in PGPROC object, too */
1318 MyProc->heldLocks = myProcHeldLocks;
1319 MyProc->waitLock = lock;
1320 MyProc->waitProcLock = proclock;
1321 MyProc->waitLockMode = lockmode;
1322
1323 MyProc->waitStatus = PROC_WAIT_STATUS_WAITING;
1324
1325 return PROC_WAIT_STATUS_WAITING;
1326 }
1327
1328 /*
1329 * ProcSleep -- put process to sleep waiting on lock
1330 *
1331 * This must be called when JoinWaitQueue() returns PROC_WAIT_STATUS_WAITING.
1332 * Returns after the lock has been granted, or if a deadlock is detected. Can
1333 * also bail out with ereport(ERROR), if some other error condition, or a
1334 * timeout or cancellation is triggered.
1335 *
1336 * Result is one of the following:
1337 *
1338 * PROC_WAIT_STATUS_OK - lock was granted
1339 * PROC_WAIT_STATUS_ERROR - a deadlock was detected
1340 */
1341 ProcWaitStatus
1342 ProcSleep(LOCALLOCK *locallock)
1343 {
1344 LOCKMODE lockmode = locallock->tag.mode;
1345 LOCK *lock = locallock->lock;
1346 uint32 hashcode = locallock->hashcode;
1347 LWLock *partitionLock = LockHashPartitionLock(hashcode);
1348 TimestampTz standbyWaitStart = 0;
1349 bool allow_autovacuum_cancel = true;
1350 bool logged_recovery_conflict = false;
1351 ProcWaitStatus myWaitStatus;
1352
1353 /* The caller must've armed the on-error cleanup mechanism */
1354 Assert(GetAwaitedLock() == locallock);
1355 Assert(!LWLockHeldByMe(partitionLock));
1356
1357 /*
1358 * Now that we will successfully clean up after an ereport, it's safe to
1359 * check to see if there's a buffer pin deadlock against the Startup
1360 * process. Of course, that's only necessary if we're doing Hot Standby
1361 * and are not the Startup process ourselves.
1362 */
1363 if (RecoveryInProgress() && !InRecovery)
1364 CheckRecoveryConflictDeadlock();
1365
1366 /* Reset deadlock_state before enabling the timeout handler */
1367 deadlock_state = DS_NOT_YET_CHECKED;
1368 got_deadlock_timeout = false;
1369
1370 /*
1371 * Set timer so we can wake up after awhile and check for a deadlock. If a
1372 * deadlock is detected, the handler sets MyProc->waitStatus =
1373 * PROC_WAIT_STATUS_ERROR, allowing us to know that we must report failure
1374 * rather than success.
1375 *
1376 * By delaying the check until we've waited for a bit, we can avoid
1377 * running the rather expensive deadlock-check code in most cases.
1378 *
1379 * If LockTimeout is set, also enable the timeout for that. We can save a
1380 * few cycles by enabling both timeout sources in one call.
1381 *
1382 * If InHotStandby we set lock waits slightly later for clarity with other
1383 * code.
1384 */
1385 if (!InHotStandby)
1386 {
1387 if (LockTimeout > 0)
1388 {
1389 EnableTimeoutParams timeouts[2];
1390
1391 timeouts[0].id = DEADLOCK_TIMEOUT;
1392 timeouts[0].type = TMPARAM_AFTER;
1393 timeouts[0].delay_ms = DeadlockTimeout;
1394 timeouts[1].id = LOCK_TIMEOUT;
1395 timeouts[1].type = TMPARAM_AFTER;
1396 timeouts[1].delay_ms = LockTimeout;
1397 enable_timeouts(timeouts, 2);
1398 }
1399 else
1400 enable_timeout_after(DEADLOCK_TIMEOUT, DeadlockTimeout);
1401
1402 /*
1403 * Use the current time obtained for the deadlock timeout timer as
1404 * waitStart (i.e., the time when this process started waiting for the
1405 * lock). Since getting the current time newly can cause overhead, we
1406 * reuse the already-obtained time to avoid that overhead.
1407 *
1408 * Note that waitStart is updated without holding the lock table's
1409 * partition lock, to avoid the overhead by additional lock
1410 * acquisition. This can cause "waitstart" in pg_locks to become NULL
1411 * for a very short period of time after the wait started even though
1412 * "granted" is false. This is OK in practice because we can assume
1413 * that users are likely to look at "waitstart" when waiting for the
1414 * lock for a long time.
1415 */
1416 pg_atomic_write_u64(&MyProc->waitStart,
1417 get_timeout_start_time(DEADLOCK_TIMEOUT));
1418 }
1419 else if (log_recovery_conflict_waits)
1420 {
1421 /*
1422 * Set the wait start timestamp if logging is enabled and in hot
1423 * standby.
1424 */
1425 standbyWaitStart = GetCurrentTimestamp();
1426 }
1427
1428 /*
1429 * If somebody wakes us between LWLockRelease and WaitLatch, the latch
1430 * will not wait. But a set latch does not necessarily mean that the lock
1431 * is free now, as there are many other sources for latch sets than
1432 * somebody releasing the lock.
1433 *
1434 * We process interrupts whenever the latch has been set, so cancel/die
1435 * interrupts are processed quickly. This means we must not mind losing
1436 * control to a cancel/die interrupt here. We don't, because we have no
1437 * shared-state-change work to do after being granted the lock (the
1438 * grantor did it all). We do have to worry about canceling the deadlock
1439 * timeout and updating the locallock table, but if we lose control to an
1440 * error, LockErrorCleanup will fix that up.
1441 */
1442 do
1443 {
1444 if (InHotStandby)
1445 {
1446 bool maybe_log_conflict =
1447 (standbyWaitStart != 0 && !logged_recovery_conflict);
1448
1449 /* Set a timer and wait for that or for the lock to be granted */
1450 ResolveRecoveryConflictWithLock(locallock->tag.lock,
1451 maybe_log_conflict);
1452
1453 /*
1454 * Emit the log message if the startup process is waiting longer
1455 * than deadlock_timeout for recovery conflict on lock.
1456 */
1457 if (maybe_log_conflict)
1458 {
1459 TimestampTz now = GetCurrentTimestamp();
1460
1461 if (TimestampDifferenceExceeds(standbyWaitStart, now,
1462 DeadlockTimeout))
1463 {
1464 VirtualTransactionId *vxids;
1465 int cnt;
1466
1467 vxids = GetLockConflicts(&locallock->tag.lock,
1468 AccessExclusiveLock, &cnt);
1469
1470 /*
1471 * Log the recovery conflict and the list of PIDs of
1472 * backends holding the conflicting lock. Note that we do
1473 * logging even if there are no such backends right now
1474 * because the startup process here has already waited
1475 * longer than deadlock_timeout.
1476 */
1477 LogRecoveryConflict(PROCSIG_RECOVERY_CONFLICT_LOCK,
1478 standbyWaitStart, now,
1479 cnt > 0 ? vxids : NULL, true);
1480 logged_recovery_conflict = true;
1481 }
1482 }
1483 }
1484 else
1485 {
1486 (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH, 0,
1487 PG_WAIT_LOCK | locallock->tag.lock.locktag_type);
1488 ResetLatch(MyLatch);
1489 /* check for deadlocks first, as that's probably log-worthy */
1490 if (got_deadlock_timeout)
1491 {
1492 CheckDeadLock();
1493 got_deadlock_timeout = false;
1494 }
1495 CHECK_FOR_INTERRUPTS();
1496 }
1497
1498 /*
1499 * waitStatus could change from PROC_WAIT_STATUS_WAITING to something
1500 * else asynchronously. Read it just once per loop to prevent
1501 * surprising behavior (such as missing log messages).
1502 */
1503 myWaitStatus = *((volatile ProcWaitStatus *) &MyProc->waitStatus);
1504
1505 /*
1506 * If we are not deadlocked, but are waiting on an autovacuum-induced
1507 * task, send a signal to interrupt it.
1508 */
1509 if (deadlock_state == DS_BLOCKED_BY_AUTOVACUUM && allow_autovacuum_cancel)
1510 {
1511 PGPROC *autovac = GetBlockingAutoVacuumPgproc();
1512 uint8 statusFlags;
1513 uint8 lockmethod_copy;
1514 LOCKTAG locktag_copy;
1515
1516 /*
1517 * Grab info we need, then release lock immediately. Note this
1518 * coding means that there is a tiny chance that the process
1519 * terminates its current transaction and starts a different one
1520 * before we have a change to send the signal; the worst possible
1521 * consequence is that a for-wraparound vacuum is canceled. But
1522 * that could happen in any case unless we were to do kill() with
1523 * the lock held, which is much more undesirable.
1524 */
1525 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
1526 statusFlags = ProcGlobal->statusFlags[autovac->pgxactoff];
1527 lockmethod_copy = lock->tag.locktag_lockmethodid;
1528 locktag_copy = lock->tag;
1529 LWLockRelease(ProcArrayLock);
1530
1531 /*
1532 * Only do it if the worker is not working to protect against Xid
1533 * wraparound.
1534 */
1535 if ((statusFlags & PROC_IS_AUTOVACUUM) &&
1536 !(statusFlags & PROC_VACUUM_FOR_WRAPAROUND))
1537 {
1538 int pid = autovac->pid;
1539
1540 /* report the case, if configured to do so */
1541 if (message_level_is_interesting(DEBUG1))
1542 {
1543 StringInfoData locktagbuf;
1544 StringInfoData logbuf; /* errdetail for server log */
1545
1546 initStringInfo(&locktagbuf);
1547 initStringInfo(&logbuf);
1548 DescribeLockTag(&locktagbuf, &locktag_copy);
1549 appendStringInfo(&logbuf,
1550 "Process %d waits for %s on %s.",
1551 MyProcPid,
1552 GetLockmodeName(lockmethod_copy, lockmode),
1553 locktagbuf.data);
1554
1555 ereport(DEBUG1,
1556 (errmsg_internal("sending cancel to blocking autovacuum PID %d",
1557 pid),
1558 errdetail_log("%s", logbuf.data)));
1559
1560 pfree(locktagbuf.data);
1561 pfree(logbuf.data);
1562 }
1563
1564 /* send the autovacuum worker Back to Old Kent Road */
1565 if (kill(pid, SIGINT) < 0)
1566 {
1567 /*
1568 * There's a race condition here: once we release the
1569 * ProcArrayLock, it's possible for the autovac worker to
1570 * close up shop and exit before we can do the kill().
1571 * Therefore, we do not whinge about no-such-process.
1572 * Other errors such as EPERM could conceivably happen if
1573 * the kernel recycles the PID fast enough, but such cases
1574 * seem improbable enough that it's probably best to issue
1575 * a warning if we see some other errno.
1576 */
1577 if (errno != ESRCH)
1578 ereport(WARNING,
1579 (errmsg("could not send signal to process %d: %m",
1580 pid)));
1581 }
1582 }
1583
1584 /* prevent signal from being sent again more than once */
1585 allow_autovacuum_cancel = false;
1586 }
1587
1588 /*
1589 * If awoken after the deadlock check interrupt has run, and
1590 * log_lock_waits is on, then report about the wait.
1591 */
1592 if (log_lock_waits && deadlock_state != DS_NOT_YET_CHECKED)
1593 {
1594 StringInfoData buf,
1595 lock_waiters_sbuf,
1596 lock_holders_sbuf;
1597 const char *modename;
1598 long secs;
1599 int usecs;
1600 long msecs;
1601 int lockHoldersNum = 0;
1602
1603 initStringInfo(&buf);
1604 initStringInfo(&lock_waiters_sbuf);
1605 initStringInfo(&lock_holders_sbuf);
1606
1607 DescribeLockTag(&buf, &locallock->tag.lock);
1608 modename = GetLockmodeName(locallock->tag.lock.locktag_lockmethodid,
1609 lockmode);
1610 TimestampDifference(get_timeout_start_time(DEADLOCK_TIMEOUT),
1611 GetCurrentTimestamp(),
1612 &secs, &usecs);
1613 msecs = secs * 1000 + usecs / 1000;
1614 usecs = usecs % 1000;
1615
1616 /* Gather a list of all lock holders and waiters */
1617 LWLockAcquire(partitionLock, LW_SHARED);
1618 GetLockHoldersAndWaiters(locallock, &lock_holders_sbuf,
1619 &lock_waiters_sbuf, &lockHoldersNum);
1620 LWLockRelease(partitionLock);
1621
1622 if (deadlock_state == DS_SOFT_DEADLOCK)
1623 ereport(LOG,
1624 (errmsg("process %d avoided deadlock for %s on %s by rearranging queue order after %ld.%03d ms",
1625 MyProcPid, modename, buf.data, msecs, usecs),
1626 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1627 "Processes holding the lock: %s. Wait queue: %s.",
1628 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1629 else if (deadlock_state == DS_HARD_DEADLOCK)
1630 {
1631 /*
1632 * This message is a bit redundant with the error that will be
1633 * reported subsequently, but in some cases the error report
1634 * might not make it to the log (eg, if it's caught by an
1635 * exception handler), and we want to ensure all long-wait
1636 * events get logged.
1637 */
1638 ereport(LOG,
1639 (errmsg("process %d detected deadlock while waiting for %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 if (myWaitStatus == PROC_WAIT_STATUS_WAITING)
1647 ereport(LOG,
1648 (errmsg("process %d still waiting for %s on %s after %ld.%03d ms",
1649 MyProcPid, modename, buf.data, msecs, usecs),
1650 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1651 "Processes holding the lock: %s. Wait queue: %s.",
1652 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1653 else if (myWaitStatus == PROC_WAIT_STATUS_OK)
1654 ereport(LOG,
1655 (errmsg("process %d acquired %s on %s after %ld.%03d ms",
1656 MyProcPid, modename, buf.data, msecs, usecs)));
1657 else
1658 {
1659 Assert(myWaitStatus == PROC_WAIT_STATUS_ERROR);
1660
1661 /*
1662 * Currently, the deadlock checker always kicks its own
1663 * process, which means that we'll only see
1664 * PROC_WAIT_STATUS_ERROR when deadlock_state ==
1665 * DS_HARD_DEADLOCK, and there's no need to print redundant
1666 * messages. But for completeness and future-proofing, print
1667 * a message if it looks like someone else kicked us off the
1668 * lock.
1669 */
1670 if (deadlock_state != DS_HARD_DEADLOCK)
1671 ereport(LOG,
1672 (errmsg("process %d failed to acquire %s on %s after %ld.%03d ms",
1673 MyProcPid, modename, buf.data, msecs, usecs),
1674 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1675 "Processes holding the lock: %s. Wait queue: %s.",
1676 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1677 }
1678
1679 /*
1680 * At this point we might still need to wait for the lock. Reset
1681 * state so we don't print the above messages again.
1682 */
1683 deadlock_state = DS_NO_DEADLOCK;
1684
1685 pfree(buf.data);
1686 pfree(lock_holders_sbuf.data);
1687 pfree(lock_waiters_sbuf.data);
1688 }
1689 } while (myWaitStatus == PROC_WAIT_STATUS_WAITING);
1690
1691 /*
1692 * Disable the timers, if they are still running. As in LockErrorCleanup,
1693 * we must preserve the LOCK_TIMEOUT indicator flag: if a lock timeout has
1694 * already caused QueryCancelPending to become set, we want the cancel to
1695 * be reported as a lock timeout, not a user cancel.
1696 */
1697 if (!InHotStandby)
1698 {
1699 if (LockTimeout > 0)
1700 {
1701 DisableTimeoutParams timeouts[2];
1702
1703 timeouts[0].id = DEADLOCK_TIMEOUT;
1704 timeouts[0].keep_indicator = false;
1705 timeouts[1].id = LOCK_TIMEOUT;
1706 timeouts[1].keep_indicator = true;
1707 disable_timeouts(timeouts, 2);
1708 }
1709 else
1710 disable_timeout(DEADLOCK_TIMEOUT, false);
1711 }
1712
1713 /*
1714 * Emit the log message if recovery conflict on lock was resolved but the
1715 * startup process waited longer than deadlock_timeout for it.
1716 */
1717 if (InHotStandby && logged_recovery_conflict)
1718 LogRecoveryConflict(PROCSIG_RECOVERY_CONFLICT_LOCK,
1719 standbyWaitStart, GetCurrentTimestamp(),
1720 NULL, false);
1721
1722 /*
1723 * We don't have to do anything else, because the awaker did all the
1724 * necessary updates of the lock table and MyProc. (The caller is
1725 * responsible for updating the local lock table.)
1726 */
1727 return myWaitStatus;
1728 }
1729
1730
1731 /*
1732 * ProcWakeup -- wake up a process by setting its latch.
1733 *
1734 * Also remove the process from the wait queue and set its links invalid.
1735 *
1736 * The appropriate lock partition lock must be held by caller.
1737 *
1738 * XXX: presently, this code is only used for the "success" case, and only
1739 * works correctly for that case. To clean up in failure case, would need
1740 * to twiddle the lock's request counts too --- see RemoveFromWaitQueue.
1741 * Hence, in practice the waitStatus parameter must be PROC_WAIT_STATUS_OK.
1742 */
1743 void
1744 ProcWakeup(PGPROC *proc, ProcWaitStatus waitStatus)
1745 {
1746 if (dlist_node_is_detached(&proc->links))
1747 return;
1748
1749 Assert(proc->waitStatus == PROC_WAIT_STATUS_WAITING);
1750
1751 /* Remove process from wait queue */
1752 dclist_delete_from_thoroughly(&proc->waitLock->waitProcs, &proc->links);
1753
1754 /* Clean up process' state and pass it the ok/fail signal */
1755 proc->waitLock = NULL;
1756 proc->waitProcLock = NULL;
1757 proc->waitStatus = waitStatus;
1758 pg_atomic_write_u64(&proc->waitStart, 0);
1759
1760 /* And awaken it */
1761 SetLatch(&proc->procLatch);
1762 }
1763
1764 /*
1765 * ProcLockWakeup -- routine for waking up processes when a lock is
1766 * released (or a prior waiter is aborted). Scan all waiters
1767 * for lock, waken any that are no longer blocked.
1768 *
1769 * The appropriate lock partition lock must be held by caller.
1770 */
1771 void
1772 ProcLockWakeup(LockMethod lockMethodTable, LOCK *lock)
1773 {
1774 dclist_head *waitQueue = &lock->waitProcs;
1775 LOCKMASK aheadRequests = 0;
1776 dlist_mutable_iter miter;
1777
1778 if (dclist_is_empty(waitQueue))
1779 return;
1780
1781 dclist_foreach_modify(miter, waitQueue)
1782 {
1783 PGPROC *proc = dlist_container(PGPROC, links, miter.cur);
1784 LOCKMODE lockmode = proc->waitLockMode;
1785
1786 /*
1787 * Waken if (a) doesn't conflict with requests of earlier waiters, and
1788 * (b) doesn't conflict with already-held locks.
1789 */
1790 if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
1791 !LockCheckConflicts(lockMethodTable, lockmode, lock,
1792 proc->waitProcLock))
1793 {
1794 /* OK to waken */
1795 GrantLock(lock, proc->waitProcLock, lockmode);
1796 /* removes proc from the lock's waiting process queue */
1797 ProcWakeup(proc, PROC_WAIT_STATUS_OK);
1798 }
1799 else
1800 {
1801 /*
1802 * Lock conflicts: Don't wake, but remember requested mode for
1803 * later checks.
1804 */
1805 aheadRequests |= LOCKBIT_ON(lockmode);
1806 }
1807 }
1808 }
1809
1810 /*
1811 * CheckDeadLock
1812 *
1813 * We only get to this routine, if DEADLOCK_TIMEOUT fired while waiting for a
1814 * lock to be released by some other process. Check if there's a deadlock; if
1815 * not, just return. (But signal ProcSleep to log a message, if
1816 * log_lock_waits is true.) If we have a real deadlock, remove ourselves from
1817 * the lock's wait queue and signal an error to ProcSleep.
1818 */
1819 static void
1820 CheckDeadLock(void)
1821 {
1822 int i;
1823
1824 /*
1825 * Acquire exclusive lock on the entire shared lock data structures. Must
1826 * grab LWLocks in partition-number order to avoid LWLock deadlock.
1827 *
1828 * Note that the deadlock check interrupt had better not be enabled
1829 * anywhere that this process itself holds lock partition locks, else this
1830 * will wait forever. Also note that LWLockAcquire creates a critical
1831 * section, so that this routine cannot be interrupted by cancel/die
1832 * interrupts.
1833 */
1834 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
1835 LWLockAcquire(LockHashPartitionLockByIndex(i), LW_EXCLUSIVE);
1836
1837 /*
1838 * Check to see if we've been awoken by anyone in the interim.
1839 *
1840 * If we have, we can return and resume our transaction -- happy day.
1841 * Before we are awoken the process releasing the lock grants it to us so
1842 * we know that we don't have to wait anymore.
1843 *
1844 * We check by looking to see if we've been unlinked from the wait queue.
1845 * This is safe because we hold the lock partition lock.
1846 */
1847 if (MyProc->links.prev == NULL ||
1848 MyProc->links.next == NULL)
1849 goto check_done;
1850
1851 #ifdef LOCK_DEBUG
1852 if (Debug_deadlocks)
1853 DumpAllLocks();
1854 #endif
1855
1856 /* Run the deadlock check, and set deadlock_state for use by ProcSleep */
1857 deadlock_state = DeadLockCheck(MyProc);
1858
1859 if (deadlock_state == DS_HARD_DEADLOCK)
1860 {
1861 /*
1862 * Oops. We have a deadlock.
1863 *
1864 * Get this process out of wait state. (Note: we could do this more
1865 * efficiently by relying on lockAwaited, but use this coding to
1866 * preserve the flexibility to kill some other transaction than the
1867 * one detecting the deadlock.)
1868 *
1869 * RemoveFromWaitQueue sets MyProc->waitStatus to
1870 * PROC_WAIT_STATUS_ERROR, so ProcSleep will report an error after we
1871 * return from the signal handler.
1872 */
1873 Assert(MyProc->waitLock != NULL);
1874 RemoveFromWaitQueue(MyProc, LockTagHashCode(&(MyProc->waitLock->tag)));
1875
1876 /*
1877 * We're done here. Transaction abort caused by the error that
1878 * ProcSleep will raise will cause any other locks we hold to be
1879 * released, thus allowing other processes to wake up; we don't need
1880 * to do that here. NOTE: an exception is that releasing locks we
1881 * hold doesn't consider the possibility of waiters that were blocked
1882 * behind us on the lock we just failed to get, and might now be
1883 * wakable because we're not in front of them anymore. However,
1884 * RemoveFromWaitQueue took care of waking up any such processes.
1885 */
1886 }
1887
1888 /*
1889 * And release locks. We do this in reverse order for two reasons: (1)
1890 * Anyone else who needs more than one of the locks will be trying to lock
1891 * them in increasing order; we don't want to release the other process
1892 * until it can get all the locks it needs. (2) This avoids O(N^2)
1893 * behavior inside LWLockRelease.
1894 */
1895 check_done:
1896 for (i = NUM_LOCK_PARTITIONS; --i >= 0;)
1897 LWLockRelease(LockHashPartitionLockByIndex(i));
1898 }
1899
1900 /*
1901 * CheckDeadLockAlert - Handle the expiry of deadlock_timeout.
1902 *
1903 * NB: Runs inside a signal handler, be careful.
1904 */
1905 void
1906 CheckDeadLockAlert(void)
1907 {
1908 int save_errno = errno;
1909
1910 got_deadlock_timeout = true;
1911
1912 /*
1913 * Have to set the latch again, even if handle_sig_alarm already did. Back
1914 * then got_deadlock_timeout wasn't yet set... It's unlikely that this
1915 * ever would be a problem, but setting a set latch again is cheap.
1916 *
1917 * Note that, when this function runs inside procsignal_sigusr1_handler(),
1918 * the handler function sets the latch again after the latch is set here.
1919 */
1920 SetLatch(MyLatch);
1921 errno = save_errno;
1922 }
1923
1924 /*
1925 * GetLockHoldersAndWaiters - get lock holders and waiters for a lock
1926 *
1927 * Fill lock_holders_sbuf and lock_waiters_sbuf with the PIDs of processes holding
1928 * and waiting for the lock, and set lockHoldersNum to the number of lock holders.
1929 *
1930 * The lock table's partition lock must be held on entry and remains held on exit.
1931 */
1932 void
1933 GetLockHoldersAndWaiters(LOCALLOCK *locallock, StringInfo lock_holders_sbuf,
1934 StringInfo lock_waiters_sbuf, int *lockHoldersNum)
1935 {
1936 dlist_iter proc_iter;
1937 PROCLOCK *curproclock;
1938 LOCK *lock = locallock->lock;
1939 bool first_holder = true,
1940 first_waiter = true;
1941
1942 #ifdef USE_ASSERT_CHECKING
1943 {
1944 uint32 hashcode = locallock->hashcode;
1945 LWLock *partitionLock = LockHashPartitionLock(hashcode);
1946
1947 Assert(LWLockHeldByMe(partitionLock));
1948 }
1949 #endif
1950
1951 *lockHoldersNum = 0;
1952
1953 /*
1954 * Loop over the lock's procLocks to gather a list of all holders and
1955 * waiters. Thus we will be able to provide more detailed information for
1956 * lock debugging purposes.
1957 *
1958 * lock->procLocks contains all processes which hold or wait for this
1959 * lock.
1960 */
1961 dlist_foreach(proc_iter, &lock->procLocks)
1962 {
1963 curproclock =
1964 dlist_container(PROCLOCK, lockLink, proc_iter.cur);
1965
1966 /*
1967 * We are a waiter if myProc->waitProcLock == curproclock; we are a
1968 * holder if it is NULL or something different.
1969 */
1970 if (curproclock->tag.myProc->waitProcLock == curproclock)
1971 {
1972 if (first_waiter)
1973 {
1974 appendStringInfo(lock_waiters_sbuf, "%d",
1975 curproclock->tag.myProc->pid);
1976 first_waiter = false;
1977 }
1978 else
1979 appendStringInfo(lock_waiters_sbuf, ", %d",
1980 curproclock->tag.myProc->pid);
1981 }
1982 else
1983 {
1984 if (first_holder)
1985 {
1986 appendStringInfo(lock_holders_sbuf, "%d",
1987 curproclock->tag.myProc->pid);
1988 first_holder = false;
1989 }
1990 else
1991 appendStringInfo(lock_holders_sbuf, ", %d",
1992 curproclock->tag.myProc->pid);
1993
1994 (*lockHoldersNum)++;
1995 }
1996 }
1997 }
1998
1999 /*
2000 * ProcWaitForSignal - wait for a signal from another backend.
2001 *
2002 * As this uses the generic process latch the caller has to be robust against
2003 * unrelated wakeups: Always check that the desired state has occurred, and
2004 * wait again if not.
2005 */
2006 void
2007 ProcWaitForSignal(uint32 wait_event_info)
2008 {
2009 (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH, 0,
2010 wait_event_info);
2011 ResetLatch(MyLatch);
2012 CHECK_FOR_INTERRUPTS();
2013 }
2014
2015 /*
2016 * ProcSendSignal - set the latch of a backend identified by ProcNumber
2017 */
2018 void
2019 ProcSendSignal(ProcNumber procNumber)
2020 {
2021 if (procNumber < 0 || procNumber >= ProcGlobal->allProcCount)
2022 elog(ERROR, "procNumber out of range");
2023
2024 SetLatch(&ProcGlobal->allProcs[procNumber].procLatch);
2025 }
2026
2027 /*
2028 * BecomeLockGroupLeader - designate process as lock group leader
2029 *
2030 * Once this function has returned, other processes can join the lock group
2031 * by calling BecomeLockGroupMember.
2032 */
2033 void
2034 BecomeLockGroupLeader(void)
2035 {
2036 LWLock *leader_lwlock;
2037
2038 /* If we already did it, we don't need to do it again. */
2039 if (MyProc->lockGroupLeader == MyProc)
2040 return;
2041
2042 /* We had better not be a follower. */
2043 Assert(MyProc->lockGroupLeader == NULL);
2044
2045 /* Create single-member group, containing only ourselves. */
2046 leader_lwlock = LockHashPartitionLockByProc(MyProc);
2047 LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
2048 MyProc->lockGroupLeader = MyProc;
2049 dlist_push_head(&MyProc->lockGroupMembers, &MyProc->lockGroupLink);
2050 LWLockRelease(leader_lwlock);
2051 }
2052
2053 /*
2054 * BecomeLockGroupMember - designate process as lock group member
2055 *
2056 * This is pretty straightforward except for the possibility that the leader
2057 * whose group we're trying to join might exit before we manage to do so;
2058 * and the PGPROC might get recycled for an unrelated process. To avoid
2059 * that, we require the caller to pass the PID of the intended PGPROC as
2060 * an interlock. Returns true if we successfully join the intended lock
2061 * group, and false if not.
2062 */
2063 bool
2064 BecomeLockGroupMember(PGPROC *leader, int pid)
2065 {
2066 LWLock *leader_lwlock;
2067 bool ok = false;
2068
2069 /* Group leader can't become member of group */
2070 Assert(MyProc != leader);
2071
2072 /* Can't already be a member of a group */
2073 Assert(MyProc->lockGroupLeader == NULL);
2074
2075 /* PID must be valid. */
2076 Assert(pid != 0);
2077
2078 /*
2079 * Get lock protecting the group fields. Note LockHashPartitionLockByProc
2080 * calculates the proc number based on the PGPROC slot without looking at
2081 * its contents, so we will acquire the correct lock even if the leader
2082 * PGPROC is in process of being recycled.
2083 */
2084 leader_lwlock = LockHashPartitionLockByProc(leader);
2085 LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
2086
2087 /* Is this the leader we're looking for? */
2088 if (leader->pid == pid && leader->lockGroupLeader == leader)
2089 {
2090 /* OK, join the group */
2091 ok = true;
2092 MyProc->lockGroupLeader = leader;
2093 dlist_push_tail(&leader->lockGroupMembers, &MyProc->lockGroupLink);
2094 }
2095 LWLockRelease(leader_lwlock);
2096
2097 return ok;
2098 }