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 enum LWLockWaitState LWLockWaitState
 
typedef struct LWLock LWLock
 
typedef union LWLockPadded LWLockPadded
 
typedef struct NamedLWLockTranche NamedLWLockTranche
 
typedef enum LWLockMode LWLockMode
 
typedef enum BuiltinTrancheIds BuiltinTrancheIds
 
typedef LWLockLWLockId
 

Enumerations

enum  LWLockWaitState { LW_WS_NOT_WAITING , LW_WS_WAITING , LW_WS_PENDING_WAKEUP }
 
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_PGSTATS_DSA , LWTRANCHE_PGSTATS_HASH , LWTRANCHE_PGSTATS_DATA , 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 LWLockAnyHeldByMe (LWLock *lock, int nlocks, size_t stride)
 
bool LWLockHeldByMeInMode (LWLock *lock, LWLockMode mode)
 
bool LWLockWaitForVar (LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval)
 
void LWLockUpdateVar (LWLock *lock, uint64 *valptr, uint64 val)
 
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 102 of file lwlock.h.

◆ LOCK_MANAGER_LWLOCK_OFFSET

#define LOCK_MANAGER_LWLOCK_OFFSET    (BUFFER_MAPPING_LWLOCK_OFFSET + NUM_BUFFER_PARTITIONS)

Definition at line 103 of file lwlock.h.

◆ LOG2_NUM_LOCK_PARTITIONS

#define LOG2_NUM_LOCK_PARTITIONS   4

Definition at line 94 of file lwlock.h.

◆ LOG2_NUM_PREDICATELOCK_PARTITIONS

#define LOG2_NUM_PREDICATELOCK_PARTITIONS   4

Definition at line 98 of file lwlock.h.

◆ LWLOCK_PADDED_SIZE

#define LWLOCK_PADDED_SIZE   PG_CACHE_LINE_SIZE

Definition at line 60 of file lwlock.h.

◆ NUM_BUFFER_PARTITIONS

#define NUM_BUFFER_PARTITIONS   128

Definition at line 91 of file lwlock.h.

◆ NUM_FIXED_LWLOCKS

Definition at line 107 of file lwlock.h.

◆ NUM_LOCK_PARTITIONS

#define NUM_LOCK_PARTITIONS   (1 << LOG2_NUM_LOCK_PARTITIONS)

Definition at line 95 of file lwlock.h.

◆ NUM_PREDICATELOCK_PARTITIONS

#define NUM_PREDICATELOCK_PARTITIONS   (1 << LOG2_NUM_PREDICATELOCK_PARTITIONS)

Definition at line 99 of file lwlock.h.

◆ PREDICATELOCK_MANAGER_LWLOCK_OFFSET

#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET    (LOCK_MANAGER_LWLOCK_OFFSET + NUM_LOCK_PARTITIONS)

Definition at line 105 of file lwlock.h.

Typedef Documentation

◆ BuiltinTrancheIds

◆ LWLock

typedef struct LWLock LWLock

◆ LWLockId

typedef LWLock* LWLockId

Definition at line 212 of file lwlock.h.

◆ LWLockMode

typedef enum LWLockMode LWLockMode

◆ LWLockPadded

typedef union LWLockPadded LWLockPadded

◆ LWLockWaitState

◆ 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_PGSTATS_DSA 
LWTRANCHE_PGSTATS_HASH 
LWTRANCHE_PGSTATS_DATA 
LWTRANCHE_FIRST_USER_DEFINED 

Definition at line 175 of file lwlock.h.

