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 "storage/proc.h"
#include "storage/proclist.h"
#include "storage/spin.h"
#include "utils/memutils.h"
#include "storage/lwlocklist.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 PG_LWLOCK(id, lockname)   [id] = CppAsString(lockname) "Lock",
 
#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, "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
 
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 302 of file lwlock.c.

◆ LW_FLAG_HAS_WAITERS

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

Definition at line 97 of file lwlock.c.

◆ LW_FLAG_LOCKED

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

Definition at line 99 of file lwlock.c.

◆ LW_FLAG_RELEASE_OK

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

Definition at line 98 of file lwlock.c.

◆ LW_LOCK_MASK

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

Definition at line 104 of file lwlock.c.

◆ LW_SHARED_MASK

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

Definition at line 106 of file lwlock.c.

◆ LW_VAL_EXCLUSIVE

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

Definition at line 101 of file lwlock.c.

◆ LW_VAL_SHARED

#define LW_VAL_SHARED   1

Definition at line 102 of file lwlock.c.

◆ MAX_SIMUL_LWLOCKS

#define MAX_SIMUL_LWLOCKS   200

Definition at line 199 of file lwlock.c.

◆ PG_LWLOCK

#define PG_LWLOCK (   id,
  lockname 
)    [id] = CppAsString(lockname) "Lock",

◆ PRINT_LWDEBUG

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

Definition at line 301 of file lwlock.c.

◆ T_NAME

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

Definition at line 237 of file lwlock.c.

Typedef Documentation

◆ LWLockHandle

typedef struct LWLockHandle LWLockHandle

◆ NamedLWLockTrancheRequest

Function Documentation

◆ CreateLWLocks()

void CreateLWLocks ( void  )

Definition at line 453 of file lwlock.c.

454 {
455  if (!IsUnderPostmaster)
456  {
457  Size spaceLocks = LWLockShmemSize();
458  int *LWLockCounter;
459  char *ptr;
460 
461  /* Allocate space */
462  ptr = (char *) ShmemAlloc(spaceLocks);
463 
464  /* Leave room for dynamic allocation of tranches */
465  ptr += sizeof(int);
466 
467  /* Ensure desired alignment of LWLock array */
468  ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
469 
470  MainLWLockArray = (LWLockPadded *) ptr;
471 
472  /*
473  * Initialize the dynamic-allocation counter for tranches, which is
474  * stored just before the first LWLock.
475  */
476  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
477  *LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
478 
479  /* Initialize all LWLocks */
481  }
482 
483  /* Register named extension LWLock tranches in the current process. */
484  for (int i = 0; i < NamedLWLockTrancheRequests; i++)
486  NamedLWLockTrancheArray[i].trancheName);
487 }
size_t Size
Definition: c.h:605
bool IsUnderPostmaster
Definition: globals.c:117
int i
Definition: isn.c:73
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:230
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:630
int NamedLWLockTrancheRequests
Definition: lwlock.c:227
static void InitializeLWLocks(void)
Definition: lwlock.c:493
LWLockPadded * MainLWLockArray
Definition: lwlock.c:191
Size LWLockShmemSize(void)
Definition: lwlock.c:423
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:62
@ LWTRANCHE_FIRST_USER_DEFINED
Definition: lwlock.h:218
void * ShmemAlloc(Size size)
Definition: shmem.c:152

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

Referenced by CreateOrAttachShmemStructs().

◆ GetLWLockIdentifier()

const char* GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 769 of file lwlock.c.

770 {
771  Assert(classId == PG_WAIT_LWLOCK);
772  /* The event IDs are just tranche numbers. */
773  return GetLWTrancheName(eventId);
774 }
#define Assert(condition)
Definition: c.h:858
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:745
#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 745 of file lwlock.c.

