PostgreSQL Source Code git master
Loading...
Searching...
No Matches
lwlock.h File Reference
#include "port/atomics.h"
#include "storage/lwlocknames.h"
#include "storage/proclist_types.h"
#include "storage/lwlocklist.h"
Include dependency graph for lwlock.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  LWLock
 
union  LWLockPadded
 

Macros

#define LWLOCK_PADDED_SIZE   PG_CACHE_LINE_SIZE
 
#define NUM_BUFFER_PARTITIONS   128
 
#define LOG2_NUM_LOCK_PARTITIONS   4
 
#define NUM_LOCK_PARTITIONS   (1 << LOG2_NUM_LOCK_PARTITIONS)
 
#define LOG2_NUM_PREDICATELOCK_PARTITIONS   4
 
#define NUM_PREDICATELOCK_PARTITIONS   (1 << LOG2_NUM_PREDICATELOCK_PARTITIONS)
 
#define BUFFER_MAPPING_LWLOCK_OFFSET   NUM_INDIVIDUAL_LWLOCKS
 
#define LOCK_MANAGER_LWLOCK_OFFSET    (BUFFER_MAPPING_LWLOCK_OFFSET + NUM_BUFFER_PARTITIONS)
 
#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET    (LOCK_MANAGER_LWLOCK_OFFSET + NUM_LOCK_PARTITIONS)
 
#define NUM_FIXED_LWLOCKS    (PREDICATELOCK_MANAGER_LWLOCK_OFFSET + NUM_PREDICATELOCK_PARTITIONS)
 
#define PG_LWLOCK(id, name)
 
#define PG_LWLOCKTRANCHE(id, name)   LWTRANCHE_##id,
 

Typedefs

typedef enum LWLockWaitState LWLockWaitState
 
typedef struct LWLock LWLock
 
typedef union LWLockPadded LWLockPadded
 
typedef struct NamedLWLockTrancheRequest NamedLWLockTrancheRequest
 
typedef enum LWLockMode LWLockMode
 
typedef enum BuiltinTrancheIds BuiltinTrancheIds
 
typedef LWLockLWLockId
 

Enumerations

enum  LWLockWaitState { LW_WS_NOT_WAITING , LW_WS_WAITING , LW_WS_PENDING_WAKEUP }
 
enum  LWLockMode { LW_EXCLUSIVE , LW_SHARED , LW_WAIT_UNTIL_FREE }
 
enum  BuiltinTrancheIds { LWTRANCHE_INVALID = NUM_INDIVIDUAL_LWLOCKS - 1 , LWTRANCHE_FIRST_USER_DEFINED }
 

Functions

 StaticAssertDecl (sizeof(LWLock)<=LWLOCK_PADDED_SIZE, "Miscalculated LWLock padding")
 
bool LWLockAcquire (LWLock *lock, LWLockMode mode)
 
bool LWLockConditionalAcquire (LWLock *lock, LWLockMode mode)
 
bool LWLockAcquireOrWait (LWLock *lock, LWLockMode mode)
 
void LWLockRelease (LWLock *lock)
 
void LWLockReleaseClearVar (LWLock *lock, 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)
 
bool LWLockWaitForVar (LWLock *lock, pg_atomic_uint64 *valptr, uint64 oldval, uint64 *newval)
 
void LWLockUpdateVar (LWLock *lock, pg_atomic_uint64 *valptr, uint64 val)
 
Size LWLockShmemSize (void)
 
void CreateLWLocks (void)
 
void InitLWLockAccess (void)
 
const charGetLWLockIdentifier (uint32 classId, uint16 eventId)
 
void RequestNamedLWLockTranche (const char *tranche_name, int num_lwlocks)
 
LWLockPaddedGetNamedLWLockTranche (const char *tranche_name)
 
int LWLockNewTrancheId (const char *name)
 
void LWLockInitialize (LWLock *lock, int tranche_id)
 

Variables

PGDLLIMPORT LWLockPaddedMainLWLockArray
 
PGDLLIMPORT char ** LWLockTrancheNames
 
PGDLLIMPORT int NamedLWLockTrancheRequests
 
PGDLLIMPORT NamedLWLockTrancheRequestNamedLWLockTrancheRequestArray
 
PGDLLIMPORT intLWLockCounter
 

Macro Definition Documentation

◆ BUFFER_MAPPING_LWLOCK_OFFSET

#define BUFFER_MAPPING_LWLOCK_OFFSET   NUM_INDIVIDUAL_LWLOCKS

Definition at line 102 of file lwlock.h.

◆ LOCK_MANAGER_LWLOCK_OFFSET

#define LOCK_MANAGER_LWLOCK_OFFSET    (BUFFER_MAPPING_LWLOCK_OFFSET + NUM_BUFFER_PARTITIONS)

Definition at line 103 of file lwlock.h.

