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