176 {
177  LWTRANCHE_XACT_BUFFER = NUM_INDIVIDUAL_LWLOCKS,
BuiltinTrancheIds
Definition: lwlock.h:176
@ LWTRANCHE_FIRST_USER_DEFINED
Definition: lwlock.h:204
@ LWTRANCHE_SHARED_TIDBITMAP
Definition: lwlock.h:198
@ LWTRANCHE_PER_SESSION_DSA
Definition: lwlock.h:194
@ LWTRANCHE_PARALLEL_QUERY_DSA
Definition: lwlock.h:193
@ LWTRANCHE_COMMITTS_BUFFER
Definition: lwlock.h:178
@ LWTRANCHE_PGSTATS_HASH
Definition: lwlock.h:202
@ LWTRANCHE_SUBTRANS_BUFFER
Definition: lwlock.h:179
@ LWTRANCHE_PER_SESSION_RECORD_TYPMOD
Definition: lwlock.h:196
@ LWTRANCHE_XACT_BUFFER
Definition: lwlock.h:177
@ LWTRANCHE_REPLICATION_ORIGIN_STATE
Definition: lwlock.h:186
@ LWTRANCHE_PARALLEL_APPEND
Definition: lwlock.h:199
@ LWTRANCHE_REPLICATION_SLOT_IO
Definition: lwlock.h:187
@ LWTRANCHE_BUFFER_CONTENT
Definition: lwlock.h:185
@ LWTRANCHE_MULTIXACTMEMBER_BUFFER
Definition: lwlock.h:181
@ LWTRANCHE_NOTIFY_BUFFER
Definition: lwlock.h:182
@ LWTRANCHE_PER_SESSION_RECORD_TYPE
Definition: lwlock.h:195
@ LWTRANCHE_PREDICATE_LOCK_MANAGER
Definition: lwlock.h:191
@ LWTRANCHE_BUFFER_MAPPING
Definition: lwlock.h:189
@ LWTRANCHE_SERIAL_BUFFER
Definition: lwlock.h:183
@ LWTRANCHE_PGSTATS_DSA
Definition: lwlock.h:201
@ LWTRANCHE_PARALLEL_HASH_JOIN
Definition: lwlock.h:192
@ LWTRANCHE_PGSTATS_DATA
Definition: lwlock.h:203
@ LWTRANCHE_PER_XACT_PREDICATE_LIST
Definition: lwlock.h:200
@ LWTRANCHE_MULTIXACTOFFSET_BUFFER
Definition: lwlock.h:180
@ LWTRANCHE_WAL_INSERT
Definition: lwlock.h:184
@ LWTRANCHE_LOCK_MANAGER
Definition: lwlock.h:190
@ LWTRANCHE_SHARED_TUPLESTORE
Definition: lwlock.h:197
@ LWTRANCHE_LOCK_FASTPATH
Definition: lwlock.h:188

◆ LWLockMode

enum LWLockMode
Enumerator
LW_EXCLUSIVE 
LW_SHARED 
LW_WAIT_UNTIL_FREE 

Definition at line 110 of file lwlock.h.

111 {
112  LW_EXCLUSIVE,
113  LW_SHARED,
114  LW_WAIT_UNTIL_FREE /* A special mode used in PGPROC->lwWaitMode,
115  * when waiting for lock to become free. Not
116  * to be used as LWLockAcquire argument */
117 } LWLockMode;
LWLockMode
Definition: lwlock.h:111
@ LW_SHARED
Definition: lwlock.h:113
@ LW_WAIT_UNTIL_FREE
Definition: lwlock.h:114
@ LW_EXCLUSIVE
Definition: lwlock.h:112

◆ LWLockWaitState

Enumerator
LW_WS_NOT_WAITING 
LW_WS_WAITING 
LW_WS_PENDING_WAKEUP 

Definition at line 27 of file lwlock.h.

28 {
29  LW_WS_NOT_WAITING, /* not currently waiting / woken up */
30  LW_WS_WAITING, /* currently waiting */
31  LW_WS_PENDING_WAKEUP, /* removed from waitlist, but not yet signalled */
LWLockWaitState
Definition: lwlock.h:28
@ LW_WS_NOT_WAITING
Definition: lwlock.h:29
@ LW_WS_WAITING
Definition: lwlock.h:30
@ LW_WS_PENDING_WAKEUP
Definition: lwlock.h:31

Function Documentation

◆ CreateLWLocks()

void CreateLWLocks ( void  )

Definition at line 467 of file lwlock.c.

468 {
470  "MAX_BACKENDS too big for lwlock.c");
471 
473  "Miscalculated LWLock padding");
474 
475  if (!IsUnderPostmaster)
476  {
477  Size spaceLocks = LWLockShmemSize();
478  int *LWLockCounter;
479  char *ptr;
480 
481  /* Allocate space */
482  ptr = (char *) ShmemAlloc(spaceLocks);
483 
484  /* Leave room for dynamic allocation of tranches */
485  ptr += sizeof(int);
486 
487  /* Ensure desired alignment of LWLock array */
488  ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
489 
490  MainLWLockArray = (LWLockPadded *) ptr;
491 
492  /*
493  * Initialize the dynamic-allocation counter for tranches, which is
494  * stored just before the first LWLock.
495  */
496  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
497  *LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
498 
499  /* Initialize all LWLocks */
501  }
502 
503  /* Register named extension LWLock tranches in the current process. */
504  for (int i = 0; i < NamedLWLockTrancheRequests; i++)
506  NamedLWLockTrancheArray[i].trancheName);
507 }
unsigned int uint32
Definition: c.h:442
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:869
size_t Size
Definition: c.h:541
bool IsUnderPostmaster
Definition: globals.c:113
int i
Definition: isn.c:73
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:104
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:244
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:650
int NamedLWLockTrancheRequests
Definition: lwlock.c:241
static void InitializeLWLocks(void)
Definition: lwlock.c:513
LWLockPadded * MainLWLockArray
Definition: lwlock.c:205
Size LWLockShmemSize(void)
Definition: lwlock.c:437
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:60
#define MAX_BACKENDS
Definition: postmaster.h:77
void * ShmemAlloc(Size size)
Definition: shmem.c:161
Definition: lwlock.h:40

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 793 of file lwlock.c.