746 {
747  /* Built-in tranche or individual LWLock? */
748  if (trancheId < LWTRANCHE_FIRST_USER_DEFINED)
749  return BuiltinTrancheNames[trancheId];
750 
751  /*
752  * It's an extension tranche, so look in LWLockTrancheNames[]. However,
753  * it's possible that the tranche has never been registered in the current
754  * process, in which case give up and return "extension".
755  */
756  trancheId -= LWTRANCHE_FIRST_USER_DEFINED;
757 
758  if (trancheId >= LWLockTrancheNamesAllocated ||
759  LWLockTrancheNames[trancheId] == NULL)
760  return "extension";
761 
762  return LWLockTrancheNames[trancheId];
763 }
static int LWLockTrancheNamesAllocated
Definition: lwlock.c:184
static const char *const BuiltinTrancheNames[]
Definition: lwlock.c:129
static const char ** LWLockTrancheNames
Definition: lwlock.c:183

References BuiltinTrancheNames, LWLockTrancheNames, LWLockTrancheNamesAllocated, and LWTRANCHE_FIRST_USER_DEFINED.

Referenced by GetLWLockIdentifier().

◆ GetNamedLWLockTranche()

LWLockPadded* GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 576 of file lwlock.c.

577 {
578  int lock_pos;
579  int i;
580 
581  /*
582  * Obtain the position of base address of LWLock belonging to requested
583  * tranche_name in MainLWLockArray. LWLocks for named tranches are placed
584  * in MainLWLockArray after fixed locks.
585  */
586  lock_pos = NUM_FIXED_LWLOCKS;
587  for (i = 0; i < NamedLWLockTrancheRequests; i++)
588  {
589  if (strcmp(NamedLWLockTrancheRequestArray[i].tranche_name,
590  tranche_name) == 0)
591  return &MainLWLockArray[lock_pos];
592 
594  }
595 
596  elog(ERROR, "requested tranche is not registered");
597 
598  /* just to keep compiler quiet */
599  return NULL;
600 }
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:218
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:109

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

494 {
495  int numNamedLocks = NumLWLocksForNamedTranches();
496  int id;
497  int i;
498  int j;
499  LWLockPadded *lock;
500 
501  /* Initialize all individual LWLocks in main array */
502  for (id = 0, lock = MainLWLockArray; id < NUM_INDIVIDUAL_LWLOCKS; id++, lock++)
503  LWLockInitialize(&lock->lock, id);
504 
505  /* Initialize buffer mapping LWLocks in main array */
507  for (id = 0; id < NUM_BUFFER_PARTITIONS; id++, lock++)
509 
510  /* Initialize lmgrs' LWLocks in main array */
512  for (id = 0; id < NUM_LOCK_PARTITIONS; id++, lock++)
514 
515  /* Initialize predicate lmgrs' LWLocks in main array */
517  for (id = 0; id < NUM_PREDICATELOCK_PARTITIONS; id++, lock++)
519 
520  /*
521  * Copy the info about any named tranches into shared memory (so that
522  * other processes can see it), and initialize the requested LWLocks.
523  */
525  {
526  char *trancheNames;
527 
529  &MainLWLockArray[NUM_FIXED_LWLOCKS + numNamedLocks];
530 
531  trancheNames = (char *) NamedLWLockTrancheArray +
534 
535  for (i = 0; i < NamedLWLockTrancheRequests; i++)
536  {
537  NamedLWLockTrancheRequest *request;
538  NamedLWLockTranche *tranche;
539  char *name;
540 
541  request = &NamedLWLockTrancheRequestArray[i];
542  tranche = &NamedLWLockTrancheArray[i];
543 
544  name = trancheNames;
545  trancheNames += strlen(request->tranche_name) + 1;
546  strcpy(name, request->tranche_name);
547  tranche->trancheId = LWLockNewTrancheId();
548  tranche->trancheName = name;
549 
550  for (j = 0; j < request->num_lwlocks; j++, lock++)
551  LWLockInitialize(&lock->lock, tranche->trancheId);
552  }
553  }
554 }
int j
Definition: isn.c:74
int LWLockNewTrancheId(void)
Definition: lwlock.c:606
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:408
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:709
#define BUFFER_MAPPING_LWLOCK_OFFSET
Definition: lwlock.h:104
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:97
@ LWTRANCHE_PREDICATE_LOCK_MANAGER
Definition: lwlock.h:193
@ LWTRANCHE_BUFFER_MAPPING
Definition: lwlock.h:191
@ LWTRANCHE_LOCK_MANAGER
Definition: lwlock.h:192
#define LOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:105
#define NUM_BUFFER_PARTITIONS
Definition: lwlock.h:93
#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:107
#define NUM_PREDICATELOCK_PARTITIONS
Definition: lwlock.h:101
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:214
char * trancheName
Definition: lwlock.h:80
LWLock lock
Definition: lwlock.h:70
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 560 of file lwlock.c.

