PostgreSQL Source Code  git master
lwlock.c File Reference
#include "postgres.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "pgstat.h"
#include "port/pg_bitutils.h"
#include "postmaster/postmaster.h"
#include "replication/slot.h"
#include "storage/ipc.h"
#include "storage/predicate.h"
#include "storage/proc.h"
#include "storage/proclist.h"
#include "storage/spin.h"
#include "utils/memutils.h"
Include dependency graph for lwlock.c:

Go to the source code of this file.

Data Structures

struct  LWLockHandle
 
struct  NamedLWLockTrancheRequest
 

Macros

#define LW_FLAG_HAS_WAITERS   ((uint32) 1 << 30)
 
#define LW_FLAG_RELEASE_OK   ((uint32) 1 << 29)
 
#define LW_FLAG_LOCKED   ((uint32) 1 << 28)
 
#define LW_VAL_EXCLUSIVE   ((uint32) 1 << 24)
 
#define LW_VAL_SHARED   1
 
#define LW_LOCK_MASK   ((uint32) ((1 << 25)-1))
 
#define LW_SHARED_MASK   ((uint32) ((1 << 24)-1))
 
#define MAX_SIMUL_LWLOCKS   200
 
#define T_NAME(lock)    GetLWTrancheName((lock)->tranche)
 
#define PRINT_LWDEBUG(a, b, c)   ((void)0)
 
#define LOG_LWDEBUG(a, b, c)   ((void)0)
 

Typedefs

typedef struct LWLockHandle LWLockHandle
 
typedef struct NamedLWLockTrancheRequest NamedLWLockTrancheRequest
 

Functions

 StaticAssertDecl (LW_VAL_EXCLUSIVE >(uint32) MAX_BACKENDS, "MAX_BACKENDS too big for lwlock.c")
 
 StaticAssertDecl (lengthof(BuiltinTrancheNames)==LWTRANCHE_FIRST_USER_DEFINED - NUM_INDIVIDUAL_LWLOCKS, "missing entries in BuiltinTrancheNames[]")
 
static void InitializeLWLocks (void)
 
static void LWLockReportWaitStart (LWLock *lock)
 
static void LWLockReportWaitEnd (void)
 
static const char * GetLWTrancheName (uint16 trancheId)
 
static int NumLWLocksForNamedTranches (void)
 
Size LWLockShmemSize (void)
 
void CreateLWLocks (void)
 
void InitLWLockAccess (void)
 
LWLockPaddedGetNamedLWLockTranche (const char *tranche_name)
 
int LWLockNewTrancheId (void)
 
void LWLockRegisterTranche (int tranche_id, const char *tranche_name)
 
void RequestNamedLWLockTranche (const char *tranche_name, int num_lwlocks)
 
void LWLockInitialize (LWLock *lock, int tranche_id)
 
const char * GetLWLockIdentifier (uint32 classId, uint16 eventId)
 
static bool LWLockAttemptLock (LWLock *lock, LWLockMode mode)
 
static void LWLockWaitListLock (LWLock *lock)
 
static void LWLockWaitListUnlock (LWLock *lock)
 
static void LWLockWakeup (LWLock *lock)
 
static void LWLockQueueSelf (LWLock *lock, LWLockMode mode)
 
static void LWLockDequeueSelf (LWLock *lock)
 
bool LWLockAcquire (LWLock *lock, LWLockMode mode)
 
bool LWLockConditionalAcquire (LWLock *lock, LWLockMode mode)
 
bool LWLockAcquireOrWait (LWLock *lock, LWLockMode mode)
 
static bool LWLockConflictsWithVar (LWLock *lock, pg_atomic_uint64 *valptr, uint64 oldval, uint64 *newval, bool *result)
 
bool LWLockWaitForVar (LWLock *lock, pg_atomic_uint64 *valptr, uint64 oldval, uint64 *newval)
 
void LWLockUpdateVar (LWLock *lock, pg_atomic_uint64 *valptr, uint64 val)
 
void LWLockRelease (LWLock *lock)
 
void LWLockReleaseClearVar (LWLock *lock, pg_atomic_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)
 

Variables

slock_tShmemLock
 
const char *const IndividualLWLockNames []
 
static const char *const BuiltinTrancheNames []
 
static const char ** LWLockTrancheNames = NULL
 
static int LWLockTrancheNamesAllocated = 0
 
LWLockPaddedMainLWLockArray = NULL
 
static int num_held_lwlocks = 0
 
static LWLockHandle held_lwlocks [MAX_SIMUL_LWLOCKS]
 
static NamedLWLockTrancheRequestNamedLWLockTrancheRequestArray = NULL
 
static int NamedLWLockTrancheRequestsAllocated = 0
 
int NamedLWLockTrancheRequests = 0
 
NamedLWLockTrancheNamedLWLockTrancheArray = NULL
 

Macro Definition Documentation

◆ LOG_LWDEBUG

#define LOG_LWDEBUG (   a,
  b,
  c 
)    ((void)0)

Definition at line 323 of file lwlock.c.

◆ LW_FLAG_HAS_WAITERS

#define LW_FLAG_HAS_WAITERS   ((uint32) 1 << 30)

Definition at line 100 of file lwlock.c.

◆ LW_FLAG_LOCKED

#define LW_FLAG_LOCKED   ((uint32) 1 << 28)

Definition at line 102 of file lwlock.c.

◆ LW_FLAG_RELEASE_OK

#define LW_FLAG_RELEASE_OK   ((uint32) 1 << 29)

Definition at line 101 of file lwlock.c.

◆ LW_LOCK_MASK

#define LW_LOCK_MASK   ((uint32) ((1 << 25)-1))

Definition at line 107 of file lwlock.c.

◆ LW_SHARED_MASK

#define LW_SHARED_MASK   ((uint32) ((1 << 24)-1))

Definition at line 109 of file lwlock.c.

◆ LW_VAL_EXCLUSIVE

#define LW_VAL_EXCLUSIVE   ((uint32) 1 << 24)

Definition at line 104 of file lwlock.c.