111{
113 LW_SHARED,
114 LW_WAIT_UNTIL_FREE, /* A special mode used in PGPROC->lwWaitMode,
115 * when waiting for lock to become free. Not
116 * to be used as LWLockAcquire argument */
117} LWLockMode;
118
119
120#ifdef LOCK_DEBUG
121extern PGDLLIMPORT bool Trace_lwlocks;
122#endif
123
124extern bool LWLockAcquire(LWLock *lock, LWLockMode mode);
126extern bool LWLockAcquireOrWait(LWLock *lock, LWLockMode mode);
127extern void LWLockRelease(LWLock *lock);
129extern void LWLockReleaseAll(void);
130extern bool LWLockHeldByMe(LWLock *lock);
131extern bool LWLockAnyHeldByMe(LWLock *lock, int nlocks, size_t stride);
132extern bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode);
133
136
137extern Size LWLockShmemSize(void);
138extern void CreateLWLocks(void);
139extern void InitLWLockAccess(void);
140
141extern const char *GetLWLockIdentifier(uint32 classId, uint16 eventId);
142
143/*
144 * Extensions (or core code) can obtain an LWLocks by calling
145 * RequestNamedLWLockTranche() during postmaster startup. Subsequently,
146 * call GetNamedLWLockTranche() to obtain a pointer to an array containing
147 * the number of LWLocks requested.
148 */
149extern void RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks);
150extern LWLockPadded *GetNamedLWLockTranche(const char *tranche_name);
151
152/*
153 * There is another, more flexible method of obtaining lwlocks. First, call
154 * LWLockNewTrancheId to obtain a tranche ID; this allocates from a shared
155 * counter. Second, LWLockInitialize should be called just once per lwlock,
156 * passing the tranche ID as an argument.
157 */
158extern int LWLockNewTrancheId(const char *name);
159extern void LWLockInitialize(LWLock *lock, int tranche_id);
160
161/*
162 * Every tranche ID less than NUM_INDIVIDUAL_LWLOCKS is reserved; also,
163 * we reserve additional tranche IDs for builtin tranches not included in
164 * the set of individual LWLocks. A call to LWLockNewTrancheId will never
165 * return a value less than LWTRANCHE_FIRST_USER_DEFINED. The actual list of
166 * built-in tranches is kept in lwlocklist.h.
167 */
168typedef enum BuiltinTrancheIds
169{
170 /*
171 * LWTRANCHE_INVALID is an unused value that only exists to initialize the
172 * rest of the tranches to appropriate values.
173 */
175
176#define PG_LWLOCK(id, name)
177#define PG_LWLOCKTRANCHE(id, name) LWTRANCHE_##id,
178#include "storage/lwlocklist.h"
179#undef PG_LWLOCK
180#undef PG_LWLOCKTRANCHE
181
184
185/*
186 * Prior to PostgreSQL 9.4, we used an enum type called LWLockId to refer
187 * to LWLocks. New code should instead use LWLock *. However, for the
188 * convenience of third-party code, we include the following typedef.
189 */
190typedef LWLock *LWLockId;
191
192#endif /* LWLOCK_H */
#define PGDLLIMPORT
Definition c.h:1328
uint64_t uint64
Definition c.h:547
uint16_t uint16
Definition c.h:545
uint32_t uint32
Definition c.h:546
size_t Size
Definition c.h:619
#define newval
long val
Definition informix.c:689
void LWLockUpdateVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 val)
Definition lwlock.c:1728
bool LWLockHeldByMe(LWLock *lock)
Definition lwlock.c:1911
void LWLockReleaseClearVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 val)
Definition lwlock.c:1866
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1176
void CreateLWLocks(void)
Definition lwlock.c:441
int LWLockNewTrancheId(const char *name)
Definition lwlock.c:596
LWLockPadded * GetNamedLWLockTranche(const char *tranche_name)
Definition lwlock.c:566
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1955
bool LWLockWaitForVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 oldval, uint64 *newval)
Definition lwlock.c:1592
void RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks)
Definition lwlock.c:649
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1793
BuiltinTrancheIds
Definition lwlock.h:169
@ LWTRANCHE_FIRST_USER_DEFINED
Definition lwlock.h:182
@ LWTRANCHE_INVALID
Definition lwlock.h:174
void LWLockReleaseAll(void)
Definition lwlock.c:1892
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition lwlock.c:698
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1347
bool LWLockAcquireOrWait(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1404
LWLockMode
Definition lwlock.h:111
@ LW_SHARED
Definition lwlock.h:113
@ LW_WAIT_UNTIL_FREE
Definition lwlock.h:114
@ LW_EXCLUSIVE
Definition lwlock.h:112
LWLock * LWLockId
Definition lwlock.h:190
const char * GetLWLockIdentifier(uint32 classId, uint16 eventId)
Definition lwlock.c:773
Size LWLockShmemSize(void)
Definition lwlock.c:397
bool LWLockAnyHeldByMe(LWLock *lock, int nlocks, size_t stride)
Definition lwlock.c:1929
void InitLWLockAccess(void)
Definition lwlock.c:550
static PgChecksumMode mode
static int fb(int x)
const char * name

◆ LOG2_NUM_LOCK_PARTITIONS

#define LOG2_NUM_LOCK_PARTITIONS   4

Definition at line 94 of file lwlock.h.

◆ LOG2_NUM_PREDICATELOCK_PARTITIONS

#define LOG2_NUM_PREDICATELOCK_PARTITIONS   4

Definition at line 98 of file lwlock.h.

◆ LWLOCK_PADDED_SIZE

#define LWLOCK_PADDED_SIZE   PG_CACHE_LINE_SIZE

Definition at line 62 of file lwlock.h.

◆ NUM_BUFFER_PARTITIONS

#define NUM_BUFFER_PARTITIONS   128

Definition at line 91 of file lwlock.h.

◆ NUM_FIXED_LWLOCKS

Definition at line 107 of file lwlock.h.

◆ NUM_LOCK_PARTITIONS

#define NUM_LOCK_PARTITIONS   (1 << LOG2_NUM_LOCK_PARTITIONS)

Definition at line 95 of file lwlock.h.

◆ NUM_PREDICATELOCK_PARTITIONS

#define NUM_PREDICATELOCK_PARTITIONS   (1 << LOG2_NUM_PREDICATELOCK_PARTITIONS)

Definition at line 99 of file lwlock.h.

◆ PG_LWLOCK

#define PG_LWLOCK (   id,
  name 
)

