PostgreSQL Source Code  git master
lwlock.c File Reference
#include "postgres.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "pg_trace.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 T_NAME(lock)   (LWLockTrancheArray[(lock)->tranche])
 
#define MAX_SIMUL_LWLOCKS   200
 
#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

static void InitializeLWLocks (void)
 
static void RegisterLWLockTranches (void)
 
static void LWLockReportWaitStart (LWLock *lock)
 
static void LWLockReportWaitEnd (void)
 
static int NumLWLocksByNamedTranches (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
 
static const char ** LWLockTrancheArray = NULL
 
static int LWLockTranchesAllocated = 0
 
LWLockPaddedMainLWLockArray = NULL
 
static int num_held_lwlocks = 0
 
static LWLockHandle held_lwlocks [MAX_SIMUL_LWLOCKS]
 
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 133 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)    (LWLockTrancheArray[(lock)->tranche])

Typedef Documentation

◆ LWLockHandle

typedef struct LWLockHandle LWLockHandle

◆ NamedLWLockTrancheRequest

Function Documentation

◆ CreateLWLocks()

void CreateLWLocks ( void  )

Definition at line 381 of file lwlock.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

382 {
384  "MAX_BACKENDS too big for lwlock.c");
385 
387  sizeof(LWLock) <= LWLOCK_PADDED_SIZE,
388  "Miscalculated LWLock padding");
389 
390  if (!IsUnderPostmaster)
391  {
392  Size spaceLocks = LWLockShmemSize();
393  int *LWLockCounter;
394  char *ptr;
395 
396  /* Allocate space */
397  ptr = (char *) ShmemAlloc(spaceLocks);
398 
399  /* Leave room for dynamic allocation of tranches */
400  ptr += sizeof(int);
401 
402  /* Ensure desired alignment of LWLock array */
403  ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
404 
405  MainLWLockArray = (LWLockPadded *) ptr;
406 
407  /*
408  * Initialize the dynamic-allocation counter for tranches, which is
409  * stored just before the first LWLock.
410  */
411  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
412  *LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
413 
414  /* Initialize all LWLocks */
416  }
417 
418  /* Register all LWLock tranches */
420 }
Definition: lwlock.h:32
void * ShmemAlloc(Size size)
Definition: shmem.c:157
Size LWLockShmemSize(void)
Definition: lwlock.c:349
static void RegisterLWLockTranches(void)
Definition: lwlock.c:491
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:842
#define LWLOCK_MINIMAL_SIZE
Definition: lwlock.h:74
#define MAX_BACKENDS
Definition: postmaster.h:75
bool IsUnderPostmaster
Definition: globals.c:109
unsigned int uint32
Definition: c.h:358
static void InitializeLWLocks(void)
Definition: lwlock.c:426
size_t Size
Definition: c.h:466
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:103
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:73
LWLockPadded * MainLWLockArray
Definition: lwlock.c:125

◆ GetLWLockIdentifier()

const char* GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 714 of file lwlock.c.

References Assert, LWLockTrancheArray, LWLockTranchesAllocated, and PG_WAIT_LWLOCK.

Referenced by pgstat_get_wait_event().

715 {
716  Assert(classId == PG_WAIT_LWLOCK);
717 
718  /*
719  * It is quite possible that user has registered tranche in one of the
720  * backends (e.g. by allocating lwlocks in dynamic shared memory) but not
721  * all of them, so we can't assume the tranche is registered here.
722  */
723  if (eventId >= LWLockTranchesAllocated ||
724  LWLockTrancheArray[eventId] == NULL)
725  return "extension";
726 
727  return LWLockTrancheArray[eventId];
728 }
static int LWLockTranchesAllocated
Definition: lwlock.c:115
static const char ** LWLockTrancheArray
Definition: lwlock.c:114
#define Assert(condition)
Definition: c.h:732
#define PG_WAIT_LWLOCK
Definition: pgstat.h:754

◆ GetNamedLWLockTranche()

LWLockPadded* GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 552 of file lwlock.c.

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

Referenced by pgss_shmem_startup().

553 {
554  int lock_pos;
555  int i;
556 
557  /*
558  * Obtain the position of base address of LWLock belonging to requested
559  * tranche_name in MainLWLockArray. LWLocks for named tranches are placed
560  * in MainLWLockArray after fixed locks.
561  */
562  lock_pos = NUM_FIXED_LWLOCKS;
563  for (i = 0; i < NamedLWLockTrancheRequests; i++)
564  {
565  if (strcmp(NamedLWLockTrancheRequestArray[i].tranche_name,
566  tranche_name) == 0)
567  return &MainLWLockArray[lock_pos];
568 
570  }
571 
572  if (i >= NamedLWLockTrancheRequests)
573  elog(ERROR, "requested tranche is not registered");
574 
575  /* just to keep compiler quiet */
576  return NULL;
577 }
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:129
#define ERROR
Definition: elog.h:43
int NamedLWLockTrancheRequests
Definition: lwlock.c:154
NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:152
#define elog(elevel,...)
Definition: elog.h:226
int i
LWLockPadded * MainLWLockArray
Definition: lwlock.c:125

◆ InitializeLWLocks()

static void InitializeLWLocks ( void  )
static

Definition at line 426 of file lwlock.c.

References i, LWLockPadded::lock, LWLockHandle::lock, 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, NumLWLocksByNamedTranches(), NamedLWLockTrancheRequest::tranche_name, NamedLWLockTranche::trancheId, and NamedLWLockTranche::trancheName.

Referenced by CreateLWLocks().

427 {
428  int numNamedLocks = NumLWLocksByNamedTranches();
429  int id;
430  int i;
431  int j;
432  LWLockPadded *lock;
433 
434  /* Initialize all individual LWLocks in main array */
435  for (id = 0, lock = MainLWLockArray; id < NUM_INDIVIDUAL_LWLOCKS; id++, lock++)
436  LWLockInitialize(&lock->lock, id);
437 
438  /* Initialize buffer mapping LWLocks in main array */
439  lock = MainLWLockArray + NUM_INDIVIDUAL_LWLOCKS;
440  for (id = 0; id < NUM_BUFFER_PARTITIONS; id++, lock++)
442 
443  /* Initialize lmgrs' LWLocks in main array */
444  lock = MainLWLockArray + NUM_INDIVIDUAL_LWLOCKS + NUM_BUFFER_PARTITIONS;
445  for (id = 0; id < NUM_LOCK_PARTITIONS; id++, lock++)
447 
448  /* Initialize predicate lmgrs' LWLocks in main array */
449  lock = MainLWLockArray + NUM_INDIVIDUAL_LWLOCKS +
450  NUM_BUFFER_PARTITIONS + NUM_LOCK_PARTITIONS;
451  for (id = 0; id < NUM_PREDICATELOCK_PARTITIONS; id++, lock++)
453 
454  /* Initialize named tranches. */
456  {
457  char *trancheNames;
458 
460  &MainLWLockArray[NUM_FIXED_LWLOCKS + numNamedLocks];
461 
462  trancheNames = (char *) NamedLWLockTrancheArray +
465 
466  for (i = 0; i < NamedLWLockTrancheRequests; i++)
467  {
468  NamedLWLockTrancheRequest *request;
469  NamedLWLockTranche *tranche;
470  char *name;
471 
472  request = &NamedLWLockTrancheRequestArray[i];
473  tranche = &NamedLWLockTrancheArray[i];
474 
475  name = trancheNames;
476  trancheNames += strlen(request->tranche_name) + 1;
477  strcpy(name, request->tranche_name);
478  tranche->trancheId = LWLockNewTrancheId();
479  tranche->trancheName = name;
480 
481  for (j = 0; j < request->num_lwlocks; j++, lock++)
482  LWLockInitialize(&lock->lock, tranche->trancheId);
483  }
484  }
485 }
int LWLockNewTrancheId(void)
Definition: lwlock.c:583
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:148
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:156
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:129
int NamedLWLockTrancheRequests
Definition: lwlock.c:154
#define NUM_BUFFER_PARTITIONS
Definition: lwlock.h:113
char * trancheName
Definition: lwlock.h:97
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:678
LWLock lock
Definition: lwlock.h:79
static int NumLWLocksByNamedTranches(void)
Definition: lwlock.c:334
const char * name
Definition: encode.c:521
NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:152
int i
LWLockPadded * MainLWLockArray
Definition: lwlock.c:125
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:117
#define NUM_PREDICATELOCK_PARTITIONS
Definition: lwlock.h:121

