PostgreSQL Source Code  git master
lwlock.h File Reference
#include "storage/proclist_types.h"
#include "storage/s_lock.h"
#include "port/atomics.h"
#include "storage/lwlocknames.h"
Include dependency graph for lwlock.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  LWLock
 
union  LWLockPadded
 
union  LWLockMinimallyPadded
 
struct  NamedLWLockTranche
 

Macros

#define LWLOCK_PADDED_SIZE   PG_CACHE_LINE_SIZE
 
#define LWLOCK_MINIMAL_SIZE   (sizeof(LWLock) <= 32 ? 32 : 64)
 
#define NUM_BUFFER_PARTITIONS   128
 
#define LOG2_NUM_LOCK_PARTITIONS   4
 
#define NUM_LOCK_PARTITIONS   (1 << LOG2_NUM_LOCK_PARTITIONS)
 
#define LOG2_NUM_PREDICATELOCK_PARTITIONS   4
 
#define NUM_PREDICATELOCK_PARTITIONS   (1 << LOG2_NUM_PREDICATELOCK_PARTITIONS)
 
#define BUFFER_MAPPING_LWLOCK_OFFSET   NUM_INDIVIDUAL_LWLOCKS
 
#define LOCK_MANAGER_LWLOCK_OFFSET   (BUFFER_MAPPING_LWLOCK_OFFSET + NUM_BUFFER_PARTITIONS)
 
#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET   (LOCK_MANAGER_LWLOCK_OFFSET + NUM_LOCK_PARTITIONS)
 
#define NUM_FIXED_LWLOCKS   (PREDICATELOCK_MANAGER_LWLOCK_OFFSET + NUM_PREDICATELOCK_PARTITIONS)
 

Typedefs

typedef struct LWLock LWLock
 
typedef union LWLockPadded LWLockPadded
 
typedef union LWLockMinimallyPadded LWLockMinimallyPadded
 
typedef struct NamedLWLockTranche NamedLWLockTranche
 
typedef enum LWLockMode LWLockMode
 
typedef enum BuiltinTrancheIds BuiltinTrancheIds
 
typedef LWLockLWLockId
 

Enumerations

enum  LWLockMode { LW_EXCLUSIVE, LW_SHARED, LW_WAIT_UNTIL_FREE }
 
enum  BuiltinTrancheIds {
  LWTRANCHE_CLOG_BUFFERS = NUM_INDIVIDUAL_LWLOCKS, LWTRANCHE_COMMITTS_BUFFERS, LWTRANCHE_SUBTRANS_BUFFERS, LWTRANCHE_MXACTOFFSET_BUFFERS,
  LWTRANCHE_MXACTMEMBER_BUFFERS, LWTRANCHE_ASYNC_BUFFERS, LWTRANCHE_OLDSERXID_BUFFERS, LWTRANCHE_WAL_INSERT,
  LWTRANCHE_BUFFER_CONTENT, LWTRANCHE_BUFFER_IO_IN_PROGRESS, LWTRANCHE_REPLICATION_ORIGIN, LWTRANCHE_REPLICATION_SLOT_IO_IN_PROGRESS,
  LWTRANCHE_PROC, LWTRANCHE_BUFFER_MAPPING, LWTRANCHE_LOCK_MANAGER, LWTRANCHE_PREDICATE_LOCK_MANAGER,
  LWTRANCHE_PARALLEL_HASH_JOIN, LWTRANCHE_PARALLEL_QUERY_DSA, LWTRANCHE_SESSION_DSA, LWTRANCHE_SESSION_RECORD_TABLE,
  LWTRANCHE_SESSION_TYPMOD_TABLE, LWTRANCHE_SHARED_TUPLESTORE, LWTRANCHE_TBM, LWTRANCHE_PARALLEL_APPEND,
  LWTRANCHE_FIRST_USER_DEFINED
}
 

Functions

bool LWLockAcquire (LWLock *lock, LWLockMode mode)
 
bool LWLockConditionalAcquire (LWLock *lock, LWLockMode mode)
 
bool LWLockAcquireOrWait (LWLock *lock, LWLockMode mode)
 
void LWLockRelease (LWLock *lock)
 
void LWLockReleaseClearVar (LWLock *lock, uint64 *valptr, uint64 val)
 
void LWLockReleaseAll (void)
 
bool LWLockHeldByMe (LWLock *lock)
 
bool LWLockHeldByMeInMode (LWLock *lock, LWLockMode mode)
 
bool LWLockWaitForVar (LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval)
 
void LWLockUpdateVar (LWLock *lock, uint64 *valptr, uint64 value)
 
Size LWLockShmemSize (void)
 
void CreateLWLocks (void)
 
void InitLWLockAccess (void)
 
const char * GetLWLockIdentifier (uint32 classId, uint16 eventId)
 
void RequestNamedLWLockTranche (const char *tranche_name, int num_lwlocks)
 
LWLockPaddedGetNamedLWLockTranche (const char *tranche_name)
 
int LWLockNewTrancheId (void)
 
