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 (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, uint64 *valptr, uint64 oldval, uint64 *newval, bool *result)
 
bool LWLockWaitForVar (LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval)
 
void LWLockUpdateVar (LWLock *lock, uint64 *valptr, uint64 val)
 
void LWLockRelease (LWLock *lock)
 
void LWLockReleaseClearVar (LWLock *lock, uint64 *valptr, uint64 val)
 
void LWLockReleaseAll (void)
 
bool LWLockHeldByMe (LWLock *l)
 
bool LWLockHeldByMeInMode (LWLock *l, LWLockMode mode)
 
int LWLockHeldCount (void)
 

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

◆ PRINT_LWDEBUG

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

Definition at line 315 of file lwlock.c.

◆ T_NAME

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

Definition at line 251 of file lwlock.c.

Typedef Documentation

◆ LWLockHandle

typedef struct LWLockHandle LWLockHandle

◆ NamedLWLockTrancheRequest

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:452
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:929
size_t Size
Definition: c.h:551
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:52
@ LWTRANCHE_FIRST_USER_DEFINED
Definition: lwlock.h:196
#define MAX_BACKENDS
Definition: postmaster.h:75
void * ShmemAlloc(Size size)
Definition: shmem.c:161
Definition: lwlock.h:32

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

Referenced by CreateSharedMemoryAndSemaphores().

◆ GetLWLockIdentifier()

const char* GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 798 of file lwlock.c.

