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

◆ 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 StaticAssertExpr.

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 LWLOCK_MINIMAL_SIZE
Definition: lwlock.h:74
#define MAX_BACKENDS
Definition: postmaster.h:75
bool IsUnderPostmaster
Definition: globals.c:101
unsigned int uint32
Definition: c.h:296
static void InitializeLWLocks(void)
Definition: lwlock.c:426
#define StaticAssertExpr(condition, errmessage)
Definition: c.h:755
size_t Size
Definition: c.h:404
#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 710 of file lwlock.c.

References Assert, LWLockTrancheArray, LWLockTranchesAllocated, and PG_WAIT_LWLOCK.

Referenced by pgstat_get_wait_event().

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

◆ GetNamedLWLockTranche()

LWLockPadded* GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 548 of file lwlock.c.

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

Referenced by pgss_shmem_startup().

549 {
550  int lock_pos;
551  int i;
552 
553  /*
554  * Obtain the position of base address of LWLock belonging to requested
555  * tranche_name in MainLWLockArray. LWLocks for named tranches are placed
556  * in MainLWLockArray after fixed locks.
557  */
558  lock_pos = NUM_FIXED_LWLOCKS;
559  for (i = 0; i < NamedLWLockTrancheRequests; i++)
560  {
561  if (strcmp(NamedLWLockTrancheRequestArray[i].tranche_name,
562  tranche_name) == 0)
563  return &MainLWLockArray[lock_pos];
564 
566  }
567 
568  if (i >= NamedLWLockTrancheRequests)
569  elog(ERROR, "requested tranche is not registered");
570 
571  /* just to keep compiler quiet */
572  return NULL;
573 }
#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
int i
#define elog
Definition: elog.h:219
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:579
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:674
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 532 of file lwlock.c.

Referenced by InitProcess().

533 {
534 #ifdef LWLOCK_STATS
535  init_lwlock_stats();
536 #endif
537 }

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1118 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(), AbsorbFsyncRequests(), ActivateCommitTs(), 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(), 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(), ExpireAllKnownAssignedTransactionIds(), ExpireOldKnownAssignedTransactionIds(), ExpireTreeKnownAssignedTransactionIds(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), ForceTransactionIdLimitUpdate(), ForwardFsyncRequest(), 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_backend_random(), 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(), ProcessTwoPhaseBuffer(), ProcKill(), ProcSleep(), ReadBuffer_common(), ReadMultiXactCounts(), ReadNewTransactionId(), ReadNextMultiXactId(), ReadRecord(), RecordKnownAssignedTransactionIds(), 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(), 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(), xact_redo_abort(), xact_redo_commit(), XidCacheRemoveRunningXids(), xlog_redo(), and XLogBackgroundFlush().

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

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)

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

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

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

◆ LWLockConditionalAcquire()

bool LWLockConditionalAcquire ( LWLock lock,
LWLockMode  mode 
)

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

