PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
lwlock.h File Reference
#include "port/atomics.h"
#include "storage/lwlocknames.h"
#include "storage/proclist_types.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
 
struct  NamedLWLockTranche
 

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)
 

Typedefs

typedef enum LWLockWaitState LWLockWaitState
 
typedef struct LWLock LWLock
 
typedef union LWLockPadded LWLockPadded
 
typedef struct NamedLWLockTranche NamedLWLockTranche
 
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_XACT_BUFFER = NUM_INDIVIDUAL_LWLOCKS , LWTRANCHE_COMMITTS_BUFFER , LWTRANCHE_SUBTRANS_BUFFER , LWTRANCHE_MULTIXACTOFFSET_BUFFER ,
  LWTRANCHE_MULTIXACTMEMBER_BUFFER , LWTRANCHE_NOTIFY_BUFFER , LWTRANCHE_SERIAL_BUFFER , LWTRANCHE_WAL_INSERT ,
  LWTRANCHE_BUFFER_CONTENT , LWTRANCHE_REPLICATION_ORIGIN_STATE , LWTRANCHE_REPLICATION_SLOT_IO , LWTRANCHE_LOCK_FASTPATH ,
  LWTRANCHE_BUFFER_MAPPING , LWTRANCHE_LOCK_MANAGER , LWTRANCHE_PREDICATE_LOCK_MANAGER , LWTRANCHE_PARALLEL_HASH_JOIN ,
  LWTRANCHE_PARALLEL_BTREE_SCAN , LWTRANCHE_PARALLEL_QUERY_DSA , LWTRANCHE_PER_SESSION_DSA , LWTRANCHE_PER_SESSION_RECORD_TYPE ,
  LWTRANCHE_PER_SESSION_RECORD_TYPMOD , LWTRANCHE_SHARED_TUPLESTORE , LWTRANCHE_SHARED_TIDBITMAP , LWTRANCHE_PARALLEL_APPEND ,
  LWTRANCHE_PER_XACT_PREDICATE_LIST , LWTRANCHE_PGSTATS_DSA , LWTRANCHE_PGSTATS_HASH , LWTRANCHE_PGSTATS_DATA ,
  LWTRANCHE_LAUNCHER_DSA , LWTRANCHE_LAUNCHER_HASH , LWTRANCHE_DSM_REGISTRY_DSA , LWTRANCHE_DSM_REGISTRY_HASH ,
  LWTRANCHE_COMMITTS_SLRU , LWTRANCHE_MULTIXACTMEMBER_SLRU , LWTRANCHE_MULTIXACTOFFSET_SLRU , LWTRANCHE_NOTIFY_SLRU ,
  LWTRANCHE_SERIAL_SLRU , LWTRANCHE_SUBTRANS_SLRU , LWTRANCHE_XACT_SLRU , LWTRANCHE_PARALLEL_VACUUM_DSA ,
  LWTRANCHE_AIO_URING_COMPLETION , LWTRANCHE_MEMORY_CONTEXT_REPORTING_STATE , LWTRANCHE_MEMORY_CONTEXT_REPORTING_PROC , 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)
 
void LWLockDisown (LWLock *l)
 
void LWLockReleaseDisowned (LWLock *l, LWLockMode mode)
 
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 char * GetLWLockIdentifier (uint32 classId, uint16 eventId)
 
void RequestNamedLWLockTranche (const char *tranche_name, int num_lwlocks)
 
LWLockPaddedGetNamedLWLockTranche (const char *tranche_name)
 
int LWLockNewTrancheId (void)
 
void LWLockRegisterTranche (int tranche_id, const char *tranche_name)
 
void LWLockInitialize (LWLock *lock, int tranche_id)
 

Variables

PGDLLIMPORT LWLockPaddedMainLWLockArray
 
PGDLLIMPORT NamedLWLockTrancheNamedLWLockTrancheArray
 
PGDLLIMPORT int NamedLWLockTrancheRequests
 

Macro Definition Documentation

◆ BUFFER_MAPPING_LWLOCK_OFFSET

#define BUFFER_MAPPING_LWLOCK_OFFSET   NUM_INDIVIDUAL_LWLOCKS

Definition at line 104 of file lwlock.h.

◆ LOCK_MANAGER_LWLOCK_OFFSET

#define LOCK_MANAGER_LWLOCK_OFFSET    (BUFFER_MAPPING_LWLOCK_OFFSET + NUM_BUFFER_PARTITIONS)

