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.

◆ LOCK_MANAGER_LWLOCK_OFFSET

#define LOCK_MANAGER_LWLOCK_OFFSET    (BUFFER_MAPPING_LWLOCK_OFFSET + NUM_BUFFER_PARTITIONS)

Definition at line 95 of file lwlock.h.

◆ LOG2_NUM_LOCK_PARTITIONS

#define LOG2_NUM_LOCK_PARTITIONS   4

Definition at line 86 of file lwlock.h.

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

◆ NUM_BUFFER_PARTITIONS

#define NUM_BUFFER_PARTITIONS   128

Definition at line 83 of file lwlock.h.

◆ NUM_FIXED_LWLOCKS

Definition at line 99 of file lwlock.h.

◆ NUM_LOCK_PARTITIONS

#define NUM_LOCK_PARTITIONS   (1 << LOG2_NUM_LOCK_PARTITIONS)

Definition at line 87 of file lwlock.h.

◆ NUM_PREDICATELOCK_PARTITIONS

#define NUM_PREDICATELOCK_PARTITIONS   (1 << LOG2_NUM_PREDICATELOCK_PARTITIONS)

Definition at line 91 of file lwlock.h.

◆ PREDICATELOCK_MANAGER_LWLOCK_OFFSET

#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET    (LOCK_MANAGER_LWLOCK_OFFSET + NUM_LOCK_PARTITIONS)

Definition at line 97 of file lwlock.h.

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:167
@ LWTRANCHE_FIRST_USER_DEFINED
Definition: lwlock.h:192
@ LWTRANCHE_SHARED_TIDBITMAP
Definition: lwlock.h:189
@ LWTRANCHE_PER_SESSION_DSA
Definition: lwlock.h:185
@ LWTRANCHE_PARALLEL_QUERY_DSA
Definition: lwlock.h:184
@ LWTRANCHE_COMMITTS_BUFFER
Definition: lwlock.h:169
@ LWTRANCHE_SUBTRANS_BUFFER
Definition: lwlock.h:170
@ LWTRANCHE_PER_SESSION_RECORD_TYPMOD
Definition: lwlock.h:187
@ LWTRANCHE_XACT_BUFFER
Definition: lwlock.h:168
@ LWTRANCHE_REPLICATION_ORIGIN_STATE
Definition: lwlock.h:177
@ LWTRANCHE_PARALLEL_APPEND
Definition: lwlock.h:190
@ LWTRANCHE_REPLICATION_SLOT_IO
Definition: lwlock.h:178
@ LWTRANCHE_BUFFER_CONTENT
Definition: lwlock.h:176
@ LWTRANCHE_MULTIXACTMEMBER_BUFFER
Definition: lwlock.h:172
@ LWTRANCHE_NOTIFY_BUFFER
Definition: lwlock.h:173
@ LWTRANCHE_PER_SESSION_RECORD_TYPE
Definition: lwlock.h:186
@ LWTRANCHE_PREDICATE_LOCK_MANAGER
Definition: lwlock.h:182
@ LWTRANCHE_BUFFER_MAPPING
Definition: lwlock.h:180
@ LWTRANCHE_SERIAL_BUFFER
Definition: lwlock.h:174
@ LWTRANCHE_PARALLEL_HASH_JOIN
Definition: lwlock.h:183
@ LWTRANCHE_PER_XACT_PREDICATE_LIST
Definition: lwlock.h:191
@ LWTRANCHE_MULTIXACTOFFSET_BUFFER
Definition: lwlock.h:171
@ LWTRANCHE_WAL_INSERT
Definition: lwlock.h:175
@ LWTRANCHE_LOCK_MANAGER
Definition: lwlock.h:181
@ LWTRANCHE_SHARED_TUPLESTORE
Definition: lwlock.h:188
@ LWTRANCHE_LOCK_FASTPATH
Definition: lwlock.h:179

◆ 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:103
@ LW_SHARED
Definition: lwlock.h:105
@ LW_WAIT_UNTIL_FREE
Definition: lwlock.h:106
@ LW_EXCLUSIVE
Definition: lwlock.h:104

Function Documentation

◆ CreateLWLocks()

void CreateLWLocks ( void  )

Definition at line 466 of file lwlock.c.

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

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

Referenced by CreateSharedMemoryAndSemaphores().

◆ GetLWLockIdentifier()

const char* GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 800 of file lwlock.c.