794 {
795  Assert(classId == PG_WAIT_LWLOCK);
796  /* The event IDs are just tranche numbers. */
797  return GetLWTrancheName(eventId);
798 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:765
#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 596 of file lwlock.c.

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

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 580 of file lwlock.c.

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

Referenced by InitProcess().

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1194 of file lwlock.c.

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

References Assert(), elog(), ERROR, held_lwlocks, HOLD_INTERRUPTS, IsUnderPostmaster, LWLockHandle::lock, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_RELEASE_OK, LW_SHARED, LW_WS_NOT_WAITING, 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(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), 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_backup_start(), do_pg_backup_stop(), 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(), dshash_seq_next(), 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(), FindAndDropRelationBuffers(), 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(), IsInstallXLogFileSegmentActive(), KnownAssignedXidsCompress(), 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(), 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(), pgstat_archiver_reset_all_cb(), pgstat_archiver_snapshot_cb(), pgstat_bgwriter_reset_all_cb(), pgstat_bgwriter_snapshot_cb(), pgstat_build_snapshot(), pgstat_checkpointer_reset_all_cb(), pgstat_checkpointer_snapshot_cb(), pgstat_flush_wal(), pgstat_lock_entry(), pgstat_lock_entry_shared(), pgstat_reset_matching_entries(), pgstat_reset_slru_counter_internal(), pgstat_slru_flush(), pgstat_slru_snapshot_cb(), pgstat_wal_reset_all_cb(), pgstat_wal_snapshot_cb(), 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(), ReachedEndOfBackup(), read_relmap_file(), ReadBuffer_common(), ReadMultiXactCounts(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadReplicationSlot(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePreInvalidate(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), relmap_redo(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDropPtr(), ReplicationSlotName(), 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(), SetInstallXLogFileSegmentActive(), 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(), SwitchIntoArchiveRecovery(), SyncOneBuffer(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateOtherDBBackends(), test_slru_page_exists(), test_slru_page_read(), test_slru_page_write(), 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(), 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 1422 of file lwlock.c.

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

References Assert(), elog(), ERROR, held_lwlocks, HOLD_INTERRUPTS, LWLockHandle::lock, LOG_LWDEBUG, LW_EXCLUSIVE, LW_SHARED, LW_WAIT_UNTIL_FREE, LW_WS_NOT_WAITING, 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().

◆ LWLockAnyHeldByMe()

bool LWLockAnyHeldByMe ( LWLock lock,
int  nlocks,
size_t  stride 
)

Definition at line 1936 of file lwlock.c.

1937 {
1938  char *held_lock_addr;
1939  char *begin;
1940  char *end;
1941  int i;
1942 
1943  begin = (char *) lock;
1944  end = begin + nlocks * stride;
1945  for (i = 0; i < num_held_lwlocks; i++)
1946  {
1947  held_lock_addr = (char *) held_lwlocks[i].lock;
1948  if (held_lock_addr >= begin &&
1949  held_lock_addr < end &&
1950  (held_lock_addr - begin) % stride == 0)
1951  return true;
1952  }
1953  return false;
1954 }

References held_lwlocks, i, and num_held_lwlocks.

◆ LWLockConditionalAcquire()

bool LWLockConditionalAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1365 of file lwlock.c.

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

References Assert(), 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(), pgstat_flush_wal(), pgstat_lock_entry(), pgstat_lock_entry_shared(), pgstat_slru_flush(), ProcArrayEndTransaction(), SimpleLruWaitIO(), ss_report_location(), TransactionIdSetPageStatus(), and XLogNeedsFlush().

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

◆ LWLockInitialize()

void LWLockInitialize ( LWLock lock,
int  tranche_id 
)

Definition at line 729 of file lwlock.c.

730 {
732 #ifdef LOCK_DEBUG
733  pg_atomic_init_u32(&lock->nwaiters, 0);
734 #endif
735  lock->tranche = tranche_id;
736  proclist_init(&lock->waiters);
737 }
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:218
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
uint16 tranche
Definition: lwlock.h:41
proclist_head waiters
Definition: lwlock.h:43

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(), pgstat_init_entry(), ReplicationOriginShmemInit(), ReplicationSlotsShmemInit(), SimpleLruInit(), StatsShmemInit(), sts_initialize(), tbm_prepare_shared_iterate(), test_slru_shmem_startup(), and XLOGShmemInit().

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( void  )

Definition at line 626 of file lwlock.c.

627 {
628  int result;
629  int *LWLockCounter;
630 
631  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
633  result = (*LWLockCounter)++;
635 
636  return result;
637 }
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(), InitializeLWLocks(), and test_slru_shmem_startup().

◆ LWLockRegisterTranche()

void LWLockRegisterTranche ( int  tranche_id,
const char *  tranche_name 
)

Definition at line 650 of file lwlock.c.

651 {
652  /* This should only be called for user-defined tranches. */
653  if (tranche_id < LWTRANCHE_FIRST_USER_DEFINED)
654  return;
655 
656  /* Convert to array index. */
657  tranche_id -= LWTRANCHE_FIRST_USER_DEFINED;
658 
659  /* If necessary, create or enlarge array. */
660  if (tranche_id >= LWLockTrancheNamesAllocated)
661  {
662  int newalloc;
663 
664  newalloc = pg_nextpower2_32(Max(8, tranche_id + 1));
665 
666  if (LWLockTrancheNames == NULL)
667  LWLockTrancheNames = (const char **)
669  newalloc * sizeof(char *));
670  else
673  LWLockTrancheNamesAllocated = newalloc;
674  }
675 
676  LWLockTrancheNames[tranche_id] = tranche_name;
677 }
#define Max(x, y)
Definition: c.h:931
static int LWLockTrancheNamesAllocated
Definition: lwlock.c:198
static const char ** LWLockTrancheNames
Definition: lwlock.c:197
MemoryContext TopMemoryContext
Definition: mcxt.c:130
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1037
#define repalloc0_array(pointer, type, oldcount, count)
Definition: palloc.h:107
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:140

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

Referenced by apw_init_shmem(), CreateLWLocks(), and test_slru_shmem_startup().

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1802 of file lwlock.c.

1803 {
1804  LWLockMode mode;
1805  uint32 oldstate;
1806  bool check_waiters;
1807  int i;
1808 
1809  /*
1810  * Remove lock from list of locks held. Usually, but not always, it will
1811  * be the latest-acquired lock; so search array backwards.
1812  */
1813  for (i = num_held_lwlocks; --i >= 0;)
1814  if (lock == held_lwlocks[i].lock)
1815  break;
1816 
1817  if (i < 0)
1818  elog(ERROR, "lock %s is not held", T_NAME(lock));
1819 
1820  mode = held_lwlocks[i].mode;
1821 
1822  num_held_lwlocks--;
1823  for (; i < num_held_lwlocks; i++)
1824  held_lwlocks[i] = held_lwlocks[i + 1];
1825 
1826  PRINT_LWDEBUG("LWLockRelease", lock, mode);
1827 
1828  /*
1829  * Release my hold on lock, after that it can immediately be acquired by
1830  * others, even if we still have to wakeup other waiters.
1831  */
1832  if (mode == LW_EXCLUSIVE)
1833  oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_EXCLUSIVE);
1834  else
1835  oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_SHARED);
1836 
1837  /* nobody else can have that kind of lock */
1838  Assert(!(oldstate & LW_VAL_EXCLUSIVE));
1839 
1840  if (TRACE_POSTGRESQL_LWLOCK_RELEASE_ENABLED())
1841  TRACE_POSTGRESQL_LWLOCK_RELEASE(T_NAME(lock));
1842 
1843  /*
1844  * We're still waiting for backends to get scheduled, don't wake them up
1845  * again.
1846  */
1847  if ((oldstate & (LW_FLAG_HAS_WAITERS | LW_FLAG_RELEASE_OK)) ==
1849  (oldstate & LW_LOCK_MASK) == 0)
1850  check_waiters = true;
1851  else
1852  check_waiters = false;
1853 
1854  /*
1855  * As waking up waiters requires the spinlock to be acquired, only do so
1856  * if necessary.
1857  */
1858  if (check_waiters)
1859  {
1860  /* XXX: remove before commit? */
1861  LOG_LWDEBUG("LWLockRelease", lock, "releasing waiters");
1862  LWLockWakeup(lock);
1863  }
1864 
1865  /*
1866  * Now okay to allow cancel/die interrupts.
1867  */
1869 }
static uint32 pg_atomic_sub_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:396
static void LWLockWakeup(LWLock *lock)
Definition: lwlock.c:946
#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(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), 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_backup_start(), do_pg_backup_stop(), 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(), dshash_seq_next(), dshash_seq_term(), 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(), FindAndDropRelationBuffers(), 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(), IsInstallXLogFileSegmentActive(), KnownAssignedXidsCompress(), 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(), 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(), pgstat_archiver_reset_all_cb(), pgstat_archiver_snapshot_cb(), pgstat_bgwriter_reset_all_cb(), pgstat_bgwriter_snapshot_cb(), pgstat_build_snapshot(), pgstat_checkpointer_reset_all_cb(), pgstat_checkpointer_snapshot_cb(), pgstat_flush_wal(), pgstat_reset_matching_entries(), pgstat_reset_slru_counter_internal(), pgstat_slru_flush(), pgstat_slru_snapshot_cb(), pgstat_unlock_entry(), pgstat_wal_reset_all_cb(), pgstat_wal_snapshot_cb(), 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(), ReachedEndOfBackup(), read_relmap_file(), ReadMultiXactCounts(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadReplicationSlot(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePostInvalidate(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), relmap_redo(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDropPtr(), ReplicationSlotName(), 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(), SetInstallXLogFileSegmentActive(), 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(), SwitchIntoArchiveRecovery(), SyncOneBuffer(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateOtherDBBackends(), test_slru_page_exists(), test_slru_page_read(), test_slru_page_readonly(), test_slru_page_write(), 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(), WaitOnLock(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), XLogNeedsFlush(), XLogReportParameters(), and XLogShutdownWalRcv().

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

Definition at line 1901 of file lwlock.c.

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

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 1875 of file lwlock.c.

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

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

Referenced by WALInsertLockRelease().

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 437 of file lwlock.c.

438 {
439  Size size;
440  int i;
441  int numLocks = NUM_FIXED_LWLOCKS;
442 
443  /* Calculate total number of locks needed in the main array. */
444  numLocks += NumLWLocksForNamedTranches();
445 
446  /* Space for the LWLock array. */
447  size = mul_size(numLocks, sizeof(LWLockPadded));
448 
449  /* Space for dynamic allocation counter, plus room for alignment. */
450  size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
451 
452  /* space for named tranches. */
454 
455  /* space for name of each tranche. */
456  for (i = 0; i < NamedLWLockTrancheRequests; i++)
457  size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
458 
459  return size;
460 }
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:422
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, 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  val 
)

Definition at line 1744 of file lwlock.c.

1745 {
1747  proclist_mutable_iter iter;
1748 
1749  PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1750 
1752 
1753  LWLockWaitListLock(lock);
1754 
1756 
1757  /* Update the lock's value */
1758  *valptr = val;
1759 
1760  /*
1761  * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1762  * up. They are always in the front of the queue.
1763  */
1764  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1765  {
1766  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1767 
1768  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1769  break;
1770 
1771  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1772  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1773 
1774  /* see LWLockWakeup() */
1775  Assert(waiter->lwWaiting == LW_WS_WAITING);
1776  waiter->lwWaiting = LW_WS_PENDING_WAKEUP;
1777  }
1778 
1779  /* We are done updating shared state of the lock itself. */
1780  LWLockWaitListUnlock(lock);
1781 
1782  /*
1783  * Awaken any waiters I removed from the queue.
1784  */
1785  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1786  {
1787  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1788 
1789  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1790  /* check comment in LWLockWakeup() about this barrier */
1791  pg_write_barrier();
1792  waiter->lwWaiting = LW_WS_NOT_WAITING;
1793  PGSemaphoreUnlock(waiter->sem);
1794  }
1795 }
#define pg_write_barrier()
Definition: atomics.h:154
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:236
#define GetPGProcByNumber(n)
Definition: proc.h:408
#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:215
static TimestampTz wakeup[NUM_WALRCV_WAKEUPS]
Definition: walreceiver.c:132

References Assert(), proclist_mutable_iter::cur, GetPGProcByNumber, LW_EXCLUSIVE, LW_VAL_EXCLUSIVE, LW_WAIT_UNTIL_FREE, LW_WS_NOT_WAITING, LW_WS_PENDING_WAKEUP, LW_WS_WAITING, 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, LWLock::waiters, and wakeup.

Referenced by WALInsertLockAcquireExclusive(), and WALInsertLockUpdateInsertingAt().

◆ LWLockWaitForVar()

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

Definition at line 1609 of file lwlock.c.

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

References Assert(), HOLD_INTERRUPTS, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_RELEASE_OK, LW_WAIT_UNTIL_FREE, LW_WS_NOT_WAITING, 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 692 of file lwlock.c.

693 {
694  NamedLWLockTrancheRequest *request;
695 
697  elog(FATAL, "cannot request additional LWLocks outside shmem_request_hook");
698 
699  if (NamedLWLockTrancheRequestArray == NULL)
700  {
705  * sizeof(NamedLWLockTrancheRequest));
706  }
707 
709  {
711 
714  i * sizeof(NamedLWLockTrancheRequest));
716  }
717 
719  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
720  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
721  request->num_lwlocks = num_lwlocks;
723 }
#define FATAL
Definition: elog.h:41
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:233
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1321
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:994
bool process_shmem_requests_in_progress
Definition: miscinit.c:1769
#define NAMEDATALEN
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:228

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

Referenced by pgss_shmem_request().

Variable Documentation

◆ MainLWLockArray

◆ NamedLWLockTrancheArray

PGDLLIMPORT NamedLWLockTranche* NamedLWLockTrancheArray
extern

Definition at line 244 of file lwlock.c.

Referenced by CreateLWLocks(), and InitializeLWLocks().

◆ NamedLWLockTrancheRequests