Definition at line 105 of file lwlock.h.

◆ LOG2_NUM_LOCK_PARTITIONS

#define LOG2_NUM_LOCK_PARTITIONS   4

Definition at line 96 of file lwlock.h.

◆ LOG2_NUM_PREDICATELOCK_PARTITIONS

#define LOG2_NUM_PREDICATELOCK_PARTITIONS   4

Definition at line 100 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 93 of file lwlock.h.

◆ NUM_FIXED_LWLOCKS

Definition at line 109 of file lwlock.h.

◆ NUM_LOCK_PARTITIONS

#define NUM_LOCK_PARTITIONS   (1 << LOG2_NUM_LOCK_PARTITIONS)

Definition at line 97 of file lwlock.h.

◆ NUM_PREDICATELOCK_PARTITIONS

#define NUM_PREDICATELOCK_PARTITIONS   (1 << LOG2_NUM_PREDICATELOCK_PARTITIONS)

Definition at line 101 of file lwlock.h.

◆ PREDICATELOCK_MANAGER_LWLOCK_OFFSET

#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET    (LOCK_MANAGER_LWLOCK_OFFSET + NUM_LOCK_PARTITIONS)

Definition at line 107 of file lwlock.h.

Typedef Documentation

◆ BuiltinTrancheIds

◆ LWLock

typedef struct LWLock LWLock

◆ LWLockId

typedef LWLock* LWLockId

Definition at line 232 of file lwlock.h.

◆ LWLockMode

typedef enum LWLockMode LWLockMode

◆ LWLockPadded

typedef union LWLockPadded LWLockPadded

◆ LWLockWaitState

◆ NamedLWLockTranche

Enumeration Type Documentation

◆ BuiltinTrancheIds

Enumerator
LWTRANCHE_XACT_BUFFER 
LWTRANCHE_COMMITTS_BUFFER 
LWTRANCHE_SUBTRANS_BUFFER 
LWTRANCHE_MULTIXACTOFFSET_BUFFER 
LWTRANCHE_MULTIXACTMEMBER_BUFFER 
LWTRANCHE_NOTIFY_BUFFER 
LWTRANCHE_SERIAL_BUFFER 
LWTRANCHE_WAL_INSERT 
LWTRANCHE_BUFFER_CONTENT 
LWTRANCHE_REPLICATION_ORIGIN_STATE 
LWTRANCHE_REPLICATION_SLOT_IO 
LWTRANCHE_LOCK_FASTPATH 
LWTRANCHE_BUFFER_MAPPING 
LWTRANCHE_LOCK_MANAGER 
LWTRANCHE_PREDICATE_LOCK_MANAGER 
LWTRANCHE_PARALLEL_HASH_JOIN 
LWTRANCHE_PARALLEL_BTREE_SCAN 
LWTRANCHE_PARALLEL_QUERY_DSA 
LWTRANCHE_PER_SESSION_DSA 
LWTRANCHE_PER_SESSION_RECORD_TYPE 
LWTRANCHE_PER_SESSION_RECORD_TYPMOD 
LWTRANCHE_SHARED_TUPLESTORE 
LWTRANCHE_SHARED_TIDBITMAP 
LWTRANCHE_PARALLEL_APPEND 
LWTRANCHE_PER_XACT_PREDICATE_LIST 
LWTRANCHE_PGSTATS_DSA 
LWTRANCHE_PGSTATS_HASH 
LWTRANCHE_PGSTATS_DATA 
LWTRANCHE_LAUNCHER_DSA 
LWTRANCHE_LAUNCHER_HASH 
LWTRANCHE_DSM_REGISTRY_DSA 
LWTRANCHE_DSM_REGISTRY_HASH 
LWTRANCHE_COMMITTS_SLRU 
LWTRANCHE_MULTIXACTMEMBER_SLRU 
LWTRANCHE_MULTIXACTOFFSET_SLRU 
LWTRANCHE_NOTIFY_SLRU 
LWTRANCHE_SERIAL_SLRU 
LWTRANCHE_SUBTRANS_SLRU 
LWTRANCHE_XACT_SLRU 
LWTRANCHE_PARALLEL_VACUUM_DSA 
LWTRANCHE_AIO_URING_COMPLETION 
LWTRANCHE_MEMORY_CONTEXT_REPORTING_STATE 
LWTRANCHE_MEMORY_CONTEXT_REPORTING_PROC 
LWTRANCHE_FIRST_USER_DEFINED 