◆ InitLWLockAccess()

void InitLWLockAccess ( void  )

Definition at line 536 of file lwlock.c.

Referenced by InitProcess().

537 {
538 #ifdef LWLOCK_STATS
539  init_lwlock_stats();
540 #endif
541 }

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1122 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(), analyze_rel(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_init_shmem(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AsyncShmemInit(), 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(), 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(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldestXmin(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionData(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), HaveVirtualXIDsDelayingChkpt(), InstallXLogFileSegment(), InvalidateBuffer(), 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(), OldSerXidAdd(), OldSerXidGetMinConflictCommitSeqNo(), OldSerXidSetActiveSerXmin(), PageIsPredicateLocked(), perform_relmap_update(), pg_get_replication_slots(), pg_notification_queue_usage(), pg_show_replication_origin_status(), pg_stat_get_subscription(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgss_shmem_startup(), pgss_store(), PostPrepare_Locks(), PostPrepare_MultiXact(), PostPrepare_Twophase(), PreCommit_CheckForSerializationFailure(), PreCommit_Notify(), predicatelock_twophase_recover(), PredicateLockPageSplit(), PredicateLockTwoPhaseFinish(), PrefetchBuffer(), PrescanPreparedTransactions(), ProcArrayAdd(), ProcArrayApplyRecoveryInfo(), ProcArrayApplyXidAssignment(), ProcArrayGetReplicationSlotXmin(), ProcArrayGroupClearXid(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), ProcArrayRemove(), ProcArraySetReplicationSlotXmin(), process_syncing_tables_for_apply(), ProcKill(), ProcSleep(), ReadBuffer_common(), ReadMultiXactCounts(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadRecord(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePreInvalidate(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), 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(), SetCommitTsLimit(), SetMultiXactIdLimit(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SIInsertDataEntries(), SimpleLruFlush(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), StandbyRecoverPreparedTransactions(), StartBufferIO(), StartupCLOG(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SyncOneBuffer(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepInitConfig(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TransactionGroupUpdateXidStatus(), TransactionIdGetCommitTsData(), TransactionIdIsActive(), TransactionIdIsInProgress(), TransactionIdLimitedForOldSnapshots(), TransactionIdSetPageStatus(), TransactionTreeSetCommitTsData(), TransferPredicateLocksToNewTarget(), TrimCLOG(), TrimMultiXact(), TruncateMultiXact(), TwoPhaseGetGXact(), txid_status(), UpdateMinRecoveryPoint(), 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(), and XLogBackgroundFlush().

1123 {
1124  PGPROC *proc = MyProc;
1125  bool result = true;
1126  int extraWaits = 0;
1127 #ifdef LWLOCK_STATS
1128  lwlock_stats *lwstats;
1129 
1130  lwstats = get_lwlock_stats_entry(lock);
1131 #endif
1132 
1134 
1135  PRINT_LWDEBUG("LWLockAcquire", lock, mode);
1136 
1137 #ifdef LWLOCK_STATS
1138  /* Count lock acquisition attempts */
1139  if (mode == LW_EXCLUSIVE)
1140  lwstats->ex_acquire_count++;
1141  else
1142  lwstats->sh_acquire_count++;
1143 #endif /* LWLOCK_STATS */
1144 
1145  /*
1146  * We can't wait if we haven't got a PGPROC. This should only occur
1147  * during bootstrap or shared memory initialization. Put an Assert here
1148  * to catch unsafe coding practices.
1149  */
1150  Assert(!(proc == NULL && IsUnderPostmaster));
1151 
1152  /* Ensure we will have room to remember the lock */
1154  elog(ERROR, "too many LWLocks taken");
1155 
1156  /*
1157  * Lock out cancel/die interrupts until we exit the code section protected
1158  * by the LWLock. This ensures that interrupts will not interfere with
1159  * manipulations of data structures in shared memory.
1160  */
1161  HOLD_INTERRUPTS();
1162 
1163  /*
1164  * Loop here to try to acquire lock after each time we are signaled by
1165  * LWLockRelease.
1166  *
1167  * NOTE: it might seem better to have LWLockRelease actually grant us the
1168  * lock, rather than retrying and possibly having to go back to sleep. But
1169  * in practice that is no good because it means a process swap for every
1170  * lock acquisition when two or more processes are contending for the same
1171  * lock. Since LWLocks are normally used to protect not-very-long
1172  * sections of computation, a process needs to be able to acquire and
1173  * release the same lock many times during a single CPU time slice, even
1174  * in the presence of contention. The efficiency of being able to do that
1175  * outweighs the inefficiency of sometimes wasting a process dispatch
1176  * cycle because the lock is not free when a released waiter finally gets
1177  * to run. See pgsql-hackers archives for 29-Dec-01.
1178  */
1179  for (;;)
1180  {
1181  bool mustwait;
1182 
1183  /*
1184  * Try to grab the lock the first time, we're not in the waitqueue
1185  * yet/anymore.
1186  */
1187  mustwait = LWLockAttemptLock(lock, mode);
1188 
1189  if (!mustwait)
1190  {
1191  LOG_LWDEBUG("LWLockAcquire", lock, "immediately acquired lock");
1192  break; /* got the lock */
1193  }
1194 
1195  /*
1196  * Ok, at this point we couldn't grab the lock on the first try. We
1197  * cannot simply queue ourselves to the end of the list and wait to be
1198  * woken up because by now the lock could long have been released.
1199  * Instead add us to the queue and try to grab the lock again. If we
1200  * succeed we need to revert the queuing and be happy, otherwise we
1201  * recheck the lock. If we still couldn't grab it, we know that the
1202  * other locker will see our queue entries when releasing since they
1203  * existed before we checked for the lock.
1204  */
1205 
1206  /* add to the queue */
1207  LWLockQueueSelf(lock, mode);
1208 
1209  /* we're now guaranteed to be woken up if necessary */
1210  mustwait = LWLockAttemptLock(lock, mode);
1211 
1212  /* ok, grabbed the lock the second time round, need to undo queueing */
1213  if (!mustwait)
1214  {
1215  LOG_LWDEBUG("LWLockAcquire", lock, "acquired, undoing queue");
1216 
1217  LWLockDequeueSelf(lock);
1218  break;
1219  }
1220 
1221  /*
1222  * Wait until awakened.
1223  *
1224  * Since we share the process wait semaphore with the regular lock
1225  * manager and ProcWaitForSignal, and we may need to acquire an LWLock
1226  * while one of those is pending, it is possible that we get awakened
1227  * for a reason other than being signaled by LWLockRelease. If so,
1228  * loop back and wait again. Once we've gotten the LWLock,
1229  * re-increment the sema by the number of additional signals received,
1230  * so that the lock manager or signal manager will see the received
1231  * signal when it next waits.
1232  */
1233  LOG_LWDEBUG("LWLockAcquire", lock, "waiting");
1234 
1235 #ifdef LWLOCK_STATS
1236  lwstats->block_count++;
1237 #endif
1238 
1239  LWLockReportWaitStart(lock);
1240  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), mode);
1241 
1242  for (;;)
1243  {
1244  PGSemaphoreLock(proc->sem);
1245  if (!proc->lwWaiting)
1246  break;
1247  extraWaits++;
1248  }
1249 
1250  /* Retrying, allow LWLockRelease to release waiters again. */
1252 
1253 #ifdef LOCK_DEBUG
1254  {
1255  /* not waiting anymore */
1256  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1257 
1258  Assert(nwaiters < MAX_BACKENDS);
1259  }
1260 #endif
1261 
1262  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode);
1264 
1265  LOG_LWDEBUG("LWLockAcquire", lock, "awakened");
1266 
1267  /* Now loop back and try to acquire lock again. */
1268  result = false;
1269  }
1270 
1271  TRACE_POSTGRESQL_LWLOCK_ACQUIRE(T_NAME(lock), mode);
1272 
1273  /* Add lock to list of locks held by this backend */
1276 
1277  /*
1278  * Fix the process wait semaphore's count for any absorbed wakeups.
1279  */
1280  while (extraWaits-- > 0)
1281  PGSemaphoreUnlock(proc->sem);
1282 
1283  return result;
1284 }
#define T_NAME(lock)
Definition: lwlock.c:117
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:740
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
PGPROC * MyProc
Definition: proc.c:68
bool lwWaiting
Definition: proc.h:130
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:133
pg_atomic_uint32 state
Definition: lwlock.h:35
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:143
#define ERROR
Definition: elog.h:43
#define MAX_BACKENDS
Definition: postmaster.h:75
LWLockMode mode
Definition: lwlock.c:139
bool IsUnderPostmaster
Definition: globals.c:109
static void LWLockReportWaitEnd(void)
Definition: lwlock.c:705
unsigned int uint32
Definition: c.h:358
static void LWLockDequeueSelf(LWLock *lock)
Definition: lwlock.c:1027
#define AssertArg(condition)
Definition: c.h:734
static void LWLockReportWaitStart(LWLock *lock)
Definition: lwlock.c:696
static void LWLockQueueSelf(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:983
static int num_held_lwlocks
Definition: lwlock.c:142
#define Assert(condition)
Definition: c.h:732
LWLock * lock
Definition: lwlock.c:138
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:227
#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:226
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:372
PGSemaphore sem
Definition: proc.h:101
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:123
Definition: proc.h:95
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:228

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)

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

1350 {
1351  PGPROC *proc = MyProc;
1352  bool mustwait;
1353  int extraWaits = 0;
1354 #ifdef LWLOCK_STATS
1355  lwlock_stats *lwstats;
1356 
1357  lwstats = get_lwlock_stats_entry(lock);
1358 #endif
1359 
1361 
1362  PRINT_LWDEBUG("LWLockAcquireOrWait", lock, mode);
1363 
1364  /* Ensure we will have room to remember the lock */
1366  elog(ERROR, "too many LWLocks taken");
1367 
1368  /*
1369  * Lock out cancel/die interrupts until we exit the code section protected
1370  * by the LWLock. This ensures that interrupts will not interfere with
1371  * manipulations of data structures in shared memory.
1372  */
1373  HOLD_INTERRUPTS();
1374 
1375  /*
1376  * NB: We're using nearly the same twice-in-a-row lock acquisition
1377  * protocol as LWLockAcquire(). Check its comments for details.
1378  */
1379  mustwait = LWLockAttemptLock(lock, mode);
1380 
1381  if (mustwait)
1382  {
1384 
1385  mustwait = LWLockAttemptLock(lock, mode);
1386 
1387  if (mustwait)
1388  {
1389  /*
1390  * Wait until awakened. Like in LWLockAcquire, be prepared for
1391  * bogus wakeups, because we share the semaphore with
1392  * ProcWaitForSignal.
1393  */
1394  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "waiting");
1395 
1396 #ifdef LWLOCK_STATS
1397  lwstats->block_count++;
1398 #endif
1399 
1400  LWLockReportWaitStart(lock);
1401  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), mode);
1402 
1403  for (;;)
1404  {
1405  PGSemaphoreLock(proc->sem);
1406  if (!proc->lwWaiting)
1407  break;
1408  extraWaits++;
1409  }
1410 
1411 #ifdef LOCK_DEBUG
1412  {
1413  /* not waiting anymore */
1414  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1415 
1416  Assert(nwaiters < MAX_BACKENDS);
1417  }
1418 #endif
1419  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode);
1421 
1422  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "awakened");
1423  }
1424  else
1425  {
1426  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "acquired, undoing queue");
1427 
1428  /*
1429  * Got lock in the second attempt, undo queueing. We need to treat
1430  * this as having successfully acquired the lock, otherwise we'd
1431  * not necessarily wake up people we've prevented from acquiring
1432  * the lock.
1433  */
1434  LWLockDequeueSelf(lock);
1435  }
1436  }
1437 
1438  /*
1439  * Fix the process wait semaphore's count for any absorbed wakeups.
1440  */
1441  while (extraWaits-- > 0)
1442  PGSemaphoreUnlock(proc->sem);
1443 
1444  if (mustwait)
1445  {
1446  /* Failed to get lock, so release interrupt holdoff */
1448  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "failed");
1449  TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_FAIL(T_NAME(lock), mode);
1450  }
1451  else
1452  {
1453  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "succeeded");
1454  /* Add lock to list of locks held by this backend */
1457  TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT(T_NAME(lock), mode);
1458  }
1459 
1460  return !mustwait;
1461 }
#define T_NAME(lock)
Definition: lwlock.c:117
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:740
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
PGPROC * MyProc
Definition: proc.c:68
bool lwWaiting
Definition: proc.h:130
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:133
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:143
#define ERROR
Definition: elog.h:43
#define MAX_BACKENDS
Definition: postmaster.h:75
LWLockMode mode
Definition: lwlock.c:139
static void LWLockReportWaitEnd(void)
Definition: lwlock.c:705
unsigned int uint32
Definition: c.h:358
static void LWLockDequeueSelf(LWLock *lock)
Definition: lwlock.c:1027
static void LWLockReportWaitStart(LWLock *lock)
Definition: lwlock.c:696
static void LWLockQueueSelf(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:983
static int num_held_lwlocks
Definition: lwlock.c:142
#define Assert(condition)
Definition: c.h:732
LWLock * lock
Definition: lwlock.c:138
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:227
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:320
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define elog(elevel,...)
Definition: elog.h:226
PGSemaphore sem
Definition: proc.h:101
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:123
Definition: proc.h:95
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:228

◆ LWLockAttemptLock()

static bool LWLockAttemptLock ( LWLock lock,
LWLockMode  mode 
)
static

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

741 {
742  uint32 old_state;
743 
745 
746  /*
747  * Read once outside the loop, later iterations will get the newer value
748  * via compare & exchange.
749  */
750  old_state = pg_atomic_read_u32(&lock->state);
751 
752  /* loop until we've determined whether we could acquire the lock or not */
753  while (true)
754  {
755  uint32 desired_state;
756  bool lock_free;
757 
758  desired_state = old_state;
759 
760  if (mode == LW_EXCLUSIVE)
761  {
762  lock_free = (old_state & LW_LOCK_MASK) == 0;
763  if (lock_free)
764  desired_state += LW_VAL_EXCLUSIVE;
765  }
766  else
767  {
768  lock_free = (old_state & LW_VAL_EXCLUSIVE) == 0;
769  if (lock_free)
770  desired_state += LW_VAL_SHARED;
771  }
772 
773  /*
774  * Attempt to swap in the state we are expecting. If we didn't see
775  * lock to be free, that's just the old value. If we saw it as free,
776  * we'll attempt to mark it acquired. The reason that we always swap
777  * in the value is that this doubles as a memory barrier. We could try
778  * to be smarter and only swap in values if we saw the lock as free,
779  * but benchmark haven't shown it as beneficial so far.
780  *
781  * Retry if the value changed since we last looked at it.
782  */
784  &old_state, desired_state))
785  {
786  if (lock_free)
787  {
788  /* Great! Got the lock. */
789 #ifdef LOCK_DEBUG
790  if (mode == LW_EXCLUSIVE)
791  lock->owner = MyProc;
792 #endif
793  return false;
794  }
795  else
796  return true; /* somebody else has the lock */
797  }
798  }
799  pg_unreachable();
800 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
#define pg_unreachable()
Definition: c.h:193
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:35
#define LW_LOCK_MASK
Definition: lwlock.c:106
#define LW_VAL_SHARED
Definition: lwlock.c:104
unsigned int uint32
Definition: c.h:358
#define AssertArg(condition)
Definition: c.h:734
#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 1294 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().

