PostgreSQL Source Code  git master
lwlock.h File Reference
#include "port/atomics.h"
#include "storage/proclist_types.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
 
struct  NamedLWLockTranche
 

Macros

#define LWLOCK_PADDED_SIZE   PG_CACHE_LINE_SIZE
 
#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 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_XACT_BUFFER = NUM_INDIVIDUAL_LWLOCKS, LWTRANCHE_COMMITTS_BUFFER, LWTRANCHE_SUBTRANS_BUFFER, LWTRANCHE_MULTIXACTOFFSET_BUFFER,
  LWTRANCHE_MULTIXACTMEMBER_BUFFER, LWTRANCHE_NOTIFY_BUFFER, LWTRANCHE_SERIAL_BUFFER, LWTRANCHE_WAL_INSERT,
  LWTRANCHE_BUFFER_CONTENT, LWTRANCHE_REPLICATION_ORIGIN_STATE, LWTRANCHE_REPLICATION_SLOT_IO, LWTRANCHE_LOCK_FASTPATH,
  LWTRANCHE_BUFFER_MAPPING, LWTRANCHE_LOCK_MANAGER, LWTRANCHE_PREDICATE_LOCK_MANAGER, LWTRANCHE_PARALLEL_HASH_JOIN,
  LWTRANCHE_PARALLEL_QUERY_DSA, LWTRANCHE_PER_SESSION_DSA, LWTRANCHE_PER_SESSION_RECORD_TYPE, LWTRANCHE_PER_SESSION_RECORD_TYPMOD,
  LWTRANCHE_SHARED_TUPLESTORE, LWTRANCHE_SHARED_TIDBITMAP, LWTRANCHE_PARALLEL_APPEND, LWTRANCHE_PER_XACT_PREDICATE_LIST,
  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
 
PGDLLIMPORT NamedLWLockTrancheNamedLWLockTrancheArray
 
PGDLLIMPORT int NamedLWLockTrancheRequests
 

Macro Definition Documentation

◆ BUFFER_MAPPING_LWLOCK_OFFSET

#define BUFFER_MAPPING_LWLOCK_OFFSET   NUM_INDIVIDUAL_LWLOCKS

Definition at line 94 of file lwlock.h.

Referenced by InitializeLWLocks().

◆ LOCK_MANAGER_LWLOCK_OFFSET

#define LOCK_MANAGER_LWLOCK_OFFSET   (BUFFER_MAPPING_LWLOCK_OFFSET + NUM_BUFFER_PARTITIONS)

Definition at line 95 of file lwlock.h.

Referenced by InitializeLWLocks().

◆ LOG2_NUM_LOCK_PARTITIONS

#define LOG2_NUM_LOCK_PARTITIONS   4

Definition at line 86 of file lwlock.h.

Referenced by proclock_hash(), and ProcLockHashCode().

◆ LOG2_NUM_PREDICATELOCK_PARTITIONS

#define LOG2_NUM_PREDICATELOCK_PARTITIONS   4

Definition at line 90 of file lwlock.h.

◆ LWLOCK_PADDED_SIZE

#define LWLOCK_PADDED_SIZE   PG_CACHE_LINE_SIZE

Definition at line 52 of file lwlock.h.

Referenced by CreateLWLocks(), and LWLockShmemSize().

◆ NUM_BUFFER_PARTITIONS

#define NUM_BUFFER_PARTITIONS   128

Definition at line 83 of file lwlock.h.

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

◆ NUM_FIXED_LWLOCKS

Definition at line 99 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 97 of file lwlock.h.

Referenced by InitializeLWLocks().

Typedef Documentation

◆ BuiltinTrancheIds

◆ LWLock

typedef struct LWLock LWLock

◆ LWLockId

typedef LWLock* LWLockId

Definition at line 200 of file lwlock.h.

◆ LWLockMode

typedef enum LWLockMode LWLockMode

◆ LWLockPadded

typedef union LWLockPadded LWLockPadded

◆ NamedLWLockTranche

Enumeration Type Documentation

◆ BuiltinTrancheIds

