PostgreSQL Source Code  git master
lwlock.c File Reference
#include "postgres.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "pgstat.h"
#include "port/pg_bitutils.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 100 of file lwlock.c.

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

◆ LW_FLAG_LOCKED

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

Definition at line 102 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 107 of file lwlock.c.

Referenced by LWLockAttemptLock(), and LWLockRelease().

◆ LW_SHARED_MASK

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

Definition at line 109 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 105 of file lwlock.c.

Referenced by LWLockAttemptLock(), and LWLockRelease().

◆ MAX_SIMUL_LWLOCKS

#define MAX_SIMUL_LWLOCKS   200

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

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

◆ GetLWLockIdentifier()

const char* GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 800 of file lwlock.c.

References Assert, GetLWTrancheName(), and PG_WAIT_LWLOCK.

Referenced by pgstat_get_wait_event().

801 {
802  Assert(classId == PG_WAIT_LWLOCK);
803  /* The event IDs are just tranche numbers. */
804  return GetLWTrancheName(eventId);
805 }
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:772
#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 772 of file lwlock.c.

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

Referenced by GetLWLockIdentifier().

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

◆ GetNamedLWLockTranche()

LWLockPadded* GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 595 of file lwlock.c.

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

Referenced by pgss_shmem_startup().

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

◆ InitializeLWLocks()

static void InitializeLWLocks ( void  )
static

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

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

◆ InitLWLockAccess()

void InitLWLockAccess ( void  )

Definition at line 579 of file lwlock.c.

Referenced by InitProcess().

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

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1199 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(), BootStrapXLOG(), 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(), InvalidatePossiblyObsoleteSlot(), KnownAssignedXidsAdd(), KnownAssignedXidsReset(), load_relmap_file(), 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(), LookupGXact(), 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(), relmap_redo(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), 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(), SetNextObjectId(), 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(), WaitForWALToBecomeAvailable(), WALInsertLockAcquire(), WALInsertLockAcquireExclusive(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogReportParameters(), and XLogShutdownWalRcv().

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

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)

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

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

◆ LWLockAttemptLock()

static bool LWLockAttemptLock ( LWLock lock,
LWLockMode  mode 
)
static

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

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

