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