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