1291 {
1292  bool mustwait;
1293 
1294  AssertArg(mode == LW_SHARED || mode == LW_EXCLUSIVE);
1295 
1296  PRINT_LWDEBUG("LWLockConditionalAcquire", lock, mode);
1297 
1298  /* Ensure we will have room to remember the lock */
1300  elog(ERROR, "too many LWLocks taken");
1301 
1302  /*
1303  * Lock out cancel/die interrupts until we exit the code section protected
1304  * by the LWLock. This ensures that interrupts will not interfere with
1305  * manipulations of data structures in shared memory.
1306  */
1307  HOLD_INTERRUPTS();
1308 
1309  /* Check for the lock */
1310  mustwait = LWLockAttemptLock(lock, mode);
1311 
1312  if (mustwait)
1313  {
1314  /* Failed to get lock, so release interrupt holdoff */
1316 
1317  LOG_LWDEBUG("LWLockConditionalAcquire", lock, "failed");
1318  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL(T_NAME(lock), mode);
1319  }
1320  else
1321  {
1322  /* Add lock to list of locks held by this backend */
1325  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(T_NAME(lock), mode);
1326  }
1327  return !mustwait;
1328 }
#define T_NAME(lock)
Definition: lwlock.c:117
static bool LWLockAttemptLock(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:736
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:133
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
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:672
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:115
#define elog
Definition: elog.h:219
#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 1469 of file lwlock.c.

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

Referenced by LWLockWaitForVar().

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

◆ LWLockDequeueSelf()

static void LWLockDequeueSelf ( LWLock lock)
static

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

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

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

bool LWLockHeldByMeInMode ( LWLock l,
LWLockMode  mode 
)

Definition at line 1856 of file lwlock.c.

References i, and num_held_lwlocks.

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

1857 {
1858  int i;
1859 
1860  for (i = 0; i < num_held_lwlocks; i++)
1861  {
1862  if (held_lwlocks[i].lock == l && held_lwlocks[i].mode == mode)
1863  return true;
1864  }
1865  return false;
1866 }
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 674 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(), InitBufferPool(), InitializeLWLocks(), InitProcGlobal(), ReplicationOriginShmemInit(), ReplicationSlotsShmemInit(), SimpleLruInit(), tbm_prepare_shared_iterate(), and XLOGShmemInit().

675 {
677 #ifdef LOCK_DEBUG
678  pg_atomic_init_u32(&lock->nwaiters, 0);
679 #endif
680  lock->tranche = tranche_id;
681  proclist_init(&lock->waiters);
682 }
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:234

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( void  )

Definition at line 579 of file lwlock.c.

References ShmemLock, SpinLockAcquire, and SpinLockRelease.

Referenced by apw_init_shmem(), and InitializeLWLocks().

580 {
581  int result;
582  int *LWLockCounter;
583 
584  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
586  result = (*LWLockCounter)++;
588 
589  return result;
590 }
#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 979 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().

980 {
981  /*
982  * If we don't have a PGPROC structure, there's no way to wait. This
983  * should never occur, since MyProc should only be null during shared
984  * memory initialization.
985  */
986  if (MyProc == NULL)
987  elog(PANIC, "cannot wait without a PGPROC structure");
988 
989  if (MyProc->lwWaiting)
990  elog(PANIC, "queueing for lock while waiting on another one");
991 
992  LWLockWaitListLock(lock);
993 
994  /* setting the flag is protected by the spinlock */
996 
997  MyProc->lwWaiting = true;
998  MyProc->lwWaitMode = mode;
999 
1000  /* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */
1001  if (mode == LW_WAIT_UNTIL_FREE)
1002  proclist_push_head(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1003  else
1004  proclist_push_tail(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1005 
1006  /* Can release the mutex now */
1007  LWLockWaitListUnlock(lock);
1008 
1009 #ifdef LOCK_DEBUG
1010  pg_atomic_fetch_add_u32(&lock->nwaiters, 1);
1011 #endif
1012 
1013 }
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:99
PGPROC * MyProc
Definition: proc.c:67
proclist_head waiters
Definition: lwlock.h:36
bool lwWaiting
Definition: proc.h:127
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:859
uint8 lwWaitMode
Definition: proc.h:128
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:178
static uint32 pg_atomic_fetch_add_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:339
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:180
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:807
int pgprocno
Definition: proc.h:110
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:383
#define elog
Definition: elog.h:219

◆ LWLockRegisterTranche()

void LWLockRegisterTranche ( int  tranche_id,
const char *  tranche_name 
)

Definition at line 599 of file lwlock.c.

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

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

600 {
601  Assert(LWLockTrancheArray != NULL);
602 
603  if (tranche_id >= LWLockTranchesAllocated)
604  {
606  int j = LWLockTranchesAllocated;
607 
608  while (i <= tranche_id)
609  i *= 2;
610 
611  LWLockTrancheArray = (const char **)
612  repalloc(LWLockTrancheArray, i * sizeof(char *));
614  while (j < LWLockTranchesAllocated)
615  LWLockTrancheArray[j++] = NULL;
616  }
617 
618  LWLockTrancheArray[tranche_id] = tranche_name;
619 }
static int LWLockTranchesAllocated
Definition: lwlock.c:115
static const char ** LWLockTrancheArray
Definition: lwlock.c:114
#define Assert(condition)
Definition: c.h:670
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:962
int i

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1722 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(), AbsorbFsyncRequests(), ActivateCommitTs(), 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(), 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(), ExpireAllKnownAssignedTransactionIds(), ExpireOldKnownAssignedTransactionIds(), ExpireTreeKnownAssignedTransactionIds(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), find_multixact_start(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), ForceTransactionIdLimitUpdate(), ForwardFsyncRequest(), 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_backend_random(), 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(), ProcessTwoPhaseBuffer(), ProcKill(), ProcSleep(), ReadMultiXactCounts(), ReadNewTransactionId(), ReadNextMultiXactId(), ReadRecord(), RecordKnownAssignedTransactionIds(), 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(), 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(), xact_redo_abort(), xact_redo_commit(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), and XLogNeedsFlush().

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

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

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

1822 {
1823  while (num_held_lwlocks > 0)
1824  {
1825  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1826 
1828  }
1829 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1722
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:115

◆ LWLockReleaseClearVar()

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

Definition at line 1795 of file lwlock.c.

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

Referenced by WALInsertLockRelease().

1796 {
1797  LWLockWaitListLock(lock);
1798 
1799  /*
1800  * Set the variable's value before releasing the lock, that prevents race
1801  * a race condition wherein a new locker acquires the lock, but hasn't yet
1802  * set the variables value.
1803  */
1804  *valptr = val;
1805  LWLockWaitListUnlock(lock);
1806 
1807  LWLockRelease(lock);
1808 }
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:859
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1722
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:807
long val
Definition: informix.c:689

◆ LWLockReportWaitEnd()

static void LWLockReportWaitEnd ( void  )
inlinestatic

Definition at line 701 of file lwlock.c.

References pgstat_report_wait_end().

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

702 {
704 }
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244

◆ LWLockReportWaitStart()

static void LWLockReportWaitStart ( LWLock lock)
inlinestatic

Definition at line 692 of file lwlock.c.

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

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

693 {
695 }
uint16 tranche
Definition: lwlock.h:34
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
#define PG_WAIT_LWLOCK
Definition: pgstat.h:737

◆ 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:404
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 1668 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().

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

◆ LWLockWaitForVar()

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

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

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

◆ LWLockWaitListLock()

static void LWLockWaitListLock ( LWLock lock)
static

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

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

◆ LWLockWaitListUnlock()

static void LWLockWaitListUnlock ( LWLock lock)
static

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

860 {
862 
863  old_state = pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_LOCKED);
864 
865  Assert(old_state & LW_FLAG_LOCKED);
866 }
#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:369
unsigned int uint32
Definition: c.h:296
#define Assert(condition)
Definition: c.h:670
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:122

◆ LWLockWakeup()

static void LWLockWakeup ( LWLock lock)
static

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

873 {
874  bool new_release_ok;
875  bool wokeup_somebody = false;
876  proclist_head wakeup;
878 
879  proclist_init(&wakeup);
880 
881  new_release_ok = true;
882 
883  /* lock wait list while collecting backends to wake up */
884  LWLockWaitListLock(lock);
885 
886  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
887  {
888  PGPROC *waiter = GetPGProcByNumber(iter.cur);
889 
890  if (wokeup_somebody && waiter->lwWaitMode == LW_EXCLUSIVE)
891  continue;
892 
893  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
894  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
895 
896  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
897  {
898  /*
899  * Prevent additional wakeups until retryer gets to run. Backends
900  * that are just waiting for the lock to become free don't retry
901  * automatically.
902  */
903  new_release_ok = false;
904 
905  /*
906  * Don't wakeup (further) exclusive locks.
907  */
908  wokeup_somebody = true;
909  }
910 
911  /*
912  * Once we've woken up an exclusive lock, there's no point in waking
913  * up anybody else.
914  */
915  if (waiter->lwWaitMode == LW_EXCLUSIVE)
916  break;
917  }
918 
920 
921  /* unset required flags, and release lock, in one fell swoop */
922  {
923  uint32 old_state;
924  uint32 desired_state;
925 
926  old_state = pg_atomic_read_u32(&lock->state);
927  while (true)
928  {
929  desired_state = old_state;
930 
931  /* compute desired flags */
932 
933  if (new_release_ok)
934  desired_state |= LW_FLAG_RELEASE_OK;
935  else
936  desired_state &= ~LW_FLAG_RELEASE_OK;
937 
938  if (proclist_is_empty(&wakeup))
939  desired_state &= ~LW_FLAG_HAS_WAITERS;
940 
941  desired_state &= ~LW_FLAG_LOCKED; /* release lock */
942 
943  if (pg_atomic_compare_exchange_u32(&lock->state, &old_state,
944  desired_state))
945  break;
946  }
947  }
948 
949  /* Awaken any waiters I removed from the queue. */
950  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
951  {
952  PGPROC *waiter = GetPGProcByNumber(iter.cur);
953 
954  LOG_LWDEBUG("LWLockRelease", lock, "release waiter");
955  proclist_delete(&wakeup, iter.cur, lwWaitLink);
956 
957  /*
958  * Guarantee that lwWaiting being unset only becomes visible once the
959  * unlink from the link has completed. Otherwise the target backend
960  * could be woken up for other reason and enqueue for a new lock - if
961  * that happens before the list unlink happens, the list would end up
962  * being corrupted.
963  *
964  * The barrier pairs with the LWLockWaitListLock() when enqueuing for
965  * another lock.
966  */
968  waiter->lwWaiting = false;
969  PGSemaphoreUnlock(waiter->sem);
970  }
971 }
#define GetPGProcByNumber(n)
Definition: proc.h:277
#define LW_FLAG_LOCKED
Definition: lwlock.c:101
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:323
#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:322
proclist_head waiters
Definition: lwlock.h:36
bool lwWaiting
Definition: proc.h:127
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:195
uint8 lwWaitMode
Definition: proc.h:128
pg_atomic_uint32 state
Definition: lwlock.h:35
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:176
unsigned int uint32
Definition: c.h:296
#define Assert(condition)
Definition: c.h:670
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:180
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:807
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
#define pg_write_barrier()
Definition: atomics.h:162
PGSemaphore sem
Definition: proc.h:101
Definition: proc.h:95
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:252
#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_QUERY_DSA, LWTRANCHE_PREDICATE_LOCK_MANAGER, LWTRANCHE_SESSION_DSA, LWTRANCHE_SESSION_RECORD_TABLE, LWTRANCHE_SESSION_TYPMOD_TABLE, 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");
521 
522  /* Register named tranches. */
523  for (i = 0; i < NamedLWLockTrancheRequests; i++)
525  NamedLWLockTrancheArray[i].trancheName);
526 }
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:156
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:599
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:43
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:741
#define Assert(condition)
Definition: c.h:670
char * MainLWLockNames[]
int i

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

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

635 {
636  NamedLWLockTrancheRequest *request;
637 
639  return; /* too late */
640 
641  if (NamedLWLockTrancheRequestArray == NULL)
642  {
647  * sizeof(NamedLWLockTrancheRequest));
648  }
649 
651  {
653 
654  while (i <= NamedLWLockTrancheRequests)
655  i *= 2;
656 
659  i * sizeof(NamedLWLockTrancheRequest));
661  }
662 
664  Assert(strlen(tranche_name) + 1 < NAMEDATALEN);
665  StrNCpy(request->tranche_name, tranche_name, NAMEDATALEN);
666  request->num_lwlocks = num_lwlocks;
668 }
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:101
MemoryContext TopMemoryContext
Definition: mcxt.c:43
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:153
#define Assert(condition)
Definition: c.h:670
#define StrNCpy(dst, src, len)
Definition: c.h:826
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:962
NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:152
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:706
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