void LWLockRegisterTranche (int tranche_id, const char *tranche_name)
 
void LWLockInitialize (LWLock *lock, int tranche_id)
 

Variables

PGDLLIMPORT LWLockPaddedMainLWLockArray
 
const char *const MainLWLockNames []
 
PGDLLIMPORT NamedLWLockTrancheNamedLWLockTrancheArray
 
PGDLLIMPORT int NamedLWLockTrancheRequests
 

Macro Definition Documentation

◆ BUFFER_MAPPING_LWLOCK_OFFSET

#define BUFFER_MAPPING_LWLOCK_OFFSET   NUM_INDIVIDUAL_LWLOCKS

Definition at line 124 of file lwlock.h.

◆ LOCK_MANAGER_LWLOCK_OFFSET

#define LOCK_MANAGER_LWLOCK_OFFSET   (BUFFER_MAPPING_LWLOCK_OFFSET + NUM_BUFFER_PARTITIONS)

Definition at line 125 of file lwlock.h.

◆ LOG2_NUM_LOCK_PARTITIONS

#define LOG2_NUM_LOCK_PARTITIONS   4

Definition at line 116 of file lwlock.h.

Referenced by proclock_hash(), and ProcLockHashCode().

◆ LOG2_NUM_PREDICATELOCK_PARTITIONS

#define LOG2_NUM_PREDICATELOCK_PARTITIONS   4

Definition at line 120 of file lwlock.h.

◆ LWLOCK_MINIMAL_SIZE

#define LWLOCK_MINIMAL_SIZE   (sizeof(LWLock) <= 32 ? 32 : 64)

Definition at line 74 of file lwlock.h.

Referenced by CreateLWLocks().

◆ LWLOCK_PADDED_SIZE

#define LWLOCK_PADDED_SIZE   PG_CACHE_LINE_SIZE

Definition at line 73 of file lwlock.h.

Referenced by CreateLWLocks(), and LWLockShmemSize().

◆ NUM_BUFFER_PARTITIONS

#define NUM_BUFFER_PARTITIONS   128

Definition at line 113 of file lwlock.h.

Referenced by InitBufTable(), InitializeLWLocks(), StrategyInitialize(), and StrategyShmemSize().

◆ NUM_FIXED_LWLOCKS

Definition at line 129 of file lwlock.h.

Referenced by GetNamedLWLockTranche(), InitializeLWLocks(), and LWLockShmemSize().

◆ NUM_LOCK_PARTITIONS

◆ NUM_PREDICATELOCK_PARTITIONS

◆ PREDICATELOCK_MANAGER_LWLOCK_OFFSET

#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET   (LOCK_MANAGER_LWLOCK_OFFSET + NUM_LOCK_PARTITIONS)

Definition at line 127 of file lwlock.h.

Typedef Documentation

◆ BuiltinTrancheIds

◆ LWLock

◆ LWLockId

Definition at line 230 of file lwlock.h.

◆ LWLockMinimallyPadded

◆ LWLockMode

◆ LWLockPadded

◆ NamedLWLockTranche

Enumeration Type Documentation

◆ BuiltinTrancheIds

Enumerator
LWTRANCHE_CLOG_BUFFERS 
LWTRANCHE_COMMITTS_BUFFERS 
LWTRANCHE_SUBTRANS_BUFFERS 
LWTRANCHE_MXACTOFFSET_BUFFERS 
LWTRANCHE_MXACTMEMBER_BUFFERS 
LWTRANCHE_ASYNC_BUFFERS 
LWTRANCHE_OLDSERXID_BUFFERS 
LWTRANCHE_WAL_INSERT 
LWTRANCHE_BUFFER_CONTENT 
LWTRANCHE_BUFFER_IO_IN_PROGRESS 
LWTRANCHE_REPLICATION_ORIGIN 
LWTRANCHE_REPLICATION_SLOT_IO_IN_PROGRESS 
LWTRANCHE_PROC 
LWTRANCHE_BUFFER_MAPPING 
LWTRANCHE_LOCK_MANAGER 
LWTRANCHE_PREDICATE_LOCK_MANAGER 
LWTRANCHE_PARALLEL_HASH_JOIN 
LWTRANCHE_PARALLEL_QUERY_DSA 
LWTRANCHE_SESSION_DSA 
LWTRANCHE_SESSION_RECORD_TABLE 
LWTRANCHE_SESSION_TYPMOD_TABLE 
LWTRANCHE_SHARED_TUPLESTORE 
LWTRANCHE_TBM 
LWTRANCHE_PARALLEL_APPEND 
LWTRANCHE_FIRST_USER_DEFINED 

Definition at line 196 of file lwlock.h.

