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