PostgreSQL Source Code  git master
lwlock.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * lwlock.c
4  * Lightweight lock manager
5  *
6  * Lightweight locks are intended primarily to provide mutual exclusion of
7  * access to shared-memory data structures. Therefore, they offer both
8  * exclusive and shared lock modes (to support read/write and read-only
9  * access to a shared object). There are few other frammishes. User-level
10  * locking should be done with the full lock manager --- which depends on
11  * LWLocks to protect its shared state.
12  *
13  * In addition to exclusive and shared modes, lightweight locks can be used to
14  * wait until a variable changes value. The variable is initially not set
15  * when the lock is acquired with LWLockAcquire, i.e. it remains set to the
16  * value it was set to when the lock was released last, and can be updated
17  * without releasing the lock by calling LWLockUpdateVar. LWLockWaitForVar
18  * waits for the variable to be updated, or until the lock is free. When
19  * releasing the lock with LWLockReleaseClearVar() the value can be set to an
20  * appropriate value for a free lock. The meaning of the variable is up to
21  * the caller, the lightweight lock code just assigns and compares it.
22  *
23  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
24  * Portions Copyright (c) 1994, Regents of the University of California
25  *
26  * IDENTIFICATION
27  * src/backend/storage/lmgr/lwlock.c
28  *
29  * NOTES:
30  *
31  * This used to be a pretty straight forward reader-writer lock
32  * implementation, in which the internal state was protected by a
33  * spinlock. Unfortunately the overhead of taking the spinlock proved to be
34  * too high for workloads/locks that were taken in shared mode very
35  * frequently. Often we were spinning in the (obviously exclusive) spinlock,
36  * while trying to acquire a shared lock that was actually free.
37  *
38  * Thus a new implementation was devised that provides wait-free shared lock
39  * acquisition for locks that aren't exclusively locked.
40  *
41  * The basic idea is to have a single atomic variable 'lockcount' instead of
42  * the formerly separate shared and exclusive counters and to use atomic
43  * operations to acquire the lock. That's fairly easy to do for plain
44  * rw-spinlocks, but a lot harder for something like LWLocks that want to wait
45  * in the OS.
46  *
47  * For lock acquisition we use an atomic compare-and-exchange on the lockcount
48  * variable. For exclusive lock we swap in a sentinel value
49  * (LW_VAL_EXCLUSIVE), for shared locks we count the number of holders.
50  *
51  * To release the lock we use an atomic decrement to release the lock. If the
52  * new value is zero (we get that atomically), we know we can/have to release
53  * waiters.
54  *
55  * Obviously it is important that the sentinel value for exclusive locks
56  * doesn't conflict with the maximum number of possible share lockers -
57  * luckily MAX_BACKENDS makes that easily possible.
58  *
59  *
60  * The attentive reader might have noticed that naively doing the above has a
61  * glaring race condition: We try to lock using the atomic operations and
62  * notice that we have to wait. Unfortunately by the time we have finished
63  * queuing, the former locker very well might have already finished it's
64  * work. That's problematic because we're now stuck waiting inside the OS.
65 
66  * To mitigate those races we use a two phased attempt at locking:
67  * Phase 1: Try to do it atomically, if we succeed, nice
68  * Phase 2: Add ourselves to the waitqueue of the lock
69  * Phase 3: Try to grab the lock again, if we succeed, remove ourselves from
70  * the queue
71  * Phase 4: Sleep till wake-up, goto Phase 1
72  *
73  * This protects us against the problem from above as nobody can release too
74  * quick, before we're queued, since after Phase 2 we're already queued.
75  * -------------------------------------------------------------------------
76  */
77 #include "postgres.h"
78 
79 #include "miscadmin.h"
80 #include "pg_trace.h"
81 #include "pgstat.h"
82 #include "port/pg_bitutils.h"
83 #include "postmaster/postmaster.h"
84 #include "replication/slot.h"
85 #include "storage/ipc.h"
86 #include "storage/predicate.h"
87 #include "storage/proc.h"
88 #include "storage/proclist.h"
89 #include "storage/spin.h"
90 #include "utils/memutils.h"
91 
92 #ifdef LWLOCK_STATS
93 #include "utils/hsearch.h"
94 #endif
95 
96 
97 /* We use the ShmemLock spinlock to protect LWLockCounter */
98 extern slock_t *ShmemLock;
99 
100 #define LW_FLAG_HAS_WAITERS ((uint32) 1 << 30)
101 #define LW_FLAG_RELEASE_OK ((uint32) 1 << 29)
102 #define LW_FLAG_LOCKED ((uint32) 1 << 28)
103 
104 #define LW_VAL_EXCLUSIVE ((uint32) 1 << 24)
105 #define LW_VAL_SHARED 1
106 
107 #define LW_LOCK_MASK ((uint32) ((1 << 25)-1))
108 /* Must be greater than MAX_BACKENDS - which is 2^23-1, so we're fine. */
109 #define LW_SHARED_MASK ((uint32) ((1 << 24)-1))
110 
111 /*
112  * There are three sorts of LWLock "tranches":
113  *
114  * 1. The individually-named locks defined in lwlocknames.h each have their
115  * own tranche. The names of these tranches appear in IndividualLWLockNames[]
116  * in lwlocknames.c.
117  *
118  * 2. There are some predefined tranches for built-in groups of locks.
119  * These are listed in enum BuiltinTrancheIds in lwlock.h, and their names
120  * appear in BuiltinTrancheNames[] below.
121  *
122  * 3. Extensions can create new tranches, via either RequestNamedLWLockTranche
123  * or LWLockRegisterTranche. The names of these that are known in the current
124  * process appear in LWLockTrancheNames[].
125  *
126  * All these names are user-visible as wait event names, so choose with care
127  * ... and do not forget to update the documentation's list of wait events.
128  */
129 extern const char *const IndividualLWLockNames[]; /* in lwlocknames.c */
130 
131 static const char *const BuiltinTrancheNames[] = {
132  /* LWTRANCHE_XACT_BUFFER: */
133  "XactBuffer",
134  /* LWTRANCHE_COMMITTS_BUFFER: */
135  "CommitTSBuffer",
136  /* LWTRANCHE_SUBTRANS_BUFFER: */
137  "SubtransBuffer",
138  /* LWTRANCHE_MULTIXACTOFFSET_BUFFER: */
139  "MultiXactOffsetBuffer",
140  /* LWTRANCHE_MULTIXACTMEMBER_BUFFER: */
141  "MultiXactMemberBuffer",
142  /* LWTRANCHE_NOTIFY_BUFFER: */
143  "NotifyBuffer",
144  /* LWTRANCHE_SERIAL_BUFFER: */
145  "SerialBuffer",
146  /* LWTRANCHE_WAL_INSERT: */
147  "WALInsert",
148  /* LWTRANCHE_BUFFER_CONTENT: */
149  "BufferContent",
150  /* LWTRANCHE_REPLICATION_ORIGIN_STATE: */
151  "ReplicationOriginState",
152  /* LWTRANCHE_REPLICATION_SLOT_IO: */
153  "ReplicationSlotIO",
154  /* LWTRANCHE_LOCK_FASTPATH: */
155  "LockFastPath",
156  /* LWTRANCHE_BUFFER_MAPPING: */
157  "BufferMapping",
158  /* LWTRANCHE_LOCK_MANAGER: */
159  "LockManager",
160  /* LWTRANCHE_PREDICATE_LOCK_MANAGER: */
161  "PredicateLockManager",
162  /* LWTRANCHE_PARALLEL_HASH_JOIN: */
163  "ParallelHashJoin",
164  /* LWTRANCHE_PARALLEL_QUERY_DSA: */
165  "ParallelQueryDSA",
166  /* LWTRANCHE_PER_SESSION_DSA: */
167  "PerSessionDSA",
168  /* LWTRANCHE_PER_SESSION_RECORD_TYPE: */
169  "PerSessionRecordType",
170  /* LWTRANCHE_PER_SESSION_RECORD_TYPMOD: */
171  "PerSessionRecordTypmod",
172  /* LWTRANCHE_SHARED_TUPLESTORE: */
173  "SharedTupleStore",
174  /* LWTRANCHE_SHARED_TIDBITMAP: */
175  "SharedTidBitmap",
176  /* LWTRANCHE_PARALLEL_APPEND: */
177  "ParallelAppend",
178  /* LWTRANCHE_PER_XACT_PREDICATE_LIST: */
179  "PerXactPredicateList",
180  /* LWTRANCHE_PGSTATS_DSA: */
181  "PgStatsDSA",
182  /* LWTRANCHE_PGSTATS_HASH: */
183  "PgStatsHash",
184  /* LWTRANCHE_PGSTATS_DATA: */
185  "PgStatsData",
186 };
187 
189  LWTRANCHE_FIRST_USER_DEFINED - NUM_INDIVIDUAL_LWLOCKS,
190  "missing entries in BuiltinTrancheNames[]");
191 
192 /*
193  * This is indexed by tranche ID minus LWTRANCHE_FIRST_USER_DEFINED, and
194  * stores the names of all dynamically-created tranches known to the current
195  * process. Any unused entries in the array will contain NULL.
196  */
197 static const char **LWLockTrancheNames = NULL;
199 
200 /*
201  * This points to the main array of LWLocks in shared memory. Backends inherit
202  * the pointer by fork from the postmaster (except in the EXEC_BACKEND case,
203  * where we have special measures to pass it down).
204  */
206 
207 /*
208  * We use this structure to keep track of locked LWLocks for release
209  * during error recovery. Normally, only a few will be held at once, but
210  * occasionally the number can be much higher; for example, the pg_buffercache
211  * extension locks all buffer partitions simultaneously.
212  */
213 #define MAX_SIMUL_LWLOCKS 200
214 
215 /* struct representing the LWLocks we're holding */
216 typedef struct LWLockHandle
217 {
221 
222 static int num_held_lwlocks = 0;
224 
225 /* struct representing the LWLock tranche request for named tranche */
227 {
231 
234 
235 /*
236  * NamedLWLockTrancheRequests is both the valid length of the request array,
237  * and the length of the shared-memory NamedLWLockTrancheArray later on.
238  * This variable and NamedLWLockTrancheArray are non-static so that
239  * postmaster.c can copy them to child processes in EXEC_BACKEND builds.
240  */
242 
243 /* points to data in shared memory: */
245 
246 static void InitializeLWLocks(void);
247 static inline void LWLockReportWaitStart(LWLock *lock);
248 static inline void LWLockReportWaitEnd(void);
249 static const char *GetLWTrancheName(uint16 trancheId);
250 
251 #define T_NAME(lock) \
252  GetLWTrancheName((lock)->tranche)
253 
254 #ifdef LWLOCK_STATS
255 typedef struct lwlock_stats_key
256 {
257  int tranche;
258  void *instance;
259 } lwlock_stats_key;
260 
261 typedef struct lwlock_stats
262 {
263  lwlock_stats_key key;
264  int sh_acquire_count;
265  int ex_acquire_count;
266  int block_count;
267  int dequeue_self_count;
268  int spin_delay_count;
269 } lwlock_stats;
270 
271 static HTAB *lwlock_stats_htab;
272 static lwlock_stats lwlock_stats_dummy;
273 #endif
274 
275 #ifdef LOCK_DEBUG
276 bool Trace_lwlocks = false;
277 
278 inline static void
279 PRINT_LWDEBUG(const char *where, LWLock *lock, LWLockMode mode)
280 {
281  /* hide statement & context here, otherwise the log is just too verbose */
282  if (Trace_lwlocks)
283  {
285 
286  ereport(LOG,
287  (errhidestmt(true),
288  errhidecontext(true),
289  errmsg_internal("%d: %s(%s %p): excl %u shared %u haswaiters %u waiters %u rOK %d",
290  MyProcPid,
291  where, T_NAME(lock), lock,
292  (state & LW_VAL_EXCLUSIVE) != 0,
294  (state & LW_FLAG_HAS_WAITERS) != 0,
295  pg_atomic_read_u32(&lock->nwaiters),
296  (state & LW_FLAG_RELEASE_OK) != 0)));
297  }
298 }
299 
300 inline static void
301 LOG_LWDEBUG(const char *where, LWLock *lock, const char *msg)
302 {
303  /* hide statement & context here, otherwise the log is just too verbose */
304  if (Trace_lwlocks)
305  {
306  ereport(LOG,
307  (errhidestmt(true),
308  errhidecontext(true),
309  errmsg_internal("%s(%s %p): %s", where,
310  T_NAME(lock), lock, msg)));
311  }
312 }
313 
314 #else /* not LOCK_DEBUG */
315 #define PRINT_LWDEBUG(a,b,c) ((void)0)
316 #define LOG_LWDEBUG(a,b,c) ((void)0)
317 #endif /* LOCK_DEBUG */
318 
319 #ifdef LWLOCK_STATS
320 
321 static void init_lwlock_stats(void);
322 static void print_lwlock_stats(int code, Datum arg);
323 static lwlock_stats * get_lwlock_stats_entry(LWLock *lock);
324 
325 static void
326 init_lwlock_stats(void)
327 {
328  HASHCTL ctl;
329  static MemoryContext lwlock_stats_cxt = NULL;
330  static bool exit_registered = false;
331 
332  if (lwlock_stats_cxt != NULL)
333  MemoryContextDelete(lwlock_stats_cxt);
334 
335  /*
336  * The LWLock stats will be updated within a critical section, which
337  * requires allocating new hash entries. Allocations within a critical
338  * section are normally not allowed because running out of memory would
339  * lead to a PANIC, but LWLOCK_STATS is debugging code that's not normally
340  * turned on in production, so that's an acceptable risk. The hash entries
341  * are small, so the risk of running out of memory is minimal in practice.
342  */
343  lwlock_stats_cxt = AllocSetContextCreate(TopMemoryContext,
344  "LWLock stats",
346  MemoryContextAllowInCriticalSection(lwlock_stats_cxt, true);
347 
348  ctl.keysize = sizeof(lwlock_stats_key);
349  ctl.entrysize = sizeof(lwlock_stats);
350  ctl.hcxt = lwlock_stats_cxt;
351  lwlock_stats_htab = hash_create("lwlock stats", 16384, &ctl,
353  if (!exit_registered)
354  {
355  on_shmem_exit(print_lwlock_stats, 0);
356  exit_registered = true;
357  }
358 }
359 
360 static void
361 print_lwlock_stats(int code, Datum arg)
362 {
363  HASH_SEQ_STATUS scan;
364  lwlock_stats *lwstats;
365 
366  hash_seq_init(&scan, lwlock_stats_htab);
367 
368  /* Grab an LWLock to keep different backends from mixing reports */
370 
371  while ((lwstats = (lwlock_stats *) hash_seq_search(&scan)) != NULL)
372  {
373  fprintf(stderr,
374  "PID %d lwlock %s %p: shacq %u exacq %u blk %u spindelay %u dequeue self %u\n",
375  MyProcPid, GetLWTrancheName(lwstats->key.tranche),
376  lwstats->key.instance, lwstats->sh_acquire_count,
377  lwstats->ex_acquire_count, lwstats->block_count,
378  lwstats->spin_delay_count, lwstats->dequeue_self_count);
379  }
380 
381  LWLockRelease(&MainLWLockArray[0].lock);
382 }
383 
384 static lwlock_stats *
385 get_lwlock_stats_entry(LWLock *lock)
386 {
387  lwlock_stats_key key;
388  lwlock_stats *lwstats;
389  bool found;
390 
391  /*
392  * During shared memory initialization, the hash table doesn't exist yet.
393  * Stats of that phase aren't very interesting, so just collect operations
394  * on all locks in a single dummy entry.
395  */
396  if (lwlock_stats_htab == NULL)
397  return &lwlock_stats_dummy;
398 
399  /* Fetch or create the entry. */
400  MemSet(&key, 0, sizeof(key));
401  key.tranche = lock->tranche;
402  key.instance = lock;
403  lwstats = hash_search(lwlock_stats_htab, &key, HASH_ENTER, &found);
404  if (!found)
405  {
406  lwstats->sh_acquire_count = 0;
407  lwstats->ex_acquire_count = 0;
408  lwstats->block_count = 0;
409  lwstats->dequeue_self_count = 0;
410  lwstats->spin_delay_count = 0;
411  }
412  return lwstats;
413 }
414 #endif /* LWLOCK_STATS */
415 
416 
417 /*
418  * Compute number of LWLocks required by named tranches. These will be
419  * allocated in the main array.
420  */
421 static int
423 {
424  int numLocks = 0;
425  int i;
426 
427  for (i = 0; i < NamedLWLockTrancheRequests; i++)
428  numLocks += NamedLWLockTrancheRequestArray[i].num_lwlocks;
429 
430  return numLocks;
431 }
432 
433 /*
434  * Compute shmem space needed for LWLocks and named tranches.
435  */
436 Size
438 {
439  Size size;
440  int i;
441  int numLocks = NUM_FIXED_LWLOCKS;
442 
443  /* Calculate total number of locks needed in the main array. */
444  numLocks += NumLWLocksForNamedTranches();
445 
446  /* Space for the LWLock array. */
447  size = mul_size(numLocks, sizeof(LWLockPadded));
448 
449  /* Space for dynamic allocation counter, plus room for alignment. */
450  size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
451 
452  /* space for named tranches. */
454 
455  /* space for name of each tranche. */
456  for (i = 0; i < NamedLWLockTrancheRequests; i++)
457  size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
458 
459  return size;
460 }
461 
462 /*
463  * Allocate shmem space for the main LWLock array and all tranches and
464  * initialize it. We also register extension LWLock tranches here.
465  */
466 void
468 {
470  "MAX_BACKENDS too big for lwlock.c");
471 
473  "Miscalculated LWLock padding");
474 
475  if (!IsUnderPostmaster)
476  {
477  Size spaceLocks = LWLockShmemSize();
478  int *LWLockCounter;
479  char *ptr;
480 
481  /* Allocate space */
482  ptr = (char *) ShmemAlloc(spaceLocks);
483 
484  /* Leave room for dynamic allocation of tranches */
485  ptr += sizeof(int);
486 
487  /* Ensure desired alignment of LWLock array */
488  ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
489 
490  MainLWLockArray = (LWLockPadded *) ptr;
491 
492  /*
493  * Initialize the dynamic-allocation counter for tranches, which is
494  * stored just before the first LWLock.
495  */
496  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
497  *LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
498 
499  /* Initialize all LWLocks */
501  }
502 
503  /* Register named extension LWLock tranches in the current process. */
504  for (int i = 0; i < NamedLWLockTrancheRequests; i++)
506  NamedLWLockTrancheArray[i].trancheName);
507 }
508 
509 /*
510  * Initialize LWLocks that are fixed and those belonging to named tranches.
511  */
512 static void
514 {
515  int numNamedLocks = NumLWLocksForNamedTranches();
516  int id;
517  int i;
518  int j;
519  LWLockPadded *lock;
520 
521  /* Initialize all individual LWLocks in main array */
522  for (id = 0, lock = MainLWLockArray; id < NUM_INDIVIDUAL_LWLOCKS; id++, lock++)
523  LWLockInitialize(&lock->lock, id);
524 
525  /* Initialize buffer mapping LWLocks in main array */
527  for (id = 0; id < NUM_BUFFER_PARTITIONS; id++, lock++)
529 
530  /* Initialize lmgrs' LWLocks in main array */
532  for (id = 0; id < NUM_LOCK_PARTITIONS; id++, lock++)
534 
535  /* Initialize predicate lmgrs' LWLocks in main array */
537  for (id = 0; id < NUM_PREDICATELOCK_PARTITIONS; id++, lock++)
539 
540  /*
541  * Copy the info about any named tranches into shared memory (so that
542  * other processes can see it), and initialize the requested LWLocks.
543  */
545  {
546  char *trancheNames;
547 
549  &MainLWLockArray[NUM_FIXED_LWLOCKS + numNamedLocks];
550 
551  trancheNames = (char *) NamedLWLockTrancheArray +
554 
555  for (i = 0; i < NamedLWLockTrancheRequests; i++)
556  {
557  NamedLWLockTrancheRequest *request;
558  NamedLWLockTranche *tranche;
559  char *name;
560 
561  request = &NamedLWLockTrancheRequestArray[i];
562  tranche = &NamedLWLockTrancheArray[i];
563 
564  name = trancheNames;
565  trancheNames += strlen(request->tranche_name) + 1;
566  strcpy(name, request->tranche_name);
567  tranche->trancheId = LWLockNewTrancheId();
568  tranche->trancheName = name;
569 
570  for (j = 0; j < request->num_lwlocks; j++, lock++)
571  LWLockInitialize(&lock->lock, tranche->trancheId);
572  }
573  }
574 }
575 
576 /*
577  * InitLWLockAccess - initialize backend-local state needed to hold LWLocks
578  */
579 void
581 {
582 #ifdef LWLOCK_STATS
583  init_lwlock_stats();
584 #endif
585 }
586 
587 /*
588  * GetNamedLWLockTranche - returns the base address of LWLock from the
589  * specified tranche.
590  *
591  * Caller needs to retrieve the requested number of LWLocks starting from
592  * the base lock address returned by this API. This can be used for
593  * tranches that are requested by using RequestNamedLWLockTranche() API.
594  */
595 LWLockPadded *
596 GetNamedLWLockTranche(const char *tranche_name)
597 {
598  int lock_pos;
599  int i;
600 
601  /*
602  * Obtain the position of base address of LWLock belonging to requested
603  * tranche_name in MainLWLockArray. LWLocks for named tranches are placed
604  * in MainLWLockArray after fixed locks.
605  */
606  lock_pos = NUM_FIXED_LWLOCKS;
607  for (i = 0; i < NamedLWLockTrancheRequests; i++)
608  {
609  if (strcmp(NamedLWLockTrancheRequestArray[i].tranche_name,
610  tranche_name) == 0)
611  return &MainLWLockArray[lock_pos];
612 
614  }
615 
616  elog(ERROR, "requested tranche is not registered");
617 
618  /* just to keep compiler quiet */
619  return NULL;
620 }
621 
622 /*
623  * Allocate a new tranche ID.
624  */
625 int
627 {
628  int result;
629  int *LWLockCounter;
630 
631  LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
633  result = (*LWLockCounter)++;
635 
636  return result;
637 }
638 
639 /*
640  * Register a dynamic tranche name in the lookup table of the current process.
641  *
642  * This routine will save a pointer to the tranche name passed as an argument,
643  * so the name should be allocated in a backend-lifetime context
644  * (shared memory, TopMemoryContext, static constant, or similar).
645  *
646  * The tranche name will be user-visible as a wait event name, so try to
647  * use a name that fits the style for those.
648  */
649 void
650 LWLockRegisterTranche(int tranche_id, const char *tranche_name)
651 {
652  /* This should only be called for user-defined tranches. */
653  if (tranche_id < LWTRANCHE_FIRST_USER_DEFINED)
654  return;
655 
656  /* Convert to array index. */
657  tranche_id -= LWTRANCHE_FIRST_USER_DEFINED;
658 
659  /* If necessary, create or enlarge array. */
660  if (tranche_id >= LWLockTrancheNamesAllocated)
661  {
662  int newalloc;
663 
664  newalloc = pg_nextpower2_32(Max(8, tranche_id + 1));
665 
666  if (LWLockTrancheNames == NULL)
667  LWLockTrancheNames = (const char **)
669  newalloc * sizeof(char *));
670  else
671  {
672  LWLockTrancheNames = (const char **)
673  repalloc(LWLockTrancheNames, newalloc * sizeof(char *));
675  0,
676  (newalloc - LWLockTrancheNamesAllocated) * sizeof(char *));
677  }
678  LWLockTrancheNamesAllocated = newalloc;
679  }
680 
681  LWLockTrancheNames[tranche_id] = tranche_name;
682 }
683 
684 /*
685  * RequestNamedLWLockTranche
686  * Request that extra LWLocks be allocated during postmaster
687  * startup.
688  *
689  * This may only be called via the shmem_request_hook of a library that is
690  * loaded into the postmaster via shared_preload_libraries. Calls from
691  * elsewhere will fail.
692  *
693  * The tranche name will be user-visible as a wait event name, so try to
694  * use a name that fits the style for those.
695  */
696 void
697 RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks)
698 {
699  NamedLWLockTrancheRequest *request;
700 
702  elog(FATAL, "cannot request additional LWLocks outside shmem_request_hook");
703 
704  if (NamedLWLockTrancheRequestArray == NULL)
705  {
710  * sizeof(NamedLWLockTrancheRequest));
711  }
712 
714  {
716 
719  i * sizeof(NamedLWLockTrancheRequest));
721  }
722 
724  Assert(strlen(tranche_name) + 1 <= NAMEDATALEN);
725  strlcpy(request->tranche_name, tranche_name, NAMEDATALEN);
726  request->num_lwlocks = num_lwlocks;
728 }
729 
730 /*
731  * LWLockInitialize - initialize a new lwlock; it's initially unlocked
732  */
733 void
734 LWLockInitialize(LWLock *lock, int tranche_id)
735 {
737 #ifdef LOCK_DEBUG
738  pg_atomic_init_u32(&lock->nwaiters, 0);
739 #endif
740  lock->tranche = tranche_id;
741  proclist_init(&lock->waiters);
742 }
743 
744 /*
745  * Report start of wait event for light-weight locks.
746  *
747  * This function will be used by all the light-weight lock calls which
748  * needs to wait to acquire the lock. This function distinguishes wait
749  * event based on tranche and lock id.
750  */
751 static inline void
753 {
755 }
756 
757 /*
758  * Report end of wait event for light-weight locks.
759  */
760 static inline void
762 {
764 }
765 
766 /*
767  * Return the name of an LWLock tranche.
768  */
769 static const char *
771 {
772  /* Individual LWLock? */
773  if (trancheId < NUM_INDIVIDUAL_LWLOCKS)
774  return IndividualLWLockNames[trancheId];
775 
776  /* Built-in tranche? */
777  if (trancheId < LWTRANCHE_FIRST_USER_DEFINED)
778  return BuiltinTrancheNames[trancheId - NUM_INDIVIDUAL_LWLOCKS];
779 
780  /*
781  * It's an extension tranche, so look in LWLockTrancheNames[]. However,
782  * it's possible that the tranche has never been registered in the current
783  * process, in which case give up and return "extension".
784  */
785  trancheId -= LWTRANCHE_FIRST_USER_DEFINED;
786 
787  if (trancheId >= LWLockTrancheNamesAllocated ||
788  LWLockTrancheNames[trancheId] == NULL)
789  return "extension";
790 
791  return LWLockTrancheNames[trancheId];
792 }
793 
794 /*
795  * Return an identifier for an LWLock based on the wait class and event.
796  */
797 const char *
799 {
800  Assert(classId == PG_WAIT_LWLOCK);
801  /* The event IDs are just tranche numbers. */
802  return GetLWTrancheName(eventId);
803 }
804 
805 /*
806  * Internal function that tries to atomically acquire the lwlock in the passed
807  * in mode.
808  *
809  * This function will not block waiting for a lock to become free - that's the
810  * callers job.
811  *
812  * Returns true if the lock isn't free and we need to wait.
813  */
814 static bool
816 {
817  uint32 old_state;
818 
820 
821  /*
822  * Read once outside the loop, later iterations will get the newer value
823  * via compare & exchange.
824  */
825  old_state = pg_atomic_read_u32(&lock->state);
826 
827  /* loop until we've determined whether we could acquire the lock or not */
828  while (true)
829  {
830  uint32 desired_state;
831  bool lock_free;
832 
833  desired_state = old_state;
834 
835  if (mode == LW_EXCLUSIVE)
836  {
837  lock_free = (old_state & LW_LOCK_MASK) == 0;
838  if (lock_free)
839  desired_state += LW_VAL_EXCLUSIVE;
840  }
841  else
842  {
843  lock_free = (old_state & LW_VAL_EXCLUSIVE) == 0;
844  if (lock_free)
845  desired_state += LW_VAL_SHARED;
846  }
847 
848  /*
849  * Attempt to swap in the state we are expecting. If we didn't see
850  * lock to be free, that's just the old value. If we saw it as free,
851  * we'll attempt to mark it acquired. The reason that we always swap
852  * in the value is that this doubles as a memory barrier. We could try
853  * to be smarter and only swap in values if we saw the lock as free,
854  * but benchmark haven't shown it as beneficial so far.
855  *
856  * Retry if the value changed since we last looked at it.
857  */
859  &old_state, desired_state))
860  {
861  if (lock_free)
862  {
863  /* Great! Got the lock. */
864 #ifdef LOCK_DEBUG
865  if (mode == LW_EXCLUSIVE)
866  lock->owner = MyProc;
867 #endif
868  return false;
869  }
870  else
871  return true; /* somebody else has the lock */
872  }
873  }
874  pg_unreachable();
875 }
876 
877 /*
878  * Lock the LWLock's wait list against concurrent activity.
879  *
880  * NB: even though the wait list is locked, non-conflicting lock operations
881  * may still happen concurrently.
882  *
883  * Time spent holding mutex should be short!
884  */
885 static void
887 {
888  uint32 old_state;
889 #ifdef LWLOCK_STATS
890  lwlock_stats *lwstats;
891  uint32 delays = 0;
892 
893  lwstats = get_lwlock_stats_entry(lock);
894 #endif
895 
896  while (true)
897  {
898  /* always try once to acquire lock directly */
899  old_state = pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_LOCKED);
900  if (!(old_state & LW_FLAG_LOCKED))
901  break; /* got lock */
902 
903  /* and then spin without atomic operations until lock is released */
904  {
905  SpinDelayStatus delayStatus;
906 
907  init_local_spin_delay(&delayStatus);
908 
909  while (old_state & LW_FLAG_LOCKED)
910  {
911  perform_spin_delay(&delayStatus);
912  old_state = pg_atomic_read_u32(&lock->state);
913  }
914 #ifdef LWLOCK_STATS
915  delays += delayStatus.delays;
916 #endif
917  finish_spin_delay(&delayStatus);
918  }
919 
920  /*
921  * Retry. The lock might obviously already be re-acquired by the time
922  * we're attempting to get it again.
923  */
924  }
925 
926 #ifdef LWLOCK_STATS
927  lwstats->spin_delay_count += delays;
928 #endif
929 }
930 
931 /*
932  * Unlock the LWLock's wait list.
933  *
934  * Note that it can be more efficient to manipulate flags and release the
935  * locks in a single atomic operation.
936  */
937 static void
939 {
941 
942  old_state = pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_LOCKED);
943 
944  Assert(old_state & LW_FLAG_LOCKED);
945 }
946 
947 /*
948  * Wakeup all the lockers that currently have a chance to acquire the lock.
949  */
950 static void
952 {
953  bool new_release_ok;
954  bool wokeup_somebody = false;
955  proclist_head wakeup;
957 
958  proclist_init(&wakeup);
959 
960  new_release_ok = true;
961 
962  /* lock wait list while collecting backends to wake up */
963  LWLockWaitListLock(lock);
964 
965  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
966  {
967  PGPROC *waiter = GetPGProcByNumber(iter.cur);
968 
969  if (wokeup_somebody && waiter->lwWaitMode == LW_EXCLUSIVE)
970  continue;
971 
972  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
973  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
974 
975  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
976  {
977  /*
978  * Prevent additional wakeups until retryer gets to run. Backends
979  * that are just waiting for the lock to become free don't retry
980  * automatically.
981  */
982  new_release_ok = false;
983 
984  /*
985  * Don't wakeup (further) exclusive locks.
986  */
987  wokeup_somebody = true;
988  }
989 
990  /*
991  * Once we've woken up an exclusive lock, there's no point in waking
992  * up anybody else.
993  */
994  if (waiter->lwWaitMode == LW_EXCLUSIVE)
995  break;
996  }
997 
999 
1000  /* unset required flags, and release lock, in one fell swoop */
1001  {
1002  uint32 old_state;
1003  uint32 desired_state;
1004 
1005  old_state = pg_atomic_read_u32(&lock->state);
1006  while (true)
1007  {
1008  desired_state = old_state;
1009 
1010  /* compute desired flags */
1011 
1012  if (new_release_ok)
1013  desired_state |= LW_FLAG_RELEASE_OK;
1014  else
1015  desired_state &= ~LW_FLAG_RELEASE_OK;
1016 
1017  if (proclist_is_empty(&wakeup))
1018  desired_state &= ~LW_FLAG_HAS_WAITERS;
1019 
1020  desired_state &= ~LW_FLAG_LOCKED; /* release lock */
1021 
1022  if (pg_atomic_compare_exchange_u32(&lock->state, &old_state,
1023  desired_state))
1024  break;
1025  }
1026  }
1027 
1028  /* Awaken any waiters I removed from the queue. */
1029  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1030  {
1031  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1032 
1033  LOG_LWDEBUG("LWLockRelease", lock, "release waiter");
1034  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1035 
1036  /*
1037  * Guarantee that lwWaiting being unset only becomes visible once the
1038  * unlink from the link has completed. Otherwise the target backend
1039  * could be woken up for other reason and enqueue for a new lock - if
1040  * that happens before the list unlink happens, the list would end up
1041  * being corrupted.
1042  *
1043  * The barrier pairs with the LWLockWaitListLock() when enqueuing for
1044  * another lock.
1045  */
1046  pg_write_barrier();
1047  waiter->lwWaiting = false;
1048  PGSemaphoreUnlock(waiter->sem);
1049  }
1050 }
1051 
1052 /*
1053  * Add ourselves to the end of the queue.
1054  *
1055  * NB: Mode can be LW_WAIT_UNTIL_FREE here!
1056  */
1057 static void
1059 {
1060  /*
1061  * If we don't have a PGPROC structure, there's no way to wait. This
1062  * should never occur, since MyProc should only be null during shared
1063  * memory initialization.
1064  */
1065  if (MyProc == NULL)
1066  elog(PANIC, "cannot wait without a PGPROC structure");
1067 
1068  if (MyProc->lwWaiting)
1069  elog(PANIC, "queueing for lock while waiting on another one");
1070 
1071  LWLockWaitListLock(lock);
1072 
1073  /* setting the flag is protected by the spinlock */
1075 
1076  MyProc->lwWaiting = true;
1077  MyProc->lwWaitMode = mode;
1078 
1079  /* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */
1080  if (mode == LW_WAIT_UNTIL_FREE)
1081  proclist_push_head(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1082  else
1083  proclist_push_tail(&lock->waiters, MyProc->pgprocno, lwWaitLink);
1084 
1085  /* Can release the mutex now */
1086  LWLockWaitListUnlock(lock);
1087 
1088 #ifdef LOCK_DEBUG
1089  pg_atomic_fetch_add_u32(&lock->nwaiters, 1);
1090 #endif
1091 }
1092 
1093 /*
1094  * Remove ourselves from the waitlist.
1095  *
1096  * This is used if we queued ourselves because we thought we needed to sleep
1097  * but, after further checking, we discovered that we don't actually need to
1098  * do so.
1099  */
1100 static void
1102 {
1103  bool found = false;
1104  proclist_mutable_iter iter;
1105 
1106 #ifdef LWLOCK_STATS
1107  lwlock_stats *lwstats;
1108 
1109  lwstats = get_lwlock_stats_entry(lock);
1110 
1111  lwstats->dequeue_self_count++;
1112 #endif
1113 
1114  LWLockWaitListLock(lock);
1115 
1116  /*
1117  * Can't just remove ourselves from the list, but we need to iterate over
1118  * all entries as somebody else could have dequeued us.
1119  */
1120  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1121  {
1122  if (iter.cur == MyProc->pgprocno)
1123  {
1124  found = true;
1125  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1126  break;
1127  }
1128  }
1129 
1130  if (proclist_is_empty(&lock->waiters) &&
1131  (pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS) != 0)
1132  {
1134  }
1135 
1136  /* XXX: combine with fetch_and above? */
1137  LWLockWaitListUnlock(lock);
1138 
1139  /* clear waiting state again, nice for debugging */
1140  if (found)
1141  MyProc->lwWaiting = false;
1142  else
1143  {
1144  int extraWaits = 0;
1145 
1146  /*
1147  * Somebody else dequeued us and has or will wake us up. Deal with the
1148  * superfluous absorption of a wakeup.
1149  */
1150 
1151  /*
1152  * Reset RELEASE_OK flag if somebody woke us before we removed
1153  * ourselves - they'll have set it to false.
1154  */
1156 
1157  /*
1158  * Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
1159  * get reset at some inconvenient point later. Most of the time this
1160  * will immediately return.
1161  */
1162  for (;;)
1163  {
1165  if (!MyProc->lwWaiting)
1166  break;
1167  extraWaits++;
1168  }
1169 
1170  /*
1171  * Fix the process wait semaphore's count for any absorbed wakeups.
1172  */
1173  while (extraWaits-- > 0)
1175  }
1176 
1177 #ifdef LOCK_DEBUG
1178  {
1179  /* not waiting anymore */
1180  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1181 
1182  Assert(nwaiters < MAX_BACKENDS);
1183  }
1184 #endif
1185 }
1186 
1187 /*
1188  * LWLockAcquire - acquire a lightweight lock in the specified mode
1189  *
1190  * If the lock is not available, sleep until it is. Returns true if the lock
1191  * was available immediately, false if we had to sleep.
1192  *
1193  * Side effect: cancel/die interrupts are held off until lock release.
1194  */
1195 bool
1197 {
1198  PGPROC *proc = MyProc;
1199  bool result = true;
1200  int extraWaits = 0;
1201 #ifdef LWLOCK_STATS
1202  lwlock_stats *lwstats;
1203 
1204  lwstats = get_lwlock_stats_entry(lock);
1205 #endif
1206 
1208 
1209  PRINT_LWDEBUG("LWLockAcquire", lock, mode);
1210 
1211 #ifdef LWLOCK_STATS
1212  /* Count lock acquisition attempts */
1213  if (mode == LW_EXCLUSIVE)
1214  lwstats->ex_acquire_count++;
1215  else
1216  lwstats->sh_acquire_count++;
1217 #endif /* LWLOCK_STATS */
1218 
1219  /*
1220  * We can't wait if we haven't got a PGPROC. This should only occur
1221  * during bootstrap or shared memory initialization. Put an Assert here
1222  * to catch unsafe coding practices.
1223  */
1224  Assert(!(proc == NULL && IsUnderPostmaster));
1225 
1226  /* Ensure we will have room to remember the lock */
1228  elog(ERROR, "too many LWLocks taken");
1229 
1230  /*
1231  * Lock out cancel/die interrupts until we exit the code section protected
1232  * by the LWLock. This ensures that interrupts will not interfere with
1233  * manipulations of data structures in shared memory.
1234  */
1235  HOLD_INTERRUPTS();
1236 
1237  /*
1238  * Loop here to try to acquire lock after each time we are signaled by
1239  * LWLockRelease.
1240  *
1241  * NOTE: it might seem better to have LWLockRelease actually grant us the
1242  * lock, rather than retrying and possibly having to go back to sleep. But
1243  * in practice that is no good because it means a process swap for every
1244  * lock acquisition when two or more processes are contending for the same
1245  * lock. Since LWLocks are normally used to protect not-very-long
1246  * sections of computation, a process needs to be able to acquire and
1247  * release the same lock many times during a single CPU time slice, even
1248  * in the presence of contention. The efficiency of being able to do that
1249  * outweighs the inefficiency of sometimes wasting a process dispatch
1250  * cycle because the lock is not free when a released waiter finally gets
1251  * to run. See pgsql-hackers archives for 29-Dec-01.
1252  */
1253  for (;;)
1254  {
1255  bool mustwait;
1256 
1257  /*
1258  * Try to grab the lock the first time, we're not in the waitqueue
1259  * yet/anymore.
1260  */
1261  mustwait = LWLockAttemptLock(lock, mode);
1262 
1263  if (!mustwait)
1264  {
1265  LOG_LWDEBUG("LWLockAcquire", lock, "immediately acquired lock");
1266  break; /* got the lock */
1267  }
1268 
1269  /*
1270  * Ok, at this point we couldn't grab the lock on the first try. We
1271  * cannot simply queue ourselves to the end of the list and wait to be
1272  * woken up because by now the lock could long have been released.
1273  * Instead add us to the queue and try to grab the lock again. If we
1274  * succeed we need to revert the queuing and be happy, otherwise we
1275  * recheck the lock. If we still couldn't grab it, we know that the
1276  * other locker will see our queue entries when releasing since they
1277  * existed before we checked for the lock.
1278  */
1279 
1280  /* add to the queue */
1281  LWLockQueueSelf(lock, mode);
1282 
1283  /* we're now guaranteed to be woken up if necessary */
1284  mustwait = LWLockAttemptLock(lock, mode);
1285 
1286  /* ok, grabbed the lock the second time round, need to undo queueing */
1287  if (!mustwait)
1288  {
1289  LOG_LWDEBUG("LWLockAcquire", lock, "acquired, undoing queue");
1290 
1291  LWLockDequeueSelf(lock);
1292  break;
1293  }
1294 
1295  /*
1296  * Wait until awakened.
1297  *
1298  * It is possible that we get awakened for a reason other than being
1299  * signaled by LWLockRelease. If so, loop back and wait again. Once
1300  * we've gotten the LWLock, re-increment the sema by the number of
1301  * additional signals received.
1302  */
1303  LOG_LWDEBUG("LWLockAcquire", lock, "waiting");
1304 
1305 #ifdef LWLOCK_STATS
1306  lwstats->block_count++;
1307 #endif
1308 
1309  LWLockReportWaitStart(lock);
1310  if (TRACE_POSTGRESQL_LWLOCK_WAIT_START_ENABLED())
1311  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), mode);
1312 
1313  for (;;)
1314  {
1315  PGSemaphoreLock(proc->sem);
1316  if (!proc->lwWaiting)
1317  break;
1318  extraWaits++;
1319  }
1320 
1321  /* Retrying, allow LWLockRelease to release waiters again. */
1323 
1324 #ifdef LOCK_DEBUG
1325  {
1326  /* not waiting anymore */
1327  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1328 
1329  Assert(nwaiters < MAX_BACKENDS);
1330  }
1331 #endif
1332 
1333  if (TRACE_POSTGRESQL_LWLOCK_WAIT_DONE_ENABLED())
1334  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode);
1336 
1337  LOG_LWDEBUG("LWLockAcquire", lock, "awakened");
1338 
1339  /* Now loop back and try to acquire lock again. */
1340  result = false;
1341  }
1342 
1343  if (TRACE_POSTGRESQL_LWLOCK_ACQUIRE_ENABLED())
1344  TRACE_POSTGRESQL_LWLOCK_ACQUIRE(T_NAME(lock), mode);
1345 
1346  /* Add lock to list of locks held by this backend */
1349 
1350  /*
1351  * Fix the process wait semaphore's count for any absorbed wakeups.
1352  */
1353  while (extraWaits-- > 0)
1354  PGSemaphoreUnlock(proc->sem);
1355 
1356  return result;
1357 }
1358 
1359 /*
1360  * LWLockConditionalAcquire - acquire a lightweight lock in the specified mode
1361  *
1362  * If the lock is not available, return false with no side-effects.
1363  *
1364  * If successful, cancel/die interrupts are held off until lock release.
1365  */
1366 bool
1368 {
1369  bool mustwait;
1370 
1372 
1373  PRINT_LWDEBUG("LWLockConditionalAcquire", lock, mode);
1374 
1375  /* Ensure we will have room to remember the lock */
1377  elog(ERROR, "too many LWLocks taken");
1378 
1379  /*
1380  * Lock out cancel/die interrupts until we exit the code section protected
1381  * by the LWLock. This ensures that interrupts will not interfere with
1382  * manipulations of data structures in shared memory.
1383  */
1384  HOLD_INTERRUPTS();
1385 
1386  /* Check for the lock */
1387  mustwait = LWLockAttemptLock(lock, mode);
1388 
1389  if (mustwait)
1390  {
1391  /* Failed to get lock, so release interrupt holdoff */
1393 
1394  LOG_LWDEBUG("LWLockConditionalAcquire", lock, "failed");
1395  if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL_ENABLED())
1396  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL(T_NAME(lock), mode);
1397  }
1398  else
1399  {
1400  /* Add lock to list of locks held by this backend */
1403  if (TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_ENABLED())
1404  TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(T_NAME(lock), mode);
1405  }
1406  return !mustwait;
1407 }
1408 
1409 /*
1410  * LWLockAcquireOrWait - Acquire lock, or wait until it's free
1411  *
1412  * The semantics of this function are a bit funky. If the lock is currently
1413  * free, it is acquired in the given mode, and the function returns true. If
1414  * the lock isn't immediately free, the function waits until it is released
1415  * and returns false, but does not acquire the lock.
1416  *
1417  * This is currently used for WALWriteLock: when a backend flushes the WAL,
1418  * holding WALWriteLock, it can flush the commit records of many other
1419  * backends as a side-effect. Those other backends need to wait until the
1420  * flush finishes, but don't need to acquire the lock anymore. They can just
1421  * wake up, observe that their records have already been flushed, and return.
1422  */
1423 bool
1425 {
1426  PGPROC *proc = MyProc;
1427  bool mustwait;
1428  int extraWaits = 0;
1429 #ifdef LWLOCK_STATS
1430  lwlock_stats *lwstats;
1431 
1432  lwstats = get_lwlock_stats_entry(lock);
1433 #endif
1434 
1436 
1437  PRINT_LWDEBUG("LWLockAcquireOrWait", lock, mode);
1438 
1439  /* Ensure we will have room to remember the lock */
1441  elog(ERROR, "too many LWLocks taken");
1442 
1443  /*
1444  * Lock out cancel/die interrupts until we exit the code section protected
1445  * by the LWLock. This ensures that interrupts will not interfere with
1446  * manipulations of data structures in shared memory.
1447  */
1448  HOLD_INTERRUPTS();
1449 
1450  /*
1451  * NB: We're using nearly the same twice-in-a-row lock acquisition
1452  * protocol as LWLockAcquire(). Check its comments for details.
1453  */
1454  mustwait = LWLockAttemptLock(lock, mode);
1455 
1456  if (mustwait)
1457  {
1459 
1460  mustwait = LWLockAttemptLock(lock, mode);
1461 
1462  if (mustwait)
1463  {
1464  /*
1465  * Wait until awakened. Like in LWLockAcquire, be prepared for
1466  * bogus wakeups.
1467  */
1468  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "waiting");
1469 
1470 #ifdef LWLOCK_STATS
1471  lwstats->block_count++;
1472 #endif
1473 
1474  LWLockReportWaitStart(lock);
1475  if (TRACE_POSTGRESQL_LWLOCK_WAIT_START_ENABLED())
1476  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), mode);
1477 
1478  for (;;)
1479  {
1480  PGSemaphoreLock(proc->sem);
1481  if (!proc->lwWaiting)
1482  break;
1483  extraWaits++;
1484  }
1485 
1486 #ifdef LOCK_DEBUG
1487  {
1488  /* not waiting anymore */
1489  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1490 
1491  Assert(nwaiters < MAX_BACKENDS);
1492  }
1493 #endif
1494  if (TRACE_POSTGRESQL_LWLOCK_WAIT_DONE_ENABLED())
1495  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode);
1497 
1498  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "awakened");
1499  }
1500  else
1501  {
1502  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "acquired, undoing queue");
1503 
1504  /*
1505  * Got lock in the second attempt, undo queueing. We need to treat
1506  * this as having successfully acquired the lock, otherwise we'd
1507  * not necessarily wake up people we've prevented from acquiring
1508  * the lock.
1509  */
1510  LWLockDequeueSelf(lock);
1511  }
1512  }
1513 
1514  /*
1515  * Fix the process wait semaphore's count for any absorbed wakeups.
1516  */
1517  while (extraWaits-- > 0)
1518  PGSemaphoreUnlock(proc->sem);
1519 
1520  if (mustwait)
1521  {
1522  /* Failed to get lock, so release interrupt holdoff */
1524  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "failed");
1525  if (TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_FAIL_ENABLED())
1526  TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_FAIL(T_NAME(lock), mode);
1527  }
1528  else
1529  {
1530  LOG_LWDEBUG("LWLockAcquireOrWait", lock, "succeeded");
1531  /* Add lock to list of locks held by this backend */
1534  if (TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_ENABLED())
1535  TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT(T_NAME(lock), mode);
1536  }
1537 
1538  return !mustwait;
1539 }
1540 
1541 /*
1542  * Does the lwlock in its current state need to wait for the variable value to
1543  * change?
1544  *
1545  * If we don't need to wait, and it's because the value of the variable has
1546  * changed, store the current value in newval.
1547  *
1548  * *result is set to true if the lock was free, and false otherwise.
1549  */
1550 static bool
1552  uint64 *valptr, uint64 oldval, uint64 *newval,
1553  bool *result)
1554 {
1555  bool mustwait;
1556  uint64 value;
1557 
1558  /*
1559  * Test first to see if it the slot is free right now.
1560  *
1561  * XXX: the caller uses a spinlock before this, so we don't need a memory
1562  * barrier here as far as the current usage is concerned. But that might
1563  * not be safe in general.
1564  */
1565  mustwait = (pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE) != 0;
1566 
1567  if (!mustwait)
1568  {
1569  *result = true;
1570  return false;
1571  }
1572 
1573  *result = false;
1574 
1575  /*
1576  * Read value using the lwlock's wait list lock, as we can't generally
1577  * rely on atomic 64 bit reads/stores. TODO: On platforms with a way to
1578  * do atomic 64 bit reads/writes the spinlock should be optimized away.
1579  */
1580  LWLockWaitListLock(lock);
1581  value = *valptr;
1582  LWLockWaitListUnlock(lock);
1583 
1584  if (value != oldval)
1585  {
1586  mustwait = false;
1587  *newval = value;
1588  }
1589  else
1590  {
1591  mustwait = true;
1592  }
1593 
1594  return mustwait;
1595 }
1596 
1597 /*
1598  * LWLockWaitForVar - Wait until lock is free, or a variable is updated.
1599  *
1600  * If the lock is held and *valptr equals oldval, waits until the lock is
1601  * either freed, or the lock holder updates *valptr by calling
1602  * LWLockUpdateVar. If the lock is free on exit (immediately or after
1603  * waiting), returns true. If the lock is still held, but *valptr no longer
1604  * matches oldval, returns false and sets *newval to the current value in
1605  * *valptr.
1606  *
1607  * Note: this function ignores shared lock holders; if the lock is held
1608  * in shared mode, returns 'true'.
1609  */
1610 bool
1611 LWLockWaitForVar(LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval)
1612 {
1613  PGPROC *proc = MyProc;
1614  int extraWaits = 0;
1615  bool result = false;
1616 #ifdef LWLOCK_STATS
1617  lwlock_stats *lwstats;
1618 
1619  lwstats = get_lwlock_stats_entry(lock);
1620 #endif
1621 
1622  PRINT_LWDEBUG("LWLockWaitForVar", lock, LW_WAIT_UNTIL_FREE);
1623 
1624  /*
1625  * Lock out cancel/die interrupts while we sleep on the lock. There is no
1626  * cleanup mechanism to remove us from the wait queue if we got
1627  * interrupted.
1628  */
1629  HOLD_INTERRUPTS();
1630 
1631  /*
1632  * Loop here to check the lock's status after each time we are signaled.
1633  */
1634  for (;;)
1635  {
1636  bool mustwait;
1637 
1638  mustwait = LWLockConflictsWithVar(lock, valptr, oldval, newval,
1639  &result);
1640 
1641  if (!mustwait)
1642  break; /* the lock was free or value didn't match */
1643 
1644  /*
1645  * Add myself to wait queue. Note that this is racy, somebody else
1646  * could wakeup before we're finished queuing. NB: We're using nearly
1647  * the same twice-in-a-row lock acquisition protocol as
1648  * LWLockAcquire(). Check its comments for details. The only
1649  * difference is that we also have to check the variable's values when
1650  * checking the state of the lock.
1651  */
1653 
1654  /*
1655  * Set RELEASE_OK flag, to make sure we get woken up as soon as the
1656  * lock is released.
1657  */
1659 
1660  /*
1661  * We're now guaranteed to be woken up if necessary. Recheck the lock
1662  * and variables state.
1663  */
1664  mustwait = LWLockConflictsWithVar(lock, valptr, oldval, newval,
1665  &result);
1666 
1667  /* Ok, no conflict after we queued ourselves. Undo queueing. */
1668  if (!mustwait)
1669  {
1670  LOG_LWDEBUG("LWLockWaitForVar", lock, "free, undoing queue");
1671 
1672  LWLockDequeueSelf(lock);
1673  break;
1674  }
1675 
1676  /*
1677  * Wait until awakened.
1678  *
1679  * It is possible that we get awakened for a reason other than being
1680  * signaled by LWLockRelease. If so, loop back and wait again. Once
1681  * we've gotten the LWLock, re-increment the sema by the number of
1682  * additional signals received.
1683  */
1684  LOG_LWDEBUG("LWLockWaitForVar", lock, "waiting");
1685 
1686 #ifdef LWLOCK_STATS
1687  lwstats->block_count++;
1688 #endif
1689 
1690  LWLockReportWaitStart(lock);
1691  if (TRACE_POSTGRESQL_LWLOCK_WAIT_START_ENABLED())
1692  TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), LW_EXCLUSIVE);
1693 
1694  for (;;)
1695  {
1696  PGSemaphoreLock(proc->sem);
1697  if (!proc->lwWaiting)
1698  break;
1699  extraWaits++;
1700  }
1701 
1702 #ifdef LOCK_DEBUG
1703  {
1704  /* not waiting anymore */
1705  uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
1706 
1707  Assert(nwaiters < MAX_BACKENDS);
1708  }
1709 #endif
1710 
1711  if (TRACE_POSTGRESQL_LWLOCK_WAIT_DONE_ENABLED())
1712  TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), LW_EXCLUSIVE);
1714 
1715  LOG_LWDEBUG("LWLockWaitForVar", lock, "awakened");
1716 
1717  /* Now loop back and check the status of the lock again. */
1718  }
1719 
1720  /*
1721  * Fix the process wait semaphore's count for any absorbed wakeups.
1722  */
1723  while (extraWaits-- > 0)
1724  PGSemaphoreUnlock(proc->sem);
1725 
1726  /*
1727  * Now okay to allow cancel/die interrupts.
1728  */
1730 
1731  return result;
1732 }
1733 
1734 
1735 /*
1736  * LWLockUpdateVar - Update a variable and wake up waiters atomically
1737  *
1738  * Sets *valptr to 'val', and wakes up all processes waiting for us with
1739  * LWLockWaitForVar(). Setting the value and waking up the processes happen
1740  * atomically so that any process calling LWLockWaitForVar() on the same lock
1741  * is guaranteed to see the new value, and act accordingly.
1742  *
1743  * The caller must be holding the lock in exclusive mode.
1744  */
1745 void
1746 LWLockUpdateVar(LWLock *lock, uint64 *valptr, uint64 val)
1747 {
1748  proclist_head wakeup;
1749  proclist_mutable_iter iter;
1750 
1751  PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
1752 
1753  proclist_init(&wakeup);
1754 
1755  LWLockWaitListLock(lock);
1756 
1758 
1759  /* Update the lock's value */
1760  *valptr = val;
1761 
1762  /*
1763  * See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
1764  * up. They are always in the front of the queue.
1765  */
1766  proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
1767  {
1768  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1769 
1770  if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
1771  break;
1772 
1773  proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
1774  proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
1775  }
1776 
1777  /* We are done updating shared state of the lock itself. */
1778  LWLockWaitListUnlock(lock);
1779 
1780  /*
1781  * Awaken any waiters I removed from the queue.
1782  */
1783  proclist_foreach_modify(iter, &wakeup, lwWaitLink)
1784  {
1785  PGPROC *waiter = GetPGProcByNumber(iter.cur);
1786 
1787  proclist_delete(&wakeup, iter.cur, lwWaitLink);
1788  /* check comment in LWLockWakeup() about this barrier */
1789  pg_write_barrier();
1790  waiter->lwWaiting = false;
1791  PGSemaphoreUnlock(waiter->sem);
1792  }
1793 }
1794 
1795 
1796 /*
1797  * LWLockRelease - release a previously acquired lock
1798  */
1799 void
1801 {
1802  LWLockMode mode;
1803  uint32 oldstate;
1804  bool check_waiters;
1805  int i;
1806 
1807  /*
1808  * Remove lock from list of locks held. Usually, but not always, it will
1809  * be the latest-acquired lock; so search array backwards.
1810  */
1811  for (i = num_held_lwlocks; --i >= 0;)
1812  if (lock == held_lwlocks[i].lock)
1813  break;
1814 
1815  if (i < 0)
1816  elog(ERROR, "lock %s is not held", T_NAME(lock));
1817 
1818  mode = held_lwlocks[i].mode;
1819 
1820  num_held_lwlocks--;
1821  for (; i < num_held_lwlocks; i++)
1822  held_lwlocks[i] = held_lwlocks[i + 1];
1823 
1824  PRINT_LWDEBUG("LWLockRelease", lock, mode);
1825 
1826  /*
1827  * Release my hold on lock, after that it can immediately be acquired by
1828  * others, even if we still have to wakeup other waiters.
1829  */
1830  if (mode == LW_EXCLUSIVE)
1831  oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_EXCLUSIVE);
1832  else
1833  oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_SHARED);
1834 
1835  /* nobody else can have that kind of lock */
1836  Assert(!(oldstate & LW_VAL_EXCLUSIVE));
1837 
1838  if (TRACE_POSTGRESQL_LWLOCK_RELEASE_ENABLED())
1839  TRACE_POSTGRESQL_LWLOCK_RELEASE(T_NAME(lock));
1840 
1841  /*
1842  * We're still waiting for backends to get scheduled, don't wake them up
1843  * again.
1844  */
1845  if ((oldstate & (LW_FLAG_HAS_WAITERS | LW_FLAG_RELEASE_OK)) ==
1847  (oldstate & LW_LOCK_MASK) == 0)
1848  check_waiters = true;
1849  else
1850  check_waiters = false;
1851 
1852  /*
1853  * As waking up waiters requires the spinlock to be acquired, only do so
1854  * if necessary.
1855  */
1856  if (check_waiters)
1857  {
1858  /* XXX: remove before commit? */
1859  LOG_LWDEBUG("LWLockRelease", lock, "releasing waiters");
1860  LWLockWakeup(lock);
1861  }
1862 
1863  /*
1864  * Now okay to allow cancel/die interrupts.
1865  */
1867 }
1868 
1869 /*
1870  * LWLockReleaseClearVar - release a previously acquired lock, reset variable
1871  */
1872 void
1873 LWLockReleaseClearVar(LWLock *lock, uint64 *valptr, uint64 val)
1874 {
1875  LWLockWaitListLock(lock);
1876 
1877  /*
1878  * Set the variable's value before releasing the lock, that prevents race
1879  * a race condition wherein a new locker acquires the lock, but hasn't yet
1880  * set the variables value.
1881  */
1882  *valptr = val;
1883  LWLockWaitListUnlock(lock);
1884 
1885  LWLockRelease(lock);
1886 }
1887 
1888 
1889 /*
1890  * LWLockReleaseAll - release all currently-held locks
1891  *
1892  * Used to clean up after ereport(ERROR). An important difference between this
1893  * function and retail LWLockRelease calls is that InterruptHoldoffCount is
1894  * unchanged by this operation. This is necessary since InterruptHoldoffCount
1895  * has been set to an appropriate level earlier in error recovery. We could
1896  * decrement it below zero if we allow it to drop for each released lock!
1897  */
1898 void
1900 {
1901  while (num_held_lwlocks > 0)
1902  {
1903  HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
1904 
1906  }
1907 }
1908 
1909 
1910 /*
1911  * LWLockHeldByMe - test whether my process holds a lock in any mode
1912  *
1913  * This is meant as debug support only.
1914  */
1915 bool
1917 {
1918  int i;
1919 
1920  for (i = 0; i < num_held_lwlocks; i++)
1921  {
1922  if (held_lwlocks[i].lock == l)
1923  return true;
1924  }
1925  return false;
1926 }
1927 
1928 /*
1929  * LWLockHeldByMeInMode - test whether my process holds a lock in given mode
1930  *
1931  * This is meant as debug support only.
1932  */
1933 bool
1935 {
1936  int i;
1937 
1938  for (i = 0; i < num_held_lwlocks; i++)
1939  {
1940  if (held_lwlocks[i].lock == l && held_lwlocks[i].mode == mode)
1941  return true;
1942  }
1943  return false;
1944 }
1945 
1946 /* temp debugging aid to analyze 019_replslot_limit failures */
1947 int
1949 {
1950  return num_held_lwlocks;
1951 }
static uint32 pg_atomic_fetch_and_u32(volatile pg_atomic_uint32 *ptr, uint32 and_)
Definition: atomics.h:358
static bool pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 *expected, uint32 newval)
Definition: atomics.h:311
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:372
static uint32 pg_atomic_sub_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:401
static uint32 pg_atomic_fetch_sub_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:343
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:223
#define pg_write_barrier()
Definition: atomics.h:159
static uint32 pg_atomic_fetch_add_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:328
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241
unsigned short uint16
Definition: c.h:440
unsigned int uint32
Definition: c.h:441
#define Max(x, y)
Definition: c.h:980
#define pg_unreachable()
Definition: c.h:258
#define lengthof(array)
Definition: c.h:734
#define MemSet(start, val, len)
Definition: c.h:1008
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:918
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:155
size_t Size
Definition: c.h:540
#define AssertArg(condition)
Definition: c.h:806
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1436
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1426
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
int errhidestmt(bool hide_stmt)
Definition: elog.c:1245
int errhidecontext(bool hide_ctx)
Definition: elog.c:1264
#define LOG
Definition: elog.h:25
#define FATAL
Definition: elog.h:35
#define PANIC
Definition: elog.h:36
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
const char * name
Definition: encode.c:561
int MyProcPid
Definition: globals.c:44
bool IsUnderPostmaster
Definition: globals.c:113
#define newval
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
static struct @151 value
long val
Definition: informix.c:664
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
int j
Definition: isn.c:74
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
#define LW_VAL_EXCLUSIVE
Definition: lwlock.c:104
static void LWLockWakeup(LWLock *lock)
Definition: lwlock.c:951
#define LW_FLAG_LOCKED
Definition: lwlock.c:102
const char * GetLWLockIdentifier(uint32 classId, uint16 eventId)
Definition: lwlock.c:798
LWLockPadded * GetNamedLWLockTranche(const char *tranche_name)
Definition: lwlock.c:596
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS]
Definition: lwlock.c:223
static int LWLockTrancheNamesAllocated
Definition: lwlock.c:198
const char *const IndividualLWLockNames[]
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1196
int LWLockHeldCount(void)
Definition: lwlock.c:1948
void CreateLWLocks(void)
Definition: lwlock.c:467
NamedLWLockTranche * NamedLWLockTrancheArray
Definition: lwlock.c:244
#define LW_VAL_SHARED
Definition: lwlock.c:105
static bool LWLockAttemptLock(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:815
static void LWLockWaitListLock(LWLock *lock)
Definition: lwlock.c:886
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:650
static void LWLockReportWaitEnd(void)
Definition: lwlock.c:761
struct LWLockHandle LWLockHandle
StaticAssertDecl(lengthof(BuiltinTrancheNames)==LWTRANCHE_FIRST_USER_DEFINED - NUM_INDIVIDUAL_LWLOCKS, "missing entries in BuiltinTrancheNames[]")
int LWLockNewTrancheId(void)
Definition: lwlock.c:626
slock_t * ShmemLock
Definition: shmem.c:88
static const char * GetLWTrancheName(uint16 trancheId)
Definition: lwlock.c:770
#define LW_LOCK_MASK
Definition: lwlock.c:107
int NamedLWLockTrancheRequests
Definition: lwlock.c:241
void RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks)
Definition: lwlock.c:697
#define LW_FLAG_RELEASE_OK
Definition: lwlock.c:101
#define LW_FLAG_HAS_WAITERS
Definition: lwlock.c:100
#define MAX_SIMUL_LWLOCKS
Definition: lwlock.c:213
struct NamedLWLockTrancheRequest NamedLWLockTrancheRequest
static int NumLWLocksForNamedTranches(void)
Definition: lwlock.c:422
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1800
void LWLockUpdateVar(LWLock *lock, uint64 *valptr, uint64 val)
Definition: lwlock.c:1746
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1934
#define T_NAME(lock)
Definition: lwlock.c:251
static int num_held_lwlocks
Definition: lwlock.c:222
void LWLockReleaseAll(void)
Definition: lwlock.c:1899
static void InitializeLWLocks(void)
Definition: lwlock.c:513
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:734
static int NamedLWLockTrancheRequestsAllocated
Definition: lwlock.c:233
static const char *const BuiltinTrancheNames[]
Definition: lwlock.c:131
static NamedLWLockTrancheRequest * NamedLWLockTrancheRequestArray
Definition: lwlock.c:232
static void LWLockWaitListUnlock(LWLock *lock)
Definition: lwlock.c:938
static const char ** LWLockTrancheNames
Definition: lwlock.c:197
#define LOG_LWDEBUG(a, b, c)
Definition: lwlock.c:316
static bool LWLockConflictsWithVar(LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval, bool *result)
Definition: lwlock.c:1551
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1367
bool LWLockAcquireOrWait(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1424
static void LWLockQueueSelf(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1058
#define PRINT_LWDEBUG(a, b, c)
Definition: lwlock.c:315
static void LWLockReportWaitStart(LWLock *lock)
Definition: lwlock.c:752
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1916
LWLockPadded * MainLWLockArray
Definition: lwlock.c:205
bool LWLockWaitForVar(LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval)
Definition: lwlock.c:1611
static void LWLockDequeueSelf(LWLock *lock)
Definition: lwlock.c:1101
void LWLockReleaseClearVar(LWLock *lock, uint64 *valptr, uint64 val)
Definition: lwlock.c:1873
Size LWLockShmemSize(void)
Definition: lwlock.c:437
#define LW_SHARED_MASK
Definition: lwlock.c:109
void InitLWLockAccess(void)
Definition: lwlock.c:580
#define LWLOCK_PADDED_SIZE
Definition: lwlock.h:52
#define BUFFER_MAPPING_LWLOCK_OFFSET
Definition: lwlock.h:94
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:87
@ LWTRANCHE_FIRST_USER_DEFINED
Definition: lwlock.h:196
@ LWTRANCHE_PREDICATE_LOCK_MANAGER
Definition: lwlock.h:183
@ LWTRANCHE_BUFFER_MAPPING
Definition: lwlock.h:181
@ LWTRANCHE_LOCK_MANAGER
Definition: lwlock.h:182
#define LOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:95
#define NUM_BUFFER_PARTITIONS
Definition: lwlock.h:83
#define PREDICATELOCK_MANAGER_LWLOCK_OFFSET
Definition: lwlock.h:97
#define NUM_FIXED_LWLOCKS
Definition: lwlock.h:99
LWLockMode
Definition: lwlock.h:103
@ LW_SHARED
Definition: lwlock.h:105
@ LW_WAIT_UNTIL_FREE
Definition: lwlock.h:106
@ LW_EXCLUSIVE
Definition: lwlock.h:104
#define NUM_PREDICATELOCK_PARTITIONS
Definition: lwlock.h:91
MemoryContext TopMemoryContext
Definition: mcxt.c:48
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:906
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1188
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
void MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
Definition: mcxt.c:418
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:134
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
bool process_shmem_requests_in_progress
Definition: miscinit.c:1622
void * arg
static uint32 pg_nextpower2_32(uint32 num)
Definition: pg_bitutils.h:140
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define NAMEDATALEN
#define fprintf
Definition: port.h:229
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void PGSemaphoreUnlock(PGSemaphore sema)
Definition: posix_sema.c:340
void PGSemaphoreLock(PGSemaphore sema)
Definition: posix_sema.c:320
uintptr_t Datum
Definition: postgres.h:411
#define MAX_BACKENDS
Definition: postmaster.h:75
#define GetPGProcByNumber(n)
Definition: proc.h:402
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:187
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:191
static bool proclist_is_empty(proclist_head *list)
Definition: proclist.h:38
#define proclist_push_head(list, procno, link_member)
Definition: proclist.h:189
#define proclist_foreach_modify(iter, lhead, link_member)
Definition: proclist.h:206
void perform_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:125
void finish_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:175
#define init_local_spin_delay(status)
Definition: s_lock.h:1084
int slock_t
Definition: s_lock.h:975
void * ShmemAlloc(Size size)
Definition: shmem.c:161
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
PGPROC * MyProc
Definition: proc.c:68
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:220
LWLockMode mode
Definition: lwlock.c:219
LWLock * lock
Definition: lwlock.c:218
Definition: lwlock.h:32
pg_atomic_uint32 state
Definition: lwlock.h:34
uint16 tranche
Definition: lwlock.h:33
proclist_head waiters
Definition: lwlock.h:35
char tranche_name[NAMEDATALEN]
Definition: lwlock.c:228
char * trancheName
Definition: lwlock.h:67
Definition: proc.h:160
uint8 lwWaitMode
Definition: proc.h:209
int pgprocno
Definition: proc.h:188
bool lwWaiting
Definition: proc.h:208
PGSemaphore sem
Definition: proc.h:165
Definition: regguts.h:318
LWLock lock
Definition: lwlock.h:57
#define PG_WAIT_LWLOCK
Definition: wait_event.h:18
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:266
static void pgstat_report_wait_end(void)
Definition: wait_event.h:282