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 "storage/proc.h"
#include "storage/proclist.h"
#include "storage/procnumber.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 << 31)
 
#define LW_FLAG_RELEASE_OK   ((uint32) 1 << 30)
 
#define LW_FLAG_LOCKED   ((uint32) 1 << 29)
 
#define LW_FLAG_BITS   3
 
#define LW_FLAG_MASK   (((1<<LW_FLAG_BITS)-1)<<(32-LW_FLAG_BITS))
 
#define LW_VAL_EXCLUSIVE   (MAX_BACKENDS + 1)
 
#define LW_VAL_SHARED   1
 
#define LW_SHARED_MASK   MAX_BACKENDS
 
#define LW_LOCK_MASK   (MAX_BACKENDS | LW_VAL_EXCLUSIVE)
 
#define PG_LWLOCK(id, lockname)   [id] = CppAsString(lockname),
 
#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 (((MAX_BACKENDS+1) &MAX_BACKENDS)==0, "MAX_BACKENDS + 1 needs to be a power of 2")
 
 StaticAssertDecl ((MAX_BACKENDS &LW_FLAG_MASK)==0, "MAX_BACKENDS and LW_FLAG_MASK overlap")
 
 StaticAssertDecl ((LW_VAL_EXCLUSIVE &LW_FLAG_MASK)==0, "LW_VAL_EXCLUSIVE and LW_FLAG_MASK overlap")
 
 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)
 
static LWLockMode LWLockDisownInternal (LWLock *lock)
 
static void LWLockReleaseInternal (LWLock *lock, LWLockMode mode)
 
void LWLockDisown (LWLock *lock)
 
void LWLockRelease (LWLock *lock)
 
void LWLockReleaseDisowned (LWLock *lock, LWLockMode mode)
 
void LWLockReleaseClearVar (LWLock *lock, pg_atomic_uint64 *valptr, uint64 val)
 
void LWLockReleaseAll (void)
 
void ForEachLWLockHeldByMe (void(*callback)(LWLock *, LWLockMode, void *), void *context)
 
bool LWLockHeldByMe (LWLock *lock)
 
bool LWLockAnyHeldByMe (LWLock *lock, int nlocks, size_t stride)
 
bool LWLockHeldByMeInMode (LWLock *lock, LWLockMode mode)
 

Variables

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

◆ LW_FLAG_BITS

#define LW_FLAG_BITS   3

Definition at line 97 of file lwlock.c.

◆ LW_FLAG_HAS_WAITERS

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

Definition at line 94 of file lwlock.c.

◆ LW_FLAG_LOCKED

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

Definition at line 96 of file lwlock.c.

◆ LW_FLAG_MASK

#define LW_FLAG_MASK   (((1<<LW_FLAG_BITS)-1)<<(32-LW_FLAG_BITS))

Definition at line 98 of file lwlock.c.

◆ LW_FLAG_RELEASE_OK

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

Definition at line 95 of file lwlock.c.

◆ LW_LOCK_MASK

#define LW_LOCK_MASK   (MAX_BACKENDS | LW_VAL_EXCLUSIVE)

Definition at line 106 of file lwlock.c.

◆ LW_SHARED_MASK

#define LW_SHARED_MASK   MAX_BACKENDS

Definition at line 105 of file lwlock.c.

◆ LW_VAL_EXCLUSIVE

#define LW_VAL_EXCLUSIVE   (MAX_BACKENDS + 1)

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

◆ PG_LWLOCK

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

◆ PRINT_LWDEBUG

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

Definition at line 310 of file lwlock.c.

◆ T_NAME

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

Definition at line 246 of file lwlock.c.

Typedef Documentation

◆ LWLockHandle

typedef struct LWLockHandle LWLockHandle

◆ NamedLWLockTrancheRequest

Function Documentation

◆ CreateLWLocks()

void CreateLWLocks ( void  )

Definition at line 462 of file lwlock.c.

