Age Owner Branch data TLA 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
29 heikki.linnakangas@i 105 :GNC 1244 : CalculateFastPathLockShmemSize(void)
106 : : {
398 tomas.vondra@postgre 107 :CBC 1244 : 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 : : */
591 115 : 1244 : fpLockBitsSize = MAXALIGN(FastPathLockGroupsPerBackend * sizeof(uint64));
427 116 : 1244 : fpRelIdSize = MAXALIGN(FastPathLockSlotsPerBackend() * sizeof(Oid));
117 : :
591 118 : 1244 : size = add_size(size, mul_size(TotalProcs, (fpLockBitsSize + fpRelIdSize)));
119 : :
29 heikki.linnakangas@i 120 [ - + ]:GNC 1244 : Assert(TotalProcs > 0);
121 [ - + ]: 1244 : Assert(size > 0);
122 : :
7888 tgl@sss.pgh.pa.us 123 :CBC 1244 : return size;
124 : : }
125 : :
126 : : /*
127 : : * Report number of semaphores needed by ProcGlobalShmemInit.
128 : : */
129 : : int
7627 130 : 3553 : ProcGlobalSemas(void)
131 : : {
132 : : /*
133 : : * We need a sema per backend (including autovacuum), plus one for each
134 : : * auxiliary process.
135 : : */
1484 rhaas@postgresql.org 136 : 3553 : 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
29 heikki.linnakangas@i 147 :GNC 1244 : 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 : 1244 : TotalProcs =
161 : 1244 : add_size(MaxBackends, add_size(NUM_AUXILIARY_PROCS, max_prepared_xacts));
162 : :
163 : 1244 : size = 0;
164 : 1244 : size = add_size(size, mul_size(TotalProcs, sizeof(PGPROC)));
165 : 1244 : size = add_size(size, mul_size(TotalProcs, sizeof(*ProcGlobal->xids)));
166 : 1244 : size = add_size(size, mul_size(TotalProcs, sizeof(*ProcGlobal->subxidStates)));
167 : 1244 : size = add_size(size, mul_size(TotalProcs, sizeof(*ProcGlobal->statusFlags)));
168 : 1244 : ProcGlobalAllProcsShmemSize = size;
169 : 1244 : ShmemRequestStruct(.name = "PGPROC structures",
170 : : .size = ProcGlobalAllProcsShmemSize,
171 : : .ptr = &AllProcsShmemPtr,
172 : : );
173 : :
174 [ + - ]: 1244 : if (!IsUnderPostmaster)
175 : 1244 : size = FastPathLockArrayShmemSize = CalculateFastPathLockShmemSize();
176 : : else
29 heikki.linnakangas@i 177 :UNC 0 : size = SHMEM_ATTACH_UNKNOWN_SIZE;
29 heikki.linnakangas@i 178 :GNC 1244 : 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 : 1244 : 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 : 1244 : PGSemaphoreShmemRequest(ProcGlobalSemas());
196 : 1244 : }
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 : 1241 : 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 [ - + ]: 1241 : Assert(ProcGlobal);
5441 rhaas@postgresql.org 236 :CBC 1241 : ProcGlobal->spins_per_delay = DEFAULT_SPINS_PER_DELAY;
83 heikki.linnakangas@i 237 :GNC 1241 : SpinLockInit(&ProcGlobal->freeProcsLock);
1203 andres@anarazel.de 238 :CBC 1241 : dlist_init(&ProcGlobal->freeProcs);
239 : 1241 : dlist_init(&ProcGlobal->autovacFreeProcs);
240 : 1241 : dlist_init(&ProcGlobal->bgworkerFreeProcs);
241 : 1241 : dlist_init(&ProcGlobal->walsenderFreeProcs);
5390 tgl@sss.pgh.pa.us 242 : 1241 : ProcGlobal->startupBufferPinWaitBufId = -1;
550 heikki.linnakangas@i 243 : 1241 : ProcGlobal->walwriterProc = INVALID_PROC_NUMBER;
244 : 1241 : ProcGlobal->checkpointerProc = INVALID_PROC_NUMBER;
793 245 : 1241 : pg_atomic_init_u32(&ProcGlobal->procArrayGroupFirst, INVALID_PROC_NUMBER);
246 : 1241 : pg_atomic_init_u32(&ProcGlobal->clogGroupFirst, INVALID_PROC_NUMBER);
247 : :
29 heikki.linnakangas@i 248 :GNC 1241 : ptr = AllProcsShmemPtr;
249 : 1241 : requestSize = ProcGlobalAllProcsShmemSize;
398 tomas.vondra@postgre 250 [ + - + + :CBC 1241 : MemSet(ptr, 0, requestSize);
+ - - + -
- ]
251 : :
252 : : /* Carve out the allProcs array from the shared memory area */
253 : 1241 : procs = (PGPROC *) ptr;
154 peter@eisentraut.org 254 :GNC 1241 : ptr = ptr + TotalProcs * sizeof(PGPROC);
255 : :
5456 rhaas@postgresql.org 256 :CBC 1241 : ProcGlobal->allProcs = procs;
257 : : /* XXX allProcCount isn't really all of them; it excludes prepared xacts */
1484 258 : 1241 : 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 : : */
398 tomas.vondra@postgre 267 : 1241 : ProcGlobal->xids = (TransactionId *) ptr;
154 peter@eisentraut.org 268 :GNC 1241 : ptr = ptr + (TotalProcs * sizeof(*ProcGlobal->xids));
269 : :
398 tomas.vondra@postgre 270 :CBC 1241 : ProcGlobal->subxidStates = (XidCacheStatus *) ptr;
154 peter@eisentraut.org 271 :GNC 1241 : ptr = ptr + (TotalProcs * sizeof(*ProcGlobal->subxidStates));
272 : :
398 tomas.vondra@postgre 273 :CBC 1241 : ProcGlobal->statusFlags = (uint8 *) ptr;
154 peter@eisentraut.org 274 :GNC 1241 : ptr = ptr + (TotalProcs * sizeof(*ProcGlobal->statusFlags));
275 : :
276 : : /* make sure we didn't overflow */
398 tomas.vondra@postgre 277 [ + - - + ]:CBC 1241 : 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 : : */
591 284 : 1241 : fpLockBitsSize = MAXALIGN(FastPathLockGroupsPerBackend * sizeof(uint64));
427 285 : 1241 : fpRelIdSize = MAXALIGN(FastPathLockSlotsPerBackend() * sizeof(Oid));
286 : :
29 heikki.linnakangas@i 287 :GNC 1241 : fpPtr = FastPathLockArrayShmemPtr;
288 : 1241 : requestSize = FastPathLockArrayShmemSize;
289 : 1241 : memset(fpPtr, 0, requestSize);
290 : :
291 : : /* For asserts checking we did not overflow. */
398 tomas.vondra@postgre 292 :CBC 1241 : fpEndPtr = fpPtr + requestSize;
293 : :
294 : : /* Initialize semaphores */
29 heikki.linnakangas@i 295 :GNC 1241 : PGSemaphoreInit(ProcGlobalSemas());
296 : :
5441 rhaas@postgresql.org 297 [ + + ]:CBC 164896 : for (i = 0; i < TotalProcs; i++)
298 : : {
1203 andres@anarazel.de 299 : 163655 : 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 : : */
591 tomas.vondra@postgre 307 : 163655 : proc->fpLockBits = (uint64 *) fpPtr;
308 : 163655 : fpPtr += fpLockBitsSize;
309 : :
310 : 163655 : proc->fpRelId = (Oid *) fpPtr;
311 : 163655 : fpPtr += fpRelIdSize;
312 : :
313 [ - + ]: 163655 : 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 : : */
64 heikki.linnakangas@i 320 [ + + ]: 163655 : if (i < FIRST_PREPARED_XACT_PROC_NUMBER)
321 : : {
1203 andres@anarazel.de 322 : 162783 : proc->sem = PGSemaphoreCreate();
323 : 162783 : InitSharedLatch(&(proc->procLatch));
324 : 162783 : 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 : : */
5441 rhaas@postgresql.org 336 [ + + ]: 163655 : if (i < MaxConnections)
337 : : {
338 : : /* PGPROC for normal backend, add to freeProcs list */
74 heikki.linnakangas@i 339 :GNC 81544 : dlist_push_tail(&ProcGlobal->freeProcs, &proc->freeProcsLink);
1203 andres@anarazel.de 340 :CBC 81544 : proc->procgloballist = &ProcGlobal->freeProcs;
341 : : }
484 nathan@postgresql.or 342 [ + + ]: 82111 : else if (i < MaxConnections + autovacuum_worker_slots + NUM_SPECIAL_WORKER_PROCS)
343 : : {
344 : : /* PGPROC for AV or special worker, add to autovacFreeProcs list */
74 heikki.linnakangas@i 345 :GNC 16252 : dlist_push_tail(&ProcGlobal->autovacFreeProcs, &proc->freeProcsLink);
1203 andres@anarazel.de 346 :CBC 16252 : proc->procgloballist = &ProcGlobal->autovacFreeProcs;
347 : : }
484 nathan@postgresql.or 348 [ + + ]: 65859 : else if (i < MaxConnections + autovacuum_worker_slots + NUM_SPECIAL_WORKER_PROCS + max_worker_processes)
349 : : {
350 : : /* PGPROC for bgworker, add to bgworkerFreeProcs list */
74 heikki.linnakangas@i 351 :GNC 9921 : dlist_push_tail(&ProcGlobal->bgworkerFreeProcs, &proc->freeProcsLink);
1203 andres@anarazel.de 352 :CBC 9921 : proc->procgloballist = &ProcGlobal->bgworkerFreeProcs;
353 : : }
1484 rhaas@postgresql.org 354 [ + + ]: 55938 : else if (i < MaxBackends)
355 : : {
356 : : /* PGPROC for walsender, add to walsenderFreeProcs list */
74 heikki.linnakangas@i 357 :GNC 7908 : dlist_push_tail(&ProcGlobal->walsenderFreeProcs, &proc->freeProcsLink);
1203 andres@anarazel.de 358 :CBC 7908 : proc->procgloballist = &ProcGlobal->walsenderFreeProcs;
359 : : }
360 : :
361 : : /* Initialize myProcLocks[] shared memory queues. */
5299 rhaas@postgresql.org 362 [ + + ]: 2782135 : for (j = 0; j < NUM_LOCK_PARTITIONS; j++)
1203 andres@anarazel.de 363 : 2618480 : dlist_init(&(proc->myProcLocks[j]));
364 : :
365 : : /* Initialize lockGroupMembers list. */
366 : 163655 : 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 : : */
793 heikki.linnakangas@i 372 : 163655 : pg_atomic_init_u32(&(proc->procArrayGroupNext), INVALID_PROC_NUMBER);
373 : 163655 : pg_atomic_init_u32(&(proc->clogGroupNext), INVALID_PROC_NUMBER);
1203 andres@anarazel.de 374 : 163655 : pg_atomic_init_u64(&(proc->waitStart), 0);
375 : : }
376 : :
377 : : /* Should have consumed exactly the expected amount of fast-path memory. */
589 tomas.vondra@postgre 378 [ - + ]: 1241 : Assert(fpPtr == fpEndPtr);
379 : :
380 : : /*
381 : : * Save pointers to the blocks of PGPROC structures reserved for auxiliary
382 : : * processes and prepared transactions.
383 : : */
1484 rhaas@postgresql.org 384 : 1241 : AuxiliaryProcs = &procs[MaxBackends];
64 heikki.linnakangas@i 385 : 1241 : PreparedXactProcs = &procs[FIRST_PREPARED_XACT_PROC_NUMBER];
10892 scrappy@hub.org 386 : 1241 : }
387 : :
388 : : /*
389 : : * InitProcess -- initialize a per-process PGPROC entry for this backend
390 : : */
391 : : void
9289 tgl@sss.pgh.pa.us 392 : 18604 : 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 : : */
3854 rhaas@postgresql.org 400 [ - + ]: 18604 : if (ProcGlobal == NULL)
8321 tgl@sss.pgh.pa.us 401 [ # # ]:UBC 0 : elog(PANIC, "proc header uninitialized");
402 : :
9006 tgl@sss.pgh.pa.us 403 [ - + ]:CBC 18604 : if (MyProc != NULL)
8321 tgl@sss.pgh.pa.us 404 [ # # ]:UBC 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 : : */
537 heikki.linnakangas@i 411 [ + + ]:CBC 18604 : if (IsUnderPostmaster)
574 412 : 18471 : 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 : : */
493 tgl@sss.pgh.pa.us 418 [ + + + + : 18604 : if (AmAutoVacuumWorkerProcess() || AmSpecialWorkerProcess())
+ + ]
3854 rhaas@postgresql.org 419 : 543 : procgloballist = &ProcGlobal->autovacFreeProcs;
792 heikki.linnakangas@i 420 [ + + ]: 18061 : else if (AmBackgroundWorkerProcess())
3854 rhaas@postgresql.org 421 : 3172 : procgloballist = &ProcGlobal->bgworkerFreeProcs;
792 heikki.linnakangas@i 422 [ + + ]: 14889 : else if (AmWalSenderProcess())
2639 michael@paquier.xyz 423 : 1283 : procgloballist = &ProcGlobal->walsenderFreeProcs;
424 : : else
3854 rhaas@postgresql.org 425 : 13606 : 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 : : */
83 heikki.linnakangas@i 434 :GNC 18604 : SpinLockAcquire(&ProcGlobal->freeProcsLock);
435 : :
3854 rhaas@postgresql.org 436 :CBC 18604 : set_spins_per_delay(ProcGlobal->spins_per_delay);
437 : :
1203 andres@anarazel.de 438 [ + + ]: 18604 : if (!dlist_is_empty(procgloballist))
439 : : {
74 heikki.linnakangas@i 440 :GNC 18601 : MyProc = dlist_container(PGPROC, freeProcsLink, dlist_pop_head_node(procgloballist));
83 441 : 18601 : 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);
792 heikki.linnakangas@i 452 [ + + ]:CBC 3 : if (AmWalSenderProcess())
2639 michael@paquier.xyz 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)));
8321 tgl@sss.pgh.pa.us 457 [ + - ]: 1 : ereport(FATAL,
458 : : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
459 : : errmsg("sorry, too many clients already")));
460 : : }
803 heikki.linnakangas@i 461 : 18601 : 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 : : */
3934 rhaas@postgresql.org 467 [ - + ]: 18601 : Assert(MyProc->procgloballist == procgloballist);
468 : :
469 : : /*
470 : : * Initialize all fields of MyProc, except for those previously
471 : : * initialized by ProcGlobalShmemInit.
472 : : */
74 heikki.linnakangas@i 473 :GNC 18601 : dlist_node_init(&MyProc->freeProcsLink);
2148 peter@eisentraut.org 474 :CBC 18601 : MyProc->waitStatus = PROC_WAIT_STATUS_OK;
4905 simon@2ndQuadrant.co 475 : 18601 : MyProc->fpVXIDLock = false;
476 : 18601 : MyProc->fpLocalTransactionId = InvalidLocalTransactionId;
2090 andres@anarazel.de 477 : 18601 : MyProc->xid = InvalidTransactionId;
2091 478 : 18601 : MyProc->xmin = InvalidTransactionId;
8984 tgl@sss.pgh.pa.us 479 : 18601 : MyProc->pid = MyProcPid;
793 heikki.linnakangas@i 480 : 18601 : MyProc->vxid.procNumber = MyProcNumber;
481 : 18601 : MyProc->vxid.lxid = InvalidLocalTransactionId;
482 : : /* databaseId and roleId will be filled in later */
7426 tgl@sss.pgh.pa.us 483 : 18601 : MyProc->databaseId = InvalidOid;
7583 484 : 18601 : MyProc->roleId = InvalidOid;
2822 michael@paquier.xyz 485 : 18601 : MyProc->tempNamespaceId = InvalidOid;
90 heikki.linnakangas@i 486 :GNC 18601 : MyProc->backendType = MyBackendType;
1488 rhaas@postgresql.org 487 :CBC 18601 : MyProc->delayChkptFlags = 0;
1996 alvherre@alvh.no-ip. 488 : 18601 : MyProc->statusFlags = 0;
489 : : /* NB -- autovac launcher intentionally does not set IS_AUTOVACUUM */
792 heikki.linnakangas@i 490 [ + + ]: 18601 : if (AmAutoVacuumWorkerProcess())
1996 alvherre@alvh.no-ip. 491 : 60 : MyProc->statusFlags |= PROC_IS_AUTOVACUUM;
1262 andres@anarazel.de 492 : 18601 : MyProc->lwWaiting = LW_WS_NOT_WAITING;
5209 heikki.linnakangas@i 493 : 18601 : MyProc->lwWaitMode = 0;
9234 tgl@sss.pgh.pa.us 494 : 18601 : MyProc->waitLock = NULL;
74 heikki.linnakangas@i 495 :GNC 18601 : dlist_node_init(&MyProc->waitLink);
7921 tgl@sss.pgh.pa.us 496 :CBC 18601 : MyProc->waitProcLock = NULL;
1898 fujii@postgresql.org 497 : 18601 : 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. */
5299 rhaas@postgresql.org 503 [ + + ]: 316217 : for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
1203 andres@anarazel.de 504 [ - + ]: 297616 : Assert(dlist_is_empty(&(MyProc->myProcLocks[i])));
505 : : }
506 : : #endif
84 heikki.linnakangas@i 507 :GNC 18601 : pg_atomic_write_u32(&MyProc->pendingRecoveryConflicts, 0);
508 : :
509 : : /* Initialize fields for sync rep */
96 alvherre@kurilemu.de 510 : 18601 : MyProc->waitLSN = InvalidXLogRecPtr;
5539 simon@2ndQuadrant.co 511 :CBC 18601 : MyProc->syncRepState = SYNC_REP_NOT_WAITING;
1203 andres@anarazel.de 512 : 18601 : dlist_node_init(&MyProc->syncRepLinks);
513 : :
514 : : /* Initialize fields for group XID clearing. */
3736 rhaas@postgresql.org 515 : 18601 : MyProc->procArrayGroupMember = false;
516 : 18601 : MyProc->procArrayGroupMemberXid = InvalidTransactionId;
793 heikki.linnakangas@i 517 [ - + ]: 18601 : Assert(pg_atomic_read_u32(&MyProc->procArrayGroupNext) == INVALID_PROC_NUMBER);
518 : :
519 : : /* Check that group locking fields are in a proper initial state. */
3740 rhaas@postgresql.org 520 [ - + ]: 18601 : Assert(MyProc->lockGroupLeader == NULL);
521 [ - + ]: 18601 : Assert(dlist_is_empty(&MyProc->lockGroupMembers));
522 : :
523 : : /* Initialize wait event information. */
3708 524 : 18601 : MyProc->wait_event_info = 0;
525 : :
526 : : /* Initialize fields for group transaction status update. */
3168 527 : 18601 : MyProc->clogGroupMember = false;
528 : 18601 : MyProc->clogGroupMemberXid = InvalidTransactionId;
529 : 18601 : MyProc->clogGroupMemberXidStatus = TRANSACTION_STATUS_IN_PROGRESS;
530 : 18601 : MyProc->clogGroupMemberPage = -1;
531 : 18601 : MyProc->clogGroupMemberLsn = InvalidXLogRecPtr;
793 heikki.linnakangas@i 532 [ - + ]: 18601 : 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 : : */
5382 tgl@sss.pgh.pa.us 539 : 18601 : OwnLatch(&MyProc->procLatch);
4129 andres@anarazel.de 540 : 18601 : SwitchToSharedLatch();
541 : :
542 : : /* now that we have a proc, report wait events to shared memory */
1858 543 : 18601 : 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 : : */
3431 tgl@sss.pgh.pa.us 550 : 18601 : PGSemaphoreReset(MyProc->sem);
551 : :
552 : : /*
553 : : * Arrange to clean up at backend exit.
554 : : */
9242 555 : 18601 : 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 : : */
4327 heikki.linnakangas@i 561 : 18601 : InitLWLockAccess();
9231 tgl@sss.pgh.pa.us 562 : 18601 : 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
9242 573 : 18601 : }
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
7426 583 : 18588 : InitProcessPhase2(void)
584 : : {
585 [ - + ]: 18588 : Assert(MyProc != NULL);
586 : :
587 : : /*
588 : : * Add our PGPROC to the PGPROC array in shared memory.
589 : : */
590 : 18588 : ProcArrayAdd(MyProc);
591 : :
592 : : /*
593 : : * Arrange to clean that up at backend exit.
594 : : */
595 : 18588 : on_shmem_exit(RemoveProcFromArray, 0);
596 : 18588 : }
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
6999 alvherre@alvh.no-ip. 618 : 4369 : 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 [ + - - + ]: 4369 : if (ProcGlobal == NULL || AuxiliaryProcs == NULL)
8321 tgl@sss.pgh.pa.us 628 [ # # ]:UBC 0 : elog(PANIC, "proc header uninitialized");
629 : :
8984 tgl@sss.pgh.pa.us 630 [ - + ]:CBC 4369 : if (MyProc != NULL)
8321 tgl@sss.pgh.pa.us 631 [ # # ]:UBC 0 : elog(ERROR, "you already exist");
632 : :
537 heikki.linnakangas@i 633 [ + - ]:CBC 4369 : if (IsUnderPostmaster)
634 : 4369 : 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 : : */
83 heikki.linnakangas@i 643 :GNC 4369 : SpinLockAcquire(&ProcGlobal->freeProcsLock);
644 : :
7511 tgl@sss.pgh.pa.us 645 :CBC 4369 : set_spins_per_delay(ProcGlobal->spins_per_delay);
646 : :
647 : : /*
648 : : * Find a free auxproc ... *big* trouble if there isn't one ...
649 : : */
6999 alvherre@alvh.no-ip. 650 [ + - ]: 15333 : for (proctype = 0; proctype < NUM_AUXILIARY_PROCS; proctype++)
651 : : {
652 : 15333 : auxproc = &AuxiliaryProcs[proctype];
653 [ + + ]: 15333 : if (auxproc->pid == 0)
7426 tgl@sss.pgh.pa.us 654 : 4369 : break;
655 : : }
6999 alvherre@alvh.no-ip. 656 [ - + ]: 4369 : if (proctype >= NUM_AUXILIARY_PROCS)
657 : : {
83 heikki.linnakangas@i 658 :UNC 0 : SpinLockRelease(&ProcGlobal->freeProcsLock);
6999 alvherre@alvh.no-ip. 659 [ # # ]:UBC 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 */
6999 alvherre@alvh.no-ip. 664 :CBC 4369 : ((volatile PGPROC *) auxproc)->pid = MyProcPid;
665 : :
83 heikki.linnakangas@i 666 :GNC 4369 : SpinLockRelease(&ProcGlobal->freeProcsLock);
667 : :
793 heikki.linnakangas@i 668 :CBC 4369 : MyProc = auxproc;
803 669 : 4369 : MyProcNumber = GetNumberFromPGProc(MyProc);
670 : :
671 : : /*
672 : : * Initialize all fields of MyProc, except for those previously
673 : : * initialized by ProcGlobalShmemInit.
674 : : */
74 heikki.linnakangas@i 675 :GNC 4369 : dlist_node_init(&MyProc->freeProcsLink);
2148 peter@eisentraut.org 676 :CBC 4369 : MyProc->waitStatus = PROC_WAIT_STATUS_OK;
4905 simon@2ndQuadrant.co 677 : 4369 : MyProc->fpVXIDLock = false;
678 : 4369 : MyProc->fpLocalTransactionId = InvalidLocalTransactionId;
2090 andres@anarazel.de 679 : 4369 : MyProc->xid = InvalidTransactionId;
2091 680 : 4369 : MyProc->xmin = InvalidTransactionId;
793 heikki.linnakangas@i 681 : 4369 : MyProc->vxid.procNumber = INVALID_PROC_NUMBER;
682 : 4369 : MyProc->vxid.lxid = InvalidLocalTransactionId;
7426 tgl@sss.pgh.pa.us 683 : 4369 : MyProc->databaseId = InvalidOid;
7583 684 : 4369 : MyProc->roleId = InvalidOid;
2822 michael@paquier.xyz 685 : 4369 : MyProc->tempNamespaceId = InvalidOid;
90 heikki.linnakangas@i 686 :GNC 4369 : MyProc->backendType = MyBackendType;
1488 rhaas@postgresql.org 687 :CBC 4369 : MyProc->delayChkptFlags = 0;
1996 alvherre@alvh.no-ip. 688 : 4369 : MyProc->statusFlags = 0;
1262 andres@anarazel.de 689 : 4369 : MyProc->lwWaiting = LW_WS_NOT_WAITING;
5209 heikki.linnakangas@i 690 : 4369 : MyProc->lwWaitMode = 0;
8984 tgl@sss.pgh.pa.us 691 : 4369 : MyProc->waitLock = NULL;
74 heikki.linnakangas@i 692 :GNC 4369 : dlist_node_init(&MyProc->waitLink);
7921 tgl@sss.pgh.pa.us 693 :CBC 4369 : MyProc->waitProcLock = NULL;
1898 fujii@postgresql.org 694 : 4369 : 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. */
5299 rhaas@postgresql.org 700 [ + + ]: 74273 : for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
1203 andres@anarazel.de 701 [ - + ]: 69904 : Assert(dlist_is_empty(&(MyProc->myProcLocks[i])));
702 : : }
703 : : #endif
55 heikki.linnakangas@i 704 :GNC 4369 : 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 : : */
5382 tgl@sss.pgh.pa.us 711 :CBC 4369 : OwnLatch(&MyProc->procLatch);
4129 andres@anarazel.de 712 : 4369 : SwitchToSharedLatch();
713 : :
714 : : /* now that we have a proc, report wait events to shared memory */
1858 715 : 4369 : pgstat_set_wait_event_storage(&MyProc->wait_event_info);
716 : :
717 : : /* Check that group locking fields are in a proper initial state. */
3740 rhaas@postgresql.org 718 [ - + ]: 4369 : Assert(MyProc->lockGroupLeader == NULL);
719 [ - + ]: 4369 : 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 : : */
3431 tgl@sss.pgh.pa.us 726 : 4369 : PGSemaphoreReset(MyProc->sem);
727 : :
728 : : /*
729 : : * Arrange to clean up at process exit.
730 : : */
6999 alvherre@alvh.no-ip. 731 : 4369 : 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 : : */
886 heikki.linnakangas@i 738 : 4369 : 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
10892 scrappy@hub.org 749 : 4369 : }
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
5946 simon@2ndQuadrant.co 759 : 22 : SetStartupBufferPinWaitBufId(int bufid)
760 : : {
761 : : /* use volatile pointer to prevent code rearrangement */
762 : 22 : volatile PROC_HDR *procglobal = ProcGlobal;
763 : :
764 : 22 : procglobal->startupBufferPinWaitBufId = bufid;
765 : 22 : }
766 : :
767 : : /*
768 : : * Used by backends when they receive a request to check for buffer pin waits.
769 : : */
770 : : int
771 : 4 : GetStartupBufferPinWaitBufId(void)
772 : : {
773 : : /* use volatile pointer to prevent code rearrangement */
774 : 4 : volatile PROC_HDR *procglobal = ProcGlobal;
775 : :
5390 tgl@sss.pgh.pa.us 776 : 4 : 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
1201 rhaas@postgresql.org 787 : 402 : HaveNFreeProcs(int n, int *nfree)
788 : : {
789 : : dlist_iter iter;
790 : :
791 [ - + ]: 402 : Assert(n > 0);
792 [ - + ]: 402 : Assert(nfree);
793 : :
83 heikki.linnakangas@i 794 :GNC 402 : SpinLockAcquire(&ProcGlobal->freeProcsLock);
795 : :
1201 rhaas@postgresql.org 796 :CBC 402 : *nfree = 0;
1203 andres@anarazel.de 797 [ + - + + ]: 1204 : dlist_foreach(iter, &ProcGlobal->freeProcs)
798 : : {
1201 rhaas@postgresql.org 799 : 1202 : (*nfree)++;
800 [ + + ]: 1202 : if (*nfree == n)
1203 andres@anarazel.de 801 : 400 : break;
802 : : }
803 : :
83 heikki.linnakangas@i 804 :GNC 402 : SpinLockRelease(&ProcGlobal->freeProcsLock);
805 : :
1201 rhaas@postgresql.org 806 :CBC 402 : 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
5130 818 : 464867 : LockErrorCleanup(void)
819 : : {
820 : : LOCALLOCK *lockAwaited;
821 : : LWLock *partitionLock;
822 : : DisableTimeoutParams timeouts[2];
823 : :
4110 heikki.linnakangas@i 824 : 464867 : HOLD_INTERRUPTS();
825 : :
5130 rhaas@postgresql.org 826 : 464867 : AbortStrongLockAcquire();
827 : :
828 : : /* Nothing to do if we weren't waiting for a lock */
547 heikki.linnakangas@i 829 : 464867 : lockAwaited = GetAwaitedLock();
7450 tgl@sss.pgh.pa.us 830 [ + + ]: 464867 : if (lockAwaited == NULL)
831 : : {
4110 heikki.linnakangas@i 832 [ - + ]: 464827 : RESUME_INTERRUPTS();
6674 tgl@sss.pgh.pa.us 833 : 464827 : 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 : : */
4798 844 : 40 : timeouts[0].id = DEADLOCK_TIMEOUT;
845 : 40 : timeouts[0].keep_indicator = false;
846 : 40 : timeouts[1].id = LOCK_TIMEOUT;
847 : 40 : timeouts[1].keep_indicator = true;
848 : 40 : disable_timeouts(timeouts, 2);
849 : :
850 : : /* Unlink myself from the wait queue, if on it (might not be anymore!) */
7226 851 : 40 : partitionLock = LockHashPartitionLock(lockAwaited->hashcode);
7450 852 : 40 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
853 : :
74 heikki.linnakangas@i 854 [ + + ]:GNC 40 : if (!dlist_node_is_detached(&MyProc->waitLink))
855 : : {
856 : : /* We could not have been granted the lock yet */
7226 tgl@sss.pgh.pa.us 857 :CBC 39 : 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 : : */
2148 peter@eisentraut.org 867 [ + - ]: 1 : if (MyProc->waitStatus == PROC_WAIT_STATUS_OK)
7921 tgl@sss.pgh.pa.us 868 : 1 : GrantAwaitedLock();
869 : : }
870 : :
403 heikki.linnakangas@i 871 : 40 : ResetAwaitedLock();
872 : :
7450 tgl@sss.pgh.pa.us 873 : 40 : LWLockRelease(partitionLock);
874 : :
4110 heikki.linnakangas@i 875 [ - + ]: 40 : 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
7962 tgl@sss.pgh.pa.us 896 : 423311 : ProcReleaseLocks(bool isCommit)
897 : : {
10467 bruce@momjian.us 898 [ - + ]: 423311 : if (!MyProc)
10467 bruce@momjian.us 899 :UBC 0 : return;
900 : : /* If waiting, get off wait queue (should only be needed after error) */
5130 rhaas@postgresql.org 901 :CBC 423311 : LockErrorCleanup();
902 : : /* Release standard locks, including session-level if aborting */
7921 tgl@sss.pgh.pa.us 903 : 423311 : LockReleaseAll(DEFAULT_LOCKMETHOD, !isCommit);
904 : : /* Release transaction-level advisory locks */
5555 itagaki.takahiro@gma 905 : 423311 : LockReleaseAll(USER_LOCKMETHOD, false);
906 : : }
907 : :
908 : :
909 : : /*
910 : : * RemoveProcFromArray() -- Remove this process from the shared ProcArray.
911 : : */
912 : : static void
7426 tgl@sss.pgh.pa.us 913 : 18588 : RemoveProcFromArray(int code, Datum arg)
914 : : {
915 [ - + ]: 18588 : Assert(MyProc != NULL);
6814 916 : 18588 : ProcArrayRemove(MyProc, InvalidTransactionId);
7426 917 : 18588 : }
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
8180 peter_e@gmx.net 924 : 18601 : ProcKill(int code, Datum arg)
925 : : {
926 : : PGPROC *proc;
927 : : dlist_head *procgloballist;
928 : :
9006 tgl@sss.pgh.pa.us 929 [ - + ]: 18601 : Assert(MyProc != NULL);
930 : :
931 : : /* not safe if forked by system(), etc. */
931 nathan@postgresql.or 932 [ - + ]: 18601 : if (MyProc->pid != (int) getpid())
931 nathan@postgresql.or 933 [ # # ]:UBC 0 : elog(PANIC, "ProcKill() called in child process");
934 : :
935 : : /* Make sure we're out of the sync rep lists */
5382 tgl@sss.pgh.pa.us 936 :CBC 18601 : SyncRepCleanupAtProcExit();
937 : :
938 : : #ifdef USE_ASSERT_CHECKING
939 : : {
940 : : int i;
941 : :
942 : : /* Last process should have released all locks. */
5299 rhaas@postgresql.org 943 [ + + ]: 316217 : for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
1203 andres@anarazel.de 944 [ - + ]: 297616 : 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 : : */
7575 tgl@sss.pgh.pa.us 953 : 18601 : LWLockReleaseAll();
954 : :
955 : : /*
956 : : * Cleanup waiting for LSN if any.
957 : : */
181 akorotkov@postgresql 958 :GNC 18601 : WaitLSNCleanup();
959 : :
960 : : /* Cancel any pending condition variable sleep, too */
3451 rhaas@postgresql.org 961 :CBC 18601 : 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 : : */
3740 969 [ + + ]: 18601 : if (MyProc->lockGroupLeader != NULL)
970 : : {
971 : 2132 : PGPROC *leader = MyProc->lockGroupLeader;
972 : 2132 : LWLock *leader_lwlock = LockHashPartitionLockByProc(leader);
973 : :
974 : 2132 : LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
975 [ - + ]: 2132 : Assert(!dlist_is_empty(&leader->lockGroupMembers));
976 : 2132 : dlist_delete(&MyProc->lockGroupLink);
977 [ + + ]: 2132 : if (dlist_is_empty(&leader->lockGroupMembers))
978 : : {
979 : 121 : leader->lockGroupLeader = NULL;
980 [ - + ]: 121 : if (leader != MyProc)
981 : : {
3740 rhaas@postgresql.org 982 :UBC 0 : procgloballist = leader->procgloballist;
983 : :
984 : : /* Leader exited first; return its PGPROC. */
83 heikki.linnakangas@i 985 :UNC 0 : SpinLockAcquire(&ProcGlobal->freeProcsLock);
74 986 : 0 : dlist_push_head(procgloballist, &leader->freeProcsLink);
83 987 : 0 : SpinLockRelease(&ProcGlobal->freeProcsLock);
988 : : }
989 : : }
3740 rhaas@postgresql.org 990 [ + - ]:CBC 2011 : else if (leader != MyProc)
991 : 2011 : MyProc->lockGroupLeader = NULL;
992 : 2132 : 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 : : */
4129 andres@anarazel.de 1004 : 18601 : SwitchBackToLocalLatch();
1858 1005 : 18601 : pgstat_reset_wait_event_storage();
1006 : :
4477 rhaas@postgresql.org 1007 : 18601 : proc = MyProc;
1008 : 18601 : MyProc = NULL;
793 heikki.linnakangas@i 1009 : 18601 : MyProcNumber = INVALID_PROC_NUMBER;
4477 rhaas@postgresql.org 1010 : 18601 : DisownLatch(&proc->procLatch);
1011 : :
1012 : : /* Mark the proc no longer in use */
793 heikki.linnakangas@i 1013 : 18601 : proc->pid = 0;
1014 : 18601 : proc->vxid.procNumber = INVALID_PROC_NUMBER;
1015 : 18601 : proc->vxid.lxid = InvalidTransactionId;
1016 : :
3934 rhaas@postgresql.org 1017 : 18601 : procgloballist = proc->procgloballist;
83 heikki.linnakangas@i 1018 :GNC 18601 : 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 : : */
3740 rhaas@postgresql.org 1025 [ + - ]:CBC 18601 : if (proc->lockGroupLeader == NULL)
1026 : : {
1027 : : /* Since lockGroupLeader is NULL, lockGroupMembers should be empty. */
1028 [ - + ]: 18601 : Assert(dlist_is_empty(&proc->lockGroupMembers));
1029 : :
1030 : : /* Return PGPROC structure (and semaphore) to appropriate freelist */
74 heikki.linnakangas@i 1031 :GNC 18601 : dlist_push_tail(procgloballist, &proc->freeProcsLink);
1032 : : }
1033 : :
1034 : : /* Update shared estimate of spins_per_delay */
3854 rhaas@postgresql.org 1035 :CBC 18601 : ProcGlobal->spins_per_delay = update_spins_per_delay(ProcGlobal->spins_per_delay);
1036 : :
83 heikki.linnakangas@i 1037 :GNC 18601 : SpinLockRelease(&ProcGlobal->freeProcsLock);
8984 tgl@sss.pgh.pa.us 1038 :CBC 18601 : }
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
6999 alvherre@alvh.no-ip. 1046 : 4369 : AuxiliaryProcKill(int code, Datum arg)
1047 : : {
7919 bruce@momjian.us 1048 : 4369 : int proctype = DatumGetInt32(arg);
1049 : : PGPROC *auxproc PG_USED_FOR_ASSERTS_ONLY;
1050 : : PGPROC *proc;
1051 : :
6999 alvherre@alvh.no-ip. 1052 [ + - - + ]: 4369 : Assert(proctype >= 0 && proctype < NUM_AUXILIARY_PROCS);
1053 : :
1054 : : /* not safe if forked by system(), etc. */
931 nathan@postgresql.or 1055 [ - + ]: 4369 : if (MyProc->pid != (int) getpid())
931 nathan@postgresql.or 1056 [ # # ]:UBC 0 : elog(PANIC, "AuxiliaryProcKill() called in child process");
1057 : :
6999 alvherre@alvh.no-ip. 1058 :CBC 4369 : auxproc = &AuxiliaryProcs[proctype];
1059 : :
1060 [ - + ]: 4369 : Assert(MyProc == auxproc);
1061 : :
1062 : : /* Release any LW locks I am holding (see notes above) */
8984 tgl@sss.pgh.pa.us 1063 : 4369 : LWLockReleaseAll();
1064 : :
1065 : : /* Cancel any pending condition variable sleep, too */
3451 rhaas@postgresql.org 1066 : 4369 : ConditionVariableCancelSleep();
1067 : :
1068 : : /* look at the equivalent ProcKill() code for comments */
4129 andres@anarazel.de 1069 : 4369 : SwitchBackToLocalLatch();
1858 1070 : 4369 : pgstat_reset_wait_event_storage();
1071 : :
4477 rhaas@postgresql.org 1072 : 4369 : proc = MyProc;
1073 : 4369 : MyProc = NULL;
793 heikki.linnakangas@i 1074 : 4369 : MyProcNumber = INVALID_PROC_NUMBER;
4477 rhaas@postgresql.org 1075 : 4369 : DisownLatch(&proc->procLatch);
1076 : :
83 heikki.linnakangas@i 1077 :GNC 4369 : SpinLockAcquire(&ProcGlobal->freeProcsLock);
1078 : :
1079 : : /* Mark auxiliary proc no longer in use */
4477 rhaas@postgresql.org 1080 :CBC 4369 : proc->pid = 0;
793 heikki.linnakangas@i 1081 : 4369 : proc->vxid.procNumber = INVALID_PROC_NUMBER;
1082 : 4369 : proc->vxid.lxid = InvalidTransactionId;
1083 : :
1084 : : /* Update shared estimate of spins_per_delay */
7511 tgl@sss.pgh.pa.us 1085 : 4369 : ProcGlobal->spins_per_delay = update_spins_per_delay(ProcGlobal->spins_per_delay);
1086 : :
83 heikki.linnakangas@i 1087 :GNC 4369 : SpinLockRelease(&ProcGlobal->freeProcsLock);
10892 scrappy@hub.org 1088 :CBC 4369 : }
1089 : :
1090 : : /*
1091 : : * AuxiliaryPidGetProc -- get PGPROC for an auxiliary process
1092 : : * given its PID
1093 : : *
1094 : : * Returns NULL if not found.
1095 : : */
1096 : : PGPROC *
3327 rhaas@postgresql.org 1097 : 4322 : AuxiliaryPidGetProc(int pid)
1098 : : {
1099 : 4322 : PGPROC *result = NULL;
1100 : : int index;
1101 : :
1102 [ + + ]: 4322 : if (pid == 0) /* never match dummy PGPROCs */
1103 : 4 : return NULL;
1104 : :
1105 [ + - ]: 17658 : for (index = 0; index < NUM_AUXILIARY_PROCS; index++)
1106 : : {
1107 : 17658 : PGPROC *proc = &AuxiliaryProcs[index];
1108 : :
1109 [ + + ]: 17658 : if (proc->pid == pid)
1110 : : {
1111 : 4318 : result = proc;
1112 : 4318 : break;
1113 : : }
1114 : : }
1115 : 4318 : 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
547 heikki.linnakangas@i 1146 : 2318 : JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
1147 : : {
7450 tgl@sss.pgh.pa.us 1148 : 2318 : LOCKMODE lockmode = locallock->tag.mode;
1149 : 2318 : LOCK *lock = locallock->lock;
1150 : 2318 : PROCLOCK *proclock = locallock->proclock;
7226 1151 : 2318 : uint32 hashcode = locallock->hashcode;
547 heikki.linnakangas@i 1152 : 2318 : LWLock *partitionLock PG_USED_FOR_ASSERTS_ONLY = LockHashPartitionLock(hashcode);
1203 andres@anarazel.de 1153 : 2318 : dclist_head *waitQueue = &lock->waitProcs;
1082 tgl@sss.pgh.pa.us 1154 : 2318 : PGPROC *insert_before = NULL;
1155 : : LOCKMASK myProcHeldLocks;
1156 : : LOCKMASK myHeldLocks;
9009 1157 : 2318 : bool early_deadlock = false;
3740 rhaas@postgresql.org 1158 : 2318 : PGPROC *leader = MyProc->lockGroupLeader;
1159 : :
547 heikki.linnakangas@i 1160 [ - + ]: 2318 : Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
1161 : :
1162 : : /*
1163 : : * Set bitmask of locks this process already holds on this object.
1164 : : */
1165 : 2318 : 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 : 2318 : myProcHeldLocks = proclock->holdMask;
1180 : 2318 : myHeldLocks = myProcHeldLocks;
3740 rhaas@postgresql.org 1181 [ + + ]: 2318 : if (leader != NULL)
1182 : : {
1183 : : dlist_iter iter;
1184 : :
1203 andres@anarazel.de 1185 [ + - + + ]: 36 : dlist_foreach(iter, &lock->procLocks)
1186 : : {
1187 : : PROCLOCK *otherproclock;
1188 : :
1189 : 27 : otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
1190 : :
3740 rhaas@postgresql.org 1191 [ + + ]: 27 : if (otherproclock->groupLeader == leader)
1192 : 13 : 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 : : */
1203 andres@anarazel.de 1213 [ + + + + ]: 2318 : if (myHeldLocks != 0 && !dclist_is_empty(waitQueue))
1214 : : {
8191 bruce@momjian.us 1215 : 8 : LOCKMASK aheadRequests = 0;
1216 : : dlist_iter iter;
1217 : :
1203 andres@anarazel.de 1218 [ + - + - ]: 8 : dclist_foreach(iter, waitQueue)
1219 : : {
74 heikki.linnakangas@i 1220 :GNC 8 : 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 : : */
3740 rhaas@postgresql.org 1227 [ - + - - ]:CBC 8 : if (leader != NULL && leader == proc->lockGroupLeader)
3740 rhaas@postgresql.org 1228 :UBC 0 : continue;
1229 : :
1230 : : /* Must he wait for me? */
8692 bruce@momjian.us 1231 [ + - ]:CBC 8 : if (lockMethodTable->conflictTab[proc->waitLockMode] & myHeldLocks)
1232 : : {
1233 : : /* Must I wait for him ? */
1234 [ + + ]: 8 : 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 : : */
8510 tgl@sss.pgh.pa.us 1243 : 1 : RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
9009 1244 : 1 : early_deadlock = true;
1245 : 1 : break;
1246 : : }
1247 : : /* I must go before this waiter. Check special case. */
8692 bruce@momjian.us 1248 [ + - ]: 7 : if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
2319 peter@eisentraut.org 1249 [ + - ]: 7 : !LockCheckConflicts(lockMethodTable, lockmode, lock,
1250 : : proclock))
1251 : : {
1252 : : /* Skip the wait and just grant myself the lock. */
8477 bruce@momjian.us 1253 : 7 : GrantLock(lock, proclock, lockmode);
2148 peter@eisentraut.org 1254 : 7 : return PROC_WAIT_STATUS_OK;
1255 : : }
1256 : :
1257 : : /* Put myself into wait queue before conflicting process */
1203 andres@anarazel.de 1258 :UBC 0 : insert_before = proc;
9860 vadim4o@yahoo.com 1259 : 0 : break;
1260 : : }
1261 : : /* Nope, so advance to next waiter */
8191 bruce@momjian.us 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 : : */
547 heikki.linnakangas@i 1270 [ + + ]:CBC 2311 : 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 : : */
782 rhaas@postgresql.org 1277 [ + + ]: 2310 : if (dontWait)
1278 : 763 : return PROC_WAIT_STATUS_ERROR;
1279 : :
1280 : : /*
1281 : : * Insert self into queue, at the position determined above.
1282 : : */
1203 andres@anarazel.de 1283 [ - + ]: 1547 : if (insert_before)
74 heikki.linnakangas@i 1284 :UNC 0 : dclist_insert_before(waitQueue, &insert_before->waitLink, &MyProc->waitLink);
1285 : : else
74 heikki.linnakangas@i 1286 :GNC 1547 : dclist_push_tail(waitQueue, &MyProc->waitLink);
1287 : :
8191 bruce@momjian.us 1288 :CBC 1547 : lock->waitMask |= LOCKBIT_ON(lockmode);
1289 : :
1290 : : /* Set up wait information in PGPROC object, too */
547 heikki.linnakangas@i 1291 : 1547 : MyProc->heldLocks = myProcHeldLocks;
9234 tgl@sss.pgh.pa.us 1292 : 1547 : MyProc->waitLock = lock;
7921 1293 : 1547 : MyProc->waitProcLock = proclock;
9234 1294 : 1547 : MyProc->waitLockMode = lockmode;
1295 : :
2148 peter@eisentraut.org 1296 : 1547 : MyProc->waitStatus = PROC_WAIT_STATUS_WAITING;
1297 : :
547 heikki.linnakangas@i 1298 : 1547 : 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 : 1547 : ProcSleep(LOCALLOCK *locallock)
1316 : : {
1317 : 1547 : LOCKMODE lockmode = locallock->tag.mode;
1318 : 1547 : LOCK *lock = locallock->lock;
1319 : 1547 : uint32 hashcode = locallock->hashcode;
1320 : 1547 : LWLock *partitionLock = LockHashPartitionLock(hashcode);
1321 : 1547 : TimestampTz standbyWaitStart = 0;
1322 : 1547 : bool allow_autovacuum_cancel = true;
1323 : 1547 : bool logged_recovery_conflict = false;
50 fujii@postgresql.org 1324 :GNC 1547 : bool logged_lock_wait = false;
1325 : : ProcWaitStatus myWaitStatus;
1326 : : DeadLockState deadlock_state;
1327 : :
1328 : : /* The caller must've armed the on-error cleanup mechanism */
547 heikki.linnakangas@i 1329 [ - + ]:CBC 1547 : Assert(GetAwaitedLock() == locallock);
1330 [ - + ]: 1547 : 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 : : */
5390 tgl@sss.pgh.pa.us 1338 [ + + + + ]: 1547 : if (RecoveryInProgress() && !InRecovery)
1339 : 1 : CheckRecoveryConflictDeadlock();
1340 : :
1341 : : /* Reset deadlock_state before enabling the timeout handler */
6895 1342 : 1547 : deadlock_state = DS_NOT_YET_CHECKED;
4109 andres@anarazel.de 1343 : 1547 : 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 : : */
3708 simon@2ndQuadrant.co 1360 [ + + ]: 1547 : if (!InHotStandby)
1361 : : {
1362 [ + + ]: 1546 : if (LockTimeout > 0)
1363 : : {
1364 : : EnableTimeoutParams timeouts[2];
1365 : :
1366 : 109 : timeouts[0].id = DEADLOCK_TIMEOUT;
1367 : 109 : timeouts[0].type = TMPARAM_AFTER;
1368 : 109 : timeouts[0].delay_ms = DeadlockTimeout;
1369 : 109 : timeouts[1].id = LOCK_TIMEOUT;
1370 : 109 : timeouts[1].type = TMPARAM_AFTER;
1371 : 109 : timeouts[1].delay_ms = LockTimeout;
1372 : 109 : enable_timeouts(timeouts, 2);
1373 : : }
1374 : : else
1375 : 1437 : 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 : : */
1905 fujii@postgresql.org 1391 : 1546 : pg_atomic_write_u64(&MyProc->waitStart,
1392 : 1546 : get_timeout_start_time(DEADLOCK_TIMEOUT));
1393 : : }
1943 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 : : {
3708 simon@2ndQuadrant.co 1419 [ + + ]: 2636 : if (InHotStandby)
1420 : : {
1943 fujii@postgresql.org 1421 : 3 : bool maybe_log_conflict =
1082 tgl@sss.pgh.pa.us 1422 [ + - + + ]: 3 : (standbyWaitStart != 0 && !logged_recovery_conflict);
1423 : :
1424 : : /* Set a timer and wait for that or for the lock to be granted */
1943 fujii@postgresql.org 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 : : */
84 heikki.linnakangas@i 1452 :GNC 1 : LogRecoveryConflict(RECOVERY_CONFLICT_LOCK,
1453 : : standbyWaitStart, now,
1938 fujii@postgresql.org 1454 [ + - ]:CBC 1 : cnt > 0 ? vxids : NULL, true);
1943 1455 : 1 : logged_recovery_conflict = true;
1456 : : }
1457 : : }
1458 : : }
1459 : : else
1460 : : {
2720 tmunro@postgresql.or 1461 : 2633 : (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH, 0,
1462 : 2633 : PG_WAIT_LOCK | locallock->tag.lock.locktag_type);
3708 simon@2ndQuadrant.co 1463 : 2633 : ResetLatch(MyLatch);
1464 : : /* check for deadlocks first, as that's probably log-worthy */
1465 [ + + ]: 2633 : if (got_deadlock_timeout)
1466 : : {
85 heikki.linnakangas@i 1467 :GNC 45 : deadlock_state = CheckDeadLock();
3708 simon@2ndQuadrant.co 1468 :CBC 45 : got_deadlock_timeout = false;
1469 : : }
1470 [ + + ]: 2633 : 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 : : */
2148 peter@eisentraut.org 1478 : 2594 : 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 : : */
6766 alvherre@alvh.no-ip. 1484 [ - + - - ]: 2594 : if (deadlock_state == DS_BLOCKED_BY_AUTOVACUUM && allow_autovacuum_cancel)
1485 : : {
6746 bruce@momjian.us 1486 :UBC 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 : : */
6766 alvherre@alvh.no-ip. 1500 : 0 : LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
1989 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 : : */
1996 1510 [ # # ]: 0 : if ((statusFlags & PROC_IS_AUTOVACUUM) &&
1511 [ # # ]: 0 : !(statusFlags & PROC_VACUUM_FOR_WRAPAROUND))
1512 : : {
6746 bruce@momjian.us 1513 : 0 : int pid = autovac->pid;
1514 : :
1515 : : /* report the case, if configured to do so */
1989 tgl@sss.pgh.pa.us 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 */
6766 alvherre@alvh.no-ip. 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 : : */
3934 tgl@sss.pgh.pa.us 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 */
6766 alvherre@alvh.no-ip. 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 : : */
42 michael@paquier.xyz 1568 [ + + ]:GNC 2594 : if (deadlock_state != DS_NOT_YET_CHECKED)
1569 : : {
1570 : : long secs;
1571 : : int usecs;
1572 : : long msecs;
1573 : :
29 1574 : 997 : INJECTION_POINT("deadlock-timeout-fired", NULL);
5041 alvherre@alvh.no-ip. 1575 :CBC 997 : TimestampDifference(get_timeout_start_time(DEADLOCK_TIMEOUT),
1576 : : GetCurrentTimestamp(),
1577 : : &secs, &usecs);
6825 tgl@sss.pgh.pa.us 1578 : 997 : msecs = secs * 1000 + usecs / 1000;
1579 : 997 : usecs = usecs % 1000;
1580 : :
1581 : : /* Increment the lock statistics counters if done waiting. */
42 michael@paquier.xyz 1582 [ + + ]:GNC 997 : if (myWaitStatus == PROC_WAIT_STATUS_OK)
1583 : 38 : pgstat_count_lock_waits(locallock->tag.lock.locktag_type, msecs);
1584 : :
1585 [ + + ]: 997 : if (log_lock_waits)
1586 : : {
1587 : : StringInfoData buf,
1588 : : lock_waiters_sbuf,
1589 : : lock_holders_sbuf;
1590 : : const char *modename;
1591 : 995 : int lockHoldersNum = 0;
1592 : :
1593 : 995 : initStringInfo(&buf);
1594 : 995 : initStringInfo(&lock_waiters_sbuf);
1595 : 995 : initStringInfo(&lock_holders_sbuf);
1596 : :
1597 : 995 : DescribeLockTag(&buf, &locallock->tag.lock);
1598 : 995 : modename = GetLockmodeName(locallock->tag.lock.locktag_lockmethodid,
1599 : : lockmode);
1600 : :
1601 : : /* Gather a list of all lock holders and waiters */
1602 : 995 : LWLockAcquire(partitionLock, LW_SHARED);
1603 : 995 : GetLockHoldersAndWaiters(locallock, &lock_holders_sbuf,
1604 : : &lock_waiters_sbuf, &lockHoldersNum);
1605 : 995 : LWLockRelease(partitionLock);
1606 : :
1607 [ + + ]: 995 : if (deadlock_state == DS_SOFT_DEADLOCK)
50 fujii@postgresql.org 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))));
42 michael@paquier.xyz 1614 [ + + ]: 992 : 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 : : */
6825 tgl@sss.pgh.pa.us 1623 [ + - ]:GBC 5 : 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 : :
42 michael@paquier.xyz 1631 [ + + ]:GNC 995 : 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 [ + + ]: 953 : if (!logged_lock_wait)
1646 : : {
1647 [ + - ]: 36 : 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 : 36 : logged_lock_wait = true;
1654 : : }
1655 : : }
1656 [ + + ]: 42 : else if (myWaitStatus == PROC_WAIT_STATUS_OK)
1657 [ + - ]: 37 : 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 [ - + ]: 5 : 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 [ - + ]: 5 : if (deadlock_state != DS_HARD_DEADLOCK)
42 michael@paquier.xyz 1674 [ # # ]:UNC 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 : : }
42 michael@paquier.xyz 1681 :GNC 995 : pfree(buf.data);
1682 : 995 : pfree(lock_holders_sbuf.data);
1683 : 995 : 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 : : */
6825 tgl@sss.pgh.pa.us 1691 :CBC 997 : deadlock_state = DS_NO_DEADLOCK;
1692 : : }
2148 peter@eisentraut.org 1693 [ + + ]: 2594 : } 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 : : */
3708 simon@2ndQuadrant.co 1701 [ + + ]: 1505 : if (!InHotStandby)
1702 : : {
1703 [ + + ]: 1504 : if (LockTimeout > 0)
1704 : : {
1705 : : DisableTimeoutParams timeouts[2];
1706 : :
1707 : 103 : timeouts[0].id = DEADLOCK_TIMEOUT;
1708 : 103 : timeouts[0].keep_indicator = false;
1709 : 103 : timeouts[1].id = LOCK_TIMEOUT;
1710 : 103 : timeouts[1].keep_indicator = true;
1711 : 103 : disable_timeouts(timeouts, 2);
1712 : : }
1713 : : else
1714 : 1401 : 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 : : */
1938 fujii@postgresql.org 1721 [ + + + - ]: 1505 : if (InHotStandby && logged_recovery_conflict)
84 heikki.linnakangas@i 1722 :GNC 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 : : */
547 heikki.linnakangas@i 1731 :CBC 1505 : 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
2148 peter@eisentraut.org 1748 : 1503 : ProcWakeup(PGPROC *proc, ProcWaitStatus waitStatus)
1749 : : {
74 heikki.linnakangas@i 1750 [ - + ]:GNC 1503 : if (dlist_node_is_detached(&proc->waitLink))
1203 andres@anarazel.de 1751 :UBC 0 : return;
1752 : :
2148 peter@eisentraut.org 1753 [ - + ]:CBC 1503 : Assert(proc->waitStatus == PROC_WAIT_STATUS_WAITING);
1754 : :
1755 : : /* Remove process from wait queue */
74 heikki.linnakangas@i 1756 :GNC 1503 : dclist_delete_from_thoroughly(&proc->waitLock->waitProcs, &proc->waitLink);
1757 : :
1758 : : /* Clean up process' state and pass it the ok/fail signal */
9234 tgl@sss.pgh.pa.us 1759 :CBC 1503 : proc->waitLock = NULL;
7921 1760 : 1503 : proc->waitProcLock = NULL;
7962 1761 : 1503 : proc->waitStatus = waitStatus;
68 fujii@postgresql.org 1762 : 1503 : pg_atomic_write_u64(&proc->waitStart, 0);
1763 : :
1764 : : /* And awaken it */
4109 andres@anarazel.de 1765 : 1503 : 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
8191 bruce@momjian.us 1776 : 1505 : ProcLockWakeup(LockMethod lockMethodTable, LOCK *lock)
1777 : : {
1203 andres@anarazel.de 1778 : 1505 : dclist_head *waitQueue = &lock->waitProcs;
8191 bruce@momjian.us 1779 : 1505 : LOCKMASK aheadRequests = 0;
1780 : : dlist_mutable_iter miter;
1781 : :
1203 andres@anarazel.de 1782 [ + + ]: 1505 : if (dclist_is_empty(waitQueue))
9231 tgl@sss.pgh.pa.us 1783 : 44 : return;
1784 : :
1203 andres@anarazel.de 1785 [ + - + + ]: 3678 : dclist_foreach_modify(miter, waitQueue)
1786 : : {
74 heikki.linnakangas@i 1787 :GNC 2217 : PGPROC *proc = dlist_container(PGPROC, waitLink, miter.cur);
9175 bruce@momjian.us 1788 :CBC 2217 : 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 : : */
8692 1794 [ + + ]: 2217 : if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
2319 peter@eisentraut.org 1795 [ + + ]: 1812 : !LockCheckConflicts(lockMethodTable, lockmode, lock,
1796 : : proc->waitProcLock))
1797 : : {
1798 : : /* OK to waken */
7921 tgl@sss.pgh.pa.us 1799 : 1503 : GrantLock(lock, proc->waitProcLock, lockmode);
1800 : : /* removes proc from the lock's waiting process queue */
1203 andres@anarazel.de 1801 : 1503 : 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 : : */
8191 bruce@momjian.us 1809 : 714 : 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
8697 1823 : 45 : 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 : : */
7450 tgl@sss.pgh.pa.us 1838 [ + + ]: 765 : for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
4481 rhaas@postgresql.org 1839 : 720 : 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 : : */
74 heikki.linnakangas@i 1851 [ + + ]:GNC 45 : if (dlist_node_is_detached(&MyProc->waitLink))
1852 : : {
85 1853 : 2 : result = DS_NO_DEADLOCK;
6895 tgl@sss.pgh.pa.us 1854 :CBC 2 : goto check_done;
1855 : : }
1856 : :
1857 : : #ifdef LOCK_DEBUG
1858 : : if (Debug_deadlocks)
1859 : : DumpAllLocks();
1860 : : #endif
1861 : :
1862 : : /* Run the deadlock check */
85 heikki.linnakangas@i 1863 :GNC 43 : result = DeadLockCheck(MyProc);
1864 : :
1865 [ + + ]: 43 : 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 : : */
7003 bruce@momjian.us 1879 [ - + ]:CBC 5 : Assert(MyProc->waitLock != NULL);
1880 : 5 : 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 : : */
6895 tgl@sss.pgh.pa.us 1901 : 38 : check_done:
7153 bruce@momjian.us 1902 [ + + ]: 765 : for (i = NUM_LOCK_PARTITIONS; --i >= 0;)
4481 rhaas@postgresql.org 1903 : 720 : LWLockRelease(LockHashPartitionLockByIndex(i));
1904 : :
85 heikki.linnakangas@i 1905 :GNC 45 : return result;
10892 scrappy@hub.org 1906 :ECB (33) : }
1907 : :
1908 : : /*
1909 : : * CheckDeadLockAlert - Handle the expiry of deadlock_timeout.
1910 : : *
1911 : : * NB: Runs inside a signal handler, be careful.
1912 : : */
1913 : : void
4109 andres@anarazel.de 1914 :CBC 46 : CheckDeadLockAlert(void)
1915 : : {
1916 : 46 : int save_errno = errno;
1917 : :
1918 : 46 : 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 : 46 : SetLatch(MyLatch);
1929 : 46 : errno = save_errno;
1930 : 46 : }
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
417 fujii@postgresql.org 1941 : 995 : GetLockHoldersAndWaiters(LOCALLOCK *locallock, StringInfo lock_holders_sbuf,
1942 : : StringInfo lock_waiters_sbuf, int *lockHoldersNum)
1943 : : {
1944 : : dlist_iter proc_iter;
1945 : : PROCLOCK *curproclock;
1946 : 995 : LOCK *lock = locallock->lock;
1947 : 995 : bool first_holder = true,
1948 : 995 : first_waiter = true;
1949 : :
1950 : : #ifdef USE_ASSERT_CHECKING
1951 : : {
1952 : 995 : uint32 hashcode = locallock->hashcode;
1953 : 995 : LWLock *partitionLock = LockHashPartitionLock(hashcode);
1954 : :
1955 [ - + ]: 995 : Assert(LWLockHeldByMe(partitionLock));
1956 : : }
1957 : : #endif
1958 : :
1959 : 995 : *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 [ + - + + ]: 2968 : dlist_foreach(proc_iter, &lock->procLocks)
1970 : : {
1971 : 1973 : curproclock =
1972 : 1973 : 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 [ + + ]: 1973 : if (curproclock->tag.myProc->waitProcLock == curproclock)
1979 : : {
1980 [ + + ]: 971 : if (first_waiter)
1981 : : {
1982 : 954 : appendStringInfo(lock_waiters_sbuf, "%d",
1983 : 954 : curproclock->tag.myProc->pid);
1984 : 954 : first_waiter = false;
1985 : : }
1986 : : else
1987 : 17 : appendStringInfo(lock_waiters_sbuf, ", %d",
1988 : 17 : curproclock->tag.myProc->pid);
1989 : : }
1990 : : else
1991 : : {
1992 [ + + ]: 1002 : if (first_holder)
1993 : : {
1994 : 995 : appendStringInfo(lock_holders_sbuf, "%d",
1995 : 995 : curproclock->tag.myProc->pid);
1996 : 995 : first_holder = false;
1997 : : }
1998 : : else
1999 : 7 : appendStringInfo(lock_holders_sbuf, ", %d",
2000 : 7 : curproclock->tag.myProc->pid);
2001 : :
2002 : 1002 : (*lockHoldersNum)++;
2003 : : }
2004 : : }
2005 : 995 : }
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
3500 rhaas@postgresql.org 2015 : 74 : ProcWaitForSignal(uint32 wait_event_info)
2016 : : {
2720 tmunro@postgresql.or 2017 : 74 : (void) WaitLatch(MyLatch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH, 0,
2018 : : wait_event_info);
4109 andres@anarazel.de 2019 : 74 : ResetLatch(MyLatch);
2020 [ - + ]: 74 : CHECK_FOR_INTERRUPTS();
9069 tgl@sss.pgh.pa.us 2021 : 74 : }
2022 : :
2023 : : /*
2024 : : * ProcSendSignal - set the latch of a backend identified by ProcNumber
2025 : : */
2026 : : void
793 heikki.linnakangas@i 2027 : 61 : ProcSendSignal(ProcNumber procNumber)
2028 : : {
2029 [ + - - + ]: 61 : if (procNumber < 0 || procNumber >= ProcGlobal->allProcCount)
793 heikki.linnakangas@i 2030 [ # # ]:UBC 0 : elog(ERROR, "procNumber out of range");
2031 : :
120 drowley@postgresql.o 2032 :GNC 61 : SetLatch(&GetPGProcByNumber(procNumber)->procLatch);
9069 tgl@sss.pgh.pa.us 2033 :CBC 61 : }
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
3740 rhaas@postgresql.org 2042 : 860 : BecomeLockGroupLeader(void)
2043 : : {
2044 : : LWLock *leader_lwlock;
2045 : :
2046 : : /* If we already did it, we don't need to do it again. */
2047 [ + + ]: 860 : if (MyProc->lockGroupLeader == MyProc)
2048 : 739 : return;
2049 : :
2050 : : /* We had better not be a follower. */
2051 [ - + ]: 121 : Assert(MyProc->lockGroupLeader == NULL);
2052 : :
2053 : : /* Create single-member group, containing only ourselves. */
2054 : 121 : leader_lwlock = LockHashPartitionLockByProc(MyProc);
2055 : 121 : LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
2056 : 121 : MyProc->lockGroupLeader = MyProc;
2057 : 121 : dlist_push_head(&MyProc->lockGroupMembers, &MyProc->lockGroupLink);
2058 : 121 : 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 : 2011 : BecomeLockGroupMember(PGPROC *leader, int pid)
2073 : : {
2074 : : LWLock *leader_lwlock;
2075 : 2011 : bool ok = false;
2076 : :
2077 : : /* Group leader can't become member of group */
2078 [ - + ]: 2011 : Assert(MyProc != leader);
2079 : :
2080 : : /* Can't already be a member of a group */
3725 tgl@sss.pgh.pa.us 2081 [ - + ]: 2011 : Assert(MyProc->lockGroupLeader == NULL);
2082 : :
2083 : : /* PID must be valid. */
3740 rhaas@postgresql.org 2084 [ - + ]: 2011 : 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 : : */
3726 2092 : 2011 : leader_lwlock = LockHashPartitionLockByProc(leader);
3740 2093 : 2011 : LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
2094 : :
2095 : : /* Is this the leader we're looking for? */
3725 tgl@sss.pgh.pa.us 2096 [ + - + - ]: 2011 : if (leader->pid == pid && leader->lockGroupLeader == leader)
2097 : : {
2098 : : /* OK, join the group */
3740 rhaas@postgresql.org 2099 : 2011 : ok = true;
2100 : 2011 : MyProc->lockGroupLeader = leader;
2101 : 2011 : dlist_push_tail(&leader->lockGroupMembers, &MyProc->lockGroupLink);
2102 : : }
2103 : 2011 : LWLockRelease(leader_lwlock);
2104 : :
2105 : 2011 : return ok;
2106 : : }
|