561 {
562 #ifdef LWLOCK_STATS
563  init_lwlock_stats();
564 #endif
565 }

Referenced by InitAuxiliaryProcess(), and InitProcess().

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1170 of file lwlock.c.

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

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(), AdjustToFullTransactionId(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtEOXact_LogicalRepWorkers(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacuumRequestWork(), AutoVacWorkerMain(), 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(), consume_xids_shortcut(), 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_get_total_size(), 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(), EvictUnpinnedBuffer(), 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(), get_local_synced_slots(), get_val_in_shmem(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLeaderApplyWorkerPid(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldestUnsummarizedLSN(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionData(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), GetWaitEventExtensionIdentifier(), GetWaitEventExtensionNames(), GetWalSummarizerState(), HaveVirtualXIDsDelayingChkpt(), init_dsm_registry(), InjectionPointAttach(), InjectionPointDetach(), InjectionPointRun(), 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_control_checkpoint(), pg_control_init(), pg_control_recovery(), pg_control_system(), 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_fetch_replslot(), 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_replslot(), 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(), ProcNumberGetTransactionIds(), ProcSleep(), ReachedEndOfBackup(), read_relmap_file(), ReadMultiXactCounts(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadReplicationSlot(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePreInvalidate(), RelationMapCopy(), RelationMapFinishBootstrap(), 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(), SerialInit(), SerialSetActiveSerXmin(), set_indexsafe_procflags(), set_val_in_shmem(), SetCommitTsLimit(), SetInstallXLogFileSegmentActive(), SetMultiXactIdLimit(), SetNextObjectId(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetWalSummarizerLatch(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SignalVirtualTransaction(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), StandbyRecoverPreparedTransactions(), StandbySlotsHaveCaughtup(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SummarizeWAL(), SwitchIntoArchiveRecovery(), synchronize_one_slot(), 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(), update_synced_slots_inactive_since(), UpdateMinRecoveryPoint(), vac_truncate_clog(), vacuum_rel(), VacuumUpdateCosts(), validate_standby_slots(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitEventExtensionNew(), WaitForReplicationWorkerAttach(), WaitForWalSummarization(), WALInsertLockAcquire(), WALInsertLockAcquireExclusive(), WalSummarizerMain(), WalSummarizerShutdown(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogReportParameters(), and XLogShutdownWalRcv().

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1398 of file lwlock.c.

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

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

1914 {
1915  char *held_lock_addr;
1916  char *begin;
1917  char *end;
1918  int i;
1919 
1920  begin = (char *) lock;
1921  end = begin + nlocks * stride;
1922  for (i = 0; i < num_held_lwlocks; i++)
1923  {
1924  held_lock_addr = (char *) held_lwlocks[i].lock;
1925  if (held_lock_addr >= begin &&
1926  held_lock_addr < end &&
1927  (held_lock_addr - begin) % stride == 0)
1928  return true;
1929  }
1930  return false;
1931 }

References held_lwlocks, i, and num_held_lwlocks.

◆ LWLockAttemptLock()

static bool LWLockAttemptLock ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 786 of file lwlock.c.

787 {
788  uint32 old_state;
789 
791 
792  /*
793  * Read once outside the loop, later iterations will get the newer value
794  * via compare & exchange.
795  */
796  old_state = pg_atomic_read_u32(&lock->state);
797 
798  /* loop until we've determined whether we could acquire the lock or not */
799  while (true)
800  {
801  uint32 desired_state;
802  bool lock_free;
803 
804  desired_state = old_state;
805 
806  if (mode == LW_EXCLUSIVE)
807  {
808  lock_free = (old_state & LW_LOCK_MASK) == 0;
809  if (lock_free)
810  desired_state += LW_VAL_EXCLUSIVE;
811  }
812  else
813  {
814  lock_free = (old_state & LW_VAL_EXCLUSIVE) == 0;
815  if (lock_free)
816  desired_state += LW_VAL_SHARED;
817  }
818 
819  /*
820  * Attempt to swap in the state we are expecting. If we didn't see
821  * lock to be free, that's just the old value. If we saw it as free,
822  * we'll attempt to mark it acquired. The reason that we always swap
823  * in the value is that this doubles as a memory barrier. We could try
824  * to be smarter and only swap in values if we saw the lock as free,
825  * but benchmark haven't shown it as beneficial so far.
826  *
827  * Retry if the value changed since we last looked at it.
828  */
830  &old_state, desired_state))
831  {
832  if (lock_free)
833  {
834  /* Great! Got the lock. */
835 #ifdef LOCK_DEBUG
836  if (mode == LW_EXCLUSIVE)
837  lock->owner = MyProc;
838 #endif
839  return false;
840  }
841  else
842  return true; /* somebody else has the lock */
843  }
844  }
845  pg_unreachable();
846 }
static bool pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 *expected, uint32 newval)
Definition: atomics.h:344
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:234
#define pg_unreachable()
Definition: c.h:296
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:101
#define LW_VAL_SHARED
Definition: lwlock.c:102
#define LW_LOCK_MASK
Definition: lwlock.c:104

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

1342 {
1343  bool mustwait;
1344 
1346 
1347  PRINT_LWDEBUG("LWLockConditionalAcquire", lock, mode);
1348 
1349  /* Ensure we will have room to remember the lock */
1351  elog(ERROR, "too many LWLocks taken");
1352 
1353  /*
1354  * Lock out cancel/die interrupts until we exit the code section protected
1355  * by the LWLock. This ensures that interrupts will not interfere with
1356  * manipulations of data structures in shared memory.
1357  */
1358  HOLD_INTERRUPTS();
1359 
1360  /* Check for the lock */
1361  mustwait = LWLockAttemptLock(lock, mode);
1362 
1363  if (mustwait)
1364  {
1365  /* Failed to get lock, so release interrupt holdoff */
1367 
1368  LOG_LWDEBUG("LWLockConditionalAcquire", lock, "failed");
1369  if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL_ENABLED())
1370  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL(T_NAME(lock), mode);
1371  }
1372  else
1373  {
1374  /* Add lock to list of locks held by this backend */
1377  if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_ENABLED())
1378  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(T_NAME(lock), mode);
1379  }
1380  return !mustwait;
1381 }

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

1527 {
1528  bool mustwait;
1529  uint64 value;
1530 
1531  /*
1532  * Test first to see if it the slot is free right now.
1533  *
1534  * XXX: the unique caller of this routine, WaitXLogInsertionsToFinish()
1535  * via LWLockWaitForVar(), uses an implied barrier with a spinlock before
1536  * this, so we don't need a memory barrier here as far as the current
1537  * usage is concerned. But that might not be safe in general.
1538  */
1539  mustwait = (pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE) != 0;
1540 
1541  if (!mustwait)
1542  {
1543  *result = true;
1544  return false;
1545  }
1546 
1547  *result = false;
1548 
1549  /*
1550  * Reading this value atomically is safe even on platforms where uint64
1551  * cannot be read without observing a torn value.
1552  */
1553  value = pg_atomic_read_u64(valptr);
1554 
1555  if (value != oldval)
1556  {
1557  mustwait = false;
1558  *newval = value;
1559  }
1560  else
1561  {
1562  mustwait = true;
1563  }
1564 
1565  return mustwait;
1566 }
static uint64 pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
Definition: atomics.h:462
#define newval
static struct @155 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 1081 of file lwlock.c.

1082 {
1083  bool on_waitlist;
1084 
1085 #ifdef LWLOCK_STATS
1086  lwlock_stats *lwstats;
1087 
1088  lwstats = get_lwlock_stats_entry(lock);
1089 
1090  lwstats->dequeue_self_count++;
1091 #endif
1092 
1093  LWLockWaitListLock(lock);
1094 
1095  /*
1096  * Remove ourselves from the waitlist, unless we've already been removed.
1097  * The removal happens with the wait list lock held, so there's no race in
1098  * this check.
1099  */
1100  on_waitlist = MyProc->lwWaiting == LW_WS_WAITING;
1101  if (on_waitlist)
1102  proclist_delete(&lock->waiters, MyProcNumber, lwWaitLink);
1103 
1104  if (proclist_is_empty(&lock->waiters) &&
1105  (pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS) != 0)
1106  {
1108  }
1109 
1110  /* XXX: combine with fetch_and above? */
1111  LWLockWaitListUnlock(lock);
1112 
1113  /* clear waiting state again, nice for debugging */
1114  if (on_waitlist)
1116  else
1117  {
1118  int extraWaits = 0;
1119 
1120  /*
1121  * Somebody else dequeued us and has or will wake us up. Deal with the
1122  * superfluous absorption of a wakeup.
1123  */
1124 
1125  /*
1126  * Reset RELEASE_OK flag if somebody woke us before we removed
1127  * ourselves - they'll have set it to false.
1128  */
1130 
1131  /*
1132  * Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
1133  * get reset at some inconvenient point later. Most of the time this
1134  * will immediately return.
1135  */
1136  for (;;)
1137  {
1140  break;
1141  extraWaits++;
1142  }
1143 
1144  /*
1145  * Fix the process wait semaphore's count for any absorbed wakeups.
1146  */
1147  while (extraWaits-- > 0)
1149  }
1150 
1151 #ifdef LOCK_DEBUG
1152  {
1153  /* not waiting anymore */
1154  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1155 
1156  Assert(nwaiters < MAX_BACKENDS);
1157  }
1158 #endif
1159 }
static uint32 pg_atomic_fetch_and_u32(volatile pg_atomic_uint32 *ptr, uint32 and_)
Definition: atomics.h:391
ProcNumber MyProcNumber
Definition: globals.c:87
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:857
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:97
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:909
@ LW_WS_WAITING
Definition: lwlock.h:31
#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:45

References Assert, LW_FLAG_HAS_WAITERS, LW_FLAG_RELEASE_OK, LW_WS_NOT_WAITING, LW_WS_WAITING, LWLockWaitListLock(), LWLockWaitListUnlock(), PGPROC::lwWaiting, MAX_BACKENDS, MyProc, MyProcNumber, pg_atomic_fetch_and_u32(), pg_atomic_fetch_or_u32(), pg_atomic_fetch_sub_u32(), pg_atomic_read_u32(), PG_USED_FOR_ASSERTS_ONLY, 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 709 of file lwlock.c.

710 {
712 #ifdef LOCK_DEBUG
713  pg_atomic_init_u32(&lock->nwaiters, 0);
714 #endif
715  lock->tranche = tranche_id;
716  proclist_init(&lock->waiters);
717 }
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:216
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
uint16 tranche
Definition: lwlock.h:43

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

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

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( void  )

Definition at line 606 of file lwlock.c.

607 {
608  int result;
609  int *LWLockCounter;
610 
611  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
613  result = (*LWLockCounter)++;
615 
616  return result;
617 }
slock_t * ShmemLock
Definition: shmem.c:87
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62

References MainLWLockArray, ShmemLock, SpinLockAcquire, and SpinLockRelease.

Referenced by apw_init_state(), InitializeLWLocks(), tdr_init_shmem(), test_basic(), test_create(), test_dsa_basic(), test_dsa_resowners(), test_empty(), test_random(), and test_slru_shmem_startup().

◆ LWLockQueueSelf()

static void LWLockQueueSelf ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 1038 of file lwlock.c.

1039 {
1040  /*
1041  * If we don't have a PGPROC structure, there's no way to wait. This
1042  * should never occur, since MyProc should only be null during shared
1043  * memory initialization.
1044  */
1045  if (MyProc == NULL)
1046  elog(PANIC, "cannot wait without a PGPROC structure");
1047 
1049  elog(PANIC, "queueing for lock while waiting on another one");
1050 
1051  LWLockWaitListLock(lock);
1052 
1053  /* setting the flag is protected by the spinlock */
1055 
1057  MyProc->lwWaitMode = mode;
1058 
1059  /* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */
1060  if (mode == LW_WAIT_UNTIL_FREE)
1061  proclist_push_head(&lock->waiters, MyProcNumber, lwWaitLink);
1062  else
1063  proclist_push_tail(&lock->waiters, MyProcNumber, lwWaitLink);
1064 
1065  /* Can release the mutex now */
1066  LWLockWaitListUnlock(lock);
1067 
1068 #ifdef LOCK_DEBUG
1069  pg_atomic_fetch_add_u32(&lock->nwaiters, 1);
1070 #endif
1071 }
static uint32 pg_atomic_fetch_add_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:361
#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:220

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, MyProcNumber, PANIC, pg_atomic_fetch_add_u32(), pg_atomic_fetch_or_u32(), 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 630 of file lwlock.c.

631 {
632  /* This should only be called for user-defined tranches. */
633  if (tranche_id < LWTRANCHE_FIRST_USER_DEFINED)
634  return;
635 
636  /* Convert to array index. */
637  tranche_id -= LWTRANCHE_FIRST_USER_DEFINED;
638 
639  /* If necessary, create or enlarge array. */
640  if (tranche_id >= LWLockTrancheNamesAllocated)
641  {
642  int newalloc;
643 
644  newalloc = pg_nextpower2_32(Max(8, tranche_id + 1));
645 
646  if (LWLockTrancheNames == NULL)
647  LWLockTrancheNames = (const char **)
649  newalloc * sizeof(char *));
650  else
653  LWLockTrancheNamesAllocated = newalloc;
654  }
655 
656  LWLockTrancheNames[tranche_id] = tranche_name;
657 }
#define Max(x, y)
Definition: c.h:998
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1214
#define repalloc0_array(pointer, type, oldcount, count)
Definition: palloc.h:109
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(), tdr_attach_shmem(), test_basic(), test_create(), test_dsa_basic(), test_dsa_resowners(), test_empty(), test_random(), and test_slru_shmem_startup().

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1783 of file lwlock.c.

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

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(), AdjustToFullTransactionId(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtEOXact_LogicalRepWorkers(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacuumRequestWork(), AutoVacWorkerMain(), 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(), consume_xids_shortcut(), 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_get_total_size(), 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(), EvictUnpinnedBuffer(), 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(), get_local_synced_slots(), get_val_in_shmem(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLeaderApplyWorkerPid(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldestUnsummarizedLSN(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetStrictOldestNonRemovableTransactionId(), GetVictimBuffer(), GetVirtualXIDsDelayingChkpt(), GetWaitEventExtensionIdentifier(), GetWaitEventExtensionNames(), GetWalSummarizerState(), HaveVirtualXIDsDelayingChkpt(), init_dsm_registry(), InjectionPointAttach(), InjectionPointDetach(), InjectionPointRun(), 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_control_checkpoint(), pg_control_init(), pg_control_recovery(), pg_control_system(), 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_fetch_replslot(), pgstat_flush_io(), pgstat_flush_wal(), pgstat_io_reset_all_cb(), pgstat_io_snapshot_cb(), pgstat_reset_matching_entries(), pgstat_reset_replslot(), 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(), ProcNumberGetTransactionIds(), ProcSleep(), ReachedEndOfBackup(), read_relmap_file(), ReadMultiXactCounts(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadReplicationSlot(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePostInvalidate(), RelationMapCopy(), RelationMapFinishBootstrap(), 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(), SerialInit(), SerialSetActiveSerXmin(), set_indexsafe_procflags(), set_val_in_shmem(), SetCommitTsLimit(), SetInstallXLogFileSegmentActive(), SetMultiXactIdLimit(), SetNextObjectId(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetWalSummarizerLatch(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SignalVirtualTransaction(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), ss_report_location(), StandbyRecoverPreparedTransactions(), StandbySlotsHaveCaughtup(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransGetParent(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SummarizeWAL(), SwitchIntoArchiveRecovery(), synchronize_one_slot(), 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(), update_synced_slots_inactive_since(), UpdateMinRecoveryPoint(), vac_truncate_clog(), vacuum_rel(), VacuumUpdateCosts(), validate_standby_slots(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitEventExtensionNew(), WaitForReplicationWorkerAttach(), WaitForWalSummarization(), WaitOnLock(), WalSummarizerMain(), WalSummarizerShutdown(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), XLogNeedsFlush(), XLogReportParameters(), and XLogShutdownWalRcv().

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

Definition at line 1878 of file lwlock.c.

1879 {
1880  while (num_held_lwlocks > 0)
1881  {
1882  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1883 
1885  }
1886 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1783

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

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

◆ LWLockReleaseClearVar()

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

Definition at line 1856 of file lwlock.c.

1857 {
1858  /*
1859  * Note that pg_atomic_exchange_u64 is a full barrier, so we're guaranteed
1860  * that the variable is updated before releasing the lock.
1861  */
1862  pg_atomic_exchange_u64(valptr, val);
1863 
1864  LWLockRelease(lock);
1865 }
static uint64 pg_atomic_exchange_u64(volatile pg_atomic_uint64 *ptr, uint64 newval)
Definition: atomics.h:498
long val
Definition: informix.c:670

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

Referenced by WALInsertLockRelease().

◆ LWLockReportWaitEnd()

static void LWLockReportWaitEnd ( void  )
inlinestatic

Definition at line 736 of file lwlock.c.

737 {
739 }
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 727 of file lwlock.c.

728 {
730 }
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 423 of file lwlock.c.

424 {
425  Size size;
426  int i;
427  int numLocks = NUM_FIXED_LWLOCKS;
428 
429  /* Calculate total number of locks needed in the main array. */
430  numLocks += NumLWLocksForNamedTranches();
431 
432  /* Space for the LWLock array. */
433  size = mul_size(numLocks, sizeof(LWLockPadded));
434 
435  /* Space for dynamic allocation counter, plus room for alignment. */
436  size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
437 
438  /* space for named tranches. */
440 
441  /* space for name of each tranche. */
442  for (i = 0; i < NamedLWLockTrancheRequests; i++)
443  size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
444 
445  return size;
446 }
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
static pg_noinline void Size size
Definition: slab.c:607

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

Referenced by CalculateShmemSize(), and CreateLWLocks().

◆ LWLockUpdateVar()

void LWLockUpdateVar ( LWLock lock,
pg_atomic_uint64 valptr,
uint64  val 
)

Definition at line 1722 of file lwlock.c.

1723 {
1725  proclist_mutable_iter iter;
1726 
1727  PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1728 
1729  /*
1730  * Note that pg_atomic_exchange_u64 is a full barrier, so we're guaranteed
1731  * that the variable is updated before waking up waiters.
1732  */
1733  pg_atomic_exchange_u64(valptr, val);
1734 
1736 
1737  LWLockWaitListLock(lock);
1738 
1740 
1741  /*
1742  * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1743  * up. They are always in the front of the queue.
1744  */
1745  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1746  {
1747  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1748 
1749  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1750  break;
1751 
1752  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1753  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1754 
1755  /* see LWLockWakeup() */
1756  Assert(waiter->lwWaiting == LW_WS_WAITING);
1757  waiter->lwWaiting = LW_WS_PENDING_WAKEUP;
1758  }
1759 
1760  /* We are done updating shared state of the lock itself. */
1761  LWLockWaitListUnlock(lock);
1762 
1763  /*
1764  * Awaken any waiters I removed from the queue.
1765  */
1766  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1767  {
1768  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1769 
1770  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1771  /* check comment in LWLockWakeup() about this barrier */
1772  pg_write_barrier();
1773  waiter->lwWaiting = LW_WS_NOT_WAITING;
1774  PGSemaphoreUnlock(waiter->sem);
1775  }
1776 }
#define pg_write_barrier()
Definition: atomics.h:152
@ LW_WS_PENDING_WAKEUP
Definition: lwlock.h:32
#define GetPGProcByNumber(n)
Definition: proc.h:428
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
static TimestampTz wakeup[NUM_WALRCV_WAKEUPS]
Definition: walreceiver.c:129

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

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

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

858 {
859  uint32 old_state;
860 #ifdef LWLOCK_STATS
861  lwlock_stats *lwstats;
862  uint32 delays = 0;
863 
864  lwstats = get_lwlock_stats_entry(lock);
865 #endif
866 
867  while (true)
868  {
869  /* always try once to acquire lock directly */
870  old_state = pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_LOCKED);
871  if (!(old_state & LW_FLAG_LOCKED))
872  break; /* got lock */
873 
874  /* and then spin without atomic operations until lock is released */
875  {
876  SpinDelayStatus delayStatus;
877 
878  init_local_spin_delay(&delayStatus);
879 
880  while (old_state & LW_FLAG_LOCKED)
881  {
882  perform_spin_delay(&delayStatus);
883  old_state = pg_atomic_read_u32(&lock->state);
884  }
885 #ifdef LWLOCK_STATS
886  delays += delayStatus.delays;
887 #endif
888  finish_spin_delay(&delayStatus);
889  }
890 
891  /*
892  * Retry. The lock might obviously already be re-acquired by the time
893  * we're attempting to get it again.
894  */
895  }
896 
897 #ifdef LWLOCK_STATS
898  lwstats->spin_delay_count += delays;
899 #endif
900 }
#define LW_FLAG_LOCKED
Definition: lwlock.c:99
void perform_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:132
void finish_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:192
#define init_local_spin_delay(status)
Definition: s_lock.h:843

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

910 {
912 
913  old_state = pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_LOCKED);
914 
915  Assert(old_state & LW_FLAG_LOCKED);
916 }

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

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

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

409 {
410  int numLocks = 0;
411  int i;
412 
413  for (i = 0; i < NamedLWLockTrancheRequests; i++)
414  numLocks += NamedLWLockTrancheRequestArray[i].num_lwlocks;
415 
416  return numLocks;
417 }

References i, NamedLWLockTrancheRequestArray, and NamedLWLockTrancheRequests.

Referenced by InitializeLWLocks(), and LWLockShmemSize().

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 672 of file lwlock.c.

673 {
674  NamedLWLockTrancheRequest *request;
675 
677  elog(FATAL, "cannot request additional LWLocks outside shmem_request_hook");
678 
679  if (NamedLWLockTrancheRequestArray == NULL)
680  {
685  * sizeof(NamedLWLockTrancheRequest));
686  }
687 
689  {
691 
694  i * sizeof(NamedLWLockTrancheRequest));
696  }
697 
699  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
700  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
701  request->num_lwlocks = num_lwlocks;
703 }
#define FATAL
Definition: elog.h:41
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:219
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1540
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1180
bool process_shmem_requests_in_progress
Definition: miscinit.c:1782
#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,
"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 129 of file lwlock.c.

Referenced by GetLWTrancheName().

◆ held_lwlocks

◆ LWLockTrancheNames

const char** LWLockTrancheNames = NULL
static

Definition at line 183 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ LWLockTrancheNamesAllocated

int LWLockTrancheNamesAllocated = 0
static

Definition at line 184 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ MainLWLockArray

◆ NamedLWLockTrancheArray

NamedLWLockTranche* NamedLWLockTrancheArray = NULL

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

Referenced by RequestNamedLWLockTranche().

◆ num_held_lwlocks

◆ ShmemLock

slock_t* ShmemLock
extern

Definition at line 87 of file shmem.c.

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