463{
465 {
466 Size spaceLocks = LWLockShmemSize();
467 int *LWLockCounter;
468 char *ptr;
469
470 /* Allocate space */
471 ptr = (char *) ShmemAlloc(spaceLocks);
472
473 /* Leave room for dynamic allocation of tranches */
474 ptr += sizeof(int);
475
476 /* Ensure desired alignment of LWLock array */
477 ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
478
480
481 /*
482 * Initialize the dynamic-allocation counter for tranches, which is
483 * stored just before the first LWLock.
484 */
485 LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
486 *LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
487
488 /* Initialize all LWLocks */
490 }
491
492 /* Register named extension LWLock tranches in the current process. */
493 for (int i = 0; i < NamedLWLockTrancheRequests; i++)
495 NamedLWLockTrancheArray[i].trancheName);
496}
size_t Size
Definition: c.h:576
bool IsUnderPostmaster
Definition: globals.c:120
int i
Definition: isn.c:77
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:239
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:640
int NamedLWLockTrancheRequests
Definition: lwlock.c:236
static void InitializeLWLocks(void)
Definition: lwlock.c:502
LWLockPadded * MainLWLockArray
Definition: lwlock.c:200
Size LWLockShmemSize(void)
Definition: lwlock.c:432
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:62
@ LWTRANCHE_FIRST_USER_DEFINED
Definition: lwlock.h:224
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().

◆ ForEachLWLockHeldByMe()

void ForEachLWLockHeldByMe ( void(*)(LWLock *, LWLockMode, void *)  callback,
void *  context 
)

Definition at line 1968 of file lwlock.c.

1970{
1971 int i;
1972
1973 for (i = 0; i < num_held_lwlocks; i++)
1974 callback(held_lwlocks[i].lock, held_lwlocks[i].mode, context);
1975}
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:218
static int num_held_lwlocks
Definition: lwlock.c:217
static PgChecksumMode mode
Definition: pg_checksums.c:55
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:46

References callback(), held_lwlocks, i, mode, and num_held_lwlocks.

◆ GetLWLockIdentifier()

const char * GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 779 of file lwlock.c.

780{
781 Assert(classId == PG_WAIT_LWLOCK);
782 /* The event IDs are just tranche numbers. */
783 return GetLWTrancheName(eventId);
784}
Assert(PointerIsAligned(start, uint64))
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:755
#define PG_WAIT_LWLOCK
Definition: wait_classes.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 755 of file lwlock.c.

756{
757 /* Built-in tranche or individual LWLock? */
758 if (trancheId < LWTRANCHE_FIRST_USER_DEFINED)
759 return BuiltinTrancheNames[trancheId];
760
761 /*
762 * It's an extension tranche, so look in LWLockTrancheNames[]. However,
763 * it's possible that the tranche has never been registered in the current
764 * process, in which case give up and return "extension".
765 */
766 trancheId -= LWTRANCHE_FIRST_USER_DEFINED;
767
768 if (trancheId >= LWLockTrancheNamesAllocated ||
769 LWLockTrancheNames[trancheId] == NULL)
770 return "extension";
771
772 return LWLockTrancheNames[trancheId];
773}
static int LWLockTrancheNamesAllocated
Definition: lwlock.c:193
static const char *const BuiltinTrancheNames[]
Definition: lwlock.c:136
static const char ** LWLockTrancheNames
Definition: lwlock.c:192

References BuiltinTrancheNames, LWLockTrancheNames, LWLockTrancheNamesAllocated, and LWTRANCHE_FIRST_USER_DEFINED.

Referenced by GetLWLockIdentifier().

◆ GetNamedLWLockTranche()

LWLockPadded * GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 585 of file lwlock.c.

586{
587 int lock_pos;
588 int i;
589
590 /*
591 * Obtain the position of base address of LWLock belonging to requested
592 * tranche_name in MainLWLockArray. LWLocks for named tranches are placed
593 * in MainLWLockArray after fixed locks.
594 */
595 lock_pos = NUM_FIXED_LWLOCKS;
596 for (i = 0; i < NamedLWLockTrancheRequests; i++)
597 {
598 if (strcmp(NamedLWLockTrancheRequestArray[i].tranche_name,
599 tranche_name) == 0)
600 return &MainLWLockArray[lock_pos];
601
603 }
604
605 elog(ERROR, "requested tranche is not registered");
606
607 /* just to keep compiler quiet */
608 return NULL;
609}
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:227
#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 502 of file lwlock.c.