Enumerator
LWTRANCHE_XACT_BUFFER 
LWTRANCHE_COMMITTS_BUFFER 
LWTRANCHE_SUBTRANS_BUFFER 
LWTRANCHE_MULTIXACTOFFSET_BUFFER 
LWTRANCHE_MULTIXACTMEMBER_BUFFER 
LWTRANCHE_NOTIFY_BUFFER 
LWTRANCHE_SERIAL_BUFFER 
LWTRANCHE_WAL_INSERT 
LWTRANCHE_BUFFER_CONTENT 
LWTRANCHE_REPLICATION_ORIGIN_STATE 
LWTRANCHE_REPLICATION_SLOT_IO 
LWTRANCHE_LOCK_FASTPATH 
LWTRANCHE_BUFFER_MAPPING 
LWTRANCHE_LOCK_MANAGER 
LWTRANCHE_PREDICATE_LOCK_MANAGER 
LWTRANCHE_PARALLEL_HASH_JOIN 
LWTRANCHE_PARALLEL_QUERY_DSA 
LWTRANCHE_PER_SESSION_DSA 
LWTRANCHE_PER_SESSION_RECORD_TYPE 
LWTRANCHE_PER_SESSION_RECORD_TYPMOD 
LWTRANCHE_SHARED_TUPLESTORE 
LWTRANCHE_SHARED_TIDBITMAP 
LWTRANCHE_PARALLEL_APPEND 
LWTRANCHE_PER_XACT_PREDICATE_LIST 
LWTRANCHE_FIRST_USER_DEFINED 

Definition at line 166 of file lwlock.h.