Definition at line 176 of file lwlock.h.

◆ PG_LWLOCKTRANCHE

#define PG_LWLOCKTRANCHE (   id,
  name 
)    LWTRANCHE_##id,

Definition at line 177 of file lwlock.h.

◆ PREDICATELOCK_MANAGER_LWLOCK_OFFSET

#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET    (LOCK_MANAGER_LWLOCK_OFFSET + NUM_LOCK_PARTITIONS)

Definition at line 105 of file lwlock.h.

Typedef Documentation

◆ BuiltinTrancheIds

◆ LWLock

◆ LWLockId

Definition at line 190 of file lwlock.h.

◆ LWLockMode

◆ LWLockPadded

◆ LWLockWaitState

◆ NamedLWLockTrancheRequest

Enumeration Type Documentation

◆ BuiltinTrancheIds

Enumerator
LWTRANCHE_INVALID 
LWTRANCHE_FIRST_USER_DEFINED 

Definition at line 168 of file lwlock.h.

169{
170 /*
171 * LWTRANCHE_INVALID is an unused value that only exists to initialize the
172 * rest of the tranches to appropriate values.
173 */
175
176#define PG_LWLOCK(id, name)
177#define PG_LWLOCKTRANCHE(id, name) LWTRANCHE_##id,
178#include "storage/lwlocklist.h"
179#undef PG_LWLOCK
180#undef PG_LWLOCKTRANCHE
181

◆ LWLockMode

Enumerator
LW_EXCLUSIVE 
LW_SHARED 
LW_WAIT_UNTIL_FREE 

Definition at line 110 of file lwlock.h.

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

◆ LWLockWaitState

Enumerator
LW_WS_NOT_WAITING 
LW_WS_WAITING 
LW_WS_PENDING_WAKEUP 

Definition at line 28 of file lwlock.h.

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

Function Documentation

◆ CreateLWLocks()

void CreateLWLocks ( void  )
extern

Definition at line 441 of file lwlock.c.

442{
444 {
446 char *ptr;
447
448 /* Allocate space */
449 ptr = (char *) ShmemAlloc(spaceLocks);
450
451 /* Initialize the dynamic-allocation counter for tranches */
452 LWLockCounter = (int *) ptr;
454 ptr += MAXALIGN(sizeof(int));
455
456 /* Initialize tranche names */
457 LWLockTrancheNames = (char **) ptr;
458 ptr += MAX_NAMED_TRANCHES * sizeof(char *);
459 for (int i = 0; i < MAX_NAMED_TRANCHES; i++)
460 {
461 LWLockTrancheNames[i] = ptr;
462 ptr += NAMEDATALEN;
463 }
464
465 /*
466 * Move named tranche requests to shared memory. This is done for the
467 * benefit of EXEC_BACKEND builds, which otherwise wouldn't be able to
468 * call GetNamedLWLockTranche() outside postmaster.
469 */
471 {
472 /*
473 * Save the pointer to the request array in postmaster's local
474 * memory. We'll need it if we ever need to re-initialize shared
475 * memory after a crash.
476 */
478
483 }
484
485 /* Ensure desired alignment of LWLock array */
488
489 /* Initialize all LWLocks */
491 }
492}
#define MAXALIGN(LEN)
Definition c.h:826
bool IsUnderPostmaster
Definition globals.c:120
int i
Definition isn.c:77
char ** LWLockTrancheNames
Definition lwlock.c:154
int NamedLWLockTrancheRequests
Definition lwlock.c:192
static NamedLWLockTrancheRequest * LocalNamedLWLockTrancheRequestArray
Definition lwlock.c:196
static void InitializeLWLocks(void)
Definition lwlock.c:498
NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition lwlock.c:193
LWLockPadded * MainLWLockArray
Definition lwlock.c:161
int * LWLockCounter
Definition lwlock.c:199
Size LWLockShmemSize(void)
Definition lwlock.c:397
#define MAX_NAMED_TRANCHES
Definition lwlock.c:204
#define LWLOCK_PADDED_SIZE
Definition lwlock.h:62
#define NAMEDATALEN
void * ShmemAlloc(Size size)
Definition shmem.c:154

References fb(), i, InitializeLWLocks(), IsUnderPostmaster, LocalNamedLWLockTrancheRequestArray, LWLOCK_PADDED_SIZE, LWLockCounter, LWLockShmemSize(), LWLockTrancheNames, LWTRANCHE_FIRST_USER_DEFINED, MainLWLockArray, MAX_NAMED_TRANCHES, MAXALIGN, NAMEDATALEN, NamedLWLockTrancheRequestArray, NamedLWLockTrancheRequests, and ShmemAlloc().

Referenced by CreateOrAttachShmemStructs().

◆ GetLWLockIdentifier()

const char * GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)
extern

