PostgreSQL Source Code  git master
lwlock.c File Reference
#include "postgres.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "pgstat.h"
#include "postmaster/postmaster.h"
#include "replication/slot.h"
#include "storage/ipc.h"
#include "storage/predicate.h"
#include "storage/proc.h"
#include "storage/proclist.h"
#include "storage/spin.h"
#include "utils/memutils.h"
Include dependency graph for lwlock.c:

Go to the source code of this file.

Data Structures

struct  LWLockHandle
 
struct  NamedLWLockTrancheRequest
 

Macros

#define LW_FLAG_HAS_WAITERS   ((uint32) 1 << 30)
 
#define LW_FLAG_RELEASE_OK   ((uint32) 1 << 29)
 
#define LW_FLAG_LOCKED   ((uint32) 1 << 28)
 
#define LW_VAL_EXCLUSIVE   ((uint32) 1 << 24)
 
#define LW_VAL_SHARED   1
 
#define LW_LOCK_MASK   ((uint32) ((1 << 25)-1))
 
#define LW_SHARED_MASK   ((uint32) ((1 << 24)-1))
 
#define MAX_SIMUL_LWLOCKS   200
 
#define T_NAME(lock)   GetLWTrancheName((lock)->tranche)
 
#define PRINT_LWDEBUG(a, b, c)   ((void)0)
 
#define LOG_LWDEBUG(a, b, c)   ((void)0)
 

Typedefs

typedef struct LWLockHandle LWLockHandle
 
typedef struct NamedLWLockTrancheRequest NamedLWLockTrancheRequest
 

Functions

 StaticAssertDecl (lengthof(BuiltinTrancheNames)==LWTRANCHE_FIRST_USER_DEFINED - NUM_INDIVIDUAL_LWLOCKS, "missing entries in BuiltinTrancheNames[]")
 
static void InitializeLWLocks (void)
 
static void LWLockReportWaitStart (LWLock *lock)
 
static void LWLockReportWaitEnd (void)
 
static const char * GetLWTrancheName (uint16 trancheId)
 
static int NumLWLocksForNamedTranches (void)
 
Size LWLockShmemSize (void)
 
void CreateLWLocks (void)
 
void InitLWLockAccess (void)
 
LWLockPaddedGetNamedLWLockTranche (const char *tranche_name)
 
int LWLockNewTrancheId (void)
 
void LWLockRegisterTranche (int tranche_id, const char *tranche_name)
 
void RequestNamedLWLockTranche (const char *tranche_name, int num_lwlocks)
 
void LWLockInitialize (LWLock *lock, int tranche_id)
 
const char * GetLWLockIdentifier (uint32 classId, uint16 eventId)
 
static bool LWLockAttemptLock (LWLock *lock, LWLockMode mode)
 
static void LWLockWaitListLock (LWLock *lock)
 
static void LWLockWaitListUnlock (LWLock *lock)
 
static void LWLockWakeup (LWLock *lock)
 
static void LWLockQueueSelf (LWLock *lock, LWLockMode mode)
 
static void LWLockDequeueSelf (LWLock *lock)
 
bool LWLockAcquire (LWLock *lock, LWLockMode mode)
 
bool LWLockConditionalAcquire (LWLock *lock, LWLockMode mode)
 
bool LWLockAcquireOrWait (LWLock *lock, LWLockMode mode)
 
static bool LWLockConflictsWithVar (LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval, bool *result)
 
bool LWLockWaitForVar (LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval)
 
void LWLockUpdateVar (LWLock *lock, uint64 *valptr, uint64 val)
 
void LWLockRelease (LWLock *lock)
 
void LWLockReleaseClearVar (LWLock *lock, uint64 *valptr, uint64 val)
 
void LWLockReleaseAll (void)
 
bool LWLockHeldByMe (LWLock *l)
 
bool LWLockHeldByMeInMode (LWLock *l, LWLockMode mode)
 

Variables

slock_tShmemLock
 
const char *const IndividualLWLockNames []
 
static const char *const BuiltinTrancheNames []
 
static const char ** LWLockTrancheNames = NULL
 
static int LWLockTrancheNamesAllocated = 0
 
LWLockPaddedMainLWLockArray = NULL
 
static int num_held_lwlocks = 0
 
static LWLockHandle held_lwlocks [MAX_SIMUL_LWLOCKS]
 
static NamedLWLockTrancheRequestNamedLWLockTrancheRequestArray = NULL
 
static int NamedLWLockTrancheRequestsAllocated = 0
 
int NamedLWLockTrancheRequests = 0
 
NamedLWLockTrancheNamedLWLockTrancheArray = NULL
 
static bool lock_named_request_allowed = true
 

Macro Definition Documentation

◆ LOG_LWDEBUG

#define LOG_LWDEBUG (   a,
  b,
  c 
)    ((void)0)

◆ LW_FLAG_HAS_WAITERS

#define LW_FLAG_HAS_WAITERS   ((uint32) 1 << 30)

Definition at line 99 of file lwlock.c.

Referenced by LWLockDequeueSelf(), LWLockQueueSelf(), LWLockRelease(), and LWLockWakeup().

◆ LW_FLAG_LOCKED

#define LW_FLAG_LOCKED   ((uint32) 1 << 28)

Definition at line 101 of file lwlock.c.

Referenced by LWLockWaitListLock(), LWLockWaitListUnlock(), and LWLockWakeup().

◆ LW_FLAG_RELEASE_OK

#define LW_FLAG_RELEASE_OK   ((uint32) 1 << 29)

◆ LW_LOCK_MASK

#define LW_LOCK_MASK   ((uint32) ((1 << 25)-1))

Definition at line 106 of file lwlock.c.

Referenced by LWLockAttemptLock(), and LWLockRelease().

◆ LW_SHARED_MASK

#define LW_SHARED_MASK   ((uint32) ((1 << 24)-1))

Definition at line 108 of file lwlock.c.

◆ LW_VAL_EXCLUSIVE

#define LW_VAL_EXCLUSIVE   ((uint32) 1 << 24)

◆ LW_VAL_SHARED

#define LW_VAL_SHARED   1

Definition at line 104 of file lwlock.c.

Referenced by LWLockAttemptLock(), and LWLockRelease().

◆ MAX_SIMUL_LWLOCKS

#define MAX_SIMUL_LWLOCKS   200

Definition at line 206 of file lwlock.c.

Referenced by LWLockAcquire(), LWLockAcquireOrWait(), and LWLockConditionalAcquire().

◆ PRINT_LWDEBUG

#define PRINT_LWDEBUG (   a,
  b,
  c 
)    ((void)0)

◆ T_NAME

#define T_NAME (   lock)    GetLWTrancheName((lock)->tranche)

Typedef Documentation

◆ LWLockHandle

typedef struct LWLockHandle LWLockHandle

◆ NamedLWLockTrancheRequest

Function Documentation

◆ CreateLWLocks()

void CreateLWLocks ( void  )

Definition at line 465 of file lwlock.c.

References i, InitializeLWLocks(), IsUnderPostmaster, LW_VAL_EXCLUSIVE, LWLOCK_PADDED_SIZE, LWLockRegisterTranche(), LWLockShmemSize(), LWTRANCHE_FIRST_USER_DEFINED, MAX_BACKENDS, NamedLWLockTrancheRequests, ShmemAlloc(), and StaticAssertStmt.

Referenced by CreateSharedMemoryAndSemaphores().

466 {
468  "MAX_BACKENDS too big for lwlock.c");
469 
471  "Miscalculated LWLock padding");
472 
473  if (!IsUnderPostmaster)
474  {
475  Size spaceLocks = LWLockShmemSize();
476  int *LWLockCounter;
477  char *ptr;
478 
479  /* Allocate space */
480  ptr = (char *) ShmemAlloc(spaceLocks);
481 
482  /* Leave room for dynamic allocation of tranches */
483  ptr += sizeof(int);
484 
485  /* Ensure desired alignment of LWLock array */
486  ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
487 
488  MainLWLockArray = (LWLockPadded *) ptr;
489 
490  /*
491  * Initialize the dynamic-allocation counter for tranches, which is
492  * stored just before the first LWLock.
493  */
494  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
495  *LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
496 
497  /* Initialize all LWLocks */
499  }
500 
501  /* Register named extension LWLock tranches in the current process. */
502  for (int i = 0; i < NamedLWLockTrancheRequests; i++)
504  NamedLWLockTrancheArray[i].trancheName);
505 }
Definition: lwlock.h:31
void * ShmemAlloc(Size size)
Definition: shmem.c:161
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:237
Size LWLockShmemSize(void)
Definition: lwlock.c:432
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:648
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:918
#define MAX_BACKENDS
Definition: postmaster.h:76
int NamedLWLockTrancheRequests
Definition: lwlock.c:234
bool IsUnderPostmaster
Definition: globals.c:112
unsigned int uint32
Definition: c.h:441
static void InitializeLWLocks(void)
Definition: lwlock.c:511
size_t Size
Definition: c.h:540
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:103
int i
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:52
LWLockPadded * MainLWLockArray
Definition: lwlock.c:198

◆ GetLWLockIdentifier()

const char* GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 804 of file lwlock.c.

References Assert, GetLWTrancheName(), and PG_WAIT_LWLOCK.

Referenced by pgstat_get_wait_event().

805 {
806  Assert(classId == PG_WAIT_LWLOCK);
807  /* The event IDs are just tranche numbers. */
808  return GetLWTrancheName(eventId);
809 }
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:776
#define PG_WAIT_LWLOCK
Definition: wait_event.h:18
#define Assert(condition)
Definition: c.h:804

◆ GetLWTrancheName()

static const char * GetLWTrancheName ( uint16  trancheId)
static

Definition at line 776 of file lwlock.c.

References BuiltinTrancheNames, IndividualLWLockNames, LWLockTrancheNames, LWLockTrancheNamesAllocated, and LWTRANCHE_FIRST_USER_DEFINED.

Referenced by GetLWLockIdentifier().

777 {
778  /* Individual LWLock? */
779  if (trancheId < NUM_INDIVIDUAL_LWLOCKS)
780  return IndividualLWLockNames[trancheId];
781 
782  /* Built-in tranche? */
783  if (trancheId < LWTRANCHE_FIRST_USER_DEFINED)
784  return BuiltinTrancheNames[trancheId - NUM_INDIVIDUAL_LWLOCKS];
785 
786  /*
787  * It's an extension tranche, so look in LWLockTrancheNames[]. However,
788  * it's possible that the tranche has never been registered in the current
789  * process, in which case give up and return "extension".
790  */
791  trancheId -= LWTRANCHE_FIRST_USER_DEFINED;
792 
793  if (trancheId >= LWLockTrancheNamesAllocated ||
794  LWLockTrancheNames[trancheId] == NULL)
795  return "extension";
796 
797  return LWLockTrancheNames[trancheId];
798 }
static int LWLockTrancheNamesAllocated
Definition: lwlock.c:191
const char *const IndividualLWLockNames[]
static const char *const BuiltinTrancheNames[]
Definition: lwlock.c:130
static const char ** LWLockTrancheNames
Definition: lwlock.c:190