Definition at line 179 of file lwlock.h.

180{
181 LWTRANCHE_XACT_BUFFER = NUM_INDIVIDUAL_LWLOCKS,
BuiltinTrancheIds
Definition: lwlock.h:180
@ LWTRANCHE_FIRST_USER_DEFINED
Definition: lwlock.h:224
@ LWTRANCHE_SHARED_TIDBITMAP
Definition: lwlock.h:203
@ LWTRANCHE_SERIAL_SLRU
Definition: lwlock.h:217
@ LWTRANCHE_PER_SESSION_DSA
Definition: lwlock.h:199
@ LWTRANCHE_PARALLEL_QUERY_DSA
Definition: lwlock.h:198
@ LWTRANCHE_COMMITTS_BUFFER
Definition: lwlock.h:182
@ LWTRANCHE_PARALLEL_VACUUM_DSA
Definition: lwlock.h:220
@ LWTRANCHE_AIO_URING_COMPLETION
Definition: lwlock.h:221
@ LWTRANCHE_PGSTATS_HASH
Definition: lwlock.h:207
@ LWTRANCHE_PARALLEL_BTREE_SCAN
Definition: lwlock.h:197
@ LWTRANCHE_SUBTRANS_BUFFER
Definition: lwlock.h:183
@ LWTRANCHE_PER_SESSION_RECORD_TYPMOD
Definition: lwlock.h:201
@ LWTRANCHE_LAUNCHER_HASH
Definition: lwlock.h:210
@ LWTRANCHE_DSM_REGISTRY_DSA
Definition: lwlock.h:211
@ LWTRANCHE_XACT_BUFFER
Definition: lwlock.h:181
@ LWTRANCHE_DSM_REGISTRY_HASH
Definition: lwlock.h:212
@ LWTRANCHE_NOTIFY_SLRU
Definition: lwlock.h:216
@ LWTRANCHE_REPLICATION_ORIGIN_STATE
Definition: lwlock.h:190
@ LWTRANCHE_MULTIXACTOFFSET_SLRU
Definition: lwlock.h:215
@ LWTRANCHE_PARALLEL_APPEND
Definition: lwlock.h:204
@ LWTRANCHE_REPLICATION_SLOT_IO
Definition: lwlock.h:191
@ LWTRANCHE_SUBTRANS_SLRU
Definition: lwlock.h:218
@ LWTRANCHE_MULTIXACTMEMBER_SLRU
Definition: lwlock.h:214
@ LWTRANCHE_BUFFER_CONTENT
Definition: lwlock.h:189
@ LWTRANCHE_MULTIXACTMEMBER_BUFFER
Definition: lwlock.h:185
@ LWTRANCHE_NOTIFY_BUFFER
Definition: lwlock.h:186
@ LWTRANCHE_PER_SESSION_RECORD_TYPE
Definition: lwlock.h:200
@ LWTRANCHE_PREDICATE_LOCK_MANAGER
Definition: lwlock.h:195
@ LWTRANCHE_BUFFER_MAPPING
Definition: lwlock.h:193
@ LWTRANCHE_MEMORY_CONTEXT_REPORTING_PROC
Definition: lwlock.h:223
@ LWTRANCHE_SERIAL_BUFFER
Definition: lwlock.h:187
@ LWTRANCHE_LAUNCHER_DSA
Definition: lwlock.h:209
@ LWTRANCHE_PGSTATS_DSA
Definition: lwlock.h:206
@ LWTRANCHE_PARALLEL_HASH_JOIN
Definition: lwlock.h:196
@ LWTRANCHE_COMMITTS_SLRU
Definition: lwlock.h:213
@ LWTRANCHE_PGSTATS_DATA
Definition: lwlock.h:208
@ LWTRANCHE_PER_XACT_PREDICATE_LIST
Definition: lwlock.h:205
@ LWTRANCHE_XACT_SLRU
Definition: lwlock.h:219
@ LWTRANCHE_MULTIXACTOFFSET_BUFFER
Definition: lwlock.h:184
@ LWTRANCHE_MEMORY_CONTEXT_REPORTING_STATE
Definition: lwlock.h:222
@ LWTRANCHE_WAL_INSERT
Definition: lwlock.h:188
@ LWTRANCHE_LOCK_MANAGER
Definition: lwlock.h:194
@ LWTRANCHE_SHARED_TUPLESTORE
Definition: lwlock.h:202
@ LWTRANCHE_LOCK_FASTPATH
Definition: lwlock.h:192

◆ LWLockMode

enum LWLockMode
Enumerator
LW_EXCLUSIVE 
LW_SHARED 
LW_WAIT_UNTIL_FREE 

Definition at line 112 of file lwlock.h.

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

◆ 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  )

