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 208 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 468 of file lwlock.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

469 {
471  "MAX_BACKENDS too big for lwlock.c");
472 
474  sizeof(LWLock) <= LWLOCK_PADDED_SIZE,
475  "Miscalculated LWLock padding");
476 
477  if (!IsUnderPostmaster)
478  {
479  Size spaceLocks = LWLockShmemSize();
480  int *LWLockCounter;
481  char *ptr;
482 
483  /* Allocate space */
484  ptr = (char *) ShmemAlloc(spaceLocks);
485 
486  /* Leave room for dynamic allocation of tranches */
487  ptr += sizeof(int);
488 
489  /* Ensure desired alignment of LWLock array */
490  ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
491 
492  MainLWLockArray = (LWLockPadded *) ptr;
493 
494  /*
495  * Initialize the dynamic-allocation counter for tranches, which is
496  * stored just before the first LWLock.
497  */
498  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
499  *LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
500 
501  /* Initialize all LWLocks */
503  }
504 
505  /* Register named extension LWLock tranches in the current process. */
506  for (int i = 0; i < NamedLWLockTrancheRequests; i++)
508  NamedLWLockTrancheArray[i].trancheName);
509 }
Definition: lwlock.h:31
void * ShmemAlloc(Size size)
Definition: shmem.c:161
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:239
Size LWLockShmemSize(void)
Definition: lwlock.c:435
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:652
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:914
#define LWLOCK_MINIMAL_SIZE
Definition: lwlock.h:73
#define MAX_BACKENDS
Definition: postmaster.h:75
int NamedLWLockTrancheRequests
Definition: lwlock.c:236
bool IsUnderPostmaster
Definition: globals.c:109
unsigned int uint32
Definition: c.h:429
static void InitializeLWLocks(void)
Definition: lwlock.c:515
size_t Size
Definition: c.h:528
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:103
int i
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:72
LWLockPadded * MainLWLockArray
Definition: lwlock.c:200

◆ GetLWLockIdentifier()

const char* GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 808 of file lwlock.c.

References Assert, GetLWTrancheName(), and PG_WAIT_LWLOCK.

Referenced by pgstat_get_wait_event().

809 {
810  Assert(classId == PG_WAIT_LWLOCK);
811  /* The event IDs are just tranche numbers. */
812  return GetLWTrancheName(eventId);
813 }
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:780
#define Assert(condition)
Definition: c.h:800
#define PG_WAIT_LWLOCK
Definition: pgstat.h:855

◆ GetLWTrancheName()

static const char * GetLWTrancheName ( uint16  trancheId)
static

Definition at line 780 of file lwlock.c.

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

Referenced by GetLWLockIdentifier().

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

◆ GetNamedLWLockTranche()

LWLockPadded* GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 598 of file lwlock.c.

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

Referenced by pgss_shmem_startup().

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

◆ InitializeLWLocks()

static void InitializeLWLocks ( void  )
static

Definition at line 515 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().