◆ GetNamedLWLockTranche()

LWLockPadded* GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 594 of file lwlock.c.

References elog, ERROR, i, NamedLWLockTrancheRequests, NUM_FIXED_LWLOCKS, and NamedLWLockTrancheRequest::num_lwlocks.

Referenced by pgss_shmem_startup().

595 {
596  int lock_pos;
597  int i;
598 
599  /*
600  * Obtain the position of base address of LWLock belonging to requested
601  * tranche_name in MainLWLockArray. LWLocks for named tranches are placed
602  * in MainLWLockArray after fixed locks.
603  */
604  lock_pos = NUM_FIXED_LWLOCKS;
605  for (i = 0; i < NamedLWLockTrancheRequests; i++)
606  {
607  if (strcmp(NamedLWLockTrancheRequestArray[i].tranche_name,
608  tranche_name) == 0)
609  return &MainLWLockArray[lock_pos];
610 
612  }
613 
614  elog(ERROR, "requested tranche is not registered");
615 
616  /* just to keep compiler quiet */
617  return NULL;
618 }
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:99
#define ERROR
Definition: elog.h:46
int NamedLWLockTrancheRequests
Definition: lwlock.c:234
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:225
#define elog(elevel,...)
Definition: elog.h:232
int i
LWLockPadded * MainLWLockArray
Definition: lwlock.c:198

◆ InitializeLWLocks()

static void InitializeLWLocks ( void  )
static

Definition at line 511 of file lwlock.c.

References BUFFER_MAPPING_LWLOCK_OFFSET, i, LWLockPadded::lock, LWLockHandle::lock, LOCK_MANAGER_LWLOCK_OFFSET, LWLockInitialize(), LWLockNewTrancheId(), LWTRANCHE_BUFFER_MAPPING, LWTRANCHE_LOCK_MANAGER, LWTRANCHE_PREDICATE_LOCK_MANAGER, name, NamedLWLockTrancheRequests, NUM_BUFFER_PARTITIONS, NUM_FIXED_LWLOCKS, NUM_LOCK_PARTITIONS, NamedLWLockTrancheRequest::num_lwlocks, NUM_PREDICATELOCK_PARTITIONS, NumLWLocksForNamedTranches(), PREDICATELOCK_MANAGER_LWLOCK_OFFSET, NamedLWLockTrancheRequest::tranche_name, NamedLWLockTranche::trancheId, and NamedLWLockTranche::trancheName.

Referenced by CreateLWLocks().

512 {
513  int numNamedLocks = NumLWLocksForNamedTranches();
514  int id;
515  int i;
516  int j;
517  LWLockPadded *lock;
518 
519  /* Initialize all individual LWLocks in main array */
520  for (id = 0, lock = MainLWLockArray; id < NUM_INDIVIDUAL_LWLOCKS; id++, lock++)
521  LWLockInitialize(&lock->lock, id);
522 
523  /* Initialize buffer mapping LWLocks in main array */
525  for (id = 0; id < NUM_BUFFER_PARTITIONS; id++, lock++)
527 
528  /* Initialize lmgrs' LWLocks in main array */
530  for (id = 0; id < NUM_LOCK_PARTITIONS; id++, lock++)
532 
533  /* Initialize predicate lmgrs' LWLocks in main array */
535  for (id = 0; id < NUM_PREDICATELOCK_PARTITIONS; id++, lock++)
537 
538  /*
539  * Copy the info about any named tranches into shared memory (so that
540  * other processes can see it), and initialize the requested LWLocks.
541  */
543  {
544  char *trancheNames;
545 
547  &MainLWLockArray[NUM_FIXED_LWLOCKS + numNamedLocks];
548 
549  trancheNames = (char *) NamedLWLockTrancheArray +
552 
553  for (i = 0; i < NamedLWLockTrancheRequests; i++)
554  {
555  NamedLWLockTrancheRequest *request;
556  NamedLWLockTranche *tranche;
557  char *name;
558 
559  request = &NamedLWLockTrancheRequestArray[i];
560  tranche = &NamedLWLockTrancheArray[i];
561 
562  name = trancheNames;
563  trancheNames += strlen(request->tranche_name) + 1;
564  strcpy(name, request->tranche_name);
565  tranche->trancheId = LWLockNewTrancheId();
566  tranche->trancheName = name;
567 
568  for (j = 0; j < request->num_lwlocks; j++, lock++)
569  LWLockInitialize(&lock->lock, tranche->trancheId);
570  }
571  }
572 }
#define BUFFER_MAPPING_LWLOCK_OFFSET
Definition: lwlock.h:94
int LWLockNewTrancheId(void)
Definition: lwlock.c:624
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:221
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:237
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:99
int NamedLWLockTrancheRequests
Definition: lwlock.c:234
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:417
#define NUM_BUFFER_PARTITIONS
Definition: lwlock.h:83
char * trancheName
Definition: lwlock.h:67
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:740
#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:97
LWLock lock
Definition: lwlock.h:57
const char * name
Definition: encode.c:515
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:225
#define LOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:95
int i
LWLockPadded * MainLWLockArray
Definition: lwlock.c:198
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:87
#define NUM_PREDICATELOCK_PARTITIONS
Definition: lwlock.h:91

◆ InitLWLockAccess()

void InitLWLockAccess ( void  )

Definition at line 578 of file lwlock.c.

Referenced by InitProcess().

579 {
580 #ifdef LWLOCK_STATS
581  init_lwlock_stats();
582 #endif
583 }

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1203 of file lwlock.c.

References Assert, AssertArg, elog, ERROR, HOLD_INTERRUPTS, IsUnderPostmaster, LWLockHandle::lock, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_RELEASE_OK, LW_SHARED, LWLockAttemptLock(), LWLockDequeueSelf(), LWLockQueueSelf(), LWLockReportWaitEnd(), LWLockReportWaitStart(), PGPROC::lwWaiting, MAX_BACKENDS, MAX_SIMUL_LWLOCKS, LWLockHandle::mode, MyProc, num_held_lwlocks, pg_atomic_fetch_or_u32(), pg_atomic_fetch_sub_u32(), PG_USED_FOR_ASSERTS_ONLY, PGSemaphoreLock(), PGSemaphoreUnlock(), PRINT_LWDEBUG, PGPROC::sem, LWLock::state, and T_NAME.