Definition at line 464 of file lwlock.c.

465{
467 {
468 Size spaceLocks = LWLockShmemSize();
469 int *LWLockCounter;
470 char *ptr;
471
472 /* Allocate space */
473 ptr = (char *) ShmemAlloc(spaceLocks);
474
475 /* Leave room for dynamic allocation of tranches */
476 ptr += sizeof(int);
477
478 /* Ensure desired alignment of LWLock array */
479 ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
480
482
483 /*
484 * Initialize the dynamic-allocation counter for tranches, which is
485 * stored just before the first LWLock.
486 */
487 LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
488 *LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
489
490 /* Initialize all LWLocks */
492 }
493
494 /* Register named extension LWLock tranches in the current process. */
495 for (int i = 0; i < NamedLWLockTrancheRequests; i++)
497 NamedLWLockTrancheArray[i].trancheName);
498}
size_t Size
Definition: c.h:576
bool IsUnderPostmaster
Definition: globals.c:121
int i
Definition: isn.c:77
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:241
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:642
int NamedLWLockTrancheRequests
Definition: lwlock.c:238
static void InitializeLWLocks(void)
Definition: lwlock.c:504
LWLockPadded * MainLWLockArray
Definition: lwlock.c:202
Size LWLockShmemSize(void)
Definition: lwlock.c:434
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:62
void * ShmemAlloc(Size size)
Definition: shmem.c:152

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

Referenced by CreateOrAttachShmemStructs().

◆ GetLWLockIdentifier()

const char * GetLWLockIdentifier ( uint32  classId,
uint16  eventId 
)

Definition at line 781 of file lwlock.c.

782{
783 Assert(classId == PG_WAIT_LWLOCK);
784 /* The event IDs are just tranche numbers. */
785 return GetLWTrancheName(eventId);
786}
Assert(PointerIsAligned(start, uint64))
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:757
#define PG_WAIT_LWLOCK
Definition: wait_event.h:18

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

Referenced by pgstat_get_wait_event().

◆ GetNamedLWLockTranche()

LWLockPadded * GetNamedLWLockTranche ( const char *  tranche_name)

Definition at line 587 of file lwlock.c.

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

◆ InitLWLockAccess()

void InitLWLockAccess ( void  )

Definition at line 571 of file lwlock.c.

572{
573#ifdef LWLOCK_STATS
574 init_lwlock_stats();
575#endif
576}

Referenced by InitAuxiliaryProcess(), and InitProcess().

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1182 of file lwlock.c.

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

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(), AtProcExit_memstats_cleanup(), 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_process_memory_contexts(), 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(), ProcessGetMemoryContextInterrupt(), 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 1410 of file lwlock.c.

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

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

1989{
1990 char *held_lock_addr;
1991 char *begin;
1992 char *end;
1993 int i;
1994
1995 begin = (char *) lock;
1996 end = begin + nlocks * stride;
1997 for (i = 0; i < num_held_lwlocks; i++)
1998 {
1999 held_lock_addr = (char *) held_lwlocks[i].lock;
2000 if (held_lock_addr >= begin &&
2001 held_lock_addr < end &&
2002 (held_lock_addr - begin) % stride == 0)
2003 return true;
2004 }
2005 return false;
2006}

References held_lwlocks, i, and num_held_lwlocks.

◆ LWLockConditionalAcquire()

bool LWLockConditionalAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1353 of file lwlock.c.

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

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

◆ LWLockDisown()

void LWLockDisown ( LWLock l)

Definition at line 1891 of file lwlock.c.

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

References LWLockDisownInternal(), and RESUME_INTERRUPTS.

Referenced by buffer_stage_common().

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

◆ LWLockInitialize()

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( void  )

Definition at line 617 of file lwlock.c.

618{
619 int result;
620 int *LWLockCounter;
621
622 LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
623 /* We use the ShmemLock spinlock to protect LWLockCounter */
625 result = (*LWLockCounter)++;
627
628 return result;
629}
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().

◆ LWLockRegisterTranche()

void LWLockRegisterTranche ( int  tranche_id,
const char *  tranche_name 
)

