1 /*-------------------------------------------------------------------------
4 * routines to manage per-process shared memory data structure
6 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/storage/lmgr/proc.c
13 *-------------------------------------------------------------------------
17 * ProcSleep(), ProcWakeup(),
18 * ProcQueueAlloc() -- create a shm queue for sleeping processes
19 * ProcQueueInit() -- create a queue without allocing memory
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).
27 * ProcReleaseLocks -- frees the locks associated with current transaction
29 * ProcKill -- destroys the shared memory state (and locks)
30 * associated with the process.
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"
56 int DeadlockTimeout = 1000;
57 int StatementTimeout = 0;
59 bool log_lock_waits = false;
61 /* Pointer to this process's PGPROC and PGXACT structs, if any */
62 PGPROC *MyProc = NULL;
63 PGXACT *MyPgXact = NULL;
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.
72 NON_EXEC_STATIC slock_t *ProcStructLock = NULL;
74 /* Pointers to shared-memory structures */
75 PROC_HDR *ProcGlobal = NULL;
76 NON_EXEC_STATIC PGPROC *AuxiliaryProcs = NULL;
77 PGPROC *PreparedXactProcs = NULL;
79 /* If we are waiting for a lock, this points to the associated LOCALLOCK */
80 static LOCALLOCK *lockAwaited = NULL;
82 /* Mark this volatile because it can be changed by signal handler */
83 static volatile DeadLockState deadlock_state = DS_NOT_YET_CHECKED;
86 static void RemoveProcFromArray(int code, Datum arg);
87 static void ProcKill(int code, Datum arg);
88 static void AuxiliaryProcKill(int code, Datum arg);
92 * Report shared-memory space needed by InitProcGlobal.
95 ProcGlobalShmemSize(void)
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)));
104 size = add_size(size, mul_size(NUM_AUXILIARY_PROCS, sizeof(PGPROC)));
106 size = add_size(size, mul_size(max_prepared_xacts, sizeof(PGPROC)));
108 size = add_size(size, sizeof(slock_t));
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)));
118 * Report number of semaphores needed by InitProcGlobal.
121 ProcGlobalSemas(void)
124 * We need a sema per backend (including autovacuum), plus one for each
127 return MaxBackends + NUM_AUXILIARY_PROCS;
132 * Initialize the global process table during postmaster or standalone
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.
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.
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.
162 uint32 TotalProcs = MaxBackends + NUM_AUXILIARY_PROCS + max_prepared_xacts;
164 /* Create the ProcGlobal shared structure */
165 ProcGlobal = (PROC_HDR *)
166 ShmemInitStruct("Proc Header", sizeof(PROC_HDR), &found);
170 * Initialize the data structures.
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;
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
190 procs = (PGPROC *) ShmemAlloc(TotalProcs * sizeof(PGPROC));
191 ProcGlobal->allProcs = procs;
192 ProcGlobal->allProcCount = TotalProcs;
195 (errcode(ERRCODE_OUT_OF_MEMORY),
196 errmsg("out of shared memory")));
197 MemSet(procs, 0, TotalProcs * sizeof(PGPROC));
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
207 pgxacts = (PGXACT *) ShmemAlloc(TotalProcs * sizeof(PGXACT));
208 MemSet(pgxacts, 0, TotalProcs * sizeof(PGXACT));
209 ProcGlobal->allPgXact = pgxacts;
211 for (i = 0; i < TotalProcs; i++)
213 /* Common initialization for all PGPROCs, regardless of type. */
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
220 if (i < MaxBackends + NUM_AUXILIARY_PROCS)
222 PGSemaphoreCreate(&(procs[i].sem));
223 InitSharedLatch(&(procs[i].procLatch));
224 procs[i].backendLock = LWLockAssign();
226 procs[i].pgprocno = i;
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().
236 if (i < MaxConnections)
238 /* PGPROC for normal backend, add to freeProcs list */
239 procs[i].links.next = (SHM_QUEUE *) ProcGlobal->freeProcs;
240 ProcGlobal->freeProcs = &procs[i];
242 else if (i < MaxConnections + autovacuum_max_workers + 1)
244 /* PGPROC for AV launcher/worker, add to autovacFreeProcs list */
245 procs[i].links.next = (SHM_QUEUE *) ProcGlobal->autovacFreeProcs;
246 ProcGlobal->autovacFreeProcs = &procs[i];
248 else if (i < MaxBackends)
250 /* PGPROC for bgworker, add to bgworkerFreeProcs list */
251 procs[i].links.next = (SHM_QUEUE *) ProcGlobal->bgworkerFreeProcs;
252 ProcGlobal->bgworkerFreeProcs = &procs[i];
255 /* Initialize myProcLocks[] shared memory queues. */
256 for (j = 0; j < NUM_LOCK_PARTITIONS; j++)
257 SHMQueueInit(&(procs[i].myProcLocks[j]));
261 * Save pointers to the blocks of PGPROC structures reserved for auxiliary
262 * processes and prepared transactions.
264 AuxiliaryProcs = &procs[MaxBackends];
265 PreparedXactProcs = &procs[MaxBackends + NUM_AUXILIARY_PROCS];
267 /* Create ProcStructLock spinlock, too */
268 ProcStructLock = (slock_t *) ShmemAlloc(sizeof(slock_t));
269 SpinLockInit(ProcStructLock);
273 * InitProcess -- initialize a per-process data structure for this backend
278 /* use volatile pointer to prevent code rearrangement */
279 volatile PROC_HDR *procglobal = ProcGlobal;
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).
285 if (procglobal == NULL)
286 elog(PANIC, "proc header uninitialized");
289 elog(ERROR, "you already exist");
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.
296 InitializeLatchSupport();
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).
302 * While we are holding the ProcStructLock, also copy the current shared
303 * estimate of spins_per_delay to local storage.
305 SpinLockAcquire(ProcStructLock);
307 set_spins_per_delay(procglobal->spins_per_delay);
309 if (IsAnyAutoVacuumProcess())
310 MyProc = procglobal->autovacFreeProcs;
311 else if (IsBackgroundWorker)
312 MyProc = procglobal->bgworkerFreeProcs;
314 MyProc = procglobal->freeProcs;
318 if (IsAnyAutoVacuumProcess())
319 procglobal->autovacFreeProcs = (PGPROC *) MyProc->links.next;
320 else if (IsBackgroundWorker)
321 procglobal->bgworkerFreeProcs = (PGPROC *) MyProc->links.next;
323 procglobal->freeProcs = (PGPROC *) MyProc->links.next;
324 SpinLockRelease(ProcStructLock);
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?
334 SpinLockRelease(ProcStructLock);
336 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
337 errmsg("sorry, too many clients already")));
339 MyPgXact = &ProcGlobal->allPgXact[MyProc->pgprocno];
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.)
347 if (IsUnderPostmaster && !IsAutoVacuumLauncherProcess())
348 MarkPostmasterChildActive();
351 * Initialize all fields of MyProc, except for those previously
352 * initialized by InitProcGlobal.
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
381 /* Last process should have released all locks. */
382 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
383 Assert(SHMQueueEmpty(&(MyProc->myProcLocks[i])));
386 MyProc->recoveryConflictPending = false;
388 /* Initialize fields for sync rep */
390 MyProc->syncRepState = SYNC_REP_NOT_WAITING;
391 SHMQueueElemInit(&(MyProc->syncRepLinks));
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.
397 OwnLatch(&MyProc->procLatch);
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.)
404 PGSemaphoreReset(&MyProc->sem);
407 * Arrange to clean up at backend exit.
409 on_shmem_exit(ProcKill, 0);
412 * Now that we have a PGPROC, we could try to acquire locks, so initialize
413 * the deadlock checker.
415 InitDeadLockChecking();
419 * InitProcessPhase2 -- make MyProc visible in the shared ProcArray.
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.
426 InitProcessPhase2(void)
428 Assert(MyProc != NULL);
431 * Add our PGPROC to the PGPROC array in shared memory.
433 ProcArrayAdd(MyProc);
436 * Arrange to clean that up at backend exit.
438 on_shmem_exit(RemoveProcFromArray, 0);
442 * InitAuxiliaryProcess -- create a per-auxiliary-process data structure
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
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.
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.
461 InitAuxiliaryProcess(void)
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).
470 if (ProcGlobal == NULL || AuxiliaryProcs == NULL)
471 elog(PANIC, "proc header uninitialized");
474 elog(ERROR, "you already exist");
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.
481 InitializeLatchSupport();
484 * We use the ProcStructLock to protect assignment and releasing of
485 * AuxiliaryProcs entries.
487 * While we are holding the ProcStructLock, also copy the current shared
488 * estimate of spins_per_delay to local storage.
490 SpinLockAcquire(ProcStructLock);
492 set_spins_per_delay(ProcGlobal->spins_per_delay);
495 * Find a free auxproc ... *big* trouble if there isn't one ...
497 for (proctype = 0; proctype < NUM_AUXILIARY_PROCS; proctype++)
499 auxproc = &AuxiliaryProcs[proctype];
500 if (auxproc->pid == 0)
503 if (proctype >= NUM_AUXILIARY_PROCS)
505 SpinLockRelease(ProcStructLock);
506 elog(FATAL, "all AuxiliaryProcs are in use");
509 /* Mark auxiliary proc as in use by me */
510 /* use volatile pointer to prevent code rearrangement */
511 ((volatile PGPROC *) auxproc)->pid = MyProcPid;
514 MyPgXact = &ProcGlobal->allPgXact[auxproc->pgprocno];
516 SpinLockRelease(ProcStructLock);
519 * Initialize all fields of MyProc, except for those previously
520 * initialized by InitProcGlobal.
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
544 /* Last process should have released all locks. */
545 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
546 Assert(SHMQueueEmpty(&(MyProc->myProcLocks[i])));
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.
554 OwnLatch(&MyProc->procLatch);
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.)
561 PGSemaphoreReset(&MyProc->sem);
564 * Arrange to clean up at process exit.
566 on_shmem_exit(AuxiliaryProcKill, Int32GetDatum(proctype));
570 * Record the PID and PGPROC structures for the Startup process, for use in
571 * ProcSendSignal(). See comments there for further explanation.
574 PublishStartupProcessInformation(void)
576 /* use volatile pointer to prevent code rearrangement */
577 volatile PROC_HDR *procglobal = ProcGlobal;
579 SpinLockAcquire(ProcStructLock);
581 procglobal->startupProc = MyProc;
582 procglobal->startupProcPid = MyProcPid;
584 SpinLockRelease(ProcStructLock);
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.
595 SetStartupBufferPinWaitBufId(int bufid)
597 /* use volatile pointer to prevent code rearrangement */
598 volatile PROC_HDR *procglobal = ProcGlobal;
600 procglobal->startupBufferPinWaitBufId = bufid;
604 * Used by backends when they receive a request to check for buffer pin waits.
607 GetStartupBufferPinWaitBufId(void)
609 /* use volatile pointer to prevent code rearrangement */
610 volatile PROC_HDR *procglobal = ProcGlobal;
612 return procglobal->startupBufferPinWaitBufId;
616 * Check whether there are at least N free PGPROC objects.
618 * Note: this is designed on the assumption that N will generally be small.
621 HaveNFreeProcs(int n)
625 /* use volatile pointer to prevent code rearrangement */
626 volatile PROC_HDR *procglobal = ProcGlobal;
628 SpinLockAcquire(ProcStructLock);
630 proc = procglobal->freeProcs;
632 while (n > 0 && proc != NULL)
634 proc = (PGPROC *) proc->links.next;
638 SpinLockRelease(ProcStructLock);
644 * Check if the current process is awaiting a lock.
647 IsWaitingForLock(void)
649 if (lockAwaited == NULL)
656 * Cancel any pending wait for lock, when aborting a transaction, and revert
657 * any strong lock count acquisition for a lock being acquired.
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.)
664 LockErrorCleanup(void)
666 LWLockId partitionLock;
667 DisableTimeoutParams timeouts[2];
669 AbortStrongLockAcquire();
671 /* Nothing to do if we weren't waiting for a lock */
672 if (lockAwaited == NULL)
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
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);
689 /* Unlink myself from the wait queue, if on it (might not be anymore!) */
690 partitionLock = LockHashPartitionLock(lockAwaited->hashcode);
691 LWLockAcquire(partitionLock, LW_EXCLUSIVE);
693 if (MyProc->links.next != NULL)
695 /* We could not have been granted the lock yet */
696 RemoveFromWaitQueue(MyProc, lockAwaited->hashcode);
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
706 if (MyProc->waitStatus == STATUS_OK)
712 LWLockRelease(partitionLock);
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.
727 * ProcReleaseLocks() -- release locks associated with current transaction
728 * at main transaction commit or abort
730 * At main transaction commit, we release standard locks except session locks.
731 * At main transaction abort, we release all locks including session locks.
733 * Advisory locks are released only if they are transaction-level;
734 * session-level holds remain, whether this is a commit or not.
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.
743 ProcReleaseLocks(bool isCommit)
747 /* If waiting, get off wait queue (should only be needed after error) */
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);
757 * RemoveProcFromArray() -- Remove this process from the shared ProcArray.
760 RemoveProcFromArray(int code, Datum arg)
762 Assert(MyProc != NULL);
763 ProcArrayRemove(MyProc, InvalidTransactionId);
767 * ProcKill() -- Destroy the per-proc data structure for
768 * this process. Release any of its held LW locks.
771 ProcKill(int code, Datum arg)
773 /* use volatile pointer to prevent code rearrangement */
774 volatile PROC_HDR *procglobal = ProcGlobal;
776 Assert(MyProc != NULL);
778 /* Make sure we're out of the sync rep lists */
779 SyncRepCleanupAtProcExit();
781 #ifdef USE_ASSERT_CHECKING
786 /* Last process should have released all locks. */
787 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
788 Assert(SHMQueueEmpty(&(MyProc->myProcLocks[i])));
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 ...
799 /* Release ownership of the process's latch, too */
800 DisownLatch(&MyProc->procLatch);
802 SpinLockAcquire(ProcStructLock);
804 /* Return PGPROC structure (and semaphore) to appropriate freelist */
805 if (IsAnyAutoVacuumProcess())
807 MyProc->links.next = (SHM_QUEUE *) procglobal->autovacFreeProcs;
808 procglobal->autovacFreeProcs = MyProc;
810 else if (IsBackgroundWorker)
812 MyProc->links.next = (SHM_QUEUE *) procglobal->bgworkerFreeProcs;
813 procglobal->bgworkerFreeProcs = MyProc;
817 MyProc->links.next = (SHM_QUEUE *) procglobal->freeProcs;
818 procglobal->freeProcs = MyProc;
821 /* PGPROC struct isn't mine anymore */
824 /* Update shared estimate of spins_per_delay */
825 procglobal->spins_per_delay = update_spins_per_delay(procglobal->spins_per_delay);
827 SpinLockRelease(ProcStructLock);
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)
834 if (IsUnderPostmaster && !IsAutoVacuumLauncherProcess())
835 MarkPostmasterChildInactive();
837 /* wake autovac launcher if needed -- see comments in FreeWorkerInfo */
838 if (AutovacuumLauncherPid != 0)
839 kill(AutovacuumLauncherPid, SIGUSR2);
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.
848 AuxiliaryProcKill(int code, Datum arg)
850 int proctype = DatumGetInt32(arg);
851 PGPROC *auxproc PG_USED_FOR_ASSERTS_ONLY;
853 Assert(proctype >= 0 && proctype < NUM_AUXILIARY_PROCS);
855 auxproc = &AuxiliaryProcs[proctype];
857 Assert(MyProc == auxproc);
859 /* Release any LW locks I am holding (see notes above) */
862 /* Release ownership of the process's latch, too */
863 DisownLatch(&MyProc->procLatch);
865 SpinLockAcquire(ProcStructLock);
867 /* Mark auxiliary proc no longer in use */
870 /* PGPROC struct isn't mine anymore */
873 /* Update shared estimate of spins_per_delay */
874 ProcGlobal->spins_per_delay = update_spins_per_delay(ProcGlobal->spins_per_delay);
876 SpinLockRelease(ProcStructLock);
881 * ProcQueue package: routines for putting processes to sleep
886 * ProcQueueAlloc -- alloc/attach to a shared memory process queue
888 * Returns: a pointer to the queue
889 * Side Effects: Initializes the queue if it wasn't there before
893 ProcQueueAlloc(const char *name)
898 queue = (PROC_QUEUE *)
899 ShmemInitStruct(name, sizeof(PROC_QUEUE), &found);
902 ProcQueueInit(queue);
909 * ProcQueueInit -- initialize a shared memory process queue
912 ProcQueueInit(PROC_QUEUE *queue)
914 SHMQueueInit(&(queue->links));
920 * ProcSleep -- put a process to sleep on the specified lock
922 * Caller must have set MyProc->heldLocks to reflect locks already held
923 * on the lockable object by this process (under all XIDs).
925 * The lock table's partition lock must be held at entry, and will be held
928 * Result: STATUS_OK if we acquired the lock, STATUS_ERROR if not (deadlock).
930 * ASSUME: that no one will fiddle with the queue until after
931 * we release the partition lock.
933 * NOTES: The process queue is now a priority queue for locking.
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.
939 ProcSleep(LOCALLOCK *locallock, LockMethod lockMethodTable)
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;
955 * Determine where to add myself in the wait queue.
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.
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
971 if (myHeldLocks != 0)
973 LOCKMASK aheadRequests = 0;
975 proc = (PGPROC *) waitQueue->links.next;
976 for (i = 0; i < waitQueue->size; i++)
978 /* Must he wait for me? */
979 if (lockMethodTable->conflictTab[proc->waitLockMode] & myHeldLocks)
981 /* Must I wait for him ? */
982 if (lockMethodTable->conflictTab[lockmode] & proc->heldLocks)
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.
991 RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
992 early_deadlock = true;
995 /* I must go before this waiter. Check special case. */
996 if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
997 LockCheckConflicts(lockMethodTable,
1000 proclock) == STATUS_OK)
1002 /* Skip the wait and just grant myself the lock. */
1003 GrantLock(lock, proclock, lockmode);
1007 /* Break out of loop to put myself before him */
1010 /* Nope, so advance to next waiter */
1011 aheadRequests |= LOCKBIT_ON(proc->waitLockMode);
1012 proc = (PGPROC *) proc->links.next;
1016 * If we fall out of loop normally, proc points to waitQueue head, so
1017 * we will insert at tail of queue as desired.
1022 /* I hold no locks, so I can't push in front of anyone. */
1023 proc = (PGPROC *) &(waitQueue->links);
1027 * Insert self into queue, ahead of the given proc (or at tail of queue).
1029 SHMQueueInsertBefore(&(proc->links), &(MyProc->links));
1032 lock->waitMask |= LOCKBIT_ON(lockmode);
1034 /* Set up wait information in PGPROC object, too */
1035 MyProc->waitLock = lock;
1036 MyProc->waitProcLock = proclock;
1037 MyProc->waitLockMode = lockmode;
1039 MyProc->waitStatus = STATUS_WAITING;
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.
1048 RemoveFromWaitQueue(MyProc, hashcode);
1049 return STATUS_ERROR;
1052 /* mark that we are waiting for a lock */
1053 lockAwaited = locallock;
1056 * Release the lock table's partition lock.
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.
1063 LWLockRelease(partitionLock);
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.
1071 if (RecoveryInProgress() && !InRecovery)
1072 CheckRecoveryConflictDeadlock();
1074 /* Reset deadlock_state before enabling the timeout handler */
1075 deadlock_state = DS_NOT_YET_CHECKED;
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.
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.
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.
1089 if (LockTimeout > 0)
1091 EnableTimeoutParams timeouts[2];
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);
1102 enable_timeout_after(DEADLOCK_TIMEOUT, DeadlockTimeout);
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.
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.
1123 PGSemaphoreLock(&MyProc->sem, true);
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).
1130 myWaitStatus = MyProc->waitStatus;
1133 * If we are not deadlocked, but are waiting on an autovacuum-induced
1134 * task, send a signal to interrupt it.
1136 if (deadlock_state == DS_BLOCKED_BY_AUTOVACUUM && allow_autovacuum_cancel)
1138 PGPROC *autovac = GetBlockingAutoVacuumPgproc();
1139 PGXACT *autovac_pgxact = &ProcGlobal->allPgXact[autovac->pgprocno];
1141 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
1144 * Only do it if the worker is not working to protect against Xid
1147 if ((autovac != NULL) &&
1148 (autovac_pgxact->vacuumFlags & PROC_IS_AUTOVACUUM) &&
1149 !(autovac_pgxact->vacuumFlags & PROC_VACUUM_FOR_WRAPAROUND))
1151 int pid = autovac->pid;
1152 StringInfoData locktagbuf;
1153 StringInfoData logbuf; /* errdetail for server log */
1155 initStringInfo(&locktagbuf);
1156 initStringInfo(&logbuf);
1157 DescribeLockTag(&locktagbuf, &lock->tag);
1158 appendStringInfo(&logbuf,
1159 _("Process %d waits for %s on %s."),
1161 GetLockmodeName(lock->tag.locktag_lockmethodid,
1165 /* release lock as quickly as possible */
1166 LWLockRelease(ProcArrayLock);
1169 (errmsg("sending cancel to blocking autovacuum PID %d",
1171 errdetail_log("%s", logbuf.data)));
1174 pfree(locktagbuf.data);
1176 /* send the autovacuum worker Back to Old Kent Road */
1177 if (kill(pid, SIGINT) < 0)
1179 /* Just a warning to allow multiple callers */
1181 (errmsg("could not send signal to process %d: %m",
1186 LWLockRelease(ProcArrayLock);
1188 /* prevent signal from being resent more than once */
1189 allow_autovacuum_cancel = false;
1193 * If awoken after the deadlock check interrupt has run, and
1194 * log_lock_waits is on, then report about the wait.
1196 if (log_lock_waits && deadlock_state != DS_NOT_YET_CHECKED)
1199 const char *modename;
1204 initStringInfo(&buf);
1205 DescribeLockTag(&buf, &locallock->tag.lock);
1206 modename = GetLockmodeName(locallock->tag.lock.locktag_lockmethodid,
1208 TimestampDifference(get_timeout_start_time(DEADLOCK_TIMEOUT),
1209 GetCurrentTimestamp(),
1211 msecs = secs * 1000 + usecs / 1000;
1212 usecs = usecs % 1000;
1214 if (deadlock_state == DS_SOFT_DEADLOCK)
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)
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.
1228 (errmsg("process %d detected deadlock while waiting for %s on %s after %ld.%03d ms",
1229 MyProcPid, modename, buf.data, msecs, usecs)));
1232 if (myWaitStatus == STATUS_WAITING)
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)
1238 (errmsg("process %d acquired %s on %s after %ld.%03d ms",
1239 MyProcPid, modename, buf.data, msecs, usecs)));
1242 Assert(myWaitStatus == STATUS_ERROR);
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.
1252 if (deadlock_state != DS_HARD_DEADLOCK)
1254 (errmsg("process %d failed to acquire %s on %s after %ld.%03d ms",
1255 MyProcPid, modename, buf.data, msecs, usecs)));
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.
1262 deadlock_state = DS_NO_DEADLOCK;
1266 } while (myWaitStatus == STATUS_WAITING);
1269 * Disable the timers, if they are still running
1271 if (LockTimeout > 0)
1273 DisableTimeoutParams timeouts[2];
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);
1282 disable_timeout(DEADLOCK_TIMEOUT, false);
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).
1289 LWLockAcquire(partitionLock, LW_EXCLUSIVE);
1292 * We no longer want LockErrorCleanup to do anything.
1297 * If we got the lock, be sure to remember it in the locallock table.
1299 if (MyProc->waitStatus == STATUS_OK)
1303 * We don't have to do anything else, because the awaker did all the
1304 * necessary update of the lock table and MyProc.
1306 return MyProc->waitStatus;
1311 * ProcWakeup -- wake up a process by releasing its private semaphore.
1313 * Also remove the process from the wait queue and set its links invalid.
1314 * RETURN: the next process in the wait queue.
1316 * The appropriate lock partition lock must be held by caller.
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.
1324 ProcWakeup(PGPROC *proc, int waitStatus)
1328 /* Proc should be sleeping ... */
1329 if (proc->links.prev == NULL ||
1330 proc->links.next == NULL)
1332 Assert(proc->waitStatus == STATUS_WAITING);
1334 /* Save next process before we zap the list link */
1335 retProc = (PGPROC *) proc->links.next;
1337 /* Remove process from wait queue */
1338 SHMQueueDelete(&(proc->links));
1339 (proc->waitLock->waitProcs.size)--;
1341 /* Clean up process' state and pass it the ok/fail signal */
1342 proc->waitLock = NULL;
1343 proc->waitProcLock = NULL;
1344 proc->waitStatus = waitStatus;
1347 PGSemaphoreUnlock(&proc->sem);
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.
1357 * The appropriate lock partition lock must be held by caller.
1360 ProcLockWakeup(LockMethod lockMethodTable, LOCK *lock)
1362 PROC_QUEUE *waitQueue = &(lock->waitProcs);
1363 int queue_size = waitQueue->size;
1365 LOCKMASK aheadRequests = 0;
1367 Assert(queue_size >= 0);
1369 if (queue_size == 0)
1372 proc = (PGPROC *) waitQueue->links.next;
1374 while (queue_size-- > 0)
1376 LOCKMODE lockmode = proc->waitLockMode;
1379 * Waken if (a) doesn't conflict with requests of earlier waiters, and
1380 * (b) doesn't conflict with already-held locks.
1382 if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
1383 LockCheckConflicts(lockMethodTable,
1386 proc->waitProcLock) == STATUS_OK)
1389 GrantLock(lock, proc->waitProcLock, lockmode);
1390 proc = ProcWakeup(proc, STATUS_OK);
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.
1401 * Cannot wake this guy. Remember his request for later checks.
1403 aheadRequests |= LOCKBIT_ON(lockmode);
1404 proc = (PGPROC *) proc->links.next;
1408 Assert(waitQueue->size >= 0);
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.
1421 * NB: this is run inside a signal handler, so be very wary about what is done
1422 * here or in called routines.
1430 * Acquire exclusive lock on the entire shared lock data structures. Must
1431 * grab LWLocks in partition-number order to avoid LWLock deadlock.
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
1439 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
1440 LWLockAcquire(FirstLockMgrLock + i, LW_EXCLUSIVE);
1443 * Check to see if we've been awoken by anyone in the interim.
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.
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.
1453 if (MyProc->links.prev == NULL ||
1454 MyProc->links.next == NULL)
1458 if (Debug_deadlocks)
1462 /* Run the deadlock check, and set deadlock_state for use by ProcSleep */
1463 deadlock_state = DeadLockCheck(MyProc);
1465 if (deadlock_state == DS_HARD_DEADLOCK)
1468 * Oops. We have a deadlock.
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.)
1475 * RemoveFromWaitQueue sets MyProc->waitStatus to STATUS_ERROR, so
1476 * ProcSleep will report an error after we return from the signal
1479 Assert(MyProc->waitLock != NULL);
1480 RemoveFromWaitQueue(MyProc, LockTagHashCode(&(MyProc->waitLock->tag)));
1483 * Unlock my semaphore so that the interrupted ProcSleep() call can
1486 PGSemaphoreUnlock(&MyProc->sem);
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.
1499 else if (log_lock_waits || deadlock_state == DS_BLOCKED_BY_AUTOVACUUM)
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
1507 * If blocked by autovacuum, this wakeup will enable ProcSleep to send
1508 * the canceling signal to the autovacuum worker.
1510 PGSemaphoreUnlock(&MyProc->sem);
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.
1521 for (i = NUM_LOCK_PARTITIONS; --i >= 0;)
1522 LWLockRelease(FirstLockMgrLock + i);
1527 * ProcWaitForSignal - wait for a signal from another backend.
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.
1538 ProcWaitForSignal(void)
1540 PGSemaphoreLock(&MyProc->sem, true);
1544 * ProcSendSignal - send a signal to a backend identified by PID
1547 ProcSendSignal(int pid)
1549 PGPROC *proc = NULL;
1551 if (RecoveryInProgress())
1553 /* use volatile pointer to prevent code rearrangement */
1554 volatile PROC_HDR *procglobal = ProcGlobal;
1556 SpinLockAcquire(ProcStructLock);
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.
1566 if (pid == procglobal->startupProcPid)
1567 proc = procglobal->startupProc;
1569 SpinLockRelease(ProcStructLock);
1573 proc = BackendPidGetProc(pid);
1576 PGSemaphoreUnlock(&proc->sem);