197 {
198  LWTRANCHE_CLOG_BUFFERS = NUM_INDIVIDUAL_LWLOCKS,
BuiltinTrancheIds
Definition: lwlock.h:196

◆ LWLockMode

enum LWLockMode
Enumerator
LW_EXCLUSIVE 
LW_SHARED 
LW_WAIT_UNTIL_FREE 

Definition at line 132 of file lwlock.h.

133 {
134  LW_EXCLUSIVE,
135  LW_SHARED,
136  LW_WAIT_UNTIL_FREE /* A special mode used in PGPROC->lwlockMode,
137  * when waiting for lock to become free. Not
138  * to be used as LWLockAcquire argument */
139 } LWLockMode;
LWLockMode
Definition: lwlock.h:132

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:828
#define LWLOCK_MINIMAL_SIZE
Definition: lwlock.h:74
#define MAX_BACKENDS
Definition: postmaster.h:75
bool IsUnderPostmaster
Definition: globals.c:108
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 713 of file lwlock.c.

References Assert, LWLockTrancheArray, LWLockTranchesAllocated, and PG_WAIT_LWLOCK.

Referenced by pgstat_get_wait_event().

714 {
715  Assert(classId == PG_WAIT_LWLOCK);
716 
717  /*
718  * It is quite possible that user has registered tranche in one of the
719  * backends (e.g. by allocating lwlocks in dynamic shared memory) but not
720  * all of them, so we can't assume the tranche is registered here.
721  */
722  if (eventId >= LWLockTranchesAllocated ||
723  LWLockTrancheArray[eventId] == NULL)
724  return "extension";
725 
726  return LWLockTrancheArray[eventId];
727 }
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:737

◆ GetNamedLWLockTranche()

LWLockPadded* GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 551 of file lwlock.c.

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

Referenced by pgss_shmem_startup().

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

◆ InitLWLockAccess()

void InitLWLockAccess ( void  )

Definition at line 535 of file lwlock.c.

Referenced by InitProcess().

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

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1121 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(), ExecParallelHashMergeCounters(), ExecParallelHashPopChunkQueue(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), 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(), 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(), xact_redo_abort(), xact_redo_commit(), XidCacheRemoveRunningXids(), xlog_redo(), and XLogBackgroundFlush().

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

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

◆ LWLockConditionalAcquire()

bool LWLockConditionalAcquire ( LWLock lock,
LWLockMode  mode 
)

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

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

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

bool LWLockHeldByMeInMode ( LWLock lock,
LWLockMode  mode 
)

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

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

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

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( void  )

Definition at line 582 of file lwlock.c.

References ShmemLock, SpinLockAcquire, and SpinLockRelease.

Referenced by apw_init_shmem(), and InitializeLWLocks().

583 {
584  int result;
585  int *LWLockCounter;
586 
587  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
589  result = (*LWLockCounter)++;
591 
592  return result;
593 }
#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

◆ LWLockRegisterTranche()

void LWLockRegisterTranche ( int  tranche_id,
const char *  tranche_name 
)

Definition at line 602 of file lwlock.c.

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

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

603 {
604  Assert(LWLockTrancheArray != NULL);
605 
606  if (tranche_id >= LWLockTranchesAllocated)
607  {
609  int j = LWLockTranchesAllocated;
610 
611  while (i <= tranche_id)
612  i *= 2;
613 
614  LWLockTrancheArray = (const char **)
615  repalloc(LWLockTrancheArray, i * sizeof(char *));
617  while (j < LWLockTranchesAllocated)
618  LWLockTrancheArray[j++] = NULL;
619  }
620 
621  LWLockTrancheArray[tranche_id] = tranche_name;
622 }
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:1044
int i

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1725 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(), ExecParallelHashMergeCounters(), ExecParallelHashPopChunkQueue(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), 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(), 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(), xact_redo_abort(), xact_redo_commit(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), and XLogNeedsFlush().

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

1825 {
1826  while (num_held_lwlocks > 0)
1827  {
1828  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1829 
1831  }
1832 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
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 1798 of file lwlock.c.

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

Referenced by WALInsertLockRelease().

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

◆ 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  value 
)

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

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

◆ LWLockWaitForVar()

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

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

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

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

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

638 {
639  NamedLWLockTrancheRequest *request;
640 
642  return; /* too late */
643 
644  if (NamedLWLockTrancheRequestArray == NULL)
645  {
650  * sizeof(NamedLWLockTrancheRequest));
651  }
652 
654  {
656 
657  while (i <= NamedLWLockTrancheRequests)
658  i *= 2;
659 
662  i * sizeof(NamedLWLockTrancheRequest));
664  }
665 
667  Assert(strlen(tranche_name) + 1 < NAMEDATALEN);
668  StrNCpy(request->tranche_name, tranche_name, NAMEDATALEN);
669  request->num_lwlocks = num_lwlocks;
671 }
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:108
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:914
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1044
NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:152
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
int i

Variable Documentation

◆ MainLWLockArray

PGDLLIMPORT LWLockPadded* MainLWLockArray

Definition at line 125 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ MainLWLockNames

const char* const MainLWLockNames[]

Referenced by RegisterLWLockTranches().

◆ NamedLWLockTrancheArray

PGDLLIMPORT NamedLWLockTranche* NamedLWLockTrancheArray

Definition at line 156 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheRequests