PostgreSQL Source Code  git master
lwlock.h File Reference
#include "port/atomics.h"
#include "storage/proclist_types.h"
#include "storage/lwlocknames.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_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_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 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 106 of file lwlock.h.

◆ LOCK_MANAGER_LWLOCK_OFFSET

#define LOCK_MANAGER_LWLOCK_OFFSET    (BUFFER_MAPPING_LWLOCK_OFFSET + NUM_BUFFER_PARTITIONS)

Definition at line 107 of file lwlock.h.

◆ LOG2_NUM_LOCK_PARTITIONS

#define LOG2_NUM_LOCK_PARTITIONS   4

Definition at line 98 of file lwlock.h.

◆ LOG2_NUM_PREDICATELOCK_PARTITIONS

#define LOG2_NUM_PREDICATELOCK_PARTITIONS   4

Definition at line 102 of file lwlock.h.

◆ LWLOCK_PADDED_SIZE

#define LWLOCK_PADDED_SIZE   PG_CACHE_LINE_SIZE

Definition at line 61 of file lwlock.h.

◆ NUM_BUFFER_PARTITIONS

#define NUM_BUFFER_PARTITIONS   128

Definition at line 95 of file lwlock.h.

◆ NUM_FIXED_LWLOCKS

Definition at line 111 of file lwlock.h.

◆ NUM_LOCK_PARTITIONS

#define NUM_LOCK_PARTITIONS   (1 << LOG2_NUM_LOCK_PARTITIONS)

Definition at line 99 of file lwlock.h.

◆ NUM_PREDICATELOCK_PARTITIONS

#define NUM_PREDICATELOCK_PARTITIONS   (1 << LOG2_NUM_PREDICATELOCK_PARTITIONS)

Definition at line 103 of file lwlock.h.

◆ PREDICATELOCK_MANAGER_LWLOCK_OFFSET

#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET    (LOCK_MANAGER_LWLOCK_OFFSET + NUM_LOCK_PARTITIONS)

Definition at line 109 of file lwlock.h.

Typedef Documentation

◆ BuiltinTrancheIds

◆ LWLock

typedef struct LWLock LWLock

◆ LWLockId

typedef LWLock* LWLockId

Definition at line 227 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_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_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:219
@ LWTRANCHE_SHARED_TIDBITMAP
Definition: lwlock.h:202
@ LWTRANCHE_SERIAL_SLRU
Definition: lwlock.h:216
@ LWTRANCHE_PER_SESSION_DSA
Definition: lwlock.h:198
@ LWTRANCHE_PARALLEL_QUERY_DSA
Definition: lwlock.h:197
@ LWTRANCHE_COMMITTS_BUFFER
Definition: lwlock.h:182
@ LWTRANCHE_PGSTATS_HASH
Definition: lwlock.h:206
@ LWTRANCHE_SUBTRANS_BUFFER
Definition: lwlock.h:183
@ LWTRANCHE_PER_SESSION_RECORD_TYPMOD
Definition: lwlock.h:200
@ LWTRANCHE_LAUNCHER_HASH
Definition: lwlock.h:209
@ LWTRANCHE_DSM_REGISTRY_DSA
Definition: lwlock.h:210
@ LWTRANCHE_XACT_BUFFER
Definition: lwlock.h:181
@ LWTRANCHE_DSM_REGISTRY_HASH
Definition: lwlock.h:211
@ LWTRANCHE_NOTIFY_SLRU
Definition: lwlock.h:215
@ LWTRANCHE_REPLICATION_ORIGIN_STATE
Definition: lwlock.h:190
@ LWTRANCHE_MULTIXACTOFFSET_SLRU
Definition: lwlock.h:214
@ LWTRANCHE_PARALLEL_APPEND
Definition: lwlock.h:203
@ LWTRANCHE_REPLICATION_SLOT_IO
Definition: lwlock.h:191
@ LWTRANCHE_SUBTRANS_SLRU
Definition: lwlock.h:217
@ LWTRANCHE_MULTIXACTMEMBER_SLRU
Definition: lwlock.h:213
@ 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:199
@ LWTRANCHE_PREDICATE_LOCK_MANAGER
Definition: lwlock.h:195
@ LWTRANCHE_BUFFER_MAPPING
Definition: lwlock.h:193
@ LWTRANCHE_SERIAL_BUFFER
Definition: lwlock.h:187
@ LWTRANCHE_LAUNCHER_DSA
Definition: lwlock.h:208
@ LWTRANCHE_PGSTATS_DSA
Definition: lwlock.h:205
@ LWTRANCHE_PARALLEL_HASH_JOIN
Definition: lwlock.h:196
@ LWTRANCHE_COMMITTS_SLRU
Definition: lwlock.h:212
@ LWTRANCHE_PGSTATS_DATA
Definition: lwlock.h:207
@ LWTRANCHE_PER_XACT_PREDICATE_LIST
Definition: lwlock.h:204
@ LWTRANCHE_XACT_SLRU
Definition: lwlock.h:218
@ LWTRANCHE_MULTIXACTOFFSET_BUFFER
Definition: lwlock.h:184
@ LWTRANCHE_WAL_INSERT
Definition: lwlock.h:188
@ LWTRANCHE_LOCK_MANAGER
Definition: lwlock.h:194
@ LWTRANCHE_SHARED_TUPLESTORE
Definition: lwlock.h:201
@ LWTRANCHE_LOCK_FASTPATH
Definition: lwlock.h:192

◆ LWLockMode

enum LWLockMode
Enumerator
LW_EXCLUSIVE 
LW_SHARED 
LW_WAIT_UNTIL_FREE 

Definition at line 114 of file lwlock.h.

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

◆ LWLockWaitState

Enumerator
LW_WS_NOT_WAITING 
LW_WS_WAITING 
LW_WS_PENDING_WAKEUP 

Definition at line 27 of file lwlock.h.

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

Function Documentation

◆ CreateLWLocks()

void CreateLWLocks ( void  )

Definition at line 451 of file lwlock.c.

452 {
453  if (!IsUnderPostmaster)
454  {
455  Size spaceLocks = LWLockShmemSize();
456  int *LWLockCounter;
457  char *ptr;
458 
459  /* Allocate space */
460  ptr = (char *) ShmemAlloc(spaceLocks);
461 
462  /* Leave room for dynamic allocation of tranches */
463  ptr += sizeof(int);
464 
465  /* Ensure desired alignment of LWLock array */
466  ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
467 
468  MainLWLockArray = (LWLockPadded *) ptr;
469 
470  /*
471  * Initialize the dynamic-allocation counter for tranches, which is
472  * stored just before the first LWLock.
473  */
474  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
475  *LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
476 
477  /* Initialize all LWLocks */
479  }
480 
481  /* Register named extension LWLock tranches in the current process. */
482  for (int i = 0; i < NamedLWLockTrancheRequests; i++)
484  NamedLWLockTrancheArray[i].trancheName);
485 }
size_t Size
Definition: c.h:592
bool IsUnderPostmaster
Definition: globals.c:117
int i
Definition: isn.c:73
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:228
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:628
int NamedLWLockTrancheRequests
Definition: lwlock.c:225
static void InitializeLWLocks(void)
Definition: lwlock.c:491
LWLockPadded * MainLWLockArray
Definition: lwlock.c:189
Size LWLockShmemSize(void)
Definition: lwlock.c:421
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:61
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 771 of file lwlock.c.

772 {
773  Assert(classId == PG_WAIT_LWLOCK);
774  /* The event IDs are just tranche numbers. */
775  return GetLWTrancheName(eventId);
776 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:743
#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 574 of file lwlock.c.

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

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

559 {
560 #ifdef LWLOCK_STATS
561  init_lwlock_stats();
562 #endif
563 }

Referenced by InitAuxiliaryProcess(), and InitProcess().

◆ LWLockAcquire()

bool LWLockAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1172 of file lwlock.c.

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

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

Referenced by _bt_end_vacuum(), _bt_start_vacuum(), _bt_vacuum_cycleid(), AbsorbSyncRequests(), ActivateCommitTs(), AdjustToFullTransactionId(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtEOXact_LogicalRepWorkers(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BootStrapCLOG(), BootStrapMultiXact(), BootStrapSUBTRANS(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), CheckTableForSerializableConflictIn(), CheckTargetForConflictsIn(), choose_next_subplan_for_leader(), choose_next_subplan_for_worker(), CleanupInvalidationState(), ClearOldPredicateLocks(), clog_redo(), commit_ts_redo(), ComputeXidHorizons(), consume_xids_shortcut(), copy_replication_slot(), CountDBBackends(), CountDBConnections(), CountOtherDBBackends(), CountUserBackends(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateInitDecodingContext(), CreatePredicateLock(), CreateRestartPoint(), DeactivateCommitTs(), DeleteChildTargetLocks(), DeleteLockTarget(), destroy_superblock(), do_autovacuum(), do_pg_backup_start(), do_pg_backup_stop(), do_start_worker(), DropAllPredicateLocksFromTable(), DropSubscription(), DropTableSpace(), dsa_allocate_extended(), dsa_dump(), dsa_free(), dsa_get_total_size(), dsa_pin(), dsa_release_in_place(), dsa_set_size_limit(), dsa_trim(), dsa_unpin(), dshash_delete_key(), dshash_dump(), dshash_find(), dshash_find_or_insert(), dshash_seq_next(), dsm_attach(), dsm_create(), dsm_detach(), dsm_pin_segment(), dsm_unpin_segment(), ensure_active_superblock(), entry_reset(), Exec_ListenPreCommit(), ExecParallelHashMergeCounters(), ExecParallelHashPopChunkQueue(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), ExpireAllKnownAssignedTransactionIds(), ExpireOldKnownAssignedTransactionIds(), ExpireTreeKnownAssignedTransactionIds(), ExtendBufferedRelShared(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), FindAndDropRelationBuffers(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), FlushRelationsAllBuffers(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), get_local_synced_slots(), get_val_in_shmem(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLeaderApplyWorkerPid(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldestUnsummarizedLSN(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionData(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetVirtualXIDsDelayingChkpt(), GetWaitEventExtensionIdentifier(), GetWaitEventExtensionNames(), GetWalSummarizerState(), HaveVirtualXIDsDelayingChkpt(), init_dsm_registry(), InjectionPointAttach(), InjectionPointDetach(), InjectionPointRun(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), InvalidatePossiblyObsoleteSlot(), InvalidateVictimBuffer(), IsInstallXLogFileSegmentActive(), KnownAssignedXidsCompress(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockBuffer(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_launcher_attach_dshmem(), logicalrep_pa_worker_stop(), logicalrep_worker_attach(), logicalrep_worker_detach(), logicalrep_worker_launch(), logicalrep_worker_stop(), logicalrep_worker_stop_internal(), logicalrep_worker_wakeup(), LookupGXact(), MarkAsPrepared(), MarkAsPreparing(), MaybeExtendOffsetSlru(), multixact_redo(), MultiXactAdvanceNextMXact(), MultiXactGetCheckptMulti(), MultiXactIdSetOldestMember(), MultiXactIdSetOldestVisible(), MultiXactSetNextMXact(), PageIsPredicateLocked(), perform_relmap_update(), pg_control_checkpoint(), pg_control_init(), pg_control_recovery(), pg_control_system(), pg_get_replication_slots(), pg_get_shmem_allocations(), pg_notification_queue_usage(), pg_show_replication_origin_status(), pg_stat_get_subscription(), pg_stat_statements_internal(), pg_xact_status(), pgss_shmem_startup(), pgss_store(), pgstat_archiver_reset_all_cb(), pgstat_archiver_snapshot_cb(), pgstat_bgwriter_reset_all_cb(), pgstat_bgwriter_snapshot_cb(), pgstat_build_snapshot(), pgstat_checkpointer_reset_all_cb(), pgstat_checkpointer_snapshot_cb(), pgstat_fetch_replslot(), pgstat_flush_io(), pgstat_flush_wal(), pgstat_io_reset_all_cb(), pgstat_io_snapshot_cb(), pgstat_lock_entry(), pgstat_lock_entry_shared(), pgstat_reset_matching_entries(), pgstat_reset_replslot(), pgstat_reset_slru_counter_internal(), pgstat_slru_flush(), pgstat_slru_snapshot_cb(), pgstat_wal_reset_all_cb(), pgstat_wal_snapshot_cb(), PostPrepare_Locks(), PostPrepare_MultiXact(), PostPrepare_Twophase(), PreCommit_CheckForSerializationFailure(), PreCommit_Notify(), predicatelock_twophase_recover(), PredicateLockPageSplit(), PredicateLockTwoPhaseFinish(), PrefetchSharedBuffer(), PrescanPreparedTransactions(), ProcArrayAdd(), ProcArrayApplyRecoveryInfo(), ProcArrayApplyXidAssignment(), ProcArrayClearTransaction(), ProcArrayEndTransaction(), ProcArrayGetReplicationSlotXmin(), ProcArrayGroupClearXid(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), ProcArrayRemove(), ProcArraySetReplicationSlotXmin(), process_syncing_tables_for_apply(), ProcKill(), ProcNumberGetTransactionIds(), ProcSleep(), ReachedEndOfBackup(), read_relmap_file(), ReadBuffer_common(), ReadMultiXactCounts(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadReplicationSlot(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePreInvalidate(), RelationMapCopy(), RelationMapFinishBootstrap(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), relmap_redo(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDropPtr(), ReplicationSlotName(), ReplicationSlotRelease(), ReplicationSlotsComputeLogicalRestartLSN(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), replorigin_advance(), replorigin_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset(), replorigin_session_setup(), replorigin_state_clear(), resize(), RestoreScratchTarget(), restoreTwoPhaseData(), SaveSlotToPath(), SearchNamedReplicationSlot(), SerialAdd(), SerialGetMinConflictCommitSeqNo(), SerialInit(), SerialSetActiveSerXmin(), set_indexsafe_procflags(), set_val_in_shmem(), SetCommitTsLimit(), SetInstallXLogFileSegmentActive(), SetMultiXactIdLimit(), SetNextObjectId(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetWalSummarizerLatch(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SignalVirtualTransaction(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), StandbyRecoverPreparedTransactions(), StandbySlotsHaveCaughtup(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SummarizeWAL(), SwitchIntoArchiveRecovery(), synchronize_one_slot(), SyncOneBuffer(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateOtherDBBackends(), test_slru_page_exists(), test_slru_page_read(), test_slru_page_write(), TransactionGroupUpdateXidStatus(), TransactionIdGetCommitTsData(), TransactionIdIsActive(), TransactionIdIsInProgress(), TransactionIdSetPageStatus(), TransactionTreeSetCommitTsData(), TransferPredicateLocksToNewTarget(), TrimCLOG(), TrimMultiXact(), TruncateMultiXact(), TwoPhaseGetGXact(), TwoPhaseGetXidByVirtualXID(), update_cached_xid_range(), UpdateMinRecoveryPoint(), vac_truncate_clog(), vacuum_rel(), VacuumUpdateCosts(), validate_standby_slots(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitEventExtensionNew(), WaitForReplicationWorkerAttach(), WaitForWalSummarization(), WALInsertLockAcquire(), WALInsertLockAcquireExclusive(), WalSummarizerMain(), WalSummarizerShutdown(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogReportParameters(), and XLogShutdownWalRcv().

◆ LWLockAcquireOrWait()

bool LWLockAcquireOrWait ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1400 of file lwlock.c.

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

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

Referenced by XLogFlush().

◆ LWLockAnyHeldByMe()

bool LWLockAnyHeldByMe ( LWLock lock,
int  nlocks,
size_t  stride 
)

Definition at line 1915 of file lwlock.c.

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

References held_lwlocks, i, and num_held_lwlocks.

◆ LWLockConditionalAcquire()

bool LWLockConditionalAcquire ( LWLock lock,
LWLockMode  mode 
)

Definition at line 1343 of file lwlock.c.

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

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

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

◆ LWLockHeldByMe()

◆ LWLockHeldByMeInMode()

◆ LWLockInitialize()

void LWLockInitialize ( LWLock lock,
int  tranche_id 
)

Definition at line 707 of file lwlock.c.

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

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

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

◆ LWLockNewTrancheId()

int LWLockNewTrancheId ( void  )

Definition at line 604 of file lwlock.c.

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

References MainLWLockArray, ShmemLock, SpinLockAcquire, and SpinLockRelease.

Referenced by apw_init_state(), InitializeLWLocks(), tdr_init_shmem(), test_basic(), test_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 628 of file lwlock.c.

629 {
630  /* This should only be called for user-defined tranches. */
631  if (tranche_id < LWTRANCHE_FIRST_USER_DEFINED)
632  return;
633 
634  /* Convert to array index. */
635  tranche_id -= LWTRANCHE_FIRST_USER_DEFINED;
636 
637  /* If necessary, create or enlarge array. */
638  if (tranche_id >= LWLockTrancheNamesAllocated)
639  {
640  int newalloc;
641 
642  newalloc = pg_nextpower2_32(Max(8, tranche_id + 1));
643 
644  if (LWLockTrancheNames == NULL)
645  LWLockTrancheNames = (const char **)
647  newalloc * sizeof(char *));
648  else
651  LWLockTrancheNamesAllocated = newalloc;
652  }
653 
654  LWLockTrancheNames[tranche_id] = tranche_name;
655 }
#define Max(x, y)
Definition: c.h:985
static int LWLockTrancheNamesAllocated
Definition: lwlock.c:182
static const char ** LWLockTrancheNames
Definition: lwlock.c:181
MemoryContext TopMemoryContext
Definition: mcxt.c:137
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1202
#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_dsa_basic(), test_dsa_resowners(), test_empty(), test_random(), and test_slru_shmem_startup().

◆ LWLockRelease()

void LWLockRelease ( LWLock lock)

Definition at line 1785 of file lwlock.c.

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

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

Referenced by _bt_end_vacuum(), _bt_start_vacuum(), _bt_vacuum_cycleid(), AbsorbSyncRequests(), ActivateCommitTs(), AdjustToFullTransactionId(), AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AdvanceOldestCommitTsXid(), AdvanceXLInsertBuffer(), alloc_object(), AlterSystemSetConfigFile(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_load_buffers(), asyncQueueAddEntries(), asyncQueueAdvanceTail(), asyncQueueReadAllNotifications(), asyncQueueUnregister(), AtAbort_Twophase(), AtEOXact_LogicalRepWorkers(), AtPrepare_PredicateLocks(), attach_internal(), autoprewarm_main(), autoprewarm_start_worker(), AutoVacuumRequestWork(), AutoVacWorkerMain(), BackendPidGetProc(), BackendXidGetPid(), BecomeLockGroupLeader(), BecomeLockGroupMember(), BootStrapCLOG(), BootStrapMultiXact(), BootStrapSUBTRANS(), BufferAlloc(), CancelDBBackends(), check_for_freed_segments(), CheckDeadLock(), CheckForSerializableConflictOut(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointTwoPhase(), CheckTableForSerializableConflictIn(), CheckTargetForConflictsIn(), choose_next_subplan_for_leader(), choose_next_subplan_for_worker(), CleanupInvalidationState(), ClearOldPredicateLocks(), clog_redo(), commit_ts_redo(), ComputeXidHorizons(), consume_xids_shortcut(), copy_replication_slot(), CountDBBackends(), CountDBConnections(), CountOtherDBBackends(), CountUserBackends(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateInitDecodingContext(), CreatePredicateLock(), CreateRestartPoint(), DeactivateCommitTs(), DeleteChildTargetLocks(), DeleteLockTarget(), destroy_superblock(), do_autovacuum(), do_pg_backup_start(), do_pg_backup_stop(), do_start_worker(), DropAllPredicateLocksFromTable(), DropSubscription(), DropTableSpace(), dsa_allocate_extended(), dsa_dump(), dsa_free(), dsa_get_total_size(), dsa_pin(), dsa_release_in_place(), dsa_set_size_limit(), dsa_trim(), dsa_unpin(), dshash_delete_entry(), dshash_delete_key(), dshash_dump(), dshash_find(), dshash_find_or_insert(), dshash_release_lock(), dshash_seq_next(), dshash_seq_term(), dsm_attach(), dsm_create(), dsm_detach(), dsm_pin_segment(), dsm_unpin_segment(), ensure_active_superblock(), entry_reset(), Exec_ListenPreCommit(), ExecParallelHashMergeCounters(), ExecParallelHashPopChunkQueue(), ExecParallelHashTupleAlloc(), ExecParallelHashTuplePrealloc(), ExpireAllKnownAssignedTransactionIds(), ExpireOldKnownAssignedTransactionIds(), ExpireTreeKnownAssignedTransactionIds(), ExtendBufferedRelShared(), ExtendCLOG(), ExtendCommitTs(), ExtendMultiXactMember(), ExtendMultiXactOffset(), ExtendSUBTRANS(), FastPathGetRelationLockEntry(), FastPathTransferRelationLocks(), find_multixact_start(), FindAndDropRelationBuffers(), FinishPreparedTransaction(), FlushDatabaseBuffers(), FlushRelationBuffers(), FlushRelationsAllBuffers(), ForceTransactionIdLimitUpdate(), ForwardSyncRequest(), FreeWorkerInfo(), get_local_synced_slots(), get_val_in_shmem(), GetBackgroundWorkerPid(), GetBackgroundWorkerTypeByPid(), GetBlockerStatusData(), GetConflictingVirtualXIDs(), GetCurrentVirtualXIDs(), GetLastImportantRecPtr(), GetLastSegSwitchData(), GetLatestCommitTsData(), GetLeaderApplyWorkerPid(), GetLockConflicts(), GetLockStatusData(), GetMultiXactIdMembers(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestMultiXactId(), GetOldestRestartPoint(), GetOldestSafeDecodingTransactionId(), GetOldestUnsummarizedLSN(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetRunningTransactionLocks(), GetSafeSnapshot(), GetSafeSnapshotBlockingPids(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), GetStrictOldestNonRemovableTransactionId(), GetVictimBuffer(), GetVirtualXIDsDelayingChkpt(), GetWaitEventExtensionIdentifier(), GetWaitEventExtensionNames(), GetWalSummarizerState(), HaveVirtualXIDsDelayingChkpt(), init_dsm_registry(), InjectionPointAttach(), InjectionPointDetach(), InjectionPointRun(), InstallXLogFileSegment(), InvalidateBuffer(), InvalidateObsoleteReplicationSlots(), InvalidatePossiblyObsoleteSlot(), InvalidateVictimBuffer(), IsInstallXLogFileSegmentActive(), KnownAssignedXidsCompress(), KnownAssignedXidsReset(), lock_twophase_recover(), LockAcquireExtended(), LockBuffer(), LockErrorCleanup(), LockGXact(), LockHasWaiters(), LockRefindAndRelease(), LockRelease(), LockReleaseAll(), LockWaiterCount(), logicalrep_launcher_attach_dshmem(), logicalrep_pa_worker_stop(), logicalrep_worker_attach(), logicalrep_worker_detach(), logicalrep_worker_launch(), logicalrep_worker_stop(), logicalrep_worker_stop_internal(), logicalrep_worker_wakeup(), LogStandbySnapshot(), LookupGXact(), LWLockReleaseAll(), LWLockReleaseClearVar(), MarkAsPrepared(), MarkAsPreparing(), MaybeExtendOffsetSlru(), multixact_redo(), MultiXactAdvanceNextMXact(), MultiXactGetCheckptMulti(), MultiXactIdSetOldestMember(), MultiXactIdSetOldestVisible(), MultiXactSetNextMXact(), OnConflict_CheckForSerializationFailure(), PageIsPredicateLocked(), perform_relmap_update(), pg_control_checkpoint(), pg_control_init(), pg_control_recovery(), pg_control_system(), pg_get_replication_slots(), pg_get_shmem_allocations(), pg_notification_queue_usage(), pg_show_replication_origin_status(), pg_stat_get_subscription(), pg_stat_statements_internal(), pg_xact_status(), pgss_shmem_startup(), pgss_store(), pgstat_archiver_reset_all_cb(), pgstat_archiver_snapshot_cb(), pgstat_bgwriter_reset_all_cb(), pgstat_bgwriter_snapshot_cb(), pgstat_build_snapshot(), pgstat_checkpointer_reset_all_cb(), pgstat_checkpointer_snapshot_cb(), pgstat_fetch_replslot(), pgstat_flush_io(), pgstat_flush_wal(), pgstat_io_reset_all_cb(), pgstat_io_snapshot_cb(), pgstat_reset_matching_entries(), pgstat_reset_replslot(), pgstat_reset_slru_counter_internal(), pgstat_slru_flush(), pgstat_slru_snapshot_cb(), pgstat_unlock_entry(), pgstat_wal_reset_all_cb(), pgstat_wal_snapshot_cb(), PostPrepare_Locks(), PostPrepare_MultiXact(), PostPrepare_Twophase(), PreCommit_CheckForSerializationFailure(), PreCommit_Notify(), predicatelock_twophase_recover(), PredicateLockPageSplit(), PredicateLockTwoPhaseFinish(), PrefetchSharedBuffer(), PrescanPreparedTransactions(), ProcArrayAdd(), ProcArrayApplyRecoveryInfo(), ProcArrayApplyXidAssignment(), ProcArrayClearTransaction(), ProcArrayEndTransaction(), ProcArrayGetReplicationSlotXmin(), ProcArrayGroupClearXid(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), ProcArrayRemove(), ProcArraySetReplicationSlotXmin(), process_syncing_tables_for_apply(), ProcKill(), ProcNumberGetTransactionIds(), ProcSleep(), ReachedEndOfBackup(), read_relmap_file(), ReadMultiXactCounts(), ReadMultiXactIdRange(), ReadNextFullTransactionId(), ReadNextMultiXactId(), ReadReplicationSlot(), RecordNewMultiXact(), RecoverPreparedTransactions(), RegisterDynamicBackgroundWorker(), RegisterPredicateLockingXid(), RelationCacheInitFilePostInvalidate(), RelationMapCopy(), RelationMapFinishBootstrap(), ReleaseOneSerializableXact(), ReleasePredicateLocks(), relmap_redo(), RemoveScratchTarget(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDropPtr(), ReplicationSlotName(), ReplicationSlotRelease(), ReplicationSlotsComputeLogicalRestartLSN(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), replorigin_advance(), replorigin_get_progress(), replorigin_session_advance(), replorigin_session_get_progress(), replorigin_session_reset(), replorigin_session_setup(), replorigin_state_clear(), resize(), RestoreScratchTarget(), restoreTwoPhaseData(), SaveSlotToPath(), SearchNamedReplicationSlot(), SerialAdd(), SerialGetMinConflictCommitSeqNo(), SerialInit(), SerialSetActiveSerXmin(), set_indexsafe_procflags(), set_val_in_shmem(), SetCommitTsLimit(), SetInstallXLogFileSegmentActive(), SetMultiXactIdLimit(), SetNextObjectId(), SetOffsetVacuumLimit(), SetTransactionIdLimit(), SetWalSummarizerLatch(), SetXidCommitTsInPage(), SharedInvalBackendInit(), ShmemInitStruct(), SICleanupQueue(), SIGetDataEntries(), SignalBackends(), SignalVirtualTransaction(), SIInsertDataEntries(), SimpleLruReadPage(), SimpleLruReadPage_ReadOnly(), SimpleLruTruncate(), SimpleLruWaitIO(), SimpleLruWriteAll(), SlruDeleteSegment(), SlruInternalWritePage(), SnapBuildInitialSnapshot(), ss_get_location(), ss_report_location(), StandbyRecoverPreparedTransactions(), StandbySlotsHaveCaughtup(), StartupDecodingContext(), StartupSUBTRANS(), StartupXLOG(), sts_parallel_scan_next(), SubTransGetParent(), SubTransSetParent(), SummarizeOldestCommittedSxact(), SummarizeWAL(), SwitchIntoArchiveRecovery(), synchronize_one_slot(), SyncOneBuffer(), SyncRepCancelWait(), SyncRepCleanupAtProcExit(), SyncRepReleaseWaiters(), SyncRepUpdateSyncStandbysDefined(), SyncRepWaitForLSN(), TablespaceCreateDbspace(), tbm_shared_iterate(), TerminateBackgroundWorker(), TerminateOtherDBBackends(), test_slru_page_exists(), test_slru_page_read(), test_slru_page_readonly(), test_slru_page_write(), TransactionGroupUpdateXidStatus(), TransactionIdGetCommitTsData(), TransactionIdGetStatus(), TransactionIdIsActive(), TransactionIdIsInProgress(), TransactionIdSetPageStatus(), TransactionTreeSetCommitTsData(), TransferPredicateLocksToNewTarget(), TrimCLOG(), TrimMultiXact(), TruncateMultiXact(), TwoPhaseGetGXact(), TwoPhaseGetXidByVirtualXID(), update_cached_xid_range(), UpdateMinRecoveryPoint(), vac_truncate_clog(), vacuum_rel(), VacuumUpdateCosts(), validate_standby_slots(), VirtualXactLock(), VirtualXactLockTableCleanup(), VirtualXactLockTableInsert(), wait_for_relation_state_change(), wait_for_worker_state_change(), WaitEventExtensionNew(), WaitForReplicationWorkerAttach(), WaitForWalSummarization(), WaitOnLock(), WalSummarizerMain(), WalSummarizerShutdown(), write_relcache_init_file(), xact_redo(), XidCacheRemoveRunningXids(), xlog_redo(), XLogBackgroundFlush(), XLogFlush(), XLogNeedsFlush(), XLogReportParameters(), and XLogShutdownWalRcv().

◆ LWLockReleaseAll()

void LWLockReleaseAll ( void  )

Definition at line 1880 of file lwlock.c.

1881 {
1882  while (num_held_lwlocks > 0)
1883  {
1884  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1885 
1887  }
1888 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1785

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

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

◆ LWLockReleaseClearVar()

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

Definition at line 1858 of file lwlock.c.

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

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

Referenced by WALInsertLockRelease().

◆ LWLockShmemSize()

Size LWLockShmemSize ( void  )

Definition at line 421 of file lwlock.c.

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

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

Referenced by CalculateShmemSize(), and CreateLWLocks().

◆ LWLockUpdateVar()

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

Definition at line 1724 of file lwlock.c.

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

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

Referenced by WALInsertLockAcquireExclusive(), and WALInsertLockUpdateInsertingAt().

◆ LWLockWaitForVar()

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

Definition at line 1588 of file lwlock.c.

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

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

671 {
672  NamedLWLockTrancheRequest *request;
673 
675  elog(FATAL, "cannot request additional LWLocks outside shmem_request_hook");
676 
677  if (NamedLWLockTrancheRequestArray == NULL)
678  {
683  * sizeof(NamedLWLockTrancheRequest));
684  }
685 
687  {
689 
692  i * sizeof(NamedLWLockTrancheRequest));
694  }
695 
697  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
698  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
699  request->num_lwlocks = num_lwlocks;
701 }
#define FATAL
Definition: elog.h:41
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:217
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1528
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1168
bool process_shmem_requests_in_progress
Definition: miscinit.c:1782
#define NAMEDATALEN
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:212

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

Referenced by CreateLWLocks(), and InitializeLWLocks().

◆ NamedLWLockTrancheRequests