1295 {
1296  bool mustwait;
1297 
1299 
1300  PRINT_LWDEBUG("LWLockConditionalAcquire", lock, mode);
1301 
1302  /* Ensure we will have room to remember the lock */
1304  elog(ERROR, "too many LWLocks taken");
1305 
1306  /*
1307  * Lock out cancel/die interrupts until we exit the code section protected
1308  * by the LWLock. This ensures that interrupts will not interfere with
1309  * manipulations of data structures in shared memory.
1310  */
1311  HOLD_INTERRUPTS();
1312 
1313  /* Check for the lock */
1314  mustwait = LWLockAttemptLock(lock, mode);
1315 
1316  if (mustwait)
1317  {
1318  /* Failed to get lock, so release interrupt holdoff */
1320 
1321  LOG_LWDEBUG("LWLockConditionalAcquire", lock, "failed");
1322  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL(T_NAME(lock), mode);
1323  }
1324  else
1325  {
1326  /* Add lock to list of locks held by this backend */
1329  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(T_NAME(lock), mode);
1330  }
1331  return !mustwait;
1332 }
#define T_NAME(lock)
Definition: lwlock.c:117
static PgChecksumMode mode
Definition: pg_checksums.c:61
static bool LWLockAttemptLock(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:740
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:133
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:143
#define ERROR
Definition: elog.h:43
LWLockMode mode
Definition: lwlock.c:139
#define AssertArg(condition)
Definition: c.h:734
static int num_held_lwlocks
Definition: lwlock.c:142
LWLock * lock
Definition: lwlock.c:138
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:227
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define elog(elevel,...)
Definition: elog.h:226
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:228

◆ LWLockConflictsWithVar()

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

Definition at line 1473 of file lwlock.c.

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

Referenced by LWLockWaitForVar().

1476 {
1477  bool mustwait;
1478  uint64 value;
1479 
1480  /*
1481  * Test first to see if it the slot is free right now.
1482  *
1483  * XXX: the caller uses a spinlock before this, so we don't need a memory
1484  * barrier here as far as the current usage is concerned. But that might
1485  * not be safe in general.
1486  */
1487  mustwait = (pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE) != 0;
1488 
1489  if (!mustwait)
1490  {
1491  *result = true;
1492  return false;
1493  }
1494 
1495  *result = false;
1496 
1497  /*
1498  * Read value using the lwlock's wait list lock, as we can't generally
1499  * rely on atomic 64 bit reads/stores. TODO: On platforms with a way to
1500  * do atomic 64 bit reads/writes the spinlock should be optimized away.
1501  */
1502  LWLockWaitListLock(lock);
1503  value = *valptr;
1504  LWLockWaitListUnlock(lock);
1505 
1506  if (value != oldval)
1507  {
1508  mustwait = false;
1509  *newval = value;
1510  }
1511  else
1512  {
1513  mustwait = true;
1514  }
1515 
1516  return mustwait;
1517 }
static struct @145 value
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:863
pg_atomic_uint32 state
Definition: lwlock.h:35
#define newval
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:811
#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 1027 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().

1028 {
1029  bool found = false;
1030  proclist_mutable_iter iter;
1031 
1032 #ifdef LWLOCK_STATS
1033  lwlock_stats *lwstats;
1034 
1035  lwstats = get_lwlock_stats_entry(lock);
1036 
1037  lwstats->dequeue_self_count++;
1038 #endif
1039 
1040  LWLockWaitListLock(lock);
1041 
1042  /*
1043  * Can't just remove ourselves from the list, but we need to iterate over
1044  * all entries as somebody else could have dequeued us.
1045  */
1046  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1047  {
1048  if (iter.cur == MyProc->pgprocno)
1049  {
1050  found = true;
1051  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1052  break;
1053  }
1054  }
1055 
1056  if (proclist_is_empty(&lock->waiters) &&
1057  (pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS) != 0)
1058  {
1060  }
1061 
1062  /* XXX: combine with fetch_and above? */
1063  LWLockWaitListUnlock(lock);
1064 
1065  /* clear waiting state again, nice for debugging */
1066  if (found)
1067  MyProc->lwWaiting = false;
1068  else
1069  {
1070  int extraWaits = 0;
1071 
1072  /*
1073  * Somebody else dequeued us and has or will wake us up. Deal with the
1074  * superfluous absorption of a wakeup.
1075  */
1076 
1077  /*
1078  * Reset RELEASE_OK flag if somebody woke us before we removed
1079  * ourselves - they'll have set it to false.
1080  */
1082 
1083  /*
1084  * Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
1085  * get reset at some inconvenient point later. Most of the time this
1086  * will immediately return.
1087  */
1088  for (;;)
1089  {
1091  if (!MyProc->lwWaiting)
1092  break;
1093  extraWaits++;
1094  }
1095 
1096  /*
1097  * Fix the process wait semaphore's count for any absorbed wakeups.
1098  */
1099  while (extraWaits-- > 0)
1101  }
1102 
1103 #ifdef LOCK_DEBUG
1104  {
1105  /* not waiting anymore */
1106  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1107 
1108  Assert(nwaiters < MAX_BACKENDS);
1109  }
1110 #endif
1111 }
static uint32 pg_atomic_fetch_sub_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:343
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:99
PGPROC * MyProc
Definition: proc.c:68
proclist_head waiters
Definition: lwlock.h:36
bool lwWaiting
Definition: proc.h:130
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:863
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
pg_atomic_uint32 state
Definition: lwlock.h:35
#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:358
#define Assert(condition)
Definition: c.h:732
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:811
int pgprocno
Definition: proc.h:110
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:372
PGSemaphore sem
Definition: proc.h:101
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:123
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 1860 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(), ProcessTwoPhaseBuffer(), RemoveGXact(), TransactionIdSetPageStatusInternal(), and TransferPredicateLocksToNewTarget().

1861 {
1862  int i;
1863 
1864  for (i = 0; i < num_held_lwlocks; i++)
1865  {
1866  if (held_lwlocks[i].lock == l && held_lwlocks[i].mode == mode)
1867  return true;
1868  }
1869  return false;
1870 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:143
static int num_held_lwlocks
Definition: lwlock.c:142
int i

◆ LWLockInitialize()

void LWLockInitialize ( LWLock lock,
int  tranche_id 
)

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

679 {
681 #ifdef LOCK_DEBUG
682  pg_atomic_init_u32(&lock->nwaiters, 0);
683 #endif
684  lock->tranche = tranche_id;
685  proclist_init(&lock->waiters);
686 }
proclist_head waiters
Definition: lwlock.h:36
pg_atomic_uint32 state
Definition: lwlock.h:35
uint16 tranche
Definition: lwlock.h:34
#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 583 of file lwlock.c.

References ShmemLock, SpinLockAcquire, and SpinLockRelease.

Referenced by apw_init_shmem(), and InitializeLWLocks().

584 {
585  int result;
586  int *LWLockCounter;
587 
588  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
590  result = (*LWLockCounter)++;
592 
593  return result;
594 }
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
slock_t * ShmemLock
Definition: shmem.c:84
LWLockPadded * MainLWLockArray
Definition: lwlock.c:125

◆ LWLockQueueSelf()

static void LWLockQueueSelf ( LWLock lock,
LWLockMode  mode 
)
static

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

984 {
985  /*
986  * If we don't have a PGPROC structure, there's no way to wait. This
987  * should never occur, since MyProc should only be null during shared
988  * memory initialization.
989  */
990  if (MyProc == NULL)
991  elog(PANIC, "cannot wait without a PGPROC structure");
992 
993  if (MyProc->lwWaiting)
994  elog(PANIC, "queueing for lock while waiting on another one");
995 
996  LWLockWaitListLock(lock);
997 
998  /* setting the flag is protected by the spinlock */
1000 
1001  MyProc->lwWaiting = true;
1002  MyProc->lwWaitMode = mode;
1003 
1004  /* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */
1005  if (mode == LW_WAIT_UNTIL_FREE)
1006  proclist_push_head(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1007  else
1008  proclist_push_tail(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1009 
1010  /* Can release the mutex now */
1011  LWLockWaitListUnlock(lock);
1012 
1013 #ifdef LOCK_DEBUG
1014  pg_atomic_fetch_add_u32(&lock->nwaiters, 1);
1015 #endif
1016 
1017 }
static PgChecksumMode mode
Definition: pg_checksums.c:61
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:99
PGPROC * MyProc
Definition: proc.c:68
proclist_head waiters
Definition: lwlock.h:36
bool lwWaiting
Definition: proc.h:130
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:863
uint8 lwWaitMode
Definition: proc.h:131
pg_atomic_uint32 state
Definition: lwlock.h:35
#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:811
int pgprocno
Definition: proc.h:110
#define elog(elevel,...)
Definition: elog.h:226
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 603 of file lwlock.c.

References Assert, i, LWLockTrancheArray, LWLockTranchesAllocated, and repalloc().

Referenced by apw_init_shmem(), CreateSharedProcArray(), InitBufferPool(), RegisterLWLockTranches(), ReplicationOriginShmemInit(), ReplicationSlotsShmemInit(), SimpleLruInit(), and XLOGShmemInit().

604 {
605  Assert(LWLockTrancheArray != NULL);
606 
607  if (tranche_id >= LWLockTranchesAllocated)
608  {
610  int j = LWLockTranchesAllocated;
611 
612  while (i <= tranche_id)
613  i *= 2;
614 
615  LWLockTrancheArray = (const char **)
616  repalloc(LWLockTrancheArray, i * sizeof(char *));
618  while (j < LWLockTranchesAllocated)
619  LWLockTrancheArray[j++] = NULL;
620  }
621 
622  LWLockTrancheArray[tranche_id] = tranche_name;
623 }
static int LWLockTranchesAllocated
Definition: lwlock.c:115
static const char ** LWLockTrancheArray
Definition: lwlock.c:114
#define Assert(condition)
Definition: c.h:732
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
int i

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1726 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(), analyze_rel(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_init_shmem(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AsyncShmemInit(), 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(), 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(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldestXmin(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), HaveVirtualXIDsDelayingChkpt(), InstallXLogFileSegment(), InvalidateBuffer(), 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(), OldSerXidAdd(), OldSerXidGetMinConflictCommitSeqNo(), OldSerXidSetActiveSerXmin(), OnConflict_CheckForSerializationFailure(), PageIsPredicateLocked(), perform_relmap_update(), pg_get_replication_slots(), pg_notification_queue_usage(), pg_show_replication_origin_status(), pg_stat_get_subscription(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgss_shmem_startup(), pgss_store(), PostPrepare_Locks(), PostPrepare_MultiXact(), PostPrepare_Twophase(), PreCommit_CheckForSerializationFailure(), PreCommit_Notify(), predicatelock_twophase_recover(), PredicateLockPageSplit(), PredicateLockTwoPhaseFinish(), PrefetchBuffer(), PrescanPreparedTransactions(), ProcArrayAdd(), ProcArrayApplyRecoveryInfo(), ProcArrayApplyXidAssignment(), ProcArrayEndTransaction(), ProcArrayGetReplicationSlotXmin(), ProcArrayGroupClearXid(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), ProcArrayRemove(), ProcArraySetReplicationSlotXmin(), process_syncing_tables_for_apply(), ProcKill(), ProcSleep(), ReadMultiXactCounts(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadRecord(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePostInvalidate(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), 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(), SetCommitTsLimit(), SetMultiXactIdLimit(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SIInsertDataEntries(), SimpleLruFlush(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), 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(), SyncRepInitConfig(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateBufferIO(), TransactionGroupUpdateXidStatus(), TransactionIdGetCommitTsData(), TransactionIdGetStatus(), TransactionIdIsActive(), TransactionIdIsInProgress(), TransactionIdLimitedForOldSnapshots(), TransactionIdSetPageStatus(), TransactionTreeSetCommitTsData(), TransferPredicateLocksToNewTarget(), TrimCLOG(), TrimMultiXact(), TruncateMultiXact(), TwoPhaseGetGXact(), txid_status(), UpdateMinRecoveryPoint(), 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(), and XLogNeedsFlush().

1727 {
1728  LWLockMode mode;
1729  uint32 oldstate;
1730  bool check_waiters;
1731  int i;
1732 
1733  /*
1734  * Remove lock from list of locks held. Usually, but not always, it will
1735  * be the latest-acquired lock; so search array backwards.
1736  */
1737  for (i = num_held_lwlocks; --i >= 0;)
1738  if (lock == held_lwlocks[i].lock)
1739  break;
1740 
1741  if (i < 0)
1742  elog(ERROR, "lock %s is not held", T_NAME(lock));
1743 
1744  mode = held_lwlocks[i].mode;
1745 
1746  num_held_lwlocks--;
1747  for (; i < num_held_lwlocks; i++)
1748  held_lwlocks[i] = held_lwlocks[i + 1];
1749 
1750  PRINT_LWDEBUG("LWLockRelease", lock, mode);
1751 
1752  /*
1753  * Release my hold on lock, after that it can immediately be acquired by
1754  * others, even if we still have to wakeup other waiters.
1755  */
1756  if (mode == LW_EXCLUSIVE)
1757  oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_EXCLUSIVE);
1758  else
1759  oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_SHARED);
1760 
1761  /* nobody else can have that kind of lock */
1762  Assert(!(oldstate & LW_VAL_EXCLUSIVE));
1763 
1764 
1765  /*
1766  * We're still waiting for backends to get scheduled, don't wake them up
1767  * again.
1768  */
1769  if ((oldstate & (LW_FLAG_HAS_WAITERS | LW_FLAG_RELEASE_OK)) ==
1771  (oldstate & LW_LOCK_MASK) == 0)
1772  check_waiters = true;
1773  else
1774  check_waiters = false;
1775 
1776  /*
1777  * As waking up waiters requires the spinlock to be acquired, only do so
1778  * if necessary.
1779  */
1780  if (check_waiters)
1781  {
1782  /* XXX: remove before commit? */
1783  LOG_LWDEBUG("LWLockRelease", lock, "releasing waiters");
1784  LWLockWakeup(lock);
1785  }
1786 
1787  TRACE_POSTGRESQL_LWLOCK_RELEASE(T_NAME(lock));
1788 
1789  /*
1790  * Now okay to allow cancel/die interrupts.
1791  */
1793 }
#define T_NAME(lock)
Definition: lwlock.c:117
static PgChecksumMode mode
Definition: pg_checksums.c:61
LWLockMode
Definition: lwlock.h:132
#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:143
#define ERROR
Definition: elog.h:43
LWLockMode mode
Definition: lwlock.c:139
static void LWLockWakeup(LWLock *lock)
Definition: lwlock.c:876
unsigned int uint32
Definition: c.h:358
static int num_held_lwlocks
Definition: lwlock.c:142
#define Assert(condition)
Definition: c.h:732
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:227
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:100
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:103
#define elog(elevel,...)
Definition: elog.h:226
int i
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:228

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

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

1826 {
1827  while (num_held_lwlocks > 0)
1828  {
1829  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1830 
1832  }
1833 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:143
static int num_held_lwlocks
Definition: lwlock.c:142
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116

◆ LWLockReleaseClearVar()

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

Definition at line 1799 of file lwlock.c.

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

Referenced by WALInsertLockRelease().

1800 {
1801  LWLockWaitListLock(lock);
1802 
1803  /*
1804  * Set the variable's value before releasing the lock, that prevents race
1805  * a race condition wherein a new locker acquires the lock, but hasn't yet
1806  * set the variables value.
1807  */
1808  *valptr = val;
1809  LWLockWaitListUnlock(lock);
1810 
1811  LWLockRelease(lock);
1812 }
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:863
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:811
long val
Definition: informix.c:684

◆ LWLockReportWaitEnd()

static void LWLockReportWaitEnd ( void  )
inlinestatic

Definition at line 705 of file lwlock.c.

References pgstat_report_wait_end().

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

706 {
708 }
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1342

◆ LWLockReportWaitStart()

static void LWLockReportWaitStart ( LWLock lock)
inlinestatic

Definition at line 696 of file lwlock.c.

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

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

697 {
699 }
uint16 tranche
Definition: lwlock.h:34
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1318
#define PG_WAIT_LWLOCK
Definition: pgstat.h:754

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 349 of file lwlock.c.

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

Referenced by CreateLWLocks(), and CreateSharedMemoryAndSemaphores().

350 {
351  Size size;
352  int i;
353  int numLocks = NUM_FIXED_LWLOCKS;
354 
355  numLocks += NumLWLocksByNamedTranches();
356 
357  /* Space for the LWLock array. */
358  size = mul_size(numLocks, sizeof(LWLockPadded));
359 
360  /* Space for dynamic allocation counter, plus room for alignment. */
361  size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
362 
363  /* space for named tranches. */
365 
366  /* space for name of each tranche. */
367  for (i = 0; i < NamedLWLockTrancheRequests; i++)
368  size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
369 
370  /* Disallow named LWLocks' requests after startup */
372 
373  return size;
374 }
static bool lock_named_request_allowed
Definition: lwlock.c:158
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:129
int NamedLWLockTrancheRequests
Definition: lwlock.c:154
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
size_t Size
Definition: c.h:466
static int NumLWLocksByNamedTranches(void)
Definition: lwlock.c:334
NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:152
int i
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:73

◆ LWLockUpdateVar()

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

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

1673 {
1674  proclist_head wakeup;
1675  proclist_mutable_iter iter;
1676 
1677  PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1678 
1679  proclist_init(&wakeup);
1680 
1681  LWLockWaitListLock(lock);
1682 
1684 
1685  /* Update the lock's value */
1686  *valptr = val;
1687 
1688  /*
1689  * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1690  * up. They are always in the front of the queue.
1691  */
1692  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1693  {
1694  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1695 
1696  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1697  break;
1698 
1699  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1700  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1701  }
1702 
1703  /* We are done updating shared state of the lock itself. */
1704  LWLockWaitListUnlock(lock);
1705 
1706  /*
1707  * Awaken any waiters I removed from the queue.
1708  */
1709  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1710  {
1711  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1712 
1713  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1714  /* check comment in LWLockWakeup() about this barrier */
1715  pg_write_barrier();
1716  waiter->lwWaiting = false;
1717  PGSemaphoreUnlock(waiter->sem);
1718  }
1719 }
#define GetPGProcByNumber(n)
Definition: proc.h:282
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
proclist_head waiters
Definition: lwlock.h:36
bool lwWaiting
Definition: proc.h:130
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:863
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
uint8 lwWaitMode
Definition: proc.h:131
pg_atomic_uint32 state
Definition: lwlock.h:35
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:187
#define Assert(condition)
Definition: c.h:732
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:227
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:191
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:811
#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:101
Definition: proc.h:95
long val
Definition: informix.c:684
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 1533 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().

1534 {
1535  PGPROC *proc = MyProc;
1536  int extraWaits = 0;
1537  bool result = false;
1538 #ifdef LWLOCK_STATS
1539  lwlock_stats *lwstats;
1540 
1541  lwstats = get_lwlock_stats_entry(lock);
1542 #endif
1543 
1544  PRINT_LWDEBUG("LWLockWaitForVar", lock, LW_WAIT_UNTIL_FREE);
1545 
1546  /*
1547  * Lock out cancel/die interrupts while we sleep on the lock. There is no
1548  * cleanup mechanism to remove us from the wait queue if we got
1549  * interrupted.
1550  */
1551  HOLD_INTERRUPTS();
1552 
1553  /*
1554  * Loop here to check the lock's status after each time we are signaled.
1555  */
1556  for (;;)
1557  {
1558  bool mustwait;
1559 
1560  mustwait = LWLockConflictsWithVar(lock, valptr, oldval, newval,
1561  &result);
1562 
1563  if (!mustwait)
1564  break; /* the lock was free or value didn't match */
1565 
1566  /*
1567  * Add myself to wait queue. Note that this is racy, somebody else
1568  * could wakeup before we're finished queuing. NB: We're using nearly
1569  * the same twice-in-a-row lock acquisition protocol as
1570  * LWLockAcquire(). Check its comments for details. The only
1571  * difference is that we also have to check the variable's values when
1572  * checking the state of the lock.
1573  */
1575 
1576  /*
1577  * Set RELEASE_OK flag, to make sure we get woken up as soon as the
1578  * lock is released.
1579  */
1581 
1582  /*
1583  * We're now guaranteed to be woken up if necessary. Recheck the lock
1584  * and variables state.
1585  */
1586  mustwait = LWLockConflictsWithVar(lock, valptr, oldval, newval,
1587  &result);
1588 
1589  /* Ok, no conflict after we queued ourselves. Undo queueing. */
1590  if (!mustwait)
1591  {
1592  LOG_LWDEBUG("LWLockWaitForVar", lock, "free, undoing queue");
1593 
1594  LWLockDequeueSelf(lock);
1595  break;
1596  }
1597 
1598  /*
1599  * Wait until awakened.
1600  *
1601  * Since we share the process wait semaphore with the regular lock
1602  * manager and ProcWaitForSignal, and we may need to acquire an LWLock
1603  * while one of those is pending, it is possible that we get awakened
1604  * for a reason other than being signaled by LWLockRelease. If so,
1605  * loop back and wait again. Once we've gotten the LWLock,
1606  * re-increment the sema by the number of additional signals received,
1607  * so that the lock manager or signal manager will see the received
1608  * signal when it next waits.
1609  */
1610  LOG_LWDEBUG("LWLockWaitForVar", lock, "waiting");
1611 
1612 #ifdef LWLOCK_STATS
1613  lwstats->block_count++;
1614 #endif
1615 
1616  LWLockReportWaitStart(lock);
1617  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), LW_EXCLUSIVE);
1618 
1619  for (;;)
1620  {
1621  PGSemaphoreLock(proc->sem);
1622  if (!proc->lwWaiting)
1623  break;
1624  extraWaits++;
1625  }
1626 
1627 #ifdef LOCK_DEBUG
1628  {
1629  /* not waiting anymore */
1630  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1631 
1632  Assert(nwaiters < MAX_BACKENDS);
1633  }
1634 #endif
1635 
1636  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), LW_EXCLUSIVE);
1638 
1639  LOG_LWDEBUG("LWLockWaitForVar", lock, "awakened");
1640 
1641  /* Now loop back and check the status of the lock again. */
1642  }
1643 
1644  TRACE_POSTGRESQL_LWLOCK_ACQUIRE(T_NAME(lock), LW_EXCLUSIVE);
1645 
1646  /*
1647  * Fix the process wait semaphore's count for any absorbed wakeups.
1648  */
1649  while (extraWaits-- > 0)
1650  PGSemaphoreUnlock(proc->sem);
1651 
1652  /*
1653  * Now okay to allow cancel/die interrupts.
1654  */
1656 
1657  return result;
1658 }
#define T_NAME(lock)
Definition: lwlock.c:117
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:130
pg_atomic_uint32 state
Definition: lwlock.h:35
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
#define MAX_BACKENDS
Definition: postmaster.h:75
static void LWLockReportWaitEnd(void)
Definition: lwlock.c:705
unsigned int uint32
Definition: c.h:358
static void LWLockDequeueSelf(LWLock *lock)
Definition: lwlock.c:1027
static void LWLockReportWaitStart(LWLock *lock)
Definition: lwlock.c:696
static void LWLockQueueSelf(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:983
#define Assert(condition)
Definition: c.h:732
#define newval
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:227
#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:1473
#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:101
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:123
Definition: proc.h:95
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:228

◆ LWLockWaitListLock()

static void LWLockWaitListLock ( LWLock lock)
static

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

812 {
813  uint32 old_state;
814 #ifdef LWLOCK_STATS
815  lwlock_stats *lwstats;
816  uint32 delays = 0;
817 
818  lwstats = get_lwlock_stats_entry(lock);
819 #endif
820 
821  while (true)
822  {
823  /* always try once to acquire lock directly */
824  old_state = pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_LOCKED);
825  if (!(old_state & LW_FLAG_LOCKED))
826  break; /* got lock */
827 
828  /* and then spin without atomic operations until lock is released */
829  {
830  SpinDelayStatus delayStatus;
831 
832  init_local_spin_delay(&delayStatus);
833 
834  while (old_state & LW_FLAG_LOCKED)
835  {
836  perform_spin_delay(&delayStatus);
837  old_state = pg_atomic_read_u32(&lock->state);
838  }
839 #ifdef LWLOCK_STATS
840  delays += delayStatus.delays;
841 #endif
842  finish_spin_delay(&delayStatus);
843  }
844 
845  /*
846  * Retry. The lock might obviously already be re-acquired by the time
847  * we're attempting to get it again.
848  */
849  }
850 
851 #ifdef LWLOCK_STATS
852  lwstats->spin_delay_count += delays;
853 #endif
854 }
#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:35
void finish_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:175
unsigned int uint32
Definition: c.h:358
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:125
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 863 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().

864 {
866 
867  old_state = pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_LOCKED);
868 
869  Assert(old_state & LW_FLAG_LOCKED);
870 }
#define LW_FLAG_LOCKED
Definition: lwlock.c:101
pg_atomic_uint32 state
Definition: lwlock.h:35
static uint32 pg_atomic_fetch_and_u32(volatile pg_atomic_uint32 *ptr, uint32 and_)
Definition: atomics.h:358
unsigned int uint32
Definition: c.h:358
#define Assert(condition)
Definition: c.h:732
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:123

◆ LWLockWakeup()

static void LWLockWakeup ( LWLock lock)
static

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

877 {
878  bool new_release_ok;
879  bool wokeup_somebody = false;
880  proclist_head wakeup;
882 
883  proclist_init(&wakeup);
884 
885  new_release_ok = true;
886 
887  /* lock wait list while collecting backends to wake up */
888  LWLockWaitListLock(lock);
889 
890  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
891  {
892  PGPROC *waiter = GetPGProcByNumber(iter.cur);
893 
894  if (wokeup_somebody && waiter->lwWaitMode == LW_EXCLUSIVE)
895  continue;
896 
897  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
898  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
899 
900  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
901  {
902  /*
903  * Prevent additional wakeups until retryer gets to run. Backends
904  * that are just waiting for the lock to become free don't retry
905  * automatically.
906  */
907  new_release_ok = false;
908 
909  /*
910  * Don't wakeup (further) exclusive locks.
911  */
912  wokeup_somebody = true;
913  }
914 
915  /*
916  * Once we've woken up an exclusive lock, there's no point in waking
917  * up anybody else.
918  */
919  if (waiter->lwWaitMode == LW_EXCLUSIVE)
920  break;
921  }
922 
924 
925  /* unset required flags, and release lock, in one fell swoop */
926  {
927  uint32 old_state;
928  uint32 desired_state;
929 
930  old_state = pg_atomic_read_u32(&lock->state);
931  while (true)
932  {
933  desired_state = old_state;
934 
935  /* compute desired flags */
936 
937  if (new_release_ok)
938  desired_state |= LW_FLAG_RELEASE_OK;
939  else
940  desired_state &= ~LW_FLAG_RELEASE_OK;
941 
942  if (proclist_is_empty(&wakeup))
943  desired_state &= ~LW_FLAG_HAS_WAITERS;
944 
945  desired_state &= ~LW_FLAG_LOCKED; /* release lock */
946 
947  if (pg_atomic_compare_exchange_u32(&lock->state, &old_state,
948  desired_state))
949  break;
950  }
951  }
952 
953  /* Awaken any waiters I removed from the queue. */
954  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
955  {
956  PGPROC *waiter = GetPGProcByNumber(iter.cur);
957 
958  LOG_LWDEBUG("LWLockRelease", lock, "release waiter");
959  proclist_delete(&wakeup, iter.cur, lwWaitLink);
960 
961  /*
962  * Guarantee that lwWaiting being unset only becomes visible once the
963  * unlink from the link has completed. Otherwise the target backend
964  * could be woken up for other reason and enqueue for a new lock - if
965  * that happens before the list unlink happens, the list would end up
966  * being corrupted.
967  *
968  * The barrier pairs with the LWLockWaitListLock() when enqueuing for
969  * another lock.
970  */
972  waiter->lwWaiting = false;
973  PGSemaphoreUnlock(waiter->sem);
974  }
975 }
#define GetPGProcByNumber(n)
Definition: proc.h:282
#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:36
bool lwWaiting
Definition: proc.h:130
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
uint8 lwWaitMode
Definition: proc.h:131
pg_atomic_uint32 state
Definition: lwlock.h:35
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:187
unsigned int uint32
Definition: c.h:358
#define Assert(condition)
Definition: c.h:732
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:811
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
#define pg_write_barrier()
Definition: atomics.h:159
PGSemaphore sem
Definition: proc.h:101
Definition: proc.h:95
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:228

◆ NumLWLocksByNamedTranches()

static int NumLWLocksByNamedTranches ( void  )
static

Definition at line 334 of file lwlock.c.

References i, and NamedLWLockTrancheRequests.

Referenced by InitializeLWLocks(), and LWLockShmemSize().

335 {
336  int numLocks = 0;
337  int i;
338 
339  for (i = 0; i < NamedLWLockTrancheRequests; i++)
340  numLocks += NamedLWLockTrancheRequestArray[i].num_lwlocks;
341 
342  return numLocks;
343 }
int NamedLWLockTrancheRequests
Definition: lwlock.c:154
NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:152
int i

◆ RegisterLWLockTranches()

static void RegisterLWLockTranches ( void  )
static

Definition at line 491 of file lwlock.c.

References Assert, i, LWLockRegisterTranche(), LWLockTrancheArray, LWLockTranchesAllocated, LWTRANCHE_BUFFER_MAPPING, LWTRANCHE_FIRST_USER_DEFINED, LWTRANCHE_LOCK_MANAGER, LWTRANCHE_PARALLEL_APPEND, LWTRANCHE_PARALLEL_HASH_JOIN, LWTRANCHE_PARALLEL_QUERY_DSA, LWTRANCHE_PREDICATE_LOCK_MANAGER, LWTRANCHE_SESSION_DSA, LWTRANCHE_SESSION_RECORD_TABLE, LWTRANCHE_SESSION_TYPMOD_TABLE, LWTRANCHE_SHARED_TUPLESTORE, LWTRANCHE_SXACT, LWTRANCHE_TBM, MainLWLockNames, MemoryContextAllocZero(), NamedLWLockTrancheRequests, and TopMemoryContext.

Referenced by CreateLWLocks().

492 {
493  int i;
494 
495  if (LWLockTrancheArray == NULL)
496  {
498  LWLockTrancheArray = (const char **)
500  LWLockTranchesAllocated * sizeof(char *));
502  }
503 
504  for (i = 0; i < NUM_INDIVIDUAL_LWLOCKS; ++i)
506 
510  "predicate_lock_manager");
512  "parallel_query_dsa");
514  "session_dsa");
516  "session_record_table");
518  "session_typmod_table");
520  "shared_tuplestore");
524  LWLockRegisterTranche(LWTRANCHE_SXACT, "serializable_xact");
525 
526  /* Register named tranches. */
527  for (i = 0; i < NamedLWLockTrancheRequests; i++)
529  NamedLWLockTrancheArray[i].trancheName);
530 }
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:156
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:603
static int LWLockTranchesAllocated
Definition: lwlock.c:115
int NamedLWLockTrancheRequests
Definition: lwlock.c:154
static const char ** LWLockTrancheArray
Definition: lwlock.c:114
MemoryContext TopMemoryContext
Definition: mcxt.c:44
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:839
#define Assert(condition)
Definition: c.h:732
int i
const char *const MainLWLockNames[]

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 638 of file lwlock.c.

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

