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