1 /*-------------------------------------------------------------------------
2 *
3 * proc.c
4 * routines to manage per-process shared memory data structure
5 *
6 * Portions Copyright (c) 1996-2016, 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 * ProcSleep(), ProcWakeup(),
18 * ProcQueueAlloc() -- create a shm queue for sleeping processes
19 * ProcQueueInit() -- create a queue without allocing memory
20 *
21 * Waiting for a lock causes the backend to be put to sleep. Whoever releases
22 * the lock wakes the process up again (and gives it an error code so it knows
23 * whether it was awoken on an error condition).
24 *
25 * Interface (b):
26 *
27 * ProcReleaseLocks -- frees the locks associated with current transaction
28 *
29 * ProcKill -- destroys the shared memory state (and locks)
30 * associated with the process.
31 */
32 #include "postgres.h"
33
34 #include <signal.h>
35 #include <unistd.h>
36 #include <sys/time.h>
37
38 #include "access/transam.h"
39 #include "access/twophase.h"
40 #include "access/xact.h"
41 #include "miscadmin.h"
42 #include "postmaster/autovacuum.h"
43 #include "replication/slot.h"
44 #include "replication/syncrep.h"
45 #include "storage/standby.h"
46 #include "storage/ipc.h"
47 #include "storage/lmgr.h"
48 #include "storage/pmsignal.h"
49 #include "storage/proc.h"
50 #include "storage/procarray.h"
51 #include "storage/procsignal.h"
52 #include "storage/spin.h"
53 #include "utils/timeout.h"
54 #include "utils/timestamp.h"
55
56
57 /* GUC variables */
58 int DeadlockTimeout = 1000;
59 int StatementTimeout = 0;
60 int LockTimeout = 0;
61 int IdleInTransactionSessionTimeout = 0;
62 bool log_lock_waits = false;
63
64 /* Pointer to this process's PGPROC and PGXACT structs, if any */
65 PGPROC *MyProc = NULL;
66 PGXACT *MyPgXact = NULL;
67
68 /*
69 * This spinlock protects the freelist of recycled PGPROC structures.
70 * We cannot use an LWLock because the LWLock manager depends on already
71 * having a PGPROC and a wait semaphore! But these structures are touched
72 * relatively infrequently (only at backend startup or shutdown) and not for
73 * very long, so a spinlock is okay.
74 */
75 NON_EXEC_STATIC slock_t *ProcStructLock = NULL;
76
77 /* Pointers to shared-memory structures */
78 PROC_HDR *ProcGlobal = NULL;
79 NON_EXEC_STATIC PGPROC *AuxiliaryProcs = NULL;
80 PGPROC *PreparedXactProcs = NULL;
81
82 /* If we are waiting for a lock, this points to the associated LOCALLOCK */
83 static LOCALLOCK *lockAwaited = NULL;
84
85 static DeadLockState deadlock_state = DS_NOT_YET_CHECKED;
86
87 /* Is a deadlock check pending? */
88 static volatile sig_atomic_t got_deadlock_timeout;
89
90 static void RemoveProcFromArray(int code, Datum arg);
91 static void ProcKill(int code, Datum arg);
92 static void AuxiliaryProcKill(int code, Datum arg);
93 static void CheckDeadLock(void);
94
95
96 /*
97 * Report shared-memory space needed by InitProcGlobal.
98 */
99 Size
ProcGlobalShmemSize(void)100 ProcGlobalShmemSize(void)
101 {
102 Size size = 0;
103
104 /* ProcGlobal */
105 size = add_size(size, sizeof(PROC_HDR));
106 /* MyProcs, including autovacuum workers and launcher */
107 size = add_size(size, mul_size(MaxBackends, sizeof(PGPROC)));
108 /* AuxiliaryProcs */
109 size = add_size(size, mul_size(NUM_AUXILIARY_PROCS, sizeof(PGPROC)));
110 /* Prepared xacts */
111 size = add_size(size, mul_size(max_prepared_xacts, sizeof(PGPROC)));
112 /* ProcStructLock */
113 size = add_size(size, sizeof(slock_t));
114
115 size = add_size(size, mul_size(MaxBackends, sizeof(PGXACT)));
116 size = add_size(size, mul_size(NUM_AUXILIARY_PROCS, sizeof(PGXACT)));
117 size = add_size(size, mul_size(max_prepared_xacts, sizeof(PGXACT)));
118
119 return size;
120 }
121
122 /*
123 * Report number of semaphores needed by InitProcGlobal.
124 */
125 int
ProcGlobalSemas(void)126 ProcGlobalSemas(void)
127 {
128 /*
129 * We need a sema per backend (including autovacuum), plus one for each
130 * auxiliary process.
131 */
132 return MaxBackends + NUM_AUXILIARY_PROCS;
133 }
134
135 /*
136 * InitProcGlobal -
137 * Initialize the global process table during postmaster or standalone
138 * backend startup.
139 *
140 * We also create all the per-process semaphores we will need to support
141 * the requested number of backends. We used to allocate semaphores
142 * only when backends were actually started up, but that is bad because
143 * it lets Postgres fail under load --- a lot of Unix systems are
144 * (mis)configured with small limits on the number of semaphores, and
145 * running out when trying to start another backend is a common failure.
146 * So, now we grab enough semaphores to support the desired max number
147 * of backends immediately at initialization --- if the sysadmin has set
148 * MaxConnections, max_worker_processes, or autovacuum_max_workers higher
149 * than his kernel will support, he'll find out sooner rather than later.
150 *
151 * Another reason for creating semaphores here is that the semaphore
152 * implementation typically requires us to create semaphores in the
153 * postmaster, not in backends.
154 *
155 * Note: this is NOT called by individual backends under a postmaster,
156 * not even in the EXEC_BACKEND case. The ProcGlobal and AuxiliaryProcs
157 * pointers must be propagated specially for EXEC_BACKEND operation.
158 */
159 void
InitProcGlobal(void)160 InitProcGlobal(void)
161 {
162 PGPROC *procs;
163 PGXACT *pgxacts;
164 int i,
165 j;
166 bool found;
167 uint32 TotalProcs = MaxBackends + NUM_AUXILIARY_PROCS + max_prepared_xacts;
168
169 /* Create the ProcGlobal shared structure */
170 ProcGlobal = (PROC_HDR *)
171 ShmemInitStruct("Proc Header", sizeof(PROC_HDR), &found);
172 Assert(!found);
173
174 /*
175 * Initialize the data structures.
176 */
177 ProcGlobal->spins_per_delay = DEFAULT_SPINS_PER_DELAY;
178 ProcGlobal->freeProcs = NULL;
179 ProcGlobal->autovacFreeProcs = NULL;
180 ProcGlobal->bgworkerFreeProcs = NULL;
181 ProcGlobal->startupProc = NULL;
182 ProcGlobal->startupProcPid = 0;
183 ProcGlobal->startupBufferPinWaitBufId = -1;
184 ProcGlobal->walwriterLatch = NULL;
185 ProcGlobal->checkpointerLatch = NULL;
186 pg_atomic_init_u32(&ProcGlobal->procArrayGroupFirst, INVALID_PGPROCNO);
187
188 /*
189 * Create and initialize all the PGPROC structures we'll need. There are
190 * five separate consumers: (1) normal backends, (2) autovacuum workers
191 * and the autovacuum launcher, (3) background workers, (4) auxiliary
192 * processes, and (5) prepared transactions. Each PGPROC structure is
193 * dedicated to exactly one of these purposes, and they do not move
194 * between groups.
195 */
196 procs = (PGPROC *) ShmemAlloc(TotalProcs * sizeof(PGPROC));
197 ProcGlobal->allProcs = procs;
198 /* XXX allProcCount isn't really all of them; it excludes prepared xacts */
199 ProcGlobal->allProcCount = MaxBackends + NUM_AUXILIARY_PROCS;
200 if (!procs)
201 ereport(FATAL,
202 (errcode(ERRCODE_OUT_OF_MEMORY),
203 errmsg("out of shared memory")));
204 MemSet(procs, 0, TotalProcs * sizeof(PGPROC));
205
206 /*
207 * Also allocate a separate array of PGXACT structures. This is separate
208 * from the main PGPROC array so that the most heavily accessed data is
209 * stored contiguously in memory in as few cache lines as possible. This
210 * provides significant performance benefits, especially on a
211 * multiprocessor system. There is one PGXACT structure for every PGPROC
212 * structure.
213 */
214 pgxacts = (PGXACT *) ShmemAlloc(TotalProcs * sizeof(PGXACT));
215 MemSet(pgxacts, 0, TotalProcs * sizeof(PGXACT));
216 ProcGlobal->allPgXact = pgxacts;
217
218 for (i = 0; i < TotalProcs; i++)
219 {
220 /* Common initialization for all PGPROCs, regardless of type. */
221
222 /*
223 * Set up per-PGPROC semaphore, latch, and backendLock. Prepared xact
224 * dummy PGPROCs don't need these though - they're never associated
225 * with a real process
226 */
227 if (i < MaxBackends + NUM_AUXILIARY_PROCS)
228 {
229 PGSemaphoreCreate(&(procs[i].sem));
230 InitSharedLatch(&(procs[i].procLatch));
231 LWLockInitialize(&(procs[i].backendLock), LWTRANCHE_PROC);
232 }
233 procs[i].pgprocno = i;
234
235 /*
236 * Newly created PGPROCs for normal backends, autovacuum and bgworkers
237 * must be queued up on the appropriate free list. Because there can
238 * only ever be a small, fixed number of auxiliary processes, no free
239 * list is used in that case; InitAuxiliaryProcess() instead uses a
240 * linear search. PGPROCs for prepared transactions are added to a
241 * free list by TwoPhaseShmemInit().
242 */
243 if (i < MaxConnections)
244 {
245 /* PGPROC for normal backend, add to freeProcs list */
246 procs[i].links.next = (SHM_QUEUE *) ProcGlobal->freeProcs;
247 ProcGlobal->freeProcs = &procs[i];
248 procs[i].procgloballist = &ProcGlobal->freeProcs;
249 }
250 else if (i < MaxConnections + autovacuum_max_workers + 1)
251 {
252 /* PGPROC for AV launcher/worker, add to autovacFreeProcs list */
253 procs[i].links.next = (SHM_QUEUE *) ProcGlobal->autovacFreeProcs;
254 ProcGlobal->autovacFreeProcs = &procs[i];
255 procs[i].procgloballist = &ProcGlobal->autovacFreeProcs;
256 }
257 else if (i < MaxBackends)
258 {
259 /* PGPROC for bgworker, add to bgworkerFreeProcs list */
260 procs[i].links.next = (SHM_QUEUE *) ProcGlobal->bgworkerFreeProcs;
261 ProcGlobal->bgworkerFreeProcs = &procs[i];
262 procs[i].procgloballist = &ProcGlobal->bgworkerFreeProcs;
263 }
264
265 /* Initialize myProcLocks[] shared memory queues. */
266 for (j = 0; j < NUM_LOCK_PARTITIONS; j++)
267 SHMQueueInit(&(procs[i].myProcLocks[j]));
268
269 /* Initialize lockGroupMembers list. */
270 dlist_init(&procs[i].lockGroupMembers);
271
272 /*
273 * Initialize the atomic variable, otherwise, it won't be safe to
274 * access it for backends that aren't currently in use.
275 */
276 pg_atomic_init_u32(&(procs[i].procArrayGroupNext), INVALID_PGPROCNO);
277 }
278
279 /*
280 * Save pointers to the blocks of PGPROC structures reserved for auxiliary
281 * processes and prepared transactions.
282 */
283 AuxiliaryProcs = &procs[MaxBackends];
284 PreparedXactProcs = &procs[MaxBackends + NUM_AUXILIARY_PROCS];
285
286 /* Create ProcStructLock spinlock, too */
287 ProcStructLock = (slock_t *) ShmemAlloc(sizeof(slock_t));
288 SpinLockInit(ProcStructLock);
289 }
290
291 /*
292 * InitProcess -- initialize a per-process data structure for this backend
293 */
294 void
InitProcess(void)295 InitProcess(void)
296 {
297 PGPROC *volatile * procgloballist;
298
299 /*
300 * ProcGlobal should be set up already (if we are a backend, we inherit
301 * this by fork() or EXEC_BACKEND mechanism from the postmaster).
302 */
303 if (ProcGlobal == NULL)
304 elog(PANIC, "proc header uninitialized");
305
306 if (MyProc != NULL)
307 elog(ERROR, "you already exist");
308
309 /* Decide which list should supply our PGPROC. */
310 if (IsAnyAutoVacuumProcess())
311 procgloballist = &ProcGlobal->autovacFreeProcs;
312 else if (IsBackgroundWorker)
313 procgloballist = &ProcGlobal->bgworkerFreeProcs;
314 else
315 procgloballist = &ProcGlobal->freeProcs;
316
317 /*
318 * Try to get a proc struct from the appropriate free list. If this
319 * fails, we must be out of PGPROC structures (not to mention semaphores).
320 *
321 * While we are holding the ProcStructLock, also copy the current shared
322 * estimate of spins_per_delay to local storage.
323 */
324 SpinLockAcquire(ProcStructLock);
325
326 set_spins_per_delay(ProcGlobal->spins_per_delay);
327
328 MyProc = *procgloballist;
329
330 if (MyProc != NULL)
331 {
332 *procgloballist = (PGPROC *) MyProc->links.next;
333 SpinLockRelease(ProcStructLock);
334 }
335 else
336 {
337 /*
338 * If we reach here, all the PGPROCs are in use. This is one of the
339 * possible places to detect "too many backends", so give the standard
340 * error message. XXX do we need to give a different failure message
341 * in the autovacuum case?
342 */
343 SpinLockRelease(ProcStructLock);
344 ereport(FATAL,
345 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
346 errmsg("sorry, too many clients already")));
347 }
348 MyPgXact = &ProcGlobal->allPgXact[MyProc->pgprocno];
349
350 /*
351 * Cross-check that the PGPROC is of the type we expect; if this were not
352 * the case, it would get returned to the wrong list.
353 */
354 Assert(MyProc->procgloballist == procgloballist);
355
356 /*
357 * Now that we have a PGPROC, mark ourselves as an active postmaster
358 * child; this is so that the postmaster can detect it if we exit without
359 * cleaning up. (XXX autovac launcher currently doesn't participate in
360 * this; it probably should.)
361 */
362 if (IsUnderPostmaster && !IsAutoVacuumLauncherProcess())
363 MarkPostmasterChildActive();
364
365 /*
366 * Initialize all fields of MyProc, except for those previously
367 * initialized by InitProcGlobal.
368 */
369 SHMQueueElemInit(&(MyProc->links));
370 MyProc->waitStatus = STATUS_OK;
371 MyProc->lxid = InvalidLocalTransactionId;
372 MyProc->fpVXIDLock = false;
373 MyProc->fpLocalTransactionId = InvalidLocalTransactionId;
374 MyPgXact->xid = InvalidTransactionId;
375 MyPgXact->xmin = InvalidTransactionId;
376 MyProc->pid = MyProcPid;
377 /* backendId, databaseId and roleId will be filled in later */
378 MyProc->backendId = InvalidBackendId;
379 MyProc->databaseId = InvalidOid;
380 MyProc->roleId = InvalidOid;
381 MyProc->isBackgroundWorker = IsBackgroundWorker;
382 MyPgXact->delayChkpt = false;
383 MyPgXact->vacuumFlags = 0;
384 /* NB -- autovac launcher intentionally does not set IS_AUTOVACUUM */
385 if (IsAutoVacuumWorkerProcess())
386 MyPgXact->vacuumFlags |= PROC_IS_AUTOVACUUM;
387 MyProc->lwWaiting = false;
388 MyProc->lwWaitMode = 0;
389 MyProc->waitLock = NULL;
390 MyProc->waitProcLock = NULL;
391 #ifdef USE_ASSERT_CHECKING
392 {
393 int i;
394
395 /* Last process should have released all locks. */
396 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
397 Assert(SHMQueueEmpty(&(MyProc->myProcLocks[i])));
398 }
399 #endif
400 MyProc->recoveryConflictPending = false;
401
402 /* Initialize fields for sync rep */
403 MyProc->waitLSN = 0;
404 MyProc->syncRepState = SYNC_REP_NOT_WAITING;
405 SHMQueueElemInit(&(MyProc->syncRepLinks));
406
407 /* Initialize fields for group XID clearing. */
408 MyProc->procArrayGroupMember = false;
409 MyProc->procArrayGroupMemberXid = InvalidTransactionId;
410 Assert(pg_atomic_read_u32(&MyProc->procArrayGroupNext) == INVALID_PGPROCNO);
411
412 /* Check that group locking fields are in a proper initial state. */
413 Assert(MyProc->lockGroupLeader == NULL);
414 Assert(dlist_is_empty(&MyProc->lockGroupMembers));
415
416 /* Initialize wait event information. */
417 MyProc->wait_event_info = 0;
418
419 /*
420 * Acquire ownership of the PGPROC's latch, so that we can use WaitLatch
421 * on it. That allows us to repoint the process latch, which so far
422 * points to process local one, to the shared one.
423 */
424 OwnLatch(&MyProc->procLatch);
425 SwitchToSharedLatch();
426
427 /*
428 * We might be reusing a semaphore that belonged to a failed process. So
429 * be careful and reinitialize its value here. (This is not strictly
430 * necessary anymore, but seems like a good idea for cleanliness.)
431 */
432 PGSemaphoreReset(&MyProc->sem);
433
434 /*
435 * Arrange to clean up at backend exit.
436 */
437 on_shmem_exit(ProcKill, 0);
438
439 /*
440 * Now that we have a PGPROC, we could try to acquire locks, so initialize
441 * local state needed for LWLocks, and the deadlock checker.
442 */
443 InitLWLockAccess();
444 InitDeadLockChecking();
445 }
446
447 /*
448 * InitProcessPhase2 -- make MyProc visible in the shared ProcArray.
449 *
450 * This is separate from InitProcess because we can't acquire LWLocks until
451 * we've created a PGPROC, but in the EXEC_BACKEND case ProcArrayAdd won't
452 * work until after we've done CreateSharedMemoryAndSemaphores.
453 */
454 void
InitProcessPhase2(void)455 InitProcessPhase2(void)
456 {
457 Assert(MyProc != NULL);
458
459 /*
460 * Add our PGPROC to the PGPROC array in shared memory.
461 */
462 ProcArrayAdd(MyProc);
463
464 /*
465 * Arrange to clean that up at backend exit.
466 */
467 on_shmem_exit(RemoveProcFromArray, 0);
468 }
469
470 /*
471 * InitAuxiliaryProcess -- create a per-auxiliary-process data structure
472 *
473 * This is called by bgwriter and similar processes so that they will have a
474 * MyProc value that's real enough to let them wait for LWLocks. The PGPROC
475 * and sema that are assigned are one of the extra ones created during
476 * InitProcGlobal.
477 *
478 * Auxiliary processes are presently not expected to wait for real (lockmgr)
479 * locks, so we need not set up the deadlock checker. They are never added
480 * to the ProcArray or the sinval messaging mechanism, either. They also
481 * don't get a VXID assigned, since this is only useful when we actually
482 * hold lockmgr locks.
483 *
484 * Startup process however uses locks but never waits for them in the
485 * normal backend sense. Startup process also takes part in sinval messaging
486 * as a sendOnly process, so never reads messages from sinval queue. So
487 * Startup process does have a VXID and does show up in pg_locks.
488 */
489 void
InitAuxiliaryProcess(void)490 InitAuxiliaryProcess(void)
491 {
492 PGPROC *auxproc;
493 int proctype;
494
495 /*
496 * ProcGlobal should be set up already (if we are a backend, we inherit
497 * this by fork() or EXEC_BACKEND mechanism from the postmaster).
498 */
499 if (ProcGlobal == NULL || AuxiliaryProcs == NULL)
500 elog(PANIC, "proc header uninitialized");
501
502 if (MyProc != NULL)
503 elog(ERROR, "you already exist");
504
505 /*
506 * We use the ProcStructLock to protect assignment and releasing of
507 * AuxiliaryProcs entries.
508 *
509 * While we are holding the ProcStructLock, also copy the current shared
510 * estimate of spins_per_delay to local storage.
511 */
512 SpinLockAcquire(ProcStructLock);
513
514 set_spins_per_delay(ProcGlobal->spins_per_delay);
515
516 /*
517 * Find a free auxproc ... *big* trouble if there isn't one ...
518 */
519 for (proctype = 0; proctype < NUM_AUXILIARY_PROCS; proctype++)
520 {
521 auxproc = &AuxiliaryProcs[proctype];
522 if (auxproc->pid == 0)
523 break;
524 }
525 if (proctype >= NUM_AUXILIARY_PROCS)
526 {
527 SpinLockRelease(ProcStructLock);
528 elog(FATAL, "all AuxiliaryProcs are in use");
529 }
530
531 /* Mark auxiliary proc as in use by me */
532 /* use volatile pointer to prevent code rearrangement */
533 ((volatile PGPROC *) auxproc)->pid = MyProcPid;
534
535 MyProc = auxproc;
536 MyPgXact = &ProcGlobal->allPgXact[auxproc->pgprocno];
537
538 SpinLockRelease(ProcStructLock);
539
540 /*
541 * Initialize all fields of MyProc, except for those previously
542 * initialized by InitProcGlobal.
543 */
544 SHMQueueElemInit(&(MyProc->links));
545 MyProc->waitStatus = STATUS_OK;
546 MyProc->lxid = InvalidLocalTransactionId;
547 MyProc->fpVXIDLock = false;
548 MyProc->fpLocalTransactionId = InvalidLocalTransactionId;
549 MyPgXact->xid = InvalidTransactionId;
550 MyPgXact->xmin = InvalidTransactionId;
551 MyProc->backendId = InvalidBackendId;
552 MyProc->databaseId = InvalidOid;
553 MyProc->roleId = InvalidOid;
554 MyProc->isBackgroundWorker = IsBackgroundWorker;
555 MyPgXact->delayChkpt = false;
556 MyPgXact->vacuumFlags = 0;
557 MyProc->lwWaiting = false;
558 MyProc->lwWaitMode = 0;
559 MyProc->waitLock = NULL;
560 MyProc->waitProcLock = NULL;
561 #ifdef USE_ASSERT_CHECKING
562 {
563 int i;
564
565 /* Last process should have released all locks. */
566 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
567 Assert(SHMQueueEmpty(&(MyProc->myProcLocks[i])));
568 }
569 #endif
570
571 /*
572 * Acquire ownership of the PGPROC's latch, so that we can use WaitLatch
573 * on it. That allows us to repoint the process latch, which so far
574 * points to process local one, to the shared one.
575 */
576 OwnLatch(&MyProc->procLatch);
577 SwitchToSharedLatch();
578
579 /* Check that group locking fields are in a proper initial state. */
580 Assert(MyProc->lockGroupLeader == NULL);
581 Assert(dlist_is_empty(&MyProc->lockGroupMembers));
582
583 /*
584 * We might be reusing a semaphore that belonged to a failed process. So
585 * be careful and reinitialize its value here. (This is not strictly
586 * necessary anymore, but seems like a good idea for cleanliness.)
587 */
588 PGSemaphoreReset(&MyProc->sem);
589
590 /*
591 * Arrange to clean up at process exit.
592 */
593 on_shmem_exit(AuxiliaryProcKill, Int32GetDatum(proctype));
594 }
595
596 /*
597 * Record the PID and PGPROC structures for the Startup process, for use in
598 * ProcSendSignal(). See comments there for further explanation.
599 */
600 void
PublishStartupProcessInformation(void)601 PublishStartupProcessInformation(void)
602 {
603 SpinLockAcquire(ProcStructLock);
604
605 ProcGlobal->startupProc = MyProc;
606 ProcGlobal->startupProcPid = MyProcPid;
607
608 SpinLockRelease(ProcStructLock);
609 }
610
611 /*
612 * Used from bufgr to share the value of the buffer that Startup waits on,
613 * or to reset the value to "not waiting" (-1). This allows processing
614 * of recovery conflicts for buffer pins. Set is made before backends look
615 * at this value, so locking not required, especially since the set is
616 * an atomic integer set operation.
617 */
618 void
SetStartupBufferPinWaitBufId(int bufid)619 SetStartupBufferPinWaitBufId(int bufid)
620 {
621 /* use volatile pointer to prevent code rearrangement */
622 volatile PROC_HDR *procglobal = ProcGlobal;
623
624 procglobal->startupBufferPinWaitBufId = bufid;
625 }
626
627 /*
628 * Used by backends when they receive a request to check for buffer pin waits.
629 */
630 int
GetStartupBufferPinWaitBufId(void)631 GetStartupBufferPinWaitBufId(void)
632 {
633 /* use volatile pointer to prevent code rearrangement */
634 volatile PROC_HDR *procglobal = ProcGlobal;
635
636 return procglobal->startupBufferPinWaitBufId;
637 }
638
639 /*
640 * Check whether there are at least N free PGPROC objects.
641 *
642 * Note: this is designed on the assumption that N will generally be small.
643 */
644 bool
HaveNFreeProcs(int n)645 HaveNFreeProcs(int n)
646 {
647 PGPROC *proc;
648
649 SpinLockAcquire(ProcStructLock);
650
651 proc = ProcGlobal->freeProcs;
652
653 while (n > 0 && proc != NULL)
654 {
655 proc = (PGPROC *) proc->links.next;
656 n--;
657 }
658
659 SpinLockRelease(ProcStructLock);
660
661 return (n <= 0);
662 }
663
664 /*
665 * Check if the current process is awaiting a lock.
666 */
667 bool
IsWaitingForLock(void)668 IsWaitingForLock(void)
669 {
670 if (lockAwaited == NULL)
671 return false;
672
673 return true;
674 }
675
676 /*
677 * Cancel any pending wait for lock, when aborting a transaction, and revert
678 * any strong lock count acquisition for a lock being acquired.
679 *
680 * (Normally, this would only happen if we accept a cancel/die
681 * interrupt while waiting; but an ereport(ERROR) before or during the lock
682 * wait is within the realm of possibility, too.)
683 */
684 void
LockErrorCleanup(void)685 LockErrorCleanup(void)
686 {
687 LWLock *partitionLock;
688 DisableTimeoutParams timeouts[2];
689
690 HOLD_INTERRUPTS();
691
692 AbortStrongLockAcquire();
693
694 /* Nothing to do if we weren't waiting for a lock */
695 if (lockAwaited == NULL)
696 {
697 RESUME_INTERRUPTS();
698 return;
699 }
700
701 /*
702 * Turn off the deadlock and lock timeout timers, if they are still
703 * running (see ProcSleep). Note we must preserve the LOCK_TIMEOUT
704 * indicator flag, since this function is executed before
705 * ProcessInterrupts when responding to SIGINT; else we'd lose the
706 * knowledge that the SIGINT came from a lock timeout and not an external
707 * source.
708 */
709 timeouts[0].id = DEADLOCK_TIMEOUT;
710 timeouts[0].keep_indicator = false;
711 timeouts[1].id = LOCK_TIMEOUT;
712 timeouts[1].keep_indicator = true;
713 disable_timeouts(timeouts, 2);
714
715 /* Unlink myself from the wait queue, if on it (might not be anymore!) */
716 partitionLock = LockHashPartitionLock(lockAwaited->hashcode);
717 LWLockAcquire(partitionLock, LW_EXCLUSIVE);
718
719 if (MyProc->links.next != NULL)
720 {
721 /* We could not have been granted the lock yet */
722 RemoveFromWaitQueue(MyProc, lockAwaited->hashcode);
723 }
724 else
725 {
726 /*
727 * Somebody kicked us off the lock queue already. Perhaps they
728 * granted us the lock, or perhaps they detected a deadlock. If they
729 * did grant us the lock, we'd better remember it in our local lock
730 * table.
731 */
732 if (MyProc->waitStatus == STATUS_OK)
733 GrantAwaitedLock();
734 }
735
736 lockAwaited = NULL;
737
738 LWLockRelease(partitionLock);
739
740 RESUME_INTERRUPTS();
741 }
742
743
744 /*
745 * ProcReleaseLocks() -- release locks associated with current transaction
746 * at main transaction commit or abort
747 *
748 * At main transaction commit, we release standard locks except session locks.
749 * At main transaction abort, we release all locks including session locks.
750 *
751 * Advisory locks are released only if they are transaction-level;
752 * session-level holds remain, whether this is a commit or not.
753 *
754 * At subtransaction commit, we don't release any locks (so this func is not
755 * needed at all); we will defer the releasing to the parent transaction.
756 * At subtransaction abort, we release all locks held by the subtransaction;
757 * this is implemented by retail releasing of the locks under control of
758 * the ResourceOwner mechanism.
759 */
760 void
ProcReleaseLocks(bool isCommit)761 ProcReleaseLocks(bool isCommit)
762 {
763 if (!MyProc)
764 return;
765 /* If waiting, get off wait queue (should only be needed after error) */
766 LockErrorCleanup();
767 /* Release standard locks, including session-level if aborting */
768 LockReleaseAll(DEFAULT_LOCKMETHOD, !isCommit);
769 /* Release transaction-level advisory locks */
770 LockReleaseAll(USER_LOCKMETHOD, false);
771 }
772
773
774 /*
775 * RemoveProcFromArray() -- Remove this process from the shared ProcArray.
776 */
777 static void
RemoveProcFromArray(int code,Datum arg)778 RemoveProcFromArray(int code, Datum arg)
779 {
780 Assert(MyProc != NULL);
781 ProcArrayRemove(MyProc, InvalidTransactionId);
782 }
783
784 /*
785 * ProcKill() -- Destroy the per-proc data structure for
786 * this process. Release any of its held LW locks.
787 */
788 static void
ProcKill(int code,Datum arg)789 ProcKill(int code, Datum arg)
790 {
791 PGPROC *proc;
792 PGPROC *volatile * procgloballist;
793
794 Assert(MyProc != NULL);
795
796 /* Make sure we're out of the sync rep lists */
797 SyncRepCleanupAtProcExit();
798
799 #ifdef USE_ASSERT_CHECKING
800 {
801 int i;
802
803 /* Last process should have released all locks. */
804 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
805 Assert(SHMQueueEmpty(&(MyProc->myProcLocks[i])));
806 }
807 #endif
808
809 /*
810 * Release any LW locks I am holding. There really shouldn't be any, but
811 * it's cheap to check again before we cut the knees off the LWLock
812 * facility by releasing our PGPROC ...
813 */
814 LWLockReleaseAll();
815
816 /* Make sure active replication slots are released */
817 if (MyReplicationSlot != NULL)
818 ReplicationSlotRelease();
819
820 /*
821 * Detach from any lock group of which we are a member. If the leader
822 * exist before all other group members, it's PGPROC will remain allocated
823 * until the last group process exits; that process must return the
824 * leader's PGPROC to the appropriate list.
825 */
826 if (MyProc->lockGroupLeader != NULL)
827 {
828 PGPROC *leader = MyProc->lockGroupLeader;
829 LWLock *leader_lwlock = LockHashPartitionLockByProc(leader);
830
831 LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
832 Assert(!dlist_is_empty(&leader->lockGroupMembers));
833 dlist_delete(&MyProc->lockGroupLink);
834 if (dlist_is_empty(&leader->lockGroupMembers))
835 {
836 leader->lockGroupLeader = NULL;
837 if (leader != MyProc)
838 {
839 procgloballist = leader->procgloballist;
840
841 /* Leader exited first; return its PGPROC. */
842 SpinLockAcquire(ProcStructLock);
843 leader->links.next = (SHM_QUEUE *) *procgloballist;
844 *procgloballist = leader;
845 SpinLockRelease(ProcStructLock);
846 }
847 }
848 else if (leader != MyProc)
849 MyProc->lockGroupLeader = NULL;
850 LWLockRelease(leader_lwlock);
851 }
852
853 /*
854 * Reset MyLatch to the process local one. This is so that signal
855 * handlers et al can continue using the latch after the shared latch
856 * isn't ours anymore. After that clear MyProc and disown the shared
857 * latch.
858 */
859 SwitchBackToLocalLatch();
860 proc = MyProc;
861 MyProc = NULL;
862 DisownLatch(&proc->procLatch);
863
864 procgloballist = proc->procgloballist;
865 SpinLockAcquire(ProcStructLock);
866
867 /*
868 * If we're still a member of a locking group, that means we're a leader
869 * which has somehow exited before its children. The last remaining child
870 * will release our PGPROC. Otherwise, release it now.
871 */
872 if (proc->lockGroupLeader == NULL)
873 {
874 /* Since lockGroupLeader is NULL, lockGroupMembers should be empty. */
875 Assert(dlist_is_empty(&proc->lockGroupMembers));
876
877 /* Return PGPROC structure (and semaphore) to appropriate freelist */
878 proc->links.next = (SHM_QUEUE *) *procgloballist;
879 *procgloballist = proc;
880 }
881
882 /* Update shared estimate of spins_per_delay */
883 ProcGlobal->spins_per_delay = update_spins_per_delay(ProcGlobal->spins_per_delay);
884
885 SpinLockRelease(ProcStructLock);
886
887 /*
888 * This process is no longer present in shared memory in any meaningful
889 * way, so tell the postmaster we've cleaned up acceptably well. (XXX
890 * autovac launcher should be included here someday)
891 */
892 if (IsUnderPostmaster && !IsAutoVacuumLauncherProcess())
893 MarkPostmasterChildInactive();
894
895 /* wake autovac launcher if needed -- see comments in FreeWorkerInfo */
896 if (AutovacuumLauncherPid != 0)
897 kill(AutovacuumLauncherPid, SIGUSR2);
898 }
899
900 /*
901 * AuxiliaryProcKill() -- Cut-down version of ProcKill for auxiliary
902 * processes (bgwriter, etc). The PGPROC and sema are not released, only
903 * marked as not-in-use.
904 */
905 static void
AuxiliaryProcKill(int code,Datum arg)906 AuxiliaryProcKill(int code, Datum arg)
907 {
908 int proctype = DatumGetInt32(arg);
909 PGPROC *auxproc PG_USED_FOR_ASSERTS_ONLY;
910 PGPROC *proc;
911
912 Assert(proctype >= 0 && proctype < NUM_AUXILIARY_PROCS);
913
914 auxproc = &AuxiliaryProcs[proctype];
915
916 Assert(MyProc == auxproc);
917
918 /* Release any LW locks I am holding (see notes above) */
919 LWLockReleaseAll();
920
921 /*
922 * Reset MyLatch to the process local one. This is so that signal
923 * handlers et al can continue using the latch after the shared latch
924 * isn't ours anymore. After that clear MyProc and disown the shared
925 * latch.
926 */
927 SwitchBackToLocalLatch();
928 proc = MyProc;
929 MyProc = NULL;
930 DisownLatch(&proc->procLatch);
931
932 SpinLockAcquire(ProcStructLock);
933
934 /* Mark auxiliary proc no longer in use */
935 proc->pid = 0;
936
937 /* Update shared estimate of spins_per_delay */
938 ProcGlobal->spins_per_delay = update_spins_per_delay(ProcGlobal->spins_per_delay);
939
940 SpinLockRelease(ProcStructLock);
941 }
942
943
944 /*
945 * ProcQueue package: routines for putting processes to sleep
946 * and waking them up
947 */
948
949 /*
950 * ProcQueueAlloc -- alloc/attach to a shared memory process queue
951 *
952 * Returns: a pointer to the queue
953 * Side Effects: Initializes the queue if it wasn't there before
954 */
955 #ifdef NOT_USED
956 PROC_QUEUE *
ProcQueueAlloc(const char * name)957 ProcQueueAlloc(const char *name)
958 {
959 PROC_QUEUE *queue;
960 bool found;
961
962 queue = (PROC_QUEUE *)
963 ShmemInitStruct(name, sizeof(PROC_QUEUE), &found);
964
965 if (!found)
966 ProcQueueInit(queue);
967
968 return queue;
969 }
970 #endif
971
972 /*
973 * ProcQueueInit -- initialize a shared memory process queue
974 */
975 void
ProcQueueInit(PROC_QUEUE * queue)976 ProcQueueInit(PROC_QUEUE *queue)
977 {
978 SHMQueueInit(&(queue->links));
979 queue->size = 0;
980 }
981
982
983 /*
984 * ProcSleep -- put a process to sleep on the specified lock
985 *
986 * Caller must have set MyProc->heldLocks to reflect locks already held
987 * on the lockable object by this process (under all XIDs).
988 *
989 * The lock table's partition lock must be held at entry, and will be held
990 * at exit.
991 *
992 * Result: STATUS_OK if we acquired the lock, STATUS_ERROR if not (deadlock).
993 *
994 * ASSUME: that no one will fiddle with the queue until after
995 * we release the partition lock.
996 *
997 * NOTES: The process queue is now a priority queue for locking.
998 */
999 int
ProcSleep(LOCALLOCK * locallock,LockMethod lockMethodTable)1000 ProcSleep(LOCALLOCK *locallock, LockMethod lockMethodTable)
1001 {
1002 LOCKMODE lockmode = locallock->tag.mode;
1003 LOCK *lock = locallock->lock;
1004 PROCLOCK *proclock = locallock->proclock;
1005 uint32 hashcode = locallock->hashcode;
1006 LWLock *partitionLock = LockHashPartitionLock(hashcode);
1007 PROC_QUEUE *waitQueue = &(lock->waitProcs);
1008 LOCKMASK myHeldLocks = MyProc->heldLocks;
1009 bool early_deadlock = false;
1010 bool allow_autovacuum_cancel = true;
1011 int myWaitStatus;
1012 PGPROC *proc;
1013 PGPROC *leader = MyProc->lockGroupLeader;
1014 int i;
1015
1016 /*
1017 * If group locking is in use, locks held by members of my locking group
1018 * need to be included in myHeldLocks.
1019 */
1020 if (leader != NULL)
1021 {
1022 SHM_QUEUE *procLocks = &(lock->procLocks);
1023 PROCLOCK *otherproclock;
1024
1025 otherproclock = (PROCLOCK *)
1026 SHMQueueNext(procLocks, procLocks, offsetof(PROCLOCK, lockLink));
1027 while (otherproclock != NULL)
1028 {
1029 if (otherproclock->groupLeader == leader)
1030 myHeldLocks |= otherproclock->holdMask;
1031 otherproclock = (PROCLOCK *)
1032 SHMQueueNext(procLocks, &otherproclock->lockLink,
1033 offsetof(PROCLOCK, lockLink));
1034 }
1035 }
1036
1037 /*
1038 * Determine where to add myself in the wait queue.
1039 *
1040 * Normally I should go at the end of the queue. However, if I already
1041 * hold locks that conflict with the request of any previous waiter, put
1042 * myself in the queue just in front of the first such waiter. This is not
1043 * a necessary step, since deadlock detection would move me to before that
1044 * waiter anyway; but it's relatively cheap to detect such a conflict
1045 * immediately, and avoid delaying till deadlock timeout.
1046 *
1047 * Special case: if I find I should go in front of some waiter, check to
1048 * see if I conflict with already-held locks or the requests before that
1049 * waiter. If not, then just grant myself the requested lock immediately.
1050 * This is the same as the test for immediate grant in LockAcquire, except
1051 * we are only considering the part of the wait queue before my insertion
1052 * point.
1053 */
1054 if (myHeldLocks != 0)
1055 {
1056 LOCKMASK aheadRequests = 0;
1057
1058 proc = (PGPROC *) waitQueue->links.next;
1059 for (i = 0; i < waitQueue->size; i++)
1060 {
1061 /*
1062 * If we're part of the same locking group as this waiter, its
1063 * locks neither conflict with ours nor contribute to
1064 * aheadRequests.
1065 */
1066 if (leader != NULL && leader == proc->lockGroupLeader)
1067 {
1068 proc = (PGPROC *) proc->links.next;
1069 continue;
1070 }
1071 /* Must he wait for me? */
1072 if (lockMethodTable->conflictTab[proc->waitLockMode] & myHeldLocks)
1073 {
1074 /* Must I wait for him ? */
1075 if (lockMethodTable->conflictTab[lockmode] & proc->heldLocks)
1076 {
1077 /*
1078 * Yes, so we have a deadlock. Easiest way to clean up
1079 * correctly is to call RemoveFromWaitQueue(), but we
1080 * can't do that until we are *on* the wait queue. So, set
1081 * a flag to check below, and break out of loop. Also,
1082 * record deadlock info for later message.
1083 */
1084 RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
1085 early_deadlock = true;
1086 break;
1087 }
1088 /* I must go before this waiter. Check special case. */
1089 if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
1090 LockCheckConflicts(lockMethodTable,
1091 lockmode,
1092 lock,
1093 proclock) == STATUS_OK)
1094 {
1095 /* Skip the wait and just grant myself the lock. */
1096 GrantLock(lock, proclock, lockmode);
1097 GrantAwaitedLock();
1098 return STATUS_OK;
1099 }
1100 /* Break out of loop to put myself before him */
1101 break;
1102 }
1103 /* Nope, so advance to next waiter */
1104 aheadRequests |= LOCKBIT_ON(proc->waitLockMode);
1105 proc = (PGPROC *) proc->links.next;
1106 }
1107
1108 /*
1109 * If we fall out of loop normally, proc points to waitQueue head, so
1110 * we will insert at tail of queue as desired.
1111 */
1112 }
1113 else
1114 {
1115 /* I hold no locks, so I can't push in front of anyone. */
1116 proc = (PGPROC *) &(waitQueue->links);
1117 }
1118
1119 /*
1120 * Insert self into queue, ahead of the given proc (or at tail of queue).
1121 */
1122 SHMQueueInsertBefore(&(proc->links), &(MyProc->links));
1123 waitQueue->size++;
1124
1125 lock->waitMask |= LOCKBIT_ON(lockmode);
1126
1127 /* Set up wait information in PGPROC object, too */
1128 MyProc->waitLock = lock;
1129 MyProc->waitProcLock = proclock;
1130 MyProc->waitLockMode = lockmode;
1131
1132 MyProc->waitStatus = STATUS_WAITING;
1133
1134 /*
1135 * If we detected deadlock, give up without waiting. This must agree with
1136 * CheckDeadLock's recovery code.
1137 */
1138 if (early_deadlock)
1139 {
1140 RemoveFromWaitQueue(MyProc, hashcode);
1141 return STATUS_ERROR;
1142 }
1143
1144 /* mark that we are waiting for a lock */
1145 lockAwaited = locallock;
1146
1147 /*
1148 * Release the lock table's partition lock.
1149 *
1150 * NOTE: this may also cause us to exit critical-section state, possibly
1151 * allowing a cancel/die interrupt to be accepted. This is OK because we
1152 * have recorded the fact that we are waiting for a lock, and so
1153 * LockErrorCleanup will clean up if cancel/die happens.
1154 */
1155 LWLockRelease(partitionLock);
1156
1157 /*
1158 * Also, now that we will successfully clean up after an ereport, it's
1159 * safe to check to see if there's a buffer pin deadlock against the
1160 * Startup process. Of course, that's only necessary if we're doing Hot
1161 * Standby and are not the Startup process ourselves.
1162 */
1163 if (RecoveryInProgress() && !InRecovery)
1164 CheckRecoveryConflictDeadlock();
1165
1166 /* Reset deadlock_state before enabling the timeout handler */
1167 deadlock_state = DS_NOT_YET_CHECKED;
1168 got_deadlock_timeout = false;
1169
1170 /*
1171 * Set timer so we can wake up after awhile and check for a deadlock. If a
1172 * deadlock is detected, the handler sets MyProc->waitStatus =
1173 * STATUS_ERROR, allowing us to know that we must report failure rather
1174 * than success.
1175 *
1176 * By delaying the check until we've waited for a bit, we can avoid
1177 * running the rather expensive deadlock-check code in most cases.
1178 *
1179 * If LockTimeout is set, also enable the timeout for that. We can save a
1180 * few cycles by enabling both timeout sources in one call.
1181 *
1182 * If InHotStandby we set lock waits slightly later for clarity with other
1183 * code.
1184 */
1185 if (!InHotStandby)
1186 {
1187 if (LockTimeout > 0)
1188 {
1189 EnableTimeoutParams timeouts[2];
1190
1191 timeouts[0].id = DEADLOCK_TIMEOUT;
1192 timeouts[0].type = TMPARAM_AFTER;
1193 timeouts[0].delay_ms = DeadlockTimeout;
1194 timeouts[1].id = LOCK_TIMEOUT;
1195 timeouts[1].type = TMPARAM_AFTER;
1196 timeouts[1].delay_ms = LockTimeout;
1197 enable_timeouts(timeouts, 2);
1198 }
1199 else
1200 enable_timeout_after(DEADLOCK_TIMEOUT, DeadlockTimeout);
1201 }
1202
1203 /*
1204 * If somebody wakes us between LWLockRelease and WaitLatch, the latch
1205 * will not wait. But a set latch does not necessarily mean that the lock
1206 * is free now, as there are many other sources for latch sets than
1207 * somebody releasing the lock.
1208 *
1209 * We process interrupts whenever the latch has been set, so cancel/die
1210 * interrupts are processed quickly. This means we must not mind losing
1211 * control to a cancel/die interrupt here. We don't, because we have no
1212 * shared-state-change work to do after being granted the lock (the
1213 * grantor did it all). We do have to worry about canceling the deadlock
1214 * timeout and updating the locallock table, but if we lose control to an
1215 * error, LockErrorCleanup will fix that up.
1216 */
1217 do
1218 {
1219 if (InHotStandby)
1220 {
1221 /* Set a timer and wait for that or for the Lock to be granted */
1222 ResolveRecoveryConflictWithLock(locallock->tag.lock);
1223 }
1224 else
1225 {
1226 WaitLatch(MyLatch, WL_LATCH_SET, 0);
1227 ResetLatch(MyLatch);
1228 /* check for deadlocks first, as that's probably log-worthy */
1229 if (got_deadlock_timeout)
1230 {
1231 CheckDeadLock();
1232 got_deadlock_timeout = false;
1233 }
1234 CHECK_FOR_INTERRUPTS();
1235 }
1236
1237 /*
1238 * waitStatus could change from STATUS_WAITING to something else
1239 * asynchronously. Read it just once per loop to prevent surprising
1240 * behavior (such as missing log messages).
1241 */
1242 myWaitStatus = *((volatile int *) &MyProc->waitStatus);
1243
1244 /*
1245 * If we are not deadlocked, but are waiting on an autovacuum-induced
1246 * task, send a signal to interrupt it.
1247 */
1248 if (deadlock_state == DS_BLOCKED_BY_AUTOVACUUM && allow_autovacuum_cancel)
1249 {
1250 PGPROC *autovac = GetBlockingAutoVacuumPgproc();
1251 PGXACT *autovac_pgxact = &ProcGlobal->allPgXact[autovac->pgprocno];
1252
1253 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
1254
1255 /*
1256 * Only do it if the worker is not working to protect against Xid
1257 * wraparound.
1258 */
1259 if ((autovac_pgxact->vacuumFlags & PROC_IS_AUTOVACUUM) &&
1260 !(autovac_pgxact->vacuumFlags & PROC_VACUUM_FOR_WRAPAROUND))
1261 {
1262 int pid = autovac->pid;
1263 StringInfoData locktagbuf;
1264 StringInfoData logbuf; /* errdetail for server log */
1265
1266 initStringInfo(&locktagbuf);
1267 initStringInfo(&logbuf);
1268 DescribeLockTag(&locktagbuf, &lock->tag);
1269 appendStringInfo(&logbuf,
1270 _("Process %d waits for %s on %s."),
1271 MyProcPid,
1272 GetLockmodeName(lock->tag.locktag_lockmethodid,
1273 lockmode),
1274 locktagbuf.data);
1275
1276 /* release lock as quickly as possible */
1277 LWLockRelease(ProcArrayLock);
1278
1279 /* send the autovacuum worker Back to Old Kent Road */
1280 ereport(DEBUG1,
1281 (errmsg("sending cancel to blocking autovacuum PID %d",
1282 pid),
1283 errdetail_log("%s", logbuf.data)));
1284
1285 if (kill(pid, SIGINT) < 0)
1286 {
1287 /*
1288 * There's a race condition here: once we release the
1289 * ProcArrayLock, it's possible for the autovac worker to
1290 * close up shop and exit before we can do the kill().
1291 * Therefore, we do not whinge about no-such-process.
1292 * Other errors such as EPERM could conceivably happen if
1293 * the kernel recycles the PID fast enough, but such cases
1294 * seem improbable enough that it's probably best to issue
1295 * a warning if we see some other errno.
1296 */
1297 if (errno != ESRCH)
1298 ereport(WARNING,
1299 (errmsg("could not send signal to process %d: %m",
1300 pid)));
1301 }
1302
1303 pfree(logbuf.data);
1304 pfree(locktagbuf.data);
1305 }
1306 else
1307 LWLockRelease(ProcArrayLock);
1308
1309 /* prevent signal from being sent again more than once */
1310 allow_autovacuum_cancel = false;
1311 }
1312
1313 /*
1314 * If awoken after the deadlock check interrupt has run, and
1315 * log_lock_waits is on, then report about the wait.
1316 */
1317 if (log_lock_waits && deadlock_state != DS_NOT_YET_CHECKED)
1318 {
1319 StringInfoData buf,
1320 lock_waiters_sbuf,
1321 lock_holders_sbuf;
1322 const char *modename;
1323 long secs;
1324 int usecs;
1325 long msecs;
1326 SHM_QUEUE *procLocks;
1327 PROCLOCK *proclock;
1328 bool first_holder = true,
1329 first_waiter = true;
1330 int lockHoldersNum = 0;
1331
1332 initStringInfo(&buf);
1333 initStringInfo(&lock_waiters_sbuf);
1334 initStringInfo(&lock_holders_sbuf);
1335
1336 DescribeLockTag(&buf, &locallock->tag.lock);
1337 modename = GetLockmodeName(locallock->tag.lock.locktag_lockmethodid,
1338 lockmode);
1339 TimestampDifference(get_timeout_start_time(DEADLOCK_TIMEOUT),
1340 GetCurrentTimestamp(),
1341 &secs, &usecs);
1342 msecs = secs * 1000 + usecs / 1000;
1343 usecs = usecs % 1000;
1344
1345 /*
1346 * we loop over the lock's procLocks to gather a list of all
1347 * holders and waiters. Thus we will be able to provide more
1348 * detailed information for lock debugging purposes.
1349 *
1350 * lock->procLocks contains all processes which hold or wait for
1351 * this lock.
1352 */
1353
1354 LWLockAcquire(partitionLock, LW_SHARED);
1355
1356 procLocks = &(lock->procLocks);
1357 proclock = (PROCLOCK *) SHMQueueNext(procLocks, procLocks,
1358 offsetof(PROCLOCK, lockLink));
1359
1360 while (proclock)
1361 {
1362 /*
1363 * we are a waiter if myProc->waitProcLock == proclock; we are
1364 * a holder if it is NULL or something different
1365 */
1366 if (proclock->tag.myProc->waitProcLock == proclock)
1367 {
1368 if (first_waiter)
1369 {
1370 appendStringInfo(&lock_waiters_sbuf, "%d",
1371 proclock->tag.myProc->pid);
1372 first_waiter = false;
1373 }
1374 else
1375 appendStringInfo(&lock_waiters_sbuf, ", %d",
1376 proclock->tag.myProc->pid);
1377 }
1378 else
1379 {
1380 if (first_holder)
1381 {
1382 appendStringInfo(&lock_holders_sbuf, "%d",
1383 proclock->tag.myProc->pid);
1384 first_holder = false;
1385 }
1386 else
1387 appendStringInfo(&lock_holders_sbuf, ", %d",
1388 proclock->tag.myProc->pid);
1389
1390 lockHoldersNum++;
1391 }
1392
1393 proclock = (PROCLOCK *) SHMQueueNext(procLocks, &proclock->lockLink,
1394 offsetof(PROCLOCK, lockLink));
1395 }
1396
1397 LWLockRelease(partitionLock);
1398
1399 if (deadlock_state == DS_SOFT_DEADLOCK)
1400 ereport(LOG,
1401 (errmsg("process %d avoided deadlock for %s on %s by rearranging queue order after %ld.%03d ms",
1402 MyProcPid, modename, buf.data, msecs, usecs),
1403 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1404 "Processes holding the lock: %s. Wait queue: %s.",
1405 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1406 else if (deadlock_state == DS_HARD_DEADLOCK)
1407 {
1408 /*
1409 * This message is a bit redundant with the error that will be
1410 * reported subsequently, but in some cases the error report
1411 * might not make it to the log (eg, if it's caught by an
1412 * exception handler), and we want to ensure all long-wait
1413 * events get logged.
1414 */
1415 ereport(LOG,
1416 (errmsg("process %d detected deadlock while waiting for %s on %s after %ld.%03d ms",
1417 MyProcPid, modename, buf.data, msecs, usecs),
1418 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1419 "Processes holding the lock: %s. Wait queue: %s.",
1420 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1421 }
1422
1423 if (myWaitStatus == STATUS_WAITING)
1424 ereport(LOG,
1425 (errmsg("process %d still waiting for %s on %s after %ld.%03d ms",
1426 MyProcPid, modename, buf.data, msecs, usecs),
1427 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1428 "Processes holding the lock: %s. Wait queue: %s.",
1429 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1430 else if (myWaitStatus == STATUS_OK)
1431 ereport(LOG,
1432 (errmsg("process %d acquired %s on %s after %ld.%03d ms",
1433 MyProcPid, modename, buf.data, msecs, usecs)));
1434 else
1435 {
1436 Assert(myWaitStatus == STATUS_ERROR);
1437
1438 /*
1439 * Currently, the deadlock checker always kicks its own
1440 * process, which means that we'll only see STATUS_ERROR when
1441 * deadlock_state == DS_HARD_DEADLOCK, and there's no need to
1442 * print redundant messages. But for completeness and
1443 * future-proofing, print a message if it looks like someone
1444 * else kicked us off the lock.
1445 */
1446 if (deadlock_state != DS_HARD_DEADLOCK)
1447 ereport(LOG,
1448 (errmsg("process %d failed to acquire %s on %s after %ld.%03d ms",
1449 MyProcPid, modename, buf.data, msecs, usecs),
1450 (errdetail_log_plural("Process holding the lock: %s. Wait queue: %s.",
1451 "Processes holding the lock: %s. Wait queue: %s.",
1452 lockHoldersNum, lock_holders_sbuf.data, lock_waiters_sbuf.data))));
1453 }
1454
1455 /*
1456 * At this point we might still need to wait for the lock. Reset
1457 * state so we don't print the above messages again.
1458 */
1459 deadlock_state = DS_NO_DEADLOCK;
1460
1461 pfree(buf.data);
1462 pfree(lock_holders_sbuf.data);
1463 pfree(lock_waiters_sbuf.data);
1464 }
1465 } while (myWaitStatus == STATUS_WAITING);
1466
1467 /*
1468 * Disable the timers, if they are still running. As in LockErrorCleanup,
1469 * we must preserve the LOCK_TIMEOUT indicator flag: if a lock timeout has
1470 * already caused QueryCancelPending to become set, we want the cancel to
1471 * be reported as a lock timeout, not a user cancel.
1472 */
1473 if (!InHotStandby)
1474 {
1475 if (LockTimeout > 0)
1476 {
1477 DisableTimeoutParams timeouts[2];
1478
1479 timeouts[0].id = DEADLOCK_TIMEOUT;
1480 timeouts[0].keep_indicator = false;
1481 timeouts[1].id = LOCK_TIMEOUT;
1482 timeouts[1].keep_indicator = true;
1483 disable_timeouts(timeouts, 2);
1484 }
1485 else
1486 disable_timeout(DEADLOCK_TIMEOUT, false);
1487 }
1488
1489 /*
1490 * Re-acquire the lock table's partition lock. We have to do this to hold
1491 * off cancel/die interrupts before we can mess with lockAwaited (else we
1492 * might have a missed or duplicated locallock update).
1493 */
1494 LWLockAcquire(partitionLock, LW_EXCLUSIVE);
1495
1496 /*
1497 * We no longer want LockErrorCleanup to do anything.
1498 */
1499 lockAwaited = NULL;
1500
1501 /*
1502 * If we got the lock, be sure to remember it in the locallock table.
1503 */
1504 if (MyProc->waitStatus == STATUS_OK)
1505 GrantAwaitedLock();
1506
1507 /*
1508 * We don't have to do anything else, because the awaker did all the
1509 * necessary update of the lock table and MyProc.
1510 */
1511 return MyProc->waitStatus;
1512 }
1513
1514
1515 /*
1516 * ProcWakeup -- wake up a process by setting its latch.
1517 *
1518 * Also remove the process from the wait queue and set its links invalid.
1519 * RETURN: the next process in the wait queue.
1520 *
1521 * The appropriate lock partition lock must be held by caller.
1522 *
1523 * XXX: presently, this code is only used for the "success" case, and only
1524 * works correctly for that case. To clean up in failure case, would need
1525 * to twiddle the lock's request counts too --- see RemoveFromWaitQueue.
1526 * Hence, in practice the waitStatus parameter must be STATUS_OK.
1527 */
1528 PGPROC *
ProcWakeup(PGPROC * proc,int waitStatus)1529 ProcWakeup(PGPROC *proc, int waitStatus)
1530 {
1531 PGPROC *retProc;
1532
1533 /* Proc should be sleeping ... */
1534 if (proc->links.prev == NULL ||
1535 proc->links.next == NULL)
1536 return NULL;
1537 Assert(proc->waitStatus == STATUS_WAITING);
1538
1539 /* Save next process before we zap the list link */
1540 retProc = (PGPROC *) proc->links.next;
1541
1542 /* Remove process from wait queue */
1543 SHMQueueDelete(&(proc->links));
1544 (proc->waitLock->waitProcs.size)--;
1545
1546 /* Clean up process' state and pass it the ok/fail signal */
1547 proc->waitLock = NULL;
1548 proc->waitProcLock = NULL;
1549 proc->waitStatus = waitStatus;
1550
1551 /* And awaken it */
1552 SetLatch(&proc->procLatch);
1553
1554 return retProc;
1555 }
1556
1557 /*
1558 * ProcLockWakeup -- routine for waking up processes when a lock is
1559 * released (or a prior waiter is aborted). Scan all waiters
1560 * for lock, waken any that are no longer blocked.
1561 *
1562 * The appropriate lock partition lock must be held by caller.
1563 */
1564 void
ProcLockWakeup(LockMethod lockMethodTable,LOCK * lock)1565 ProcLockWakeup(LockMethod lockMethodTable, LOCK *lock)
1566 {
1567 PROC_QUEUE *waitQueue = &(lock->waitProcs);
1568 int queue_size = waitQueue->size;
1569 PGPROC *proc;
1570 LOCKMASK aheadRequests = 0;
1571
1572 Assert(queue_size >= 0);
1573
1574 if (queue_size == 0)
1575 return;
1576
1577 proc = (PGPROC *) waitQueue->links.next;
1578
1579 while (queue_size-- > 0)
1580 {
1581 LOCKMODE lockmode = proc->waitLockMode;
1582
1583 /*
1584 * Waken if (a) doesn't conflict with requests of earlier waiters, and
1585 * (b) doesn't conflict with already-held locks.
1586 */
1587 if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
1588 LockCheckConflicts(lockMethodTable,
1589 lockmode,
1590 lock,
1591 proc->waitProcLock) == STATUS_OK)
1592 {
1593 /* OK to waken */
1594 GrantLock(lock, proc->waitProcLock, lockmode);
1595 proc = ProcWakeup(proc, STATUS_OK);
1596
1597 /*
1598 * ProcWakeup removes proc from the lock's waiting process queue
1599 * and returns the next proc in chain; don't use proc's next-link,
1600 * because it's been cleared.
1601 */
1602 }
1603 else
1604 {
1605 /*
1606 * Cannot wake this guy. Remember his request for later checks.
1607 */
1608 aheadRequests |= LOCKBIT_ON(lockmode);
1609 proc = (PGPROC *) proc->links.next;
1610 }
1611 }
1612
1613 Assert(waitQueue->size >= 0);
1614 }
1615
1616 /*
1617 * CheckDeadLock
1618 *
1619 * We only get to this routine, if DEADLOCK_TIMEOUT fired while waiting for a
1620 * lock to be released by some other process. Check if there's a deadlock; if
1621 * not, just return. (But signal ProcSleep to log a message, if
1622 * log_lock_waits is true.) If we have a real deadlock, remove ourselves from
1623 * the lock's wait queue and signal an error to ProcSleep.
1624 */
1625 static void
CheckDeadLock(void)1626 CheckDeadLock(void)
1627 {
1628 int i;
1629
1630 /*
1631 * Acquire exclusive lock on the entire shared lock data structures. Must
1632 * grab LWLocks in partition-number order to avoid LWLock deadlock.
1633 *
1634 * Note that the deadlock check interrupt had better not be enabled
1635 * anywhere that this process itself holds lock partition locks, else this
1636 * will wait forever. Also note that LWLockAcquire creates a critical
1637 * section, so that this routine cannot be interrupted by cancel/die
1638 * interrupts.
1639 */
1640 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
1641 LWLockAcquire(LockHashPartitionLockByIndex(i), LW_EXCLUSIVE);
1642
1643 /*
1644 * Check to see if we've been awoken by anyone in the interim.
1645 *
1646 * If we have, we can return and resume our transaction -- happy day.
1647 * Before we are awoken the process releasing the lock grants it to us so
1648 * we know that we don't have to wait anymore.
1649 *
1650 * We check by looking to see if we've been unlinked from the wait queue.
1651 * This is safe because we hold the lock partition lock.
1652 */
1653 if (MyProc->links.prev == NULL ||
1654 MyProc->links.next == NULL)
1655 goto check_done;
1656
1657 #ifdef LOCK_DEBUG
1658 if (Debug_deadlocks)
1659 DumpAllLocks();
1660 #endif
1661
1662 /* Run the deadlock check, and set deadlock_state for use by ProcSleep */
1663 deadlock_state = DeadLockCheck(MyProc);
1664
1665 if (deadlock_state == DS_HARD_DEADLOCK)
1666 {
1667 /*
1668 * Oops. We have a deadlock.
1669 *
1670 * Get this process out of wait state. (Note: we could do this more
1671 * efficiently by relying on lockAwaited, but use this coding to
1672 * preserve the flexibility to kill some other transaction than the
1673 * one detecting the deadlock.)
1674 *
1675 * RemoveFromWaitQueue sets MyProc->waitStatus to STATUS_ERROR, so
1676 * ProcSleep will report an error after we return from the signal
1677 * handler.
1678 */
1679 Assert(MyProc->waitLock != NULL);
1680 RemoveFromWaitQueue(MyProc, LockTagHashCode(&(MyProc->waitLock->tag)));
1681
1682 /*
1683 * We're done here. Transaction abort caused by the error that
1684 * ProcSleep will raise will cause any other locks we hold to be
1685 * released, thus allowing other processes to wake up; we don't need
1686 * to do that here. NOTE: an exception is that releasing locks we
1687 * hold doesn't consider the possibility of waiters that were blocked
1688 * behind us on the lock we just failed to get, and might now be
1689 * wakable because we're not in front of them anymore. However,
1690 * RemoveFromWaitQueue took care of waking up any such processes.
1691 */
1692 }
1693
1694 /*
1695 * And release locks. We do this in reverse order for two reasons: (1)
1696 * Anyone else who needs more than one of the locks will be trying to lock
1697 * them in increasing order; we don't want to release the other process
1698 * until it can get all the locks it needs. (2) This avoids O(N^2)
1699 * behavior inside LWLockRelease.
1700 */
1701 check_done:
1702 for (i = NUM_LOCK_PARTITIONS; --i >= 0;)
1703 LWLockRelease(LockHashPartitionLockByIndex(i));
1704 }
1705
1706 /*
1707 * CheckDeadLockAlert - Handle the expiry of deadlock_timeout.
1708 *
1709 * NB: Runs inside a signal handler, be careful.
1710 */
1711 void
CheckDeadLockAlert(void)1712 CheckDeadLockAlert(void)
1713 {
1714 int save_errno = errno;
1715
1716 got_deadlock_timeout = true;
1717
1718 /*
1719 * Have to set the latch again, even if handle_sig_alarm already did. Back
1720 * then got_deadlock_timeout wasn't yet set... It's unlikely that this
1721 * ever would be a problem, but setting a set latch again is cheap.
1722 *
1723 * Note that, when this function runs inside procsignal_sigusr1_handler(),
1724 * the handler function sets the latch again after the latch is set here.
1725 */
1726 SetLatch(MyLatch);
1727 errno = save_errno;
1728 }
1729
1730 /*
1731 * ProcWaitForSignal - wait for a signal from another backend.
1732 *
1733 * As this uses the generic process latch the caller has to be robust against
1734 * unrelated wakeups: Always check that the desired state has occurred, and
1735 * wait again if not.
1736 */
1737 void
ProcWaitForSignal(void)1738 ProcWaitForSignal(void)
1739 {
1740 WaitLatch(MyLatch, WL_LATCH_SET, 0);
1741 ResetLatch(MyLatch);
1742 CHECK_FOR_INTERRUPTS();
1743 }
1744
1745 /*
1746 * ProcSendSignal - send a signal to a backend identified by PID
1747 */
1748 void
ProcSendSignal(int pid)1749 ProcSendSignal(int pid)
1750 {
1751 PGPROC *proc = NULL;
1752
1753 if (RecoveryInProgress())
1754 {
1755 SpinLockAcquire(ProcStructLock);
1756
1757 /*
1758 * Check to see whether it is the Startup process we wish to signal.
1759 * This call is made by the buffer manager when it wishes to wake up a
1760 * process that has been waiting for a pin in so it can obtain a
1761 * cleanup lock using LockBufferForCleanup(). Startup is not a normal
1762 * backend, so BackendPidGetProc() will not return any pid at all. So
1763 * we remember the information for this special case.
1764 */
1765 if (pid == ProcGlobal->startupProcPid)
1766 proc = ProcGlobal->startupProc;
1767
1768 SpinLockRelease(ProcStructLock);
1769 }
1770
1771 if (proc == NULL)
1772 proc = BackendPidGetProc(pid);
1773
1774 if (proc != NULL)
1775 {
1776 SetLatch(&proc->procLatch);
1777 }
1778 }
1779
1780 /*
1781 * BecomeLockGroupLeader - designate process as lock group leader
1782 *
1783 * Once this function has returned, other processes can join the lock group
1784 * by calling BecomeLockGroupMember.
1785 */
1786 void
BecomeLockGroupLeader(void)1787 BecomeLockGroupLeader(void)
1788 {
1789 LWLock *leader_lwlock;
1790
1791 /* If we already did it, we don't need to do it again. */
1792 if (MyProc->lockGroupLeader == MyProc)
1793 return;
1794
1795 /* We had better not be a follower. */
1796 Assert(MyProc->lockGroupLeader == NULL);
1797
1798 /* Create single-member group, containing only ourselves. */
1799 leader_lwlock = LockHashPartitionLockByProc(MyProc);
1800 LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
1801 MyProc->lockGroupLeader = MyProc;
1802 dlist_push_head(&MyProc->lockGroupMembers, &MyProc->lockGroupLink);
1803 LWLockRelease(leader_lwlock);
1804 }
1805
1806 /*
1807 * BecomeLockGroupMember - designate process as lock group member
1808 *
1809 * This is pretty straightforward except for the possibility that the leader
1810 * whose group we're trying to join might exit before we manage to do so;
1811 * and the PGPROC might get recycled for an unrelated process. To avoid
1812 * that, we require the caller to pass the PID of the intended PGPROC as
1813 * an interlock. Returns true if we successfully join the intended lock
1814 * group, and false if not.
1815 */
1816 bool
BecomeLockGroupMember(PGPROC * leader,int pid)1817 BecomeLockGroupMember(PGPROC *leader, int pid)
1818 {
1819 LWLock *leader_lwlock;
1820 bool ok = false;
1821
1822 /* Group leader can't become member of group */
1823 Assert(MyProc != leader);
1824
1825 /* Can't already be a member of a group */
1826 Assert(MyProc->lockGroupLeader == NULL);
1827
1828 /* PID must be valid. */
1829 Assert(pid != 0);
1830
1831 /*
1832 * Get lock protecting the group fields. Note LockHashPartitionLockByProc
1833 * accesses leader->pgprocno in a PGPROC that might be free. This is safe
1834 * because all PGPROCs' pgprocno fields are set during shared memory
1835 * initialization and never change thereafter; so we will acquire the
1836 * correct lock even if the leader PGPROC is in process of being recycled.
1837 */
1838 leader_lwlock = LockHashPartitionLockByProc(leader);
1839 LWLockAcquire(leader_lwlock, LW_EXCLUSIVE);
1840
1841 /* Is this the leader we're looking for? */
1842 if (leader->pid == pid && leader->lockGroupLeader == leader)
1843 {
1844 /* OK, join the group */
1845 ok = true;
1846 MyProc->lockGroupLeader = leader;
1847 dlist_push_tail(&leader->lockGroupMembers, &MyProc->lockGroupLink);
1848 }
1849 LWLockRelease(leader_lwlock);
1850
1851 return ok;
1852 }
1853