Definition at line 773 of file lwlock.c.

774{
775 Assert(classId == PG_WAIT_LWLOCK);
776 /* The event IDs are just tranche numbers. */
778}
#define Assert(condition)
Definition c.h:873
static const char * GetLWTrancheName(uint16 trancheId)
Definition lwlock.c:737
#define PG_WAIT_LWLOCK

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

Referenced by pgstat_get_wait_event().

◆ GetNamedLWLockTranche()

LWLockPadded * GetNamedLWLockTranche ( const char tranche_name)
extern

Definition at line 566 of file lwlock.c.

567{
568 int lock_pos;
569 int i;
570
571 /*
572 * Obtain the position of base address of LWLock belonging to requested
573 * tranche_name in MainLWLockArray. LWLocks for named tranches are placed
574 * in MainLWLockArray after fixed locks.
575 */
577 for (i = 0; i < NamedLWLockTrancheRequests; i++)
578 {
579 if (strcmp(NamedLWLockTrancheRequestArray[i].tranche_name,
580 tranche_name) == 0)
581 return &MainLWLockArray[lock_pos];
582
584 }
585
586 elog(ERROR, "requested tranche is not registered");
587
588 /* just to keep compiler quiet */
589 return NULL;
590}
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define NUM_FIXED_LWLOCKS
Definition lwlock.h:107

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

Referenced by pgss_shmem_startup(), and test_lwlock_tranche_lookup().

◆ InitLWLockAccess()

void InitLWLockAccess ( void  )
extern

Definition at line 550 of file lwlock.c.

551{
552#ifdef LWLOCK_STATS
554#endif
555}

References fb().

Referenced by InitAuxiliaryProcess(), and InitProcess().

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)
extern

Definition at line 1176 of file lwlock.c.

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