◆ LW_VAL_SHARED

#define LW_VAL_SHARED   1

Definition at line 105 of file lwlock.c.

◆ MAX_SIMUL_LWLOCKS

#define MAX_SIMUL_LWLOCKS   200

Definition at line 220 of file lwlock.c.

◆ PRINT_LWDEBUG

#define PRINT_LWDEBUG (   a,
  b,
  c 
)    ((void)0)

Definition at line 322 of file lwlock.c.

◆ T_NAME

#define T_NAME (   lock)     GetLWTrancheName((lock)->tranche)

Definition at line 258 of file lwlock.c.

Typedef Documentation

◆ LWLockHandle

typedef struct LWLockHandle LWLockHandle

◆ NamedLWLockTrancheRequest

Function Documentation

◆ CreateLWLocks()

void CreateLWLocks ( void  )

Definition at line 474 of file lwlock.c.

475 {
476  if (!IsUnderPostmaster)
477  {
478  Size spaceLocks = LWLockShmemSize();
479  int *LWLockCounter;
480  char *ptr;
481 
482  /* Allocate space */
483  ptr = (char *) ShmemAlloc(spaceLocks);
484 
485  /* Leave room for dynamic allocation of tranches */
486  ptr += sizeof(int);
487 
488  /* Ensure desired alignment of LWLock array */
489  ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
490 
491  MainLWLockArray = (LWLockPadded *) ptr;
492 
493  /*
494  * Initialize the dynamic-allocation counter for tranches, which is
495  * stored just before the first LWLock.
496  */
497  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
498  *LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
499 
500  /* Initialize all LWLocks */
502  }
503 
504  /* Register named extension LWLock tranches in the current process. */
505  for (int i = 0; i < NamedLWLockTrancheRequests; i++)
507  NamedLWLockTrancheArray[i].trancheName);
508 }
size_t Size
Definition: c.h:594
bool IsUnderPostmaster
Definition: globals.c:113
int i
Definition: isn.c:73
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:251
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:651
int NamedLWLockTrancheRequests
Definition: lwlock.c:248
static void InitializeLWLocks(void)
Definition: lwlock.c:514
LWLockPadded * MainLWLockArray
Definition: lwlock.c:212
Size LWLockShmemSize(void)
Definition: lwlock.c:444
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:61
@ LWTRANCHE_FIRST_USER_DEFINED
Definition: lwlock.h:210
void * ShmemAlloc(Size size)
Definition: shmem.c:161

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

Referenced by CreateSharedMemoryAndSemaphores().

◆ GetLWLockIdentifier()

const char* GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 794 of file lwlock.c.