Referenced by _bt_end_vacuum(), _bt_start_vacuum(), _bt_vacuum_cycleid(), AbsorbSyncRequests(), ActivateCommitTs(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_init_shmem(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacLauncherMain(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendIdGetProc(), BackendIdGetTransactionIds(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BootStrapCLOG(), BootStrapMultiXact(), BootStrapSUBTRANS(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), CheckRecoveryConsistency(), CheckTableForSerializableConflictIn(), CheckTargetForConflictsIn(), choose_next_subplan_for_leader(), choose_next_subplan_for_worker(), CleanupInvalidationState(), ClearOldPredicateLocks(), clog_redo(), commit_ts_redo(), ComputeXidHorizons(), copy_replication_slot(), CountDBBackends(), CountDBConnections(), CountOtherDBBackends(), CountUserBackends(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateInitDecodingContext(), CreatePredicateLock(), CreateRestartPoint(), DeactivateCommitTs(), DeleteChildTargetLocks(), DeleteLockTarget(), destroy_superblock(), do_autovacuum(), do_pg_start_backup(), do_pg_stop_backup(), do_start_worker(), DropAllPredicateLocksFromTable(), DropSubscription(), DropTableSpace(), dsa_allocate_extended(), dsa_dump(), dsa_free(), dsa_pin(), dsa_release_in_place(), dsa_set_size_limit(), dsa_trim(), dsa_unpin(), dshash_delete_key(), dshash_dump(), dshash_find(), dshash_find_or_insert(), dsm_attach(), dsm_create(), dsm_detach(), dsm_pin_segment(), dsm_unpin_segment(), ensure_active_superblock(), entry_reset(), Exec_ListenPreCommit(), ExecParallelHashMergeCounters(), ExecParallelHashPopChunkQueue(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), ExpireAllKnownAssignedTransactionIds(), ExpireOldKnownAssignedTransactionIds(), ExpireTreeKnownAssignedTransactionIds(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), FindAndDropRelFileNodeBuffers(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), FlushRelationsAllBuffers(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), get_xid_status(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldSnapshotFromTimeMapping(), GetOldSnapshotTimeMapping(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionData(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), HandleAutoVacLauncherInterrupts(), HaveVirtualXIDsDelayingChkpt(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), KnownAssignedXidsAdd(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockBuffer(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_worker_attach(), logicalrep_worker_detach(), logicalrep_worker_launch(), logicalrep_worker_stop(), logicalrep_worker_wakeup(), MaintainOldSnapshotTimeMapping(), MarkAsPrepared(), MarkAsPreparing(), MaybeExtendOffsetSlru(), multixact_redo(), MultiXactAdvanceNextMXact(), MultiXactGetCheckptMulti(), MultiXactIdSetOldestMember(), MultiXactIdSetOldestVisible(), MultiXactSetNextMXact(), PageIsPredicateLocked(), perform_relmap_update(), pg_get_replication_slots(), pg_get_shmem_allocations(), pg_notification_queue_usage(), pg_show_replication_origin_status(), pg_stat_get_subscription(), pg_stat_statements_internal(), pg_xact_status(), pgss_shmem_startup(), pgss_store(), PostPrepare_Locks(), PostPrepare_MultiXact(), PostPrepare_Twophase(), PreCommit_CheckForSerializationFailure(), PreCommit_Notify(), predicatelock_twophase_recover(), PredicateLockPageSplit(), PredicateLockTwoPhaseFinish(), PrefetchSharedBuffer(), PrescanPreparedTransactions(), ProcArrayAdd(), ProcArrayApplyRecoveryInfo(), ProcArrayApplyXidAssignment(), ProcArrayClearTransaction(), ProcArrayEndTransaction(), ProcArrayGetReplicationSlotXmin(), ProcArrayGroupClearXid(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), ProcArrayRemove(), ProcArraySetReplicationSlotXmin(), process_syncing_tables_for_apply(), ProcKill(), ProcSleep(), ReadBuffer_common(), ReadMultiXactCounts(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadRecord(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePreInvalidate(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquireInternal(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDropPtr(), ReplicationSlotRelease(), ReplicationSlotsComputeLogicalRestartLSN(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), replorigin_advance(), replorigin_drop_guts(), replorigin_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset(), replorigin_session_setup(), resize(), RestoreScratchTarget(), restoreTwoPhaseData(), SaveSlotToPath(), SearchNamedReplicationSlot(), SerialAdd(), SerialGetMinConflictCommitSeqNo(), SerialSetActiveSerXmin(), set_indexsafe_procflags(), SetCommitTsLimit(), SetMultiXactIdLimit(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SignalVirtualTransaction(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), StandbyRecoverPreparedTransactions(), StartupCLOG(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SyncOneBuffer(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateOtherDBBackends(), TransactionGroupUpdateXidStatus(), TransactionIdGetCommitTsData(), TransactionIdIsActive(), TransactionIdIsInProgress(), TransactionIdSetPageStatus(), TransactionTreeSetCommitTsData(), TransferPredicateLocksToNewTarget(), TrimCLOG(), TrimMultiXact(), TruncateMultiXact(), TwoPhaseGetGXact(), update_cached_xid_range(), UpdateMinRecoveryPoint(), vac_truncate_clog(), vacuum_rel(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitForReplicationWorkerAttach(), WALInsertLockAcquire(), WALInsertLockAcquireExclusive(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), and XLogReportParameters().

1204 {
1205  PGPROC *proc = MyProc;
1206  bool result = true;
1207  int extraWaits = 0;
1208 #ifdef LWLOCK_STATS
1209  lwlock_stats *lwstats;
1210 
1211  lwstats = get_lwlock_stats_entry(lock);
1212 #endif
1213 
1215 
1216  PRINT_LWDEBUG("LWLockAcquire", lock, mode);
1217 
1218 #ifdef LWLOCK_STATS
1219  /* Count lock acquisition attempts */
1220  if (mode == LW_EXCLUSIVE)
1221  lwstats->ex_acquire_count++;
1222  else
1223  lwstats->sh_acquire_count++;
1224 #endif /* LWLOCK_STATS */
1225 
1226  /*
1227  * We can't wait if we haven't got a PGPROC. This should only occur
1228  * during bootstrap or shared memory initialization. Put an Assert here
1229  * to catch unsafe coding practices.
1230  */
1231  Assert(!(proc == NULL && IsUnderPostmaster));
1232 
1233  /* Ensure we will have room to remember the lock */
1235  elog(ERROR, "too many LWLocks taken");
1236 
1237  /*
1238  * Lock out cancel/die interrupts until we exit the code section protected
1239  * by the LWLock. This ensures that interrupts will not interfere with
1240  * manipulations of data structures in shared memory.
1241  */
1242  HOLD_INTERRUPTS();
1243 
1244  /*
1245  * Loop here to try to acquire lock after each time we are signaled by
1246  * LWLockRelease.
1247  *
1248  * NOTE: it might seem better to have LWLockRelease actually grant us the
1249  * lock, rather than retrying and possibly having to go back to sleep. But
1250  * in practice that is no good because it means a process swap for every
1251  * lock acquisition when two or more processes are contending for the same
1252  * lock. Since LWLocks are normally used to protect not-very-long
1253  * sections of computation, a process needs to be able to acquire and
1254  * release the same lock many times during a single CPU time slice, even
1255  * in the presence of contention. The efficiency of being able to do that
1256  * outweighs the inefficiency of sometimes wasting a process dispatch
1257  * cycle because the lock is not free when a released waiter finally gets
1258  * to run. See pgsql-hackers archives for 29-Dec-01.
1259  */
1260  for (;;)
1261  {
1262  bool mustwait;
1263 
1264  /*
1265  * Try to grab the lock the first time, we're not in the waitqueue
1266  * yet/anymore.
1267  */
1268  mustwait = LWLockAttemptLock(lock, mode);
1269 
1270  if (!mustwait)
1271  {
1272  LOG_LWDEBUG("LWLockAcquire", lock, "immediately acquired lock");
1273  break; /* got the lock */
1274  }
1275 
1276  /*
1277  * Ok, at this point we couldn't grab the lock on the first try. We
1278  * cannot simply queue ourselves to the end of the list and wait to be
1279  * woken up because by now the lock could long have been released.
1280  * Instead add us to the queue and try to grab the lock again. If we
1281  * succeed we need to revert the queuing and be happy, otherwise we
1282  * recheck the lock. If we still couldn't grab it, we know that the
1283  * other locker will see our queue entries when releasing since they
1284  * existed before we checked for the lock.
1285  */
1286 
1287  /* add to the queue */
1288  LWLockQueueSelf(lock, mode);
1289 
1290  /* we're now guaranteed to be woken up if necessary */
1291  mustwait = LWLockAttemptLock(lock, mode);
1292 
1293  /* ok, grabbed the lock the second time round, need to undo queueing */
1294  if (!mustwait)
1295  {
1296  LOG_LWDEBUG("LWLockAcquire", lock, "acquired, undoing queue");
1297 
1298  LWLockDequeueSelf(lock);
1299  break;
1300  }
1301 
1302  /*
1303  * Wait until awakened.
1304  *
1305  * Since we share the process wait semaphore with the regular lock
1306  * manager and ProcWaitForSignal, and we may need to acquire an LWLock
1307  * while one of those is pending, it is possible that we get awakened
1308  * for a reason other than being signaled by LWLockRelease. If so,
1309  * loop back and wait again. Once we've gotten the LWLock,
1310  * re-increment the sema by the number of additional signals received,
1311  * so that the lock manager or signal manager will see the received
1312  * signal when it next waits.
1313  */
1314  LOG_LWDEBUG("LWLockAcquire", lock, "waiting");
1315 
1316 #ifdef LWLOCK_STATS
1317  lwstats->block_count++;
1318 #endif
1319 
1320  LWLockReportWaitStart(lock);
1321  if (TRACE_POSTGRESQL_LWLOCK_WAIT_START_ENABLED())
1322  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), mode);
1323 
1324  for (;;)
1325  {
1326  PGSemaphoreLock(proc->sem);
1327  if (!proc->lwWaiting)
1328  break;
1329  extraWaits++;
1330  }
1331 
1332  /* Retrying, allow LWLockRelease to release waiters again. */
1334 
1335 #ifdef LOCK_DEBUG
1336  {
1337  /* not waiting anymore */
1338  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1339 
1340  Assert(nwaiters < MAX_BACKENDS);
1341  }
1342 #endif
1343 
1344  if (TRACE_POSTGRESQL_LWLOCK_WAIT_DONE_ENABLED())
1345  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode);
1347 
1348  LOG_LWDEBUG("LWLockAcquire", lock, "awakened");
1349 
1350  /* Now loop back and try to acquire lock again. */
1351  result = false;
1352  }
1353 
1354  if (TRACE_POSTGRESQL_LWLOCK_ACQUIRE_ENABLED())
1355  TRACE_POSTGRESQL_LWLOCK_ACQUIRE(T_NAME(lock), mode);
1356 
1357  /* Add lock to list of locks held by this backend */
1360 
1361  /*
1362  * Fix the process wait semaphore's count for any absorbed wakeups.
1363  */
1364  while (extraWaits-- > 0)
1365  PGSemaphoreUnlock(proc->sem);
1366 
1367  return result;
1368 }
#define T_NAME(lock)
Definition: lwlock.c:246
static PgChecksumMode mode
Definition: pg_checksums.c:61
static uint32 pg_atomic_fetch_sub_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:343
static bool LWLockAttemptLock(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:821
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
PGPROC * MyProc
Definition: proc.c:68
bool lwWaiting
Definition: proc.h:170
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:206
pg_atomic_uint32 state
Definition: lwlock.h:34
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:216
#define ERROR
Definition: elog.h:46
#define MAX_BACKENDS
Definition: postmaster.h:76
LWLockMode mode
Definition: lwlock.c:212
bool IsUnderPostmaster
Definition: globals.c:112
static void LWLockReportWaitEnd(void)
Definition: lwlock.c:767
unsigned int uint32
Definition: c.h:441
static void LWLockDequeueSelf(LWLock *lock)
Definition: lwlock.c:1108
#define AssertArg(condition)
Definition: c.h:806
static void LWLockReportWaitStart(LWLock *lock)
Definition: lwlock.c:758
static void LWLockQueueSelf(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1064
static int num_held_lwlocks
Definition: lwlock.c:215
#define Assert(condition)
Definition: c.h:804
LWLock * lock
Definition: lwlock.c:211
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:310
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:100
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:320
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:119
#define elog(elevel,...)
Definition: elog.h:232
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:372
PGSemaphore sem
Definition: proc.h:127
Definition: proc.h:121
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:311

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1435 of file lwlock.c.

References Assert, elog, ERROR, HOLD_INTERRUPTS, LWLockHandle::lock, LOG_LWDEBUG, LW_EXCLUSIVE, LW_SHARED, LW_WAIT_UNTIL_FREE, LWLockAttemptLock(), LWLockDequeueSelf(), LWLockQueueSelf(), LWLockReportWaitEnd(), LWLockReportWaitStart(), PGPROC::lwWaiting, MAX_BACKENDS, MAX_SIMUL_LWLOCKS, LWLockHandle::mode, MyProc, num_held_lwlocks, pg_atomic_fetch_sub_u32(), PG_USED_FOR_ASSERTS_ONLY, PGSemaphoreLock(), PGSemaphoreUnlock(), PRINT_LWDEBUG, RESUME_INTERRUPTS, PGPROC::sem, and T_NAME.

Referenced by XLogFlush().

1436 {
1437  PGPROC *proc = MyProc;
1438  bool mustwait;
1439  int extraWaits = 0;
1440 #ifdef LWLOCK_STATS
1441  lwlock_stats *lwstats;
1442 
1443  lwstats = get_lwlock_stats_entry(lock);
1444 #endif
1445 
1447 
1448  PRINT_LWDEBUG("LWLockAcquireOrWait", lock, mode);
1449 
1450  /* Ensure we will have room to remember the lock */
1452  elog(ERROR, "too many LWLocks taken");
1453 
1454  /*
1455  * Lock out cancel/die interrupts until we exit the code section protected
1456  * by the LWLock. This ensures that interrupts will not interfere with
1457  * manipulations of data structures in shared memory.
1458  */
1459  HOLD_INTERRUPTS();
1460 
1461  /*
1462  * NB: We're using nearly the same twice-in-a-row lock acquisition
1463  * protocol as LWLockAcquire(). Check its comments for details.
1464  */
1465  mustwait = LWLockAttemptLock(lock, mode);
1466 
1467  if (mustwait)
1468  {
1470 
1471  mustwait = LWLockAttemptLock(lock, mode);
1472 
1473  if (mustwait)
1474  {
1475  /*
1476  * Wait until awakened. Like in LWLockAcquire, be prepared for
1477  * bogus wakeups, because we share the semaphore with
1478  * ProcWaitForSignal.
1479  */
1480  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "waiting");
1481 
1482 #ifdef LWLOCK_STATS
1483  lwstats->block_count++;
1484 #endif
1485 
1486  LWLockReportWaitStart(lock);
1487  if (TRACE_POSTGRESQL_LWLOCK_WAIT_START_ENABLED())
1488  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), mode);
1489 
1490  for (;;)
1491  {
1492  PGSemaphoreLock(proc->sem);
1493  if (!proc->lwWaiting)
1494  break;
1495  extraWaits++;
1496  }
1497 
1498 #ifdef LOCK_DEBUG
1499  {
1500  /* not waiting anymore */
1501  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1502 
1503  Assert(nwaiters < MAX_BACKENDS);
1504  }
1505 #endif
1506  if (TRACE_POSTGRESQL_LWLOCK_WAIT_DONE_ENABLED())
1507  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode);
1509 
1510  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "awakened");
1511  }
1512  else
1513  {
1514  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "acquired, undoing queue");
1515 
1516  /*
1517  * Got lock in the second attempt, undo queueing. We need to treat
1518  * this as having successfully acquired the lock, otherwise we'd
1519  * not necessarily wake up people we've prevented from acquiring
1520  * the lock.
1521  */
1522  LWLockDequeueSelf(lock);
1523  }
1524  }
1525 
1526  /*
1527  * Fix the process wait semaphore's count for any absorbed wakeups.
1528  */
1529  while (extraWaits-- > 0)
1530  PGSemaphoreUnlock(proc->sem);
1531 
1532  if (mustwait)
1533  {
1534  /* Failed to get lock, so release interrupt holdoff */
1536  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "failed");
1537  if (TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_FAIL_ENABLED())
1538  TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_FAIL(T_NAME(lock), mode);
1539  }
1540  else
1541  {
1542  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "succeeded");
1543  /* Add lock to list of locks held by this backend */
1546  if (TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_ENABLED())
1547  TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT(T_NAME(lock), mode);
1548  }
1549 
1550  return !mustwait;
1551 }
#define T_NAME(lock)
Definition: lwlock.c:246
static PgChecksumMode mode
Definition: pg_checksums.c:61
static uint32 pg_atomic_fetch_sub_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:343
static bool LWLockAttemptLock(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:821
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
PGPROC * MyProc
Definition: proc.c:68
bool lwWaiting
Definition: proc.h:170
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:206
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:121
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:216
#define ERROR
Definition: elog.h:46
#define MAX_BACKENDS
Definition: postmaster.h:76
LWLockMode mode
Definition: lwlock.c:212
static void LWLockReportWaitEnd(void)
Definition: lwlock.c:767
unsigned int uint32
Definition: c.h:441
static void LWLockDequeueSelf(LWLock *lock)
Definition: lwlock.c:1108
static void LWLockReportWaitStart(LWLock *lock)
Definition: lwlock.c:758
static void LWLockQueueSelf(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1064
static int num_held_lwlocks
Definition: lwlock.c:215
#define Assert(condition)
Definition: c.h:804
LWLock * lock
Definition: lwlock.c:211
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:310
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:320
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:119
#define elog(elevel,...)
Definition: elog.h:232
PGSemaphore sem
Definition: proc.h:127
Definition: proc.h:121
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:311

◆ LWLockAttemptLock()

static bool LWLockAttemptLock ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 821 of file lwlock.c.

References AssertArg, LW_EXCLUSIVE, LW_LOCK_MASK, LW_SHARED, LW_VAL_EXCLUSIVE, LW_VAL_SHARED, MyProc, pg_atomic_compare_exchange_u32(), pg_atomic_read_u32(), pg_unreachable, and LWLock::state.

Referenced by LWLockAcquire(), LWLockAcquireOrWait(), and LWLockConditionalAcquire().

822 {
823  uint32 old_state;
824 
826 
827  /*
828  * Read once outside the loop, later iterations will get the newer value
829  * via compare & exchange.
830  */
831  old_state = pg_atomic_read_u32(&lock->state);
832 
833  /* loop until we've determined whether we could acquire the lock or not */
834  while (true)
835  {
836  uint32 desired_state;
837  bool lock_free;
838 
839  desired_state = old_state;
840 
841  if (mode == LW_EXCLUSIVE)
842  {
843  lock_free = (old_state & LW_LOCK_MASK) == 0;
844  if (lock_free)
845  desired_state += LW_VAL_EXCLUSIVE;
846  }
847  else
848  {
849  lock_free = (old_state & LW_VAL_EXCLUSIVE) == 0;
850  if (lock_free)
851  desired_state += LW_VAL_SHARED;
852  }
853 
854  /*
855  * Attempt to swap in the state we are expecting. If we didn't see
856  * lock to be free, that's just the old value. If we saw it as free,
857  * we'll attempt to mark it acquired. The reason that we always swap
858  * in the value is that this doubles as a memory barrier. We could try
859  * to be smarter and only swap in values if we saw the lock as free,
860  * but benchmark haven't shown it as beneficial so far.
861  *
862  * Retry if the value changed since we last looked at it.
863  */
865  &old_state, desired_state))
866  {
867  if (lock_free)
868  {
869  /* Great! Got the lock. */
870 #ifdef LOCK_DEBUG
871  if (mode == LW_EXCLUSIVE)
872  lock->owner = MyProc;
873 #endif
874  return false;
875  }
876  else
877  return true; /* somebody else has the lock */
878  }
879  }
880  pg_unreachable();
881 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
#define pg_unreachable()
Definition: c.h:258
static bool pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 *expected, uint32 newval)
Definition: atomics.h:311
PGPROC * MyProc
Definition: proc.c:68
pg_atomic_uint32 state
Definition: lwlock.h:34
#define LW_LOCK_MASK
Definition: lwlock.c:106
#define LW_VAL_SHARED
Definition: lwlock.c:104
unsigned int uint32
Definition: c.h:441
#define AssertArg(condition)
Definition: c.h:806
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:103
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241

◆ LWLockConditionalAcquire()

bool LWLockConditionalAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1378 of file lwlock.c.

References AssertArg, elog, ERROR, HOLD_INTERRUPTS, LWLockHandle::lock, LOG_LWDEBUG, LW_EXCLUSIVE, LW_SHARED, LWLockAttemptLock(), MAX_SIMUL_LWLOCKS, LWLockHandle::mode, num_held_lwlocks, PRINT_LWDEBUG, RESUME_INTERRUPTS, and T_NAME.

Referenced by BufferAlloc(), ConditionalLockBuffer(), ProcArrayEndTransaction(), SimpleLruWaitIO(), ss_report_location(), TransactionIdSetPageStatus(), and XLogNeedsFlush().

1379 {
1380  bool mustwait;
1381 
1383 
1384  PRINT_LWDEBUG("LWLockConditionalAcquire", lock, mode);
1385 
1386  /* Ensure we will have room to remember the lock */
1388  elog(ERROR, "too many LWLocks taken");
1389 
1390  /*
1391  * Lock out cancel/die interrupts until we exit the code section protected
1392  * by the LWLock. This ensures that interrupts will not interfere with
1393  * manipulations of data structures in shared memory.
1394  */
1395  HOLD_INTERRUPTS();
1396 
1397  /* Check for the lock */
1398  mustwait = LWLockAttemptLock(lock, mode);
1399 
1400  if (mustwait)
1401  {
1402  /* Failed to get lock, so release interrupt holdoff */
1404 
1405  LOG_LWDEBUG("LWLockConditionalAcquire", lock, "failed");
1406  if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL_ENABLED())
1407  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL(T_NAME(lock), mode);
1408  }
1409  else
1410  {
1411  /* Add lock to list of locks held by this backend */
1414  if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_ENABLED())
1415  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(T_NAME(lock), mode);
1416  }
1417  return !mustwait;
1418 }
#define T_NAME(lock)
Definition: lwlock.c:246
static PgChecksumMode mode
Definition: pg_checksums.c:61
static bool LWLockAttemptLock(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:821
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:206
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:121
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:216
#define ERROR
Definition: elog.h:46
LWLockMode mode
Definition: lwlock.c:212
#define AssertArg(condition)
Definition: c.h:806
static int num_held_lwlocks
Definition: lwlock.c:215
LWLock * lock
Definition: lwlock.c:211
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:310
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:119
#define elog(elevel,...)
Definition: elog.h:232
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:311

◆ LWLockConflictsWithVar()

static bool LWLockConflictsWithVar ( LWLock lock,
uint64 *  valptr,
uint64  oldval,
uint64 *  newval,
bool result 
)
static

Definition at line 1563 of file lwlock.c.

References LW_VAL_EXCLUSIVE, LWLockWaitListLock(), LWLockWaitListUnlock(), pg_atomic_read_u32(), LWLock::state, and value.

Referenced by LWLockWaitForVar().

1566 {
1567  bool mustwait;
1568  uint64 value;
1569 
1570  /*
1571  * Test first to see if it the slot is free right now.
1572  *
1573  * XXX: the caller uses a spinlock before this, so we don't need a memory
1574  * barrier here as far as the current usage is concerned. But that might
1575  * not be safe in general.
1576  */
1577  mustwait = (pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE) != 0;
1578 
1579  if (!mustwait)
1580  {
1581  *result = true;
1582  return false;
1583  }
1584 
1585  *result = false;
1586 
1587  /*
1588  * Read value using the lwlock's wait list lock, as we can't generally
1589  * rely on atomic 64 bit reads/stores. TODO: On platforms with a way to
1590  * do atomic 64 bit reads/writes the spinlock should be optimized away.
1591  */
1592  LWLockWaitListLock(lock);
1593  value = *valptr;
1594  LWLockWaitListUnlock(lock);
1595 
1596  if (value != oldval)
1597  {
1598  mustwait = false;
1599  *newval = value;
1600  }
1601  else
1602  {
1603  mustwait = true;
1604  }
1605 
1606  return mustwait;
1607 }
static struct @142 value
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:944
pg_atomic_uint32 state
Definition: lwlock.h:34
#define newval
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:892
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:103
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241

◆ LWLockDequeueSelf()

static void LWLockDequeueSelf ( LWLock lock)
static

Definition at line 1108 of file lwlock.c.

References Assert, proclist_mutable_iter::cur, LW_FLAG_HAS_WAITERS, LW_FLAG_RELEASE_OK, LWLockWaitListLock(), LWLockWaitListUnlock(), PGPROC::lwWaiting, MAX_BACKENDS, MyProc, pg_atomic_fetch_and_u32(), pg_atomic_fetch_or_u32(), pg_atomic_fetch_sub_u32(), pg_atomic_read_u32(), PG_USED_FOR_ASSERTS_ONLY, PGPROC::pgprocno, PGSemaphoreLock(), PGSemaphoreUnlock(), proclist_delete, proclist_foreach_modify, proclist_is_empty(), PGPROC::sem, LWLock::state, and LWLock::waiters.

Referenced by LWLockAcquire(), LWLockAcquireOrWait(), and LWLockWaitForVar().

1109 {
1110  bool found = false;
1111  proclist_mutable_iter iter;
1112 
1113 #ifdef LWLOCK_STATS
1114  lwlock_stats *lwstats;
1115 
1116  lwstats = get_lwlock_stats_entry(lock);
1117 
1118  lwstats->dequeue_self_count++;
1119 #endif
1120 
1121  LWLockWaitListLock(lock);
1122 
1123  /*
1124  * Can't just remove ourselves from the list, but we need to iterate over
1125  * all entries as somebody else could have dequeued us.
1126  */
1127  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1128  {
1129  if (iter.cur == MyProc->pgprocno)
1130  {
1131  found = true;
1132  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1133  break;
1134  }
1135  }
1136 
1137  if (proclist_is_empty(&lock->waiters) &&
1138  (pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS) != 0)
1139  {
1141  }
1142 
1143  /* XXX: combine with fetch_and above? */
1144  LWLockWaitListUnlock(lock);
1145 
1146  /* clear waiting state again, nice for debugging */
1147  if (found)
1148  MyProc->lwWaiting = false;
1149  else
1150  {
1151  int extraWaits = 0;
1152 
1153  /*
1154  * Somebody else dequeued us and has or will wake us up. Deal with the
1155  * superfluous absorption of a wakeup.
1156  */
1157 
1158  /*
1159  * Reset RELEASE_OK flag if somebody woke us before we removed
1160  * ourselves - they'll have set it to false.
1161  */
1163 
1164  /*
1165  * Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
1166  * get reset at some inconvenient point later. Most of the time this
1167  * will immediately return.
1168  */
1169  for (;;)
1170  {
1172  if (!MyProc->lwWaiting)
1173  break;
1174  extraWaits++;
1175  }
1176 
1177  /*
1178  * Fix the process wait semaphore's count for any absorbed wakeups.
1179  */
1180  while (extraWaits-- > 0)
1182  }
1183 
1184 #ifdef LOCK_DEBUG
1185  {
1186  /* not waiting anymore */
1187  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1188 
1189  Assert(nwaiters < MAX_BACKENDS);
1190  }
1191 #endif
1192 }
static uint32 pg_atomic_fetch_sub_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:343
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:99
PGPROC * MyProc
Definition: proc.c:68
proclist_head waiters
Definition: lwlock.h:35
bool lwWaiting
Definition: proc.h:170
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:944
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
pg_atomic_uint32 state
Definition: lwlock.h:34
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:187
#define MAX_BACKENDS
Definition: postmaster.h:76
static uint32 pg_atomic_fetch_and_u32(volatile pg_atomic_uint32 *ptr, uint32 and_)
Definition: atomics.h:358
unsigned int uint32
Definition: c.h:441
#define Assert(condition)
Definition: c.h:804
static bool proclist_is_empty(proclist_head *list)
Definition: proclist.h:38
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:100
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:320
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:892
int pgprocno
Definition: proc.h:150
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:372
PGSemaphore sem
Definition: proc.h:127
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

bool LWLockHeldByMeInMode ( LWLock l,
LWLockMode  mode 
)

Definition at line 1950 of file lwlock.c.

References i, and num_held_lwlocks.

Referenced by DeleteLockTarget(), dshash_delete_entry(), dshash_release_lock(), IsBufferCleanupOK(), logicalrep_worker_cleanup(), MarkAsPreparingGuts(), MarkBufferDirty(), PrepareRedoAdd(), PrepareRedoRemove(), ProcArrayEndTransactionInternal(), ProcessTwoPhaseBuffer(), RemoveGXact(), SyncRepWakeQueue(), TransactionIdSetPageStatusInternal(), and TransferPredicateLocksToNewTarget().

1951 {
1952  int i;
1953 
1954  for (i = 0; i < num_held_lwlocks; i++)
1955  {
1956  if (held_lwlocks[i].lock == l && held_lwlocks[i].mode == mode)
1957  return true;
1958  }
1959  return false;
1960 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:216
static int num_held_lwlocks
Definition: lwlock.c:215
int i

◆ LWLockInitialize()

void LWLockInitialize ( LWLock lock,
int  tranche_id 
)

Definition at line 740 of file lwlock.c.

References LW_FLAG_RELEASE_OK, pg_atomic_init_u32(), proclist_init(), LWLock::state, LWLock::tranche, and LWLock::waiters.

Referenced by apw_init_shmem(), create_internal(), dshash_create(), ExecAppendInitializeDSM(), ExecHashJoinInitializeDSM(), InitBufferPool(), InitializeLWLocks(), InitPredicateLocks(), InitProcGlobal(), ReplicationOriginShmemInit(), ReplicationSlotsShmemInit(), SimpleLruInit(), sts_initialize(), tbm_prepare_shared_iterate(), and XLOGShmemInit().

741 {
743 #ifdef LOCK_DEBUG
744  pg_atomic_init_u32(&lock->nwaiters, 0);
745 #endif
746  lock->tranche = tranche_id;
747  proclist_init(&lock->waiters);
748 }
proclist_head waiters
Definition: lwlock.h:35
pg_atomic_uint32 state
Definition: lwlock.h:34
uint16 tranche
Definition: lwlock.h:33
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:100
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:223

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( void  )

Definition at line 624 of file lwlock.c.

References ShmemLock, SpinLockAcquire, and SpinLockRelease.

Referenced by apw_init_shmem(), and InitializeLWLocks().

625 {
626  int result;
627  int *LWLockCounter;
628 
629  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
631  result = (*LWLockCounter)++;
633 
634  return result;
635 }
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
slock_t * ShmemLock
Definition: shmem.c:88
LWLockPadded * MainLWLockArray
Definition: lwlock.c:198

◆ LWLockQueueSelf()

static void LWLockQueueSelf ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 1064 of file lwlock.c.

References elog, LW_FLAG_HAS_WAITERS, LW_WAIT_UNTIL_FREE, LWLockWaitListLock(), LWLockWaitListUnlock(), PGPROC::lwWaiting, PGPROC::lwWaitMode, LWLockHandle::mode, MyProc, PANIC, pg_atomic_fetch_add_u32(), pg_atomic_fetch_or_u32(), PGPROC::pgprocno, proclist_push_head, proclist_push_tail, LWLock::state, and LWLock::waiters.

Referenced by LWLockAcquire(), LWLockAcquireOrWait(), and LWLockWaitForVar().

1065 {
1066  /*
1067  * If we don't have a PGPROC structure, there's no way to wait. This
1068  * should never occur, since MyProc should only be null during shared
1069  * memory initialization.
1070  */
1071  if (MyProc == NULL)
1072  elog(PANIC, "cannot wait without a PGPROC structure");
1073 
1074  if (MyProc->lwWaiting)
1075  elog(PANIC, "queueing for lock while waiting on another one");
1076 
1077  LWLockWaitListLock(lock);
1078 
1079  /* setting the flag is protected by the spinlock */
1081 
1082  MyProc->lwWaiting = true;
1083  MyProc->lwWaitMode = mode;
1084 
1085  /* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */
1086  if (mode == LW_WAIT_UNTIL_FREE)
1087  proclist_push_head(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1088  else
1089  proclist_push_tail(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1090 
1091  /* Can release the mutex now */
1092  LWLockWaitListUnlock(lock);
1093 
1094 #ifdef LOCK_DEBUG
1095  pg_atomic_fetch_add_u32(&lock->nwaiters, 1);
1096 #endif
1097 
1098 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:99
PGPROC * MyProc
Definition: proc.c:68
proclist_head waiters
Definition: lwlock.h:35
bool lwWaiting
Definition: proc.h:170
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:944
uint8 lwWaitMode
Definition: proc.h:171
pg_atomic_uint32 state
Definition: lwlock.h:34
#define PANIC
Definition: elog.h:50
#define proclist_push_head(list, procno, link_member)
Definition: proclist.h:189
static uint32 pg_atomic_fetch_add_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:328
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:191
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:892
int pgprocno
Definition: proc.h:150
#define elog(elevel,...)
Definition: elog.h:232
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:372

◆ LWLockRegisterTranche()

void LWLockRegisterTranche ( int  tranche_id,
const char *  tranche_name 
)

Definition at line 648 of file lwlock.c.

References LWLockTrancheNames, LWLockTrancheNamesAllocated, LWTRANCHE_FIRST_USER_DEFINED, Max, MemoryContextAllocZero(), repalloc(), and TopMemoryContext.

Referenced by apw_init_shmem(), and CreateLWLocks().

649 {
650  /* This should only be called for user-defined tranches. */
651  if (tranche_id < LWTRANCHE_FIRST_USER_DEFINED)
652  return;
653 
654  /* Convert to array index. */
655  tranche_id -= LWTRANCHE_FIRST_USER_DEFINED;
656 
657  /* If necessary, create or enlarge array. */
658  if (tranche_id >= LWLockTrancheNamesAllocated)
659  {
660  int newalloc;
661 
662  newalloc = Max(LWLockTrancheNamesAllocated, 8);
663  while (newalloc <= tranche_id)
664  newalloc *= 2;
665 
666  if (LWLockTrancheNames == NULL)
667  LWLockTrancheNames = (const char **)
669  newalloc * sizeof(char *));
670  else
671  {
672  LWLockTrancheNames = (const char **)
673  repalloc(LWLockTrancheNames, newalloc * sizeof(char *));
675  0,
676  (newalloc - LWLockTrancheNamesAllocated) * sizeof(char *));
677  }
678  LWLockTrancheNamesAllocated = newalloc;
679  }
680 
681  LWLockTrancheNames[tranche_id] = tranche_name;
682 }
static int LWLockTrancheNamesAllocated
Definition: lwlock.c:191
MemoryContext TopMemoryContext
Definition: mcxt.c:48
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:906
#define Max(x, y)
Definition: c.h:980
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
static const char ** LWLockTrancheNames
Definition: lwlock.c:190

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1816 of file lwlock.c.

References Assert, elog, ERROR, i, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_HAS_WAITERS, LW_FLAG_RELEASE_OK, LW_LOCK_MASK, LW_VAL_EXCLUSIVE, LW_VAL_SHARED, LWLockWakeup(), LWLockHandle::mode, num_held_lwlocks, pg_atomic_sub_fetch_u32(), PRINT_LWDEBUG, RESUME_INTERRUPTS, and T_NAME.

Referenced by _bt_end_vacuum(), _bt_start_vacuum(), _bt_vacuum_cycleid(), AbsorbSyncRequests(), ActivateCommitTs(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_init_shmem(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacLauncherMain(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendIdGetProc(), BackendIdGetTransactionIds(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BootStrapCLOG(), BootStrapMultiXact(), BootStrapSUBTRANS(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), CheckRecoveryConsistency(), CheckTableForSerializableConflictIn(), CheckTargetForConflictsIn(), choose_next_subplan_for_leader(), choose_next_subplan_for_worker(), CleanupInvalidationState(), ClearOldPredicateLocks(), clog_redo(), commit_ts_redo(), ComputeXidHorizons(), copy_replication_slot(), CountDBBackends(), CountDBConnections(), CountOtherDBBackends(), CountUserBackends(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateInitDecodingContext(), CreatePredicateLock(), CreateRestartPoint(), DeactivateCommitTs(), DeleteChildTargetLocks(), DeleteLockTarget(), destroy_superblock(), do_autovacuum(), do_pg_start_backup(), do_pg_stop_backup(), do_start_worker(), DropAllPredicateLocksFromTable(), DropSubscription(), DropTableSpace(), dsa_allocate_extended(), dsa_dump(), dsa_free(), dsa_pin(), dsa_release_in_place(), dsa_set_size_limit(), dsa_trim(), dsa_unpin(), dshash_delete_entry(), dshash_delete_key(), dshash_dump(), dshash_find(), dshash_find_or_insert(), dshash_release_lock(), dsm_attach(), dsm_create(), dsm_detach(), dsm_pin_segment(), dsm_unpin_segment(), ensure_active_superblock(), entry_reset(), Exec_ListenPreCommit(), ExecParallelHashMergeCounters(), ExecParallelHashPopChunkQueue(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), ExpireAllKnownAssignedTransactionIds(), ExpireOldKnownAssignedTransactionIds(), ExpireTreeKnownAssignedTransactionIds(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), find_multixact_start(), FindAndDropRelFileNodeBuffers(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), FlushRelationsAllBuffers(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), get_xid_status(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldSnapshotFromTimeMapping(), GetOldSnapshotTimeMapping(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), HandleAutoVacLauncherInterrupts(), HaveVirtualXIDsDelayingChkpt(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), KnownAssignedXidsAdd(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockBuffer(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_worker_attach(), logicalrep_worker_detach(), logicalrep_worker_launch(), logicalrep_worker_stop(), logicalrep_worker_wakeup(), LogStandbySnapshot(), LWLockReleaseAll(), LWLockReleaseClearVar(), MaintainOldSnapshotTimeMapping(), MarkAsPrepared(), MarkAsPreparing(), MaybeExtendOffsetSlru(), multixact_redo(), MultiXactAdvanceNextMXact(), MultiXactGetCheckptMulti(), MultiXactIdSetOldestMember(), MultiXactIdSetOldestVisible(), MultiXactSetNextMXact(), OnConflict_CheckForSerializationFailure(), PageIsPredicateLocked(), perform_relmap_update(), pg_get_replication_slots(), pg_get_shmem_allocations(), pg_notification_queue_usage(), pg_show_replication_origin_status(), pg_stat_get_subscription(), pg_stat_statements_internal(), pg_xact_status(), pgss_shmem_startup(), pgss_store(), PostPrepare_Locks(), PostPrepare_MultiXact(), PostPrepare_Twophase(), PreCommit_CheckForSerializationFailure(), PreCommit_Notify(), predicatelock_twophase_recover(), PredicateLockPageSplit(), PredicateLockTwoPhaseFinish(), PrefetchSharedBuffer(), PrescanPreparedTransactions(), ProcArrayAdd(), ProcArrayApplyRecoveryInfo(), ProcArrayApplyXidAssignment(), ProcArrayClearTransaction(), ProcArrayEndTransaction(), ProcArrayGetReplicationSlotXmin(), ProcArrayGroupClearXid(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), ProcArrayRemove(), ProcArraySetReplicationSlotXmin(), process_syncing_tables_for_apply(), ProcKill(), ProcSleep(), ReadMultiXactCounts(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadRecord(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePostInvalidate(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquireInternal(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDropPtr(), ReplicationSlotRelease(), ReplicationSlotsComputeLogicalRestartLSN(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), replorigin_advance(), replorigin_drop_guts(), replorigin_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset(), replorigin_session_setup(), resize(), RestoreScratchTarget(), restoreTwoPhaseData(), SaveSlotToPath(), SearchNamedReplicationSlot(), SerialAdd(), SerialGetMinConflictCommitSeqNo(), SerialSetActiveSerXmin(), set_indexsafe_procflags(), SetCommitTsLimit(), SetMultiXactIdLimit(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SignalVirtualTransaction(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), ss_report_location(), StandbyRecoverPreparedTransactions(), StartupCLOG(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransGetParent(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SyncOneBuffer(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateOtherDBBackends(), TransactionGroupUpdateXidStatus(), TransactionIdGetCommitTsData(), TransactionIdGetStatus(), TransactionIdIsActive(), TransactionIdIsInProgress(), TransactionIdSetPageStatus(), TransactionTreeSetCommitTsData(), TransferPredicateLocksToNewTarget(), TrimCLOG(), TrimMultiXact(), TruncateMultiXact(), TwoPhaseGetGXact(), update_cached_xid_range(), UpdateMinRecoveryPoint(), vac_truncate_clog(), vacuum_rel(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitForReplicationWorkerAttach(), WaitOnLock(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), XLogNeedsFlush(), and XLogReportParameters().

1817 {
1818  LWLockMode mode;
1819  uint32 oldstate;
1820  bool check_waiters;
1821  int i;
1822 
1823  /*
1824  * Remove lock from list of locks held. Usually, but not always, it will
1825  * be the latest-acquired lock; so search array backwards.
1826  */
1827  for (i = num_held_lwlocks; --i >= 0;)
1828  if (lock == held_lwlocks[i].lock)
1829  break;
1830 
1831  if (i < 0)
1832  elog(ERROR, "lock %s is not held", T_NAME(lock));
1833 
1834  mode = held_lwlocks[i].mode;
1835 
1836  num_held_lwlocks--;
1837  for (; i < num_held_lwlocks; i++)
1838  held_lwlocks[i] = held_lwlocks[i + 1];
1839 
1840  PRINT_LWDEBUG("LWLockRelease", lock, mode);
1841 
1842  /*
1843  * Release my hold on lock, after that it can immediately be acquired by
1844  * others, even if we still have to wakeup other waiters.
1845  */
1846  if (mode == LW_EXCLUSIVE)
1847  oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_EXCLUSIVE);
1848  else
1849  oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_SHARED);
1850 
1851  /* nobody else can have that kind of lock */
1852  Assert(!(oldstate & LW_VAL_EXCLUSIVE));
1853 
1854  if (TRACE_POSTGRESQL_LWLOCK_RELEASE_ENABLED())
1855  TRACE_POSTGRESQL_LWLOCK_RELEASE(T_NAME(lock));
1856 
1857  /*
1858  * We're still waiting for backends to get scheduled, don't wake them up
1859  * again.
1860  */
1861  if ((oldstate & (LW_FLAG_HAS_WAITERS | LW_FLAG_RELEASE_OK)) ==
1863  (oldstate & LW_LOCK_MASK) == 0)
1864  check_waiters = true;
1865  else
1866  check_waiters = false;
1867 
1868  /*
1869  * As waking up waiters requires the spinlock to be acquired, only do so
1870  * if necessary.
1871  */
1872  if (check_waiters)
1873  {
1874  /* XXX: remove before commit? */
1875  LOG_LWDEBUG("LWLockRelease", lock, "releasing waiters");
1876  LWLockWakeup(lock);
1877  }
1878 
1879  /*
1880  * Now okay to allow cancel/die interrupts.
1881  */
1883 }
#define T_NAME(lock)
Definition: lwlock.c:246
static PgChecksumMode mode
Definition: pg_checksums.c:61
LWLockMode
Definition: lwlock.h:102
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:99
static uint32 pg_atomic_sub_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:401
#define LW_LOCK_MASK
Definition: lwlock.c:106
#define LW_VAL_SHARED
Definition: lwlock.c:104
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:121
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:216
#define ERROR
Definition: elog.h:46
LWLockMode mode
Definition: lwlock.c:212
static void LWLockWakeup(LWLock *lock)
Definition: lwlock.c:957
unsigned int uint32
Definition: c.h:441
static int num_held_lwlocks
Definition: lwlock.c:215
#define Assert(condition)
Definition: c.h:804
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:310
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:100
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:103
#define elog(elevel,...)
Definition: elog.h:232
int i
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:311

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

Definition at line 1915 of file lwlock.c.

References HOLD_INTERRUPTS, LWLockRelease(), and num_held_lwlocks.

Referenced by AbortSubTransaction(), AbortTransaction(), AutoVacLauncherMain(), AuxiliaryProcKill(), BackgroundWriterMain(), CheckpointerMain(), ProcKill(), ShutdownAuxiliaryProcess(), WalSndErrorCleanup(), and WalWriterMain().

1916 {
1917  while (num_held_lwlocks > 0)
1918  {
1919  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1920 
1922  }
1923 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1816
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:216
static int num_held_lwlocks
Definition: lwlock.c:215
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:119

◆ LWLockReleaseClearVar()

void LWLockReleaseClearVar ( LWLock lock,
uint64 *  valptr,
uint64  val 
)

Definition at line 1889 of file lwlock.c.

References LWLockRelease(), LWLockWaitListLock(), LWLockWaitListUnlock(), and val.

Referenced by WALInsertLockRelease().

1890 {
1891  LWLockWaitListLock(lock);
1892 
1893  /*
1894  * Set the variable's value before releasing the lock, that prevents race
1895  * a race condition wherein a new locker acquires the lock, but hasn't yet
1896  * set the variables value.
1897  */
1898  *valptr = val;
1899  LWLockWaitListUnlock(lock);
1900 
1901  LWLockRelease(lock);
1902 }
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:944
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1816
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:892
long val
Definition: informix.c:664

◆ LWLockReportWaitEnd()

static void LWLockReportWaitEnd ( void  )
inlinestatic

Definition at line 767 of file lwlock.c.

References pgstat_report_wait_end().

Referenced by LWLockAcquire(), LWLockAcquireOrWait(), and LWLockWaitForVar().

768 {
770 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:277

◆ LWLockReportWaitStart()

static void LWLockReportWaitStart ( LWLock lock)
inlinestatic

Definition at line 758 of file lwlock.c.

References PG_WAIT_LWLOCK, pgstat_report_wait_start(), and LWLock::tranche.

Referenced by LWLockAcquire(), LWLockAcquireOrWait(), and LWLockWaitForVar().

759 {
761 }
#define PG_WAIT_LWLOCK
Definition: wait_event.h:18
uint16 tranche
Definition: lwlock.h:33
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:261

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 432 of file lwlock.c.

References add_size(), i, lock_named_request_allowed, LWLOCK_PADDED_SIZE, mul_size(), NamedLWLockTrancheRequests, NUM_FIXED_LWLOCKS, and NumLWLocksForNamedTranches().

Referenced by CreateLWLocks(), and CreateSharedMemoryAndSemaphores().

433 {
434  Size size;
435  int i;
436  int numLocks = NUM_FIXED_LWLOCKS;
437 
438  /* Calculate total number of locks needed in the main array. */
439  numLocks += NumLWLocksForNamedTranches();
440 
441  /* Space for the LWLock array. */
442  size = mul_size(numLocks, sizeof(LWLockPadded));
443 
444  /* Space for dynamic allocation counter, plus room for alignment. */
445  size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
446 
447  /* space for named tranches. */
449 
450  /* space for name of each tranche. */
451  for (i = 0; i < NamedLWLockTrancheRequests; i++)
452  size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
453 
454  /* Disallow adding any more named tranches. */
456 
457  return size;
458 }
static bool lock_named_request_allowed
Definition: lwlock.c:239
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:99
int NamedLWLockTrancheRequests
Definition: lwlock.c:234
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:417
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
size_t Size
Definition: c.h:540
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:225
int i
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:52

◆ LWLockUpdateVar()

void LWLockUpdateVar ( LWLock lock,
uint64 *  valptr,
uint64  val 
)

Definition at line 1762 of file lwlock.c.

References Assert, proclist_mutable_iter::cur, GetPGProcByNumber, LW_EXCLUSIVE, LW_VAL_EXCLUSIVE, LW_WAIT_UNTIL_FREE, LWLockWaitListLock(), LWLockWaitListUnlock(), PGPROC::lwWaiting, PGPROC::lwWaitMode, pg_atomic_read_u32(), pg_write_barrier, PGSemaphoreUnlock(), PRINT_LWDEBUG, proclist_delete, proclist_foreach_modify, proclist_init(), proclist_push_tail, PGPROC::sem, LWLock::state, val, and LWLock::waiters.

Referenced by WALInsertLockAcquireExclusive(), and WALInsertLockUpdateInsertingAt().

1763 {
1764  proclist_head wakeup;
1765  proclist_mutable_iter iter;
1766 
1767  PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1768 
1769  proclist_init(&wakeup);
1770 
1771  LWLockWaitListLock(lock);
1772 
1774 
1775  /* Update the lock's value */
1776  *valptr = val;
1777 
1778  /*
1779  * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1780  * up. They are always in the front of the queue.
1781  */
1782  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1783  {
1784  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1785 
1786  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1787  break;
1788 
1789  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1790  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1791  }
1792 
1793  /* We are done updating shared state of the lock itself. */
1794  LWLockWaitListUnlock(lock);
1795 
1796  /*
1797  * Awaken any waiters I removed from the queue.
1798  */
1799  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1800  {
1801  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1802 
1803  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1804  /* check comment in LWLockWakeup() about this barrier */
1805  pg_write_barrier();
1806  waiter->lwWaiting = false;
1807  PGSemaphoreUnlock(waiter->sem);
1808  }
1809 }
#define GetPGProcByNumber(n)
Definition: proc.h:367
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
proclist_head waiters
Definition: lwlock.h:35
bool lwWaiting
Definition: proc.h:170
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:944
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
uint8 lwWaitMode
Definition: proc.h:171
pg_atomic_uint32 state
Definition: lwlock.h:34
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:187
#define Assert(condition)
Definition: c.h:804
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:310
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:191
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:892
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:103
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
#define pg_write_barrier()
Definition: atomics.h:159
PGSemaphore sem
Definition: proc.h:127
Definition: proc.h:121
long val
Definition: informix.c:664
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241

◆ LWLockWaitForVar()

bool LWLockWaitForVar ( LWLock lock,
uint64 *  valptr,
uint64  oldval,
uint64 *  newval 
)

Definition at line 1623 of file lwlock.c.

References Assert, HOLD_INTERRUPTS, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_RELEASE_OK, LW_WAIT_UNTIL_FREE, LWLockConflictsWithVar(), LWLockDequeueSelf(), LWLockQueueSelf(), LWLockReportWaitEnd(), LWLockReportWaitStart(), PGPROC::lwWaiting, MAX_BACKENDS, MyProc, pg_atomic_fetch_or_u32(), pg_atomic_fetch_sub_u32(), PG_USED_FOR_ASSERTS_ONLY, PGSemaphoreLock(), PGSemaphoreUnlock(), PRINT_LWDEBUG, RESUME_INTERRUPTS, PGPROC::sem, LWLock::state, and T_NAME.

Referenced by WaitXLogInsertionsToFinish().

1624 {
1625  PGPROC *proc = MyProc;
1626  int extraWaits = 0;
1627  bool result = false;
1628 #ifdef LWLOCK_STATS
1629  lwlock_stats *lwstats;
1630 
1631  lwstats = get_lwlock_stats_entry(lock);
1632 #endif
1633 
1634  PRINT_LWDEBUG("LWLockWaitForVar", lock, LW_WAIT_UNTIL_FREE);
1635 
1636  /*
1637  * Lock out cancel/die interrupts while we sleep on the lock. There is no
1638  * cleanup mechanism to remove us from the wait queue if we got
1639  * interrupted.
1640  */
1641  HOLD_INTERRUPTS();
1642 
1643  /*
1644  * Loop here to check the lock's status after each time we are signaled.
1645  */
1646  for (;;)
1647  {
1648  bool mustwait;
1649 
1650  mustwait = LWLockConflictsWithVar(lock, valptr, oldval, newval,
1651  &result);
1652 
1653  if (!mustwait)
1654  break; /* the lock was free or value didn't match */
1655 
1656  /*
1657  * Add myself to wait queue. Note that this is racy, somebody else
1658  * could wakeup before we're finished queuing. NB: We're using nearly
1659  * the same twice-in-a-row lock acquisition protocol as
1660  * LWLockAcquire(). Check its comments for details. The only
1661  * difference is that we also have to check the variable's values when
1662  * checking the state of the lock.
1663  */
1665 
1666  /*
1667  * Set RELEASE_OK flag, to make sure we get woken up as soon as the
1668  * lock is released.
1669  */
1671 
1672  /*
1673  * We're now guaranteed to be woken up if necessary. Recheck the lock
1674  * and variables state.
1675  */
1676  mustwait = LWLockConflictsWithVar(lock, valptr, oldval, newval,
1677  &result);
1678 
1679  /* Ok, no conflict after we queued ourselves. Undo queueing. */
1680  if (!mustwait)
1681  {
1682  LOG_LWDEBUG("LWLockWaitForVar", lock, "free, undoing queue");
1683 
1684  LWLockDequeueSelf(lock);
1685  break;
1686  }
1687 
1688  /*
1689  * Wait until awakened.
1690  *
1691  * Since we share the process wait semaphore with the regular lock
1692  * manager and ProcWaitForSignal, and we may need to acquire an LWLock
1693  * while one of those is pending, it is possible that we get awakened
1694  * for a reason other than being signaled by LWLockRelease. If so,
1695  * loop back and wait again. Once we've gotten the LWLock,
1696  * re-increment the sema by the number of additional signals received,
1697  * so that the lock manager or signal manager will see the received
1698  * signal when it next waits.
1699  */
1700  LOG_LWDEBUG("LWLockWaitForVar", lock, "waiting");
1701 
1702 #ifdef LWLOCK_STATS
1703  lwstats->block_count++;
1704 #endif
1705 
1706  LWLockReportWaitStart(lock);
1707  if (TRACE_POSTGRESQL_LWLOCK_WAIT_START_ENABLED())
1708  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), LW_EXCLUSIVE);
1709 
1710  for (;;)
1711  {
1712  PGSemaphoreLock(proc->sem);
1713  if (!proc->lwWaiting)
1714  break;
1715  extraWaits++;
1716  }
1717 
1718 #ifdef LOCK_DEBUG
1719  {
1720  /* not waiting anymore */
1721  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1722 
1723  Assert(nwaiters < MAX_BACKENDS);
1724  }
1725 #endif
1726 
1727  if (TRACE_POSTGRESQL_LWLOCK_WAIT_DONE_ENABLED())
1728  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), LW_EXCLUSIVE);
1730 
1731  LOG_LWDEBUG("LWLockWaitForVar", lock, "awakened");
1732 
1733  /* Now loop back and check the status of the lock again. */
1734  }
1735 
1736  /*
1737  * Fix the process wait semaphore's count for any absorbed wakeups.
1738  */
1739  while (extraWaits-- > 0)
1740  PGSemaphoreUnlock(proc->sem);
1741 
1742  /*
1743  * Now okay to allow cancel/die interrupts.
1744  */
1746 
1747  return result;
1748 }
#define T_NAME(lock)
Definition: lwlock.c:246
static uint32 pg_atomic_fetch_sub_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:343
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
PGPROC * MyProc
Definition: proc.c:68
bool lwWaiting
Definition: proc.h:170
pg_atomic_uint32 state
Definition: lwlock.h:34
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:121
#define MAX_BACKENDS
Definition: postmaster.h:76
static void LWLockReportWaitEnd(void)
Definition: lwlock.c:767
unsigned int uint32
Definition: c.h:441
static void LWLockDequeueSelf(LWLock *lock)
Definition: lwlock.c:1108
static void LWLockReportWaitStart(LWLock *lock)
Definition: lwlock.c:758
static void LWLockQueueSelf(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1064
#define Assert(condition)
Definition: c.h:804
#define newval
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:310
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:100
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:320
static bool LWLockConflictsWithVar(LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval, bool *result)
Definition: lwlock.c:1563
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:119
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:372
PGSemaphore sem
Definition: proc.h:127
Definition: proc.h:121
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:311

◆ LWLockWaitListLock()

static void LWLockWaitListLock ( LWLock lock)
static

Definition at line 892 of file lwlock.c.

References SpinDelayStatus::delays, finish_spin_delay(), init_local_spin_delay, LW_FLAG_LOCKED, perform_spin_delay(), pg_atomic_fetch_or_u32(), pg_atomic_read_u32(), and LWLock::state.

Referenced by LWLockConflictsWithVar(), LWLockDequeueSelf(), LWLockQueueSelf(), LWLockReleaseClearVar(), LWLockUpdateVar(), and LWLockWakeup().

893 {
894  uint32 old_state;
895 #ifdef LWLOCK_STATS
896  lwlock_stats *lwstats;
897  uint32 delays = 0;
898 
899  lwstats = get_lwlock_stats_entry(lock);
900 #endif
901 
902  while (true)
903  {
904  /* always try once to acquire lock directly */
905  old_state = pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_LOCKED);
906  if (!(old_state & LW_FLAG_LOCKED))
907  break; /* got lock */
908 
909  /* and then spin without atomic operations until lock is released */
910  {
911  SpinDelayStatus delayStatus;
912 
913  init_local_spin_delay(&delayStatus);
914 
915  while (old_state & LW_FLAG_LOCKED)
916  {
917  perform_spin_delay(&delayStatus);
918  old_state = pg_atomic_read_u32(&lock->state);
919  }
920 #ifdef LWLOCK_STATS
921  delays += delayStatus.delays;
922 #endif
923  finish_spin_delay(&delayStatus);
924  }
925 
926  /*
927  * Retry. The lock might obviously already be re-acquired by the time
928  * we're attempting to get it again.
929  */
930  }
931 
932 #ifdef LWLOCK_STATS
933  lwstats->spin_delay_count += delays;
934 #endif
935 }
#define init_local_spin_delay(status)
Definition: s_lock.h:1043
#define LW_FLAG_LOCKED
Definition: lwlock.c:101
pg_atomic_uint32 state
Definition: lwlock.h:34
void finish_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:174
unsigned int uint32
Definition: c.h:441
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:372
void perform_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:124
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241

◆ LWLockWaitListUnlock()

static void LWLockWaitListUnlock ( LWLock lock)
static

Definition at line 944 of file lwlock.c.

References Assert, LW_FLAG_LOCKED, pg_atomic_fetch_and_u32(), PG_USED_FOR_ASSERTS_ONLY, and LWLock::state.

Referenced by LWLockConflictsWithVar(), LWLockDequeueSelf(), LWLockQueueSelf(), LWLockReleaseClearVar(), and LWLockUpdateVar().

945 {
947 
948  old_state = pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_LOCKED);
949 
950  Assert(old_state & LW_FLAG_LOCKED);
951 }
#define LW_FLAG_LOCKED
Definition: lwlock.c:101
pg_atomic_uint32 state
Definition: lwlock.h:34
static uint32 pg_atomic_fetch_and_u32(volatile pg_atomic_uint32 *ptr, uint32 and_)
Definition: atomics.h:358
unsigned int uint32
Definition: c.h:441
#define Assert(condition)
Definition: c.h:804
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155

◆ LWLockWakeup()

static void LWLockWakeup ( LWLock lock)
static

Definition at line 957 of file lwlock.c.

References Assert, proclist_mutable_iter::cur, GetPGProcByNumber, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_HAS_WAITERS, LW_FLAG_LOCKED, LW_FLAG_RELEASE_OK, LW_WAIT_UNTIL_FREE, LWLockWaitListLock(), PGPROC::lwWaiting, PGPROC::lwWaitMode, pg_atomic_compare_exchange_u32(), pg_atomic_read_u32(), pg_write_barrier, PGSemaphoreUnlock(), proclist_delete, proclist_foreach_modify, proclist_init(), proclist_is_empty(), proclist_push_tail, PGPROC::sem, LWLock::state, and LWLock::waiters.

Referenced by LWLockRelease().

958 {
959  bool new_release_ok;
960  bool wokeup_somebody = false;
961  proclist_head wakeup;
963 
964  proclist_init(&wakeup);
965 
966  new_release_ok = true;
967 
968  /* lock wait list while collecting backends to wake up */
969  LWLockWaitListLock(lock);
970 
971  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
972  {
973  PGPROC *waiter = GetPGProcByNumber(iter.cur);
974 
975  if (wokeup_somebody && waiter->lwWaitMode == LW_EXCLUSIVE)
976  continue;
977 
978  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
979  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
980 
981  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
982  {
983  /*
984  * Prevent additional wakeups until retryer gets to run. Backends
985  * that are just waiting for the lock to become free don't retry
986  * automatically.
987  */
988  new_release_ok = false;
989 
990  /*
991  * Don't wakeup (further) exclusive locks.
992  */
993  wokeup_somebody = true;
994  }
995 
996  /*
997  * Once we've woken up an exclusive lock, there's no point in waking
998  * up anybody else.
999  */
1000  if (waiter->lwWaitMode == LW_EXCLUSIVE)
1001  break;
1002  }
1003 
1005 
1006  /* unset required flags, and release lock, in one fell swoop */
1007  {
1008  uint32 old_state;
1009  uint32 desired_state;
1010 
1011  old_state = pg_atomic_read_u32(&lock->state);
1012  while (true)
1013  {
1014  desired_state = old_state;
1015 
1016  /* compute desired flags */
1017 
1018  if (new_release_ok)
1019  desired_state |= LW_FLAG_RELEASE_OK;
1020  else
1021  desired_state &= ~LW_FLAG_RELEASE_OK;
1022 
1023  if (proclist_is_empty(&wakeup))
1024  desired_state &= ~LW_FLAG_HAS_WAITERS;
1025 
1026  desired_state &= ~LW_FLAG_LOCKED; /* release lock */
1027 
1028  if (pg_atomic_compare_exchange_u32(&lock->state, &old_state,
1029  desired_state))
1030  break;
1031  }
1032  }
1033 
1034  /* Awaken any waiters I removed from the queue. */
1035  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1036  {
1037  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1038 
1039  LOG_LWDEBUG("LWLockRelease", lock, "release waiter");
1040  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1041 
1042  /*
1043  * Guarantee that lwWaiting being unset only becomes visible once the
1044  * unlink from the link has completed. Otherwise the target backend
1045  * could be woken up for other reason and enqueue for a new lock - if
1046  * that happens before the list unlink happens, the list would end up
1047  * being corrupted.
1048  *
1049  * The barrier pairs with the LWLockWaitListLock() when enqueuing for
1050  * another lock.
1051  */
1052  pg_write_barrier();
1053  waiter->lwWaiting = false;
1054  PGSemaphoreUnlock(waiter->sem);
1055  }
1056 }
#define GetPGProcByNumber(n)
Definition: proc.h:367
#define LW_FLAG_LOCKED
Definition: lwlock.c:101
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:99
static bool pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 *expected, uint32 newval)
Definition: atomics.h:311
proclist_head waiters
Definition: lwlock.h:35
bool lwWaiting
Definition: proc.h:170
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
uint8 lwWaitMode
Definition: proc.h:171
pg_atomic_uint32 state
Definition: lwlock.h:34
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:187
unsigned int uint32
Definition: c.h:441
#define Assert(condition)
Definition: c.h:804
static bool proclist_is_empty(proclist_head *list)
Definition: proclist.h:38
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:100
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:191
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:892
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
#define pg_write_barrier()
Definition: atomics.h:159
PGSemaphore sem
Definition: proc.h:127
Definition: proc.h:121
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:311

◆ NumLWLocksForNamedTranches()

static int NumLWLocksForNamedTranches ( void  )
static

Definition at line 417 of file lwlock.c.

References i, and NamedLWLockTrancheRequests.

Referenced by InitializeLWLocks(), and LWLockShmemSize().

418 {
419  int numLocks = 0;
420  int i;
421 
422  for (i = 0; i < NamedLWLockTrancheRequests; i++)
423  numLocks += NamedLWLockTrancheRequestArray[i].num_lwlocks;
424 
425  return numLocks;
426 }
int NamedLWLockTrancheRequests
Definition: lwlock.c:234
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:225
int i

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 700 of file lwlock.c.

References Assert, i, IsUnderPostmaster, lock_named_request_allowed, MemoryContextAlloc(), NAMEDATALEN, NamedLWLockTrancheRequests, NamedLWLockTrancheRequestsAllocated, NamedLWLockTrancheRequest::num_lwlocks, repalloc(), strlcpy(), TopMemoryContext, and NamedLWLockTrancheRequest::tranche_name.

Referenced by _PG_init().

701 {
702  NamedLWLockTrancheRequest *request;
703 
705  return; /* too late */
706 
707  if (NamedLWLockTrancheRequestArray == NULL)
708  {
713  * sizeof(NamedLWLockTrancheRequest));
714  }
715 
717  {
719 
720  while (i <= NamedLWLockTrancheRequests)
721  i *= 2;
722 
725  i * sizeof(NamedLWLockTrancheRequest));
727  }
728 
730  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
731  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
732  request->num_lwlocks = num_lwlocks;
734 }
static bool lock_named_request_allowed
Definition: lwlock.c:239
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:221
#define NAMEDATALEN
int NamedLWLockTrancheRequests
Definition: lwlock.c:234
bool IsUnderPostmaster
Definition: globals.c:112
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:226
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define Assert(condition)
Definition: c.h:804
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:225
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
int i

◆ StaticAssertDecl()

StaticAssertDecl ( lengthof(BuiltinTrancheNames = =LWTRANCHE_FIRST_USER_DEFINED - NUM_INDIVIDUAL_LWLOCKS,
"missing entries in BuiltinTrancheNames [] 
)

Variable Documentation

◆ BuiltinTrancheNames

const char* const BuiltinTrancheNames[]
static

Definition at line 130 of file lwlock.c.

Referenced by GetLWTrancheName().

◆ held_lwlocks

LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
static

Definition at line 216 of file lwlock.c.

◆ IndividualLWLockNames

const char* const IndividualLWLockNames[]

Referenced by GetLWTrancheName().

◆ lock_named_request_allowed

bool lock_named_request_allowed = true
static

Definition at line 239 of file lwlock.c.

Referenced by LWLockShmemSize(), and RequestNamedLWLockTranche().

◆ LWLockTrancheNames

const char** LWLockTrancheNames = NULL
static

Definition at line 190 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ LWLockTrancheNamesAllocated

int LWLockTrancheNamesAllocated = 0
static

Definition at line 191 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ MainLWLockArray

LWLockPadded* MainLWLockArray = NULL

Definition at line 198 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheArray

NamedLWLockTranche* NamedLWLockTrancheArray = NULL

Definition at line 237 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheRequestArray

NamedLWLockTrancheRequest* NamedLWLockTrancheRequestArray = NULL
static

Definition at line 225 of file lwlock.c.

◆ NamedLWLockTrancheRequests

◆ NamedLWLockTrancheRequestsAllocated

int NamedLWLockTrancheRequestsAllocated = 0
static

Definition at line 226 of file lwlock.c.

Referenced by RequestNamedLWLockTranche().

◆ num_held_lwlocks

◆ ShmemLock