503{
504 int numNamedLocks = NumLWLocksForNamedTranches();
505 int id;
506 int i;
507 int j;
508 LWLockPadded *lock;
509
510 /* Initialize all individual LWLocks in main array */
511 for (id = 0, lock = MainLWLockArray; id < NUM_INDIVIDUAL_LWLOCKS; id++, lock++)
512 LWLockInitialize(&lock->lock, id);
513
514 /* Initialize buffer mapping LWLocks in main array */
516 for (id = 0; id < NUM_BUFFER_PARTITIONS; id++, lock++)
518
519 /* Initialize lmgrs' LWLocks in main array */
521 for (id = 0; id < NUM_LOCK_PARTITIONS; id++, lock++)
523
524 /* Initialize predicate lmgrs' LWLocks in main array */
526 for (id = 0; id < NUM_PREDICATELOCK_PARTITIONS; id++, lock++)
528
529 /*
530 * Copy the info about any named tranches into shared memory (so that
531 * other processes can see it), and initialize the requested LWLocks.
532 */
534 {
535 char *trancheNames;
536
538 &MainLWLockArray[NUM_FIXED_LWLOCKS + numNamedLocks];
539
540 trancheNames = (char *) NamedLWLockTrancheArray +
543
544 for (i = 0; i < NamedLWLockTrancheRequests; i++)
545 {
547 NamedLWLockTranche *tranche;
548 char *name;
549
551 tranche = &NamedLWLockTrancheArray[i];
552
553 name = trancheNames;
554 trancheNames += strlen(request->tranche_name) + 1;
555 strcpy(name, request->tranche_name);
556 tranche->trancheId = LWLockNewTrancheId();
557 tranche->trancheName = name;
558
559 for (j = 0; j < request->num_lwlocks; j++, lock++)
560 LWLockInitialize(&lock->lock, tranche->trancheId);
561 }
562 }
563}
int j
Definition: isn.c:78
int LWLockNewTrancheId(void)
Definition: lwlock.c:615
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:417
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:719
#define BUFFER_MAPPING_LWLOCK_OFFSET
Definition: lwlock.h:104
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:97
@ LWTRANCHE_PREDICATE_LOCK_MANAGER
Definition: lwlock.h:197
@ LWTRANCHE_BUFFER_MAPPING
Definition: lwlock.h:195
@ LWTRANCHE_LOCK_MANAGER
Definition: lwlock.h:196
#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:223
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 569 of file lwlock.c.

570{
571#ifdef LWLOCK_STATS
572 init_lwlock_stats();
573#endif
574}