Referenced by _PG_init().

639 {
640  NamedLWLockTrancheRequest *request;
641 
643  return; /* too late */
644 
645  if (NamedLWLockTrancheRequestArray == NULL)
646  {
651  * sizeof(NamedLWLockTrancheRequest));
652  }
653 
655  {
657 
658  while (i <= NamedLWLockTrancheRequests)
659  i *= 2;
660 
663  i * sizeof(NamedLWLockTrancheRequest));
665  }
666 
668  Assert(strlen(tranche_name) + 1 < NAMEDATALEN);
669  StrNCpy(request->tranche_name, tranche_name, NAMEDATALEN);
670  request->num_lwlocks = num_lwlocks;
672 }
static bool lock_named_request_allowed
Definition: lwlock.c:158
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:148
#define NAMEDATALEN
int NamedLWLockTrancheRequests
Definition: lwlock.c:154
bool IsUnderPostmaster
Definition: globals.c:109
MemoryContext TopMemoryContext
Definition: mcxt.c:44
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:153
#define Assert(condition)
Definition: c.h:732
#define StrNCpy(dst, src, len)
Definition: c.h:928
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:152
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
int i

Variable Documentation

◆ held_lwlocks

LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
static

Definition at line 143 of file lwlock.c.

◆ lock_named_request_allowed