799 {
800  Assert(classId == PG_WAIT_LWLOCK);
801  /* The event IDs are just tranche numbers. */
802  return GetLWTrancheName(eventId);
803 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:770
#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 770 of file lwlock.c.

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

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

Referenced by GetLWLockIdentifier().

◆ 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:33
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:232
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:99

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

Referenced by pgss_shmem_startup().

◆ InitializeLWLocks()

static void InitializeLWLocks ( void  )
static

Definition at line 513 of file lwlock.c.

514 {
515  int numNamedLocks = NumLWLocksForNamedTranches();
516  int id;
517  int i;
518  int j;
519  LWLockPadded *lock;
520 
521  /* Initialize all individual LWLocks in main array */
522  for (id = 0, lock = MainLWLockArray; id < NUM_INDIVIDUAL_LWLOCKS; id++, lock++)
523  LWLockInitialize(&lock->lock, id);
524 
525  /* Initialize buffer mapping LWLocks in main array */
527  for (id = 0; id < NUM_BUFFER_PARTITIONS; id++, lock++)
529 
530  /* Initialize lmgrs' LWLocks in main array */
532  for (id = 0; id < NUM_LOCK_PARTITIONS; id++, lock++)
534 
535  /* Initialize predicate lmgrs' LWLocks in main array */
537  for (id = 0; id < NUM_PREDICATELOCK_PARTITIONS; id++, lock++)
539 
540  /*
541  * Copy the info about any named tranches into shared memory (so that
542  * other processes can see it), and initialize the requested LWLocks.
543  */
545  {
546  char *trancheNames;
547 
549  &MainLWLockArray[NUM_FIXED_LWLOCKS + numNamedLocks];
550 
551  trancheNames = (char *) NamedLWLockTrancheArray +
554 
555  for (i = 0; i < NamedLWLockTrancheRequests; i++)
556  {
557  NamedLWLockTrancheRequest *request;
558  NamedLWLockTranche *tranche;
559  char *name;
560 
561  request = &NamedLWLockTrancheRequestArray[i];
562  tranche = &NamedLWLockTrancheArray[i];
563 
564  name = trancheNames;
565  trancheNames += strlen(request->tranche_name) + 1;
566  strcpy(name, request->tranche_name);
567  tranche->trancheId = LWLockNewTrancheId();
568  tranche->trancheName = name;
569 
570  for (j = 0; j < request->num_lwlocks; j++, lock++)
571  LWLockInitialize(&lock->lock, tranche->trancheId);
572  }
573  }
574 }
const char * name
Definition: encode.c:561
int j
Definition: isn.c:74
int LWLockNewTrancheId(void)
Definition: lwlock.c:626
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:422
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:734
#define BUFFER_MAPPING_LWLOCK_OFFSET
Definition: lwlock.h:94
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:87
@ LWTRANCHE_PREDICATE_LOCK_MANAGER
Definition: lwlock.h:183
@ LWTRANCHE_BUFFER_MAPPING
Definition: lwlock.h:181
@ LWTRANCHE_LOCK_MANAGER
Definition: lwlock.h:182
#define LOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:95
#define NUM_BUFFER_PARTITIONS
Definition: lwlock.h:83
#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:97
#define NUM_PREDICATELOCK_PARTITIONS
Definition: lwlock.h:91
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:228
char * trancheName
Definition: lwlock.h:67
LWLock lock
Definition: lwlock.h:57

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

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

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

Referenced by _bt_end_vacuum(), _bt_start_vacuum(), _bt_vacuum_cycleid(), AbsorbSyncRequests(), ActivateCommitTs(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_init_shmem(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacLauncherMain(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendIdGetProc(), BackendIdGetTransactionIds(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BootStrapCLOG(), BootStrapMultiXact(), BootStrapSUBTRANS(), BootStrapXLOG(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), 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(), FindAndDropRelFileNodeBuffers(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), FlushRelationsAllBuffers(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldSnapshotFromTimeMapping(), GetOldSnapshotTimeMapping(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionData(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), HandleAutoVacLauncherInterrupts(), HaveVirtualXIDsDelayingChkpt(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), InvalidatePossiblyObsoleteSlot(), IsInstallXLogFileSegmentActive(), KnownAssignedXidsAdd(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockBuffer(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_worker_attach(), logicalrep_worker_detach(), logicalrep_worker_launch(), logicalrep_worker_stop(), logicalrep_worker_wakeup(), 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_checkpointer_reset_all_cb(), pgstat_checkpointer_snapshot_cb(), pgstat_flush_wal(), pgstat_lock_entry(), 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(), 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(), 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 1424 of file lwlock.c.

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

◆ LWLockAttemptLock()

static bool LWLockAttemptLock ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 815 of file lwlock.c.

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

References AssertArg, 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 1367 of file lwlock.c.

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

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

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

◆ LWLockConflictsWithVar()

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

Definition at line 1551 of file lwlock.c.

1554 {
1555  bool mustwait;
1556  uint64 value;
1557 
1558  /*
1559  * Test first to see if it the slot is free right now.
1560  *
1561  * XXX: the caller uses a spinlock before this, so we don't need a memory
1562  * barrier here as far as the current usage is concerned. But that might
1563  * not be safe in general.
1564  */
1565  mustwait = (pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE) != 0;
1566 
1567  if (!mustwait)
1568  {
1569  *result = true;
1570  return false;
1571  }
1572 
1573  *result = false;
1574 
1575  /*
1576  * Read value using the lwlock's wait list lock, as we can't generally
1577  * rely on atomic 64 bit reads/stores. TODO: On platforms with a way to
1578  * do atomic 64 bit reads/writes the spinlock should be optimized away.
1579  */
1580  LWLockWaitListLock(lock);
1581  value = *valptr;
1582  LWLockWaitListUnlock(lock);
1583 
1584  if (value != oldval)
1585  {
1586  mustwait = false;
1587  *newval = value;
1588  }
1589  else
1590  {
1591  mustwait = true;
1592  }
1593 
1594  return mustwait;
1595 }
#define newval
static struct @151 value
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:886
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:938

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

Referenced by LWLockWaitForVar().

◆ LWLockDequeueSelf()

static void LWLockDequeueSelf ( LWLock lock)
static

Definition at line 1101 of file lwlock.c.

1102 {
1103  bool found = false;
1104  proclist_mutable_iter iter;
1105 
1106 #ifdef LWLOCK_STATS
1107  lwlock_stats *lwstats;
1108 
1109  lwstats = get_lwlock_stats_entry(lock);
1110 
1111  lwstats->dequeue_self_count++;
1112 #endif
1113 
1114  LWLockWaitListLock(lock);
1115 
1116  /*
1117  * Can't just remove ourselves from the list, but we need to iterate over
1118  * all entries as somebody else could have dequeued us.
1119  */
1120  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1121  {
1122  if (iter.cur == MyProc->pgprocno)
1123  {
1124  found = true;
1125  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1126  break;
1127  }
1128  }
1129 
1130  if (proclist_is_empty(&lock->waiters) &&
1131  (pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS) != 0)
1132  {
1134  }
1135 
1136  /* XXX: combine with fetch_and above? */
1137  LWLockWaitListUnlock(lock);
1138 
1139  /* clear waiting state again, nice for debugging */
1140  if (found)
1141  MyProc->lwWaiting = false;
1142  else
1143  {
1144  int extraWaits = 0;
1145 
1146  /*
1147  * Somebody else dequeued us and has or will wake us up. Deal with the
1148  * superfluous absorption of a wakeup.
1149  */
1150 
1151  /*
1152  * Reset RELEASE_OK flag if somebody woke us before we removed
1153  * ourselves - they'll have set it to false.
1154  */
1156 
1157  /*
1158  * Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
1159  * get reset at some inconvenient point later. Most of the time this
1160  * will immediately return.
1161  */
1162  for (;;)
1163  {
1165  if (!MyProc->lwWaiting)
1166  break;
1167  extraWaits++;
1168  }
1169 
1170  /*
1171  * Fix the process wait semaphore's count for any absorbed wakeups.
1172  */
1173  while (extraWaits-- > 0)
1175  }
1176 
1177 #ifdef LOCK_DEBUG
1178  {
1179  /* not waiting anymore */
1180  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1181 
1182  Assert(nwaiters < MAX_BACKENDS);
1183  }
1184 #endif
1185 }
static uint32 pg_atomic_fetch_and_u32(volatile pg_atomic_uint32 *ptr, uint32 and_)
Definition: atomics.h:358
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:100
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:187
static bool proclist_is_empty(proclist_head *list)
Definition: proclist.h:38
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
proclist_head waiters
Definition: lwlock.h:35
int pgprocno
Definition: proc.h:188

References Assert(), proclist_mutable_iter::cur, LW_FLAG_HAS_WAITERS, LW_FLAG_RELEASE_OK, 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_foreach_modify, proclist_is_empty(), PGPROC::sem, LWLock::state, and LWLock::waiters.

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

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

◆ LWLockHeldCount()

int LWLockHeldCount ( void  )

Definition at line 1948 of file lwlock.c.

1949 {
1950  return num_held_lwlocks;
1951 }

References num_held_lwlocks.

Referenced by ShutdownPostgres().

◆ LWLockInitialize()

void LWLockInitialize ( LWLock lock,
int  tranche_id 
)

Definition at line 734 of file lwlock.c.

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

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

◆ LWLockQueueSelf()

static void LWLockQueueSelf ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 1058 of file lwlock.c.

1059 {
1060  /*
1061  * If we don't have a PGPROC structure, there's no way to wait. This
1062  * should never occur, since MyProc should only be null during shared
1063  * memory initialization.
1064  */
1065  if (MyProc == NULL)
1066  elog(PANIC, "cannot wait without a PGPROC structure");
1067 
1068  if (MyProc->lwWaiting)
1069  elog(PANIC, "queueing for lock while waiting on another one");
1070 
1071  LWLockWaitListLock(lock);
1072 
1073  /* setting the flag is protected by the spinlock */
1075 
1076  MyProc->lwWaiting = true;
1077  MyProc->lwWaitMode = mode;
1078 
1079  /* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */
1080  if (mode == LW_WAIT_UNTIL_FREE)
1081  proclist_push_head(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1082  else
1083  proclist_push_tail(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1084 
1085  /* Can release the mutex now */
1086  LWLockWaitListUnlock(lock);
1087 
1088 #ifdef LOCK_DEBUG
1089  pg_atomic_fetch_add_u32(&lock->nwaiters, 1);
1090 #endif
1091 }
static uint32 pg_atomic_fetch_add_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:328
#define PANIC
Definition: elog.h:36
#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:209

References elog(), LW_FLAG_HAS_WAITERS, LW_WAIT_UNTIL_FREE, 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 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
671  {
672  LWLockTrancheNames = (const char **)
673  repalloc(LWLockTrancheNames, newalloc * sizeof(char *));
675  0,
676  (newalloc - LWLockTrancheNamesAllocated) * sizeof(char *));
677  }
678  LWLockTrancheNamesAllocated = newalloc;
679  }
680 
681  LWLockTrancheNames[tranche_id] = tranche_name;
682 }
#define Max(x, y)
Definition: c.h:991
MemoryContext TopMemoryContext
Definition: mcxt.c:48
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:906
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1188
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:140

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

Referenced by apw_init_shmem(), and CreateLWLocks().

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1800 of file lwlock.c.

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

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

Referenced by _bt_end_vacuum(), _bt_start_vacuum(), _bt_vacuum_cycleid(), AbsorbSyncRequests(), ActivateCommitTs(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_init_shmem(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacLauncherMain(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendIdGetProc(), BackendIdGetTransactionIds(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BootStrapCLOG(), BootStrapMultiXact(), BootStrapSUBTRANS(), BootStrapXLOG(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), 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(), FindAndDropRelFileNodeBuffers(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), FlushRelationsAllBuffers(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldSnapshotFromTimeMapping(), GetOldSnapshotTimeMapping(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), HandleAutoVacLauncherInterrupts(), HaveVirtualXIDsDelayingChkpt(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), InvalidatePossiblyObsoleteSlot(), IsInstallXLogFileSegmentActive(), KnownAssignedXidsAdd(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockBuffer(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_worker_attach(), logicalrep_worker_detach(), logicalrep_worker_launch(), logicalrep_worker_stop(), logicalrep_worker_wakeup(), LogStandbySnapshot(), 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_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(), 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(), 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 1899 of file lwlock.c.

1900 {
1901  while (num_held_lwlocks > 0)
1902  {
1903  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1904 
1906  }
1907 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1800

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

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

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

Referenced by WALInsertLockRelease().

◆ LWLockReportWaitEnd()

static void LWLockReportWaitEnd ( void  )
inlinestatic

Definition at line 761 of file lwlock.c.

762 {
764 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:282

References pgstat_report_wait_end().

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

◆ LWLockReportWaitStart()

static void LWLockReportWaitStart ( LWLock lock)
inlinestatic

Definition at line 752 of file lwlock.c.

753 {
755 }
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:266

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

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

◆ 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 }
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 1746 of file lwlock.c.

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

References Assert(), proclist_mutable_iter::cur, GetPGProcByNumber, LW_EXCLUSIVE, LW_VAL_EXCLUSIVE, LW_WAIT_UNTIL_FREE, LWLockWaitListLock(), LWLockWaitListUnlock(), PGPROC::lwWaiting, PGPROC::lwWaitMode, pg_atomic_read_u32(), pg_write_barrier, PGSemaphoreUnlock(), PRINT_LWDEBUG, proclist_delete, proclist_foreach_modify, proclist_init(), proclist_push_tail, PGPROC::sem, LWLock::state, val, and LWLock::waiters.

Referenced by WALInsertLockAcquireExclusive(), and WALInsertLockUpdateInsertingAt().

◆ LWLockWaitForVar()

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

Definition at line 1611 of file lwlock.c.

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

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

Referenced by WaitXLogInsertionsToFinish().

◆ LWLockWaitListLock()

static void LWLockWaitListLock ( LWLock lock)
static

Definition at line 886 of file lwlock.c.

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

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 LWLockConflictsWithVar(), LWLockDequeueSelf(), LWLockQueueSelf(), LWLockReleaseClearVar(), LWLockUpdateVar(), and LWLockWakeup().

◆ LWLockWaitListUnlock()

static void LWLockWaitListUnlock ( LWLock lock)
static

◆ LWLockWakeup()

static void LWLockWakeup ( LWLock lock)
static

Definition at line 951 of file lwlock.c.

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

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, 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, and LWLock::waiters.

Referenced by LWLockRelease().

◆ NumLWLocksForNamedTranches()

static int NumLWLocksForNamedTranches ( void  )
static

Definition at line 422 of file lwlock.c.

423 {
424  int numLocks = 0;
425  int i;
426 
427  for (i = 0; i < NamedLWLockTrancheRequests; i++)
428  numLocks += NamedLWLockTrancheRequestArray[i].num_lwlocks;
429 
430  return numLocks;
431 }

References i, NamedLWLockTrancheRequestArray, and NamedLWLockTrancheRequests.

Referenced by InitializeLWLocks(), and LWLockShmemSize().

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 697 of file lwlock.c.

698 {
699  NamedLWLockTrancheRequest *request;
700 
702  elog(FATAL, "cannot request additional LWLocks outside shmem_request_hook");
703 
704  if (NamedLWLockTrancheRequestArray == NULL)
705  {
710  * sizeof(NamedLWLockTrancheRequest));
711  }
712 
714  {
716 
719  i * sizeof(NamedLWLockTrancheRequest));
721  }
722 
724  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
725  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
726  request->num_lwlocks = num_lwlocks;
728 }
#define FATAL
Definition: elog.h:35
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:233
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
bool process_shmem_requests_in_progress
Definition: miscinit.c:1621
#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()

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

Variable Documentation

◆ BuiltinTrancheNames

const char* const BuiltinTrancheNames[]
static

Definition at line 131 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 197 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ LWLockTrancheNamesAllocated

int LWLockTrancheNamesAllocated = 0
static

Definition at line 198 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ MainLWLockArray

LWLockPadded* MainLWLockArray = NULL

◆ NamedLWLockTrancheArray

NamedLWLockTranche* NamedLWLockTrancheArray = NULL

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