Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * lock.c
4 : : * POSTGRES primary lock mechanism
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/storage/lmgr/lock.c
12 : : *
13 : : * NOTES
14 : : * A lock table is a shared memory hash table. When
15 : : * a process tries to acquire a lock of a type that conflicts
16 : : * with existing locks, it is put to sleep using the routines
17 : : * in storage/lmgr/proc.c.
18 : : *
19 : : * For the most part, this code should be invoked via lmgr.c
20 : : * or another lock-management module, not directly.
21 : : *
22 : : * Interface:
23 : : *
24 : : * LockManagerShmemInit(), GetLocksMethodTable(), GetLockTagsMethodTable(),
25 : : * LockAcquire(), LockRelease(), LockReleaseAll(),
26 : : * LockCheckConflicts(), GrantLock()
27 : : *
28 : : *-------------------------------------------------------------------------
29 : : */
30 : : #include "postgres.h"
31 : :
32 : : #include <signal.h>
33 : : #include <unistd.h>
34 : :
35 : : #include "access/transam.h"
36 : : #include "access/twophase.h"
37 : : #include "access/twophase_rmgr.h"
38 : : #include "access/xlog.h"
39 : : #include "access/xlogutils.h"
40 : : #include "miscadmin.h"
41 : : #include "pg_trace.h"
42 : : #include "pgstat.h"
43 : : #include "port/atomics.h"
44 : : #include "storage/lmgr.h"
45 : : #include "storage/proc.h"
46 : : #include "storage/procarray.h"
47 : : #include "storage/shmem.h"
48 : : #include "storage/standby.h"
49 : : #include "storage/subsystems.h"
50 : : #include "utils/memutils.h"
51 : : #include "utils/ps_status.h"
52 : : #include "utils/resowner.h"
53 : :
54 : :
55 : : /* GUC variables */
56 : : int max_locks_per_xact; /* used to set the lock table size */
57 : : bool log_lock_failures = false;
58 : :
59 : : #define NLOCKENTS() \
60 : : mul_size(max_locks_per_xact, add_size(MaxBackends, max_prepared_xacts))
61 : :
62 : :
63 : : /*
64 : : * Data structures defining the semantics of the standard lock methods.
65 : : *
66 : : * The conflict table defines the semantics of the various lock modes.
67 : : */
68 : : static const LOCKMASK LockConflicts[] = {
69 : : 0,
70 : :
71 : : /* AccessShareLock */
72 : : LOCKBIT_ON(AccessExclusiveLock),
73 : :
74 : : /* RowShareLock */
75 : : LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
76 : :
77 : : /* RowExclusiveLock */
78 : : LOCKBIT_ON(ShareLock) | LOCKBIT_ON(ShareRowExclusiveLock) |
79 : : LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
80 : :
81 : : /* ShareUpdateExclusiveLock */
82 : : LOCKBIT_ON(ShareUpdateExclusiveLock) |
83 : : LOCKBIT_ON(ShareLock) | LOCKBIT_ON(ShareRowExclusiveLock) |
84 : : LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
85 : :
86 : : /* ShareLock */
87 : : LOCKBIT_ON(RowExclusiveLock) | LOCKBIT_ON(ShareUpdateExclusiveLock) |
88 : : LOCKBIT_ON(ShareRowExclusiveLock) |
89 : : LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
90 : :
91 : : /* ShareRowExclusiveLock */
92 : : LOCKBIT_ON(RowExclusiveLock) | LOCKBIT_ON(ShareUpdateExclusiveLock) |
93 : : LOCKBIT_ON(ShareLock) | LOCKBIT_ON(ShareRowExclusiveLock) |
94 : : LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
95 : :
96 : : /* ExclusiveLock */
97 : : LOCKBIT_ON(RowShareLock) |
98 : : LOCKBIT_ON(RowExclusiveLock) | LOCKBIT_ON(ShareUpdateExclusiveLock) |
99 : : LOCKBIT_ON(ShareLock) | LOCKBIT_ON(ShareRowExclusiveLock) |
100 : : LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock),
101 : :
102 : : /* AccessExclusiveLock */
103 : : LOCKBIT_ON(AccessShareLock) | LOCKBIT_ON(RowShareLock) |
104 : : LOCKBIT_ON(RowExclusiveLock) | LOCKBIT_ON(ShareUpdateExclusiveLock) |
105 : : LOCKBIT_ON(ShareLock) | LOCKBIT_ON(ShareRowExclusiveLock) |
106 : : LOCKBIT_ON(ExclusiveLock) | LOCKBIT_ON(AccessExclusiveLock)
107 : :
108 : : };
109 : :
110 : : /* Names of lock modes, for debug printouts */
111 : : static const char *const lock_mode_names[] =
112 : : {
113 : : "INVALID",
114 : : "AccessShareLock",
115 : : "RowShareLock",
116 : : "RowExclusiveLock",
117 : : "ShareUpdateExclusiveLock",
118 : : "ShareLock",
119 : : "ShareRowExclusiveLock",
120 : : "ExclusiveLock",
121 : : "AccessExclusiveLock"
122 : : };
123 : :
124 : : #ifndef LOCK_DEBUG
125 : : static bool Dummy_trace = false;
126 : : #endif
127 : :
128 : : static const LockMethodData default_lockmethod = {
129 : : MaxLockMode,
130 : : LockConflicts,
131 : : lock_mode_names,
132 : : #ifdef LOCK_DEBUG
133 : : &Trace_locks
134 : : #else
135 : : &Dummy_trace
136 : : #endif
137 : : };
138 : :
139 : : static const LockMethodData user_lockmethod = {
140 : : MaxLockMode,
141 : : LockConflicts,
142 : : lock_mode_names,
143 : : #ifdef LOCK_DEBUG
144 : : &Trace_userlocks
145 : : #else
146 : : &Dummy_trace
147 : : #endif
148 : : };
149 : :
150 : : /*
151 : : * map from lock method id to the lock table data structures
152 : : */
153 : : static const LockMethod LockMethods[] = {
154 : : NULL,
155 : : &default_lockmethod,
156 : : &user_lockmethod
157 : : };
158 : :
159 : :
160 : : /* Record that's written to 2PC state file when a lock is persisted */
161 : : typedef struct TwoPhaseLockRecord
162 : : {
163 : : LOCKTAG locktag;
164 : : LOCKMODE lockmode;
165 : : } TwoPhaseLockRecord;
166 : :
167 : :
168 : : /*
169 : : * Count of the number of fast path lock slots we believe to be used. This
170 : : * might be higher than the real number if another backend has transferred
171 : : * our locks to the primary lock table, but it can never be lower than the
172 : : * real value, since only we can acquire locks on our own behalf.
173 : : *
174 : : * XXX Allocate a static array of the maximum size. We could use a pointer
175 : : * and then allocate just the right size to save a couple kB, but then we
176 : : * would have to initialize that, while for the static array that happens
177 : : * automatically. Doesn't seem worth the extra complexity.
178 : : */
179 : : static int FastPathLocalUseCounts[FP_LOCK_GROUPS_PER_BACKEND_MAX];
180 : :
181 : : /*
182 : : * Flag to indicate if the relation extension lock is held by this backend.
183 : : * This flag is used to ensure that while holding the relation extension lock
184 : : * we don't try to acquire a heavyweight lock on any other object. This
185 : : * restriction implies that the relation extension lock won't ever participate
186 : : * in the deadlock cycle because we can never wait for any other heavyweight
187 : : * lock after acquiring this lock.
188 : : *
189 : : * Such a restriction is okay for relation extension locks as unlike other
190 : : * heavyweight locks these are not held till the transaction end. These are
191 : : * taken for a short duration to extend a particular relation and then
192 : : * released.
193 : : */
194 : : static bool IsRelationExtensionLockHeld PG_USED_FOR_ASSERTS_ONLY = false;
195 : :
196 : : /*
197 : : * Number of fast-path locks per backend - size of the arrays in PGPROC.
198 : : * This is set only once during start, before initializing shared memory,
199 : : * and remains constant after that.
200 : : *
201 : : * We set the limit based on max_locks_per_transaction GUC, because that's
202 : : * the best information about expected number of locks per backend we have.
203 : : * See InitializeFastPathLocks() for details.
204 : : */
205 : : int FastPathLockGroupsPerBackend = 0;
206 : :
207 : : /*
208 : : * Macros to calculate the fast-path group and index for a relation.
209 : : *
210 : : * The formula is a simple hash function, designed to spread the OIDs a bit,
211 : : * so that even contiguous values end up in different groups. In most cases
212 : : * there will be gaps anyway, but the multiplication should help a bit.
213 : : *
214 : : * The selected constant (49157) is a prime not too close to 2^k, and it's
215 : : * small enough to not cause overflows (in 64-bit).
216 : : *
217 : : * We can assume that FastPathLockGroupsPerBackend is a power-of-two per
218 : : * InitializeFastPathLocks().
219 : : */
220 : : #define FAST_PATH_REL_GROUP(rel) \
221 : : (((uint64) (rel) * 49157) & (FastPathLockGroupsPerBackend - 1))
222 : :
223 : : /*
224 : : * Given the group/slot indexes, calculate the slot index in the whole array
225 : : * of fast-path lock slots.
226 : : */
227 : : #define FAST_PATH_SLOT(group, index) \
228 : : (AssertMacro((uint32) (group) < FastPathLockGroupsPerBackend), \
229 : : AssertMacro((uint32) (index) < FP_LOCK_SLOTS_PER_GROUP), \
230 : : ((group) * FP_LOCK_SLOTS_PER_GROUP + (index)))
231 : :
232 : : /*
233 : : * Given a slot index (into the whole per-backend array), calculated using
234 : : * the FAST_PATH_SLOT macro, split it into group and index (in the group).
235 : : */
236 : : #define FAST_PATH_GROUP(index) \
237 : : (AssertMacro((uint32) (index) < FastPathLockSlotsPerBackend()), \
238 : : ((index) / FP_LOCK_SLOTS_PER_GROUP))
239 : : #define FAST_PATH_INDEX(index) \
240 : : (AssertMacro((uint32) (index) < FastPathLockSlotsPerBackend()), \
241 : : ((index) % FP_LOCK_SLOTS_PER_GROUP))
242 : :
243 : : /* Macros for manipulating proc->fpLockBits */
244 : : #define FAST_PATH_BITS_PER_SLOT 3
245 : : #define FAST_PATH_LOCKNUMBER_OFFSET 1
246 : : #define FAST_PATH_MASK ((1 << FAST_PATH_BITS_PER_SLOT) - 1)
247 : : #define FAST_PATH_BITS(proc, n) (proc)->fpLockBits[FAST_PATH_GROUP(n)]
248 : : #define FAST_PATH_GET_BITS(proc, n) \
249 : : ((FAST_PATH_BITS(proc, n) >> (FAST_PATH_BITS_PER_SLOT * FAST_PATH_INDEX(n))) & FAST_PATH_MASK)
250 : : #define FAST_PATH_BIT_POSITION(n, l) \
251 : : (AssertMacro((l) >= FAST_PATH_LOCKNUMBER_OFFSET), \
252 : : AssertMacro((l) < FAST_PATH_BITS_PER_SLOT+FAST_PATH_LOCKNUMBER_OFFSET), \
253 : : AssertMacro((n) < FastPathLockSlotsPerBackend()), \
254 : : ((l) - FAST_PATH_LOCKNUMBER_OFFSET + FAST_PATH_BITS_PER_SLOT * (FAST_PATH_INDEX(n))))
255 : : #define FAST_PATH_SET_LOCKMODE(proc, n, l) \
256 : : FAST_PATH_BITS(proc, n) |= UINT64CONST(1) << FAST_PATH_BIT_POSITION(n, l)
257 : : #define FAST_PATH_CLEAR_LOCKMODE(proc, n, l) \
258 : : FAST_PATH_BITS(proc, n) &= ~(UINT64CONST(1) << FAST_PATH_BIT_POSITION(n, l))
259 : : #define FAST_PATH_CHECK_LOCKMODE(proc, n, l) \
260 : : (FAST_PATH_BITS(proc, n) & (UINT64CONST(1) << FAST_PATH_BIT_POSITION(n, l)))
261 : :
262 : : /*
263 : : * The fast-path lock mechanism is concerned only with relation locks on
264 : : * unshared relations by backends bound to a database. The fast-path
265 : : * mechanism exists mostly to accelerate acquisition and release of locks
266 : : * that rarely conflict. Because ShareUpdateExclusiveLock is
267 : : * self-conflicting, it can't use the fast-path mechanism; but it also does
268 : : * not conflict with any of the locks that do, so we can ignore it completely.
269 : : */
270 : : #define EligibleForRelationFastPath(locktag, mode) \
271 : : ((locktag)->locktag_lockmethodid == DEFAULT_LOCKMETHOD && \
272 : : (locktag)->locktag_type == LOCKTAG_RELATION && \
273 : : (locktag)->locktag_field1 == MyDatabaseId && \
274 : : MyDatabaseId != InvalidOid && \
275 : : (mode) < ShareUpdateExclusiveLock)
276 : : #define ConflictsWithRelationFastPath(locktag, mode) \
277 : : ((locktag)->locktag_lockmethodid == DEFAULT_LOCKMETHOD && \
278 : : (locktag)->locktag_type == LOCKTAG_RELATION && \
279 : : (locktag)->locktag_field1 != InvalidOid && \
280 : : (mode) > ShareUpdateExclusiveLock)
281 : :
282 : : static bool FastPathGrantRelationLock(Oid relid, LOCKMODE lockmode);
283 : : static bool FastPathUnGrantRelationLock(Oid relid, LOCKMODE lockmode);
284 : : static bool FastPathTransferRelationLocks(LockMethod lockMethodTable,
285 : : const LOCKTAG *locktag, uint32 hashcode);
286 : : static PROCLOCK *FastPathGetRelationLockEntry(LOCALLOCK *locallock);
287 : :
288 : : /*
289 : : * To make the fast-path lock mechanism work, we must have some way of
290 : : * preventing the use of the fast-path when a conflicting lock might be present.
291 : : * We partition* the locktag space into FAST_PATH_STRONG_LOCK_HASH_PARTITIONS,
292 : : * and maintain an integer count of the number of "strong" lockers
293 : : * in each partition. When any "strong" lockers are present (which is
294 : : * hopefully not very often), the fast-path mechanism can't be used, and we
295 : : * must fall back to the slower method of pushing matching locks directly
296 : : * into the main lock tables.
297 : : *
298 : : * The deadlock detector does not know anything about the fast path mechanism,
299 : : * so any locks that might be involved in a deadlock must be transferred from
300 : : * the fast-path queues to the main lock table.
301 : : */
302 : :
303 : : #define FAST_PATH_STRONG_LOCK_HASH_BITS 10
304 : : #define FAST_PATH_STRONG_LOCK_HASH_PARTITIONS \
305 : : (1 << FAST_PATH_STRONG_LOCK_HASH_BITS)
306 : : #define FastPathStrongLockHashPartition(hashcode) \
307 : : ((hashcode) % FAST_PATH_STRONG_LOCK_HASH_PARTITIONS)
308 : :
309 : : static pg_atomic_uint32 *FastPathStrongRelationLocks;
310 : :
311 : : static void LockManagerShmemRequest(void *arg);
312 : : static void LockManagerShmemInit(void *arg);
313 : :
314 : : const ShmemCallbacks LockManagerShmemCallbacks = {
315 : : .request_fn = LockManagerShmemRequest,
316 : : .init_fn = LockManagerShmemInit,
317 : : };
318 : :
319 : :
320 : : /*
321 : : * Pointers to hash tables containing lock state
322 : : *
323 : : * The LockMethodLockHash and LockMethodProcLockHash hash tables are in
324 : : * shared memory; LockMethodLocalHash is local to each backend.
325 : : */
326 : : static HTAB *LockMethodLockHash;
327 : : static HTAB *LockMethodProcLockHash;
328 : : static HTAB *LockMethodLocalHash;
329 : :
330 : :
331 : : /* private state for error cleanup */
332 : : static LOCALLOCK *StrongLockInProgress;
333 : : static LOCALLOCK *awaitedLock;
334 : : static ResourceOwner awaitedOwner;
335 : :
336 : :
337 : : #ifdef LOCK_DEBUG
338 : :
339 : : /*------
340 : : * The following configuration options are available for lock debugging:
341 : : *
342 : : * TRACE_LOCKS -- give a bunch of output what's going on in this file
343 : : * TRACE_USERLOCKS -- same but for user locks
344 : : * TRACE_LOCK_OIDMIN-- do not trace locks for tables below this oid
345 : : * (use to avoid output on system tables)
346 : : * TRACE_LOCK_TABLE -- trace locks on this table (oid) unconditionally
347 : : * DEBUG_DEADLOCKS -- currently dumps locks at untimely occasions ;)
348 : : *
349 : : * Furthermore, but in storage/lmgr/lwlock.c:
350 : : * TRACE_LWLOCKS -- trace lightweight locks (pretty useless)
351 : : *
352 : : * Define LOCK_DEBUG at compile time to get all these enabled.
353 : : * --------
354 : : */
355 : :
356 : : int Trace_lock_oidmin = FirstNormalObjectId;
357 : : bool Trace_locks = false;
358 : : bool Trace_userlocks = false;
359 : : int Trace_lock_table = 0;
360 : : bool Debug_deadlocks = false;
361 : :
362 : :
363 : : inline static bool
364 : : LOCK_DEBUG_ENABLED(const LOCKTAG *tag)
365 : : {
366 : : return
367 : : (*(LockMethods[tag->locktag_lockmethodid]->trace_flag) &&
368 : : ((Oid) tag->locktag_field2 >= (Oid) Trace_lock_oidmin))
369 : : || (Trace_lock_table &&
370 : : (tag->locktag_field2 == Trace_lock_table));
371 : : }
372 : :
373 : :
374 : : inline static void
375 : : LOCK_PRINT(const char *where, const LOCK *lock, LOCKMODE type)
376 : : {
377 : : if (LOCK_DEBUG_ENABLED(&lock->tag))
378 : : elog(LOG,
379 : : "%s: lock(%p) id(%u,%u,%u,%u,%u,%u) grantMask(%x) "
380 : : "req(%d,%d,%d,%d,%d,%d,%d)=%d "
381 : : "grant(%d,%d,%d,%d,%d,%d,%d)=%d wait(%d) type(%s)",
382 : : where, lock,
383 : : lock->tag.locktag_field1, lock->tag.locktag_field2,
384 : : lock->tag.locktag_field3, lock->tag.locktag_field4,
385 : : lock->tag.locktag_type, lock->tag.locktag_lockmethodid,
386 : : lock->grantMask,
387 : : lock->requested[1], lock->requested[2], lock->requested[3],
388 : : lock->requested[4], lock->requested[5], lock->requested[6],
389 : : lock->requested[7], lock->nRequested,
390 : : lock->granted[1], lock->granted[2], lock->granted[3],
391 : : lock->granted[4], lock->granted[5], lock->granted[6],
392 : : lock->granted[7], lock->nGranted,
393 : : dclist_count(&lock->waitProcs),
394 : : LockMethods[LOCK_LOCKMETHOD(*lock)]->lockModeNames[type]);
395 : : }
396 : :
397 : :
398 : : inline static void
399 : : PROCLOCK_PRINT(const char *where, const PROCLOCK *proclockP)
400 : : {
401 : : if (LOCK_DEBUG_ENABLED(&proclockP->tag.myLock->tag))
402 : : elog(LOG,
403 : : "%s: proclock(%p) lock(%p) method(%u) proc(%p) hold(%x)",
404 : : where, proclockP, proclockP->tag.myLock,
405 : : PROCLOCK_LOCKMETHOD(*(proclockP)),
406 : : proclockP->tag.myProc, (int) proclockP->holdMask);
407 : : }
408 : : #else /* not LOCK_DEBUG */
409 : :
410 : : #define LOCK_PRINT(where, lock, type) ((void) 0)
411 : : #define PROCLOCK_PRINT(where, proclockP) ((void) 0)
412 : : #endif /* not LOCK_DEBUG */
413 : :
414 : :
415 : : static uint32 proclock_hash(const void *key, Size keysize);
416 : : static void RemoveLocalLock(LOCALLOCK *locallock);
417 : : static PROCLOCK *SetupLockInTable(LockMethod lockMethodTable, PGPROC *proc,
418 : : const LOCKTAG *locktag, uint32 hashcode, LOCKMODE lockmode);
419 : : static void GrantLockLocal(LOCALLOCK *locallock, ResourceOwner owner);
420 : : static void BeginStrongLockAcquire(LOCALLOCK *locallock, uint32 fasthashcode);
421 : : static void FinishStrongLockAcquire(void);
422 : : static ProcWaitStatus WaitOnLock(LOCALLOCK *locallock, ResourceOwner owner);
423 : : static void waitonlock_error_callback(void *arg);
424 : : static void ReleaseLockIfHeld(LOCALLOCK *locallock, bool sessionLock);
425 : : static void LockReassignOwner(LOCALLOCK *locallock, ResourceOwner parent);
426 : : static bool UnGrantLock(LOCK *lock, LOCKMODE lockmode,
427 : : PROCLOCK *proclock, LockMethod lockMethodTable);
428 : : static void CleanUpLock(LOCK *lock, PROCLOCK *proclock,
429 : : LockMethod lockMethodTable, uint32 hashcode,
430 : : bool wakeupNeeded);
431 : : static void LockRefindAndRelease(LockMethod lockMethodTable, PGPROC *proc,
432 : : LOCKTAG *locktag, LOCKMODE lockmode,
433 : : bool decrement_strong_lock_count);
434 : : static void GetSingleProcBlockerStatusData(PGPROC *blocked_proc,
435 : : BlockedProcsData *data);
436 : :
437 : :
438 : : /*
439 : : * Register the lock manager's shmem data structures.
440 : : *
441 : : * In addition to this, each backend must also call InitLockManagerAccess() to
442 : : * create the locallock hash table.
443 : : */
444 : : static void
445 : 1283 : LockManagerShmemRequest(void *arg)
446 : : {
447 : : int64 max_table_size;
448 : :
449 : : /*
450 : : * Compute sizes for lock hashtables.
451 : : */
452 : 1283 : max_table_size = NLOCKENTS();
453 : :
454 : : /*
455 : : * Hash table for LOCK structs. This stores per-locked-object
456 : : * information.
457 : : */
458 : 1283 : ShmemRequestHash(.name = "LOCK hash",
459 : : .nelems = max_table_size,
460 : : .ptr = &LockMethodLockHash,
461 : : .hash_info.keysize = sizeof(LOCKTAG),
462 : : .hash_info.entrysize = sizeof(LOCK),
463 : : .hash_info.num_partitions = NUM_LOCK_PARTITIONS,
464 : : .hash_flags = HASH_ELEM | HASH_BLOBS | HASH_PARTITION,
465 : : );
466 : :
467 : : /* Assume an average of 2 holders per lock */
468 : 1283 : max_table_size *= 2;
469 : :
470 : 1283 : ShmemRequestHash(.name = "PROCLOCK hash",
471 : : .nelems = max_table_size,
472 : : .ptr = &LockMethodProcLockHash,
473 : : .hash_info.keysize = sizeof(PROCLOCKTAG),
474 : : .hash_info.entrysize = sizeof(PROCLOCK),
475 : : .hash_info.hash = proclock_hash,
476 : : .hash_info.num_partitions = NUM_LOCK_PARTITIONS,
477 : : .hash_flags = HASH_ELEM | HASH_FUNCTION | HASH_PARTITION,
478 : : );
479 : :
480 : 1283 : ShmemRequestStruct(.name = "Fast Path Strong Relation Lock Data",
481 : : .size = mul_size(sizeof(pg_atomic_uint32),
482 : : FAST_PATH_STRONG_LOCK_HASH_PARTITIONS),
483 : : .ptr = (void **) (void *) &FastPathStrongRelationLocks,
484 : : );
485 : 1283 : }
486 : :
487 : : static void
488 : 1280 : LockManagerShmemInit(void *arg)
489 : : {
490 [ + + ]: 1312000 : for (int i = 0; i < FAST_PATH_STRONG_LOCK_HASH_PARTITIONS; i++)
491 : 1310720 : pg_atomic_init_u32(&FastPathStrongRelationLocks[i], 0);
492 : 1280 : }
493 : :
494 : : /*
495 : : * Initialize the lock manager's backend-private data structures.
496 : : */
497 : : void
498 : 25474 : InitLockManagerAccess(void)
499 : : {
500 : : /*
501 : : * Allocate non-shared hash table for LOCALLOCK structs. This stores lock
502 : : * counts and resource owner information.
503 : : */
504 : : HASHCTL info;
505 : :
506 : 25474 : info.keysize = sizeof(LOCALLOCKTAG);
507 : 25474 : info.entrysize = sizeof(LOCALLOCK);
508 : :
509 : 25474 : LockMethodLocalHash = hash_create("LOCALLOCK hash",
510 : : 16,
511 : : &info,
512 : : HASH_ELEM | HASH_BLOBS);
513 : 25474 : }
514 : :
515 : :
516 : : /*
517 : : * Fetch the lock method table associated with a given lock
518 : : */
519 : : LockMethod
520 : 111 : GetLocksMethodTable(const LOCK *lock)
521 : : {
522 : 111 : LOCKMETHODID lockmethodid = LOCK_LOCKMETHOD(*lock);
523 : :
524 : : Assert(0 < lockmethodid && lockmethodid < lengthof(LockMethods));
525 : 111 : return LockMethods[lockmethodid];
526 : : }
527 : :
528 : : /*
529 : : * Fetch the lock method table associated with a given locktag
530 : : */
531 : : LockMethod
532 : 1268 : GetLockTagsMethodTable(const LOCKTAG *locktag)
533 : : {
534 : 1268 : LOCKMETHODID lockmethodid = (LOCKMETHODID) locktag->locktag_lockmethodid;
535 : :
536 : : Assert(0 < lockmethodid && lockmethodid < lengthof(LockMethods));
537 : 1268 : return LockMethods[lockmethodid];
538 : : }
539 : :
540 : :
541 : : /*
542 : : * Compute the hash code associated with a LOCKTAG.
543 : : *
544 : : * To avoid unnecessary recomputations of the hash code, we try to do this
545 : : * just once per function, and then pass it around as needed. Aside from
546 : : * passing the hashcode to hash_search_with_hash_value(), we can extract
547 : : * the lock partition number from the hashcode.
548 : : */
549 : : uint32
550 : 25244544 : LockTagHashCode(const LOCKTAG *locktag)
551 : : {
552 : 25244544 : return get_hash_value(LockMethodLockHash, locktag);
553 : : }
554 : :
555 : : /*
556 : : * Compute the hash code associated with a PROCLOCKTAG.
557 : : *
558 : : * Because we want to use just one set of partition locks for both the
559 : : * LOCK and PROCLOCK hash tables, we have to make sure that PROCLOCKs
560 : : * fall into the same partition number as their associated LOCKs.
561 : : * dynahash.c expects the partition number to be the low-order bits of
562 : : * the hash code, and therefore a PROCLOCKTAG's hash code must have the
563 : : * same low-order bits as the associated LOCKTAG's hash code. We achieve
564 : : * this with this specialized hash function.
565 : : */
566 : : static uint32
567 : 836 : proclock_hash(const void *key, Size keysize)
568 : : {
569 : 836 : const PROCLOCKTAG *proclocktag = (const PROCLOCKTAG *) key;
570 : : uint32 lockhash;
571 : : Datum procptr;
572 : :
573 : : Assert(keysize == sizeof(PROCLOCKTAG));
574 : :
575 : : /* Look into the associated LOCK object, and compute its hash code */
576 : 836 : lockhash = LockTagHashCode(&proclocktag->myLock->tag);
577 : :
578 : : /*
579 : : * To make the hash code also depend on the PGPROC, we xor the proc
580 : : * struct's address into the hash code, left-shifted so that the
581 : : * partition-number bits don't change. Since this is only a hash, we
582 : : * don't care if we lose high-order bits of the address; use an
583 : : * intermediate variable to suppress cast-pointer-to-int warnings.
584 : : */
585 : 836 : procptr = PointerGetDatum(proclocktag->myProc);
586 : 836 : lockhash ^= DatumGetUInt32(procptr) << LOG2_NUM_LOCK_PARTITIONS;
587 : :
588 : 836 : return lockhash;
589 : : }
590 : :
591 : : /*
592 : : * Compute the hash code associated with a PROCLOCKTAG, given the hashcode
593 : : * for its underlying LOCK.
594 : : *
595 : : * We use this just to avoid redundant calls of LockTagHashCode().
596 : : */
597 : : static inline uint32
598 : 5659212 : ProcLockHashCode(const PROCLOCKTAG *proclocktag, uint32 hashcode)
599 : : {
600 : 5659212 : uint32 lockhash = hashcode;
601 : : Datum procptr;
602 : :
603 : : /*
604 : : * This must match proclock_hash()!
605 : : */
606 : 5659212 : procptr = PointerGetDatum(proclocktag->myProc);
607 : 5659212 : lockhash ^= DatumGetUInt32(procptr) << LOG2_NUM_LOCK_PARTITIONS;
608 : :
609 : 5659212 : return lockhash;
610 : : }
611 : :
612 : : /*
613 : : * Given two lock modes, return whether they would conflict.
614 : : */
615 : : bool
616 : 39027 : DoLockModesConflict(LOCKMODE mode1, LOCKMODE mode2)
617 : : {
618 : 39027 : LockMethod lockMethodTable = LockMethods[DEFAULT_LOCKMETHOD];
619 : :
620 [ + + ]: 39027 : if (lockMethodTable->conflictTab[mode1] & LOCKBIT_ON(mode2))
621 : 148 : return true;
622 : :
623 : 38879 : return false;
624 : : }
625 : :
626 : : /*
627 : : * LockHeldByMe -- test whether lock 'locktag' is held by the current
628 : : * transaction
629 : : *
630 : : * Returns true if current transaction holds a lock on 'tag' of mode
631 : : * 'lockmode'. If 'orstronger' is true, a stronger lockmode is also OK.
632 : : * ("Stronger" is defined as "numerically higher", which is a bit
633 : : * semantically dubious but is OK for the purposes we use this for.)
634 : : */
635 : : bool
636 : 1982933 : LockHeldByMe(const LOCKTAG *locktag,
637 : : LOCKMODE lockmode, bool orstronger)
638 : : {
639 : : LOCALLOCKTAG localtag;
640 : : LOCALLOCK *locallock;
641 : :
642 : : /*
643 : : * See if there is a LOCALLOCK entry for this lock and lockmode
644 : : */
645 [ + - - + : 1982933 : MemSet(&localtag, 0, sizeof(localtag)); /* must clear padding */
- - - - -
- ]
646 : 1982933 : localtag.lock = *locktag;
647 : 1982933 : localtag.mode = lockmode;
648 : :
649 : 1982933 : locallock = (LOCALLOCK *) hash_search(LockMethodLocalHash,
650 : : &localtag,
651 : : HASH_FIND, NULL);
652 : :
653 [ + + + - ]: 1982933 : if (locallock && locallock->nLocks > 0)
654 : 294853 : return true;
655 : :
656 [ + + ]: 1688080 : if (orstronger)
657 : : {
658 : : LOCKMODE slockmode;
659 : :
660 : 251658 : for (slockmode = lockmode + 1;
661 [ + + ]: 1688080 : slockmode <= MaxLockMode;
662 : 1436422 : slockmode++)
663 : : {
664 [ + + ]: 1588926 : if (LockHeldByMe(locktag, slockmode, false))
665 : 152504 : return true;
666 : : }
667 : : }
668 : :
669 : 1535576 : return false;
670 : : }
671 : :
672 : : #ifdef USE_ASSERT_CHECKING
673 : : /*
674 : : * GetLockMethodLocalHash -- return the hash of local locks, for modules that
675 : : * evaluate assertions based on all locks held.
676 : : */
677 : : HTAB *
678 : : GetLockMethodLocalHash(void)
679 : : {
680 : : return LockMethodLocalHash;
681 : : }
682 : : #endif
683 : :
684 : : /*
685 : : * LockHasWaiters -- look up 'locktag' and check if releasing this
686 : : * lock would wake up other processes waiting for it.
687 : : */
688 : : bool
689 : 0 : LockHasWaiters(const LOCKTAG *locktag, LOCKMODE lockmode, bool sessionLock)
690 : : {
691 : 0 : LOCKMETHODID lockmethodid = locktag->locktag_lockmethodid;
692 : : LockMethod lockMethodTable;
693 : : LOCALLOCKTAG localtag;
694 : : LOCALLOCK *locallock;
695 : : LOCK *lock;
696 : : PROCLOCK *proclock;
697 : : LWLock *partitionLock;
698 : 0 : bool hasWaiters = false;
699 : :
700 [ # # # # ]: 0 : if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
701 [ # # ]: 0 : elog(ERROR, "unrecognized lock method: %d", lockmethodid);
702 : 0 : lockMethodTable = LockMethods[lockmethodid];
703 [ # # # # ]: 0 : if (lockmode <= 0 || lockmode > lockMethodTable->numLockModes)
704 [ # # ]: 0 : elog(ERROR, "unrecognized lock mode: %d", lockmode);
705 : :
706 : : #ifdef LOCK_DEBUG
707 : : if (LOCK_DEBUG_ENABLED(locktag))
708 : : elog(LOG, "LockHasWaiters: lock [%u,%u] %s",
709 : : locktag->locktag_field1, locktag->locktag_field2,
710 : : lockMethodTable->lockModeNames[lockmode]);
711 : : #endif
712 : :
713 : : /*
714 : : * Find the LOCALLOCK entry for this lock and lockmode
715 : : */
716 [ # # # # : 0 : MemSet(&localtag, 0, sizeof(localtag)); /* must clear padding */
# # # # #
# ]
717 : 0 : localtag.lock = *locktag;
718 : 0 : localtag.mode = lockmode;
719 : :
720 : 0 : locallock = (LOCALLOCK *) hash_search(LockMethodLocalHash,
721 : : &localtag,
722 : : HASH_FIND, NULL);
723 : :
724 : : /*
725 : : * let the caller print its own error message, too. Do not ereport(ERROR).
726 : : */
727 [ # # # # ]: 0 : if (!locallock || locallock->nLocks <= 0)
728 : : {
729 [ # # ]: 0 : elog(WARNING, "you don't own a lock of type %s",
730 : : lockMethodTable->lockModeNames[lockmode]);
731 : 0 : return false;
732 : : }
733 : :
734 : : /*
735 : : * Check the shared lock table.
736 : : */
737 : 0 : partitionLock = LockHashPartitionLock(locallock->hashcode);
738 : :
739 : 0 : LWLockAcquire(partitionLock, LW_SHARED);
740 : :
741 : : /*
742 : : * We don't need to re-find the lock or proclock, since we kept their
743 : : * addresses in the locallock table, and they couldn't have been removed
744 : : * while we were holding a lock on them.
745 : : */
746 : 0 : lock = locallock->lock;
747 : : LOCK_PRINT("LockHasWaiters: found", lock, lockmode);
748 : 0 : proclock = locallock->proclock;
749 : : PROCLOCK_PRINT("LockHasWaiters: found", proclock);
750 : :
751 : : /*
752 : : * Double-check that we are actually holding a lock of the type we want to
753 : : * release.
754 : : */
755 [ # # ]: 0 : if (!(proclock->holdMask & LOCKBIT_ON(lockmode)))
756 : : {
757 : : PROCLOCK_PRINT("LockHasWaiters: WRONGTYPE", proclock);
758 : 0 : LWLockRelease(partitionLock);
759 [ # # ]: 0 : elog(WARNING, "you don't own a lock of type %s",
760 : : lockMethodTable->lockModeNames[lockmode]);
761 : 0 : RemoveLocalLock(locallock);
762 : 0 : return false;
763 : : }
764 : :
765 : : /*
766 : : * Do the checking.
767 : : */
768 [ # # ]: 0 : if ((lockMethodTable->conflictTab[lockmode] & lock->waitMask) != 0)
769 : 0 : hasWaiters = true;
770 : :
771 : 0 : LWLockRelease(partitionLock);
772 : :
773 : 0 : return hasWaiters;
774 : : }
775 : :
776 : : /*
777 : : * LockAcquire -- Check for lock conflicts, sleep if conflict found,
778 : : * set lock if/when no conflicts.
779 : : *
780 : : * Inputs:
781 : : * locktag: unique identifier for the lockable object
782 : : * lockmode: lock mode to acquire
783 : : * sessionLock: if true, acquire lock for session not current transaction
784 : : * dontWait: if true, don't wait to acquire lock
785 : : *
786 : : * Returns one of:
787 : : * LOCKACQUIRE_NOT_AVAIL lock not available, and dontWait=true
788 : : * LOCKACQUIRE_OK lock successfully acquired
789 : : * LOCKACQUIRE_ALREADY_HELD incremented count for lock already held
790 : : * LOCKACQUIRE_ALREADY_CLEAR incremented count for lock already clear
791 : : *
792 : : * In the normal case where dontWait=false and the caller doesn't need to
793 : : * distinguish a freshly acquired lock from one already taken earlier in
794 : : * this same transaction, there is no need to examine the return value.
795 : : *
796 : : * Side Effects: The lock is acquired and recorded in lock tables.
797 : : *
798 : : * NOTE: if we wait for the lock, there is no way to abort the wait
799 : : * short of aborting the transaction.
800 : : */
801 : : LockAcquireResult
802 : 1203052 : LockAcquire(const LOCKTAG *locktag,
803 : : LOCKMODE lockmode,
804 : : bool sessionLock,
805 : : bool dontWait)
806 : : {
807 : 1203052 : return LockAcquireExtended(locktag, lockmode, sessionLock, dontWait,
808 : : true, NULL, false);
809 : : }
810 : :
811 : : /*
812 : : * LockAcquireExtended - allows us to specify additional options
813 : : *
814 : : * reportMemoryError specifies whether a lock request that fills the lock
815 : : * table should generate an ERROR or not. Passing "false" allows the caller
816 : : * to attempt to recover from lock-table-full situations, perhaps by forcibly
817 : : * canceling other lock holders and then retrying. Note, however, that the
818 : : * return code for that is LOCKACQUIRE_NOT_AVAIL, so that it's unsafe to use
819 : : * in combination with dontWait = true, as the cause of failure couldn't be
820 : : * distinguished.
821 : : *
822 : : * If locallockp isn't NULL, *locallockp receives a pointer to the LOCALLOCK
823 : : * table entry if a lock is successfully acquired, or NULL if not.
824 : : *
825 : : * logLockFailure indicates whether to log details when a lock acquisition
826 : : * fails with dontWait = true.
827 : : */
828 : : LockAcquireResult
829 : 27138469 : LockAcquireExtended(const LOCKTAG *locktag,
830 : : LOCKMODE lockmode,
831 : : bool sessionLock,
832 : : bool dontWait,
833 : : bool reportMemoryError,
834 : : LOCALLOCK **locallockp,
835 : : bool logLockFailure)
836 : : {
837 : 27138469 : LOCKMETHODID lockmethodid = locktag->locktag_lockmethodid;
838 : : LockMethod lockMethodTable;
839 : : LOCALLOCKTAG localtag;
840 : : LOCALLOCK *locallock;
841 : : LOCK *lock;
842 : : PROCLOCK *proclock;
843 : : bool found;
844 : : ResourceOwner owner;
845 : : uint32 hashcode;
846 : : LWLock *partitionLock;
847 : : bool found_conflict;
848 : : ProcWaitStatus waitResult;
849 : 27138469 : bool log_lock = false;
850 : :
851 [ + - - + ]: 27138469 : if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
852 [ # # ]: 0 : elog(ERROR, "unrecognized lock method: %d", lockmethodid);
853 : 27138469 : lockMethodTable = LockMethods[lockmethodid];
854 [ + - - + ]: 27138469 : if (lockmode <= 0 || lockmode > lockMethodTable->numLockModes)
855 [ # # ]: 0 : elog(ERROR, "unrecognized lock mode: %d", lockmode);
856 : :
857 [ + + + + ]: 27138469 : if (RecoveryInProgress() && !InRecovery &&
858 [ + + ]: 404462 : (locktag->locktag_type == LOCKTAG_OBJECT ||
859 [ + - - + ]: 404462 : locktag->locktag_type == LOCKTAG_RELATION) &&
860 : : lockmode > RowExclusiveLock)
861 [ # # ]: 0 : ereport(ERROR,
862 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
863 : : errmsg("cannot acquire lock mode %s on database objects while recovery is in progress",
864 : : lockMethodTable->lockModeNames[lockmode]),
865 : : errhint("Only RowExclusiveLock or less can be acquired on database objects during recovery.")));
866 : :
867 : : #ifdef LOCK_DEBUG
868 : : if (LOCK_DEBUG_ENABLED(locktag))
869 : : elog(LOG, "LockAcquire: lock [%u,%u] %s",
870 : : locktag->locktag_field1, locktag->locktag_field2,
871 : : lockMethodTable->lockModeNames[lockmode]);
872 : : #endif
873 : :
874 : : /* Identify owner for lock */
875 [ + + ]: 27138469 : if (sessionLock)
876 : 157010 : owner = NULL;
877 : : else
878 : 26981459 : owner = CurrentResourceOwner;
879 : :
880 : : /*
881 : : * Find or create a LOCALLOCK entry for this lock and lockmode
882 : : */
883 [ + - - + : 27138469 : MemSet(&localtag, 0, sizeof(localtag)); /* must clear padding */
- - - - -
- ]
884 : 27138469 : localtag.lock = *locktag;
885 : 27138469 : localtag.mode = lockmode;
886 : :
887 : 27138469 : locallock = (LOCALLOCK *) hash_search(LockMethodLocalHash,
888 : : &localtag,
889 : : HASH_ENTER, &found);
890 : :
891 : : /*
892 : : * if it's a new locallock object, initialize it
893 : : */
894 [ + + ]: 27138469 : if (!found)
895 : : {
896 : 24410334 : locallock->lock = NULL;
897 : 24410334 : locallock->proclock = NULL;
898 : 24410334 : locallock->hashcode = LockTagHashCode(&(localtag.lock));
899 : 24410334 : locallock->nLocks = 0;
900 : 24410334 : locallock->holdsStrongLockCount = false;
901 : 24410334 : locallock->lockCleared = false;
902 : 24410334 : locallock->numLockOwners = 0;
903 : 24410334 : locallock->maxLockOwners = 8;
904 : 24410334 : locallock->lockOwners = NULL; /* in case next line fails */
905 : 24410334 : locallock->lockOwners = (LOCALLOCKOWNER *)
906 : 24410334 : MemoryContextAlloc(TopMemoryContext,
907 : 24410334 : locallock->maxLockOwners * sizeof(LOCALLOCKOWNER));
908 : : }
909 : : else
910 : : {
911 : : /* Make sure there will be room to remember the lock */
912 [ - + ]: 2728135 : if (locallock->lockOwners == NULL)
913 : : {
914 : : /*
915 : : * A prior acquisition may leave the array unallocated after an
916 : : * out-of-memory failure.
917 : : */
918 : 0 : locallock->maxLockOwners = 8;
919 : 0 : locallock->lockOwners = (LOCALLOCKOWNER *)
920 : 0 : MemoryContextAlloc(TopMemoryContext,
921 : 0 : locallock->maxLockOwners * sizeof(LOCALLOCKOWNER));
922 : : }
923 [ + + ]: 2728135 : else if (locallock->numLockOwners >= locallock->maxLockOwners)
924 : : {
925 : 21 : int newsize = locallock->maxLockOwners * 2;
926 : :
927 : 21 : locallock->lockOwners = repalloc_array(locallock->lockOwners,
928 : : LOCALLOCKOWNER, newsize);
929 : 21 : locallock->maxLockOwners = newsize;
930 : : }
931 : : }
932 : 27138469 : hashcode = locallock->hashcode;
933 : :
934 [ + + ]: 27138469 : if (locallockp)
935 : 25935323 : *locallockp = locallock;
936 : :
937 : : /*
938 : : * If we already hold the lock, we can just increase the count locally.
939 : : *
940 : : * If lockCleared is already set, caller need not worry about absorbing
941 : : * sinval messages related to the lock's object.
942 : : */
943 [ + + ]: 27138469 : if (locallock->nLocks > 0)
944 : : {
945 : 2728135 : GrantLockLocal(locallock, owner);
946 [ + + ]: 2728135 : if (locallock->lockCleared)
947 : 2632040 : return LOCKACQUIRE_ALREADY_CLEAR;
948 : : else
949 : 96095 : return LOCKACQUIRE_ALREADY_HELD;
950 : : }
951 : :
952 : : /*
953 : : * We don't acquire any other heavyweight lock while holding the relation
954 : : * extension lock. We do allow to acquire the same relation extension
955 : : * lock more than once but that case won't reach here.
956 : : */
957 : : Assert(!IsRelationExtensionLockHeld);
958 : :
959 : : /*
960 : : * Prepare to emit a WAL record if acquisition of this lock needs to be
961 : : * replayed in a standby server.
962 : : *
963 : : * Here we prepare to log; after lock is acquired we'll issue log record.
964 : : * This arrangement simplifies error recovery in case the preparation step
965 : : * fails.
966 : : *
967 : : * Only AccessExclusiveLocks can conflict with lock types that read-only
968 : : * transactions can acquire in a standby server. Make sure this definition
969 : : * matches the one in GetRunningTransactionLocks().
970 : : */
971 [ + + ]: 24410334 : if (lockmode >= AccessExclusiveLock &&
972 [ + + ]: 311008 : locktag->locktag_type == LOCKTAG_RELATION &&
973 [ + + ]: 204268 : !RecoveryInProgress() &&
974 [ + + ]: 177246 : XLogStandbyInfoActive())
975 : : {
976 : 169427 : LogAccessExclusiveLockPrepare();
977 : 169427 : log_lock = true;
978 : : }
979 : :
980 : : /*
981 : : * Attempt to take lock via fast path, if eligible. But if we remember
982 : : * having filled up the fast path array, we don't attempt to make any
983 : : * further use of it until we release some locks. It's possible that some
984 : : * other backend has transferred some of those locks to the shared hash
985 : : * table, leaving space free, but it's not worth acquiring the LWLock just
986 : : * to check. It's also possible that we're acquiring a second or third
987 : : * lock type on a relation we have already locked using the fast-path, but
988 : : * for now we don't worry about that case either.
989 : : */
990 [ + + + + : 24410334 : if (EligibleForRelationFastPath(locktag, lockmode))
+ + + + +
+ ]
991 : : {
992 [ + + ]: 21868242 : if (FastPathLocalUseCounts[FAST_PATH_REL_GROUP(locktag->locktag_field2)] <
993 : : FP_LOCK_SLOTS_PER_GROUP)
994 : : {
995 : 21773462 : uint32 fasthashcode = FastPathStrongLockHashPartition(hashcode);
996 : : bool acquired;
997 : :
998 : : /*
999 : : * LWLockAcquire acts as a memory sequencing point, so it's safe
1000 : : * to assume that any strong locker whose increment to
1001 : : * FastPathStrongRelationLocks becomes visible after we test it
1002 : : * has yet to begin to transfer fast-path locks.
1003 : : */
1004 : 21773462 : LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
1005 [ + + ]: 21773462 : if (pg_atomic_read_u32(&FastPathStrongRelationLocks[fasthashcode]) != 0)
1006 : 323626 : acquired = false;
1007 : : else
1008 : 21449836 : acquired = FastPathGrantRelationLock(locktag->locktag_field2,
1009 : : lockmode);
1010 : 21773462 : LWLockRelease(&MyProc->fpInfoLock);
1011 [ + + ]: 21773462 : if (acquired)
1012 : : {
1013 : : /*
1014 : : * The locallock might contain stale pointers to some old
1015 : : * shared objects; we MUST reset these to null before
1016 : : * considering the lock to be acquired via fast-path.
1017 : : */
1018 : 21449836 : locallock->lock = NULL;
1019 : 21449836 : locallock->proclock = NULL;
1020 : 21449836 : GrantLockLocal(locallock, owner);
1021 : 21449836 : return LOCKACQUIRE_OK;
1022 : : }
1023 : : }
1024 : : else
1025 : : {
1026 : : /*
1027 : : * Increment the lock statistics counter if lock could not be
1028 : : * acquired via the fast-path.
1029 : : */
1030 : 94780 : pgstat_count_lock_fastpath_exceeded(locallock->tag.lock.locktag_type);
1031 : : }
1032 : : }
1033 : :
1034 : : /*
1035 : : * If this lock could potentially have been taken via the fast-path by
1036 : : * some other backend, we must (temporarily) disable further use of the
1037 : : * fast-path for this lock tag, and migrate any locks already taken via
1038 : : * this method to the main lock table.
1039 : : */
1040 [ + + + + : 2960498 : if (ConflictsWithRelationFastPath(locktag, lockmode))
+ + + + ]
1041 : : {
1042 : 243714 : uint32 fasthashcode = FastPathStrongLockHashPartition(hashcode);
1043 : :
1044 : 243714 : BeginStrongLockAcquire(locallock, fasthashcode);
1045 [ - + ]: 243714 : if (!FastPathTransferRelationLocks(lockMethodTable, locktag,
1046 : : hashcode))
1047 : : {
1048 : 0 : AbortStrongLockAcquire();
1049 [ # # ]: 0 : if (locallock->nLocks == 0)
1050 : 0 : RemoveLocalLock(locallock);
1051 [ # # ]: 0 : if (locallockp)
1052 : 0 : *locallockp = NULL;
1053 [ # # ]: 0 : if (reportMemoryError)
1054 [ # # ]: 0 : ereport(ERROR,
1055 : : (errcode(ERRCODE_OUT_OF_MEMORY),
1056 : : errmsg("out of shared memory"),
1057 : : errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
1058 : : else
1059 : 0 : return LOCKACQUIRE_NOT_AVAIL;
1060 : : }
1061 : : }
1062 : :
1063 : : /*
1064 : : * We didn't find the lock in our LOCALLOCK table, and we didn't manage to
1065 : : * take it via the fast-path, either, so we've got to mess with the shared
1066 : : * lock table.
1067 : : */
1068 : 2960498 : partitionLock = LockHashPartitionLock(hashcode);
1069 : :
1070 : 2960498 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
1071 : :
1072 : : /*
1073 : : * Find or create lock and proclock entries with this tag
1074 : : *
1075 : : * Note: if the locallock object already existed, it might have a pointer
1076 : : * to the lock already ... but we should not assume that that pointer is
1077 : : * valid, since a lock object with zero hold and request counts can go
1078 : : * away anytime. So we have to use SetupLockInTable() to recompute the
1079 : : * lock and proclock pointers, even if they're already set.
1080 : : */
1081 : 2960498 : proclock = SetupLockInTable(lockMethodTable, MyProc, locktag,
1082 : : hashcode, lockmode);
1083 [ - + ]: 2960498 : if (!proclock)
1084 : : {
1085 : 0 : AbortStrongLockAcquire();
1086 : 0 : LWLockRelease(partitionLock);
1087 [ # # ]: 0 : if (locallock->nLocks == 0)
1088 : 0 : RemoveLocalLock(locallock);
1089 [ # # ]: 0 : if (locallockp)
1090 : 0 : *locallockp = NULL;
1091 [ # # ]: 0 : if (reportMemoryError)
1092 [ # # ]: 0 : ereport(ERROR,
1093 : : (errcode(ERRCODE_OUT_OF_MEMORY),
1094 : : errmsg("out of shared memory"),
1095 : : errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
1096 : : else
1097 : 0 : return LOCKACQUIRE_NOT_AVAIL;
1098 : : }
1099 : 2960498 : locallock->proclock = proclock;
1100 : 2960498 : lock = proclock->tag.myLock;
1101 : 2960498 : locallock->lock = lock;
1102 : :
1103 : : /*
1104 : : * If lock requested conflicts with locks requested by waiters, must join
1105 : : * wait queue. Otherwise, check for conflict with already-held locks.
1106 : : * (That's last because most complex check.)
1107 : : */
1108 [ + + ]: 2960498 : if (lockMethodTable->conflictTab[lockmode] & lock->waitMask)
1109 : 158 : found_conflict = true;
1110 : : else
1111 : 2960340 : found_conflict = LockCheckConflicts(lockMethodTable, lockmode,
1112 : : lock, proclock);
1113 : :
1114 [ + + ]: 2960498 : if (!found_conflict)
1115 : : {
1116 : : /* No conflict with held or previously requested locks */
1117 : 2958273 : GrantLock(lock, proclock, lockmode);
1118 : 2958273 : waitResult = PROC_WAIT_STATUS_OK;
1119 : : }
1120 : : else
1121 : : {
1122 : : /*
1123 : : * Join the lock's wait queue. We call this even in the dontWait
1124 : : * case, because JoinWaitQueue() may discover that we can acquire the
1125 : : * lock immediately after all.
1126 : : */
1127 : 2225 : waitResult = JoinWaitQueue(locallock, lockMethodTable, dontWait);
1128 : : }
1129 : :
1130 [ + + ]: 2960498 : if (waitResult == PROC_WAIT_STATUS_ERROR)
1131 : : {
1132 : : /*
1133 : : * We're not getting the lock because a deadlock was detected already
1134 : : * while trying to join the wait queue, or because we would have to
1135 : : * wait but the caller requested no blocking.
1136 : : *
1137 : : * Undo the changes to shared entries before releasing the partition
1138 : : * lock.
1139 : : */
1140 : 736 : AbortStrongLockAcquire();
1141 : :
1142 [ + + ]: 736 : if (proclock->holdMask == 0)
1143 : : {
1144 : : uint32 proclock_hashcode;
1145 : :
1146 : 532 : proclock_hashcode = ProcLockHashCode(&proclock->tag,
1147 : : hashcode);
1148 : 532 : dlist_delete(&proclock->lockLink);
1149 : 532 : dlist_delete(&proclock->procLink);
1150 [ - + ]: 532 : if (!hash_search_with_hash_value(LockMethodProcLockHash,
1151 : 532 : &(proclock->tag),
1152 : : proclock_hashcode,
1153 : : HASH_REMOVE,
1154 : : NULL))
1155 [ # # ]: 0 : elog(PANIC, "proclock table corrupted");
1156 : : }
1157 : : else
1158 : : PROCLOCK_PRINT("LockAcquire: did not join wait queue", proclock);
1159 : 736 : lock->nRequested--;
1160 : 736 : lock->requested[lockmode]--;
1161 : : LOCK_PRINT("LockAcquire: did not join wait queue",
1162 : : lock, lockmode);
1163 : : Assert((lock->nRequested > 0) &&
1164 : : (lock->requested[lockmode] >= 0));
1165 : : Assert(lock->nGranted <= lock->nRequested);
1166 : 736 : LWLockRelease(partitionLock);
1167 [ + - ]: 736 : if (locallock->nLocks == 0)
1168 : 736 : RemoveLocalLock(locallock);
1169 : :
1170 [ + + ]: 736 : if (dontWait)
1171 : : {
1172 : : /*
1173 : : * Log lock holders and waiters as a detail log message if
1174 : : * logLockFailure = true and lock acquisition fails with dontWait
1175 : : * = true
1176 : : */
1177 [ - + ]: 735 : if (logLockFailure)
1178 : : {
1179 : : StringInfoData buf,
1180 : : lock_waiters_sbuf,
1181 : : lock_holders_sbuf;
1182 : : const char *modename;
1183 : 0 : int lockHoldersNum = 0;
1184 : :
1185 : 0 : initStringInfo(&buf);
1186 : 0 : initStringInfo(&lock_waiters_sbuf);
1187 : 0 : initStringInfo(&lock_holders_sbuf);
1188 : :
1189 : 0 : DescribeLockTag(&buf, &locallock->tag.lock);
1190 : 0 : modename = GetLockmodeName(locallock->tag.lock.locktag_lockmethodid,
1191 : : lockmode);
1192 : :
1193 : : /* Gather a list of all lock holders and waiters */
1194 : 0 : LWLockAcquire(partitionLock, LW_SHARED);
1195 : 0 : GetLockHoldersAndWaiters(locallock, &lock_holders_sbuf,
1196 : : &lock_waiters_sbuf, &lockHoldersNum);
1197 : 0 : LWLockRelease(partitionLock);
1198 : :
1199 [ # # ]: 0 : ereport(LOG,
1200 : : (errmsg("process %d could not obtain %s on %s",
1201 : : MyProcPid, modename, buf.data),
1202 : : errdetail_log_plural(
1203 : : "Process holding the lock: %s, Wait queue: %s.",
1204 : : "Processes holding the lock: %s, Wait queue: %s.",
1205 : : lockHoldersNum,
1206 : : lock_holders_sbuf.data,
1207 : : lock_waiters_sbuf.data)));
1208 : :
1209 : 0 : pfree(buf.data);
1210 : 0 : pfree(lock_holders_sbuf.data);
1211 : 0 : pfree(lock_waiters_sbuf.data);
1212 : : }
1213 [ + + ]: 735 : if (locallockp)
1214 : 225 : *locallockp = NULL;
1215 : 735 : return LOCKACQUIRE_NOT_AVAIL;
1216 : : }
1217 : : else
1218 : : {
1219 : 1 : DeadLockReport();
1220 : : /* DeadLockReport() will not return */
1221 : : }
1222 : : }
1223 : :
1224 : : /*
1225 : : * We are now in the lock queue, or the lock was already granted. If
1226 : : * queued, go to sleep.
1227 : : */
1228 [ + + ]: 2959762 : if (waitResult == PROC_WAIT_STATUS_WAITING)
1229 : : {
1230 : : Assert(!dontWait);
1231 : : PROCLOCK_PRINT("LockAcquire: sleeping on lock", proclock);
1232 : : LOCK_PRINT("LockAcquire: sleeping on lock", lock, lockmode);
1233 : 1472 : LWLockRelease(partitionLock);
1234 : :
1235 : 1472 : waitResult = WaitOnLock(locallock, owner);
1236 : :
1237 : : /*
1238 : : * NOTE: do not do any material change of state between here and
1239 : : * return. All required changes in locktable state must have been
1240 : : * done when the lock was granted to us --- see notes in WaitOnLock.
1241 : : */
1242 : :
1243 [ + + ]: 1431 : if (waitResult == PROC_WAIT_STATUS_ERROR)
1244 : : {
1245 : : /*
1246 : : * We failed as a result of a deadlock, see CheckDeadLock(). Quit
1247 : : * now.
1248 : : */
1249 : : Assert(!dontWait);
1250 : 5 : DeadLockReport();
1251 : : /* DeadLockReport() will not return */
1252 : : }
1253 : : }
1254 : : else
1255 : 2958290 : LWLockRelease(partitionLock);
1256 : : Assert(waitResult == PROC_WAIT_STATUS_OK);
1257 : :
1258 : : /* The lock was granted to us. Update the local lock entry accordingly */
1259 : : Assert((proclock->holdMask & LOCKBIT_ON(lockmode)) != 0);
1260 : 2959716 : GrantLockLocal(locallock, owner);
1261 : :
1262 : : /*
1263 : : * Lock state is fully up-to-date now; if we error out after this, no
1264 : : * special error cleanup is required.
1265 : : */
1266 : 2959716 : FinishStrongLockAcquire();
1267 : :
1268 : : /*
1269 : : * Emit a WAL record if acquisition of this lock needs to be replayed in a
1270 : : * standby server.
1271 : : */
1272 [ + + ]: 2959716 : if (log_lock)
1273 : : {
1274 : : /*
1275 : : * Decode the locktag back to the original values, to avoid sending
1276 : : * lots of empty bytes with every message. See lock.h to check how a
1277 : : * locktag is defined for LOCKTAG_RELATION
1278 : : */
1279 : 169213 : LogAccessExclusiveLock(locktag->locktag_field1,
1280 : 169213 : locktag->locktag_field2);
1281 : : }
1282 : :
1283 : 2959716 : return LOCKACQUIRE_OK;
1284 : : }
1285 : :
1286 : : /*
1287 : : * Find or create LOCK and PROCLOCK objects as needed for a new lock
1288 : : * request.
1289 : : *
1290 : : * Returns the PROCLOCK object, or NULL if we failed to create the objects
1291 : : * for lack of shared memory.
1292 : : *
1293 : : * The appropriate partition lock must be held at entry, and will be
1294 : : * held at exit.
1295 : : */
1296 : : static PROCLOCK *
1297 : 2962764 : SetupLockInTable(LockMethod lockMethodTable, PGPROC *proc,
1298 : : const LOCKTAG *locktag, uint32 hashcode, LOCKMODE lockmode)
1299 : : {
1300 : : LOCK *lock;
1301 : : PROCLOCK *proclock;
1302 : : PROCLOCKTAG proclocktag;
1303 : : uint32 proclock_hashcode;
1304 : : bool found;
1305 : :
1306 : : /*
1307 : : * Find or create a lock with this tag.
1308 : : */
1309 : 2962764 : lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
1310 : : locktag,
1311 : : hashcode,
1312 : : HASH_ENTER_NULL,
1313 : : &found);
1314 [ - + ]: 2962764 : if (!lock)
1315 : 0 : return NULL;
1316 : :
1317 : : /*
1318 : : * if it's a new lock object, initialize it
1319 : : */
1320 [ + + ]: 2962764 : if (!found)
1321 : : {
1322 : 2668338 : lock->grantMask = 0;
1323 : 2668338 : lock->waitMask = 0;
1324 : 2668338 : dlist_init(&lock->procLocks);
1325 : 2668338 : dclist_init(&lock->waitProcs);
1326 : 2668338 : lock->nRequested = 0;
1327 : 2668338 : lock->nGranted = 0;
1328 [ + - + - : 16010028 : MemSet(lock->requested, 0, sizeof(int) * MAX_LOCKMODES);
+ - + - +
+ ]
1329 [ - + - - : 2668338 : MemSet(lock->granted, 0, sizeof(int) * MAX_LOCKMODES);
- - - - -
- ]
1330 : : LOCK_PRINT("LockAcquire: new", lock, lockmode);
1331 : : }
1332 : : else
1333 : : {
1334 : : LOCK_PRINT("LockAcquire: found", lock, lockmode);
1335 : : Assert((lock->nRequested >= 0) && (lock->requested[lockmode] >= 0));
1336 : : Assert((lock->nGranted >= 0) && (lock->granted[lockmode] >= 0));
1337 : : Assert(lock->nGranted <= lock->nRequested);
1338 : : }
1339 : :
1340 : : /*
1341 : : * Create the hash key for the proclock table.
1342 : : */
1343 : 2962764 : proclocktag.myLock = lock;
1344 : 2962764 : proclocktag.myProc = proc;
1345 : :
1346 : 2962764 : proclock_hashcode = ProcLockHashCode(&proclocktag, hashcode);
1347 : :
1348 : : /*
1349 : : * Find or create a proclock entry with this tag
1350 : : */
1351 : 2962764 : proclock = (PROCLOCK *) hash_search_with_hash_value(LockMethodProcLockHash,
1352 : : &proclocktag,
1353 : : proclock_hashcode,
1354 : : HASH_ENTER_NULL,
1355 : : &found);
1356 [ - + ]: 2962764 : if (!proclock)
1357 : : {
1358 : : /* Oops, not enough shmem for the proclock */
1359 [ # # ]: 0 : if (lock->nRequested == 0)
1360 : : {
1361 : : /*
1362 : : * There are no other requestors of this lock, so garbage-collect
1363 : : * the lock object. We *must* do this to avoid a permanent leak
1364 : : * of shared memory, because there won't be anything to cause
1365 : : * anyone to release the lock object later.
1366 : : */
1367 : : Assert(dlist_is_empty(&(lock->procLocks)));
1368 [ # # ]: 0 : if (!hash_search_with_hash_value(LockMethodLockHash,
1369 : 0 : &(lock->tag),
1370 : : hashcode,
1371 : : HASH_REMOVE,
1372 : : NULL))
1373 [ # # ]: 0 : elog(PANIC, "lock table corrupted");
1374 : : }
1375 : 0 : return NULL;
1376 : : }
1377 : :
1378 : : /*
1379 : : * If new, initialize the new entry
1380 : : */
1381 [ + + ]: 2962764 : if (!found)
1382 : : {
1383 : 2693501 : uint32 partition = LockHashPartition(hashcode);
1384 : :
1385 : : /*
1386 : : * It might seem unsafe to access proclock->groupLeader without a
1387 : : * lock, but it's not really. Either we are initializing a proclock
1388 : : * on our own behalf, in which case our group leader isn't changing
1389 : : * because the group leader for a process can only ever be changed by
1390 : : * the process itself; or else we are transferring a fast-path lock to
1391 : : * the main lock table, in which case that process can't change its
1392 : : * lock group leader without first releasing all of its locks (and in
1393 : : * particular the one we are currently transferring).
1394 : : */
1395 : 5387002 : proclock->groupLeader = proc->lockGroupLeader != NULL ?
1396 [ + + ]: 2693501 : proc->lockGroupLeader : proc;
1397 : 2693501 : proclock->holdMask = 0;
1398 : 2693501 : proclock->releaseMask = 0;
1399 : : /* Add proclock to appropriate lists */
1400 : 2693501 : dlist_push_tail(&lock->procLocks, &proclock->lockLink);
1401 : 2693501 : dlist_push_tail(&proc->myProcLocks[partition], &proclock->procLink);
1402 : : PROCLOCK_PRINT("LockAcquire: new", proclock);
1403 : : }
1404 : : else
1405 : : {
1406 : : PROCLOCK_PRINT("LockAcquire: found", proclock);
1407 : : Assert((proclock->holdMask & ~lock->grantMask) == 0);
1408 : :
1409 : : #ifdef CHECK_DEADLOCK_RISK
1410 : :
1411 : : /*
1412 : : * Issue warning if we already hold a lower-level lock on this object
1413 : : * and do not hold a lock of the requested level or higher. This
1414 : : * indicates a deadlock-prone coding practice (eg, we'd have a
1415 : : * deadlock if another backend were following the same code path at
1416 : : * about the same time).
1417 : : *
1418 : : * This is not enabled by default, because it may generate log entries
1419 : : * about user-level coding practices that are in fact safe in context.
1420 : : * It can be enabled to help find system-level problems.
1421 : : *
1422 : : * XXX Doing numeric comparison on the lockmodes is a hack; it'd be
1423 : : * better to use a table. For now, though, this works.
1424 : : */
1425 : : {
1426 : : int i;
1427 : :
1428 : : for (i = lockMethodTable->numLockModes; i > 0; i--)
1429 : : {
1430 : : if (proclock->holdMask & LOCKBIT_ON(i))
1431 : : {
1432 : : if (i >= (int) lockmode)
1433 : : break; /* safe: we have a lock >= req level */
1434 : : elog(LOG, "deadlock risk: raising lock level"
1435 : : " from %s to %s on object %u/%u/%u",
1436 : : lockMethodTable->lockModeNames[i],
1437 : : lockMethodTable->lockModeNames[lockmode],
1438 : : lock->tag.locktag_field1, lock->tag.locktag_field2,
1439 : : lock->tag.locktag_field3);
1440 : : break;
1441 : : }
1442 : : }
1443 : : }
1444 : : #endif /* CHECK_DEADLOCK_RISK */
1445 : : }
1446 : :
1447 : : /*
1448 : : * lock->nRequested and lock->requested[] count the total number of
1449 : : * requests, whether granted or waiting, so increment those immediately.
1450 : : * The other counts don't increment till we get the lock.
1451 : : */
1452 : 2962764 : lock->nRequested++;
1453 : 2962764 : lock->requested[lockmode]++;
1454 : : Assert((lock->nRequested > 0) && (lock->requested[lockmode] > 0));
1455 : :
1456 : : /*
1457 : : * We shouldn't already hold the desired lock; else locallock table is
1458 : : * broken.
1459 : : */
1460 [ - + ]: 2962764 : if (proclock->holdMask & LOCKBIT_ON(lockmode))
1461 [ # # ]: 0 : elog(ERROR, "lock %s on object %u/%u/%u is already held",
1462 : : lockMethodTable->lockModeNames[lockmode],
1463 : : lock->tag.locktag_field1, lock->tag.locktag_field2,
1464 : : lock->tag.locktag_field3);
1465 : :
1466 : 2962764 : return proclock;
1467 : : }
1468 : :
1469 : : /*
1470 : : * Check and set/reset the flag that we hold the relation extension lock.
1471 : : *
1472 : : * It is callers responsibility that this function is called after
1473 : : * acquiring/releasing the relation extension lock.
1474 : : *
1475 : : * Pass acquired as true if lock is acquired, false otherwise.
1476 : : */
1477 : : static inline void
1478 : 49516259 : CheckAndSetLockHeld(LOCALLOCK *locallock, bool acquired)
1479 : : {
1480 : : #ifdef USE_ASSERT_CHECKING
1481 : : if (LOCALLOCK_LOCKTAG(*locallock) == LOCKTAG_RELATION_EXTEND)
1482 : : IsRelationExtensionLockHeld = acquired;
1483 : : #endif
1484 : 49516259 : }
1485 : :
1486 : : /*
1487 : : * Subroutine to free a locallock entry
1488 : : */
1489 : : static void
1490 : 24410684 : RemoveLocalLock(LOCALLOCK *locallock)
1491 : : {
1492 : : int i;
1493 : :
1494 [ + + ]: 24519451 : for (i = locallock->numLockOwners - 1; i >= 0; i--)
1495 : : {
1496 [ + + ]: 108767 : if (locallock->lockOwners[i].owner != NULL)
1497 : 108706 : ResourceOwnerForgetLock(locallock->lockOwners[i].owner, locallock);
1498 : : }
1499 : 24410684 : locallock->numLockOwners = 0;
1500 [ + - ]: 24410684 : if (locallock->lockOwners != NULL)
1501 : 24410684 : pfree(locallock->lockOwners);
1502 : 24410684 : locallock->lockOwners = NULL;
1503 : :
1504 [ + + ]: 24410684 : if (locallock->holdsStrongLockCount)
1505 : : {
1506 : : uint32 fasthashcode;
1507 : :
1508 : 243383 : fasthashcode = FastPathStrongLockHashPartition(locallock->hashcode);
1509 : :
1510 : : Assert(pg_atomic_read_u32(&FastPathStrongRelationLocks[fasthashcode]) > 0);
1511 : 243383 : pg_atomic_fetch_sub_u32(&FastPathStrongRelationLocks[fasthashcode], 1);
1512 : 243383 : locallock->holdsStrongLockCount = false;
1513 : : }
1514 : :
1515 [ - + ]: 24410684 : if (!hash_search(LockMethodLocalHash,
1516 : 24410684 : &(locallock->tag),
1517 : : HASH_REMOVE, NULL))
1518 [ # # ]: 0 : elog(WARNING, "locallock table corrupted");
1519 : :
1520 : : /*
1521 : : * Indicate that the lock is released for certain types of locks
1522 : : */
1523 : 24410684 : CheckAndSetLockHeld(locallock, false);
1524 : 24410684 : }
1525 : :
1526 : : /*
1527 : : * LockCheckConflicts -- test whether requested lock conflicts
1528 : : * with those already granted
1529 : : *
1530 : : * Returns true if conflict, false if no conflict.
1531 : : *
1532 : : * NOTES:
1533 : : * Here's what makes this complicated: one process's locks don't
1534 : : * conflict with one another, no matter what purpose they are held for
1535 : : * (eg, session and transaction locks do not conflict). Nor do the locks
1536 : : * of one process in a lock group conflict with those of another process in
1537 : : * the same group. So, we must subtract off these locks when determining
1538 : : * whether the requested new lock conflicts with those already held.
1539 : : */
1540 : : bool
1541 : 2962019 : LockCheckConflicts(LockMethod lockMethodTable,
1542 : : LOCKMODE lockmode,
1543 : : LOCK *lock,
1544 : : PROCLOCK *proclock)
1545 : : {
1546 : 2962019 : int numLockModes = lockMethodTable->numLockModes;
1547 : : LOCKMASK myLocks;
1548 : 2962019 : int conflictMask = lockMethodTable->conflictTab[lockmode];
1549 : : int conflictsRemaining[MAX_LOCKMODES];
1550 : 2962019 : int totalConflictsRemaining = 0;
1551 : : dlist_iter proclock_iter;
1552 : : int i;
1553 : :
1554 : : /*
1555 : : * first check for global conflicts: If no locks conflict with my request,
1556 : : * then I get the lock.
1557 : : *
1558 : : * Checking for conflict: lock->grantMask represents the types of
1559 : : * currently held locks. conflictTable[lockmode] has a bit set for each
1560 : : * type of lock that conflicts with request. Bitwise compare tells if
1561 : : * there is a conflict.
1562 : : */
1563 [ + + ]: 2962019 : if (!(conflictMask & lock->grantMask))
1564 : : {
1565 : : PROCLOCK_PRINT("LockCheckConflicts: no conflict", proclock);
1566 : 2840021 : return false;
1567 : : }
1568 : :
1569 : : /*
1570 : : * Rats. Something conflicts. But it could still be my own lock, or a
1571 : : * lock held by another member of my locking group. First, figure out how
1572 : : * many conflicts remain after subtracting out any locks I hold myself.
1573 : : */
1574 : 121998 : myLocks = proclock->holdMask;
1575 [ + + ]: 1097982 : for (i = 1; i <= numLockModes; i++)
1576 : : {
1577 [ + + ]: 975984 : if ((conflictMask & LOCKBIT_ON(i)) == 0)
1578 : : {
1579 : 513824 : conflictsRemaining[i] = 0;
1580 : 513824 : continue;
1581 : : }
1582 : 462160 : conflictsRemaining[i] = lock->granted[i];
1583 [ + + ]: 462160 : if (myLocks & LOCKBIT_ON(i))
1584 : 131818 : --conflictsRemaining[i];
1585 : 462160 : totalConflictsRemaining += conflictsRemaining[i];
1586 : : }
1587 : :
1588 : : /* If no conflicts remain, we get the lock. */
1589 [ + + ]: 121998 : if (totalConflictsRemaining == 0)
1590 : : {
1591 : : PROCLOCK_PRINT("LockCheckConflicts: resolved (simple)", proclock);
1592 : 118941 : return false;
1593 : : }
1594 : :
1595 : : /* If no group locking, it's definitely a conflict. */
1596 [ + + + + ]: 3057 : if (proclock->groupLeader == MyProc && MyProc->lockGroupLeader == NULL)
1597 : : {
1598 : : Assert(proclock->tag.myProc == MyProc);
1599 : : PROCLOCK_PRINT("LockCheckConflicts: conflicting (simple)",
1600 : : proclock);
1601 : 2063 : return true;
1602 : : }
1603 : :
1604 : : /*
1605 : : * The relation extension lock conflict even between the group members.
1606 : : */
1607 [ + + ]: 994 : if (LOCK_LOCKTAG(*lock) == LOCKTAG_RELATION_EXTEND)
1608 : : {
1609 : : PROCLOCK_PRINT("LockCheckConflicts: conflicting (group)",
1610 : : proclock);
1611 : 4 : return true;
1612 : : }
1613 : :
1614 : : /*
1615 : : * Locks held in conflicting modes by members of our own lock group are
1616 : : * not real conflicts; we can subtract those out and see if we still have
1617 : : * a conflict. This is O(N) in the number of processes holding or
1618 : : * awaiting locks on this object. We could improve that by making the
1619 : : * shared memory state more complex (and larger) but it doesn't seem worth
1620 : : * it.
1621 : : */
1622 [ + - + + ]: 1837 : dlist_foreach(proclock_iter, &lock->procLocks)
1623 : : {
1624 : 1640 : PROCLOCK *otherproclock =
1625 : 1640 : dlist_container(PROCLOCK, lockLink, proclock_iter.cur);
1626 : :
1627 [ + + ]: 1640 : if (proclock != otherproclock &&
1628 [ + + ]: 1443 : proclock->groupLeader == otherproclock->groupLeader &&
1629 [ + + ]: 807 : (otherproclock->holdMask & conflictMask) != 0)
1630 : : {
1631 : 805 : int intersectMask = otherproclock->holdMask & conflictMask;
1632 : :
1633 [ + + ]: 7245 : for (i = 1; i <= numLockModes; i++)
1634 : : {
1635 [ + + ]: 6440 : if ((intersectMask & LOCKBIT_ON(i)) != 0)
1636 : : {
1637 [ - + ]: 818 : if (conflictsRemaining[i] <= 0)
1638 [ # # ]: 0 : elog(PANIC, "proclocks held do not match lock");
1639 : 818 : conflictsRemaining[i]--;
1640 : 818 : totalConflictsRemaining--;
1641 : : }
1642 : : }
1643 : :
1644 [ + + ]: 805 : if (totalConflictsRemaining == 0)
1645 : : {
1646 : : PROCLOCK_PRINT("LockCheckConflicts: resolved (group)",
1647 : : proclock);
1648 : 793 : return false;
1649 : : }
1650 : : }
1651 : : }
1652 : :
1653 : : /* Nope, it's a real conflict. */
1654 : : PROCLOCK_PRINT("LockCheckConflicts: conflicting (group)", proclock);
1655 : 197 : return true;
1656 : : }
1657 : :
1658 : : /*
1659 : : * GrantLock -- update the lock and proclock data structures to show
1660 : : * the lock request has been granted.
1661 : : *
1662 : : * NOTE: if proc was blocked, it also needs to be removed from the wait list
1663 : : * and have its waitLock/waitProcLock fields cleared. That's not done here.
1664 : : *
1665 : : * NOTE: the lock grant also has to be recorded in the associated LOCALLOCK
1666 : : * table entry; but since we may be awaking some other process, we can't do
1667 : : * that here; it's done by GrantLockLocal, instead.
1668 : : */
1669 : : void
1670 : 2962117 : GrantLock(LOCK *lock, PROCLOCK *proclock, LOCKMODE lockmode)
1671 : : {
1672 : 2962117 : lock->nGranted++;
1673 : 2962117 : lock->granted[lockmode]++;
1674 : 2962117 : lock->grantMask |= LOCKBIT_ON(lockmode);
1675 [ + + ]: 2962117 : if (lock->granted[lockmode] == lock->requested[lockmode])
1676 : 2961790 : lock->waitMask &= LOCKBIT_OFF(lockmode);
1677 : 2962117 : proclock->holdMask |= LOCKBIT_ON(lockmode);
1678 : : LOCK_PRINT("GrantLock", lock, lockmode);
1679 : : Assert((lock->nGranted > 0) && (lock->granted[lockmode] > 0));
1680 : : Assert(lock->nGranted <= lock->nRequested);
1681 : 2962117 : }
1682 : :
1683 : : /*
1684 : : * UnGrantLock -- opposite of GrantLock.
1685 : : *
1686 : : * Updates the lock and proclock data structures to show that the lock
1687 : : * is no longer held nor requested by the current holder.
1688 : : *
1689 : : * Returns true if there were any waiters waiting on the lock that
1690 : : * should now be woken up with ProcLockWakeup.
1691 : : */
1692 : : static bool
1693 : 2962027 : UnGrantLock(LOCK *lock, LOCKMODE lockmode,
1694 : : PROCLOCK *proclock, LockMethod lockMethodTable)
1695 : : {
1696 : 2962027 : bool wakeupNeeded = false;
1697 : :
1698 : : Assert((lock->nRequested > 0) && (lock->requested[lockmode] > 0));
1699 : : Assert((lock->nGranted > 0) && (lock->granted[lockmode] > 0));
1700 : : Assert(lock->nGranted <= lock->nRequested);
1701 : :
1702 : : /*
1703 : : * fix the general lock stats
1704 : : */
1705 : 2962027 : lock->nRequested--;
1706 : 2962027 : lock->requested[lockmode]--;
1707 : 2962027 : lock->nGranted--;
1708 : 2962027 : lock->granted[lockmode]--;
1709 : :
1710 [ + + ]: 2962027 : if (lock->granted[lockmode] == 0)
1711 : : {
1712 : : /* change the conflict mask. No more of this lock type. */
1713 : 2943260 : lock->grantMask &= LOCKBIT_OFF(lockmode);
1714 : : }
1715 : :
1716 : : LOCK_PRINT("UnGrantLock: updated", lock, lockmode);
1717 : :
1718 : : /*
1719 : : * We need only run ProcLockWakeup if the released lock conflicts with at
1720 : : * least one of the lock types requested by waiter(s). Otherwise whatever
1721 : : * conflict made them wait must still exist. NOTE: before MVCC, we could
1722 : : * skip wakeup if lock->granted[lockmode] was still positive. But that's
1723 : : * not true anymore, because the remaining granted locks might belong to
1724 : : * some waiter, who could now be awakened because he doesn't conflict with
1725 : : * his own locks.
1726 : : */
1727 [ + + ]: 2962027 : if (lockMethodTable->conflictTab[lockmode] & lock->waitMask)
1728 : 1402 : wakeupNeeded = true;
1729 : :
1730 : : /*
1731 : : * Now fix the per-proclock state.
1732 : : */
1733 : 2962027 : proclock->holdMask &= LOCKBIT_OFF(lockmode);
1734 : : PROCLOCK_PRINT("UnGrantLock: updated", proclock);
1735 : :
1736 : 2962027 : return wakeupNeeded;
1737 : : }
1738 : :
1739 : : /*
1740 : : * CleanUpLock -- clean up after releasing a lock. We garbage-collect the
1741 : : * proclock and lock objects if possible, and call ProcLockWakeup if there
1742 : : * are remaining requests and the caller says it's OK. (Normally, this
1743 : : * should be called after UnGrantLock, and wakeupNeeded is the result from
1744 : : * UnGrantLock.)
1745 : : *
1746 : : * The appropriate partition lock must be held at entry, and will be
1747 : : * held at exit.
1748 : : */
1749 : : static void
1750 : 2914433 : CleanUpLock(LOCK *lock, PROCLOCK *proclock,
1751 : : LockMethod lockMethodTable, uint32 hashcode,
1752 : : bool wakeupNeeded)
1753 : : {
1754 : : /*
1755 : : * If this was my last hold on this lock, delete my entry in the proclock
1756 : : * table.
1757 : : */
1758 [ + + ]: 2914433 : if (proclock->holdMask == 0)
1759 : : {
1760 : : uint32 proclock_hashcode;
1761 : :
1762 : : PROCLOCK_PRINT("CleanUpLock: deleting", proclock);
1763 : 2693012 : dlist_delete(&proclock->lockLink);
1764 : 2693012 : dlist_delete(&proclock->procLink);
1765 : 2693012 : proclock_hashcode = ProcLockHashCode(&proclock->tag, hashcode);
1766 [ - + ]: 2693012 : if (!hash_search_with_hash_value(LockMethodProcLockHash,
1767 : 2693012 : &(proclock->tag),
1768 : : proclock_hashcode,
1769 : : HASH_REMOVE,
1770 : : NULL))
1771 [ # # ]: 0 : elog(PANIC, "proclock table corrupted");
1772 : : }
1773 : :
1774 [ + + ]: 2914433 : if (lock->nRequested == 0)
1775 : : {
1776 : : /*
1777 : : * The caller just released the last lock, so garbage-collect the lock
1778 : : * object.
1779 : : */
1780 : : LOCK_PRINT("CleanUpLock: deleting", lock, 0);
1781 : : Assert(dlist_is_empty(&lock->procLocks));
1782 [ - + ]: 2668379 : if (!hash_search_with_hash_value(LockMethodLockHash,
1783 : 2668379 : &(lock->tag),
1784 : : hashcode,
1785 : : HASH_REMOVE,
1786 : : NULL))
1787 [ # # ]: 0 : elog(PANIC, "lock table corrupted");
1788 : : }
1789 [ + + ]: 246054 : else if (wakeupNeeded)
1790 : : {
1791 : : /* There are waiters on this lock, so wake them up. */
1792 : 1445 : ProcLockWakeup(lockMethodTable, lock);
1793 : : }
1794 : 2914433 : }
1795 : :
1796 : : /*
1797 : : * GrantLockLocal -- update the locallock data structures to show
1798 : : * the lock request has been granted.
1799 : : *
1800 : : * We expect that LockAcquire made sure there is room to add a new
1801 : : * ResourceOwner entry.
1802 : : */
1803 : : static void
1804 : 27138039 : GrantLockLocal(LOCALLOCK *locallock, ResourceOwner owner)
1805 : : {
1806 : 27138039 : LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
1807 : : int i;
1808 : :
1809 : : Assert(locallock->numLockOwners < locallock->maxLockOwners);
1810 : : /* Count the total */
1811 : 27138039 : locallock->nLocks++;
1812 : : /* Count the per-owner lock */
1813 [ + + ]: 28062140 : for (i = 0; i < locallock->numLockOwners; i++)
1814 : : {
1815 [ + + ]: 2955865 : if (lockOwners[i].owner == owner)
1816 : : {
1817 : 2031764 : lockOwners[i].nLocks++;
1818 : 2031764 : return;
1819 : : }
1820 : : }
1821 : 25106275 : lockOwners[i].owner = owner;
1822 : 25106275 : lockOwners[i].nLocks = 1;
1823 : 25106275 : locallock->numLockOwners++;
1824 [ + + ]: 25106275 : if (owner != NULL)
1825 : 24949797 : ResourceOwnerRememberLock(owner, locallock);
1826 : :
1827 : : /* Indicate that the lock is acquired for certain types of locks. */
1828 : 25106275 : CheckAndSetLockHeld(locallock, true);
1829 : : }
1830 : :
1831 : : /*
1832 : : * BeginStrongLockAcquire - inhibit use of fastpath for a given LOCALLOCK,
1833 : : * and arrange for error cleanup if it fails
1834 : : */
1835 : : static void
1836 : 243714 : BeginStrongLockAcquire(LOCALLOCK *locallock, uint32 fasthashcode)
1837 : : {
1838 : : Assert(StrongLockInProgress == NULL);
1839 : : Assert(locallock->holdsStrongLockCount == false);
1840 : :
1841 : 243714 : pg_atomic_fetch_add_u32(&FastPathStrongRelationLocks[fasthashcode], 1);
1842 : 243714 : locallock->holdsStrongLockCount = true;
1843 : 243714 : StrongLockInProgress = locallock;
1844 : 243714 : }
1845 : :
1846 : : /*
1847 : : * FinishStrongLockAcquire - cancel pending cleanup for a strong lock
1848 : : * acquisition once it's no longer needed
1849 : : */
1850 : : static void
1851 : 2959753 : FinishStrongLockAcquire(void)
1852 : : {
1853 : 2959753 : StrongLockInProgress = NULL;
1854 : 2959753 : }
1855 : :
1856 : : /*
1857 : : * AbortStrongLockAcquire - undo strong lock state changes performed by
1858 : : * BeginStrongLockAcquire.
1859 : : */
1860 : : void
1861 : 704990 : AbortStrongLockAcquire(void)
1862 : : {
1863 : : uint32 fasthashcode;
1864 : 704990 : LOCALLOCK *locallock = StrongLockInProgress;
1865 : :
1866 [ + + ]: 704990 : if (locallock == NULL)
1867 : 704777 : return;
1868 : :
1869 : 213 : fasthashcode = FastPathStrongLockHashPartition(locallock->hashcode);
1870 : : Assert(locallock->holdsStrongLockCount == true);
1871 : : Assert(pg_atomic_read_u32(&FastPathStrongRelationLocks[fasthashcode]) > 0);
1872 : 213 : pg_atomic_fetch_sub_u32(&FastPathStrongRelationLocks[fasthashcode], 1);
1873 : 213 : locallock->holdsStrongLockCount = false;
1874 : 213 : StrongLockInProgress = NULL;
1875 : : }
1876 : :
1877 : : /*
1878 : : * GrantAwaitedLock -- call GrantLockLocal for the lock we are doing
1879 : : * WaitOnLock on.
1880 : : *
1881 : : * proc.c needs this for the case where we are booted off the lock by
1882 : : * timeout, but discover that someone granted us the lock anyway.
1883 : : *
1884 : : * We could just export GrantLockLocal, but that would require including
1885 : : * resowner.h in lock.h, which creates circularity.
1886 : : */
1887 : : void
1888 : 1 : GrantAwaitedLock(void)
1889 : : {
1890 : 1 : GrantLockLocal(awaitedLock, awaitedOwner);
1891 : 1 : }
1892 : :
1893 : : /*
1894 : : * GetAwaitedLock -- Return the lock we're currently doing WaitOnLock on.
1895 : : */
1896 : : LOCALLOCK *
1897 : 704261 : GetAwaitedLock(void)
1898 : : {
1899 : 704261 : return awaitedLock;
1900 : : }
1901 : :
1902 : : /*
1903 : : * ResetAwaitedLock -- Forget that we are waiting on a lock.
1904 : : */
1905 : : void
1906 : 40 : ResetAwaitedLock(void)
1907 : : {
1908 : 40 : awaitedLock = NULL;
1909 : 40 : }
1910 : :
1911 : : /*
1912 : : * MarkLockClear -- mark an acquired lock as "clear"
1913 : : *
1914 : : * This means that we know we have absorbed all sinval messages that other
1915 : : * sessions generated before we acquired this lock, and so we can confidently
1916 : : * assume we know about any catalog changes protected by this lock.
1917 : : */
1918 : : void
1919 : 23432168 : MarkLockClear(LOCALLOCK *locallock)
1920 : : {
1921 : : Assert(locallock->nLocks > 0);
1922 : 23432168 : locallock->lockCleared = true;
1923 : 23432168 : }
1924 : :
1925 : : /*
1926 : : * WaitOnLock -- wait to acquire a lock
1927 : : *
1928 : : * This is a wrapper around ProcSleep, with extra tracing and bookkeeping.
1929 : : */
1930 : : static ProcWaitStatus
1931 : 1472 : WaitOnLock(LOCALLOCK *locallock, ResourceOwner owner)
1932 : : {
1933 : : ProcWaitStatus result;
1934 : : ErrorContextCallback waiterrcontext;
1935 : :
1936 : : TRACE_POSTGRESQL_LOCK_WAIT_START(locallock->tag.lock.locktag_field1,
1937 : : locallock->tag.lock.locktag_field2,
1938 : : locallock->tag.lock.locktag_field3,
1939 : : locallock->tag.lock.locktag_field4,
1940 : : locallock->tag.lock.locktag_type,
1941 : : locallock->tag.mode);
1942 : :
1943 : : /* Setup error traceback support for ereport() */
1944 : 1472 : waiterrcontext.callback = waitonlock_error_callback;
1945 : 1472 : waiterrcontext.arg = locallock;
1946 : 1472 : waiterrcontext.previous = error_context_stack;
1947 : 1472 : error_context_stack = &waiterrcontext;
1948 : :
1949 : : /* adjust the process title to indicate that it's waiting */
1950 : 1472 : set_ps_display_suffix("waiting");
1951 : :
1952 : : /*
1953 : : * Record the fact that we are waiting for a lock, so that
1954 : : * LockErrorCleanup will clean up if cancel/die happens.
1955 : : */
1956 : 1472 : awaitedLock = locallock;
1957 : 1472 : awaitedOwner = owner;
1958 : :
1959 : : /*
1960 : : * NOTE: Think not to put any shared-state cleanup after the call to
1961 : : * ProcSleep, in either the normal or failure path. The lock state must
1962 : : * be fully set by the lock grantor, or by CheckDeadLock if we give up
1963 : : * waiting for the lock. This is necessary because of the possibility
1964 : : * that a cancel/die interrupt will interrupt ProcSleep after someone else
1965 : : * grants us the lock, but before we've noticed it. Hence, after granting,
1966 : : * the locktable state must fully reflect the fact that we own the lock;
1967 : : * we can't do additional work on return.
1968 : : *
1969 : : * We can and do use a PG_TRY block to try to clean up after failure, but
1970 : : * this still has a major limitation: elog(FATAL) can occur while waiting
1971 : : * (eg, a "die" interrupt), and then control won't come back here. So all
1972 : : * cleanup of essential state should happen in LockErrorCleanup, not here.
1973 : : * We can use PG_TRY to clear the "waiting" status flags, since doing that
1974 : : * is unimportant if the process exits.
1975 : : */
1976 [ + + ]: 1472 : PG_TRY();
1977 : : {
1978 : 1472 : result = ProcSleep(locallock);
1979 : : }
1980 : 39 : PG_CATCH();
1981 : : {
1982 : : /* In this path, awaitedLock remains set until LockErrorCleanup */
1983 : :
1984 : : /* reset ps display to remove the suffix */
1985 : 39 : set_ps_display_remove_suffix();
1986 : :
1987 : : /* and propagate the error */
1988 : 39 : PG_RE_THROW();
1989 : : }
1990 [ - + ]: 1431 : PG_END_TRY();
1991 : :
1992 : : /*
1993 : : * We no longer want LockErrorCleanup to do anything.
1994 : : */
1995 : 1431 : awaitedLock = NULL;
1996 : :
1997 : : /* reset ps display to remove the suffix */
1998 : 1431 : set_ps_display_remove_suffix();
1999 : :
2000 : 1431 : error_context_stack = waiterrcontext.previous;
2001 : :
2002 : : TRACE_POSTGRESQL_LOCK_WAIT_DONE(locallock->tag.lock.locktag_field1,
2003 : : locallock->tag.lock.locktag_field2,
2004 : : locallock->tag.lock.locktag_field3,
2005 : : locallock->tag.lock.locktag_field4,
2006 : : locallock->tag.lock.locktag_type,
2007 : : locallock->tag.mode);
2008 : :
2009 : 1431 : return result;
2010 : : }
2011 : :
2012 : : /*
2013 : : * error context callback for failures in WaitOnLock
2014 : : *
2015 : : * We report which lock was being waited on, in the same style used in
2016 : : * deadlock reports. This helps with lock timeout errors in particular.
2017 : : */
2018 : : static void
2019 : 232 : waitonlock_error_callback(void *arg)
2020 : : {
2021 : 232 : LOCALLOCK *locallock = (LOCALLOCK *) arg;
2022 : 232 : const LOCKTAG *tag = &locallock->tag.lock;
2023 : 232 : LOCKMODE mode = locallock->tag.mode;
2024 : : StringInfoData locktagbuf;
2025 : :
2026 : 232 : initStringInfo(&locktagbuf);
2027 : 232 : DescribeLockTag(&locktagbuf, tag);
2028 : :
2029 : 464 : errcontext("waiting for %s on %s",
2030 : 232 : GetLockmodeName(tag->locktag_lockmethodid, mode),
2031 : : locktagbuf.data);
2032 : 232 : }
2033 : :
2034 : : /*
2035 : : * Remove a proc from the wait-queue it is on (caller must know it is on one).
2036 : : * This is only used when the proc has failed to get the lock, so we set its
2037 : : * waitStatus to PROC_WAIT_STATUS_ERROR.
2038 : : *
2039 : : * Appropriate partition lock must be held by caller. Also, caller is
2040 : : * responsible for signaling the proc if needed.
2041 : : *
2042 : : * NB: this does not clean up any locallock object that may exist for the lock.
2043 : : */
2044 : : void
2045 : 44 : RemoveFromWaitQueue(PGPROC *proc, uint32 hashcode)
2046 : : {
2047 : 44 : LOCK *waitLock = proc->waitLock;
2048 : 44 : PROCLOCK *proclock = proc->waitProcLock;
2049 : 44 : LOCKMODE lockmode = proc->waitLockMode;
2050 : 44 : LOCKMETHODID lockmethodid = LOCK_LOCKMETHOD(*waitLock);
2051 : :
2052 : : /* Make sure proc is waiting */
2053 : : Assert(proc->waitStatus == PROC_WAIT_STATUS_WAITING);
2054 : : Assert(!dlist_node_is_detached(&proc->waitLink));
2055 : : Assert(waitLock);
2056 : : Assert(!dclist_is_empty(&waitLock->waitProcs));
2057 : : Assert(0 < lockmethodid && lockmethodid < lengthof(LockMethods));
2058 : :
2059 : : /* Remove proc from lock's wait queue */
2060 : 44 : dclist_delete_from_thoroughly(&waitLock->waitProcs, &proc->waitLink);
2061 : :
2062 : : /* Undo increments of request counts by waiting process */
2063 : : Assert(waitLock->nRequested > 0);
2064 : : Assert(waitLock->nRequested > proc->waitLock->nGranted);
2065 : 44 : waitLock->nRequested--;
2066 : : Assert(waitLock->requested[lockmode] > 0);
2067 : 44 : waitLock->requested[lockmode]--;
2068 : : /* don't forget to clear waitMask bit if appropriate */
2069 [ + - ]: 44 : if (waitLock->granted[lockmode] == waitLock->requested[lockmode])
2070 : 44 : waitLock->waitMask &= LOCKBIT_OFF(lockmode);
2071 : :
2072 : : /* Clean up the proc's own state, and pass it the ok/fail signal */
2073 : 44 : proc->waitLock = NULL;
2074 : 44 : proc->waitProcLock = NULL;
2075 : 44 : proc->waitStatus = PROC_WAIT_STATUS_ERROR;
2076 : :
2077 : : /*
2078 : : * Delete the proclock immediately if it represents no already-held locks.
2079 : : * (This must happen now because if the owner of the lock decides to
2080 : : * release it, and the requested/granted counts then go to zero,
2081 : : * LockRelease expects there to be no remaining proclocks.) Then see if
2082 : : * any other waiters for the lock can be woken up now.
2083 : : */
2084 : 44 : CleanUpLock(waitLock, proclock,
2085 : 44 : LockMethods[lockmethodid], hashcode,
2086 : : true);
2087 : 44 : }
2088 : :
2089 : : /*
2090 : : * LockRelease -- look up 'locktag' and release one 'lockmode' lock on it.
2091 : : * Release a session lock if 'sessionLock' is true, else release a
2092 : : * regular transaction lock.
2093 : : *
2094 : : * Side Effects: find any waiting processes that are now wakable,
2095 : : * grant them their requested locks and awaken them.
2096 : : * (We have to grant the lock here to avoid a race between
2097 : : * the waking process and any new process to
2098 : : * come along and request the lock.)
2099 : : */
2100 : : bool
2101 : 23966408 : LockRelease(const LOCKTAG *locktag, LOCKMODE lockmode, bool sessionLock)
2102 : : {
2103 : 23966408 : LOCKMETHODID lockmethodid = locktag->locktag_lockmethodid;
2104 : : LockMethod lockMethodTable;
2105 : : LOCALLOCKTAG localtag;
2106 : : LOCALLOCK *locallock;
2107 : : LOCK *lock;
2108 : : PROCLOCK *proclock;
2109 : : LWLock *partitionLock;
2110 : : bool wakeupNeeded;
2111 : :
2112 [ + - - + ]: 23966408 : if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
2113 [ # # ]: 0 : elog(ERROR, "unrecognized lock method: %d", lockmethodid);
2114 : 23966408 : lockMethodTable = LockMethods[lockmethodid];
2115 [ + - - + ]: 23966408 : if (lockmode <= 0 || lockmode > lockMethodTable->numLockModes)
2116 [ # # ]: 0 : elog(ERROR, "unrecognized lock mode: %d", lockmode);
2117 : :
2118 : : #ifdef LOCK_DEBUG
2119 : : if (LOCK_DEBUG_ENABLED(locktag))
2120 : : elog(LOG, "LockRelease: lock [%u,%u] %s",
2121 : : locktag->locktag_field1, locktag->locktag_field2,
2122 : : lockMethodTable->lockModeNames[lockmode]);
2123 : : #endif
2124 : :
2125 : : /*
2126 : : * Find the LOCALLOCK entry for this lock and lockmode
2127 : : */
2128 [ + - - + : 23966408 : MemSet(&localtag, 0, sizeof(localtag)); /* must clear padding */
- - - - -
- ]
2129 : 23966408 : localtag.lock = *locktag;
2130 : 23966408 : localtag.mode = lockmode;
2131 : :
2132 : 23966408 : locallock = (LOCALLOCK *) hash_search(LockMethodLocalHash,
2133 : : &localtag,
2134 : : HASH_FIND, NULL);
2135 : :
2136 : : /*
2137 : : * let the caller print its own error message, too. Do not ereport(ERROR).
2138 : : */
2139 [ + + - + ]: 23966408 : if (!locallock || locallock->nLocks <= 0)
2140 : : {
2141 [ + - ]: 17 : elog(WARNING, "you don't own a lock of type %s",
2142 : : lockMethodTable->lockModeNames[lockmode]);
2143 : 17 : return false;
2144 : : }
2145 : :
2146 : : /*
2147 : : * Decrease the count for the resource owner.
2148 : : */
2149 : : {
2150 : 23966391 : LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
2151 : : ResourceOwner owner;
2152 : : int i;
2153 : :
2154 : : /* Identify owner for lock */
2155 [ + + ]: 23966391 : if (sessionLock)
2156 : 156458 : owner = NULL;
2157 : : else
2158 : 23809933 : owner = CurrentResourceOwner;
2159 : :
2160 [ + + ]: 23967633 : for (i = locallock->numLockOwners - 1; i >= 0; i--)
2161 : : {
2162 [ + + ]: 23967617 : if (lockOwners[i].owner == owner)
2163 : : {
2164 : : Assert(lockOwners[i].nLocks > 0);
2165 [ + + ]: 23966375 : if (--lockOwners[i].nLocks == 0)
2166 : : {
2167 [ + + ]: 23198132 : if (owner != NULL)
2168 : 23041715 : ResourceOwnerForgetLock(owner, locallock);
2169 : : /* compact out unused slot */
2170 : 23198132 : locallock->numLockOwners--;
2171 [ + + ]: 23198132 : if (i < locallock->numLockOwners)
2172 : 91 : lockOwners[i] = lockOwners[locallock->numLockOwners];
2173 : : }
2174 : 23966375 : break;
2175 : : }
2176 : : }
2177 [ + + ]: 23966391 : if (i < 0)
2178 : : {
2179 : : /* don't release a lock belonging to another owner */
2180 [ + - ]: 16 : elog(WARNING, "you don't own a lock of type %s",
2181 : : lockMethodTable->lockModeNames[lockmode]);
2182 : 16 : return false;
2183 : : }
2184 : : }
2185 : :
2186 : : /*
2187 : : * Decrease the total local count. If we're still holding the lock, we're
2188 : : * done.
2189 : : */
2190 : 23966375 : locallock->nLocks--;
2191 : :
2192 [ + + ]: 23966375 : if (locallock->nLocks > 0)
2193 : 1166054 : return true;
2194 : :
2195 : : /*
2196 : : * At this point we can no longer suppose we are clear of invalidation
2197 : : * messages related to this lock. Although we'll delete the LOCALLOCK
2198 : : * object before any intentional return from this routine, it seems worth
2199 : : * the trouble to explicitly reset lockCleared right now, just in case
2200 : : * some error prevents us from deleting the LOCALLOCK.
2201 : : */
2202 : 22800321 : locallock->lockCleared = false;
2203 : :
2204 : : /* Attempt fast release of any lock eligible for the fast path. */
2205 [ + + + + : 22800321 : if (EligibleForRelationFastPath(locktag, lockmode) &&
+ + + + +
+ ]
2206 [ + + ]: 21015781 : FastPathLocalUseCounts[FAST_PATH_REL_GROUP(locktag->locktag_field2)] > 0)
2207 : : {
2208 : : bool released;
2209 : :
2210 : : /*
2211 : : * We might not find the lock here, even if we originally entered it
2212 : : * here. Another backend may have moved it to the main table.
2213 : : */
2214 : 20735697 : LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
2215 : 20735697 : released = FastPathUnGrantRelationLock(locktag->locktag_field2,
2216 : : lockmode);
2217 : 20735697 : LWLockRelease(&MyProc->fpInfoLock);
2218 [ + + ]: 20735697 : if (released)
2219 : : {
2220 : 20622703 : RemoveLocalLock(locallock);
2221 : 20622703 : return true;
2222 : : }
2223 : : }
2224 : :
2225 : : /*
2226 : : * Otherwise we've got to mess with the shared lock table.
2227 : : */
2228 : 2177618 : partitionLock = LockHashPartitionLock(locallock->hashcode);
2229 : :
2230 : 2177618 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
2231 : :
2232 : : /*
2233 : : * Normally, we don't need to re-find the lock or proclock, since we kept
2234 : : * their addresses in the locallock table, and they couldn't have been
2235 : : * removed while we were holding a lock on them. But it's possible that
2236 : : * the lock was taken fast-path and has since been moved to the main hash
2237 : : * table by another backend, in which case we will need to look up the
2238 : : * objects here. We assume the lock field is NULL if so.
2239 : : */
2240 : 2177618 : lock = locallock->lock;
2241 [ + + ]: 2177618 : if (!lock)
2242 : : {
2243 : : PROCLOCKTAG proclocktag;
2244 : :
2245 : : Assert(EligibleForRelationFastPath(locktag, lockmode));
2246 : 8 : lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
2247 : : locktag,
2248 : : locallock->hashcode,
2249 : : HASH_FIND,
2250 : : NULL);
2251 [ - + ]: 8 : if (!lock)
2252 [ # # ]: 0 : elog(ERROR, "failed to re-find shared lock object");
2253 : 8 : locallock->lock = lock;
2254 : :
2255 : 8 : proclocktag.myLock = lock;
2256 : 8 : proclocktag.myProc = MyProc;
2257 : 8 : locallock->proclock = (PROCLOCK *) hash_search(LockMethodProcLockHash,
2258 : : &proclocktag,
2259 : : HASH_FIND,
2260 : : NULL);
2261 [ - + ]: 8 : if (!locallock->proclock)
2262 [ # # ]: 0 : elog(ERROR, "failed to re-find shared proclock object");
2263 : : }
2264 : : LOCK_PRINT("LockRelease: found", lock, lockmode);
2265 : 2177618 : proclock = locallock->proclock;
2266 : : PROCLOCK_PRINT("LockRelease: found", proclock);
2267 : :
2268 : : /*
2269 : : * Double-check that we are actually holding a lock of the type we want to
2270 : : * release.
2271 : : */
2272 [ - + ]: 2177618 : if (!(proclock->holdMask & LOCKBIT_ON(lockmode)))
2273 : : {
2274 : : PROCLOCK_PRINT("LockRelease: WRONGTYPE", proclock);
2275 : 0 : LWLockRelease(partitionLock);
2276 [ # # ]: 0 : elog(WARNING, "you don't own a lock of type %s",
2277 : : lockMethodTable->lockModeNames[lockmode]);
2278 : 0 : RemoveLocalLock(locallock);
2279 : 0 : return false;
2280 : : }
2281 : :
2282 : : /*
2283 : : * Do the releasing. CleanUpLock will waken any now-wakable waiters.
2284 : : */
2285 : 2177618 : wakeupNeeded = UnGrantLock(lock, lockmode, proclock, lockMethodTable);
2286 : :
2287 : 2177618 : CleanUpLock(lock, proclock,
2288 : : lockMethodTable, locallock->hashcode,
2289 : : wakeupNeeded);
2290 : :
2291 : 2177618 : LWLockRelease(partitionLock);
2292 : :
2293 : 2177618 : RemoveLocalLock(locallock);
2294 : 2177618 : return true;
2295 : : }
2296 : :
2297 : : /*
2298 : : * LockReleaseAll -- Release all locks of the specified lock method that
2299 : : * are held by the current process.
2300 : : *
2301 : : * Well, not necessarily *all* locks. The available behaviors are:
2302 : : * allLocks == true: release all locks including session locks.
2303 : : * allLocks == false: release all non-session locks.
2304 : : */
2305 : : void
2306 : 1344675 : LockReleaseAll(LOCKMETHODID lockmethodid, bool allLocks)
2307 : : {
2308 : : HASH_SEQ_STATUS status;
2309 : : LockMethod lockMethodTable;
2310 : : int i,
2311 : : numLockModes;
2312 : : LOCALLOCK *locallock;
2313 : : LOCK *lock;
2314 : : int partition;
2315 : 1344675 : bool have_fast_path_lwlock = false;
2316 : :
2317 [ + - - + ]: 1344675 : if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
2318 [ # # ]: 0 : elog(ERROR, "unrecognized lock method: %d", lockmethodid);
2319 : 1344675 : lockMethodTable = LockMethods[lockmethodid];
2320 : :
2321 : : #ifdef LOCK_DEBUG
2322 : : if (*(lockMethodTable->trace_flag))
2323 : : elog(LOG, "LockReleaseAll: lockmethod=%d", lockmethodid);
2324 : : #endif
2325 : :
2326 : : /*
2327 : : * Get rid of our fast-path VXID lock, if appropriate. Note that this is
2328 : : * the only way that the lock we hold on our own VXID can ever get
2329 : : * released: it is always and only released when a toplevel transaction
2330 : : * ends.
2331 : : */
2332 [ + + ]: 1344675 : if (lockmethodid == DEFAULT_LOCKMETHOD)
2333 : 662174 : VirtualXactLockTableCleanup();
2334 : :
2335 : 1344675 : numLockModes = lockMethodTable->numLockModes;
2336 : :
2337 : : /*
2338 : : * First we run through the locallock table and get rid of unwanted
2339 : : * entries, then we scan the process's proclocks and get rid of those. We
2340 : : * do this separately because we may have multiple locallock entries
2341 : : * pointing to the same proclock, and we daren't end up with any dangling
2342 : : * pointers. Fast-path locks are cleaned up during the locallock table
2343 : : * scan, though.
2344 : : */
2345 : 1344675 : hash_seq_init(&status, LockMethodLocalHash);
2346 : :
2347 [ + + ]: 3244984 : while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
2348 : : {
2349 : : /*
2350 : : * If the LOCALLOCK entry is unused, something must've gone wrong
2351 : : * while trying to acquire this lock. Just forget the local entry.
2352 : : */
2353 [ + + ]: 1900309 : if (locallock->nLocks == 0)
2354 : : {
2355 : 45 : RemoveLocalLock(locallock);
2356 : 45 : continue;
2357 : : }
2358 : :
2359 : : /* Ignore items that are not of the lockmethod to be removed */
2360 [ + + ]: 1900264 : if (LOCALLOCK_LOCKMETHOD(*locallock) != lockmethodid)
2361 : 145955 : continue;
2362 : :
2363 : : /*
2364 : : * If we are asked to release all locks, we can just zap the entry.
2365 : : * Otherwise, must scan to see if there are session locks. We assume
2366 : : * there is at most one lockOwners entry for session locks.
2367 : : */
2368 [ + + ]: 1754309 : if (!allLocks)
2369 : : {
2370 : 1647513 : LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
2371 : :
2372 : : /* If session lock is above array position 0, move it down to 0 */
2373 [ + + ]: 3427617 : for (i = 0; i < locallock->numLockOwners; i++)
2374 : : {
2375 [ + + ]: 1780104 : if (lockOwners[i].owner == NULL)
2376 : 145646 : lockOwners[0] = lockOwners[i];
2377 : : else
2378 : 1634458 : ResourceOwnerForgetLock(lockOwners[i].owner, locallock);
2379 : : }
2380 : :
2381 [ + - ]: 1647513 : if (locallock->numLockOwners > 0 &&
2382 [ + + ]: 1647513 : lockOwners[0].owner == NULL &&
2383 [ + - ]: 145646 : lockOwners[0].nLocks > 0)
2384 : : {
2385 : : /* Fix the locallock to show just the session locks */
2386 : 145646 : locallock->nLocks = lockOwners[0].nLocks;
2387 : 145646 : locallock->numLockOwners = 1;
2388 : : /* We aren't deleting this locallock, so done */
2389 : 145646 : continue;
2390 : : }
2391 : : else
2392 : 1501867 : locallock->numLockOwners = 0;
2393 : : }
2394 : :
2395 : : #ifdef USE_ASSERT_CHECKING
2396 : :
2397 : : /*
2398 : : * Tuple locks are currently held only for short durations within a
2399 : : * transaction. Check that we didn't forget to release one.
2400 : : */
2401 : : if (LOCALLOCK_LOCKTAG(*locallock) == LOCKTAG_TUPLE && !allLocks)
2402 : : elog(WARNING, "tuple lock held at commit");
2403 : : #endif
2404 : :
2405 : : /*
2406 : : * If the lock or proclock pointers are NULL, this lock was taken via
2407 : : * the relation fast-path (and is not known to have been transferred).
2408 : : */
2409 [ + + - + ]: 1608663 : if (locallock->proclock == NULL || locallock->lock == NULL)
2410 : 1609 : {
2411 : 827084 : LOCKMODE lockmode = locallock->tag.mode;
2412 : : Oid relid;
2413 : :
2414 : : /* Verify that a fast-path lock is what we've got. */
2415 [ + - + - : 827084 : if (!EligibleForRelationFastPath(&locallock->tag.lock, lockmode))
+ - + - -
+ ]
2416 [ # # ]: 0 : elog(PANIC, "locallock table corrupted");
2417 : :
2418 : : /*
2419 : : * If we don't currently hold the LWLock that protects our
2420 : : * fast-path data structures, we must acquire it before attempting
2421 : : * to release the lock via the fast-path. We will continue to
2422 : : * hold the LWLock until we're done scanning the locallock table,
2423 : : * unless we hit a transferred fast-path lock. (XXX is this
2424 : : * really such a good idea? There could be a lot of entries ...)
2425 : : */
2426 [ + + ]: 827084 : if (!have_fast_path_lwlock)
2427 : : {
2428 : 287902 : LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
2429 : 287902 : have_fast_path_lwlock = true;
2430 : : }
2431 : :
2432 : : /* Attempt fast-path release. */
2433 : 827084 : relid = locallock->tag.lock.locktag_field2;
2434 [ + + ]: 827084 : if (FastPathUnGrantRelationLock(relid, lockmode))
2435 : : {
2436 : 825475 : RemoveLocalLock(locallock);
2437 : 825475 : continue;
2438 : : }
2439 : :
2440 : : /*
2441 : : * Our lock, originally taken via the fast path, has been
2442 : : * transferred to the main lock table. That's going to require
2443 : : * some extra work, so release our fast-path lock before starting.
2444 : : */
2445 : 1609 : LWLockRelease(&MyProc->fpInfoLock);
2446 : 1609 : have_fast_path_lwlock = false;
2447 : :
2448 : : /*
2449 : : * Now dump the lock. We haven't got a pointer to the LOCK or
2450 : : * PROCLOCK in this case, so we have to handle this a bit
2451 : : * differently than a normal lock release. Unfortunately, this
2452 : : * requires an extra LWLock acquire-and-release cycle on the
2453 : : * partitionLock, but hopefully it shouldn't happen often.
2454 : : */
2455 : 1609 : LockRefindAndRelease(lockMethodTable, MyProc,
2456 : : &locallock->tag.lock, lockmode, false);
2457 : 1609 : RemoveLocalLock(locallock);
2458 : 1609 : continue;
2459 : : }
2460 : :
2461 : : /* Mark the proclock to show we need to release this lockmode */
2462 [ + - ]: 781579 : if (locallock->nLocks > 0)
2463 : 781579 : locallock->proclock->releaseMask |= LOCKBIT_ON(locallock->tag.mode);
2464 : :
2465 : : /* And remove the locallock hashtable entry */
2466 : 781579 : RemoveLocalLock(locallock);
2467 : : }
2468 : :
2469 : : /* Done with the fast-path data structures */
2470 [ + + ]: 1344675 : if (have_fast_path_lwlock)
2471 : 286293 : LWLockRelease(&MyProc->fpInfoLock);
2472 : :
2473 : : /*
2474 : : * Now, scan each lock partition separately.
2475 : : */
2476 [ + + ]: 22859475 : for (partition = 0; partition < NUM_LOCK_PARTITIONS; partition++)
2477 : : {
2478 : : LWLock *partitionLock;
2479 : 21514800 : dlist_head *procLocks = &MyProc->myProcLocks[partition];
2480 : : dlist_mutable_iter proclock_iter;
2481 : :
2482 : 21514800 : partitionLock = LockHashPartitionLockByIndex(partition);
2483 : :
2484 : : /*
2485 : : * If the proclock list for this partition is empty, we can skip
2486 : : * acquiring the partition lock. This optimization is trickier than
2487 : : * it looks, because another backend could be in process of adding
2488 : : * something to our proclock list due to promoting one of our
2489 : : * fast-path locks. However, any such lock must be one that we
2490 : : * decided not to delete above, so it's okay to skip it again now;
2491 : : * we'd just decide not to delete it again. We must, however, be
2492 : : * careful to re-fetch the list header once we've acquired the
2493 : : * partition lock, to be sure we have a valid, up-to-date pointer.
2494 : : * (There is probably no significant risk if pointer fetch/store is
2495 : : * atomic, but we don't wish to assume that.)
2496 : : *
2497 : : * XXX This argument assumes that the locallock table correctly
2498 : : * represents all of our fast-path locks. While allLocks mode
2499 : : * guarantees to clean up all of our normal locks regardless of the
2500 : : * locallock situation, we lose that guarantee for fast-path locks.
2501 : : * This is not ideal.
2502 : : */
2503 [ + + ]: 21514800 : if (dlist_is_empty(procLocks))
2504 : 20651233 : continue; /* needn't examine this partition */
2505 : :
2506 : 863567 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
2507 : :
2508 [ + - + + ]: 1888219 : dlist_foreach_modify(proclock_iter, procLocks)
2509 : : {
2510 : 1024652 : PROCLOCK *proclock = dlist_container(PROCLOCK, procLink, proclock_iter.cur);
2511 : 1024652 : bool wakeupNeeded = false;
2512 : :
2513 : : Assert(proclock->tag.myProc == MyProc);
2514 : :
2515 : 1024652 : lock = proclock->tag.myLock;
2516 : :
2517 : : /* Ignore items that are not of the lockmethod to be removed */
2518 [ + + ]: 1024652 : if (LOCK_LOCKMETHOD(*lock) != lockmethodid)
2519 : 145954 : continue;
2520 : :
2521 : : /*
2522 : : * In allLocks mode, force release of all locks even if locallock
2523 : : * table had problems
2524 : : */
2525 [ + + ]: 878698 : if (allLocks)
2526 : 45898 : proclock->releaseMask = proclock->holdMask;
2527 : : else
2528 : : Assert((proclock->releaseMask & ~proclock->holdMask) == 0);
2529 : :
2530 : : /*
2531 : : * Ignore items that have nothing to be released, unless they have
2532 : : * holdMask == 0 and are therefore recyclable
2533 : : */
2534 [ + + + - ]: 878698 : if (proclock->releaseMask == 0 && proclock->holdMask != 0)
2535 : 144756 : continue;
2536 : :
2537 : : PROCLOCK_PRINT("LockReleaseAll", proclock);
2538 : : LOCK_PRINT("LockReleaseAll", lock, 0);
2539 : : Assert(lock->nRequested >= 0);
2540 : : Assert(lock->nGranted >= 0);
2541 : : Assert(lock->nGranted <= lock->nRequested);
2542 : : Assert((proclock->holdMask & ~lock->grantMask) == 0);
2543 : :
2544 : : /*
2545 : : * Release the previously-marked lock modes
2546 : : */
2547 [ + + ]: 6605478 : for (i = 1; i <= numLockModes; i++)
2548 : : {
2549 [ + + ]: 5871536 : if (proclock->releaseMask & LOCKBIT_ON(i))
2550 : 781580 : wakeupNeeded |= UnGrantLock(lock, i, proclock,
2551 : : lockMethodTable);
2552 : : }
2553 : : Assert((lock->nRequested >= 0) && (lock->nGranted >= 0));
2554 : : Assert(lock->nGranted <= lock->nRequested);
2555 : : LOCK_PRINT("LockReleaseAll: updated", lock, 0);
2556 : :
2557 : 733942 : proclock->releaseMask = 0;
2558 : :
2559 : : /* CleanUpLock will wake up waiters if needed. */
2560 : 733942 : CleanUpLock(lock, proclock,
2561 : : lockMethodTable,
2562 : 733942 : LockTagHashCode(&lock->tag),
2563 : : wakeupNeeded);
2564 : : } /* loop over PROCLOCKs within this partition */
2565 : :
2566 : 863567 : LWLockRelease(partitionLock);
2567 : : } /* loop over partitions */
2568 : :
2569 : : #ifdef LOCK_DEBUG
2570 : : if (*(lockMethodTable->trace_flag))
2571 : : elog(LOG, "LockReleaseAll done");
2572 : : #endif
2573 : 1344675 : }
2574 : :
2575 : : /*
2576 : : * LockReleaseSession -- Release all session locks of the specified lock method
2577 : : * that are held by the current process.
2578 : : */
2579 : : void
2580 : 122 : LockReleaseSession(LOCKMETHODID lockmethodid)
2581 : : {
2582 : : HASH_SEQ_STATUS status;
2583 : : LOCALLOCK *locallock;
2584 : :
2585 [ + - - + ]: 122 : if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
2586 [ # # ]: 0 : elog(ERROR, "unrecognized lock method: %d", lockmethodid);
2587 : :
2588 : 122 : hash_seq_init(&status, LockMethodLocalHash);
2589 : :
2590 [ + + ]: 242 : while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
2591 : : {
2592 : : /* Ignore items that are not of the specified lock method */
2593 [ + + ]: 120 : if (LOCALLOCK_LOCKMETHOD(*locallock) != lockmethodid)
2594 : 11 : continue;
2595 : :
2596 : 109 : ReleaseLockIfHeld(locallock, true);
2597 : : }
2598 : 122 : }
2599 : :
2600 : : /*
2601 : : * LockReleaseCurrentOwner
2602 : : * Release all locks belonging to CurrentResourceOwner
2603 : : *
2604 : : * If the caller knows what those locks are, it can pass them as an array.
2605 : : * That speeds up the call significantly, when a lot of locks are held.
2606 : : * Otherwise, pass NULL for locallocks, and we'll traverse through our hash
2607 : : * table to find them.
2608 : : */
2609 : : void
2610 : 6382 : LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks)
2611 : : {
2612 [ + + ]: 6382 : if (locallocks == NULL)
2613 : : {
2614 : : HASH_SEQ_STATUS status;
2615 : : LOCALLOCK *locallock;
2616 : :
2617 : 9 : hash_seq_init(&status, LockMethodLocalHash);
2618 : :
2619 [ + + ]: 647 : while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
2620 : 638 : ReleaseLockIfHeld(locallock, false);
2621 : : }
2622 : : else
2623 : : {
2624 : : int i;
2625 : :
2626 [ + + ]: 9855 : for (i = nlocks - 1; i >= 0; i--)
2627 : 3482 : ReleaseLockIfHeld(locallocks[i], false);
2628 : : }
2629 : 6382 : }
2630 : :
2631 : : /*
2632 : : * ReleaseLockIfHeld
2633 : : * Release any session-level locks on this lockable object if sessionLock
2634 : : * is true; else, release any locks held by CurrentResourceOwner.
2635 : : *
2636 : : * It is tempting to pass this a ResourceOwner pointer (or NULL for session
2637 : : * locks), but without refactoring LockRelease() we cannot support releasing
2638 : : * locks belonging to resource owners other than CurrentResourceOwner.
2639 : : * If we were to refactor, it'd be a good idea to fix it so we don't have to
2640 : : * do a hashtable lookup of the locallock, too. However, currently this
2641 : : * function isn't used heavily enough to justify refactoring for its
2642 : : * convenience.
2643 : : */
2644 : : static void
2645 : 4229 : ReleaseLockIfHeld(LOCALLOCK *locallock, bool sessionLock)
2646 : : {
2647 : : ResourceOwner owner;
2648 : : LOCALLOCKOWNER *lockOwners;
2649 : : int i;
2650 : :
2651 : : /* Identify owner for lock (must match LockRelease!) */
2652 [ + + ]: 4229 : if (sessionLock)
2653 : 109 : owner = NULL;
2654 : : else
2655 : 4120 : owner = CurrentResourceOwner;
2656 : :
2657 : : /* Scan to see if there are any locks belonging to the target owner */
2658 : 4229 : lockOwners = locallock->lockOwners;
2659 [ + + ]: 4698 : for (i = locallock->numLockOwners - 1; i >= 0; i--)
2660 : : {
2661 [ + + ]: 4229 : if (lockOwners[i].owner == owner)
2662 : : {
2663 : : Assert(lockOwners[i].nLocks > 0);
2664 [ + + ]: 3760 : if (lockOwners[i].nLocks < locallock->nLocks)
2665 : : {
2666 : : /*
2667 : : * We will still hold this lock after forgetting this
2668 : : * ResourceOwner.
2669 : : */
2670 : 969 : locallock->nLocks -= lockOwners[i].nLocks;
2671 : : /* compact out unused slot */
2672 : 969 : locallock->numLockOwners--;
2673 [ + - ]: 969 : if (owner != NULL)
2674 : 969 : ResourceOwnerForgetLock(owner, locallock);
2675 [ - + ]: 969 : if (i < locallock->numLockOwners)
2676 : 0 : lockOwners[i] = lockOwners[locallock->numLockOwners];
2677 : : }
2678 : : else
2679 : : {
2680 : : Assert(lockOwners[i].nLocks == locallock->nLocks);
2681 : : /* We want to call LockRelease just once */
2682 : 2791 : lockOwners[i].nLocks = 1;
2683 : 2791 : locallock->nLocks = 1;
2684 [ - + ]: 2791 : if (!LockRelease(&locallock->tag.lock,
2685 : : locallock->tag.mode,
2686 : : sessionLock))
2687 [ # # ]: 0 : elog(WARNING, "ReleaseLockIfHeld: failed??");
2688 : : }
2689 : 3760 : break;
2690 : : }
2691 : : }
2692 : 4229 : }
2693 : :
2694 : : /*
2695 : : * LockReassignCurrentOwner
2696 : : * Reassign all locks belonging to CurrentResourceOwner to belong
2697 : : * to its parent resource owner.
2698 : : *
2699 : : * If the caller knows what those locks are, it can pass them as an array.
2700 : : * That speeds up the call significantly, when a lot of locks are held
2701 : : * (e.g pg_dump with a large schema). Otherwise, pass NULL for locallocks,
2702 : : * and we'll traverse through our hash table to find them.
2703 : : */
2704 : : void
2705 : 456770 : LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks)
2706 : : {
2707 : 456770 : ResourceOwner parent = ResourceOwnerGetParent(CurrentResourceOwner);
2708 : :
2709 : : Assert(parent != NULL);
2710 : :
2711 [ + + ]: 456770 : if (locallocks == NULL)
2712 : : {
2713 : : HASH_SEQ_STATUS status;
2714 : : LOCALLOCK *locallock;
2715 : :
2716 : 7618 : hash_seq_init(&status, LockMethodLocalHash);
2717 : :
2718 [ + + ]: 232757 : while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
2719 : 225139 : LockReassignOwner(locallock, parent);
2720 : : }
2721 : : else
2722 : : {
2723 : : int i;
2724 : :
2725 [ + + ]: 1030826 : for (i = nlocks - 1; i >= 0; i--)
2726 : 581674 : LockReassignOwner(locallocks[i], parent);
2727 : : }
2728 : 456770 : }
2729 : :
2730 : : /*
2731 : : * Subroutine of LockReassignCurrentOwner. Reassigns a given lock belonging to
2732 : : * CurrentResourceOwner to its parent.
2733 : : */
2734 : : static void
2735 : 806813 : LockReassignOwner(LOCALLOCK *locallock, ResourceOwner parent)
2736 : : {
2737 : : LOCALLOCKOWNER *lockOwners;
2738 : : int i;
2739 : 806813 : int ic = -1;
2740 : 806813 : int ip = -1;
2741 : :
2742 : : /*
2743 : : * Scan to see if there are any locks belonging to current owner or its
2744 : : * parent
2745 : : */
2746 : 806813 : lockOwners = locallock->lockOwners;
2747 [ + + ]: 1821705 : for (i = locallock->numLockOwners - 1; i >= 0; i--)
2748 : : {
2749 [ + + ]: 1014892 : if (lockOwners[i].owner == CurrentResourceOwner)
2750 : 746368 : ic = i;
2751 [ + + ]: 268524 : else if (lockOwners[i].owner == parent)
2752 : 224356 : ip = i;
2753 : : }
2754 : :
2755 [ + + ]: 806813 : if (ic < 0)
2756 : 60445 : return; /* no current locks */
2757 : :
2758 [ + + ]: 746368 : if (ip < 0)
2759 : : {
2760 : : /* Parent has no slot, so just give it the child's slot */
2761 : 582419 : lockOwners[ic].owner = parent;
2762 : 582419 : ResourceOwnerRememberLock(parent, locallock);
2763 : : }
2764 : : else
2765 : : {
2766 : : /* Merge child's count with parent's */
2767 : 163949 : lockOwners[ip].nLocks += lockOwners[ic].nLocks;
2768 : : /* compact out unused slot */
2769 : 163949 : locallock->numLockOwners--;
2770 [ + + ]: 163949 : if (ic < locallock->numLockOwners)
2771 : 882 : lockOwners[ic] = lockOwners[locallock->numLockOwners];
2772 : : }
2773 : 746368 : ResourceOwnerForgetLock(CurrentResourceOwner, locallock);
2774 : : }
2775 : :
2776 : : /*
2777 : : * FastPathGrantRelationLock
2778 : : * Grant lock using per-backend fast-path array, if there is space.
2779 : : */
2780 : : static bool
2781 : 21450149 : FastPathGrantRelationLock(Oid relid, LOCKMODE lockmode)
2782 : : {
2783 : : uint32 i;
2784 : 21450149 : uint32 unused_slot = FastPathLockSlotsPerBackend();
2785 : :
2786 : : /* fast-path group the lock belongs to */
2787 : 21450149 : uint32 group = FAST_PATH_REL_GROUP(relid);
2788 : :
2789 : : /* Scan for existing entry for this relid, remembering empty slot. */
2790 [ + + ]: 363883894 : for (i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
2791 : : {
2792 : : /* index into the whole per-backend array */
2793 : 343070764 : uint32 f = FAST_PATH_SLOT(group, i);
2794 : :
2795 [ + + ]: 343070764 : if (FAST_PATH_GET_BITS(MyProc, f) == 0)
2796 : 335816483 : unused_slot = f;
2797 [ + + ]: 7254281 : else if (MyProc->fpRelId[f] == relid)
2798 : : {
2799 : : Assert(!FAST_PATH_CHECK_LOCKMODE(MyProc, f, lockmode));
2800 : 637019 : FAST_PATH_SET_LOCKMODE(MyProc, f, lockmode);
2801 : 637019 : return true;
2802 : : }
2803 : : }
2804 : :
2805 : : /* If no existing entry, use any empty slot. */
2806 [ + - ]: 20813130 : if (unused_slot < FastPathLockSlotsPerBackend())
2807 : : {
2808 : 20813130 : MyProc->fpRelId[unused_slot] = relid;
2809 : 20813130 : FAST_PATH_SET_LOCKMODE(MyProc, unused_slot, lockmode);
2810 : 20813130 : ++FastPathLocalUseCounts[group];
2811 : 20813130 : return true;
2812 : : }
2813 : :
2814 : : /* No existing entry, and no empty slot. */
2815 : 0 : return false;
2816 : : }
2817 : :
2818 : : /*
2819 : : * FastPathUnGrantRelationLock
2820 : : * Release fast-path lock, if present. Update backend-private local
2821 : : * use count, while we're at it.
2822 : : */
2823 : : static bool
2824 : 21562781 : FastPathUnGrantRelationLock(Oid relid, LOCKMODE lockmode)
2825 : : {
2826 : : uint32 i;
2827 : 21562781 : bool result = false;
2828 : :
2829 : : /* fast-path group the lock belongs to */
2830 : 21562781 : uint32 group = FAST_PATH_REL_GROUP(relid);
2831 : :
2832 : 21562781 : FastPathLocalUseCounts[group] = 0;
2833 [ + + ]: 366567277 : for (i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
2834 : : {
2835 : : /* index into the whole per-backend array */
2836 : 345004496 : uint32 f = FAST_PATH_SLOT(group, i);
2837 : :
2838 [ + + ]: 345004496 : if (MyProc->fpRelId[f] == relid
2839 [ + + ]: 32205621 : && FAST_PATH_CHECK_LOCKMODE(MyProc, f, lockmode))
2840 : : {
2841 : : Assert(!result);
2842 : 21448178 : FAST_PATH_CLEAR_LOCKMODE(MyProc, f, lockmode);
2843 : 21448178 : result = true;
2844 : : /* we continue iterating so as to update FastPathLocalUseCount */
2845 : : }
2846 [ + + ]: 345004496 : if (FAST_PATH_GET_BITS(MyProc, f) != 0)
2847 : 8813967 : ++FastPathLocalUseCounts[group];
2848 : : }
2849 : 21562781 : return result;
2850 : : }
2851 : :
2852 : : /*
2853 : : * FastPathTransferRelationLocks
2854 : : * Transfer locks matching the given lock tag from per-backend fast-path
2855 : : * arrays to the shared hash table.
2856 : : *
2857 : : * Returns true if successful, false if ran out of shared memory.
2858 : : */
2859 : : static bool
2860 : 243714 : FastPathTransferRelationLocks(LockMethod lockMethodTable, const LOCKTAG *locktag,
2861 : : uint32 hashcode)
2862 : : {
2863 : 243714 : LWLock *partitionLock = LockHashPartitionLock(hashcode);
2864 : 243714 : Oid relid = locktag->locktag_field2;
2865 : : uint32 i;
2866 : :
2867 : : /* fast-path group the lock belongs to */
2868 : 243714 : uint32 group = FAST_PATH_REL_GROUP(relid);
2869 : :
2870 : : /*
2871 : : * Every PGPROC that can potentially hold a fast-path lock is present in
2872 : : * ProcGlobal->allProcs. Prepared transactions are not, but any
2873 : : * outstanding fast-path locks held by prepared transactions are
2874 : : * transferred to the main lock table.
2875 : : */
2876 [ + + ]: 36301686 : for (i = 0; i < ProcGlobal->allProcCount; i++)
2877 : : {
2878 : 36057972 : PGPROC *proc = GetPGProcByNumber(i);
2879 : : uint32 j;
2880 : :
2881 : 36057972 : LWLockAcquire(&proc->fpInfoLock, LW_EXCLUSIVE);
2882 : :
2883 : : /*
2884 : : * If the target backend isn't referencing the same database as the
2885 : : * lock, then we needn't examine the individual relation IDs at all;
2886 : : * none of them can be relevant.
2887 : : *
2888 : : * proc->databaseId is set at backend startup time and never changes
2889 : : * thereafter, so it might be safe to perform this test before
2890 : : * acquiring &proc->fpInfoLock. In particular, it's certainly safe to
2891 : : * assume that if the target backend holds any fast-path locks, it
2892 : : * must have performed a memory-fencing operation (in particular, an
2893 : : * LWLock acquisition) since setting proc->databaseId. However, it's
2894 : : * less clear that our backend is certain to have performed a memory
2895 : : * fencing operation since the other backend set proc->databaseId. So
2896 : : * for now, we test it after acquiring the LWLock just to be safe.
2897 : : *
2898 : : * Also skip groups without any registered fast-path locks.
2899 : : */
2900 [ + + ]: 36057972 : if (proc->databaseId != locktag->locktag_field1 ||
2901 [ + + ]: 14106605 : proc->fpLockBits[group] == 0)
2902 : : {
2903 : 35924397 : LWLockRelease(&proc->fpInfoLock);
2904 : 35924397 : continue;
2905 : : }
2906 : :
2907 [ + + ]: 2269100 : for (j = 0; j < FP_LOCK_SLOTS_PER_GROUP; j++)
2908 : : {
2909 : : uint32 lockmode;
2910 : :
2911 : : /* index into the whole per-backend array */
2912 : 2137089 : uint32 f = FAST_PATH_SLOT(group, j);
2913 : :
2914 : : /* Look for an allocated slot matching the given relid. */
2915 [ + + + + ]: 2137089 : if (relid != proc->fpRelId[f] || FAST_PATH_GET_BITS(proc, f) == 0)
2916 : 2135525 : continue;
2917 : :
2918 : : /* Find or create lock object. */
2919 : 1564 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
2920 : 1564 : for (lockmode = FAST_PATH_LOCKNUMBER_OFFSET;
2921 [ + + ]: 6256 : lockmode < FAST_PATH_LOCKNUMBER_OFFSET + FAST_PATH_BITS_PER_SLOT;
2922 : 4692 : ++lockmode)
2923 : : {
2924 : : PROCLOCK *proclock;
2925 : :
2926 [ + + ]: 4692 : if (!FAST_PATH_CHECK_LOCKMODE(proc, f, lockmode))
2927 : 3059 : continue;
2928 : 1633 : proclock = SetupLockInTable(lockMethodTable, proc, locktag,
2929 : : hashcode, lockmode);
2930 [ - + ]: 1633 : if (!proclock)
2931 : : {
2932 : 0 : LWLockRelease(partitionLock);
2933 : 0 : LWLockRelease(&proc->fpInfoLock);
2934 : 0 : return false;
2935 : : }
2936 : 1633 : GrantLock(proclock->tag.myLock, proclock, lockmode);
2937 : 1633 : FAST_PATH_CLEAR_LOCKMODE(proc, f, lockmode);
2938 : : }
2939 : 1564 : LWLockRelease(partitionLock);
2940 : :
2941 : : /* No need to examine remaining slots. */
2942 : 1564 : break;
2943 : : }
2944 : 133575 : LWLockRelease(&proc->fpInfoLock);
2945 : : }
2946 : 243714 : return true;
2947 : : }
2948 : :
2949 : : /*
2950 : : * FastPathGetRelationLockEntry
2951 : : * Return the PROCLOCK for a lock originally taken via the fast-path,
2952 : : * transferring it to the primary lock table if necessary.
2953 : : *
2954 : : * Note: caller takes care of updating the locallock object.
2955 : : */
2956 : : static PROCLOCK *
2957 : 354 : FastPathGetRelationLockEntry(LOCALLOCK *locallock)
2958 : : {
2959 : 354 : LockMethod lockMethodTable = LockMethods[DEFAULT_LOCKMETHOD];
2960 : 354 : LOCKTAG *locktag = &locallock->tag.lock;
2961 : 354 : PROCLOCK *proclock = NULL;
2962 : 354 : LWLock *partitionLock = LockHashPartitionLock(locallock->hashcode);
2963 : 354 : Oid relid = locktag->locktag_field2;
2964 : : uint32 i,
2965 : : group;
2966 : :
2967 : : /* fast-path group the lock belongs to */
2968 : 354 : group = FAST_PATH_REL_GROUP(relid);
2969 : :
2970 : 354 : LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
2971 : :
2972 [ + + ]: 5674 : for (i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
2973 : : {
2974 : : uint32 lockmode;
2975 : :
2976 : : /* index into the whole per-backend array */
2977 : 5658 : uint32 f = FAST_PATH_SLOT(group, i);
2978 : :
2979 : : /* Look for an allocated slot matching the given relid. */
2980 [ + + - + ]: 5658 : if (relid != MyProc->fpRelId[f] || FAST_PATH_GET_BITS(MyProc, f) == 0)
2981 : 5320 : continue;
2982 : :
2983 : : /* If we don't have a lock of the given mode, forget it! */
2984 : 338 : lockmode = locallock->tag.mode;
2985 [ - + ]: 338 : if (!FAST_PATH_CHECK_LOCKMODE(MyProc, f, lockmode))
2986 : 0 : break;
2987 : :
2988 : : /* Find or create lock object. */
2989 : 338 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
2990 : :
2991 : 338 : proclock = SetupLockInTable(lockMethodTable, MyProc, locktag,
2992 : : locallock->hashcode, lockmode);
2993 [ - + ]: 338 : if (!proclock)
2994 : : {
2995 : 0 : LWLockRelease(partitionLock);
2996 : 0 : LWLockRelease(&MyProc->fpInfoLock);
2997 [ # # ]: 0 : ereport(ERROR,
2998 : : (errcode(ERRCODE_OUT_OF_MEMORY),
2999 : : errmsg("out of shared memory"),
3000 : : errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
3001 : : }
3002 : 338 : GrantLock(proclock->tag.myLock, proclock, lockmode);
3003 : 338 : FAST_PATH_CLEAR_LOCKMODE(MyProc, f, lockmode);
3004 : :
3005 : 338 : LWLockRelease(partitionLock);
3006 : :
3007 : : /* No need to examine remaining slots. */
3008 : 338 : break;
3009 : : }
3010 : :
3011 : 354 : LWLockRelease(&MyProc->fpInfoLock);
3012 : :
3013 : : /* Lock may have already been transferred by some other backend. */
3014 [ + + ]: 354 : if (proclock == NULL)
3015 : : {
3016 : : LOCK *lock;
3017 : : PROCLOCKTAG proclocktag;
3018 : : uint32 proclock_hashcode;
3019 : :
3020 : 16 : LWLockAcquire(partitionLock, LW_SHARED);
3021 : :
3022 : 16 : lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
3023 : : locktag,
3024 : : locallock->hashcode,
3025 : : HASH_FIND,
3026 : : NULL);
3027 [ - + ]: 16 : if (!lock)
3028 [ # # ]: 0 : elog(ERROR, "failed to re-find shared lock object");
3029 : :
3030 : 16 : proclocktag.myLock = lock;
3031 : 16 : proclocktag.myProc = MyProc;
3032 : :
3033 : 16 : proclock_hashcode = ProcLockHashCode(&proclocktag, locallock->hashcode);
3034 : : proclock = (PROCLOCK *)
3035 : 16 : hash_search_with_hash_value(LockMethodProcLockHash,
3036 : : &proclocktag,
3037 : : proclock_hashcode,
3038 : : HASH_FIND,
3039 : : NULL);
3040 [ - + ]: 16 : if (!proclock)
3041 [ # # ]: 0 : elog(ERROR, "failed to re-find shared proclock object");
3042 : 16 : LWLockRelease(partitionLock);
3043 : : }
3044 : :
3045 : 354 : return proclock;
3046 : : }
3047 : :
3048 : : /*
3049 : : * GetLockConflicts
3050 : : * Get an array of VirtualTransactionIds of xacts currently holding locks
3051 : : * that would conflict with the specified lock/lockmode.
3052 : : * xacts merely awaiting such a lock are NOT reported.
3053 : : *
3054 : : * The result array is palloc'd and is terminated with an invalid VXID.
3055 : : * *countp, if not null, is updated to the number of items set.
3056 : : *
3057 : : * Of course, the result could be out of date by the time it's returned, so
3058 : : * use of this function has to be thought about carefully. Similarly, a
3059 : : * PGPROC with no "lxid" will be considered non-conflicting regardless of any
3060 : : * lock it holds. Existing callers don't care about a locker after that
3061 : : * locker's pg_xact updates complete. CommitTransaction() clears "lxid" after
3062 : : * pg_xact updates and before releasing locks.
3063 : : *
3064 : : * Note we never include the current xact's vxid in the result array,
3065 : : * since an xact never blocks itself.
3066 : : */
3067 : : VirtualTransactionId *
3068 : 1799 : GetLockConflicts(const LOCKTAG *locktag, LOCKMODE lockmode, int *countp)
3069 : : {
3070 : : static VirtualTransactionId *vxids;
3071 : 1799 : LOCKMETHODID lockmethodid = locktag->locktag_lockmethodid;
3072 : : LockMethod lockMethodTable;
3073 : : LOCK *lock;
3074 : : LOCKMASK conflictMask;
3075 : : dlist_iter proclock_iter;
3076 : : PROCLOCK *proclock;
3077 : : uint32 hashcode;
3078 : : LWLock *partitionLock;
3079 : 1799 : int count = 0;
3080 : 1799 : int fast_count = 0;
3081 : :
3082 [ + - - + ]: 1799 : if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
3083 [ # # ]: 0 : elog(ERROR, "unrecognized lock method: %d", lockmethodid);
3084 : 1799 : lockMethodTable = LockMethods[lockmethodid];
3085 [ + - - + ]: 1799 : if (lockmode <= 0 || lockmode > lockMethodTable->numLockModes)
3086 [ # # ]: 0 : elog(ERROR, "unrecognized lock mode: %d", lockmode);
3087 : :
3088 : : /*
3089 : : * Allocate memory to store results, and fill with InvalidVXID. We only
3090 : : * need enough space for MaxBackends + max_prepared_xacts + a terminator.
3091 : : * InHotStandby allocate once in TopMemoryContext.
3092 : : */
3093 [ + + ]: 1799 : if (InHotStandby)
3094 : : {
3095 [ + + ]: 4 : if (vxids == NULL)
3096 : 1 : vxids = (VirtualTransactionId *)
3097 : 1 : MemoryContextAlloc(TopMemoryContext,
3098 : : sizeof(VirtualTransactionId) *
3099 : 1 : (MaxBackends + max_prepared_xacts + 1));
3100 : : }
3101 : : else
3102 : 1795 : vxids = palloc0_array(VirtualTransactionId, (MaxBackends + max_prepared_xacts + 1));
3103 : :
3104 : : /* Compute hash code and partition lock, and look up conflicting modes. */
3105 : 1799 : hashcode = LockTagHashCode(locktag);
3106 : 1799 : partitionLock = LockHashPartitionLock(hashcode);
3107 : 1799 : conflictMask = lockMethodTable->conflictTab[lockmode];
3108 : :
3109 : : /*
3110 : : * Fast path locks might not have been entered in the primary lock table.
3111 : : * If the lock we're dealing with could conflict with such a lock, we must
3112 : : * examine each backend's fast-path array for conflicts.
3113 : : */
3114 [ + - + - : 1799 : if (ConflictsWithRelationFastPath(locktag, lockmode))
+ - + - ]
3115 : : {
3116 : 1799 : Oid relid = locktag->locktag_field2;
3117 : : VirtualTransactionId vxid;
3118 : :
3119 : : /* fast-path group the lock belongs to */
3120 : 1799 : uint32 group = FAST_PATH_REL_GROUP(relid);
3121 : :
3122 : : /*
3123 : : * Iterate over relevant PGPROCs. Anything held by a prepared
3124 : : * transaction will have been transferred to the primary lock table,
3125 : : * so we need not worry about those. This is all a bit fuzzy, because
3126 : : * new locks could be taken after we've visited a particular
3127 : : * partition, but the callers had better be prepared to deal with that
3128 : : * anyway, since the locks could equally well be taken between the
3129 : : * time we return the value and the time the caller does something
3130 : : * with it.
3131 : : */
3132 [ + + ]: 284707 : for (uint32 i = 0; i < ProcGlobal->allProcCount; i++)
3133 : : {
3134 : 282908 : PGPROC *proc = GetPGProcByNumber(i);
3135 : : uint32 j;
3136 : :
3137 : : /* A backend never blocks itself */
3138 [ + + ]: 282908 : if (proc == MyProc)
3139 : 1799 : continue;
3140 : :
3141 : 281109 : LWLockAcquire(&proc->fpInfoLock, LW_SHARED);
3142 : :
3143 : : /*
3144 : : * If the target backend isn't referencing the same database as
3145 : : * the lock, then we needn't examine the individual relation IDs
3146 : : * at all; none of them can be relevant.
3147 : : *
3148 : : * See FastPathTransferRelationLocks() for discussion of why we do
3149 : : * this test after acquiring the lock.
3150 : : *
3151 : : * Also skip groups without any registered fast-path locks.
3152 : : */
3153 [ + + ]: 281109 : if (proc->databaseId != locktag->locktag_field1 ||
3154 [ + + ]: 116568 : proc->fpLockBits[group] == 0)
3155 : : {
3156 : 280680 : LWLockRelease(&proc->fpInfoLock);
3157 : 280680 : continue;
3158 : : }
3159 : :
3160 [ + + ]: 7078 : for (j = 0; j < FP_LOCK_SLOTS_PER_GROUP; j++)
3161 : : {
3162 : : uint32 lockmask;
3163 : :
3164 : : /* index into the whole per-backend array */
3165 : 6864 : uint32 f = FAST_PATH_SLOT(group, j);
3166 : :
3167 : : /* Look for an allocated slot matching the given relid. */
3168 [ + + ]: 6864 : if (relid != proc->fpRelId[f])
3169 : 6649 : continue;
3170 : 215 : lockmask = FAST_PATH_GET_BITS(proc, f);
3171 [ - + ]: 215 : if (!lockmask)
3172 : 0 : continue;
3173 : 215 : lockmask <<= FAST_PATH_LOCKNUMBER_OFFSET;
3174 : :
3175 : : /*
3176 : : * There can only be one entry per relation, so if we found it
3177 : : * and it doesn't conflict, we can skip the rest of the slots.
3178 : : */
3179 [ + + ]: 215 : if ((lockmask & conflictMask) == 0)
3180 : 5 : break;
3181 : :
3182 : : /* Conflict! */
3183 : 210 : GET_VXID_FROM_PGPROC(vxid, *proc);
3184 : :
3185 [ + + ]: 210 : if (VirtualTransactionIdIsValid(vxid))
3186 : 208 : vxids[count++] = vxid;
3187 : : /* else, xact already committed or aborted */
3188 : :
3189 : : /* No need to examine remaining slots. */
3190 : 210 : break;
3191 : : }
3192 : :
3193 : 429 : LWLockRelease(&proc->fpInfoLock);
3194 : : }
3195 : : }
3196 : :
3197 : : /* Remember how many fast-path conflicts we found. */
3198 : 1799 : fast_count = count;
3199 : :
3200 : : /*
3201 : : * Look up the lock object matching the tag.
3202 : : */
3203 : 1799 : LWLockAcquire(partitionLock, LW_SHARED);
3204 : :
3205 : 1799 : lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
3206 : : locktag,
3207 : : hashcode,
3208 : : HASH_FIND,
3209 : : NULL);
3210 [ + + ]: 1799 : if (!lock)
3211 : : {
3212 : : /*
3213 : : * If the lock object doesn't exist, there is nothing holding a lock
3214 : : * on this lockable object.
3215 : : */
3216 : 72 : LWLockRelease(partitionLock);
3217 : 72 : vxids[count].procNumber = INVALID_PROC_NUMBER;
3218 : 72 : vxids[count].localTransactionId = InvalidLocalTransactionId;
3219 [ - + ]: 72 : if (countp)
3220 : 0 : *countp = count;
3221 : 72 : return vxids;
3222 : : }
3223 : :
3224 : : /*
3225 : : * Examine each existing holder (or awaiter) of the lock.
3226 : : */
3227 [ + - + + ]: 3487 : dlist_foreach(proclock_iter, &lock->procLocks)
3228 : : {
3229 : 1760 : proclock = dlist_container(PROCLOCK, lockLink, proclock_iter.cur);
3230 : :
3231 [ + + ]: 1760 : if (conflictMask & proclock->holdMask)
3232 : : {
3233 : 1756 : PGPROC *proc = proclock->tag.myProc;
3234 : :
3235 : : /* A backend never blocks itself */
3236 [ + + ]: 1756 : if (proc != MyProc)
3237 : : {
3238 : : VirtualTransactionId vxid;
3239 : :
3240 : 33 : GET_VXID_FROM_PGPROC(vxid, *proc);
3241 : :
3242 [ + - ]: 33 : if (VirtualTransactionIdIsValid(vxid))
3243 : : {
3244 : : int i;
3245 : :
3246 : : /* Avoid duplicate entries. */
3247 [ + + ]: 41 : for (i = 0; i < fast_count; ++i)
3248 [ - + - - ]: 8 : if (VirtualTransactionIdEquals(vxids[i], vxid))
3249 : 0 : break;
3250 [ + - ]: 33 : if (i >= fast_count)
3251 : 33 : vxids[count++] = vxid;
3252 : : }
3253 : : /* else, xact already committed or aborted */
3254 : : }
3255 : : }
3256 : : }
3257 : :
3258 : 1727 : LWLockRelease(partitionLock);
3259 : :
3260 [ - + ]: 1727 : if (count > MaxBackends + max_prepared_xacts) /* should never happen */
3261 [ # # ]: 0 : elog(PANIC, "too many conflicting locks found");
3262 : :
3263 : 1727 : vxids[count].procNumber = INVALID_PROC_NUMBER;
3264 : 1727 : vxids[count].localTransactionId = InvalidLocalTransactionId;
3265 [ + + ]: 1727 : if (countp)
3266 : 1724 : *countp = count;
3267 : 1727 : return vxids;
3268 : : }
3269 : :
3270 : : /*
3271 : : * Find a lock in the shared lock table and release it. It is the caller's
3272 : : * responsibility to verify that this is a sane thing to do. (For example, it
3273 : : * would be bad to release a lock here if there might still be a LOCALLOCK
3274 : : * object with pointers to it.)
3275 : : *
3276 : : * We currently use this in two situations: first, to release locks held by
3277 : : * prepared transactions on commit (see lock_twophase_postcommit); and second,
3278 : : * to release locks taken via the fast-path, transferred to the main hash
3279 : : * table, and then released (see LockReleaseAll).
3280 : : */
3281 : : static void
3282 : 2829 : LockRefindAndRelease(LockMethod lockMethodTable, PGPROC *proc,
3283 : : LOCKTAG *locktag, LOCKMODE lockmode,
3284 : : bool decrement_strong_lock_count)
3285 : : {
3286 : : LOCK *lock;
3287 : : PROCLOCK *proclock;
3288 : : PROCLOCKTAG proclocktag;
3289 : : uint32 hashcode;
3290 : : uint32 proclock_hashcode;
3291 : : LWLock *partitionLock;
3292 : : bool wakeupNeeded;
3293 : :
3294 : 2829 : hashcode = LockTagHashCode(locktag);
3295 : 2829 : partitionLock = LockHashPartitionLock(hashcode);
3296 : :
3297 : 2829 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
3298 : :
3299 : : /*
3300 : : * Re-find the lock object (it had better be there).
3301 : : */
3302 : 2829 : lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
3303 : : locktag,
3304 : : hashcode,
3305 : : HASH_FIND,
3306 : : NULL);
3307 [ - + ]: 2829 : if (!lock)
3308 [ # # ]: 0 : elog(PANIC, "failed to re-find shared lock object");
3309 : :
3310 : : /*
3311 : : * Re-find the proclock object (ditto).
3312 : : */
3313 : 2829 : proclocktag.myLock = lock;
3314 : 2829 : proclocktag.myProc = proc;
3315 : :
3316 : 2829 : proclock_hashcode = ProcLockHashCode(&proclocktag, hashcode);
3317 : :
3318 : 2829 : proclock = (PROCLOCK *) hash_search_with_hash_value(LockMethodProcLockHash,
3319 : : &proclocktag,
3320 : : proclock_hashcode,
3321 : : HASH_FIND,
3322 : : NULL);
3323 [ - + ]: 2829 : if (!proclock)
3324 [ # # ]: 0 : elog(PANIC, "failed to re-find shared proclock object");
3325 : :
3326 : : /*
3327 : : * Double-check that we are actually holding a lock of the type we want to
3328 : : * release.
3329 : : */
3330 [ - + ]: 2829 : if (!(proclock->holdMask & LOCKBIT_ON(lockmode)))
3331 : : {
3332 : : PROCLOCK_PRINT("lock_twophase_postcommit: WRONGTYPE", proclock);
3333 : 0 : LWLockRelease(partitionLock);
3334 [ # # ]: 0 : elog(WARNING, "you don't own a lock of type %s",
3335 : : lockMethodTable->lockModeNames[lockmode]);
3336 : 0 : return;
3337 : : }
3338 : :
3339 : : /*
3340 : : * Do the releasing. CleanUpLock will waken any now-wakable waiters.
3341 : : */
3342 : 2829 : wakeupNeeded = UnGrantLock(lock, lockmode, proclock, lockMethodTable);
3343 : :
3344 : 2829 : CleanUpLock(lock, proclock,
3345 : : lockMethodTable, hashcode,
3346 : : wakeupNeeded);
3347 : :
3348 : 2829 : LWLockRelease(partitionLock);
3349 : :
3350 : : /*
3351 : : * Decrement strong lock count. This logic is needed only for 2PC.
3352 : : */
3353 [ + + ]: 2829 : if (decrement_strong_lock_count
3354 [ + - + + : 925 : && ConflictsWithRelationFastPath(locktag, lockmode))
+ + + + ]
3355 : : {
3356 : 116 : uint32 fasthashcode = FastPathStrongLockHashPartition(hashcode);
3357 : :
3358 : : Assert(pg_atomic_read_u32(&FastPathStrongRelationLocks[fasthashcode]) > 0);
3359 : 116 : pg_atomic_fetch_sub_u32(&FastPathStrongRelationLocks[fasthashcode], 1);
3360 : : }
3361 : : }
3362 : :
3363 : : /*
3364 : : * CheckForSessionAndXactLocks
3365 : : * Check to see if transaction holds both session-level and xact-level
3366 : : * locks on the same object; if so, throw an error.
3367 : : *
3368 : : * If we have both session- and transaction-level locks on the same object,
3369 : : * PREPARE TRANSACTION must fail. This should never happen with regular
3370 : : * locks, since we only take those at session level in some special operations
3371 : : * like VACUUM. It's possible to hit this with advisory locks, though.
3372 : : *
3373 : : * It would be nice if we could keep the session hold and give away the
3374 : : * transactional hold to the prepared xact. However, that would require two
3375 : : * PROCLOCK objects, and we cannot be sure that another PROCLOCK will be
3376 : : * available when it comes time for PostPrepare_Locks to do the deed.
3377 : : * So for now, we error out while we can still do so safely.
3378 : : *
3379 : : * Since the LOCALLOCK table stores a separate entry for each lockmode,
3380 : : * we can't implement this check by examining LOCALLOCK entries in isolation.
3381 : : * We must build a transient hashtable that is indexed by locktag only.
3382 : : */
3383 : : static void
3384 : 332 : CheckForSessionAndXactLocks(void)
3385 : : {
3386 : : typedef struct
3387 : : {
3388 : : LOCKTAG lock; /* identifies the lockable object */
3389 : : bool sessLock; /* is any lockmode held at session level? */
3390 : : bool xactLock; /* is any lockmode held at xact level? */
3391 : : } PerLockTagEntry;
3392 : :
3393 : : HASHCTL hash_ctl;
3394 : : HTAB *lockhtab;
3395 : : HASH_SEQ_STATUS status;
3396 : : LOCALLOCK *locallock;
3397 : :
3398 : : /* Create a local hash table keyed by LOCKTAG only */
3399 : 332 : hash_ctl.keysize = sizeof(LOCKTAG);
3400 : 332 : hash_ctl.entrysize = sizeof(PerLockTagEntry);
3401 : 332 : hash_ctl.hcxt = CurrentMemoryContext;
3402 : :
3403 : 332 : lockhtab = hash_create("CheckForSessionAndXactLocks table",
3404 : : 256, /* arbitrary initial size */
3405 : : &hash_ctl,
3406 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
3407 : :
3408 : : /* Scan local lock table to find entries for each LOCKTAG */
3409 : 332 : hash_seq_init(&status, LockMethodLocalHash);
3410 : :
3411 [ + + ]: 1262 : while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
3412 : : {
3413 : 932 : LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
3414 : : PerLockTagEntry *hentry;
3415 : : bool found;
3416 : : int i;
3417 : :
3418 : : /*
3419 : : * Ignore VXID locks. We don't want those to be held by prepared
3420 : : * transactions, since they aren't meaningful after a restart.
3421 : : */
3422 [ - + ]: 932 : if (locallock->tag.lock.locktag_type == LOCKTAG_VIRTUALTRANSACTION)
3423 : 0 : continue;
3424 : :
3425 : : /* Ignore it if we don't actually hold the lock */
3426 [ - + ]: 932 : if (locallock->nLocks <= 0)
3427 : 0 : continue;
3428 : :
3429 : : /* Otherwise, find or make an entry in lockhtab */
3430 : 932 : hentry = (PerLockTagEntry *) hash_search(lockhtab,
3431 : 932 : &locallock->tag.lock,
3432 : : HASH_ENTER, &found);
3433 [ + + ]: 932 : if (!found) /* initialize, if newly created */
3434 : 839 : hentry->sessLock = hentry->xactLock = false;
3435 : :
3436 : : /* Scan to see if we hold lock at session or xact level or both */
3437 [ + + ]: 1864 : for (i = locallock->numLockOwners - 1; i >= 0; i--)
3438 : : {
3439 [ + + ]: 932 : if (lockOwners[i].owner == NULL)
3440 : 10 : hentry->sessLock = true;
3441 : : else
3442 : 922 : hentry->xactLock = true;
3443 : : }
3444 : :
3445 : : /*
3446 : : * We can throw error immediately when we see both types of locks; no
3447 : : * need to wait around to see if there are more violations.
3448 : : */
3449 [ + + + + ]: 932 : if (hentry->sessLock && hentry->xactLock)
3450 [ + - ]: 2 : ereport(ERROR,
3451 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3452 : : errmsg("cannot PREPARE while holding both session-level and transaction-level locks on the same object")));
3453 : : }
3454 : :
3455 : : /* Success, so clean up */
3456 : 330 : hash_destroy(lockhtab);
3457 : 330 : }
3458 : :
3459 : : /*
3460 : : * AtPrepare_Locks
3461 : : * Do the preparatory work for a PREPARE: make 2PC state file records
3462 : : * for all locks currently held.
3463 : : *
3464 : : * Session-level locks are ignored, as are VXID locks.
3465 : : *
3466 : : * For the most part, we don't need to touch shared memory for this ---
3467 : : * all the necessary state information is in the locallock table.
3468 : : * Fast-path locks are an exception, however: we move any such locks to
3469 : : * the main table before allowing PREPARE TRANSACTION to succeed.
3470 : : */
3471 : : void
3472 : 332 : AtPrepare_Locks(void)
3473 : : {
3474 : : HASH_SEQ_STATUS status;
3475 : : LOCALLOCK *locallock;
3476 : :
3477 : : /* First, verify there aren't locks of both xact and session level */
3478 : 332 : CheckForSessionAndXactLocks();
3479 : :
3480 : : /* Now do the per-locallock cleanup work */
3481 : 330 : hash_seq_init(&status, LockMethodLocalHash);
3482 : :
3483 [ + + ]: 1257 : while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
3484 : : {
3485 : : TwoPhaseLockRecord record;
3486 : 927 : LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
3487 : : bool haveSessionLock;
3488 : : bool haveXactLock;
3489 : : int i;
3490 : :
3491 : : /*
3492 : : * Ignore VXID locks. We don't want those to be held by prepared
3493 : : * transactions, since they aren't meaningful after a restart.
3494 : : */
3495 [ - + ]: 927 : if (locallock->tag.lock.locktag_type == LOCKTAG_VIRTUALTRANSACTION)
3496 : 8 : continue;
3497 : :
3498 : : /* Ignore it if we don't actually hold the lock */
3499 [ - + ]: 927 : if (locallock->nLocks <= 0)
3500 : 0 : continue;
3501 : :
3502 : : /* Scan to see whether we hold it at session or transaction level */
3503 : 927 : haveSessionLock = haveXactLock = false;
3504 [ + + ]: 1854 : for (i = locallock->numLockOwners - 1; i >= 0; i--)
3505 : : {
3506 [ + + ]: 927 : if (lockOwners[i].owner == NULL)
3507 : 8 : haveSessionLock = true;
3508 : : else
3509 : 919 : haveXactLock = true;
3510 : : }
3511 : :
3512 : : /* Ignore it if we have only session lock */
3513 [ + + ]: 927 : if (!haveXactLock)
3514 : 8 : continue;
3515 : :
3516 : : /* This can't happen, because we already checked it */
3517 [ - + ]: 919 : if (haveSessionLock)
3518 [ # # ]: 0 : ereport(ERROR,
3519 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3520 : : errmsg("cannot PREPARE while holding both session-level and transaction-level locks on the same object")));
3521 : :
3522 : : /*
3523 : : * If the local lock was taken via the fast-path, we need to move it
3524 : : * to the primary lock table, or just get a pointer to the existing
3525 : : * primary lock table entry if by chance it's already been
3526 : : * transferred.
3527 : : */
3528 [ + + ]: 919 : if (locallock->proclock == NULL)
3529 : : {
3530 : 354 : locallock->proclock = FastPathGetRelationLockEntry(locallock);
3531 : 354 : locallock->lock = locallock->proclock->tag.myLock;
3532 : : }
3533 : :
3534 : : /*
3535 : : * Arrange to not release any strong lock count held by this lock
3536 : : * entry. We must retain the count until the prepared transaction is
3537 : : * committed or rolled back.
3538 : : */
3539 : 919 : locallock->holdsStrongLockCount = false;
3540 : :
3541 : : /*
3542 : : * Create a 2PC record.
3543 : : */
3544 : 919 : memcpy(&(record.locktag), &(locallock->tag.lock), sizeof(LOCKTAG));
3545 : 919 : record.lockmode = locallock->tag.mode;
3546 : :
3547 : 919 : RegisterTwoPhaseRecord(TWOPHASE_RM_LOCK_ID, 0,
3548 : : &record, sizeof(TwoPhaseLockRecord));
3549 : : }
3550 : 330 : }
3551 : :
3552 : : /*
3553 : : * PostPrepare_Locks
3554 : : * Clean up after successful PREPARE
3555 : : *
3556 : : * Here, we want to transfer ownership of our locks to a dummy PGPROC
3557 : : * that's now associated with the prepared transaction, and we want to
3558 : : * clean out the corresponding entries in the LOCALLOCK table.
3559 : : *
3560 : : * Note: by removing the LOCALLOCK entries, we are leaving dangling
3561 : : * pointers in the transaction's resource owner. This is OK at the
3562 : : * moment since resowner.c doesn't try to free locks retail at a toplevel
3563 : : * transaction commit or abort. We could alternatively zero out nLocks
3564 : : * and leave the LOCALLOCK entries to be garbage-collected by LockReleaseAll,
3565 : : * but that probably costs more cycles.
3566 : : */
3567 : : void
3568 : 330 : PostPrepare_Locks(FullTransactionId fxid)
3569 : : {
3570 : 330 : PGPROC *newproc = TwoPhaseGetDummyProc(fxid, false);
3571 : : HASH_SEQ_STATUS status;
3572 : : LOCALLOCK *locallock;
3573 : : LOCK *lock;
3574 : : PROCLOCK *proclock;
3575 : : PROCLOCKTAG proclocktag;
3576 : : int partition;
3577 : :
3578 : : /* Can't prepare a lock group follower. */
3579 : : Assert(MyProc->lockGroupLeader == NULL ||
3580 : : MyProc->lockGroupLeader == MyProc);
3581 : :
3582 : : /* This is a critical section: any error means big trouble */
3583 : 330 : START_CRIT_SECTION();
3584 : :
3585 : : /*
3586 : : * First we run through the locallock table and get rid of unwanted
3587 : : * entries, then we scan the process's proclocks and transfer them to the
3588 : : * target proc.
3589 : : *
3590 : : * We do this separately because we may have multiple locallock entries
3591 : : * pointing to the same proclock, and we daren't end up with any dangling
3592 : : * pointers.
3593 : : */
3594 : 330 : hash_seq_init(&status, LockMethodLocalHash);
3595 : :
3596 [ + + ]: 1257 : while ((locallock = (LOCALLOCK *) hash_seq_search(&status)) != NULL)
3597 : : {
3598 : 927 : LOCALLOCKOWNER *lockOwners = locallock->lockOwners;
3599 : : bool haveSessionLock;
3600 : : bool haveXactLock;
3601 : : int i;
3602 : :
3603 [ + - - + ]: 927 : if (locallock->proclock == NULL || locallock->lock == NULL)
3604 : : {
3605 : : /*
3606 : : * We must've run out of shared memory while trying to set up this
3607 : : * lock. Just forget the local entry.
3608 : : */
3609 : : Assert(locallock->nLocks == 0);
3610 : 0 : RemoveLocalLock(locallock);
3611 : 0 : continue;
3612 : : }
3613 : :
3614 : : /* Ignore VXID locks */
3615 [ - + ]: 927 : if (locallock->tag.lock.locktag_type == LOCKTAG_VIRTUALTRANSACTION)
3616 : 0 : continue;
3617 : :
3618 : : /* Scan to see whether we hold it at session or transaction level */
3619 : 927 : haveSessionLock = haveXactLock = false;
3620 [ + + ]: 1854 : for (i = locallock->numLockOwners - 1; i >= 0; i--)
3621 : : {
3622 [ + + ]: 927 : if (lockOwners[i].owner == NULL)
3623 : 8 : haveSessionLock = true;
3624 : : else
3625 : 919 : haveXactLock = true;
3626 : : }
3627 : :
3628 : : /* Ignore it if we have only session lock */
3629 [ + + ]: 927 : if (!haveXactLock)
3630 : 8 : continue;
3631 : :
3632 : : /* This can't happen, because we already checked it */
3633 [ - + ]: 919 : if (haveSessionLock)
3634 [ # # ]: 0 : ereport(PANIC,
3635 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3636 : : errmsg("cannot PREPARE while holding both session-level and transaction-level locks on the same object")));
3637 : :
3638 : : /* Mark the proclock to show we need to release this lockmode */
3639 [ + - ]: 919 : if (locallock->nLocks > 0)
3640 : 919 : locallock->proclock->releaseMask |= LOCKBIT_ON(locallock->tag.mode);
3641 : :
3642 : : /* And remove the locallock hashtable entry */
3643 : 919 : RemoveLocalLock(locallock);
3644 : : }
3645 : :
3646 : : /*
3647 : : * Now, scan each lock partition separately.
3648 : : */
3649 [ + + ]: 5610 : for (partition = 0; partition < NUM_LOCK_PARTITIONS; partition++)
3650 : : {
3651 : : LWLock *partitionLock;
3652 : 5280 : dlist_head *procLocks = &(MyProc->myProcLocks[partition]);
3653 : : dlist_mutable_iter proclock_iter;
3654 : :
3655 : 5280 : partitionLock = LockHashPartitionLockByIndex(partition);
3656 : :
3657 : : /*
3658 : : * If the proclock list for this partition is empty, we can skip
3659 : : * acquiring the partition lock. This optimization is safer than the
3660 : : * situation in LockReleaseAll, because we got rid of any fast-path
3661 : : * locks during AtPrepare_Locks, so there cannot be any case where
3662 : : * another backend is adding something to our lists now. For safety,
3663 : : * though, we code this the same way as in LockReleaseAll.
3664 : : */
3665 [ + + ]: 5280 : if (dlist_is_empty(procLocks))
3666 : 4472 : continue; /* needn't examine this partition */
3667 : :
3668 : 808 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
3669 : :
3670 [ + - + + ]: 1686 : dlist_foreach_modify(proclock_iter, procLocks)
3671 : : {
3672 : 878 : proclock = dlist_container(PROCLOCK, procLink, proclock_iter.cur);
3673 : :
3674 : : Assert(proclock->tag.myProc == MyProc);
3675 : :
3676 : 878 : lock = proclock->tag.myLock;
3677 : :
3678 : : /* Ignore VXID locks */
3679 [ + + ]: 878 : if (lock->tag.locktag_type == LOCKTAG_VIRTUALTRANSACTION)
3680 : 42 : continue;
3681 : :
3682 : : PROCLOCK_PRINT("PostPrepare_Locks", proclock);
3683 : : LOCK_PRINT("PostPrepare_Locks", lock, 0);
3684 : : Assert(lock->nRequested >= 0);
3685 : : Assert(lock->nGranted >= 0);
3686 : : Assert(lock->nGranted <= lock->nRequested);
3687 : : Assert((proclock->holdMask & ~lock->grantMask) == 0);
3688 : :
3689 : : /* Ignore it if nothing to release (must be a session lock) */
3690 [ + + ]: 836 : if (proclock->releaseMask == 0)
3691 : 8 : continue;
3692 : :
3693 : : /* Else we should be releasing all locks */
3694 [ - + ]: 828 : if (proclock->releaseMask != proclock->holdMask)
3695 [ # # ]: 0 : elog(PANIC, "we seem to have dropped a bit somewhere");
3696 : :
3697 : : /*
3698 : : * We cannot simply modify proclock->tag.myProc to reassign
3699 : : * ownership of the lock, because that's part of the hash key and
3700 : : * the proclock would then be in the wrong hash chain. Instead
3701 : : * use hash_update_hash_key. (We used to create a new hash entry,
3702 : : * but that risks out-of-memory failure if other processes are
3703 : : * busy making proclocks too.) We must unlink the proclock from
3704 : : * our procLink chain and put it into the new proc's chain, too.
3705 : : *
3706 : : * Note: the updated proclock hash key will still belong to the
3707 : : * same hash partition, cf proclock_hash(). So the partition lock
3708 : : * we already hold is sufficient for this.
3709 : : */
3710 : 828 : dlist_delete(&proclock->procLink);
3711 : :
3712 : : /*
3713 : : * Create the new hash key for the proclock.
3714 : : */
3715 : 828 : proclocktag.myLock = lock;
3716 : 828 : proclocktag.myProc = newproc;
3717 : :
3718 : : /*
3719 : : * Update groupLeader pointer to point to the new proc. (We'd
3720 : : * better not be a member of somebody else's lock group!)
3721 : : */
3722 : : Assert(proclock->groupLeader == proclock->tag.myProc);
3723 : 828 : proclock->groupLeader = newproc;
3724 : :
3725 : : /*
3726 : : * Update the proclock. We should not find any existing entry for
3727 : : * the same hash key, since there can be only one entry for any
3728 : : * given lock with my own proc.
3729 : : */
3730 [ - + ]: 828 : if (!hash_update_hash_key(LockMethodProcLockHash,
3731 : : proclock,
3732 : : &proclocktag))
3733 [ # # ]: 0 : elog(PANIC, "duplicate entry found while reassigning a prepared transaction's locks");
3734 : :
3735 : : /* Re-link into the new proc's proclock list */
3736 : 828 : dlist_push_tail(&newproc->myProcLocks[partition], &proclock->procLink);
3737 : :
3738 : : PROCLOCK_PRINT("PostPrepare_Locks: updated", proclock);
3739 : : } /* loop over PROCLOCKs within this partition */
3740 : :
3741 : 808 : LWLockRelease(partitionLock);
3742 : : } /* loop over partitions */
3743 : :
3744 : 330 : END_CRIT_SECTION();
3745 : 330 : }
3746 : :
3747 : :
3748 : : /*
3749 : : * GetLockStatusData - Return a summary of the lock manager's internal
3750 : : * status, for use in a user-level reporting function.
3751 : : *
3752 : : * The return data consists of an array of LockInstanceData objects,
3753 : : * which are a lightly abstracted version of the PROCLOCK data structures,
3754 : : * i.e. there is one entry for each unique lock and interested PGPROC.
3755 : : * It is the caller's responsibility to match up related items (such as
3756 : : * references to the same lockable object or PGPROC) if wanted.
3757 : : *
3758 : : * The design goal is to hold the LWLocks for as short a time as possible;
3759 : : * thus, this function simply makes a copy of the necessary data and releases
3760 : : * the locks, allowing the caller to contemplate and format the data for as
3761 : : * long as it pleases.
3762 : : */
3763 : : LockData *
3764 : 298 : GetLockStatusData(void)
3765 : : {
3766 : : LockData *data;
3767 : : PROCLOCK *proclock;
3768 : : HASH_SEQ_STATUS seqstat;
3769 : : int els;
3770 : : int el;
3771 : :
3772 : 298 : data = palloc_object(LockData);
3773 : :
3774 : : /* Guess how much space we'll need. */
3775 : 298 : els = MaxBackends;
3776 : 298 : el = 0;
3777 : 298 : data->locks = palloc_array(LockInstanceData, els);
3778 : :
3779 : : /*
3780 : : * First, we iterate through the per-backend fast-path arrays, locking
3781 : : * them one at a time. This might produce an inconsistent picture of the
3782 : : * system state, but taking all of those LWLocks at the same time seems
3783 : : * impractical (in particular, note MAX_SIMUL_LWLOCKS). It shouldn't
3784 : : * matter too much, because none of these locks can be involved in lock
3785 : : * conflicts anyway - anything that might must be present in the main lock
3786 : : * table. (For the same reason, we don't sweat about making leaderPid
3787 : : * completely valid. We cannot safely dereference another backend's
3788 : : * lockGroupLeader field without holding all lock partition locks, and
3789 : : * it's not worth that.)
3790 : : */
3791 [ + + ]: 44324 : for (uint32 i = 0; i < ProcGlobal->allProcCount; ++i)
3792 : : {
3793 : 44026 : PGPROC *proc = GetPGProcByNumber(i);
3794 : :
3795 : : /* Skip backends with pid=0, as they don't hold fast-path locks */
3796 [ + + ]: 44026 : if (proc->pid == 0)
3797 : 39573 : continue;
3798 : :
3799 : 4453 : LWLockAcquire(&proc->fpInfoLock, LW_SHARED);
3800 : :
3801 [ + + ]: 40077 : for (uint32 g = 0; g < FastPathLockGroupsPerBackend; g++)
3802 : : {
3803 : : /* Skip groups without registered fast-path locks */
3804 [ + + ]: 35624 : if (proc->fpLockBits[g] == 0)
3805 : 32575 : continue;
3806 : :
3807 [ + + ]: 51833 : for (int j = 0; j < FP_LOCK_SLOTS_PER_GROUP; j++)
3808 : : {
3809 : : LockInstanceData *instance;
3810 : 48784 : uint32 f = FAST_PATH_SLOT(g, j);
3811 : 48784 : uint32 lockbits = FAST_PATH_GET_BITS(proc, f);
3812 : :
3813 : : /* Skip unallocated slots */
3814 [ + + ]: 48784 : if (!lockbits)
3815 : 44341 : continue;
3816 : :
3817 [ + + ]: 4443 : if (el >= els)
3818 : : {
3819 : 5 : els += MaxBackends;
3820 : 5 : data->locks = repalloc_array(data->locks, LockInstanceData, els);
3821 : : }
3822 : :
3823 : 4443 : instance = &data->locks[el];
3824 : 4443 : SET_LOCKTAG_RELATION(instance->locktag, proc->databaseId,
3825 : : proc->fpRelId[f]);
3826 : 4443 : instance->holdMask = lockbits << FAST_PATH_LOCKNUMBER_OFFSET;
3827 : 4443 : instance->waitLockMode = NoLock;
3828 : 4443 : instance->vxid.procNumber = proc->vxid.procNumber;
3829 : 4443 : instance->vxid.localTransactionId = proc->vxid.lxid;
3830 : 4443 : instance->pid = proc->pid;
3831 : 4443 : instance->leaderPid = proc->pid;
3832 : 4443 : instance->fastpath = true;
3833 : :
3834 : : /*
3835 : : * Successfully taking fast path lock means there were no
3836 : : * conflicting locks.
3837 : : */
3838 : 4443 : instance->waitStart = 0;
3839 : :
3840 : 4443 : el++;
3841 : : }
3842 : : }
3843 : :
3844 [ + + ]: 4453 : if (proc->fpVXIDLock)
3845 : : {
3846 : : VirtualTransactionId vxid;
3847 : : LockInstanceData *instance;
3848 : :
3849 [ + + ]: 1387 : if (el >= els)
3850 : : {
3851 : 5 : els += MaxBackends;
3852 : 5 : data->locks = repalloc_array(data->locks, LockInstanceData, els);
3853 : : }
3854 : :
3855 : 1387 : vxid.procNumber = proc->vxid.procNumber;
3856 : 1387 : vxid.localTransactionId = proc->fpLocalTransactionId;
3857 : :
3858 : 1387 : instance = &data->locks[el];
3859 : 1387 : SET_LOCKTAG_VIRTUALTRANSACTION(instance->locktag, vxid);
3860 : 1387 : instance->holdMask = LOCKBIT_ON(ExclusiveLock);
3861 : 1387 : instance->waitLockMode = NoLock;
3862 : 1387 : instance->vxid.procNumber = proc->vxid.procNumber;
3863 : 1387 : instance->vxid.localTransactionId = proc->vxid.lxid;
3864 : 1387 : instance->pid = proc->pid;
3865 : 1387 : instance->leaderPid = proc->pid;
3866 : 1387 : instance->fastpath = true;
3867 : 1387 : instance->waitStart = 0;
3868 : :
3869 : 1387 : el++;
3870 : : }
3871 : :
3872 : 4453 : LWLockRelease(&proc->fpInfoLock);
3873 : : }
3874 : :
3875 : : /*
3876 : : * Next, acquire lock on the entire shared lock data structure. We do
3877 : : * this so that, at least for locks in the primary lock table, the state
3878 : : * will be self-consistent.
3879 : : *
3880 : : * Since this is a read-only operation, we take shared instead of
3881 : : * exclusive lock. There's not a whole lot of point to this, because all
3882 : : * the normal operations require exclusive lock, but it doesn't hurt
3883 : : * anything either. It will at least allow two backends to do
3884 : : * GetLockStatusData in parallel.
3885 : : *
3886 : : * Must grab LWLocks in partition-number order to avoid LWLock deadlock.
3887 : : */
3888 [ + + ]: 5066 : for (int i = 0; i < NUM_LOCK_PARTITIONS; i++)
3889 : 4768 : LWLockAcquire(LockHashPartitionLockByIndex(i), LW_SHARED);
3890 : :
3891 : : /* Now we can safely count the number of proclocks */
3892 : 298 : data->nelements = el + hash_get_num_entries(LockMethodProcLockHash);
3893 [ + + ]: 298 : if (data->nelements > els)
3894 : : {
3895 : 26 : els = data->nelements;
3896 : 26 : data->locks = repalloc_array(data->locks, LockInstanceData, els);
3897 : : }
3898 : :
3899 : : /* Now scan the tables to copy the data */
3900 : 298 : hash_seq_init(&seqstat, LockMethodProcLockHash);
3901 : :
3902 [ + + ]: 4275 : while ((proclock = (PROCLOCK *) hash_seq_search(&seqstat)))
3903 : : {
3904 : 3977 : PGPROC *proc = proclock->tag.myProc;
3905 : 3977 : LOCK *lock = proclock->tag.myLock;
3906 : 3977 : LockInstanceData *instance = &data->locks[el];
3907 : :
3908 : 3977 : memcpy(&instance->locktag, &lock->tag, sizeof(LOCKTAG));
3909 : 3977 : instance->holdMask = proclock->holdMask;
3910 [ + + ]: 3977 : if (proc->waitLock == proclock->tag.myLock)
3911 : 11 : instance->waitLockMode = proc->waitLockMode;
3912 : : else
3913 : 3966 : instance->waitLockMode = NoLock;
3914 : 3977 : instance->vxid.procNumber = proc->vxid.procNumber;
3915 : 3977 : instance->vxid.localTransactionId = proc->vxid.lxid;
3916 : 3977 : instance->pid = proc->pid;
3917 : 3977 : instance->leaderPid = proclock->groupLeader->pid;
3918 : 3977 : instance->fastpath = false;
3919 : 3977 : instance->waitStart = (TimestampTz) pg_atomic_read_u64(&proc->waitStart);
3920 : :
3921 : 3977 : el++;
3922 : : }
3923 : :
3924 : : /*
3925 : : * And release locks. We do this in reverse order for two reasons: (1)
3926 : : * Anyone else who needs more than one of the locks will be trying to lock
3927 : : * them in increasing order; we don't want to release the other process
3928 : : * until it can get all the locks it needs. (2) This avoids O(N^2)
3929 : : * behavior inside LWLockRelease.
3930 : : */
3931 [ + + ]: 5066 : for (int i = NUM_LOCK_PARTITIONS; --i >= 0;)
3932 : 4768 : LWLockRelease(LockHashPartitionLockByIndex(i));
3933 : :
3934 : : Assert(el == data->nelements);
3935 : :
3936 : 298 : return data;
3937 : : }
3938 : :
3939 : : /*
3940 : : * GetBlockerStatusData - Return a summary of the lock manager's state
3941 : : * concerning locks that are blocking the specified PID or any member of
3942 : : * the PID's lock group, for use in a user-level reporting function.
3943 : : *
3944 : : * For each PID within the lock group that is awaiting some heavyweight lock,
3945 : : * the return data includes an array of LockInstanceData objects, which are
3946 : : * the same data structure used by GetLockStatusData; but unlike that function,
3947 : : * this one reports only the PROCLOCKs associated with the lock that that PID
3948 : : * is blocked on. (Hence, all the locktags should be the same for any one
3949 : : * blocked PID.) In addition, we return an array of the PIDs of those backends
3950 : : * that are ahead of the blocked PID in the lock's wait queue. These can be
3951 : : * compared with the PIDs in the LockInstanceData objects to determine which
3952 : : * waiters are ahead of or behind the blocked PID in the queue.
3953 : : *
3954 : : * If blocked_pid isn't a valid backend PID or nothing in its lock group is
3955 : : * waiting on any heavyweight lock, return empty arrays.
3956 : : *
3957 : : * The design goal is to hold the LWLocks for as short a time as possible;
3958 : : * thus, this function simply makes a copy of the necessary data and releases
3959 : : * the locks, allowing the caller to contemplate and format the data for as
3960 : : * long as it pleases.
3961 : : */
3962 : : BlockedProcsData *
3963 : 1677 : GetBlockerStatusData(int blocked_pid)
3964 : : {
3965 : : BlockedProcsData *data;
3966 : : PGPROC *proc;
3967 : : int i;
3968 : :
3969 : 1677 : data = palloc_object(BlockedProcsData);
3970 : :
3971 : : /*
3972 : : * Guess how much space we'll need, and preallocate. Most of the time
3973 : : * this will avoid needing to do repalloc while holding the LWLocks. (We
3974 : : * assume, but check with an Assert, that MaxBackends is enough entries
3975 : : * for the procs[] array; the other two could need enlargement, though.)
3976 : : */
3977 : 1677 : data->nprocs = data->nlocks = data->npids = 0;
3978 : 1677 : data->maxprocs = data->maxlocks = data->maxpids = MaxBackends;
3979 : 1677 : data->procs = palloc_array(BlockedProcData, data->maxprocs);
3980 : 1677 : data->locks = palloc_array(LockInstanceData, data->maxlocks);
3981 : 1677 : data->waiter_pids = palloc_array(int, data->maxpids);
3982 : :
3983 : : /*
3984 : : * In order to search the ProcArray for blocked_pid and assume that that
3985 : : * entry won't immediately disappear under us, we must hold ProcArrayLock.
3986 : : * In addition, to examine the lock grouping fields of any other backend,
3987 : : * we must hold all the hash partition locks. (Only one of those locks is
3988 : : * actually relevant for any one lock group, but we can't know which one
3989 : : * ahead of time.) It's fairly annoying to hold all those locks
3990 : : * throughout this, but it's no worse than GetLockStatusData(), and it
3991 : : * does have the advantage that we're guaranteed to return a
3992 : : * self-consistent instantaneous state.
3993 : : */
3994 : 1677 : LWLockAcquire(ProcArrayLock, LW_SHARED);
3995 : :
3996 : 1677 : proc = BackendPidGetProcWithLock(blocked_pid);
3997 : :
3998 : : /* Nothing to do if it's gone */
3999 [ + - ]: 1677 : if (proc != NULL)
4000 : : {
4001 : : /*
4002 : : * Acquire lock on the entire shared lock data structure. See notes
4003 : : * in GetLockStatusData().
4004 : : */
4005 [ + + ]: 28509 : for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
4006 : 26832 : LWLockAcquire(LockHashPartitionLockByIndex(i), LW_SHARED);
4007 : :
4008 [ + + ]: 1677 : if (proc->lockGroupLeader == NULL)
4009 : : {
4010 : : /* Easy case, proc is not a lock group member */
4011 : 1504 : GetSingleProcBlockerStatusData(proc, data);
4012 : : }
4013 : : else
4014 : : {
4015 : : /* Examine all procs in proc's lock group */
4016 : : dlist_iter iter;
4017 : :
4018 [ + - + + ]: 415 : dlist_foreach(iter, &proc->lockGroupLeader->lockGroupMembers)
4019 : : {
4020 : : PGPROC *memberProc;
4021 : :
4022 : 242 : memberProc = dlist_container(PGPROC, lockGroupLink, iter.cur);
4023 : 242 : GetSingleProcBlockerStatusData(memberProc, data);
4024 : : }
4025 : : }
4026 : :
4027 : : /*
4028 : : * And release locks. See notes in GetLockStatusData().
4029 : : */
4030 [ + + ]: 28509 : for (i = NUM_LOCK_PARTITIONS; --i >= 0;)
4031 : 26832 : LWLockRelease(LockHashPartitionLockByIndex(i));
4032 : :
4033 : : Assert(data->nprocs <= data->maxprocs);
4034 : : }
4035 : :
4036 : 1677 : LWLockRelease(ProcArrayLock);
4037 : :
4038 : 1677 : return data;
4039 : : }
4040 : :
4041 : : /* Accumulate data about one possibly-blocked proc for GetBlockerStatusData */
4042 : : static void
4043 : 1746 : GetSingleProcBlockerStatusData(PGPROC *blocked_proc, BlockedProcsData *data)
4044 : : {
4045 : 1746 : LOCK *theLock = blocked_proc->waitLock;
4046 : : BlockedProcData *bproc;
4047 : : dlist_iter proclock_iter;
4048 : : dlist_iter proc_iter;
4049 : : dclist_head *waitQueue;
4050 : : int queue_size;
4051 : :
4052 : : /* Nothing to do if this proc is not blocked */
4053 [ + + ]: 1746 : if (theLock == NULL)
4054 : 478 : return;
4055 : :
4056 : : /* Set up a procs[] element */
4057 : 1268 : bproc = &data->procs[data->nprocs++];
4058 : 1268 : bproc->pid = blocked_proc->pid;
4059 : 1268 : bproc->first_lock = data->nlocks;
4060 : 1268 : bproc->first_waiter = data->npids;
4061 : :
4062 : : /*
4063 : : * We may ignore the proc's fast-path arrays, since nothing in those could
4064 : : * be related to a contended lock.
4065 : : */
4066 : :
4067 : : /* Collect all PROCLOCKs associated with theLock */
4068 [ + - + + ]: 3851 : dlist_foreach(proclock_iter, &theLock->procLocks)
4069 : : {
4070 : 2583 : PROCLOCK *proclock =
4071 : 2583 : dlist_container(PROCLOCK, lockLink, proclock_iter.cur);
4072 : 2583 : PGPROC *proc = proclock->tag.myProc;
4073 : 2583 : LOCK *lock = proclock->tag.myLock;
4074 : : LockInstanceData *instance;
4075 : :
4076 [ - + ]: 2583 : if (data->nlocks >= data->maxlocks)
4077 : : {
4078 : 0 : data->maxlocks += MaxBackends;
4079 : 0 : data->locks = repalloc_array(data->locks, LockInstanceData, data->maxlocks);
4080 : : }
4081 : :
4082 : 2583 : instance = &data->locks[data->nlocks];
4083 : 2583 : memcpy(&instance->locktag, &lock->tag, sizeof(LOCKTAG));
4084 : 2583 : instance->holdMask = proclock->holdMask;
4085 [ + + ]: 2583 : if (proc->waitLock == lock)
4086 : 1310 : instance->waitLockMode = proc->waitLockMode;
4087 : : else
4088 : 1273 : instance->waitLockMode = NoLock;
4089 : 2583 : instance->vxid.procNumber = proc->vxid.procNumber;
4090 : 2583 : instance->vxid.localTransactionId = proc->vxid.lxid;
4091 : 2583 : instance->pid = proc->pid;
4092 : 2583 : instance->leaderPid = proclock->groupLeader->pid;
4093 : 2583 : instance->fastpath = false;
4094 : 2583 : data->nlocks++;
4095 : : }
4096 : :
4097 : : /* Enlarge waiter_pids[] if it's too small to hold all wait queue PIDs */
4098 : 1268 : waitQueue = &(theLock->waitProcs);
4099 : 1268 : queue_size = dclist_count(waitQueue);
4100 : :
4101 [ - + ]: 1268 : if (queue_size > data->maxpids - data->npids)
4102 : : {
4103 : 0 : data->maxpids = Max(data->maxpids + MaxBackends,
4104 : : data->npids + queue_size);
4105 : 0 : data->waiter_pids = repalloc_array(data->waiter_pids, int, data->maxpids);
4106 : : }
4107 : :
4108 : : /* Collect PIDs from the lock's wait queue, stopping at blocked_proc */
4109 [ + - + - ]: 1288 : dclist_foreach(proc_iter, waitQueue)
4110 : : {
4111 : 1288 : PGPROC *queued_proc = dlist_container(PGPROC, waitLink, proc_iter.cur);
4112 : :
4113 [ + + ]: 1288 : if (queued_proc == blocked_proc)
4114 : 1268 : break;
4115 : 20 : data->waiter_pids[data->npids++] = queued_proc->pid;
4116 : : }
4117 : :
4118 : 1268 : bproc->num_locks = data->nlocks - bproc->first_lock;
4119 : 1268 : bproc->num_waiters = data->npids - bproc->first_waiter;
4120 : : }
4121 : :
4122 : : /*
4123 : : * Returns a list of currently held AccessExclusiveLocks, for use by
4124 : : * LogStandbySnapshot(). The result is a palloc'd array,
4125 : : * with the number of elements returned into *nlocks.
4126 : : *
4127 : : * XXX This currently takes a lock on all partitions of the lock table,
4128 : : * but it's possible to do better. By reference counting locks and storing
4129 : : * the value in the ProcArray entry for each backend we could tell if any
4130 : : * locks need recording without having to acquire the partition locks and
4131 : : * scan the lock table. Whether that's worth the additional overhead
4132 : : * is pretty dubious though.
4133 : : */
4134 : : xl_standby_lock *
4135 : 1538 : GetRunningTransactionLocks(int *nlocks)
4136 : : {
4137 : : xl_standby_lock *accessExclusiveLocks;
4138 : : PROCLOCK *proclock;
4139 : : HASH_SEQ_STATUS seqstat;
4140 : : int i;
4141 : : int index;
4142 : : int els;
4143 : :
4144 : : /*
4145 : : * Acquire lock on the entire shared lock data structure.
4146 : : *
4147 : : * Must grab LWLocks in partition-number order to avoid LWLock deadlock.
4148 : : */
4149 [ + + ]: 26146 : for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
4150 : 24608 : LWLockAcquire(LockHashPartitionLockByIndex(i), LW_SHARED);
4151 : :
4152 : : /* Now we can safely count the number of proclocks */
4153 : 1538 : els = hash_get_num_entries(LockMethodProcLockHash);
4154 : :
4155 : : /*
4156 : : * Allocating enough space for all locks in the lock table is overkill,
4157 : : * but it's more convenient and faster than having to enlarge the array.
4158 : : */
4159 : 1538 : accessExclusiveLocks = palloc_array(xl_standby_lock, els);
4160 : :
4161 : : /* Now scan the tables to copy the data */
4162 : 1538 : hash_seq_init(&seqstat, LockMethodProcLockHash);
4163 : :
4164 : : /*
4165 : : * If lock is a currently granted AccessExclusiveLock then it will have
4166 : : * just one proclock holder, so locks are never accessed twice in this
4167 : : * particular case. Don't copy this code for use elsewhere because in the
4168 : : * general case this will give you duplicate locks when looking at
4169 : : * non-exclusive lock types.
4170 : : */
4171 : 1538 : index = 0;
4172 [ + + ]: 7870 : while ((proclock = (PROCLOCK *) hash_seq_search(&seqstat)))
4173 : : {
4174 : : /* make sure this definition matches the one used in LockAcquire */
4175 [ + + ]: 6332 : if ((proclock->holdMask & LOCKBIT_ON(AccessExclusiveLock)) &&
4176 [ + + ]: 2584 : proclock->tag.myLock->tag.locktag_type == LOCKTAG_RELATION)
4177 : : {
4178 : 1681 : PGPROC *proc = proclock->tag.myProc;
4179 : 1681 : LOCK *lock = proclock->tag.myLock;
4180 : 1681 : TransactionId xid = proc->xid;
4181 : :
4182 : : /*
4183 : : * Don't record locks for transactions if we know they have
4184 : : * already issued their WAL record for commit but not yet released
4185 : : * lock. It is still possible that we see locks held by already
4186 : : * complete transactions, if they haven't yet zeroed their xids.
4187 : : */
4188 [ - + ]: 1681 : if (!TransactionIdIsValid(xid))
4189 : 0 : continue;
4190 : :
4191 : 1681 : accessExclusiveLocks[index].xid = xid;
4192 : 1681 : accessExclusiveLocks[index].dbOid = lock->tag.locktag_field1;
4193 : 1681 : accessExclusiveLocks[index].relOid = lock->tag.locktag_field2;
4194 : :
4195 : 1681 : index++;
4196 : : }
4197 : : }
4198 : :
4199 : : Assert(index <= els);
4200 : :
4201 : : /*
4202 : : * And release locks. We do this in reverse order for two reasons: (1)
4203 : : * Anyone else who needs more than one of the locks will be trying to lock
4204 : : * them in increasing order; we don't want to release the other process
4205 : : * until it can get all the locks it needs. (2) This avoids O(N^2)
4206 : : * behavior inside LWLockRelease.
4207 : : */
4208 [ + + ]: 26146 : for (i = NUM_LOCK_PARTITIONS; --i >= 0;)
4209 : 24608 : LWLockRelease(LockHashPartitionLockByIndex(i));
4210 : :
4211 : 1538 : *nlocks = index;
4212 : 1538 : return accessExclusiveLocks;
4213 : : }
4214 : :
4215 : : /* Provide the textual name of any lock mode */
4216 : : const char *
4217 : 12128 : GetLockmodeName(LOCKMETHODID lockmethodid, LOCKMODE mode)
4218 : : {
4219 : : Assert(lockmethodid > 0 && lockmethodid < lengthof(LockMethods));
4220 : : Assert(mode > 0 && mode <= LockMethods[lockmethodid]->numLockModes);
4221 : 12128 : return LockMethods[lockmethodid]->lockModeNames[mode];
4222 : : }
4223 : :
4224 : : #ifdef LOCK_DEBUG
4225 : : /*
4226 : : * Dump all locks in the given proc's myProcLocks lists.
4227 : : *
4228 : : * Caller is responsible for having acquired appropriate LWLocks.
4229 : : */
4230 : : void
4231 : : DumpLocks(PGPROC *proc)
4232 : : {
4233 : : int i;
4234 : :
4235 : : if (proc == NULL)
4236 : : return;
4237 : :
4238 : : if (proc->waitLock)
4239 : : LOCK_PRINT("DumpLocks: waiting on", proc->waitLock, 0);
4240 : :
4241 : : for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
4242 : : {
4243 : : dlist_head *procLocks = &proc->myProcLocks[i];
4244 : : dlist_iter iter;
4245 : :
4246 : : dlist_foreach(iter, procLocks)
4247 : : {
4248 : : PROCLOCK *proclock = dlist_container(PROCLOCK, procLink, iter.cur);
4249 : : LOCK *lock = proclock->tag.myLock;
4250 : :
4251 : : Assert(proclock->tag.myProc == proc);
4252 : : PROCLOCK_PRINT("DumpLocks", proclock);
4253 : : LOCK_PRINT("DumpLocks", lock, 0);
4254 : : }
4255 : : }
4256 : : }
4257 : :
4258 : : /*
4259 : : * Dump all lmgr locks.
4260 : : *
4261 : : * Caller is responsible for having acquired appropriate LWLocks.
4262 : : */
4263 : : void
4264 : : DumpAllLocks(void)
4265 : : {
4266 : : PGPROC *proc;
4267 : : PROCLOCK *proclock;
4268 : : LOCK *lock;
4269 : : HASH_SEQ_STATUS status;
4270 : :
4271 : : proc = MyProc;
4272 : :
4273 : : if (proc && proc->waitLock)
4274 : : LOCK_PRINT("DumpAllLocks: waiting on", proc->waitLock, 0);
4275 : :
4276 : : hash_seq_init(&status, LockMethodProcLockHash);
4277 : :
4278 : : while ((proclock = (PROCLOCK *) hash_seq_search(&status)) != NULL)
4279 : : {
4280 : : PROCLOCK_PRINT("DumpAllLocks", proclock);
4281 : :
4282 : : lock = proclock->tag.myLock;
4283 : : if (lock)
4284 : : LOCK_PRINT("DumpAllLocks", lock, 0);
4285 : : else
4286 : : elog(LOG, "DumpAllLocks: proclock->tag.myLock = NULL");
4287 : : }
4288 : : }
4289 : : #endif /* LOCK_DEBUG */
4290 : :
4291 : : /*
4292 : : * LOCK 2PC resource manager's routines
4293 : : */
4294 : :
4295 : : /*
4296 : : * Re-acquire a lock belonging to a transaction that was prepared.
4297 : : *
4298 : : * Because this function is run at db startup, re-acquiring the locks should
4299 : : * never conflict with running transactions because there are none. We
4300 : : * assume that the lock state represented by the stored 2PC files is legal.
4301 : : *
4302 : : * When switching from Hot Standby mode to normal operation, the locks will
4303 : : * be already held by the startup process. The locks are acquired for the new
4304 : : * procs without checking for conflicts, so we don't get a conflict between the
4305 : : * startup process and the dummy procs, even though we will momentarily have
4306 : : * a situation where two procs are holding the same AccessExclusiveLock,
4307 : : * which isn't normally possible because the conflict. If we're in standby
4308 : : * mode, but a recovery snapshot hasn't been established yet, it's possible
4309 : : * that some but not all of the locks are already held by the startup process.
4310 : : *
4311 : : * This approach is simple, but also a bit dangerous, because if there isn't
4312 : : * enough shared memory to acquire the locks, an error will be thrown, which
4313 : : * is promoted to FATAL and recovery will abort, bringing down postmaster.
4314 : : * A safer approach would be to transfer the locks like we do in
4315 : : * AtPrepare_Locks, but then again, in hot standby mode it's possible for
4316 : : * read-only backends to use up all the shared lock memory anyway, so that
4317 : : * replaying the WAL record that needs to acquire a lock will throw an error
4318 : : * and PANIC anyway.
4319 : : */
4320 : : void
4321 : 96 : lock_twophase_recover(FullTransactionId fxid, uint16 info,
4322 : : void *recdata, uint32 len)
4323 : : {
4324 : 96 : TwoPhaseLockRecord *rec = (TwoPhaseLockRecord *) recdata;
4325 : 96 : PGPROC *proc = TwoPhaseGetDummyProc(fxid, false);
4326 : : LOCKTAG *locktag;
4327 : : LOCKMODE lockmode;
4328 : : LOCKMETHODID lockmethodid;
4329 : : LOCK *lock;
4330 : : PROCLOCK *proclock;
4331 : : PROCLOCKTAG proclocktag;
4332 : : bool found;
4333 : : uint32 hashcode;
4334 : : uint32 proclock_hashcode;
4335 : : int partition;
4336 : : LWLock *partitionLock;
4337 : : LockMethod lockMethodTable;
4338 : :
4339 : : Assert(len == sizeof(TwoPhaseLockRecord));
4340 : 96 : locktag = &rec->locktag;
4341 : 96 : lockmode = rec->lockmode;
4342 : 96 : lockmethodid = locktag->locktag_lockmethodid;
4343 : :
4344 [ + - - + ]: 96 : if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
4345 [ # # ]: 0 : elog(ERROR, "unrecognized lock method: %d", lockmethodid);
4346 : 96 : lockMethodTable = LockMethods[lockmethodid];
4347 : :
4348 : 96 : hashcode = LockTagHashCode(locktag);
4349 : 96 : partition = LockHashPartition(hashcode);
4350 : 96 : partitionLock = LockHashPartitionLock(hashcode);
4351 : :
4352 : 96 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
4353 : :
4354 : : /*
4355 : : * Find or create a lock with this tag.
4356 : : */
4357 : 96 : lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
4358 : : locktag,
4359 : : hashcode,
4360 : : HASH_ENTER_NULL,
4361 : : &found);
4362 [ - + ]: 96 : if (!lock)
4363 : : {
4364 : 0 : LWLockRelease(partitionLock);
4365 [ # # ]: 0 : ereport(ERROR,
4366 : : (errcode(ERRCODE_OUT_OF_MEMORY),
4367 : : errmsg("out of shared memory"),
4368 : : errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
4369 : : }
4370 : :
4371 : : /*
4372 : : * if it's a new lock object, initialize it
4373 : : */
4374 [ + + ]: 96 : if (!found)
4375 : : {
4376 : 84 : lock->grantMask = 0;
4377 : 84 : lock->waitMask = 0;
4378 : 84 : dlist_init(&lock->procLocks);
4379 : 84 : dclist_init(&lock->waitProcs);
4380 : 84 : lock->nRequested = 0;
4381 : 84 : lock->nGranted = 0;
4382 [ + - + - : 504 : MemSet(lock->requested, 0, sizeof(int) * MAX_LOCKMODES);
+ - + - +
+ ]
4383 [ - + - - : 84 : MemSet(lock->granted, 0, sizeof(int) * MAX_LOCKMODES);
- - - - -
- ]
4384 : : LOCK_PRINT("lock_twophase_recover: new", lock, lockmode);
4385 : : }
4386 : : else
4387 : : {
4388 : : LOCK_PRINT("lock_twophase_recover: found", lock, lockmode);
4389 : : Assert((lock->nRequested >= 0) && (lock->requested[lockmode] >= 0));
4390 : : Assert((lock->nGranted >= 0) && (lock->granted[lockmode] >= 0));
4391 : : Assert(lock->nGranted <= lock->nRequested);
4392 : : }
4393 : :
4394 : : /*
4395 : : * Create the hash key for the proclock table.
4396 : : */
4397 : 96 : proclocktag.myLock = lock;
4398 : 96 : proclocktag.myProc = proc;
4399 : :
4400 : 96 : proclock_hashcode = ProcLockHashCode(&proclocktag, hashcode);
4401 : :
4402 : : /*
4403 : : * Find or create a proclock entry with this tag
4404 : : */
4405 : 96 : proclock = (PROCLOCK *) hash_search_with_hash_value(LockMethodProcLockHash,
4406 : : &proclocktag,
4407 : : proclock_hashcode,
4408 : : HASH_ENTER_NULL,
4409 : : &found);
4410 [ - + ]: 96 : if (!proclock)
4411 : : {
4412 : : /* Oops, not enough shmem for the proclock */
4413 [ # # ]: 0 : if (lock->nRequested == 0)
4414 : : {
4415 : : /*
4416 : : * There are no other requestors of this lock, so garbage-collect
4417 : : * the lock object. We *must* do this to avoid a permanent leak
4418 : : * of shared memory, because there won't be anything to cause
4419 : : * anyone to release the lock object later.
4420 : : */
4421 : : Assert(dlist_is_empty(&lock->procLocks));
4422 [ # # ]: 0 : if (!hash_search_with_hash_value(LockMethodLockHash,
4423 : 0 : &(lock->tag),
4424 : : hashcode,
4425 : : HASH_REMOVE,
4426 : : NULL))
4427 [ # # ]: 0 : elog(PANIC, "lock table corrupted");
4428 : : }
4429 : 0 : LWLockRelease(partitionLock);
4430 [ # # ]: 0 : ereport(ERROR,
4431 : : (errcode(ERRCODE_OUT_OF_MEMORY),
4432 : : errmsg("out of shared memory"),
4433 : : errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
4434 : : }
4435 : :
4436 : : /*
4437 : : * If new, initialize the new entry
4438 : : */
4439 [ + + ]: 96 : if (!found)
4440 : : {
4441 : : Assert(proc->lockGroupLeader == NULL);
4442 : 88 : proclock->groupLeader = proc;
4443 : 88 : proclock->holdMask = 0;
4444 : 88 : proclock->releaseMask = 0;
4445 : : /* Add proclock to appropriate lists */
4446 : 88 : dlist_push_tail(&lock->procLocks, &proclock->lockLink);
4447 : 88 : dlist_push_tail(&proc->myProcLocks[partition],
4448 : : &proclock->procLink);
4449 : : PROCLOCK_PRINT("lock_twophase_recover: new", proclock);
4450 : : }
4451 : : else
4452 : : {
4453 : : PROCLOCK_PRINT("lock_twophase_recover: found", proclock);
4454 : : Assert((proclock->holdMask & ~lock->grantMask) == 0);
4455 : : }
4456 : :
4457 : : /*
4458 : : * lock->nRequested and lock->requested[] count the total number of
4459 : : * requests, whether granted or waiting, so increment those immediately.
4460 : : */
4461 : 96 : lock->nRequested++;
4462 : 96 : lock->requested[lockmode]++;
4463 : : Assert((lock->nRequested > 0) && (lock->requested[lockmode] > 0));
4464 : :
4465 : : /*
4466 : : * We shouldn't already hold the desired lock.
4467 : : */
4468 [ - + ]: 96 : if (proclock->holdMask & LOCKBIT_ON(lockmode))
4469 [ # # ]: 0 : elog(ERROR, "lock %s on object %u/%u/%u is already held",
4470 : : lockMethodTable->lockModeNames[lockmode],
4471 : : lock->tag.locktag_field1, lock->tag.locktag_field2,
4472 : : lock->tag.locktag_field3);
4473 : :
4474 : : /*
4475 : : * We ignore any possible conflicts and just grant ourselves the lock. Not
4476 : : * only because we don't bother, but also to avoid deadlocks when
4477 : : * switching from standby to normal mode. See function comment.
4478 : : */
4479 : 96 : GrantLock(lock, proclock, lockmode);
4480 : :
4481 : : /*
4482 : : * Bump strong lock count, to make sure any fast-path lock requests won't
4483 : : * be granted without consulting the primary lock table.
4484 : : */
4485 [ + - + + : 96 : if (ConflictsWithRelationFastPath(&lock->tag, lockmode))
+ - + + ]
4486 : : {
4487 : 18 : uint32 fasthashcode = FastPathStrongLockHashPartition(hashcode);
4488 : :
4489 : 18 : pg_atomic_fetch_add_u32(&FastPathStrongRelationLocks[fasthashcode], 1);
4490 : : }
4491 : :
4492 : 96 : LWLockRelease(partitionLock);
4493 : 96 : }
4494 : :
4495 : : /*
4496 : : * Re-acquire a lock belonging to a transaction that was prepared, when
4497 : : * starting up into hot standby mode.
4498 : : */
4499 : : void
4500 : 0 : lock_twophase_standby_recover(FullTransactionId fxid, uint16 info,
4501 : : void *recdata, uint32 len)
4502 : : {
4503 : 0 : TwoPhaseLockRecord *rec = (TwoPhaseLockRecord *) recdata;
4504 : : LOCKTAG *locktag;
4505 : : LOCKMODE lockmode;
4506 : : LOCKMETHODID lockmethodid;
4507 : :
4508 : : Assert(len == sizeof(TwoPhaseLockRecord));
4509 : 0 : locktag = &rec->locktag;
4510 : 0 : lockmode = rec->lockmode;
4511 : 0 : lockmethodid = locktag->locktag_lockmethodid;
4512 : :
4513 [ # # # # ]: 0 : if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
4514 [ # # ]: 0 : elog(ERROR, "unrecognized lock method: %d", lockmethodid);
4515 : :
4516 [ # # ]: 0 : if (lockmode == AccessExclusiveLock &&
4517 [ # # ]: 0 : locktag->locktag_type == LOCKTAG_RELATION)
4518 : : {
4519 : 0 : StandbyAcquireAccessExclusiveLock(XidFromFullTransactionId(fxid),
4520 : : locktag->locktag_field1 /* dboid */ ,
4521 : : locktag->locktag_field2 /* reloid */ );
4522 : : }
4523 : 0 : }
4524 : :
4525 : :
4526 : : /*
4527 : : * 2PC processing routine for COMMIT PREPARED case.
4528 : : *
4529 : : * Find and release the lock indicated by the 2PC record.
4530 : : */
4531 : : void
4532 : 925 : lock_twophase_postcommit(FullTransactionId fxid, uint16 info,
4533 : : void *recdata, uint32 len)
4534 : : {
4535 : 925 : TwoPhaseLockRecord *rec = (TwoPhaseLockRecord *) recdata;
4536 : 925 : PGPROC *proc = TwoPhaseGetDummyProc(fxid, true);
4537 : : LOCKTAG *locktag;
4538 : : LOCKMETHODID lockmethodid;
4539 : : LockMethod lockMethodTable;
4540 : :
4541 : : Assert(len == sizeof(TwoPhaseLockRecord));
4542 : 925 : locktag = &rec->locktag;
4543 : 925 : lockmethodid = locktag->locktag_lockmethodid;
4544 : :
4545 [ + - - + ]: 925 : if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
4546 [ # # ]: 0 : elog(ERROR, "unrecognized lock method: %d", lockmethodid);
4547 : 925 : lockMethodTable = LockMethods[lockmethodid];
4548 : :
4549 : 925 : LockRefindAndRelease(lockMethodTable, proc, locktag, rec->lockmode, true);
4550 : 925 : }
4551 : :
4552 : : /*
4553 : : * 2PC processing routine for ROLLBACK PREPARED case.
4554 : : *
4555 : : * This is actually just the same as the COMMIT case.
4556 : : */
4557 : : void
4558 : 186 : lock_twophase_postabort(FullTransactionId fxid, uint16 info,
4559 : : void *recdata, uint32 len)
4560 : : {
4561 : 186 : lock_twophase_postcommit(fxid, info, recdata, len);
4562 : 186 : }
4563 : :
4564 : : /*
4565 : : * VirtualXactLockTableInsert
4566 : : *
4567 : : * Take vxid lock via the fast-path. There can't be any pre-existing
4568 : : * lockers, as we haven't advertised this vxid via the ProcArray yet.
4569 : : *
4570 : : * Since MyProc->fpLocalTransactionId will normally contain the same data
4571 : : * as MyProc->vxid.lxid, you might wonder if we really need both. The
4572 : : * difference is that MyProc->vxid.lxid is set and cleared unlocked, and
4573 : : * examined by procarray.c, while fpLocalTransactionId is protected by
4574 : : * fpInfoLock and is used only by the locking subsystem. Doing it this
4575 : : * way makes it easier to verify that there are no funny race conditions.
4576 : : *
4577 : : * We don't bother recording this lock in the local lock table, since it's
4578 : : * only ever released at the end of a transaction. Instead,
4579 : : * LockReleaseAll() calls VirtualXactLockTableCleanup().
4580 : : */
4581 : : void
4582 : 661725 : VirtualXactLockTableInsert(VirtualTransactionId vxid)
4583 : : {
4584 : : Assert(VirtualTransactionIdIsValid(vxid));
4585 : :
4586 : 661725 : LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
4587 : :
4588 : : Assert(MyProc->vxid.procNumber == vxid.procNumber);
4589 : : Assert(MyProc->fpLocalTransactionId == InvalidLocalTransactionId);
4590 : : Assert(MyProc->fpVXIDLock == false);
4591 : :
4592 : 661725 : MyProc->fpVXIDLock = true;
4593 : 661725 : MyProc->fpLocalTransactionId = vxid.localTransactionId;
4594 : :
4595 : 661725 : LWLockRelease(&MyProc->fpInfoLock);
4596 : 661725 : }
4597 : :
4598 : : /*
4599 : : * VirtualXactLockTableCleanup
4600 : : *
4601 : : * Check whether a VXID lock has been materialized; if so, release it,
4602 : : * unblocking waiters.
4603 : : */
4604 : : void
4605 : 662303 : VirtualXactLockTableCleanup(void)
4606 : : {
4607 : : bool fastpath;
4608 : : LocalTransactionId lxid;
4609 : :
4610 : : Assert(MyProc->vxid.procNumber != INVALID_PROC_NUMBER);
4611 : :
4612 : : /*
4613 : : * Clean up shared memory state.
4614 : : */
4615 : 662303 : LWLockAcquire(&MyProc->fpInfoLock, LW_EXCLUSIVE);
4616 : :
4617 : 662303 : fastpath = MyProc->fpVXIDLock;
4618 : 662303 : lxid = MyProc->fpLocalTransactionId;
4619 : 662303 : MyProc->fpVXIDLock = false;
4620 : 662303 : MyProc->fpLocalTransactionId = InvalidLocalTransactionId;
4621 : :
4622 : 662303 : LWLockRelease(&MyProc->fpInfoLock);
4623 : :
4624 : : /*
4625 : : * If fpVXIDLock has been cleared without touching fpLocalTransactionId,
4626 : : * that means someone transferred the lock to the main lock table.
4627 : : */
4628 [ + + + + ]: 662303 : if (!fastpath && LocalTransactionIdIsValid(lxid))
4629 : : {
4630 : : VirtualTransactionId vxid;
4631 : : LOCKTAG locktag;
4632 : :
4633 : 295 : vxid.procNumber = MyProcNumber;
4634 : 295 : vxid.localTransactionId = lxid;
4635 : 295 : SET_LOCKTAG_VIRTUALTRANSACTION(locktag, vxid);
4636 : :
4637 : 295 : LockRefindAndRelease(LockMethods[DEFAULT_LOCKMETHOD], MyProc,
4638 : : &locktag, ExclusiveLock, false);
4639 : : }
4640 : 662303 : }
4641 : :
4642 : : /*
4643 : : * XactLockForVirtualXact
4644 : : *
4645 : : * If TransactionIdIsValid(xid), this is essentially XactLockTableWait(xid,
4646 : : * NULL, NULL, XLTW_None) or ConditionalXactLockTableWait(xid). Unlike those
4647 : : * functions, it assumes "xid" is never a subtransaction and that "xid" is
4648 : : * prepared, committed, or aborted.
4649 : : *
4650 : : * If !TransactionIdIsValid(xid), this locks every prepared XID having been
4651 : : * known as "vxid" before its PREPARE TRANSACTION.
4652 : : */
4653 : : static bool
4654 : 322 : XactLockForVirtualXact(VirtualTransactionId vxid,
4655 : : TransactionId xid, bool wait)
4656 : : {
4657 : 322 : bool more = false;
4658 : :
4659 : : /* There is no point to wait for 2PCs if you have no 2PCs. */
4660 [ + + ]: 322 : if (max_prepared_xacts == 0)
4661 : 121 : return true;
4662 : :
4663 : : do
4664 : : {
4665 : : LockAcquireResult lar;
4666 : : LOCKTAG tag;
4667 : :
4668 : : /* Clear state from previous iterations. */
4669 [ - + ]: 201 : if (more)
4670 : : {
4671 : 0 : xid = InvalidTransactionId;
4672 : 0 : more = false;
4673 : : }
4674 : :
4675 : : /* If we have no xid, try to find one. */
4676 [ + + ]: 201 : if (!TransactionIdIsValid(xid))
4677 : 109 : xid = TwoPhaseGetXidByVirtualXID(vxid, &more);
4678 [ + + ]: 201 : if (!TransactionIdIsValid(xid))
4679 : : {
4680 : : Assert(!more);
4681 : 74 : return true;
4682 : : }
4683 : :
4684 : : /* Check or wait for XID completion. */
4685 : 127 : SET_LOCKTAG_TRANSACTION(tag, xid);
4686 : 127 : lar = LockAcquire(&tag, ShareLock, false, !wait);
4687 [ - + ]: 127 : if (lar == LOCKACQUIRE_NOT_AVAIL)
4688 : 0 : return false;
4689 : 127 : LockRelease(&tag, ShareLock, false);
4690 [ - + ]: 127 : } while (more);
4691 : :
4692 : 127 : return true;
4693 : : }
4694 : :
4695 : : /*
4696 : : * VirtualXactLock
4697 : : *
4698 : : * If wait = true, wait as long as the given VXID or any XID acquired by the
4699 : : * same transaction is still running. Then, return true.
4700 : : *
4701 : : * If wait = false, just check whether that VXID or one of those XIDs is still
4702 : : * running, and return true or false.
4703 : : */
4704 : : bool
4705 : 362 : VirtualXactLock(VirtualTransactionId vxid, bool wait)
4706 : : {
4707 : : LOCKTAG tag;
4708 : : PGPROC *proc;
4709 : 362 : TransactionId xid = InvalidTransactionId;
4710 : :
4711 : : Assert(VirtualTransactionIdIsValid(vxid));
4712 : :
4713 [ + + ]: 362 : if (VirtualTransactionIdIsRecoveredPreparedXact(vxid))
4714 : : /* no vxid lock; localTransactionId is a normal, locked XID */
4715 : 1 : return XactLockForVirtualXact(vxid, vxid.localTransactionId, wait);
4716 : :
4717 : 361 : SET_LOCKTAG_VIRTUALTRANSACTION(tag, vxid);
4718 : :
4719 : : /*
4720 : : * If a lock table entry must be made, this is the PGPROC on whose behalf
4721 : : * it must be done. Note that the transaction might end or the PGPROC
4722 : : * might be reassigned to a new backend before we get around to examining
4723 : : * it, but it doesn't matter. If we find upon examination that the
4724 : : * relevant lxid is no longer running here, that's enough to prove that
4725 : : * it's no longer running anywhere.
4726 : : */
4727 : 361 : proc = ProcNumberGetProc(vxid.procNumber);
4728 [ + + ]: 361 : if (proc == NULL)
4729 : 3 : return XactLockForVirtualXact(vxid, InvalidTransactionId, wait);
4730 : :
4731 : : /*
4732 : : * We must acquire this lock before checking the procNumber and lxid
4733 : : * against the ones we're waiting for. The target backend will only set
4734 : : * or clear lxid while holding this lock.
4735 : : */
4736 : 358 : LWLockAcquire(&proc->fpInfoLock, LW_EXCLUSIVE);
4737 : :
4738 [ + - ]: 358 : if (proc->vxid.procNumber != vxid.procNumber
4739 [ + + ]: 358 : || proc->fpLocalTransactionId != vxid.localTransactionId)
4740 : : {
4741 : : /* VXID ended */
4742 : 43 : LWLockRelease(&proc->fpInfoLock);
4743 : 43 : return XactLockForVirtualXact(vxid, InvalidTransactionId, wait);
4744 : : }
4745 : :
4746 : : /*
4747 : : * If we aren't asked to wait, there's no need to set up a lock table
4748 : : * entry. The transaction is still in progress, so just return false.
4749 : : */
4750 [ + + ]: 315 : if (!wait)
4751 : : {
4752 : 15 : LWLockRelease(&proc->fpInfoLock);
4753 : 15 : return false;
4754 : : }
4755 : :
4756 : : /*
4757 : : * OK, we're going to need to sleep on the VXID. But first, we must set
4758 : : * up the primary lock table entry, if needed (ie, convert the proc's
4759 : : * fast-path lock on its VXID to a regular lock).
4760 : : */
4761 [ + + ]: 300 : if (proc->fpVXIDLock)
4762 : : {
4763 : : PROCLOCK *proclock;
4764 : : uint32 hashcode;
4765 : : LWLock *partitionLock;
4766 : :
4767 : 295 : hashcode = LockTagHashCode(&tag);
4768 : :
4769 : 295 : partitionLock = LockHashPartitionLock(hashcode);
4770 : 295 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
4771 : :
4772 : 295 : proclock = SetupLockInTable(LockMethods[DEFAULT_LOCKMETHOD], proc,
4773 : : &tag, hashcode, ExclusiveLock);
4774 [ - + ]: 295 : if (!proclock)
4775 : : {
4776 : 0 : LWLockRelease(partitionLock);
4777 : 0 : LWLockRelease(&proc->fpInfoLock);
4778 [ # # ]: 0 : ereport(ERROR,
4779 : : (errcode(ERRCODE_OUT_OF_MEMORY),
4780 : : errmsg("out of shared memory"),
4781 : : errhint("You might need to increase \"%s\".", "max_locks_per_transaction")));
4782 : : }
4783 : 295 : GrantLock(proclock->tag.myLock, proclock, ExclusiveLock);
4784 : :
4785 : 295 : LWLockRelease(partitionLock);
4786 : :
4787 : 295 : proc->fpVXIDLock = false;
4788 : : }
4789 : :
4790 : : /*
4791 : : * If the proc has an XID now, we'll avoid a TwoPhaseGetXidByVirtualXID()
4792 : : * search. The proc might have assigned this XID but not yet locked it,
4793 : : * in which case the proc will lock this XID before releasing the VXID.
4794 : : * The fpInfoLock critical section excludes VirtualXactLockTableCleanup(),
4795 : : * so we won't save an XID of a different VXID. It doesn't matter whether
4796 : : * we save this before or after setting up the primary lock table entry.
4797 : : */
4798 : 300 : xid = proc->xid;
4799 : :
4800 : : /* Done with proc->fpLockBits */
4801 : 300 : LWLockRelease(&proc->fpInfoLock);
4802 : :
4803 : : /* Time to wait. */
4804 : 300 : (void) LockAcquire(&tag, ShareLock, false, false);
4805 : :
4806 : 275 : LockRelease(&tag, ShareLock, false);
4807 : 275 : return XactLockForVirtualXact(vxid, xid, wait);
4808 : : }
4809 : :
4810 : : /*
4811 : : * LockWaiterCount
4812 : : *
4813 : : * Find the number of lock requester on this locktag
4814 : : */
4815 : : int
4816 : 94427 : LockWaiterCount(const LOCKTAG *locktag)
4817 : : {
4818 : 94427 : LOCKMETHODID lockmethodid = locktag->locktag_lockmethodid;
4819 : : LOCK *lock;
4820 : : bool found;
4821 : : uint32 hashcode;
4822 : : LWLock *partitionLock;
4823 : 94427 : int waiters = 0;
4824 : :
4825 [ + - - + ]: 94427 : if (lockmethodid <= 0 || lockmethodid >= lengthof(LockMethods))
4826 [ # # ]: 0 : elog(ERROR, "unrecognized lock method: %d", lockmethodid);
4827 : :
4828 : 94427 : hashcode = LockTagHashCode(locktag);
4829 : 94427 : partitionLock = LockHashPartitionLock(hashcode);
4830 : 94427 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
4831 : :
4832 : 94427 : lock = (LOCK *) hash_search_with_hash_value(LockMethodLockHash,
4833 : : locktag,
4834 : : hashcode,
4835 : : HASH_FIND,
4836 : : &found);
4837 [ + + ]: 94427 : if (found)
4838 : : {
4839 : : Assert(lock != NULL);
4840 : 13 : waiters = lock->nRequested;
4841 : : }
4842 : 94427 : LWLockRelease(partitionLock);
4843 : :
4844 : 94427 : return waiters;
4845 : : }
|