bool lock_named_request_allowed = true
static

Definition at line 158 of file lwlock.c.

Referenced by LWLockShmemSize(), and RequestNamedLWLockTranche().

◆ LWLockTrancheArray

const char** LWLockTrancheArray = NULL
static

Definition at line 114 of file lwlock.c.

Referenced by GetLWLockIdentifier(), LWLockRegisterTranche(), and RegisterLWLockTranches().

◆ LWLockTranchesAllocated

int LWLockTranchesAllocated = 0
static

Definition at line 115 of file lwlock.c.

Referenced by GetLWLockIdentifier(), LWLockRegisterTranche(), and RegisterLWLockTranches().

◆ MainLWLockArray

LWLockPadded* MainLWLockArray = NULL

Definition at line 125 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheArray

NamedLWLockTranche* NamedLWLockTrancheArray = NULL

Definition at line 156 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheRequestArray

NamedLWLockTrancheRequest* NamedLWLockTrancheRequestArray = NULL

Definition at line 152 of file lwlock.c.

◆ NamedLWLockTrancheRequests

◆ NamedLWLockTrancheRequestsAllocated

int NamedLWLockTrancheRequestsAllocated = 0
static

Definition at line 153 of file lwlock.c.

Referenced by RequestNamedLWLockTranche().

◆ num_held_lwlocks

◆ ShmemLock