167 {
168  LWTRANCHE_XACT_BUFFER = NUM_INDIVIDUAL_LWLOCKS,
BuiltinTrancheIds
Definition: lwlock.h:166

◆ LWLockMode

enum LWLockMode
Enumerator
LW_EXCLUSIVE 
LW_SHARED 
LW_WAIT_UNTIL_FREE 

Definition at line 102 of file lwlock.h.

103 {
104  LW_EXCLUSIVE,
105  LW_SHARED,
106  LW_WAIT_UNTIL_FREE /* A special mode used in PGPROC->lwWaitMode,
107  * when waiting for lock to become free. Not
108  * to be used as LWLockAcquire argument */
109 } LWLockMode;
LWLockMode
Definition: lwlock.h:102

Function Documentation

◆ CreateLWLocks()

void CreateLWLocks ( void  )

Definition at line 465 of file lwlock.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

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

◆ GetLWLockIdentifier()

const char* GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 804 of file lwlock.c.

References Assert, GetLWTrancheName(), and PG_WAIT_LWLOCK.

Referenced by pgstat_get_wait_event().

805 {
806  Assert(classId == PG_WAIT_LWLOCK);
807  /* The event IDs are just tranche numbers. */
808  return GetLWTrancheName(eventId);
809 }
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:776
#define PG_WAIT_LWLOCK
Definition: wait_event.h:18
#define Assert(condition)
Definition: c.h:804

◆ GetNamedLWLockTranche()

LWLockPadded* GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 594 of file lwlock.c.

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

Referenced by pgss_shmem_startup().

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

◆ InitLWLockAccess()

void InitLWLockAccess ( void  )

Definition at line 578 of file lwlock.c.

Referenced by InitProcess().

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

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1203 of file lwlock.c.

References Assert, AssertArg, elog, ERROR, HOLD_INTERRUPTS, IsUnderPostmaster, LWLockHandle::lock, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_RELEASE_OK, LW_SHARED, LWLockAttemptLock(), LWLockDequeueSelf(), LWLockQueueSelf(), LWLockReportWaitEnd(), LWLockReportWaitStart(), PGPROC::lwWaiting, MAX_BACKENDS, MAX_SIMUL_LWLOCKS, LWLockHandle::mode, MyProc, num_held_lwlocks, pg_atomic_fetch_or_u32(), pg_atomic_fetch_sub_u32(), PG_USED_FOR_ASSERTS_ONLY, PGSemaphoreLock(), PGSemaphoreUnlock(), PRINT_LWDEBUG, PGPROC::sem, LWLock::state, and T_NAME.

Referenced by _bt_end_vacuum(), _bt_start_vacuum(), _bt_vacuum_cycleid(), AbsorbSyncRequests(), ActivateCommitTs(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_init_shmem(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacLauncherMain(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendIdGetProc(), BackendIdGetTransactionIds(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BootStrapCLOG(), BootStrapMultiXact(), BootStrapSUBTRANS(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), CheckRecoveryConsistency(), CheckTableForSerializableConflictIn(), CheckTargetForConflictsIn(), choose_next_subplan_for_leader(), choose_next_subplan_for_worker(), CleanupInvalidationState(), ClearOldPredicateLocks(), clog_redo(), commit_ts_redo(), ComputeXidHorizons(), copy_replication_slot(), CountDBBackends(), CountDBConnections(), CountOtherDBBackends(), CountUserBackends(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateInitDecodingContext(), CreatePredicateLock(), CreateRestartPoint(), DeactivateCommitTs(), DeleteChildTargetLocks(), DeleteLockTarget(), destroy_superblock(), do_autovacuum(), do_pg_start_backup(), do_pg_stop_backup(), do_start_worker(), DropAllPredicateLocksFromTable(), DropSubscription(), DropTableSpace(), dsa_allocate_extended(), dsa_dump(), dsa_free(), dsa_pin(), dsa_release_in_place(), dsa_set_size_limit(), dsa_trim(), dsa_unpin(), dshash_delete_key(), dshash_dump(), dshash_find(), dshash_find_or_insert(), dsm_attach(), dsm_create(), dsm_detach(), dsm_pin_segment(), dsm_unpin_segment(), ensure_active_superblock(), entry_reset(), Exec_ListenPreCommit(), ExecParallelHashMergeCounters(), ExecParallelHashPopChunkQueue(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), ExpireAllKnownAssignedTransactionIds(), ExpireOldKnownAssignedTransactionIds(), ExpireTreeKnownAssignedTransactionIds(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), FindAndDropRelFileNodeBuffers(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), FlushRelationsAllBuffers(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), get_xid_status(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldSnapshotFromTimeMapping(), GetOldSnapshotTimeMapping(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionData(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), HandleAutoVacLauncherInterrupts(), HaveVirtualXIDsDelayingChkpt(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), KnownAssignedXidsAdd(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockBuffer(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_worker_attach(), logicalrep_worker_detach(), logicalrep_worker_launch(), logicalrep_worker_stop(), logicalrep_worker_wakeup(), MaintainOldSnapshotTimeMapping(), MarkAsPrepared(), MarkAsPreparing(), MaybeExtendOffsetSlru(), multixact_redo(), MultiXactAdvanceNextMXact(), MultiXactGetCheckptMulti(), MultiXactIdSetOldestMember(), MultiXactIdSetOldestVisible(), MultiXactSetNextMXact(), PageIsPredicateLocked(), perform_relmap_update(), pg_get_replication_slots(), pg_get_shmem_allocations(), pg_notification_queue_usage(), pg_show_replication_origin_status(), pg_stat_get_subscription(), pg_stat_statements_internal(), pg_xact_status(), pgss_shmem_startup(), pgss_store(), pgstat_reset_replslot_counter(), PostPrepare_Locks(), PostPrepare_MultiXact(), PostPrepare_Twophase(), PreCommit_CheckForSerializationFailure(), PreCommit_Notify(), predicatelock_twophase_recover(), PredicateLockPageSplit(), PredicateLockTwoPhaseFinish(), PrefetchSharedBuffer(), PrescanPreparedTransactions(), ProcArrayAdd(), ProcArrayApplyRecoveryInfo(), ProcArrayApplyXidAssignment(), ProcArrayClearTransaction(), ProcArrayEndTransaction(), ProcArrayGetReplicationSlotXmin(), ProcArrayGroupClearXid(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), ProcArrayRemove(), ProcArraySetReplicationSlotXmin(), process_syncing_tables_for_apply(), ProcKill(), ProcSleep(), ReadBuffer_common(), ReadMultiXactCounts(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadRecord(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePreInvalidate(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquireInternal(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDropPtr(), ReplicationSlotRelease(), ReplicationSlotsComputeLogicalRestartLSN(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), replorigin_advance(), replorigin_drop_guts(), replorigin_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset(), replorigin_session_setup(), resize(), RestoreScratchTarget(), restoreTwoPhaseData(), SaveSlotToPath(), SerialAdd(), SerialGetMinConflictCommitSeqNo(), SerialSetActiveSerXmin(), set_indexsafe_procflags(), SetCommitTsLimit(), SetMultiXactIdLimit(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SignalVirtualTransaction(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), StandbyRecoverPreparedTransactions(), StartupCLOG(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SyncOneBuffer(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateOtherDBBackends(), TransactionGroupUpdateXidStatus(), TransactionIdGetCommitTsData(), TransactionIdIsActive(), TransactionIdIsInProgress(), TransactionIdSetPageStatus(), TransactionTreeSetCommitTsData(), TransferPredicateLocksToNewTarget(), TrimCLOG(), TrimMultiXact(), TruncateMultiXact(), TwoPhaseGetGXact(), update_cached_xid_range(), UpdateMinRecoveryPoint(), vac_truncate_clog(), vacuum_rel(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitForReplicationWorkerAttach(), WALInsertLockAcquire(), WALInsertLockAcquireExclusive(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), and XLogReportParameters().

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

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)

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

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

◆ LWLockConditionalAcquire()

bool LWLockConditionalAcquire ( LWLock lock,
LWLockMode  mode 
)

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

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

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

bool LWLockHeldByMeInMode ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1938 of file lwlock.c.

References i, and num_held_lwlocks.

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

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

◆ LWLockInitialize()

void LWLockInitialize ( LWLock lock,
int  tranche_id 
)

Definition at line 740 of file lwlock.c.

References LW_FLAG_RELEASE_OK, pg_atomic_init_u32(), proclist_init(), LWLock::state, LWLock::tranche, and LWLock::waiters.

Referenced by apw_init_shmem(), create_internal(), dshash_create(), ExecAppendInitializeDSM(), ExecHashJoinInitializeDSM(), InitBufferPool(), InitializeLWLocks(), InitPredicateLocks(), InitProcGlobal(), ReplicationOriginShmemInit(), ReplicationSlotsShmemInit(), SimpleLruInit(), sts_initialize(), tbm_prepare_shared_iterate(), and XLOGShmemInit().

741 {
743 #ifdef LOCK_DEBUG
744  pg_atomic_init_u32(&lock->nwaiters, 0);
745 #endif
746  lock->tranche = tranche_id;
747  proclist_init(&lock->waiters);
748 }
proclist_head waiters
Definition: lwlock.h:35
pg_atomic_uint32 state
Definition: lwlock.h:34
uint16 tranche
Definition: lwlock.h:33
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:100
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:223

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( void  )

Definition at line 624 of file lwlock.c.

References ShmemLock, SpinLockAcquire, and SpinLockRelease.

Referenced by apw_init_shmem(), and InitializeLWLocks().

625 {
626  int result;
627  int *LWLockCounter;
628 
629  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
631  result = (*LWLockCounter)++;
633 
634  return result;
635 }
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
slock_t * ShmemLock
Definition: shmem.c:88
LWLockPadded * MainLWLockArray
Definition: lwlock.c:198

◆ LWLockRegisterTranche()

void LWLockRegisterTranche ( int  tranche_id,
const char *  tranche_name 
)

Definition at line 648 of file lwlock.c.

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

Referenced by apw_init_shmem(), and CreateLWLocks().

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

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1805 of file lwlock.c.

References Assert, elog, ERROR, i, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_HAS_WAITERS, LW_FLAG_RELEASE_OK, LW_LOCK_MASK, LW_VAL_EXCLUSIVE, LW_VAL_SHARED, LWLockWakeup(), LWLockHandle::mode, num_held_lwlocks, pg_atomic_sub_fetch_u32(), PRINT_LWDEBUG, RESUME_INTERRUPTS, and T_NAME.

Referenced by _bt_end_vacuum(), _bt_start_vacuum(), _bt_vacuum_cycleid(), AbsorbSyncRequests(), ActivateCommitTs(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_init_shmem(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacLauncherMain(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendIdGetProc(), BackendIdGetTransactionIds(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BootStrapCLOG(), BootStrapMultiXact(), BootStrapSUBTRANS(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), CheckRecoveryConsistency(), CheckTableForSerializableConflictIn(), CheckTargetForConflictsIn(), choose_next_subplan_for_leader(), choose_next_subplan_for_worker(), CleanupInvalidationState(), ClearOldPredicateLocks(), clog_redo(), commit_ts_redo(), ComputeXidHorizons(), copy_replication_slot(), CountDBBackends(), CountDBConnections(), CountOtherDBBackends(), CountUserBackends(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateInitDecodingContext(), CreatePredicateLock(), CreateRestartPoint(), DeactivateCommitTs(), DeleteChildTargetLocks(), DeleteLockTarget(), destroy_superblock(), do_autovacuum(), do_pg_start_backup(), do_pg_stop_backup(), do_start_worker(), DropAllPredicateLocksFromTable(), DropSubscription(), DropTableSpace(), dsa_allocate_extended(), dsa_dump(), dsa_free(), dsa_pin(), dsa_release_in_place(), dsa_set_size_limit(), dsa_trim(), dsa_unpin(), dshash_delete_entry(), dshash_delete_key(), dshash_dump(), dshash_find(), dshash_find_or_insert(), dshash_release_lock(), dsm_attach(), dsm_create(), dsm_detach(), dsm_pin_segment(), dsm_unpin_segment(), ensure_active_superblock(), entry_reset(), Exec_ListenPreCommit(), ExecParallelHashMergeCounters(), ExecParallelHashPopChunkQueue(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), ExpireAllKnownAssignedTransactionIds(), ExpireOldKnownAssignedTransactionIds(), ExpireTreeKnownAssignedTransactionIds(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), find_multixact_start(), FindAndDropRelFileNodeBuffers(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), FlushRelationsAllBuffers(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), get_xid_status(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldSnapshotFromTimeMapping(), GetOldSnapshotTimeMapping(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), HandleAutoVacLauncherInterrupts(), HaveVirtualXIDsDelayingChkpt(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), KnownAssignedXidsAdd(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockBuffer(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_worker_attach(), logicalrep_worker_detach(), logicalrep_worker_launch(), logicalrep_worker_stop(), logicalrep_worker_wakeup(), LogStandbySnapshot(), LWLockReleaseAll(), LWLockReleaseClearVar(), MaintainOldSnapshotTimeMapping(), MarkAsPrepared(), MarkAsPreparing(), MaybeExtendOffsetSlru(), multixact_redo(), MultiXactAdvanceNextMXact(), MultiXactGetCheckptMulti(), MultiXactIdSetOldestMember(), MultiXactIdSetOldestVisible(), MultiXactSetNextMXact(), OnConflict_CheckForSerializationFailure(), PageIsPredicateLocked(), perform_relmap_update(), pg_get_replication_slots(), pg_get_shmem_allocations(), pg_notification_queue_usage(), pg_show_replication_origin_status(), pg_stat_get_subscription(), pg_stat_statements_internal(), pg_xact_status(), pgss_shmem_startup(), pgss_store(), pgstat_reset_replslot_counter(), PostPrepare_Locks(), PostPrepare_MultiXact(), PostPrepare_Twophase(), PreCommit_CheckForSerializationFailure(), PreCommit_Notify(), predicatelock_twophase_recover(), PredicateLockPageSplit(), PredicateLockTwoPhaseFinish(), PrefetchSharedBuffer(), PrescanPreparedTransactions(), ProcArrayAdd(), ProcArrayApplyRecoveryInfo(), ProcArrayApplyXidAssignment(), ProcArrayClearTransaction(), ProcArrayEndTransaction(), ProcArrayGetReplicationSlotXmin(), ProcArrayGroupClearXid(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), ProcArrayRemove(), ProcArraySetReplicationSlotXmin(), process_syncing_tables_for_apply(), ProcKill(), ProcSleep(), ReadMultiXactCounts(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadRecord(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePostInvalidate(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquireInternal(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDropPtr(), ReplicationSlotRelease(), ReplicationSlotsComputeLogicalRestartLSN(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), replorigin_advance(), replorigin_drop_guts(), replorigin_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset(), replorigin_session_setup(), resize(), RestoreScratchTarget(), restoreTwoPhaseData(), SaveSlotToPath(), SerialAdd(), SerialGetMinConflictCommitSeqNo(), SerialSetActiveSerXmin(), set_indexsafe_procflags(), SetCommitTsLimit(), SetMultiXactIdLimit(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SignalVirtualTransaction(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), ss_report_location(), StandbyRecoverPreparedTransactions(), StartupCLOG(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransGetParent(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SyncOneBuffer(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateOtherDBBackends(), TransactionGroupUpdateXidStatus(), TransactionIdGetCommitTsData(), TransactionIdGetStatus(), TransactionIdIsActive(), TransactionIdIsInProgress(), TransactionIdSetPageStatus(), TransactionTreeSetCommitTsData(), TransferPredicateLocksToNewTarget(), TrimCLOG(), TrimMultiXact(), TruncateMultiXact(), TwoPhaseGetGXact(), update_cached_xid_range(), UpdateMinRecoveryPoint(), vac_truncate_clog(), vacuum_rel(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitForReplicationWorkerAttach(), WaitOnLock(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), XLogNeedsFlush(), and XLogReportParameters().

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

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

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

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

◆ LWLockReleaseClearVar()

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

Definition at line 1877 of file lwlock.c.

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

Referenced by WALInsertLockRelease().

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

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 432 of file lwlock.c.

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

Referenced by CreateLWLocks(), and CreateSharedMemoryAndSemaphores().

433 {
434  Size size;
435  int i;
436  int numLocks = NUM_FIXED_LWLOCKS;
437 
438  /* Calculate total number of locks needed in the main array. */
439  numLocks += NumLWLocksForNamedTranches();
440 
441  /* Space for the LWLock array. */
442  size = mul_size(numLocks, sizeof(LWLockPadded));
443 
444  /* Space for dynamic allocation counter, plus room for alignment. */
445  size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
446 
447  /* space for named tranches. */
449 
450  /* space for name of each tranche. */
451  for (i = 0; i < NamedLWLockTrancheRequests; i++)
452  size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
453 
454  /* Disallow adding any more named tranches. */
456 
457  return size;
458 }
static bool lock_named_request_allowed
Definition: lwlock.c:239
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:99
int NamedLWLockTrancheRequests
Definition: lwlock.c:234
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:417
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
size_t Size
Definition: c.h:540
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:225
int i
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:52

◆ LWLockUpdateVar()

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

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

1752 {
1753  proclist_head wakeup;
1754  proclist_mutable_iter iter;
1755 
1756  PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1757 
1758  proclist_init(&wakeup);
1759 
1760  LWLockWaitListLock(lock);
1761 
1763 
1764  /* Update the lock's value */
1765  *valptr = val;
1766 
1767  /*
1768  * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1769  * up. They are always in the front of the queue.
1770  */
1771  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1772  {
1773  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1774 
1775  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1776  break;
1777 
1778  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1779  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1780  }
1781 
1782  /* We are done updating shared state of the lock itself. */
1783  LWLockWaitListUnlock(lock);
1784 
1785  /*
1786  * Awaken any waiters I removed from the queue.
1787  */
1788  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1789  {
1790  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1791 
1792  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1793  /* check comment in LWLockWakeup() about this barrier */
1794  pg_write_barrier();
1795  waiter->lwWaiting = false;
1796  PGSemaphoreUnlock(waiter->sem);
1797  }
1798 }
#define GetPGProcByNumber(n)
Definition: proc.h:367
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
proclist_head waiters
Definition: lwlock.h:35
bool lwWaiting
Definition: proc.h:170
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:944
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
uint8 lwWaitMode
Definition: proc.h:171
pg_atomic_uint32 state
Definition: lwlock.h:34
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:187
#define Assert(condition)
Definition: c.h:804
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:310
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:191
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:892
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:103
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
#define pg_write_barrier()
Definition: atomics.h:159
PGSemaphore sem
Definition: proc.h:127
Definition: proc.h:121
long val
Definition: informix.c:664
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241

◆ LWLockWaitForVar()

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

Definition at line 1614 of file lwlock.c.

References Assert, HOLD_INTERRUPTS, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_RELEASE_OK, LW_WAIT_UNTIL_FREE, LWLockConflictsWithVar(), LWLockDequeueSelf(), LWLockQueueSelf(), LWLockReportWaitEnd(), LWLockReportWaitStart(), PGPROC::lwWaiting, MAX_BACKENDS, MyProc, pg_atomic_fetch_or_u32(), pg_atomic_fetch_sub_u32(), PG_USED_FOR_ASSERTS_ONLY, PGSemaphoreLock(), PGSemaphoreUnlock(), PRINT_LWDEBUG, RESUME_INTERRUPTS, PGPROC::sem, LWLock::state, and T_NAME.

Referenced by WaitXLogInsertionsToFinish().

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

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 700 of file lwlock.c.

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

Referenced by _PG_init().

701 {
702  NamedLWLockTrancheRequest *request;
703 
705  return; /* too late */
706 
707  if (NamedLWLockTrancheRequestArray == NULL)
708  {
713  * sizeof(NamedLWLockTrancheRequest));
714  }
715 
717  {
719 
720  while (i <= NamedLWLockTrancheRequests)
721  i *= 2;
722 
725  i * sizeof(NamedLWLockTrancheRequest));
727  }
728 
730  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
731  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
732  request->num_lwlocks = num_lwlocks;
734 }
static bool lock_named_request_allowed
Definition: lwlock.c:239
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:221
#define NAMEDATALEN
int NamedLWLockTrancheRequests
Definition: lwlock.c:234
bool IsUnderPostmaster
Definition: globals.c:112
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:226
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define Assert(condition)
Definition: c.h:804
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:225
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
int i

Variable Documentation

◆ MainLWLockArray

PGDLLIMPORT LWLockPadded* MainLWLockArray

Definition at line 198 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheArray

PGDLLIMPORT NamedLWLockTranche* NamedLWLockTrancheArray

Definition at line 237 of file lwlock.c.

Referenced by PostmasterMarkPIDForWorkerNotify().

◆ NamedLWLockTrancheRequests