516 {
517  int numNamedLocks = NumLWLocksForNamedTranches();
518  int id;
519  int i;
520  int j;
521  LWLockPadded *lock;
522 
523  /* Initialize all individual LWLocks in main array */
524  for (id = 0, lock = MainLWLockArray; id < NUM_INDIVIDUAL_LWLOCKS; id++, lock++)
525  LWLockInitialize(&lock->lock, id);
526 
527  /* Initialize buffer mapping LWLocks in main array */
529  for (id = 0; id < NUM_BUFFER_PARTITIONS; id++, lock++)
531 
532  /* Initialize lmgrs' LWLocks in main array */
534  for (id = 0; id < NUM_LOCK_PARTITIONS; id++, lock++)
536 
537  /* Initialize predicate lmgrs' LWLocks in main array */
539  for (id = 0; id < NUM_PREDICATELOCK_PARTITIONS; id++, lock++)
541 
542  /*
543  * Copy the info about any named tranches into shared memory (so that
544  * other processes can see it), and initialize the requested LWLocks.
545  */
547  {
548  char *trancheNames;
549 
551  &MainLWLockArray[NUM_FIXED_LWLOCKS + numNamedLocks];
552 
553  trancheNames = (char *) NamedLWLockTrancheArray +
556 
557  for (i = 0; i < NamedLWLockTrancheRequests; i++)
558  {
559  NamedLWLockTrancheRequest *request;
560  NamedLWLockTranche *tranche;
561  char *name;
562 
563  request = &NamedLWLockTrancheRequestArray[i];
564  tranche = &NamedLWLockTrancheArray[i];
565 
566  name = trancheNames;
567  trancheNames += strlen(request->tranche_name) + 1;
568  strcpy(name, request->tranche_name);
569  tranche->trancheId = LWLockNewTrancheId();
570  tranche->trancheName = name;
571 
572  for (j = 0; j < request->num_lwlocks; j++, lock++)
573  LWLockInitialize(&lock->lock, tranche->trancheId);
574  }
575  }
576 }
#define BUFFER_MAPPING_LWLOCK_OFFSET
Definition: lwlock.h:122
int LWLockNewTrancheId(void)
Definition: lwlock.c:628
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:223
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:239
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:127
int NamedLWLockTrancheRequests
Definition: lwlock.c:236
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:420
#define NUM_BUFFER_PARTITIONS
Definition: lwlock.h:111
char * trancheName
Definition: lwlock.h:95
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:744
#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:125
LWLock lock
Definition: lwlock.h:78
const char * name
Definition: encode.c:561
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:227
#define LOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:123
int i
LWLockPadded * MainLWLockArray
Definition: lwlock.c:200
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:115
#define NUM_PREDICATELOCK_PARTITIONS
Definition: lwlock.h:119

◆ InitLWLockAccess()

void InitLWLockAccess ( void  )

Definition at line 582 of file lwlock.c.

Referenced by InitProcess().

583 {
584 #ifdef LWLOCK_STATS
585  init_lwlock_stats();
586 #endif
587 }

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1207 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(), AbortBufferIO(), 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(), CancelVirtualTransaction(), 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(), 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(), pgstat_reset_replslot_counter(), 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(), replorigin_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset(), replorigin_session_setup(), resize(), RestoreScratchTarget(), restoreTwoPhaseData(), SaveSlotToPath(), SerialAdd(), SerialGetMinConflictCommitSeqNo(), SerialSetActiveSerXmin(), SetCommitTsLimit(), SetMultiXactIdLimit(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), StandbyRecoverPreparedTransactions(), StartBufferIO(), 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(), WaitIO(), WALInsertLockAcquire(), WALInsertLockAcquireExclusive(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), and XLogReportParameters().

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

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1434 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().

1435 {
1436  PGPROC *proc = MyProc;
1437  bool mustwait;
1438  int extraWaits = 0;
1439 #ifdef LWLOCK_STATS
1440  lwlock_stats *lwstats;
1441 
1442  lwstats = get_lwlock_stats_entry(lock);
1443 #endif
1444 
1446 
1447  PRINT_LWDEBUG("LWLockAcquireOrWait", lock, mode);
1448 
1449  /* Ensure we will have room to remember the lock */
1451  elog(ERROR, "too many LWLocks taken");
1452 
1453  /*
1454  * Lock out cancel/die interrupts until we exit the code section protected
1455  * by the LWLock. This ensures that interrupts will not interfere with
1456  * manipulations of data structures in shared memory.
1457  */
1458  HOLD_INTERRUPTS();
1459 
1460  /*
1461  * NB: We're using nearly the same twice-in-a-row lock acquisition
1462  * protocol as LWLockAcquire(). Check its comments for details.
1463  */
1464  mustwait = LWLockAttemptLock(lock, mode);
1465 
1466  if (mustwait)
1467  {
1469 
1470  mustwait = LWLockAttemptLock(lock, mode);
1471 
1472  if (mustwait)
1473  {
1474  /*
1475  * Wait until awakened. Like in LWLockAcquire, be prepared for
1476  * bogus wakeups, because we share the semaphore with
1477  * ProcWaitForSignal.
1478  */
1479  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "waiting");
1480 
1481 #ifdef LWLOCK_STATS
1482  lwstats->block_count++;
1483 #endif
1484 
1485  LWLockReportWaitStart(lock);
1486  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), mode);
1487 
1488  for (;;)
1489  {
1490  PGSemaphoreLock(proc->sem);
1491  if (!proc->lwWaiting)
1492  break;
1493  extraWaits++;
1494  }
1495 
1496 #ifdef LOCK_DEBUG
1497  {
1498  /* not waiting anymore */
1499  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1500 
1501  Assert(nwaiters < MAX_BACKENDS);
1502  }
1503 #endif
1504  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode);
1506 
1507  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "awakened");
1508  }
1509  else
1510  {
1511  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "acquired, undoing queue");
1512 
1513  /*
1514  * Got lock in the second attempt, undo queueing. We need to treat
1515  * this as having successfully acquired the lock, otherwise we'd
1516  * not necessarily wake up people we've prevented from acquiring
1517  * the lock.
1518  */
1519  LWLockDequeueSelf(lock);
1520  }
1521  }
1522 
1523  /*
1524  * Fix the process wait semaphore's count for any absorbed wakeups.
1525  */
1526  while (extraWaits-- > 0)
1527  PGSemaphoreUnlock(proc->sem);
1528 
1529  if (mustwait)
1530  {
1531  /* Failed to get lock, so release interrupt holdoff */
1533  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "failed");
1534  TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_FAIL(T_NAME(lock), mode);
1535  }
1536  else
1537  {
1538  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "succeeded");
1539  /* Add lock to list of locks held by this backend */
1542  TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT(T_NAME(lock), mode);
1543  }
1544 
1545  return !mustwait;
1546 }
#define T_NAME(lock)
Definition: lwlock.c:248
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:825
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
PGPROC * MyProc
Definition: proc.c:67
bool lwWaiting
Definition: proc.h:166
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:208
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:218
#define ERROR
Definition: elog.h:43
#define MAX_BACKENDS
Definition: postmaster.h:75
LWLockMode mode
Definition: lwlock.c:214
static void LWLockReportWaitEnd(void)
Definition: lwlock.c:771
unsigned int uint32
Definition: c.h:429
static void LWLockDequeueSelf(LWLock *lock)
Definition: lwlock.c:1112
static void LWLockReportWaitStart(LWLock *lock)
Definition: lwlock.c:762
static void LWLockQueueSelf(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1068
static int num_held_lwlocks
Definition: lwlock.c:217
#define Assert(condition)
Definition: c.h:800
LWLock * lock
Definition: lwlock.c:213
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:312
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:320
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define elog(elevel,...)
Definition: elog.h:228
PGSemaphore sem
Definition: proc.h:123
Definition: proc.h:117
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:143
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:313

◆ LWLockAttemptLock()

static bool LWLockAttemptLock ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 825 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().

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

1380 {
1381  bool mustwait;
1382 
1384 
1385  PRINT_LWDEBUG("LWLockConditionalAcquire", lock, mode);
1386 
1387  /* Ensure we will have room to remember the lock */
1389  elog(ERROR, "too many LWLocks taken");
1390 
1391  /*
1392  * Lock out cancel/die interrupts until we exit the code section protected
1393  * by the LWLock. This ensures that interrupts will not interfere with
1394  * manipulations of data structures in shared memory.
1395  */
1396  HOLD_INTERRUPTS();
1397 
1398  /* Check for the lock */
1399  mustwait = LWLockAttemptLock(lock, mode);
1400 
1401  if (mustwait)
1402  {
1403  /* Failed to get lock, so release interrupt holdoff */
1405 
1406  LOG_LWDEBUG("LWLockConditionalAcquire", lock, "failed");
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  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(T_NAME(lock), mode);
1415  }
1416  return !mustwait;
1417 }
#define T_NAME(lock)
Definition: lwlock.c:248
static PgChecksumMode mode
Definition: pg_checksums.c:61
static bool LWLockAttemptLock(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:825
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:208
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:218
#define ERROR
Definition: elog.h:43
LWLockMode mode
Definition: lwlock.c:214
#define AssertArg(condition)
Definition: c.h:802
static int num_held_lwlocks
Definition: lwlock.c:217
LWLock * lock
Definition: lwlock.c:213
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:312
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define elog(elevel,...)
Definition: elog.h:228
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:313

◆ LWLockConflictsWithVar()

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

Definition at line 1558 of file lwlock.c.

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

Referenced by LWLockWaitForVar().

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

1113 {
1114  bool found = false;
1115  proclist_mutable_iter iter;
1116 
1117 #ifdef LWLOCK_STATS
1118  lwlock_stats *lwstats;
1119 
1120  lwstats = get_lwlock_stats_entry(lock);
1121 
1122  lwstats->dequeue_self_count++;
1123 #endif
1124 
1125  LWLockWaitListLock(lock);
1126 
1127  /*
1128  * Can't just remove ourselves from the list, but we need to iterate over
1129  * all entries as somebody else could have dequeued us.
1130  */
1131  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1132  {
1133  if (iter.cur == MyProc->pgprocno)
1134  {
1135  found = true;
1136  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1137  break;
1138  }
1139  }
1140 
1141  if (proclist_is_empty(&lock->waiters) &&
1142  (pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS) != 0)
1143  {
1145  }
1146 
1147  /* XXX: combine with fetch_and above? */
1148  LWLockWaitListUnlock(lock);
1149 
1150  /* clear waiting state again, nice for debugging */
1151  if (found)
1152  MyProc->lwWaiting = false;
1153  else
1154  {
1155  int extraWaits = 0;
1156 
1157  /*
1158  * Somebody else dequeued us and has or will wake us up. Deal with the
1159  * superfluous absorption of a wakeup.
1160  */
1161 
1162  /*
1163  * Reset RELEASE_OK flag if somebody woke us before we removed
1164  * ourselves - they'll have set it to false.
1165  */
1167 
1168  /*
1169  * Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
1170  * get reset at some inconvenient point later. Most of the time this
1171  * will immediately return.
1172  */
1173  for (;;)
1174  {
1176  if (!MyProc->lwWaiting)
1177  break;
1178  extraWaits++;
1179  }
1180 
1181  /*
1182  * Fix the process wait semaphore's count for any absorbed wakeups.
1183  */
1184  while (extraWaits-- > 0)
1186  }
1187 
1188 #ifdef LOCK_DEBUG
1189  {
1190  /* not waiting anymore */
1191  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1192 
1193  Assert(nwaiters < MAX_BACKENDS);
1194  }
1195 #endif
1196 }
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:67
proclist_head waiters
Definition: lwlock.h:35
bool lwWaiting
Definition: proc.h:166
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:948
#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:75
static uint32 pg_atomic_fetch_and_u32(volatile pg_atomic_uint32 *ptr, uint32 and_)
Definition: atomics.h:358
unsigned int uint32
Definition: c.h:429
#define Assert(condition)
Definition: c.h:800
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:896
int pgprocno
Definition: proc.h:146
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:372
PGSemaphore sem
Definition: proc.h:123
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:143
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 1945 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(), SearchNamedReplicationSlot(), SyncRepWakeQueue(), TransactionIdSetPageStatusInternal(), and TransferPredicateLocksToNewTarget().

1946 {
1947  int i;
1948 
1949  for (i = 0; i < num_held_lwlocks; i++)
1950  {
1951  if (held_lwlocks[i].lock == l && held_lwlocks[i].mode == mode)
1952  return true;
1953  }
1954  return false;
1955 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:218
static int num_held_lwlocks
Definition: lwlock.c:217
int i

◆ LWLockInitialize()

void LWLockInitialize ( LWLock lock,
int  tranche_id 
)

Definition at line 744 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().

745 {
747 #ifdef LOCK_DEBUG
748  pg_atomic_init_u32(&lock->nwaiters, 0);
749 #endif
750  lock->tranche = tranche_id;
751  proclist_init(&lock->waiters);
752 }
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 628 of file lwlock.c.

References ShmemLock, SpinLockAcquire, and SpinLockRelease.

Referenced by apw_init_shmem(), and InitializeLWLocks().

629 {
630  int result;
631  int *LWLockCounter;
632 
633  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
635  result = (*LWLockCounter)++;
637 
638  return result;
639 }
#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:200

◆ LWLockQueueSelf()

static void LWLockQueueSelf ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 1068 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().

1069 {
1070  /*
1071  * If we don't have a PGPROC structure, there's no way to wait. This
1072  * should never occur, since MyProc should only be null during shared
1073  * memory initialization.
1074  */
1075  if (MyProc == NULL)
1076  elog(PANIC, "cannot wait without a PGPROC structure");
1077 
1078  if (MyProc->lwWaiting)
1079  elog(PANIC, "queueing for lock while waiting on another one");
1080 
1081  LWLockWaitListLock(lock);
1082 
1083  /* setting the flag is protected by the spinlock */
1085 
1086  MyProc->lwWaiting = true;
1087  MyProc->lwWaitMode = mode;
1088 
1089  /* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */
1090  if (mode == LW_WAIT_UNTIL_FREE)
1091  proclist_push_head(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1092  else
1093  proclist_push_tail(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1094 
1095  /* Can release the mutex now */
1096  LWLockWaitListUnlock(lock);
1097 
1098 #ifdef LOCK_DEBUG
1099  pg_atomic_fetch_add_u32(&lock->nwaiters, 1);
1100 #endif
1101 
1102 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:99
PGPROC * MyProc
Definition: proc.c:67
proclist_head waiters
Definition: lwlock.h:35
bool lwWaiting
Definition: proc.h:166
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:948
uint8 lwWaitMode
Definition: proc.h:167
pg_atomic_uint32 state
Definition: lwlock.h:34
#define PANIC
Definition: elog.h:53
#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:896
int pgprocno
Definition: proc.h:146
#define elog(elevel,...)
Definition: elog.h:228
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 652 of file lwlock.c.

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

Referenced by apw_init_shmem(), and CreateLWLocks().

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

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1811 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(), CancelVirtualTransaction(), 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(), 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(), pgstat_reset_replslot_counter(), 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(), replorigin_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset(), replorigin_session_setup(), resize(), RestoreScratchTarget(), restoreTwoPhaseData(), SaveSlotToPath(), SerialAdd(), SerialGetMinConflictCommitSeqNo(), SerialSetActiveSerXmin(), SetCommitTsLimit(), SetMultiXactIdLimit(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), ss_report_location(), StandbyRecoverPreparedTransactions(), StartBufferIO(), StartupCLOG(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransGetParent(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SyncOneBuffer(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateBufferIO(), 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(), WaitIO(), WaitOnLock(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), XLogNeedsFlush(), and XLogReportParameters().

1812 {
1813  LWLockMode mode;
1814  uint32 oldstate;
1815  bool check_waiters;
1816  int i;
1817 
1818  /*
1819  * Remove lock from list of locks held. Usually, but not always, it will
1820  * be the latest-acquired lock; so search array backwards.
1821  */
1822  for (i = num_held_lwlocks; --i >= 0;)
1823  if (lock == held_lwlocks[i].lock)
1824  break;
1825 
1826  if (i < 0)
1827  elog(ERROR, "lock %s is not held", T_NAME(lock));
1828 
1829  mode = held_lwlocks[i].mode;
1830 
1831  num_held_lwlocks--;
1832  for (; i < num_held_lwlocks; i++)
1833  held_lwlocks[i] = held_lwlocks[i + 1];
1834 
1835  PRINT_LWDEBUG("LWLockRelease", lock, mode);
1836 
1837  /*
1838  * Release my hold on lock, after that it can immediately be acquired by
1839  * others, even if we still have to wakeup other waiters.
1840  */
1841  if (mode == LW_EXCLUSIVE)
1842  oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_EXCLUSIVE);
1843  else
1844  oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_SHARED);
1845 
1846  /* nobody else can have that kind of lock */
1847  Assert(!(oldstate & LW_VAL_EXCLUSIVE));
1848 
1849 
1850  /*
1851  * We're still waiting for backends to get scheduled, don't wake them up
1852  * again.
1853  */
1854  if ((oldstate & (LW_FLAG_HAS_WAITERS | LW_FLAG_RELEASE_OK)) ==
1856  (oldstate & LW_LOCK_MASK) == 0)
1857  check_waiters = true;
1858  else
1859  check_waiters = false;
1860 
1861  /*
1862  * As waking up waiters requires the spinlock to be acquired, only do so
1863  * if necessary.
1864  */
1865  if (check_waiters)
1866  {
1867  /* XXX: remove before commit? */
1868  LOG_LWDEBUG("LWLockRelease", lock, "releasing waiters");
1869  LWLockWakeup(lock);
1870  }
1871 
1872  TRACE_POSTGRESQL_LWLOCK_RELEASE(T_NAME(lock));
1873 
1874  /*
1875  * Now okay to allow cancel/die interrupts.
1876  */
1878 }
#define T_NAME(lock)
Definition: lwlock.c:248
static PgChecksumMode mode
Definition: pg_checksums.c:61
LWLockMode
Definition: lwlock.h:130
#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:118
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:218
#define ERROR
Definition: elog.h:43
LWLockMode mode
Definition: lwlock.c:214
static void LWLockWakeup(LWLock *lock)
Definition: lwlock.c:961
unsigned int uint32
Definition: c.h:429
static int num_held_lwlocks
Definition: lwlock.c:217
#define Assert(condition)
Definition: c.h:800
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:312
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:100
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:103
#define elog(elevel,...)
Definition: elog.h:228
int i
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:313

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

Definition at line 1910 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().

1911 {
1912  while (num_held_lwlocks > 0)
1913  {
1914  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1915 
1917  }
1918 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:218
static int num_held_lwlocks
Definition: lwlock.c:217
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116

◆ LWLockReleaseClearVar()

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

Definition at line 1884 of file lwlock.c.

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

Referenced by WALInsertLockRelease().

1885 {
1886  LWLockWaitListLock(lock);
1887 
1888  /*
1889  * Set the variable's value before releasing the lock, that prevents race
1890  * a race condition wherein a new locker acquires the lock, but hasn't yet
1891  * set the variables value.
1892  */
1893  *valptr = val;
1894  LWLockWaitListUnlock(lock);
1895 
1896  LWLockRelease(lock);
1897 }
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:948
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:896
long val
Definition: informix.c:664

◆ LWLockReportWaitEnd()

static void LWLockReportWaitEnd ( void  )
inlinestatic

Definition at line 771 of file lwlock.c.

References pgstat_report_wait_end().

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

772 {
774 }
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1466

◆ LWLockReportWaitStart()

static void LWLockReportWaitStart ( LWLock lock)
inlinestatic

Definition at line 762 of file lwlock.c.

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

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

763 {
765 }
uint16 tranche
Definition: lwlock.h:33
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1442
#define PG_WAIT_LWLOCK
Definition: pgstat.h:855

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 435 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().

436 {
437  Size size;
438  int i;
439  int numLocks = NUM_FIXED_LWLOCKS;
440 
441  /* Calculate total number of locks needed in the main array. */
442  numLocks += NumLWLocksForNamedTranches();
443 
444  /* Space for the LWLock array. */
445  size = mul_size(numLocks, sizeof(LWLockPadded));
446 
447  /* Space for dynamic allocation counter, plus room for alignment. */
448  size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
449 
450  /* space for named tranches. */
452 
453  /* space for name of each tranche. */
454  for (i = 0; i < NamedLWLockTrancheRequests; i++)
455  size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
456 
457  /* Disallow adding any more named tranches. */
459 
460  return size;
461 }
static bool lock_named_request_allowed
Definition: lwlock.c:241
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:127
int NamedLWLockTrancheRequests
Definition: lwlock.c:236
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:420
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
size_t Size
Definition: c.h:528
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:227
int i
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:72

◆ LWLockUpdateVar()

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

Definition at line 1757 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().

1758 {
1759  proclist_head wakeup;
1760  proclist_mutable_iter iter;
1761 
1762  PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1763 
1764  proclist_init(&wakeup);
1765 
1766  LWLockWaitListLock(lock);
1767 
1769 
1770  /* Update the lock's value */
1771  *valptr = val;
1772 
1773  /*
1774  * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1775  * up. They are always in the front of the queue.
1776  */
1777  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1778  {
1779  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1780 
1781  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1782  break;
1783 
1784  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1785  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1786  }
1787 
1788  /* We are done updating shared state of the lock itself. */
1789  LWLockWaitListUnlock(lock);
1790 
1791  /*
1792  * Awaken any waiters I removed from the queue.
1793  */
1794  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1795  {
1796  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1797 
1798  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1799  /* check comment in LWLockWakeup() about this barrier */
1800  pg_write_barrier();
1801  waiter->lwWaiting = false;
1802  PGSemaphoreUnlock(waiter->sem);
1803  }
1804 }
#define GetPGProcByNumber(n)
Definition: proc.h:361
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
proclist_head waiters
Definition: lwlock.h:35
bool lwWaiting
Definition: proc.h:166
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:948
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
uint8 lwWaitMode
Definition: proc.h:167
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:800
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:312
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:191
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:896
#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:123
Definition: proc.h:117
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 1618 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().

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

◆ LWLockWaitListLock()

static void LWLockWaitListLock ( LWLock lock)
static

Definition at line 896 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().

897 {
898  uint32 old_state;
899 #ifdef LWLOCK_STATS
900  lwlock_stats *lwstats;
901  uint32 delays = 0;
902 
903  lwstats = get_lwlock_stats_entry(lock);
904 #endif
905 
906  while (true)
907  {
908  /* always try once to acquire lock directly */
909  old_state = pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_LOCKED);
910  if (!(old_state & LW_FLAG_LOCKED))
911  break; /* got lock */
912 
913  /* and then spin without atomic operations until lock is released */
914  {
915  SpinDelayStatus delayStatus;
916 
917  init_local_spin_delay(&delayStatus);
918 
919  while (old_state & LW_FLAG_LOCKED)
920  {
921  perform_spin_delay(&delayStatus);
922  old_state = pg_atomic_read_u32(&lock->state);
923  }
924 #ifdef LWLOCK_STATS
925  delays += delayStatus.delays;
926 #endif
927  finish_spin_delay(&delayStatus);
928  }
929 
930  /*
931  * Retry. The lock might obviously already be re-acquired by the time
932  * we're attempting to get it again.
933  */
934  }
935 
936 #ifdef LWLOCK_STATS
937  lwstats->spin_delay_count += delays;
938 #endif
939 }
#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:429
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 948 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().

949 {
951 
952  old_state = pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_LOCKED);
953 
954  Assert(old_state & LW_FLAG_LOCKED);
955 }
#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:429
#define Assert(condition)
Definition: c.h:800
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:143

◆ LWLockWakeup()

static void LWLockWakeup ( LWLock lock)
static

Definition at line 961 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().

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

◆ NumLWLocksForNamedTranches()

static int NumLWLocksForNamedTranches ( void  )
static

Definition at line 420 of file lwlock.c.

References i, and NamedLWLockTrancheRequests.

Referenced by InitializeLWLocks(), and LWLockShmemSize().

421 {
422  int numLocks = 0;
423  int i;
424 
425  for (i = 0; i < NamedLWLockTrancheRequests; i++)
426  numLocks += NamedLWLockTrancheRequestArray[i].num_lwlocks;
427 
428  return numLocks;
429 }
int NamedLWLockTrancheRequests
Definition: lwlock.c:236
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:227
int i

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 704 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().

705 {
706  NamedLWLockTrancheRequest *request;
707 
709  return; /* too late */
710 
711  if (NamedLWLockTrancheRequestArray == NULL)
712  {
717  * sizeof(NamedLWLockTrancheRequest));
718  }
719 
721  {
723 
724  while (i <= NamedLWLockTrancheRequests)
725  i *= 2;
726 
729  i * sizeof(NamedLWLockTrancheRequest));
731  }
732 
734  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
735  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
736  request->num_lwlocks = num_lwlocks;
738 }
static bool lock_named_request_allowed
Definition: lwlock.c:241
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:223
#define NAMEDATALEN
int NamedLWLockTrancheRequests
Definition: lwlock.c:236
bool IsUnderPostmaster
Definition: globals.c:109
MemoryContext TopMemoryContext
Definition: mcxt.c:44
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:228
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define Assert(condition)
Definition: c.h:800
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1070
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:227
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
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 218 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 241 of file lwlock.c.

Referenced by LWLockShmemSize(), and RequestNamedLWLockTranche().

◆ LWLockTrancheNames

const char** LWLockTrancheNames = NULL
static

Definition at line 192 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ LWLockTrancheNamesAllocated

int LWLockTrancheNamesAllocated = 0
static

Definition at line 193 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ MainLWLockArray

LWLockPadded* MainLWLockArray = NULL

Definition at line 200 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheArray

NamedLWLockTranche* NamedLWLockTrancheArray = NULL

Definition at line 239 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheRequestArray

NamedLWLockTrancheRequest* NamedLWLockTrancheRequestArray = NULL
static

Definition at line 227 of file lwlock.c.

◆ NamedLWLockTrancheRequests

◆ NamedLWLockTrancheRequestsAllocated

int NamedLWLockTrancheRequestsAllocated = 0
static

Definition at line 228 of file lwlock.c.

Referenced by RequestNamedLWLockTranche().

◆ num_held_lwlocks

◆ ShmemLock