795 {
796  Assert(classId == PG_WAIT_LWLOCK);
797  /* The event IDs are just tranche numbers. */
798  return GetLWTrancheName(eventId);
799 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:766
#define PG_WAIT_LWLOCK
Definition: wait_event.h:18

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

Referenced by pgstat_get_wait_event().

◆ GetLWTrancheName()

static const char * GetLWTrancheName ( uint16  trancheId)
static

Definition at line 766 of file lwlock.c.

767 {
768  /* Individual LWLock? */
769  if (trancheId < NUM_INDIVIDUAL_LWLOCKS)
770  return IndividualLWLockNames[trancheId];
771 
772  /* Built-in tranche? */
773  if (trancheId < LWTRANCHE_FIRST_USER_DEFINED)
774  return BuiltinTrancheNames[trancheId - NUM_INDIVIDUAL_LWLOCKS];
775 
776  /*
777  * It's an extension tranche, so look in LWLockTrancheNames[]. However,
778  * it's possible that the tranche has never been registered in the current
779  * process, in which case give up and return "extension".
780  */
781  trancheId -= LWTRANCHE_FIRST_USER_DEFINED;
782 
783  if (trancheId >= LWLockTrancheNamesAllocated ||
784  LWLockTrancheNames[trancheId] == NULL)
785  return "extension";
786 
787  return LWLockTrancheNames[trancheId];
788 }
static int LWLockTrancheNamesAllocated
Definition: lwlock.c:205
const char *const IndividualLWLockNames[]
static const char *const BuiltinTrancheNames[]
Definition: lwlock.c:134
static const char ** LWLockTrancheNames
Definition: lwlock.c:204

References BuiltinTrancheNames, IndividualLWLockNames, LWLockTrancheNames, LWLockTrancheNamesAllocated, and LWTRANCHE_FIRST_USER_DEFINED.

Referenced by GetLWLockIdentifier().

◆ GetNamedLWLockTranche()

LWLockPadded* GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 597 of file lwlock.c.

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

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

Referenced by pgss_shmem_startup().

◆ InitializeLWLocks()

static void InitializeLWLocks ( void  )
static

Definition at line 514 of file lwlock.c.

515 {
516  int numNamedLocks = NumLWLocksForNamedTranches();
517  int id;
518  int i;
519  int j;
520  LWLockPadded *lock;
521 
522  /* Initialize all individual LWLocks in main array */
523  for (id = 0, lock = MainLWLockArray; id < NUM_INDIVIDUAL_LWLOCKS; id++, lock++)
524  LWLockInitialize(&lock->lock, id);
525 
526  /* Initialize buffer mapping LWLocks in main array */
528  for (id = 0; id < NUM_BUFFER_PARTITIONS; id++, lock++)
530 
531  /* Initialize lmgrs' LWLocks in main array */
533  for (id = 0; id < NUM_LOCK_PARTITIONS; id++, lock++)
535 
536  /* Initialize predicate lmgrs' LWLocks in main array */
538  for (id = 0; id < NUM_PREDICATELOCK_PARTITIONS; id++, lock++)
540 
541  /*
542  * Copy the info about any named tranches into shared memory (so that
543  * other processes can see it), and initialize the requested LWLocks.
544  */
546  {
547  char *trancheNames;
548 
550  &MainLWLockArray[NUM_FIXED_LWLOCKS + numNamedLocks];
551 
552  trancheNames = (char *) NamedLWLockTrancheArray +
555 
556  for (i = 0; i < NamedLWLockTrancheRequests; i++)
557  {
558  NamedLWLockTrancheRequest *request;
559  NamedLWLockTranche *tranche;
560  char *name;
561 
562  request = &NamedLWLockTrancheRequestArray[i];
563  tranche = &NamedLWLockTrancheArray[i];
564 
565  name = trancheNames;
566  trancheNames += strlen(request->tranche_name) + 1;
567  strcpy(name, request->tranche_name);
568  tranche->trancheId = LWLockNewTrancheId();
569  tranche->trancheName = name;
570 
571  for (j = 0; j < request->num_lwlocks; j++, lock++)
572  LWLockInitialize(&lock->lock, tranche->trancheId);
573  }
574  }
575 }
int j
Definition: isn.c:74
int LWLockNewTrancheId(void)
Definition: lwlock.c:627
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:429
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:730
#define BUFFER_MAPPING_LWLOCK_OFFSET
Definition: lwlock.h:106
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:99
@ LWTRANCHE_PREDICATE_LOCK_MANAGER
Definition: lwlock.h:195
@ LWTRANCHE_BUFFER_MAPPING
Definition: lwlock.h:193
@ LWTRANCHE_LOCK_MANAGER
Definition: lwlock.h:194
#define LOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:107
#define NUM_BUFFER_PARTITIONS
Definition: lwlock.h:95
#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:109
#define NUM_PREDICATELOCK_PARTITIONS
Definition: lwlock.h:103
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:235
char * trancheName
Definition: lwlock.h:79
LWLock lock
Definition: lwlock.h:69
const char * name

References BUFFER_MAPPING_LWLOCK_OFFSET, i, j, LWLockPadded::lock, LOCK_MANAGER_LWLOCK_OFFSET, LWLockInitialize(), LWLockNewTrancheId(), LWTRANCHE_BUFFER_MAPPING, LWTRANCHE_LOCK_MANAGER, LWTRANCHE_PREDICATE_LOCK_MANAGER, MainLWLockArray, name, NamedLWLockTrancheArray, NamedLWLockTrancheRequestArray, NamedLWLockTrancheRequests, NUM_BUFFER_PARTITIONS, NUM_FIXED_LWLOCKS, NUM_LOCK_PARTITIONS, NamedLWLockTrancheRequest::num_lwlocks, NUM_PREDICATELOCK_PARTITIONS, NumLWLocksForNamedTranches(), PREDICATELOCK_MANAGER_LWLOCK_OFFSET, NamedLWLockTrancheRequest::tranche_name, NamedLWLockTranche::trancheId, and NamedLWLockTranche::trancheName.

Referenced by CreateLWLocks().

◆ InitLWLockAccess()

void InitLWLockAccess ( void  )

Definition at line 581 of file lwlock.c.

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

Referenced by InitProcess().

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1195 of file lwlock.c.

1196 {
1197  PGPROC *proc = MyProc;
1198  bool result = true;
1199  int extraWaits = 0;
1200 #ifdef LWLOCK_STATS
1201  lwlock_stats *lwstats;
1202 
1203  lwstats = get_lwlock_stats_entry(lock);
1204 #endif
1205 
1207 
1208  PRINT_LWDEBUG("LWLockAcquire", lock, mode);
1209 
1210 #ifdef LWLOCK_STATS
1211  /* Count lock acquisition attempts */
1212  if (mode == LW_EXCLUSIVE)
1213  lwstats->ex_acquire_count++;
1214  else
1215  lwstats->sh_acquire_count++;
1216 #endif /* LWLOCK_STATS */
1217 
1218  /*
1219  * We can't wait if we haven't got a PGPROC. This should only occur
1220  * during bootstrap or shared memory initialization. Put an Assert here
1221  * to catch unsafe coding practices.
1222  */
1223  Assert(!(proc == NULL && IsUnderPostmaster));
1224 
1225  /* Ensure we will have room to remember the lock */
1227  elog(ERROR, "too many LWLocks taken");
1228 
1229  /*
1230  * Lock out cancel/die interrupts until we exit the code section protected
1231  * by the LWLock. This ensures that interrupts will not interfere with
1232  * manipulations of data structures in shared memory.
1233  */
1234  HOLD_INTERRUPTS();
1235 
1236  /*
1237  * Loop here to try to acquire lock after each time we are signaled by
1238  * LWLockRelease.
1239  *
1240  * NOTE: it might seem better to have LWLockRelease actually grant us the
1241  * lock, rather than retrying and possibly having to go back to sleep. But
1242  * in practice that is no good because it means a process swap for every
1243  * lock acquisition when two or more processes are contending for the same
1244  * lock. Since LWLocks are normally used to protect not-very-long
1245  * sections of computation, a process needs to be able to acquire and
1246  * release the same lock many times during a single CPU time slice, even
1247  * in the presence of contention. The efficiency of being able to do that
1248  * outweighs the inefficiency of sometimes wasting a process dispatch
1249  * cycle because the lock is not free when a released waiter finally gets
1250  * to run. See pgsql-hackers archives for 29-Dec-01.
1251  */
1252  for (;;)
1253  {
1254  bool mustwait;
1255 
1256  /*
1257  * Try to grab the lock the first time, we're not in the waitqueue
1258  * yet/anymore.
1259  */
1260  mustwait = LWLockAttemptLock(lock, mode);
1261 
1262  if (!mustwait)
1263  {
1264  LOG_LWDEBUG("LWLockAcquire", lock, "immediately acquired lock");
1265  break; /* got the lock */
1266  }
1267 
1268  /*
1269  * Ok, at this point we couldn't grab the lock on the first try. We
1270  * cannot simply queue ourselves to the end of the list and wait to be
1271  * woken up because by now the lock could long have been released.
1272  * Instead add us to the queue and try to grab the lock again. If we
1273  * succeed we need to revert the queuing and be happy, otherwise we
1274  * recheck the lock. If we still couldn't grab it, we know that the
1275  * other locker will see our queue entries when releasing since they
1276  * existed before we checked for the lock.
1277  */
1278 
1279  /* add to the queue */
1280  LWLockQueueSelf(lock, mode);
1281 
1282  /* we're now guaranteed to be woken up if necessary */
1283  mustwait = LWLockAttemptLock(lock, mode);
1284 
1285  /* ok, grabbed the lock the second time round, need to undo queueing */
1286  if (!mustwait)
1287  {
1288  LOG_LWDEBUG("LWLockAcquire", lock, "acquired, undoing queue");
1289 
1290  LWLockDequeueSelf(lock);
1291  break;
1292  }
1293 
1294  /*
1295  * Wait until awakened.
1296  *
1297  * It is possible that we get awakened for a reason other than being
1298  * signaled by LWLockRelease. If so, loop back and wait again. Once
1299  * we've gotten the LWLock, re-increment the sema by the number of
1300  * additional signals received.
1301  */
1302  LOG_LWDEBUG("LWLockAcquire", lock, "waiting");
1303 
1304 #ifdef LWLOCK_STATS
1305  lwstats->block_count++;
1306 #endif
1307 
1308  LWLockReportWaitStart(lock);
1309  if (TRACE_POSTGRESQL_LWLOCK_WAIT_START_ENABLED())
1310  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), mode);
1311 
1312  for (;;)
1313  {
1314  PGSemaphoreLock(proc->sem);
1315  if (proc->lwWaiting == LW_WS_NOT_WAITING)
1316  break;
1317  extraWaits++;
1318  }
1319 
1320  /* Retrying, allow LWLockRelease to release waiters again. */
1322 
1323 #ifdef LOCK_DEBUG
1324  {
1325  /* not waiting anymore */
1326  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1327 
1328  Assert(nwaiters < MAX_BACKENDS);
1329  }
1330 #endif
1331 
1332  if (TRACE_POSTGRESQL_LWLOCK_WAIT_DONE_ENABLED())
1333  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode);
1335 
1336  LOG_LWDEBUG("LWLockAcquire", lock, "awakened");
1337 
1338  /* Now loop back and try to acquire lock again. */
1339  result = false;
1340  }
1341 
1342  if (TRACE_POSTGRESQL_LWLOCK_ACQUIRE_ENABLED())
1343  TRACE_POSTGRESQL_LWLOCK_ACQUIRE(T_NAME(lock), mode);
1344 
1345  /* Add lock to list of locks held by this backend */
1348 
1349  /*
1350  * Fix the process wait semaphore's count for any absorbed wakeups.
1351  */
1352  while (extraWaits-- > 0)
1353  PGSemaphoreUnlock(proc->sem);
1354 
1355  return result;
1356 }
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
unsigned int uint32
Definition: c.h:495
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:171
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:230
static bool LWLockAttemptLock(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:811
static void LWLockReportWaitEnd(void)
Definition: lwlock.c:757
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:101
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:220
#define T_NAME(lock)
Definition: lwlock.c:258
static int num_held_lwlocks
Definition: lwlock.c:229
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:323
static void LWLockQueueSelf(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1063
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:322
static void LWLockReportWaitStart(LWLock *lock)
Definition: lwlock.c:748
static void LWLockDequeueSelf(LWLock *lock)
Definition: lwlock.c:1106
@ LW_WS_NOT_WAITING
Definition: lwlock.h:29
@ LW_SHARED
Definition: lwlock.h:117
@ LW_EXCLUSIVE
Definition: lwlock.h:116
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
static PgChecksumMode mode
Definition: pg_checksums.c:56
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:320
#define MAX_BACKENDS
Definition: postmaster.h:78
PGPROC * MyProc
Definition: proc.c:66
LWLockMode mode
Definition: lwlock.c:226
LWLock * lock
Definition: lwlock.c:225
pg_atomic_uint32 state
Definition: lwlock.h:43
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(), AtEOXact_LogicalRepWorkers(), 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(), ExtendBufferedRelShared(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), FindAndDropRelationBuffers(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), FlushRelationsAllBuffers(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLeaderApplyWorkerPid(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionData(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), GetWaitEventExtensionIdentifier(), GetWaitEventExtensionNames(), HaveVirtualXIDsDelayingChkpt(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), InvalidatePossiblyObsoleteSlot(), InvalidateVictimBuffer(), IsInstallXLogFileSegmentActive(), KnownAssignedXidsCompress(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockBuffer(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_launcher_attach_dshmem(), logicalrep_pa_worker_stop(), logicalrep_worker_attach(), logicalrep_worker_detach(), logicalrep_worker_launch(), logicalrep_worker_stop(), logicalrep_worker_stop_internal(), logicalrep_worker_wakeup(), LookupGXact(), 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_io(), pgstat_flush_wal(), pgstat_io_reset_all_cb(), pgstat_io_snapshot_cb(), 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_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset(), replorigin_session_setup(), replorigin_state_clear(), 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(), VacuumUpdateCosts(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitEventExtensionNew(), 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 1423 of file lwlock.c.

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

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

References held_lwlocks, i, and num_held_lwlocks.

◆ LWLockAttemptLock()

static bool LWLockAttemptLock ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 811 of file lwlock.c.

812 {
813  uint32 old_state;
814 
816 
817  /*
818  * Read once outside the loop, later iterations will get the newer value
819  * via compare & exchange.
820  */
821  old_state = pg_atomic_read_u32(&lock->state);
822 
823  /* loop until we've determined whether we could acquire the lock or not */
824  while (true)
825  {
826  uint32 desired_state;
827  bool lock_free;
828 
829  desired_state = old_state;
830 
831  if (mode == LW_EXCLUSIVE)
832  {
833  lock_free = (old_state & LW_LOCK_MASK) == 0;
834  if (lock_free)
835  desired_state += LW_VAL_EXCLUSIVE;
836  }
837  else
838  {
839  lock_free = (old_state & LW_VAL_EXCLUSIVE) == 0;
840  if (lock_free)
841  desired_state += LW_VAL_SHARED;
842  }
843 
844  /*
845  * Attempt to swap in the state we are expecting. If we didn't see
846  * lock to be free, that's just the old value. If we saw it as free,
847  * we'll attempt to mark it acquired. The reason that we always swap
848  * in the value is that this doubles as a memory barrier. We could try
849  * to be smarter and only swap in values if we saw the lock as free,
850  * but benchmark haven't shown it as beneficial so far.
851  *
852  * Retry if the value changed since we last looked at it.
853  */
855  &old_state, desired_state))
856  {
857  if (lock_free)
858  {
859  /* Great! Got the lock. */
860 #ifdef LOCK_DEBUG
861  if (mode == LW_EXCLUSIVE)
862  lock->owner = MyProc;
863 #endif
864  return false;
865  }
866  else
867  return true; /* somebody else has the lock */
868  }
869  }
870  pg_unreachable();
871 }
static bool pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 *expected, uint32 newval)
Definition: atomics.h:306
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:236
#define pg_unreachable()
Definition: c.h:285
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:104
#define LW_VAL_SHARED
Definition: lwlock.c:105
#define LW_LOCK_MASK
Definition: lwlock.c:107

References Assert(), LW_EXCLUSIVE, LW_LOCK_MASK, LW_SHARED, LW_VAL_EXCLUSIVE, LW_VAL_SHARED, mode, MyProc, pg_atomic_compare_exchange_u32(), pg_atomic_read_u32(), pg_unreachable, and LWLock::state.

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

◆ LWLockConditionalAcquire()

bool LWLockConditionalAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1366 of file lwlock.c.

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

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

◆ LWLockConflictsWithVar()

static bool LWLockConflictsWithVar ( LWLock lock,
pg_atomic_uint64 valptr,
uint64  oldval,
uint64 *  newval,
bool result 
)
static

Definition at line 1550 of file lwlock.c.

1552 {
1553  bool mustwait;
1554  uint64 value;
1555 
1556  /*
1557  * Test first to see if it the slot is free right now.
1558  *
1559  * XXX: the unique caller of this routine, WaitXLogInsertionsToFinish()
1560  * via LWLockWaitForVar(), uses an implied barrier with a spinlock before
1561  * this, so we don't need a memory barrier here as far as the current
1562  * usage is concerned. But that might not be safe in general.
1563  */
1564  mustwait = (pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE) != 0;
1565 
1566  if (!mustwait)
1567  {
1568  *result = true;
1569  return false;
1570  }
1571 
1572  *result = false;
1573 
1574  /*
1575  * Reading this value atomically is safe even on platforms where uint64
1576  * cannot be read without observing a torn value.
1577  */
1578  value = pg_atomic_read_u64(valptr);
1579 
1580  if (value != oldval)
1581  {
1582  mustwait = false;
1583  *newval = value;
1584  }
1585  else
1586  {
1587  mustwait = true;
1588  }
1589 
1590  return mustwait;
1591 }
static uint64 pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
Definition: atomics.h:424
#define newval
static struct @148 value

References LW_VAL_EXCLUSIVE, newval, pg_atomic_read_u32(), pg_atomic_read_u64(), LWLock::state, and value.

Referenced by LWLockWaitForVar().

◆ LWLockDequeueSelf()

static void LWLockDequeueSelf ( LWLock lock)
static

Definition at line 1106 of file lwlock.c.

1107 {
1108  bool on_waitlist;
1109 
1110 #ifdef LWLOCK_STATS
1111  lwlock_stats *lwstats;
1112 
1113  lwstats = get_lwlock_stats_entry(lock);
1114 
1115  lwstats->dequeue_self_count++;
1116 #endif
1117 
1118  LWLockWaitListLock(lock);
1119 
1120  /*
1121  * Remove ourselves from the waitlist, unless we've already been removed.
1122  * The removal happens with the wait list lock held, so there's no race in
1123  * this check.
1124  */
1125  on_waitlist = MyProc->lwWaiting == LW_WS_WAITING;
1126  if (on_waitlist)
1127  proclist_delete(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1128 
1129  if (proclist_is_empty(&lock->waiters) &&
1130  (pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS) != 0)
1131  {
1133  }
1134 
1135  /* XXX: combine with fetch_and above? */
1136  LWLockWaitListUnlock(lock);
1137 
1138  /* clear waiting state again, nice for debugging */
1139  if (on_waitlist)
1141  else
1142  {
1143  int extraWaits = 0;
1144 
1145  /*
1146  * Somebody else dequeued us and has or will wake us up. Deal with the
1147  * superfluous absorption of a wakeup.
1148  */
1149 
1150  /*
1151  * Reset RELEASE_OK flag if somebody woke us before we removed
1152  * ourselves - they'll have set it to false.
1153  */
1155 
1156  /*
1157  * Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
1158  * get reset at some inconvenient point later. Most of the time this
1159  * will immediately return.
1160  */
1161  for (;;)
1162  {
1165  break;
1166  extraWaits++;
1167  }
1168 
1169  /*
1170  * Fix the process wait semaphore's count for any absorbed wakeups.
1171  */
1172  while (extraWaits-- > 0)
1174  }
1175 
1176 #ifdef LOCK_DEBUG
1177  {
1178  /* not waiting anymore */
1179  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1180 
1181  Assert(nwaiters < MAX_BACKENDS);
1182  }
1183 #endif
1184 }
static uint32 pg_atomic_fetch_and_u32(volatile pg_atomic_uint32 *ptr, uint32 and_)
Definition: atomics.h:353
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:882
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:100
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:934
@ LW_WS_WAITING
Definition: lwlock.h:30
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:187
static bool proclist_is_empty(const proclist_head *list)
Definition: proclist.h:38
proclist_head waiters
Definition: lwlock.h:44
int pgprocno
Definition: proc.h:191

References Assert(), LW_FLAG_HAS_WAITERS, LW_FLAG_RELEASE_OK, LW_WS_NOT_WAITING, LW_WS_WAITING, LWLockWaitListLock(), LWLockWaitListUnlock(), PGPROC::lwWaiting, MAX_BACKENDS, MyProc, pg_atomic_fetch_and_u32(), pg_atomic_fetch_or_u32(), pg_atomic_fetch_sub_u32(), pg_atomic_read_u32(), PG_USED_FOR_ASSERTS_ONLY, PGPROC::pgprocno, PGSemaphoreLock(), PGSemaphoreUnlock(), proclist_delete, proclist_is_empty(), PGPROC::sem, LWLock::state, and LWLock::waiters.

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

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

◆ LWLockInitialize()

void LWLockInitialize ( LWLock lock,
int  tranche_id 
)

Definition at line 730 of file lwlock.c.

731 {
733 #ifdef LOCK_DEBUG
734  pg_atomic_init_u32(&lock->nwaiters, 0);
735 #endif
736  lock->tranche = tranche_id;
737  proclist_init(&lock->waiters);
738 }
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:42

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

628 {
629  int result;
630  int *LWLockCounter;
631 
632  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
634  result = (*LWLockCounter)++;
636 
637  return result;
638 }
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().

◆ LWLockQueueSelf()

static void LWLockQueueSelf ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 1063 of file lwlock.c.

1064 {
1065  /*
1066  * If we don't have a PGPROC structure, there's no way to wait. This
1067  * should never occur, since MyProc should only be null during shared
1068  * memory initialization.
1069  */
1070  if (MyProc == NULL)
1071  elog(PANIC, "cannot wait without a PGPROC structure");
1072 
1074  elog(PANIC, "queueing for lock while waiting on another one");
1075 
1076  LWLockWaitListLock(lock);
1077 
1078  /* setting the flag is protected by the spinlock */
1080 
1082  MyProc->lwWaitMode = mode;
1083 
1084  /* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */
1085  if (mode == LW_WAIT_UNTIL_FREE)
1086  proclist_push_head(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1087  else
1088  proclist_push_tail(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1089 
1090  /* Can release the mutex now */
1091  LWLockWaitListUnlock(lock);
1092 
1093 #ifdef LOCK_DEBUG
1094  pg_atomic_fetch_add_u32(&lock->nwaiters, 1);
1095 #endif
1096 }
static uint32 pg_atomic_fetch_add_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:323
#define PANIC
Definition: elog.h:42
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:191
#define proclist_push_head(list, procno, link_member)
Definition: proclist.h:189
uint8 lwWaitMode
Definition: proc.h:215

References elog(), LW_FLAG_HAS_WAITERS, LW_WAIT_UNTIL_FREE, LW_WS_NOT_WAITING, LW_WS_WAITING, LWLockWaitListLock(), LWLockWaitListUnlock(), PGPROC::lwWaiting, PGPROC::lwWaitMode, mode, MyProc, PANIC, pg_atomic_fetch_add_u32(), pg_atomic_fetch_or_u32(), PGPROC::pgprocno, proclist_push_head, proclist_push_tail, LWLock::state, and LWLock::waiters.

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

◆ LWLockRegisterTranche()

void LWLockRegisterTranche ( int  tranche_id,
const char *  tranche_name 
)

Definition at line 651 of file lwlock.c.

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

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

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

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(), AtEOXact_LogicalRepWorkers(), 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(), ExtendBufferedRelShared(), 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(), GetLeaderApplyWorkerPid(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVictimBuffer(), GetVirtualXIDsDelayingChkpt(), GetWaitEventExtensionIdentifier(), GetWaitEventExtensionNames(), HaveVirtualXIDsDelayingChkpt(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), InvalidatePossiblyObsoleteSlot(), InvalidateVictimBuffer(), IsInstallXLogFileSegmentActive(), KnownAssignedXidsCompress(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockBuffer(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_launcher_attach_dshmem(), logicalrep_pa_worker_stop(), logicalrep_worker_attach(), logicalrep_worker_detach(), logicalrep_worker_launch(), logicalrep_worker_stop(), logicalrep_worker_stop_internal(), logicalrep_worker_wakeup(), LogStandbySnapshot(), LookupGXact(), LWLockReleaseAll(), LWLockReleaseClearVar(), 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_io(), pgstat_flush_wal(), pgstat_io_reset_all_cb(), pgstat_io_snapshot_cb(), 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_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset(), replorigin_session_setup(), replorigin_state_clear(), 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(), VacuumUpdateCosts(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitEventExtensionNew(), WaitForReplicationWorkerAttach(), WaitOnLock(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), XLogNeedsFlush(), XLogReportParameters(), and XLogShutdownWalRcv().

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

Definition at line 1903 of file lwlock.c.

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

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,
pg_atomic_uint64 valptr,
uint64  val 
)

Definition at line 1881 of file lwlock.c.

1882 {
1883  /*
1884  * Note that pg_atomic_exchange_u64 is a full barrier, so we're guaranteed
1885  * that the variable is updated before releasing the lock.
1886  */
1887  pg_atomic_exchange_u64(valptr, val);
1888 
1889  LWLockRelease(lock);
1890 }
static uint64 pg_atomic_exchange_u64(volatile pg_atomic_uint64 *ptr, uint64 newval)
Definition: atomics.h:442
long val
Definition: informix.c:664

References LWLockRelease(), pg_atomic_exchange_u64(), and val.

Referenced by WALInsertLockRelease().

◆ LWLockReportWaitEnd()

static void LWLockReportWaitEnd ( void  )
inlinestatic

Definition at line 757 of file lwlock.c.

758 {
760 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104

References pgstat_report_wait_end().

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

◆ LWLockReportWaitStart()

static void LWLockReportWaitStart ( LWLock lock)
inlinestatic

Definition at line 748 of file lwlock.c.

749 {
751 }
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88

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

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

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 444 of file lwlock.c.

445 {
446  Size size;
447  int i;
448  int numLocks = NUM_FIXED_LWLOCKS;
449 
450  /* Calculate total number of locks needed in the main array. */
451  numLocks += NumLWLocksForNamedTranches();
452 
453  /* Space for the LWLock array. */
454  size = mul_size(numLocks, sizeof(LWLockPadded));
455 
456  /* Space for dynamic allocation counter, plus room for alignment. */
457  size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
458 
459  /* space for named tranches. */
461 
462  /* space for name of each tranche. */
463  for (i = 0; i < NamedLWLockTrancheRequests; i++)
464  size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
465 
466  return size;
467 }
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,
pg_atomic_uint64 valptr,
uint64  val 
)

Definition at line 1747 of file lwlock.c.

1748 {
1750  proclist_mutable_iter iter;
1751 
1752  PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1753 
1754  /*
1755  * Note that pg_atomic_exchange_u64 is a full barrier, so we're guaranteed
1756  * that the variable is updated before waking up waiters.
1757  */
1758  pg_atomic_exchange_u64(valptr, val);
1759 
1761 
1762  LWLockWaitListLock(lock);
1763 
1765 
1766  /*
1767  * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1768  * up. They are always in the front of the queue.
1769  */
1770  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1771  {
1772  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1773 
1774  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1775  break;
1776 
1777  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1778  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1779 
1780  /* see LWLockWakeup() */
1781  Assert(waiter->lwWaiting == LW_WS_WAITING);
1782  waiter->lwWaiting = LW_WS_PENDING_WAKEUP;
1783  }
1784 
1785  /* We are done updating shared state of the lock itself. */
1786  LWLockWaitListUnlock(lock);
1787 
1788  /*
1789  * Awaken any waiters I removed from the queue.
1790  */
1791  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1792  {
1793  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1794 
1795  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1796  /* check comment in LWLockWakeup() about this barrier */
1797  pg_write_barrier();
1798  waiter->lwWaiting = LW_WS_NOT_WAITING;
1799  PGSemaphoreUnlock(waiter->sem);
1800  }
1801 }
#define pg_write_barrier()
Definition: atomics.h:154
@ LW_WS_PENDING_WAKEUP
Definition: lwlock.h:31
#define GetPGProcByNumber(n)
Definition: proc.h:408
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
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_exchange_u64(), 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,
pg_atomic_uint64 valptr,
uint64  oldval,
uint64 *  newval 
)

Definition at line 1611 of file lwlock.c.

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

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

◆ LWLockWaitListLock()

static void LWLockWaitListLock ( LWLock lock)
static

Definition at line 882 of file lwlock.c.

883 {
884  uint32 old_state;
885 #ifdef LWLOCK_STATS
886  lwlock_stats *lwstats;
887  uint32 delays = 0;
888 
889  lwstats = get_lwlock_stats_entry(lock);
890 #endif
891 
892  while (true)
893  {
894  /* always try once to acquire lock directly */
895  old_state = pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_LOCKED);
896  if (!(old_state & LW_FLAG_LOCKED))
897  break; /* got lock */
898 
899  /* and then spin without atomic operations until lock is released */
900  {
901  SpinDelayStatus delayStatus;
902 
903  init_local_spin_delay(&delayStatus);
904 
905  while (old_state & LW_FLAG_LOCKED)
906  {
907  perform_spin_delay(&delayStatus);
908  old_state = pg_atomic_read_u32(&lock->state);
909  }
910 #ifdef LWLOCK_STATS
911  delays += delayStatus.delays;
912 #endif
913  finish_spin_delay(&delayStatus);
914  }
915 
916  /*
917  * Retry. The lock might obviously already be re-acquired by the time
918  * we're attempting to get it again.
919  */
920  }
921 
922 #ifdef LWLOCK_STATS
923  lwstats->spin_delay_count += delays;
924 #endif
925 }
#define LW_FLAG_LOCKED
Definition: lwlock.c:102
void perform_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:126
void finish_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:186
#define init_local_spin_delay(status)
Definition: s_lock.h:863

References SpinDelayStatus::delays, finish_spin_delay(), init_local_spin_delay, LW_FLAG_LOCKED, perform_spin_delay(), pg_atomic_fetch_or_u32(), pg_atomic_read_u32(), and LWLock::state.

Referenced by LWLockDequeueSelf(), LWLockQueueSelf(), LWLockUpdateVar(), and LWLockWakeup().

◆ LWLockWaitListUnlock()

static void LWLockWaitListUnlock ( LWLock lock)
static

Definition at line 934 of file lwlock.c.

935 {
937 
938  old_state = pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_LOCKED);
939 
940  Assert(old_state & LW_FLAG_LOCKED);
941 }

References Assert(), LW_FLAG_LOCKED, pg_atomic_fetch_and_u32(), PG_USED_FOR_ASSERTS_ONLY, and LWLock::state.

Referenced by LWLockDequeueSelf(), LWLockQueueSelf(), and LWLockUpdateVar().

◆ LWLockWakeup()

static void LWLockWakeup ( LWLock lock)
static

Definition at line 947 of file lwlock.c.

948 {
949  bool new_release_ok;
950  bool wokeup_somebody = false;
953 
955 
956  new_release_ok = true;
957 
958  /* lock wait list while collecting backends to wake up */
959  LWLockWaitListLock(lock);
960 
961  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
962  {
963  PGPROC *waiter = GetPGProcByNumber(iter.cur);
964 
965  if (wokeup_somebody && waiter->lwWaitMode == LW_EXCLUSIVE)
966  continue;
967 
968  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
969  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
970 
971  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
972  {
973  /*
974  * Prevent additional wakeups until retryer gets to run. Backends
975  * that are just waiting for the lock to become free don't retry
976  * automatically.
977  */
978  new_release_ok = false;
979 
980  /*
981  * Don't wakeup (further) exclusive locks.
982  */
983  wokeup_somebody = true;
984  }
985 
986  /*
987  * Signal that the process isn't on the wait list anymore. This allows
988  * LWLockDequeueSelf() to remove itself of the waitlist with a
989  * proclist_delete(), rather than having to check if it has been
990  * removed from the list.
991  */
992  Assert(waiter->lwWaiting == LW_WS_WAITING);
994 
995  /*
996  * Once we've woken up an exclusive lock, there's no point in waking
997  * up anybody else.
998  */
999  if (waiter->lwWaitMode == LW_EXCLUSIVE)
1000  break;
1001  }
1002 
1004 
1005  /* unset required flags, and release lock, in one fell swoop */
1006  {
1007  uint32 old_state;
1008  uint32 desired_state;
1009 
1010  old_state = pg_atomic_read_u32(&lock->state);
1011  while (true)
1012  {
1013  desired_state = old_state;
1014 
1015  /* compute desired flags */
1016 
1017  if (new_release_ok)
1018  desired_state |= LW_FLAG_RELEASE_OK;
1019  else
1020  desired_state &= ~LW_FLAG_RELEASE_OK;
1021 
1022  if (proclist_is_empty(&wakeup))
1023  desired_state &= ~LW_FLAG_HAS_WAITERS;
1024 
1025  desired_state &= ~LW_FLAG_LOCKED; /* release lock */
1026 
1027  if (pg_atomic_compare_exchange_u32(&lock->state, &old_state,
1028  desired_state))
1029  break;
1030  }
1031  }
1032 
1033  /* Awaken any waiters I removed from the queue. */
1034  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1035  {
1036  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1037 
1038  LOG_LWDEBUG("LWLockRelease", lock, "release waiter");
1039  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1040 
1041  /*
1042  * Guarantee that lwWaiting being unset only becomes visible once the
1043  * unlink from the link has completed. Otherwise the target backend
1044  * could be woken up for other reason and enqueue for a new lock - if
1045  * that happens before the list unlink happens, the list would end up
1046  * being corrupted.
1047  *
1048  * The barrier pairs with the LWLockWaitListLock() when enqueuing for
1049  * another lock.
1050  */
1051  pg_write_barrier();
1052  waiter->lwWaiting = LW_WS_NOT_WAITING;
1053  PGSemaphoreUnlock(waiter->sem);
1054  }
1055 }

References Assert(), proclist_mutable_iter::cur, GetPGProcByNumber, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_HAS_WAITERS, LW_FLAG_LOCKED, LW_FLAG_RELEASE_OK, LW_WAIT_UNTIL_FREE, LW_WS_NOT_WAITING, LW_WS_PENDING_WAKEUP, LW_WS_WAITING, LWLockWaitListLock(), PGPROC::lwWaiting, PGPROC::lwWaitMode, pg_atomic_compare_exchange_u32(), pg_atomic_read_u32(), pg_write_barrier, PGSemaphoreUnlock(), proclist_delete, proclist_foreach_modify, proclist_init(), proclist_is_empty(), proclist_push_tail, PGPROC::sem, LWLock::state, LWLock::waiters, and wakeup.

Referenced by LWLockRelease().

◆ NumLWLocksForNamedTranches()

static int NumLWLocksForNamedTranches ( void  )
static

Definition at line 429 of file lwlock.c.

430 {
431  int numLocks = 0;
432  int i;
433 
434  for (i = 0; i < NamedLWLockTrancheRequests; i++)
435  numLocks += NamedLWLockTrancheRequestArray[i].num_lwlocks;
436 
437  return numLocks;
438 }

References i, NamedLWLockTrancheRequestArray, and NamedLWLockTrancheRequests.

Referenced by InitializeLWLocks(), and LWLockShmemSize().

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 693 of file lwlock.c.

694 {
695  NamedLWLockTrancheRequest *request;
696 
698  elog(FATAL, "cannot request additional LWLocks outside shmem_request_hook");
699 
700  if (NamedLWLockTrancheRequestArray == NULL)
701  {
706  * sizeof(NamedLWLockTrancheRequest));
707  }
708 
710  {
712 
715  i * sizeof(NamedLWLockTrancheRequest));
717  }
718 
720  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
721  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
722  request->num_lwlocks = num_lwlocks;
724 }
#define FATAL
Definition: elog.h:41
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:240
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1476
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1021
bool process_shmem_requests_in_progress
Definition: miscinit.c:1768
#define NAMEDATALEN
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45

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

◆ StaticAssertDecl() [1/2]

StaticAssertDecl ( lengthof(BuiltinTrancheNames = =LWTRANCHE_FIRST_USER_DEFINED - NUM_INDIVIDUAL_LWLOCKS,
"missing entries in BuiltinTrancheNames [] 
)

◆ StaticAssertDecl() [2/2]

StaticAssertDecl ( LW_VAL_EXCLUSIVE  ,
(uint32 MAX_BACKENDS,
"MAX_BACKENDS too big for lwlock.c  
)

Variable Documentation

◆ BuiltinTrancheNames

const char* const BuiltinTrancheNames[]
static

Definition at line 134 of file lwlock.c.

Referenced by GetLWTrancheName().

◆ held_lwlocks

◆ IndividualLWLockNames

const char* const IndividualLWLockNames[]
extern

Referenced by GetLWTrancheName().

◆ LWLockTrancheNames

const char** LWLockTrancheNames = NULL
static

Definition at line 204 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ LWLockTrancheNamesAllocated

int LWLockTrancheNamesAllocated = 0
static

Definition at line 205 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ MainLWLockArray

◆ NamedLWLockTrancheArray

NamedLWLockTranche* NamedLWLockTrancheArray = NULL

Definition at line 251 of file lwlock.c.

Referenced by CreateLWLocks(), and InitializeLWLocks().

◆ NamedLWLockTrancheRequestArray

NamedLWLockTrancheRequest* NamedLWLockTrancheRequestArray = NULL
static

◆ NamedLWLockTrancheRequests

int NamedLWLockTrancheRequests = 0

◆ NamedLWLockTrancheRequestsAllocated

int NamedLWLockTrancheRequestsAllocated = 0
static

Definition at line 240 of file lwlock.c.

Referenced by RequestNamedLWLockTranche().

◆ num_held_lwlocks

◆ ShmemLock

slock_t* ShmemLock
extern

Definition at line 88 of file shmem.c.

Referenced by InitShmemAllocation(), LWLockNewTrancheId(), and ShmemAllocRaw().