1371 {
1372  bool mustwait;
1373 
1375 
1376  PRINT_LWDEBUG("LWLockConditionalAcquire", lock, mode);
1377 
1378  /* Ensure we will have room to remember the lock */
1380  elog(ERROR, "too many LWLocks taken");
1381 
1382  /*
1383  * Lock out cancel/die interrupts until we exit the code section protected
1384  * by the LWLock. This ensures that interrupts will not interfere with
1385  * manipulations of data structures in shared memory.
1386  */
1387  HOLD_INTERRUPTS();
1388 
1389  /* Check for the lock */
1390  mustwait = LWLockAttemptLock(lock, mode);
1391 
1392  if (mustwait)
1393  {
1394  /* Failed to get lock, so release interrupt holdoff */
1396 
1397  LOG_LWDEBUG("LWLockConditionalAcquire", lock, "failed");
1398  if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL_ENABLED())
1399  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL(T_NAME(lock), mode);
1400  }
1401  else
1402  {
1403  /* Add lock to list of locks held by this backend */
1406  if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_ENABLED())
1407  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(T_NAME(lock), mode);
1408  }
1409  return !mustwait;
1410 }
#define T_NAME(lock)
Definition: lwlock.c:247
static PgChecksumMode mode
Definition: pg_checksums.c:65
static bool LWLockAttemptLock(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:817
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:207
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:133
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:217
#define ERROR
Definition: elog.h:46
LWLockMode mode
Definition: lwlock.c:213
#define AssertArg(condition)
Definition: c.h:806
static int num_held_lwlocks
Definition: lwlock.c:216
LWLock * lock
Definition: lwlock.c:212
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:311
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131
#define elog(elevel,...)
Definition: elog.h:232
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:312

◆ LWLockConflictsWithVar()

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

Definition at line 1554 of file lwlock.c.

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

Referenced by LWLockWaitForVar().

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

1105 {
1106  bool found = false;
1107  proclist_mutable_iter iter;
1108 
1109 #ifdef LWLOCK_STATS
1110  lwlock_stats *lwstats;
1111 
1112  lwstats = get_lwlock_stats_entry(lock);
1113 
1114  lwstats->dequeue_self_count++;
1115 #endif
1116 
1117  LWLockWaitListLock(lock);
1118 
1119  /*
1120  * Can't just remove ourselves from the list, but we need to iterate over
1121  * all entries as somebody else could have dequeued us.
1122  */
1123  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1124  {
1125  if (iter.cur == MyProc->pgprocno)
1126  {
1127  found = true;
1128  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1129  break;
1130  }
1131  }
1132 
1133  if (proclist_is_empty(&lock->waiters) &&
1134  (pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS) != 0)
1135  {
1137  }
1138 
1139  /* XXX: combine with fetch_and above? */
1140  LWLockWaitListUnlock(lock);
1141 
1142  /* clear waiting state again, nice for debugging */
1143  if (found)
1144  MyProc->lwWaiting = false;
1145  else
1146  {
1147  int extraWaits = 0;
1148 
1149  /*
1150  * Somebody else dequeued us and has or will wake us up. Deal with the
1151  * superfluous absorption of a wakeup.
1152  */
1153 
1154  /*
1155  * Reset RELEASE_OK flag if somebody woke us before we removed
1156  * ourselves - they'll have set it to false.
1157  */
1159 
1160  /*
1161  * Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
1162  * get reset at some inconvenient point later. Most of the time this
1163  * will immediately return.
1164  */
1165  for (;;)
1166  {
1168  if (!MyProc->lwWaiting)
1169  break;
1170  extraWaits++;
1171  }
1172 
1173  /*
1174  * Fix the process wait semaphore's count for any absorbed wakeups.
1175  */
1176  while (extraWaits-- > 0)
1178  }
1179 
1180 #ifdef LOCK_DEBUG
1181  {
1182  /* not waiting anymore */
1183  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1184 
1185  Assert(nwaiters < MAX_BACKENDS);
1186  }
1187 #endif
1188 }
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:100
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:940
#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:101
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:320
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:888
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 1937 of file lwlock.c.

References i, and num_held_lwlocks.

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

1938 {
1939  int i;
1940 
1941  for (i = 0; i < num_held_lwlocks; i++)
1942  {
1943  if (held_lwlocks[i].lock == l && held_lwlocks[i].mode == mode)
1944  return true;
1945  }
1946  return false;
1947 }
static PgChecksumMode mode
Definition: pg_checksums.c:65
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:217
static int num_held_lwlocks
Definition: lwlock.c:216
int i

◆ LWLockInitialize()

void LWLockInitialize ( LWLock lock,
int  tranche_id 
)

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

737 {
739 #ifdef LOCK_DEBUG
740  pg_atomic_init_u32(&lock->nwaiters, 0);
741 #endif
742  lock->tranche = tranche_id;
743  proclist_init(&lock->waiters);
744 }
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:101
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 625 of file lwlock.c.

References ShmemLock, SpinLockAcquire, and SpinLockRelease.

Referenced by apw_init_shmem(), and InitializeLWLocks().

626 {
627  int result;
628  int *LWLockCounter;
629 
630  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
632  result = (*LWLockCounter)++;
634 
635  return result;
636 }
#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:199

◆ LWLockQueueSelf()

static void LWLockQueueSelf ( LWLock lock,
LWLockMode  mode 
)
static

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

1061 {
1062  /*
1063  * If we don't have a PGPROC structure, there's no way to wait. This
1064  * should never occur, since MyProc should only be null during shared
1065  * memory initialization.
1066  */
1067  if (MyProc == NULL)
1068  elog(PANIC, "cannot wait without a PGPROC structure");
1069 
1070  if (MyProc->lwWaiting)
1071  elog(PANIC, "queueing for lock while waiting on another one");
1072 
1073  LWLockWaitListLock(lock);
1074 
1075  /* setting the flag is protected by the spinlock */
1077 
1078  MyProc->lwWaiting = true;
1079  MyProc->lwWaitMode = mode;
1080 
1081  /* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */
1082  if (mode == LW_WAIT_UNTIL_FREE)
1083  proclist_push_head(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1084  else
1085  proclist_push_tail(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1086 
1087  /* Can release the mutex now */
1088  LWLockWaitListUnlock(lock);
1089 
1090 #ifdef LOCK_DEBUG
1091  pg_atomic_fetch_add_u32(&lock->nwaiters, 1);
1092 #endif
1093 
1094 }
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:100
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:940
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:888
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 649 of file lwlock.c.

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

Referenced by apw_init_shmem(), and CreateLWLocks().

650 {
651  /* This should only be called for user-defined tranches. */
652  if (tranche_id < LWTRANCHE_FIRST_USER_DEFINED)
653  return;
654 
655  /* Convert to array index. */
656  tranche_id -= LWTRANCHE_FIRST_USER_DEFINED;
657 
658  /* If necessary, create or enlarge array. */
659  if (tranche_id >= LWLockTrancheNamesAllocated)
660  {
661  int newalloc;
662 
663  newalloc = pg_nextpower2_32(Max(8, tranche_id + 1));
664 
665  if (LWLockTrancheNames == NULL)
666  LWLockTrancheNames = (const char **)
668  newalloc * sizeof(char *));
669  else
670  {
671  LWLockTrancheNames = (const char **)
672  repalloc(LWLockTrancheNames, newalloc * sizeof(char *));
674  0,
675  (newalloc - LWLockTrancheNamesAllocated) * sizeof(char *));
676  }
677  LWLockTrancheNamesAllocated = newalloc;
678  }
679 
680  LWLockTrancheNames[tranche_id] = tranche_name;
681 }
static int LWLockTrancheNamesAllocated
Definition: lwlock.c:192
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:146
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:191

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1803 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(), BootStrapXLOG(), 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(), InvalidatePossiblyObsoleteSlot(), KnownAssignedXidsAdd(), KnownAssignedXidsReset(), load_relmap_file(), 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(), LookupGXact(), 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(), relmap_redo(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), 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(), SetNextObjectId(), 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(), WaitForWALToBecomeAvailable(), WaitOnLock(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), XLogNeedsFlush(), XLogReportParameters(), and XLogShutdownWalRcv().

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

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

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

1903 {
1904  while (num_held_lwlocks > 0)
1905  {
1906  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1907 
1909  }
1910 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:217
static int num_held_lwlocks
Definition: lwlock.c:216
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131

◆ LWLockReleaseClearVar()

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

Definition at line 1876 of file lwlock.c.

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

Referenced by WALInsertLockRelease().

1877 {
1878  LWLockWaitListLock(lock);
1879 
1880  /*
1881  * Set the variable's value before releasing the lock, that prevents race
1882  * a race condition wherein a new locker acquires the lock, but hasn't yet
1883  * set the variables value.
1884  */
1885  *valptr = val;
1886  LWLockWaitListUnlock(lock);
1887 
1888  LWLockRelease(lock);
1889 }
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:940
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:888
long val
Definition: informix.c:664

◆ LWLockReportWaitEnd()

static void LWLockReportWaitEnd ( void  )
inlinestatic

Definition at line 763 of file lwlock.c.

References pgstat_report_wait_end().

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

764 {
766 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:274

◆ LWLockReportWaitStart()

static void LWLockReportWaitStart ( LWLock lock)
inlinestatic

Definition at line 754 of file lwlock.c.

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

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

755 {
757 }
#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:258

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 433 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 CalculateShmemSize(), and CreateLWLocks().

434 {
435  Size size;
436  int i;
437  int numLocks = NUM_FIXED_LWLOCKS;
438 
439  /* Calculate total number of locks needed in the main array. */
440  numLocks += NumLWLocksForNamedTranches();
441 
442  /* Space for the LWLock array. */
443  size = mul_size(numLocks, sizeof(LWLockPadded));
444 
445  /* Space for dynamic allocation counter, plus room for alignment. */
446  size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
447 
448  /* space for named tranches. */
450 
451  /* space for name of each tranche. */
452  for (i = 0; i < NamedLWLockTrancheRequests; i++)
453  size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
454 
455  /* Disallow adding any more named tranches. */
457 
458  return size;
459 }
static bool lock_named_request_allowed
Definition: lwlock.c:240
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:99
int NamedLWLockTrancheRequests
Definition: lwlock.c:235
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:418
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:226
int i
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:52

◆ LWLockUpdateVar()

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

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

1750 {
1751  proclist_head wakeup;
1752  proclist_mutable_iter iter;
1753 
1754  PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1755 
1756  proclist_init(&wakeup);
1757 
1758  LWLockWaitListLock(lock);
1759 
1761 
1762  /* Update the lock's value */
1763  *valptr = val;
1764 
1765  /*
1766  * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1767  * up. They are always in the front of the queue.
1768  */
1769  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1770  {
1771  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1772 
1773  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1774  break;
1775 
1776  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1777  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1778  }
1779 
1780  /* We are done updating shared state of the lock itself. */
1781  LWLockWaitListUnlock(lock);
1782 
1783  /*
1784  * Awaken any waiters I removed from the queue.
1785  */
1786  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1787  {
1788  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1789 
1790  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1791  /* check comment in LWLockWakeup() about this barrier */
1792  pg_write_barrier();
1793  waiter->lwWaiting = false;
1794  PGSemaphoreUnlock(waiter->sem);
1795  }
1796 }
#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:940
#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:311
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:191
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:888
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:104
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 1614 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().

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

◆ LWLockWaitListLock()

static void LWLockWaitListLock ( LWLock lock)
static

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

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

941 {
943 
944  old_state = pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_LOCKED);
945 
946  Assert(old_state & LW_FLAG_LOCKED);
947 }
#define LW_FLAG_LOCKED
Definition: lwlock.c:102
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 953 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().

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

◆ NumLWLocksForNamedTranches()

static int NumLWLocksForNamedTranches ( void  )
static

Definition at line 418 of file lwlock.c.

References i, and NamedLWLockTrancheRequests.

Referenced by InitializeLWLocks(), and LWLockShmemSize().

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

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 699 of file lwlock.c.

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

Referenced by _PG_init().

700 {
701  NamedLWLockTrancheRequest *request;
702 
704  return; /* too late */
705 
706  if (NamedLWLockTrancheRequestArray == NULL)
707  {
712  * sizeof(NamedLWLockTrancheRequest));
713  }
714 
716  {
718 
721  i * sizeof(NamedLWLockTrancheRequest));
723  }
724 
726  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
727  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
728  request->num_lwlocks = num_lwlocks;
730 }
static bool lock_named_request_allowed
Definition: lwlock.c:240
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:222
#define NAMEDATALEN
int NamedLWLockTrancheRequests
Definition: lwlock.c:235
bool IsUnderPostmaster
Definition: globals.c:112
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:146
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:227
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:226
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 131 of file lwlock.c.

Referenced by GetLWTrancheName().

◆ held_lwlocks

LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
static

Definition at line 217 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 240 of file lwlock.c.

Referenced by LWLockShmemSize(), and RequestNamedLWLockTranche().

◆ LWLockTrancheNames

const char** LWLockTrancheNames = NULL
static

Definition at line 191 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ LWLockTrancheNamesAllocated

int LWLockTrancheNamesAllocated = 0
static

Definition at line 192 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ MainLWLockArray

LWLockPadded* MainLWLockArray = NULL

Definition at line 199 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheArray

NamedLWLockTranche* NamedLWLockTrancheArray = NULL

Definition at line 238 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheRequestArray

NamedLWLockTrancheRequest* NamedLWLockTrancheRequestArray = NULL
static

Definition at line 226 of file lwlock.c.

◆ NamedLWLockTrancheRequests

◆ NamedLWLockTrancheRequestsAllocated

int NamedLWLockTrancheRequestsAllocated = 0
static

Definition at line 227 of file lwlock.c.

Referenced by RequestNamedLWLockTranche().

◆ num_held_lwlocks

◆ ShmemLock