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