Definition at line 642 of file lwlock.c.

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

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

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(), AtProcExit_memstats_cleanup(), 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(), end_memorycontext_reporting(), 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_process_memory_contexts(), 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(), ProcessGetMemoryContextInterrupt(), 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 1931 of file lwlock.c.

1932{
1933 /*
1934 * Note that pg_atomic_exchange_u64 is a full barrier, so we're guaranteed
1935 * that the variable is updated before releasing the lock.
1936 */
1937 pg_atomic_exchange_u64(valptr, val);
1938
1939 LWLockRelease(lock);
1940}
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 l,
LWLockMode  mode 
)

Definition at line 1922 of file lwlock.c.

1923{
1925}

References LWLockReleaseInternal(), and mode.

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 434 of file lwlock.c.

435{
436 Size size;
437 int i;
438 int numLocks = NUM_FIXED_LWLOCKS;
439
440 /* Calculate total number of locks needed in the main array. */
441 numLocks += NumLWLocksForNamedTranches();
442
443 /* Space for the LWLock array. */
444 size = mul_size(numLocks, sizeof(LWLockPadded));
445
446 /* Space for dynamic allocation counter, plus room for alignment. */
447 size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
448
449 /* space for named tranches. */
451
452 /* space for name of each tranche. */
453 for (i = 0; i < NamedLWLockTrancheRequests; i++)
454 size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
455
456 return size;
457}
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:419
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 1734 of file lwlock.c.

1735{
1738
1739 PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1740
1741 /*
1742 * Note that pg_atomic_exchange_u64 is a full barrier, so we're guaranteed
1743 * that the variable is updated before waking up waiters.
1744 */
1745 pg_atomic_exchange_u64(valptr, val);
1746
1748
1749 LWLockWaitListLock(lock);
1750
1752
1753 /*
1754 * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1755 * up. They are always in the front of the queue.
1756 */
1757 proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1758 {
1759 PGPROC *waiter = GetPGProcByNumber(iter.cur);
1760
1761 if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1762 break;
1763
1764 proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1765 proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1766
1767 /* see LWLockWakeup() */
1768 Assert(waiter->lwWaiting == LW_WS_WAITING);
1770 }
1771
1772 /* We are done updating shared state of the lock itself. */
1774
1775 /*
1776 * Awaken any waiters I removed from the queue.
1777 */
1778 proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1779 {
1780 PGPROC *waiter = GetPGProcByNumber(iter.cur);
1781
1782 proclist_delete(&wakeup, iter.cur, lwWaitLink);
1783 /* check comment in LWLockWakeup() about this barrier */
1785 waiter->lwWaiting = LW_WS_NOT_WAITING;
1786 PGSemaphoreUnlock(waiter->sem);
1787 }
1788}
#define pg_write_barrier()
Definition: atomics.h:157
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:239
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:101
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:869
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:921
#define GetPGProcByNumber(n)
Definition: proc.h:424
#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:225
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 1598 of file lwlock.c.

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

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

◆ RequestNamedLWLockTranche()

void RequestNamedLWLockTranche ( const char *  tranche_name,
int  num_lwlocks 
)

Definition at line 684 of file lwlock.c.

685{
687
689 elog(FATAL, "cannot request additional LWLocks outside shmem_request_hook");
690
692 {
697 * sizeof(NamedLWLockTrancheRequest));
698 }
699
701 {
703
706 i * sizeof(NamedLWLockTrancheRequest));
708 }
709
711 Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
712 strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
713 request->num_lwlocks = num_lwlocks;
715}
#define FATAL
Definition: elog.h:41
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:230
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1256
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:2167
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
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:225

References Assert(), elog, FATAL, i, MemoryContextAlloc(), NAMEDATALEN, NamedLWLockTrancheRequestArray, NamedLWLockTrancheRequests, NamedLWLockTrancheRequestsAllocated, NamedLWLockTrancheRequest::num_lwlocks, pg_nextpower2_32(), process_shmem_requests_in_progress, repalloc(), strlcpy(), TopMemoryContext, and NamedLWLockTrancheRequest::tranche_name.

Referenced by pgss_shmem_request().

◆ StaticAssertDecl()

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

Variable Documentation

◆ MainLWLockArray

◆ NamedLWLockTrancheArray

PGDLLIMPORT NamedLWLockTranche* NamedLWLockTrancheArray
extern

Definition at line 241 of file lwlock.c.

Referenced by CreateLWLocks(), and InitializeLWLocks().

◆ NamedLWLockTrancheRequests