801 {
802  Assert(classId == PG_WAIT_LWLOCK);
803  /* The event IDs are just tranche numbers. */
804  return GetLWTrancheName(eventId);
805 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:772
#define PG_WAIT_LWLOCK
Definition: wait_event.h:18

References Assert(), GetLWTrancheName(), and PG_WAIT_LWLOCK.

Referenced by pgstat_get_wait_event().

◆ GetNamedLWLockTranche()

LWLockPadded* GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 595 of file lwlock.c.

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

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

Referenced by pgss_shmem_startup().

◆ InitLWLockAccess()

void InitLWLockAccess ( void  )

Definition at line 579 of file lwlock.c.

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

Referenced by InitProcess().

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1199 of file lwlock.c.

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

References Assert(), AssertArg, elog, ERROR, held_lwlocks, 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, mode, MyProc, num_held_lwlocks, pg_atomic_fetch_or_u32(), pg_atomic_fetch_sub_u32(), PG_USED_FOR_ASSERTS_ONLY, PGSemaphoreLock(), PGSemaphoreUnlock(), PRINT_LWDEBUG, PGPROC::sem, LWLock::state, and T_NAME.

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

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1427 of file lwlock.c.

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

References Assert(), elog, ERROR, held_lwlocks, 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, 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().

◆ LWLockConditionalAcquire()

bool LWLockConditionalAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1370 of file lwlock.c.

1371 {
1372  bool mustwait;
1373 
1375 
1376  PRINT_LWDEBUG("LWLockConditionalAcquire", lock, mode);
1377 
1378  /* Ensure we will have room to remember the lock */
1380  elog(ERROR, "too many LWLocks taken");
1381 
1382  /*
1383  * Lock out cancel/die interrupts until we exit the code section protected
1384  * by the LWLock. This ensures that interrupts will not interfere with
1385  * manipulations of data structures in shared memory.
1386  */
1387  HOLD_INTERRUPTS();
1388 
1389  /* Check for the lock */
1390  mustwait = LWLockAttemptLock(lock, mode);
1391 
1392  if (mustwait)
1393  {
1394  /* Failed to get lock, so release interrupt holdoff */
1396 
1397  LOG_LWDEBUG("LWLockConditionalAcquire", lock, "failed");
1398  if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL_ENABLED())
1399  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL(T_NAME(lock), mode);
1400  }
1401  else
1402  {
1403  /* Add lock to list of locks held by this backend */
1406  if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_ENABLED())
1407  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(T_NAME(lock), mode);
1408  }
1409  return !mustwait;
1410 }

References AssertArg, elog, ERROR, held_lwlocks, HOLD_INTERRUPTS, LWLockHandle::lock, LOG_LWDEBUG, LW_EXCLUSIVE, LW_SHARED, LWLockAttemptLock(), MAX_SIMUL_LWLOCKS, LWLockHandle::mode, mode, num_held_lwlocks, PRINT_LWDEBUG, RESUME_INTERRUPTS, and T_NAME.

Referenced by BufferAlloc(), ConditionalLockBuffer(), ProcArrayEndTransaction(), SimpleLruWaitIO(), ss_report_location(), TransactionIdSetPageStatus(), and XLogNeedsFlush().

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

◆ LWLockInitialize()

void LWLockInitialize ( LWLock lock,
int  tranche_id 
)

Definition at line 736 of file lwlock.c.

737 {
739 #ifdef LOCK_DEBUG
740  pg_atomic_init_u32(&lock->nwaiters, 0);
741 #endif
742  lock->tranche = tranche_id;
743  proclist_init(&lock->waiters);
744 }
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:223
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
uint16 tranche
Definition: lwlock.h:33
proclist_head waiters
Definition: lwlock.h:35

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().

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( void  )

Definition at line 625 of file lwlock.c.

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

References MainLWLockArray, ShmemLock, SpinLockAcquire, and SpinLockRelease.

Referenced by apw_init_shmem(), and InitializeLWLocks().

◆ LWLockRegisterTranche()

void LWLockRegisterTranche ( int  tranche_id,
const char *  tranche_name 
)

Definition at line 649 of file lwlock.c.

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

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

Referenced by apw_init_shmem(), and CreateLWLocks().

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1803 of file lwlock.c.

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

References Assert(), elog, ERROR, held_lwlocks, 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, mode, num_held_lwlocks, pg_atomic_sub_fetch_u32(), PRINT_LWDEBUG, RESUME_INTERRUPTS, LWLock::state, and T_NAME.

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

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

Definition at line 1902 of file lwlock.c.

1903 {
1904  while (num_held_lwlocks > 0)
1905  {
1906  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1907 
1909  }
1910 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803

References held_lwlocks, HOLD_INTERRUPTS, LWLockRelease(), and num_held_lwlocks.

Referenced by AbortSubTransaction(), AbortTransaction(), AutoVacLauncherMain(), AuxiliaryProcKill(), BackgroundWriterMain(), CheckpointerMain(), ProcKill(), ShutdownAuxiliaryProcess(), WalSndErrorCleanup(), and WalWriterMain().

◆ LWLockReleaseClearVar()

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

Definition at line 1876 of file lwlock.c.

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

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

Referenced by WALInsertLockRelease().

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 433 of file lwlock.c.

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

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

Referenced by CalculateShmemSize(), and CreateLWLocks().

◆ LWLockUpdateVar()

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

Definition at line 1749 of file lwlock.c.

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

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().

◆ LWLockWaitForVar()

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

Definition at line 1614 of file lwlock.c.

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

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, newval, 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().

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 699 of file lwlock.c.

700 {
701  NamedLWLockTrancheRequest *request;
702 
704  return; /* too late */
705 
706  if (NamedLWLockTrancheRequestArray == NULL)
707  {
712  * sizeof(NamedLWLockTrancheRequest));
713  }
714 
716  {
718 
721  i * sizeof(NamedLWLockTrancheRequest));
723  }
724 
726  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
727  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
728  request->num_lwlocks = num_lwlocks;
730 }
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:227
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
#define NAMEDATALEN
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:222

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

Referenced by _PG_init().

Variable Documentation

◆ MainLWLockArray

PGDLLIMPORT LWLockPadded* MainLWLockArray
extern

◆ NamedLWLockTrancheArray

PGDLLIMPORT NamedLWLockTranche* NamedLWLockTrancheArray
extern

Definition at line 238 of file lwlock.c.

Referenced by CreateLWLocks(), and InitializeLWLocks().

◆ NamedLWLockTrancheRequests