Referenced by InitAuxiliaryProcess(), and InitProcess().

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1180 of file lwlock.c.

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

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_parallel_done(), _bt_parallel_primscan_schedule(), _bt_parallel_release(), _bt_parallel_seize(), _bt_start_vacuum(), _bt_vacuum_cycleid(), AbsorbSyncRequests(), ActivateCommitTs(), 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(), AutoVacLauncherMain(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BootStrapCLOG(), BootStrapMultiXact(), BootStrapSUBTRANS(), btparallelrescan(), 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(), 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(), EvictUnpinnedBufferInternal(), 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(), get_xid_status(), 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(), GetStrictOldestNonRemovableTransactionId(), GetVirtualXIDsDelayingChkpt(), GetWaitEventCustomIdentifier(), GetWaitEventCustomNames(), GetWalSummarizerState(), HaveVirtualXIDsDelayingChkpt(), init_dsm_registry(), InitWalSender(), injection_shmem_startup(), injection_stats_fixed_reset_all_cb(), injection_stats_fixed_snapshot_cb(), InjectionPointAttach(), InjectionPointDetach(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), InvalidatePossiblyObsoleteSlot(), InvalidateVictimBuffer(), IoWorkerMain(), 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(), logicalrep_workers_find(), LookupGXact(), LookupGXactBySubid(), 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_get_shmem_allocations_numa(), pg_notification_queue_usage(), pg_show_replication_origin_status(), pg_stat_get_subscription(), pg_stat_statements_internal(), pg_xact_status(), pgaio_worker_die(), pgaio_worker_register(), pgaio_worker_submit_internal(), 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_io_flush_cb(), 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_cb(), pgstat_slru_snapshot_cb(), pgstat_wal_flush_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(), 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_aio_shmem_startup(), 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_sync_standby_slots(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitEventCustomNew(), WaitForReplicationWorkerAttach(), WaitForWalSummarization(), WakeupWalSummarizer(), WALInsertLockAcquire(), WALInsertLockAcquireExclusive(), WalSummarizerMain(), WalSummarizerShutdown(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogReportParameters(), XLogShutdownWalRcv(), and ZeroAndLockBuffer().

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1408 of file lwlock.c.

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

2002{
2003 char *held_lock_addr;
2004 char *begin;
2005 char *end;
2006 int i;
2007
2008 begin = (char *) lock;
2009 end = begin + nlocks * stride;
2010 for (i = 0; i < num_held_lwlocks; i++)
2011 {
2012 held_lock_addr = (char *) held_lwlocks[i].lock;
2013 if (held_lock_addr >= begin &&
2014 held_lock_addr < end &&
2015 (held_lock_addr - begin) % stride == 0)
2016 return true;
2017 }
2018 return false;
2019}

References held_lwlocks, i, and num_held_lwlocks.

◆ LWLockAttemptLock()

static bool LWLockAttemptLock ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 796 of file lwlock.c.

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

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

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

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_io_flush_cb(), pgstat_lock_entry(), pgstat_lock_entry_shared(), pgstat_slru_flush_cb(), pgstat_wal_flush_cb(), 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 1535 of file lwlock.c.

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

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

◆ LWLockDisown()

void LWLockDisown ( LWLock lock)

Definition at line 1889 of file lwlock.c.

1890{
1892
1894}
static LWLockMode LWLockDisownInternal(LWLock *lock)
Definition: lwlock.c:1806

References LWLockDisownInternal(), and RESUME_INTERRUPTS.

Referenced by buffer_stage_common().

◆ LWLockDisownInternal()

static LWLockMode LWLockDisownInternal ( LWLock lock)
inlinestatic

Definition at line 1806 of file lwlock.c.

1807{
1809 int i;
1810
1811 /*
1812 * Remove lock from list of locks held. Usually, but not always, it will
1813 * be the latest-acquired lock; so search array backwards.
1814 */
1815 for (i = num_held_lwlocks; --i >= 0;)
1816 if (lock == held_lwlocks[i].lock)
1817 break;
1818
1819 if (i < 0)
1820 elog(ERROR, "lock %s is not held", T_NAME(lock));
1821
1823
1825 for (; i < num_held_lwlocks; i++)
1826 held_lwlocks[i] = held_lwlocks[i + 1];
1827
1828 return mode;
1829}
LWLockMode
Definition: lwlock.h:113

References elog, ERROR, held_lwlocks, i, LWLockHandle::mode, mode, num_held_lwlocks, and T_NAME.

Referenced by LWLockDisown(), and LWLockRelease().

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

◆ LWLockInitialize()

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( void  )

Definition at line 615 of file lwlock.c.

616{
617 int result;
618 int *LWLockCounter;
619
620 LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
621 /* We use the ShmemLock spinlock to protect LWLockCounter */
623 result = (*LWLockCounter)++;
625
626 return result;
627}
slock_t * ShmemLock
Definition: shmem.c:88
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59

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

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

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

641{
642 /* This should only be called for user-defined tranches. */
643 if (tranche_id < LWTRANCHE_FIRST_USER_DEFINED)
644 return;
645
646 /* Convert to array index. */
647 tranche_id -= LWTRANCHE_FIRST_USER_DEFINED;
648
649 /* If necessary, create or enlarge array. */
650 if (tranche_id >= LWLockTrancheNamesAllocated)
651 {
652 int newalloc;
653
654 newalloc = pg_nextpower2_32(Max(8, tranche_id + 1));
655
656 if (LWLockTrancheNames == NULL)
657 LWLockTrancheNames = (const char **)
659 newalloc * sizeof(char *));
660 else
664 }
665
666 LWLockTrancheNames[tranche_id] = tranche_name;
667}
#define Max(x, y)
Definition: c.h:969
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1219
MemoryContext TopMemoryContext
Definition: mcxt.c:149
#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 1900 of file lwlock.c.

1901{
1903
1904 mode = LWLockDisownInternal(lock);
1905
1906 PRINT_LWDEBUG("LWLockRelease", lock, mode);
1907
1909
1910 /*
1911 * Now okay to allow cancel/die interrupts.
1912 */
1914}
static void LWLockReleaseInternal(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1836

References LWLockDisownInternal(), LWLockReleaseInternal(), mode, PRINT_LWDEBUG, and RESUME_INTERRUPTS.

Referenced by _bt_end_vacuum(), _bt_parallel_done(), _bt_parallel_primscan_schedule(), _bt_parallel_release(), _bt_parallel_seize(), _bt_start_vacuum(), _bt_vacuum_cycleid(), AbsorbSyncRequests(), ActivateCommitTs(), 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(), AutoVacLauncherMain(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BootStrapCLOG(), BootStrapMultiXact(), BootStrapSUBTRANS(), btparallelrescan(), 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(), 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(), EvictUnpinnedBufferInternal(), 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(), get_xid_status(), 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(), GetWaitEventCustomIdentifier(), GetWaitEventCustomNames(), GetWalSummarizerState(), HaveVirtualXIDsDelayingChkpt(), init_dsm_registry(), InitWalSender(), injection_shmem_startup(), injection_stats_fixed_reset_all_cb(), injection_stats_fixed_snapshot_cb(), InjectionPointAttach(), InjectionPointDetach(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), InvalidatePossiblyObsoleteSlot(), InvalidateVictimBuffer(), IoWorkerMain(), 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(), logicalrep_workers_find(), LogStandbySnapshot(), LookupGXact(), LookupGXactBySubid(), 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_get_shmem_allocations_numa(), pg_notification_queue_usage(), pg_show_replication_origin_status(), pg_stat_get_subscription(), pg_stat_statements_internal(), pg_xact_status(), pgaio_worker_die(), pgaio_worker_register(), pgaio_worker_submit_internal(), 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_io_flush_cb(), pgstat_io_reset_all_cb(), pgstat_io_snapshot_cb(), pgstat_reset_matching_entries(), pgstat_reset_replslot(), pgstat_reset_slru_counter_internal(), pgstat_slru_flush_cb(), pgstat_slru_snapshot_cb(), pgstat_unlock_entry(), pgstat_wal_flush_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(), 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(), 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_aio_shmem_startup(), 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_sync_standby_slots(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitEventCustomNew(), WaitForReplicationWorkerAttach(), WaitForWalSummarization(), WakeupWalSummarizer(), WalSummarizerMain(), WalSummarizerShutdown(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), XLogNeedsFlush(), XLogReportParameters(), and XLogShutdownWalRcv().

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

◆ LWLockReleaseClearVar()

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

Definition at line 1929 of file lwlock.c.

1930{
1931 /*
1932 * Note that pg_atomic_exchange_u64 is a full barrier, so we're guaranteed
1933 * that the variable is updated before releasing the lock.
1934 */
1935 pg_atomic_exchange_u64(valptr, val);
1936
1937 LWLockRelease(lock);
1938}
static uint64 pg_atomic_exchange_u64(volatile pg_atomic_uint64 *ptr, uint64 newval)
Definition: atomics.h:503
long val
Definition: informix.c:689

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

Referenced by WALInsertLockRelease().

◆ LWLockReleaseDisowned()

void LWLockReleaseDisowned ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1920 of file lwlock.c.

1921{
1923}

References LWLockReleaseInternal(), and mode.

◆ LWLockReleaseInternal()

static void LWLockReleaseInternal ( LWLock lock,
LWLockMode  mode 
)
static

Definition at line 1836 of file lwlock.c.

1837{
1838 uint32 oldstate;
1839 bool check_waiters;
1840
1841 /*
1842 * Release my hold on lock, after that it can immediately be acquired by
1843 * others, even if we still have to wakeup other waiters.
1844 */
1845 if (mode == LW_EXCLUSIVE)
1847 else
1848 oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_SHARED);
1849
1850 /* nobody else can have that kind of lock */
1851 Assert(!(oldstate & LW_VAL_EXCLUSIVE));
1852
1853 if (TRACE_POSTGRESQL_LWLOCK_RELEASE_ENABLED())
1854 TRACE_POSTGRESQL_LWLOCK_RELEASE(T_NAME(lock));
1855
1856 /*
1857 * We're still waiting for backends to get scheduled, don't wake them up
1858 * again.
1859 */
1860 if ((oldstate & (LW_FLAG_HAS_WAITERS | LW_FLAG_RELEASE_OK)) ==
1862 (oldstate & LW_LOCK_MASK) == 0)
1863 check_waiters = true;
1864 else
1865 check_waiters = false;
1866
1867 /*
1868 * As waking up waiters requires the spinlock to be acquired, only do so
1869 * if necessary.
1870 */
1871 if (check_waiters)
1872 {
1873 /* XXX: remove before commit? */
1874 LOG_LWDEBUG("LWLockRelease", lock, "releasing waiters");
1875 LWLockWakeup(lock);
1876 }
1877}
static uint32 pg_atomic_sub_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:439
static void LWLockWakeup(LWLock *lock)
Definition: lwlock.c:932

References Assert(), LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_HAS_WAITERS, LW_FLAG_RELEASE_OK, LW_LOCK_MASK, LW_VAL_EXCLUSIVE, LW_VAL_SHARED, LWLockWakeup(), mode, pg_atomic_sub_fetch_u32(), LWLock::state, and T_NAME.

Referenced by LWLockRelease(), and LWLockReleaseDisowned().

◆ LWLockReportWaitEnd()

static void LWLockReportWaitEnd ( void  )
inlinestatic

Definition at line 746 of file lwlock.c.

747{
749}
static void pgstat_report_wait_end(void)
Definition: wait_event.h:85

References pgstat_report_wait_end().

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

◆ LWLockReportWaitStart()

static void LWLockReportWaitStart ( LWLock lock)
inlinestatic

Definition at line 737 of file lwlock.c.

738{
740}
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:69

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

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

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 432 of file lwlock.c.

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

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

Referenced by CalculateShmemSize(), and CreateLWLocks().

◆ LWLockUpdateVar()

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

Definition at line 1732 of file lwlock.c.

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

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

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

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

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

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

920{
922
923 old_state = pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_LOCKED);
924
925 Assert(old_state & LW_FLAG_LOCKED);
926}

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

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

References Assert(), proclist_mutable_iter::cur, GetPGProcByNumber, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_HAS_WAITERS, 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 LWLockReleaseInternal().

◆ NumLWLocksForNamedTranches()

static int NumLWLocksForNamedTranches ( void  )
static

Definition at line 417 of file lwlock.c.

418{
419 int numLocks = 0;
420 int i;
421
422 for (i = 0; i < NamedLWLockTrancheRequests; i++)
423 numLocks += NamedLWLockTrancheRequestArray[i].num_lwlocks;
424
425 return numLocks;
426}

References i, NamedLWLockTrancheRequestArray, and NamedLWLockTrancheRequests.

Referenced by InitializeLWLocks(), and LWLockShmemSize().

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 682 of file lwlock.c.

683{
685
687 elog(FATAL, "cannot request additional LWLocks outside shmem_request_hook");
688
690 {
695 * sizeof(NamedLWLockTrancheRequest));
696 }
697
699 {
701
704 i * sizeof(NamedLWLockTrancheRequest));
706 }
707
709 Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
710 strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
711 request->num_lwlocks = num_lwlocks;
713}
#define FATAL
Definition: elog.h:41
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:228
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1185
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1548
bool process_shmem_requests_in_progress
Definition: miscinit.c:1841
#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/4]

StaticAssertDecl ( ((MAX_BACKENDS+1) &MAX_BACKENDS = =0,
"MAX_BACKENDS + 1 needs to be a power of 2"   
)

◆ StaticAssertDecl() [2/4]

StaticAssertDecl ( (LW_VAL_EXCLUSIVE &LW_FLAG_MASK = =0,
"LW_VAL_EXCLUSIVE and LW_FLAG_MASK overlap"   
)

◆ StaticAssertDecl() [3/4]

StaticAssertDecl ( (MAX_BACKENDS &LW_FLAG_MASK = =0,
"MAX_BACKENDS and LW_FLAG_MASK overlap"   
)

◆ StaticAssertDecl() [4/4]

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

Variable Documentation

◆ BuiltinTrancheNames

const char* const BuiltinTrancheNames[]
static

Definition at line 136 of file lwlock.c.

Referenced by GetLWTrancheName().

◆ held_lwlocks

◆ LWLockTrancheNames

const char** LWLockTrancheNames = NULL
static

Definition at line 192 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ LWLockTrancheNamesAllocated

int LWLockTrancheNamesAllocated = 0
static

Definition at line 193 of file lwlock.c.

Referenced by GetLWTrancheName(), and LWLockRegisterTranche().

◆ MainLWLockArray

◆ NamedLWLockTrancheArray

NamedLWLockTranche* NamedLWLockTrancheArray = NULL

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

Referenced by RequestNamedLWLockTranche().

◆ num_held_lwlocks