References Assert, elog, ERROR, fb(), held_lwlocks, HOLD_INTERRUPTS, IsUnderPostmaster, LWLockHandle::lock, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_WAKE_IN_PROGRESS, 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_and_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(), abort_logical_decoding_activation(), AbsorbSyncRequests(), ActivateCommitTs(), addLSNWaiter(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_load_buffers(), AsyncNotifyFreezeXids(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtEOXact_LogicalRepWorkers(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacLauncherMain(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BecomeRegisteredListener(), btparallelrescan(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckLogicalSlotExists(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), CheckTableForSerializableConflictIn(), CheckTargetForConflictsIn(), choose_next_subplan_for_leader(), choose_next_subplan_for_worker(), CleanupInvalidationState(), ClearOldPredicateLocks(), ComputeXidHorizons(), consume_xids_shortcut(), copy_replication_slot(), CountDBBackends(), CountDBConnections(), CountOtherDBBackends(), CountUserBackends(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateInitDecodingContext(), CreatePredicateLock(), CreateRestartPoint(), DeactivateCommitTs(), DeleteChildTargetLocks(), DeleteLockTarget(), deleteLSNWaiter(), destroy_superblock(), DisableLogicalDecoding(), DisableLogicalDecodingIfNecessary(), 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_get_total_size_from_handle(), 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(), EnableLogicalDecoding(), ensure_active_superblock(), entry_reset(), ExecParallelHashMergeCounters(), ExecParallelHashPopChunkQueue(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), ExpireAllKnownAssignedTransactionIds(), ExpireOldKnownAssignedTransactionIds(), ExpireTreeKnownAssignedTransactionIds(), ExtendBufferedRelShared(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), FindAndDropRelationBuffers(), FindDeletedTupleInLocalRel(), FinishPreparedTransaction(), 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(), GetMultiXactInfo(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldestUnsummarizedLSN(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionData(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetStrictOldestNonRemovableTransactionId(), GetVirtualXIDsDelayingChkpt(), GetWaitEventCustomIdentifier(), GetWaitEventCustomNames(), GetWalSummarizerState(), HaveVirtualXIDsDelayingChkpt(), init_conflict_slot_xmin(), init_dsm_registry(), initGlobalChannelTable(), InitWalSender(), injection_shmem_startup(), InjectionPointAttach(), InjectionPointDetach(), InjectionPointList(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), InvalidatePossiblyObsoleteSlot(), InvalidateVictimBuffer(), IoWorkerMain(), IsInstallXLogFileSegmentActive(), IsLogicalDecodingEnabled(), IsXLogLogicalInfoEnabled(), KnownAssignedXidsCompress(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_launcher_attach_dshmem(), logicalrep_pa_worker_stop(), logicalrep_reset_seqsync_start_time(), 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(), 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(), ProcessSequencesForSync(), ProcessSyncingTablesForApply(), ProcKill(), ProcNumberGetTransactionIds(), ProcSleep(), ReachedEndOfBackup(), read_relmap_file(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadReplicationSlot(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePreInvalidate(), RelationMapCopy(), RelationMapFinishBootstrap(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), relmap_redo(), RemoveScratchTarget(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDropPtr(), ReplicationSlotName(), ReplicationSlotRelease(), ReplicationSlotReserveWal(), ReplicationSlotsComputeLogicalRestartLSN(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), replorigin_advance(), replorigin_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset_internal(), replorigin_session_setup(), replorigin_state_clear(), RequestDisableLogicalDecoding(), reserve_wal_for_local_slot(), ResetInstallXLogFileSegmentActive(), resize(), RestoreScratchTarget(), restoreTwoPhaseData(), SaveSlotToPath(), SearchNamedReplicationSlot(), SerialAdd(), SerialGetMinConflictCommitSeqNo(), SerialInit(), SerialSetActiveSerXmin(), set_indexsafe_procflags(), set_val_in_shmem(), SetCommitTsLimit(), SetInstallXLogFileSegmentActive(), SetMultiXactIdLimit(), SetNextObjectId(), SetOldestOffset(), SetTransactionIdLimit(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SignalVirtualTransaction(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SimpleLruZeroAndWritePage(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), StandbyRecoverPreparedTransactions(), StandbySlotsHaveCaughtup(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SummarizeWAL(), SwitchIntoArchiveRecovery(), synchronize_one_slot(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateBackgroundWorkersForDatabase(), TerminateOtherDBBackends(), test_aio_shmem_startup(), test_custom_stats_fixed_reset_all_cb(), test_custom_stats_fixed_snapshot_cb(), test_custom_stats_fixed_update(), test_slru_page_exists(), test_slru_page_read(), test_slru_page_write(), TransactionGroupUpdateXidStatus(), TransactionIdGetCommitTsData(), TransactionIdIsInProgress(), TransactionIdSetPageStatus(), TransactionTreeSetCommitTsData(), TransferPredicateLocksToNewTarget(), TrimCLOG(), TrimMultiXact(), TruncateMultiXact(), TwoPhaseGetGXact(), TwoPhaseGetOldestXidInCommit(), TwoPhaseGetXidByVirtualXID(), update_cached_xid_range(), update_synced_slots_inactive_since(), UpdateLogicalDecodingStatusEndOfRecovery(), UpdateMinRecoveryPoint(), vac_truncate_clog(), vacuum_rel(), VacuumUpdateCosts(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_table_state_change(), wait_for_worker_state_change(), WaitEventCustomNew(), WaitForReplicationWorkerAttach(), WaitForWalSummarization(), wakeupWaiters(), WakeupWalSummarizer(), WALInsertLockAcquire(), WALInsertLockAcquireExclusive(), WalSummarizerMain(), WalSummarizerShutdown(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), and XLogReportParameters().

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)
extern

Definition at line 1404 of file lwlock.c.

1405{
1406 PGPROC *proc = MyProc;
1407 bool mustwait;
1408 int extraWaits = 0;
1409#ifdef LWLOCK_STATS
1411
1413#endif
1414
1416
1417 PRINT_LWDEBUG("LWLockAcquireOrWait", lock, mode);
1418
1419 /* Ensure we will have room to remember the lock */
1421 elog(ERROR, "too many LWLocks taken");
1422
1423 /*
1424 * Lock out cancel/die interrupts until we exit the code section protected
1425 * by the LWLock. This ensures that interrupts will not interfere with
1426 * manipulations of data structures in shared memory.
1427 */
1429
1430 /*
1431 * NB: We're using nearly the same twice-in-a-row lock acquisition
1432 * protocol as LWLockAcquire(). Check its comments for details.
1433 */
1435
1436 if (mustwait)
1437 {
1439
1441
1442 if (mustwait)
1443 {
1444 /*
1445 * Wait until awakened. Like in LWLockAcquire, be prepared for
1446 * bogus wakeups.
1447 */
1448 LOG_LWDEBUG("LWLockAcquireOrWait", lock, "waiting");
1449
1450#ifdef LWLOCK_STATS
1451 lwstats->block_count++;
1452#endif
1453
1457
1458 for (;;)
1459 {
1460 PGSemaphoreLock(proc->sem);
1461 if (proc->lwWaiting == LW_WS_NOT_WAITING)
1462 break;
1463 extraWaits++;
1464 }
1465
1466#ifdef LOCK_DEBUG
1467 {
1468 /* not waiting anymore */
1470
1472 }
1473#endif
1477
1478 LOG_LWDEBUG("LWLockAcquireOrWait", lock, "awakened");
1479 }
1480 else
1481 {
1482 LOG_LWDEBUG("LWLockAcquireOrWait", lock, "acquired, undoing queue");
1483
1484 /*
1485 * Got lock in the second attempt, undo queueing. We need to treat
1486 * this as having successfully acquired the lock, otherwise we'd
1487 * not necessarily wake up people we've prevented from acquiring
1488 * the lock.
1489 */
1490 LWLockDequeueSelf(lock);
1491 }
1492 }
1493
1494 /*
1495 * Fix the process wait semaphore's count for any absorbed wakeups.
1496 */
1497 while (extraWaits-- > 0)
1498 PGSemaphoreUnlock(proc->sem);
1499
1500 if (mustwait)
1501 {
1502 /* Failed to get lock, so release interrupt holdoff */
1504 LOG_LWDEBUG("LWLockAcquireOrWait", lock, "failed");
1507 }
1508 else
1509 {
1510 LOG_LWDEBUG("LWLockAcquireOrWait", lock, "succeeded");
1511 /* Add lock to list of locks held by this backend */
1516 }
1517
1518 return !mustwait;
1519}
#define RESUME_INTERRUPTS()
Definition miscadmin.h:136

References Assert, elog, ERROR, fb(), 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 
)
extern

Definition at line 1929 of file lwlock.c.

1930{
1931 char *held_lock_addr;
1932 char *begin;
1933 char *end;
1934 int i;
1935
1936 begin = (char *) lock;
1937 end = begin + nlocks * stride;
1938 for (i = 0; i < num_held_lwlocks; i++)
1939 {
1940 held_lock_addr = (char *) held_lwlocks[i].lock;
1941 if (held_lock_addr >= begin &&
1942 held_lock_addr < end &&
1943 (held_lock_addr - begin) % stride == 0)
1944 return true;
1945 }
1946 return false;
1947}

References fb(), held_lwlocks, i, and num_held_lwlocks.

◆ LWLockConditionalAcquire()

bool LWLockConditionalAcquire ( LWLock lock,
LWLockMode  mode 
)
extern

Definition at line 1347 of file lwlock.c.

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

References Assert, elog, ERROR, fb(), 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 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().

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

◆ LWLockInitialize()

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( const char name)
extern

Definition at line 596 of file lwlock.c.

597{
598 int result;
599
600 if (!name)
603 errmsg("tranche name cannot be NULL")));
604
605 if (strlen(name) >= NAMEDATALEN)
608 errmsg("tranche name too long"),
609 errdetail("LWLock tranche names must be no longer than %d bytes.",
610 NAMEDATALEN - 1)));
611
612 /*
613 * We use the ShmemLock spinlock to protect LWLockCounter and
614 * LWLockTrancheNames.
615 */
617
619 {
622 (errmsg("maximum number of tranches already registered"),
623 errdetail("No more than %d tranches may be registered.",
625 }
626
627 result = (*LWLockCounter)++;
630
632
633 return result;
634}
int errdetail(const char *fmt,...)
Definition elog.c:1216
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define ereport(elevel,...)
Definition elog.h:150
static int LocalLWLockCounter
Definition lwlock.c:202
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
slock_t * ShmemLock
Definition shmem.c:90
#define SpinLockRelease(lock)
Definition spin.h:61
#define SpinLockAcquire(lock)
Definition spin.h:59

References ereport, errcode(), errdetail(), errmsg(), ERROR, fb(), LocalLWLockCounter, LWLockCounter, LWLockTrancheNames, LWTRANCHE_FIRST_USER_DEFINED, MAX_NAMED_TRANCHES, name, NAMEDATALEN, ShmemLock, SpinLockAcquire, SpinLockRelease, and strlcpy().

Referenced by apw_init_state(), GetNamedDSA(), GetNamedDSHash(), init_tdr_dsm(), init_tranche(), InitializeLWLocks(), test_basic(), test_create(), test_empty(), test_lwlock_tranche_creation(), test_lwlock_tranches(), test_random(), and test_slru_shmem_startup().

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)
extern

Definition at line 1793 of file lwlock.c.

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

References Assert, elog, ERROR, fb(), held_lwlocks, i, LOG_LWDEBUG, LW_EXCLUSIVE, LW_FLAG_HAS_WAITERS, LW_FLAG_WAKE_IN_PROGRESS, 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_parallel_done(), _bt_parallel_primscan_schedule(), _bt_parallel_release(), _bt_parallel_seize(), _bt_start_vacuum(), _bt_vacuum_cycleid(), abort_logical_decoding_activation(), AbsorbSyncRequests(), ActivateCommitTs(), addLSNWaiter(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_load_buffers(), AsyncNotifyFreezeXids(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueProcessPageEntries(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtEOXact_LogicalRepWorkers(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacLauncherMain(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BecomeRegisteredListener(), btparallelrescan(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckLogicalSlotExists(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), CheckTableForSerializableConflictIn(), CheckTargetForConflictsIn(), choose_next_subplan_for_leader(), choose_next_subplan_for_worker(), CleanupInvalidationState(), ClearOldPredicateLocks(), ComputeXidHorizons(), consume_xids_shortcut(), copy_replication_slot(), CountDBBackends(), CountDBConnections(), CountOtherDBBackends(), CountUserBackends(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateInitDecodingContext(), CreatePredicateLock(), CreateRestartPoint(), DeactivateCommitTs(), DeleteChildTargetLocks(), DeleteLockTarget(), deleteLSNWaiter(), destroy_superblock(), DisableLogicalDecoding(), DisableLogicalDecodingIfNecessary(), 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_get_total_size_from_handle(), 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(), EnableLogicalDecoding(), ensure_active_superblock(), entry_reset(), ExecParallelHashMergeCounters(), ExecParallelHashPopChunkQueue(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), ExpireAllKnownAssignedTransactionIds(), ExpireOldKnownAssignedTransactionIds(), ExpireTreeKnownAssignedTransactionIds(), ExtendBufferedRelShared(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), find_multixact_start(), FindAndDropRelationBuffers(), FindDeletedTupleInLocalRel(), FinishPreparedTransaction(), 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(), GetMultiXactInfo(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldestUnsummarizedLSN(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetStrictOldestNonRemovableTransactionId(), GetVirtualXIDsDelayingChkpt(), GetWaitEventCustomIdentifier(), GetWaitEventCustomNames(), GetWalSummarizerState(), HaveVirtualXIDsDelayingChkpt(), init_conflict_slot_xmin(), init_dsm_registry(), initGlobalChannelTable(), InitWalSender(), injection_shmem_startup(), InjectionPointAttach(), InjectionPointDetach(), InjectionPointList(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), InvalidatePossiblyObsoleteSlot(), InvalidateVictimBuffer(), IoWorkerMain(), IsInstallXLogFileSegmentActive(), IsLogicalDecodingEnabled(), IsXLogLogicalInfoEnabled(), KnownAssignedXidsCompress(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_launcher_attach_dshmem(), logicalrep_pa_worker_stop(), logicalrep_reset_seqsync_start_time(), 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(), 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(), ProcessSequencesForSync(), ProcessSyncingTablesForApply(), ProcKill(), ProcNumberGetTransactionIds(), ProcSleep(), ReachedEndOfBackup(), read_relmap_file(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadReplicationSlot(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePostInvalidate(), RelationMapCopy(), RelationMapFinishBootstrap(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), relmap_redo(), RemoveScratchTarget(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDropPtr(), ReplicationSlotName(), ReplicationSlotRelease(), ReplicationSlotReserveWal(), ReplicationSlotsComputeLogicalRestartLSN(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), replorigin_advance(), replorigin_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset_internal(), replorigin_session_setup(), replorigin_state_clear(), RequestDisableLogicalDecoding(), reserve_wal_for_local_slot(), ResetInstallXLogFileSegmentActive(), resize(), RestoreScratchTarget(), restoreTwoPhaseData(), SaveSlotToPath(), SearchNamedReplicationSlot(), SerialAdd(), SerialGetMinConflictCommitSeqNo(), SerialInit(), SerialSetActiveSerXmin(), set_indexsafe_procflags(), set_val_in_shmem(), SetCommitTsLimit(), SetInstallXLogFileSegmentActive(), SetMultiXactIdLimit(), SetNextObjectId(), SetOldestOffset(), SetTransactionIdLimit(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SignalVirtualTransaction(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SimpleLruZeroAndWritePage(), 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(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateBackgroundWorkersForDatabase(), TerminateOtherDBBackends(), test_aio_shmem_startup(), test_custom_stats_fixed_reset_all_cb(), test_custom_stats_fixed_snapshot_cb(), test_custom_stats_fixed_update(), test_slru_page_exists(), test_slru_page_read(), test_slru_page_readonly(), test_slru_page_write(), TransactionGroupUpdateXidStatus(), TransactionIdGetCommitTsData(), TransactionIdGetStatus(), TransactionIdIsInProgress(), TransactionIdSetPageStatus(), TransactionTreeSetCommitTsData(), TransferPredicateLocksToNewTarget(), TrimCLOG(), TrimMultiXact(), TruncateMultiXact(), TwoPhaseGetGXact(), TwoPhaseGetOldestXidInCommit(), TwoPhaseGetXidByVirtualXID(), update_cached_xid_range(), update_synced_slots_inactive_since(), UpdateLogicalDecodingStatusEndOfRecovery(), UpdateMinRecoveryPoint(), vac_truncate_clog(), vacuum_rel(), VacuumUpdateCosts(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_table_state_change(), wait_for_worker_state_change(), WaitEventCustomNew(), WaitForReplicationWorkerAttach(), WaitForWalSummarization(), wakeupWaiters(), WakeupWalSummarizer(), WalSummarizerMain(), WalSummarizerShutdown(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), XLogNeedsFlush(), and XLogReportParameters().

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )
extern

◆ LWLockReleaseClearVar()

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

Definition at line 1866 of file lwlock.c.

1867{
1868 /*
1869 * Note that pg_atomic_exchange_u64 is a full barrier, so we're guaranteed
1870 * that the variable is updated before releasing the lock.
1871 */
1873
1874 LWLockRelease(lock);
1875}
static uint64 pg_atomic_exchange_u64(volatile pg_atomic_uint64 *ptr, uint64 newval)
Definition atomics.h:513

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

Referenced by WALInsertLockRelease().

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )
extern

Definition at line 397 of file lwlock.c.

398{
399 Size size;
400 int numLocks = NUM_FIXED_LWLOCKS;
401
402 /*
403 * If re-initializing shared memory, the request array will no longer be
404 * accessible, so switch to the copy in postmaster's local memory. We'll
405 * copy it back into shared memory later when CreateLWLocks() is called
406 * again.
407 */
410
411 /* Calculate total number of locks needed in the main array. */
412 numLocks += NumLWLocksForNamedTranches();
413
414 /* Space for dynamic allocation counter. */
415 size = MAXALIGN(sizeof(int));
416
417 /* Space for named tranches. */
418 size = add_size(size, mul_size(MAX_NAMED_TRANCHES, sizeof(char *)));
420
421 /*
422 * Make space for named tranche requests. This is done for the benefit of
423 * EXEC_BACKEND builds, which otherwise wouldn't be able to call
424 * GetNamedLWLockTranche() outside postmaster.
425 */
428
429 /* Space for the LWLock array, plus room for cache line alignment. */
430 size = add_size(size, LWLOCK_PADDED_SIZE);
431 size = add_size(size, mul_size(numLocks, sizeof(LWLockPadded)));
432
433 return size;
434}
static int NumLWLocksForNamedTranches(void)
Definition lwlock.c:382
Size add_size(Size s1, Size s2)
Definition shmem.c:495
Size mul_size(Size s1, Size s2)
Definition shmem.c:510

References add_size(), LocalNamedLWLockTrancheRequestArray, LWLOCK_PADDED_SIZE, MAX_NAMED_TRANCHES, MAXALIGN, mul_size(), NAMEDATALEN, NamedLWLockTrancheRequestArray, NamedLWLockTrancheRequests, NUM_FIXED_LWLOCKS, and NumLWLocksForNamedTranches().

Referenced by CalculateShmemSize(), and CreateLWLocks().

◆ LWLockUpdateVar()

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

Definition at line 1728 of file lwlock.c.

1729{
1732
1733 PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1734
1735 /*
1736 * Note that pg_atomic_exchange_u64 is a full barrier, so we're guaranteed
1737 * that the variable is updated before waking up waiters.
1738 */
1740
1742
1743 LWLockWaitListLock(lock);
1744
1746
1747 /*
1748 * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1749 * up. They are always in the front of the queue.
1750 */
1751 proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1752 {
1753 PGPROC *waiter = GetPGProcByNumber(iter.cur);
1754
1755 if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1756 break;
1757
1758 proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1759 proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1760
1761 /* see LWLockWakeup() */
1762 Assert(waiter->lwWaiting == LW_WS_WAITING);
1764 }
1765
1766 /* We are done updating shared state of the lock itself. */
1768
1769 /*
1770 * Awaken any waiters I removed from the queue.
1771 */
1772 proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1773 {
1774 PGPROC *waiter = GetPGProcByNumber(iter.cur);
1775
1776 proclist_delete(&wakeup, iter.cur, lwWaitLink);
1777 /* check comment in LWLockWakeup() about this barrier */
1779 waiter->lwWaiting = LW_WS_NOT_WAITING;
1780 PGSemaphoreUnlock(waiter->sem);
1781 }
1782}
#define pg_write_barrier()
Definition atomics.h:155
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:237
static void LWLockWaitListLock(LWLock *lock)
Definition lwlock.c:861
static void LWLockWaitListUnlock(LWLock *lock)
Definition lwlock.c:917
#define GetPGProcByNumber(n)
Definition proc.h:446
#define proclist_delete(list, procno, link_member)
Definition proclist.h:187
#define proclist_push_tail(list, procno, link_member)
Definition proclist.h:191
#define proclist_foreach_modify(iter, lhead, link_member)
Definition proclist.h:206
uint8 lwWaitMode
Definition proc.h:247
static TimestampTz wakeup[NUM_WALRCV_WAKEUPS]

References Assert, proclist_mutable_iter::cur, fb(), 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 
)
extern

Definition at line 1592 of file lwlock.c.

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

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

Referenced by WaitXLogInsertionsToFinish().

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char tranche_name,
int  num_lwlocks 
)
extern

Definition at line 649 of file lwlock.c.

650{
653
655 elog(FATAL, "cannot request additional LWLocks outside shmem_request_hook");
656
657 if (!tranche_name)
660 errmsg("tranche name cannot be NULL")));
661
662 if (strlen(tranche_name) >= NAMEDATALEN)
665 errmsg("tranche name too long"),
666 errdetail("LWLock tranche names must be no longer than %d bytes.",
667 NAMEDATALEN - 1)));
668
670 {
675 * sizeof(NamedLWLockTrancheRequest));
676 }
677
679 {
681
684 i * sizeof(NamedLWLockTrancheRequest));
686 }
687
689 strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
690 request->num_lwlocks = num_lwlocks;
692}
#define FATAL
Definition elog.h:41
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
void * repalloc(void *pointer, Size size)
Definition mcxt.c:1632
MemoryContext TopMemoryContext
Definition mcxt.c:166
bool process_shmem_requests_in_progress
Definition miscinit.c:1790
static uint32 pg_nextpower2_32(uint32 num)

References elog, ereport, errcode(), errdetail(), errmsg(), ERROR, FATAL, fb(), i, MemoryContextAlloc(), NAMEDATALEN, NamedLWLockTrancheRequestArray, NamedLWLockTrancheRequests, pg_nextpower2_32(), process_shmem_requests_in_progress, repalloc(), strlcpy(), and TopMemoryContext.

Referenced by pgss_shmem_request(), and test_lwlock_tranches_shmem_request().

◆ StaticAssertDecl()

StaticAssertDecl ( sizeof(LWLock)<=  LWLOCK_PADDED_SIZE,
"Miscalculated LWLock padding"   
)

Variable Documentation

◆ LWLockCounter

PGDLLIMPORT int* LWLockCounter
extern

Definition at line 199 of file lwlock.c.

Referenced by CreateLWLocks(), GetLWTrancheName(), and LWLockNewTrancheId().

◆ LWLockTrancheNames

PGDLLIMPORT char** LWLockTrancheNames
extern

Definition at line 154 of file lwlock.c.

Referenced by CreateLWLocks(), GetLWTrancheName(), and LWLockNewTrancheId().

◆ MainLWLockArray

◆ NamedLWLockTrancheRequestArray

◆ NamedLWLockTrancheRequests