Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * predicate.c
4 : : * POSTGRES predicate locking
5 : : * to support full serializable transaction isolation
6 : : *
7 : : *
8 : : * The approach taken is to implement Serializable Snapshot Isolation (SSI)
9 : : * as initially described in this paper:
10 : : *
11 : : * Michael J. Cahill, Uwe Röhm, and Alan D. Fekete. 2008.
12 : : * Serializable isolation for snapshot databases.
13 : : * In SIGMOD '08: Proceedings of the 2008 ACM SIGMOD
14 : : * international conference on Management of data,
15 : : * pages 729-738, New York, NY, USA. ACM.
16 : : * http://doi.acm.org/10.1145/1376616.1376690
17 : : *
18 : : * and further elaborated in Cahill's doctoral thesis:
19 : : *
20 : : * Michael James Cahill. 2009.
21 : : * Serializable Isolation for Snapshot Databases.
22 : : * Sydney Digital Theses.
23 : : * University of Sydney, School of Information Technologies.
24 : : * http://hdl.handle.net/2123/5353
25 : : *
26 : : *
27 : : * Predicate locks for Serializable Snapshot Isolation (SSI) are SIREAD
28 : : * locks, which are so different from normal locks that a distinct set of
29 : : * structures is required to handle them. They are needed to detect
30 : : * rw-conflicts when the read happens before the write. (When the write
31 : : * occurs first, the reading transaction can check for a conflict by
32 : : * examining the MVCC data.)
33 : : *
34 : : * (1) Besides tuples actually read, they must cover ranges of tuples
35 : : * which would have been read based on the predicate. This will
36 : : * require modelling the predicates through locks against database
37 : : * objects such as pages, index ranges, or entire tables.
38 : : *
39 : : * (2) They must be kept in RAM for quick access. Because of this, it
40 : : * isn't possible to always maintain tuple-level granularity -- when
41 : : * the space allocated to store these approaches exhaustion, a
42 : : * request for a lock may need to scan for situations where a single
43 : : * transaction holds many fine-grained locks which can be coalesced
44 : : * into a single coarser-grained lock.
45 : : *
46 : : * (3) They never block anything; they are more like flags than locks
47 : : * in that regard; although they refer to database objects and are
48 : : * used to identify rw-conflicts with normal write locks.
49 : : *
50 : : * (4) While they are associated with a transaction, they must survive
51 : : * a successful COMMIT of that transaction, and remain until all
52 : : * overlapping transactions complete. This even means that they
53 : : * must survive termination of the transaction's process. If a
54 : : * top level transaction is rolled back, however, it is immediately
55 : : * flagged so that it can be ignored, and its SIREAD locks can be
56 : : * released any time after that.
57 : : *
58 : : * (5) The only transactions which create SIREAD locks or check for
59 : : * conflicts with them are serializable transactions.
60 : : *
61 : : * (6) When a write lock for a top level transaction is found to cover
62 : : * an existing SIREAD lock for the same transaction, the SIREAD lock
63 : : * can be deleted.
64 : : *
65 : : * (7) A write from a serializable transaction must ensure that an xact
66 : : * record exists for the transaction, with the same lifespan (until
67 : : * all concurrent transaction complete or the transaction is rolled
68 : : * back) so that rw-dependencies to that transaction can be
69 : : * detected.
70 : : *
71 : : * We use an optimization for read-only transactions. Under certain
72 : : * circumstances, a read-only transaction's snapshot can be shown to
73 : : * never have conflicts with other transactions. This is referred to
74 : : * as a "safe" snapshot (and one known not to be is "unsafe").
75 : : * However, it can't be determined whether a snapshot is safe until
76 : : * all concurrent read/write transactions complete.
77 : : *
78 : : * Once a read-only transaction is known to have a safe snapshot, it
79 : : * can release its predicate locks and exempt itself from further
80 : : * predicate lock tracking. READ ONLY DEFERRABLE transactions run only
81 : : * on safe snapshots, waiting as necessary for one to be available.
82 : : *
83 : : *
84 : : * Lightweight locks to manage access to the predicate locking shared
85 : : * memory objects must be taken in this order, and should be released in
86 : : * reverse order:
87 : : *
88 : : * SerializableFinishedListLock
89 : : * - Protects the list of transactions which have completed but which
90 : : * may yet matter because they overlap still-active transactions.
91 : : *
92 : : * SerializablePredicateListLock
93 : : * - Protects the linked list of locks held by a transaction. Note
94 : : * that the locks themselves are also covered by the partition
95 : : * locks of their respective lock targets; this lock only affects
96 : : * the linked list connecting the locks related to a transaction.
97 : : * - All transactions share this single lock (with no partitioning).
98 : : * - There is never a need for a process other than the one running
99 : : * an active transaction to walk the list of locks held by that
100 : : * transaction, except parallel query workers sharing the leader's
101 : : * transaction. In the parallel case, an extra per-sxact lock is
102 : : * taken; see below.
103 : : * - It is relatively infrequent that another process needs to
104 : : * modify the list for a transaction, but it does happen for such
105 : : * things as index page splits for pages with predicate locks and
106 : : * freeing of predicate locked pages by a vacuum process. When
107 : : * removing a lock in such cases, the lock itself contains the
108 : : * pointers needed to remove it from the list. When adding a
109 : : * lock in such cases, the lock can be added using the anchor in
110 : : * the transaction structure. Neither requires walking the list.
111 : : * - Cleaning up the list for a terminated transaction is sometimes
112 : : * not done on a retail basis, in which case no lock is required.
113 : : * - Due to the above, a process accessing its active transaction's
114 : : * list always uses a shared lock, regardless of whether it is
115 : : * walking or maintaining the list. This improves concurrency
116 : : * for the common access patterns.
117 : : * - A process which needs to alter the list of a transaction other
118 : : * than its own active transaction must acquire an exclusive
119 : : * lock.
120 : : *
121 : : * SERIALIZABLEXACT's member 'perXactPredicateListLock'
122 : : * - Protects the linked list of predicate locks held by a transaction.
123 : : * Only needed for parallel mode, where multiple backends share the
124 : : * same SERIALIZABLEXACT object. Not needed if
125 : : * SerializablePredicateListLock is held exclusively.
126 : : *
127 : : * PredicateLockHashPartitionLock(hashcode)
128 : : * - The same lock protects a target, all locks on that target, and
129 : : * the linked list of locks on the target.
130 : : * - When more than one is needed, acquire in ascending address order.
131 : : * - When all are needed (rare), acquire in ascending index order with
132 : : * PredicateLockHashPartitionLockByIndex(index).
133 : : *
134 : : * SerializableXactHashLock
135 : : * - Protects both PredXact and SerializableXidHash.
136 : : *
137 : : * SerialControlLock
138 : : * - Protects SerialControlData members
139 : : *
140 : : * SLRU per-bank locks
141 : : * - Protects SerialSlruCtl
142 : : *
143 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
144 : : * Portions Copyright (c) 1994, Regents of the University of California
145 : : *
146 : : *
147 : : * IDENTIFICATION
148 : : * src/backend/storage/lmgr/predicate.c
149 : : *
150 : : *-------------------------------------------------------------------------
151 : : */
152 : :
153 : : #include "postgres.h"
154 : :
155 : : #include "access/parallel.h"
156 : : #include "access/slru.h"
157 : : #include "access/transam.h"
158 : : #include "access/twophase.h"
159 : : #include "access/twophase_rmgr.h"
160 : : #include "access/xact.h"
161 : : #include "access/xlog.h"
162 : : #include "miscadmin.h"
163 : : #include "pgstat.h"
164 : : #include "port/pg_lfind.h"
165 : : #include "storage/predicate.h"
166 : : #include "storage/predicate_internals.h"
167 : : #include "storage/proc.h"
168 : : #include "storage/procarray.h"
169 : : #include "storage/shmem.h"
170 : : #include "storage/subsystems.h"
171 : : #include "utils/guc_hooks.h"
172 : : #include "utils/rel.h"
173 : : #include "utils/snapmgr.h"
174 : : #include "utils/wait_event.h"
175 : :
176 : : /* Uncomment the next line to test the graceful degradation code. */
177 : : /* #define TEST_SUMMARIZE_SERIAL */
178 : :
179 : : /*
180 : : * Test the most selective fields first, for performance.
181 : : *
182 : : * a is covered by b if all of the following hold:
183 : : * 1) a.database = b.database
184 : : * 2) a.relation = b.relation
185 : : * 3) b.offset is invalid (b is page-granularity or higher)
186 : : * 4) either of the following:
187 : : * 4a) a.offset is valid (a is tuple-granularity) and a.page = b.page
188 : : * or 4b) a.offset is invalid and b.page is invalid (a is
189 : : * page-granularity and b is relation-granularity
190 : : */
191 : : #define TargetTagIsCoveredBy(covered_target, covering_target) \
192 : : ((GET_PREDICATELOCKTARGETTAG_RELATION(covered_target) == /* (2) */ \
193 : : GET_PREDICATELOCKTARGETTAG_RELATION(covering_target)) \
194 : : && (GET_PREDICATELOCKTARGETTAG_OFFSET(covering_target) == \
195 : : InvalidOffsetNumber) /* (3) */ \
196 : : && (((GET_PREDICATELOCKTARGETTAG_OFFSET(covered_target) != \
197 : : InvalidOffsetNumber) /* (4a) */ \
198 : : && (GET_PREDICATELOCKTARGETTAG_PAGE(covering_target) == \
199 : : GET_PREDICATELOCKTARGETTAG_PAGE(covered_target))) \
200 : : || ((GET_PREDICATELOCKTARGETTAG_PAGE(covering_target) == \
201 : : InvalidBlockNumber) /* (4b) */ \
202 : : && (GET_PREDICATELOCKTARGETTAG_PAGE(covered_target) \
203 : : != InvalidBlockNumber))) \
204 : : && (GET_PREDICATELOCKTARGETTAG_DB(covered_target) == /* (1) */ \
205 : : GET_PREDICATELOCKTARGETTAG_DB(covering_target)))
206 : :
207 : : /*
208 : : * The predicate locking target and lock shared hash tables are partitioned to
209 : : * reduce contention. To determine which partition a given target belongs to,
210 : : * compute the tag's hash code with PredicateLockTargetTagHashCode(), then
211 : : * apply one of these macros.
212 : : * NB: NUM_PREDICATELOCK_PARTITIONS must be a power of 2!
213 : : */
214 : : #define PredicateLockHashPartition(hashcode) \
215 : : ((hashcode) % NUM_PREDICATELOCK_PARTITIONS)
216 : : #define PredicateLockHashPartitionLock(hashcode) \
217 : : (&MainLWLockArray[PREDICATELOCK_MANAGER_LWLOCK_OFFSET + \
218 : : PredicateLockHashPartition(hashcode)].lock)
219 : : #define PredicateLockHashPartitionLockByIndex(i) \
220 : : (&MainLWLockArray[PREDICATELOCK_MANAGER_LWLOCK_OFFSET + (i)].lock)
221 : :
222 : : #define NPREDICATELOCKTARGETENTS() \
223 : : mul_size(max_predicate_locks_per_xact, add_size(MaxBackends, max_prepared_xacts))
224 : :
225 : : #define SxactIsOnFinishedList(sxact) (!dlist_node_is_detached(&(sxact)->finishedLink))
226 : :
227 : : /*
228 : : * Note that a sxact is marked "prepared" once it has passed
229 : : * PreCommit_CheckForSerializationFailure, even if it isn't using
230 : : * 2PC. This is the point at which it can no longer be aborted.
231 : : *
232 : : * The PREPARED flag remains set after commit, so SxactIsCommitted
233 : : * implies SxactIsPrepared.
234 : : */
235 : : #define SxactIsCommitted(sxact) (((sxact)->flags & SXACT_FLAG_COMMITTED) != 0)
236 : : #define SxactIsPrepared(sxact) (((sxact)->flags & SXACT_FLAG_PREPARED) != 0)
237 : : #define SxactIsRolledBack(sxact) (((sxact)->flags & SXACT_FLAG_ROLLED_BACK) != 0)
238 : : #define SxactIsDoomed(sxact) (((sxact)->flags & SXACT_FLAG_DOOMED) != 0)
239 : : #define SxactIsReadOnly(sxact) (((sxact)->flags & SXACT_FLAG_READ_ONLY) != 0)
240 : : #define SxactHasSummaryConflictIn(sxact) (((sxact)->flags & SXACT_FLAG_SUMMARY_CONFLICT_IN) != 0)
241 : : #define SxactHasSummaryConflictOut(sxact) (((sxact)->flags & SXACT_FLAG_SUMMARY_CONFLICT_OUT) != 0)
242 : : /*
243 : : * The following macro actually means that the specified transaction has a
244 : : * conflict out *to a transaction which committed ahead of it*. It's hard
245 : : * to get that into a name of a reasonable length.
246 : : */
247 : : #define SxactHasConflictOut(sxact) (((sxact)->flags & SXACT_FLAG_CONFLICT_OUT) != 0)
248 : : #define SxactIsDeferrableWaiting(sxact) (((sxact)->flags & SXACT_FLAG_DEFERRABLE_WAITING) != 0)
249 : : #define SxactIsROSafe(sxact) (((sxact)->flags & SXACT_FLAG_RO_SAFE) != 0)
250 : : #define SxactIsROUnsafe(sxact) (((sxact)->flags & SXACT_FLAG_RO_UNSAFE) != 0)
251 : : #define SxactIsPartiallyReleased(sxact) (((sxact)->flags & SXACT_FLAG_PARTIALLY_RELEASED) != 0)
252 : :
253 : : /*
254 : : * Compute the hash code associated with a PREDICATELOCKTARGETTAG.
255 : : *
256 : : * To avoid unnecessary recomputations of the hash code, we try to do this
257 : : * just once per function, and then pass it around as needed. Aside from
258 : : * passing the hashcode to hash_search_with_hash_value(), we can extract
259 : : * the lock partition number from the hashcode.
260 : : */
261 : : #define PredicateLockTargetTagHashCode(predicatelocktargettag) \
262 : : get_hash_value(PredicateLockTargetHash, predicatelocktargettag)
263 : :
264 : : /*
265 : : * Given a predicate lock tag, and the hash for its target,
266 : : * compute the lock hash.
267 : : *
268 : : * To make the hash code also depend on the transaction, we xor the sxid
269 : : * struct's address into the hash code, left-shifted so that the
270 : : * partition-number bits don't change. Since this is only a hash, we
271 : : * don't care if we lose high-order bits of the address; use an
272 : : * intermediate variable to suppress cast-pointer-to-int warnings.
273 : : */
274 : : #define PredicateLockHashCodeFromTargetHashCode(predicatelocktag, targethash) \
275 : : ((targethash) ^ ((uint32) PointerGetDatum((predicatelocktag)->myXact)) \
276 : : << LOG2_NUM_PREDICATELOCK_PARTITIONS)
277 : :
278 : :
279 : : /*
280 : : * The SLRU buffer area through which we access the old xids.
281 : : */
282 : : static bool SerialPagePrecedesLogically(int64 page1, int64 page2);
283 : : static int serial_errdetail_for_io_error(const void *opaque_data);
284 : :
285 : : static SlruDesc SerialSlruDesc;
286 : :
287 : : #define SerialSlruCtl (&SerialSlruDesc)
288 : :
289 : : #define SERIAL_PAGESIZE BLCKSZ
290 : : #define SERIAL_ENTRYSIZE sizeof(SerCommitSeqNo)
291 : : #define SERIAL_ENTRIESPERPAGE (SERIAL_PAGESIZE / SERIAL_ENTRYSIZE)
292 : :
293 : : /*
294 : : * Set maximum pages based on the number needed to track all transactions.
295 : : */
296 : : #define SERIAL_MAX_PAGE (MaxTransactionId / SERIAL_ENTRIESPERPAGE)
297 : :
298 : : #define SerialNextPage(page) (((page) >= SERIAL_MAX_PAGE) ? 0 : (page) + 1)
299 : :
300 : : #define SerialValue(slotno, xid) (*((SerCommitSeqNo *) \
301 : : (SerialSlruCtl->shared->page_buffer[slotno] + \
302 : : ((((uint32) (xid)) % SERIAL_ENTRIESPERPAGE) * SERIAL_ENTRYSIZE))))
303 : :
304 : : #define SerialPage(xid) (((uint32) (xid)) / SERIAL_ENTRIESPERPAGE)
305 : :
306 : : typedef struct SerialControlData
307 : : {
308 : : int64 headPage; /* newest initialized page */
309 : : TransactionId headXid; /* newest valid Xid in the SLRU */
310 : : TransactionId tailXid; /* oldest xmin we might be interested in */
311 : : } SerialControlData;
312 : :
313 : : typedef struct SerialControlData *SerialControl;
314 : :
315 : : static SerialControl serialControl;
316 : :
317 : : /*
318 : : * When the oldest committed transaction on the "finished" list is moved to
319 : : * SLRU, its predicate locks will be moved to this "dummy" transaction,
320 : : * collapsing duplicate targets. When a duplicate is found, the later
321 : : * commitSeqNo is used.
322 : : */
323 : : static SERIALIZABLEXACT *OldCommittedSxact;
324 : :
325 : :
326 : : /*
327 : : * These configuration variables are used to set the predicate lock table size
328 : : * and to control promotion of predicate locks to coarser granularity in an
329 : : * attempt to degrade performance (mostly as false positive serialization
330 : : * failure) gracefully in the face of memory pressure.
331 : : */
332 : : int max_predicate_locks_per_xact; /* in guc_tables.c */
333 : : int max_predicate_locks_per_relation; /* in guc_tables.c */
334 : : int max_predicate_locks_per_page; /* in guc_tables.c */
335 : :
336 : : /*
337 : : * This provides a list of objects in order to track transactions
338 : : * participating in predicate locking. Entries in the list are fixed size,
339 : : * and reside in shared memory. The memory address of an entry must remain
340 : : * fixed during its lifetime. The list will be protected from concurrent
341 : : * update externally; no provision is made in this code to manage that. The
342 : : * number of entries in the list, and the size allowed for each entry is
343 : : * fixed upon creation.
344 : : */
345 : : static PredXactList PredXact;
346 : :
347 : : static void PredicateLockShmemRequest(void *arg);
348 : : static void PredicateLockShmemInit(void *arg);
349 : : static void PredicateLockShmemAttach(void *arg);
350 : :
351 : : const ShmemCallbacks PredicateLockShmemCallbacks = {
352 : : .request_fn = PredicateLockShmemRequest,
353 : : .init_fn = PredicateLockShmemInit,
354 : : .attach_fn = PredicateLockShmemAttach,
355 : : };
356 : :
357 : :
358 : : /*
359 : : * This provides a pool of RWConflict data elements to use in conflict lists
360 : : * between transactions.
361 : : */
362 : : static RWConflictPoolHeader RWConflictPool;
363 : :
364 : : /*
365 : : * The predicate locking hash tables are in shared memory.
366 : : * Each backend keeps pointers to them.
367 : : */
368 : : static HTAB *SerializableXidHash;
369 : : static HTAB *PredicateLockTargetHash;
370 : : static HTAB *PredicateLockHash;
371 : : static dlist_head *FinishedSerializableTransactions;
372 : :
373 : : /*
374 : : * Tag for a dummy entry in PredicateLockTargetHash. By temporarily removing
375 : : * this entry, you can ensure that there's enough scratch space available for
376 : : * inserting one entry in the hash table. This is an otherwise-invalid tag.
377 : : */
378 : : static const PREDICATELOCKTARGETTAG ScratchTargetTag = {0, 0, 0, 0};
379 : : static uint32 ScratchTargetTagHash;
380 : : static LWLock *ScratchPartitionLock;
381 : :
382 : : /*
383 : : * The local hash table used to determine when to combine multiple fine-
384 : : * grained locks into a single courser-grained lock.
385 : : */
386 : : static HTAB *LocalPredicateLockHash = NULL;
387 : :
388 : : /*
389 : : * Keep a pointer to the currently-running serializable transaction (if any)
390 : : * for quick reference. Also, remember if we have written anything that could
391 : : * cause a rw-conflict.
392 : : */
393 : : static SERIALIZABLEXACT *MySerializableXact = InvalidSerializableXact;
394 : : static bool MyXactDidWrite = false;
395 : :
396 : : /*
397 : : * The SXACT_FLAG_RO_UNSAFE optimization might lead us to release
398 : : * MySerializableXact early. If that happens in a parallel query, the leader
399 : : * needs to defer the destruction of the SERIALIZABLEXACT until end of
400 : : * transaction, because the workers still have a reference to it. In that
401 : : * case, the leader stores it here.
402 : : */
403 : : static SERIALIZABLEXACT *SavedSerializableXact = InvalidSerializableXact;
404 : :
405 : : static int64 max_serializable_xacts;
406 : :
407 : : /* local functions */
408 : :
409 : : static SERIALIZABLEXACT *CreatePredXact(void);
410 : : static void ReleasePredXact(SERIALIZABLEXACT *sxact);
411 : :
412 : : static bool RWConflictExists(const SERIALIZABLEXACT *reader, const SERIALIZABLEXACT *writer);
413 : : static void SetRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer);
414 : : static void SetPossibleUnsafeConflict(SERIALIZABLEXACT *roXact, SERIALIZABLEXACT *activeXact);
415 : : static void ReleaseRWConflict(RWConflict conflict);
416 : : static void FlagSxactUnsafe(SERIALIZABLEXACT *sxact);
417 : :
418 : : static void SerialAdd(TransactionId xid, SerCommitSeqNo minConflictCommitSeqNo);
419 : : static SerCommitSeqNo SerialGetMinConflictCommitSeqNo(TransactionId xid);
420 : : static void SerialSetActiveSerXmin(TransactionId xid);
421 : :
422 : : static uint32 predicatelock_hash(const void *key, Size keysize);
423 : :
424 : : static void SummarizeOldestCommittedSxact(void);
425 : : static Snapshot GetSafeSnapshot(Snapshot origSnapshot);
426 : : static Snapshot GetSerializableTransactionSnapshotInt(Snapshot snapshot,
427 : : VirtualTransactionId *sourcevxid,
428 : : int sourcepid);
429 : : static bool PredicateLockExists(const PREDICATELOCKTARGETTAG *targettag);
430 : : static bool GetParentPredicateLockTag(const PREDICATELOCKTARGETTAG *tag,
431 : : PREDICATELOCKTARGETTAG *parent);
432 : : static bool CoarserLockCovers(const PREDICATELOCKTARGETTAG *newtargettag);
433 : : static void RemoveScratchTarget(bool lockheld);
434 : : static void RestoreScratchTarget(bool lockheld);
435 : : static void RemoveTargetIfNoLongerUsed(PREDICATELOCKTARGET *target,
436 : : uint32 targettaghash);
437 : : static void DeleteChildTargetLocks(const PREDICATELOCKTARGETTAG *newtargettag);
438 : : static int MaxPredicateChildLocks(const PREDICATELOCKTARGETTAG *tag);
439 : : static bool CheckAndPromotePredicateLockRequest(const PREDICATELOCKTARGETTAG *reqtag);
440 : : static void DecrementParentLocks(const PREDICATELOCKTARGETTAG *targettag);
441 : : static void CreatePredicateLock(const PREDICATELOCKTARGETTAG *targettag,
442 : : uint32 targettaghash,
443 : : SERIALIZABLEXACT *sxact);
444 : : static void DeleteLockTarget(PREDICATELOCKTARGET *target, uint32 targettaghash);
445 : : static bool TransferPredicateLocksToNewTarget(PREDICATELOCKTARGETTAG oldtargettag,
446 : : PREDICATELOCKTARGETTAG newtargettag,
447 : : bool removeOld);
448 : : static void PredicateLockAcquire(const PREDICATELOCKTARGETTAG *targettag);
449 : : static void DropAllPredicateLocksFromTable(Relation relation,
450 : : bool transfer);
451 : : static void SetNewSxactGlobalXmin(void);
452 : : static void ClearOldPredicateLocks(void);
453 : : static void ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial,
454 : : bool summarize);
455 : : static bool XidIsConcurrent(TransactionId xid);
456 : : static void CheckTargetForConflictsIn(PREDICATELOCKTARGETTAG *targettag);
457 : : static void FlagRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer);
458 : : static void OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
459 : : SERIALIZABLEXACT *writer);
460 : : static void CreateLocalPredicateLockHash(void);
461 : : static void ReleasePredicateLocksLocal(void);
462 : :
463 : :
464 : : /*------------------------------------------------------------------------*/
465 : :
466 : : /*
467 : : * Does this relation participate in predicate locking? Temporary and system
468 : : * relations are exempt.
469 : : */
470 : : static inline bool
5622 heikki.linnakangas@i 471 :CBC 142132 : PredicateLockingNeededForRelation(Relation relation)
472 : : {
1939 tgl@sss.pgh.pa.us 473 [ + + ]: 181998 : return !(relation->rd_id < FirstUnpinnedObjectId ||
1435 michael@paquier.xyz 474 [ + + ]: 39866 : RelationUsesLocalBuffers(relation));
475 : : }
476 : :
477 : : /*
478 : : * When a public interface method is called for a read, this is the test to
479 : : * see if we should do a quick return.
480 : : *
481 : : * Note: this function has side-effects! If this transaction has been flagged
482 : : * as RO-safe since the last call, we release all predicate locks and reset
483 : : * MySerializableXact. That makes subsequent calls to return quickly.
484 : : *
485 : : * This is marked as 'inline' to eliminate the function call overhead in the
486 : : * common case that serialization is not needed.
487 : : */
488 : : static inline bool
5622 heikki.linnakangas@i 489 : 79944119 : SerializationNeededForRead(Relation relation, Snapshot snapshot)
490 : : {
491 : : /* Nothing to do if this is not a serializable transaction */
492 [ + + ]: 79944119 : if (MySerializableXact == InvalidSerializableXact)
493 : 79807373 : return false;
494 : :
495 : : /*
496 : : * Don't acquire locks or conflict when scanning with a special snapshot.
497 : : * This excludes things like CLUSTER and REINDEX. They use the wholesale
498 : : * functions TransferPredicateLocksToHeapRelation() and
499 : : * CheckTableForSerializableConflictIn() to participate in serialization,
500 : : * but the scans involved don't need serialization.
501 : : */
502 [ + + ]: 136746 : if (!IsMVCCSnapshot(snapshot))
503 : 1811 : return false;
504 : :
505 : : /*
506 : : * Check if we have just become "RO-safe". If we have, immediately release
507 : : * all locks as they're not needed anymore. This also resets
508 : : * MySerializableXact, so that subsequent calls to this function can exit
509 : : * quickly.
510 : : *
511 : : * A transaction is flagged as RO_SAFE if all concurrent R/W transactions
512 : : * commit without having conflicts out to an earlier snapshot, thus
513 : : * ensuring that no conflicts are possible for this transaction.
514 : : */
515 [ + + ]: 134935 : if (SxactIsROSafe(MySerializableXact))
516 : : {
2792 tmunro@postgresql.or 517 : 33 : ReleasePredicateLocks(false, true);
5622 heikki.linnakangas@i 518 : 33 : return false;
519 : : }
520 : :
521 : : /* Check if the relation doesn't participate in predicate locking */
522 [ + + ]: 134902 : if (!PredicateLockingNeededForRelation(relation))
523 : 99726 : return false;
524 : :
5621 525 : 35176 : return true; /* no excuse to skip predicate locking */
526 : : }
527 : :
528 : : /*
529 : : * Like SerializationNeededForRead(), but called on writes.
530 : : * The logic is the same, but there is no snapshot and we can't be RO-safe.
531 : : */
532 : : static inline bool
5622 533 : 24817410 : SerializationNeededForWrite(Relation relation)
534 : : {
535 : : /* Nothing to do if this is not a serializable transaction */
536 [ + + ]: 24817410 : if (MySerializableXact == InvalidSerializableXact)
537 : 24810310 : return false;
538 : :
539 : : /* Check if the relation doesn't participate in predicate locking */
540 [ + + ]: 7100 : if (!PredicateLockingNeededForRelation(relation))
541 : 2600 : return false;
542 : :
5621 543 : 4500 : return true; /* no excuse to skip predicate locking */
544 : : }
545 : :
546 : :
547 : : /*------------------------------------------------------------------------*/
548 : :
549 : : /*
550 : : * These functions are a simple implementation of a list for this specific
551 : : * type of struct. If there is ever a generalized shared memory list, we
552 : : * should probably switch to that.
553 : : */
554 : : static SERIALIZABLEXACT *
5750 555 : 3006 : CreatePredXact(void)
556 : : {
557 : : SERIALIZABLEXACT *sxact;
558 : :
1386 andres@anarazel.de 559 [ - + ]: 3006 : if (dlist_is_empty(&PredXact->availableList))
5750 heikki.linnakangas@i 560 :UBC 0 : return NULL;
561 : :
1386 andres@anarazel.de 562 :CBC 3006 : sxact = dlist_container(SERIALIZABLEXACT, xactLink,
563 : : dlist_pop_head_node(&PredXact->availableList));
564 : 3006 : dlist_push_tail(&PredXact->activeList, &sxact->xactLink);
565 : 3006 : return sxact;
566 : : }
567 : :
568 : : static void
5750 heikki.linnakangas@i 569 : 1703 : ReleasePredXact(SERIALIZABLEXACT *sxact)
570 : : {
571 [ - + ]: 1703 : Assert(ShmemAddrIsValid(sxact));
572 : :
1386 andres@anarazel.de 573 : 1703 : dlist_delete(&sxact->xactLink);
574 : 1703 : dlist_push_tail(&PredXact->availableList, &sxact->xactLink);
5750 heikki.linnakangas@i 575 : 1703 : }
576 : :
577 : : /*------------------------------------------------------------------------*/
578 : :
579 : : /*
580 : : * These functions manage primitive access to the RWConflict pool and lists.
581 : : */
582 : : static bool
5615 tgl@sss.pgh.pa.us 583 : 2747 : RWConflictExists(const SERIALIZABLEXACT *reader, const SERIALIZABLEXACT *writer)
584 : : {
585 : : dlist_iter iter;
586 : :
5750 heikki.linnakangas@i 587 [ - + ]: 2747 : Assert(reader != writer);
588 : :
589 : : /* Check the ends of the purported conflict first. */
5622 590 [ + - ]: 2747 : if (SxactIsDoomed(reader)
591 [ + + ]: 2747 : || SxactIsDoomed(writer)
1386 andres@anarazel.de 592 [ + + ]: 2739 : || dlist_is_empty(&reader->outConflicts)
593 [ + + ]: 610 : || dlist_is_empty(&writer->inConflicts))
5750 heikki.linnakangas@i 594 : 2209 : return false;
595 : :
596 : : /*
597 : : * A conflict is possible; walk the list to find out.
598 : : *
599 : : * The unconstify is needed as we have no const version of
600 : : * dlist_foreach().
601 : : */
1386 andres@anarazel.de 602 [ + - + + ]: 562 : dlist_foreach(iter, &unconstify(SERIALIZABLEXACT *, reader)->outConflicts)
603 : : {
604 : 538 : RWConflict conflict =
605 : : dlist_container(RWConflictData, outLink, iter.cur);
606 : :
5750 heikki.linnakangas@i 607 [ + + ]: 538 : if (conflict->sxactIn == writer)
608 : 514 : return true;
609 : : }
610 : :
611 : : /* No conflict found. */
612 : 24 : return false;
613 : : }
614 : :
615 : : static void
616 : 812 : SetRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
617 : : {
618 : : RWConflict conflict;
619 : :
620 [ - + ]: 812 : Assert(reader != writer);
621 [ - + ]: 812 : Assert(!RWConflictExists(reader, writer));
622 : :
1386 andres@anarazel.de 623 [ - + ]: 812 : if (dlist_is_empty(&RWConflictPool->availableList))
5750 heikki.linnakangas@i 624 [ # # ]:UBC 0 : ereport(ERROR,
625 : : (errcode(ERRCODE_OUT_OF_MEMORY),
626 : : errmsg("not enough elements in RWConflictPool to record a read/write conflict"),
627 : : errhint("You might need to run fewer transactions at a time or increase \"max_connections\".")));
628 : :
1386 andres@anarazel.de 629 :CBC 812 : conflict = dlist_head_element(RWConflictData, outLink, &RWConflictPool->availableList);
630 : 812 : dlist_delete(&conflict->outLink);
631 : :
5750 heikki.linnakangas@i 632 : 812 : conflict->sxactOut = reader;
633 : 812 : conflict->sxactIn = writer;
1386 andres@anarazel.de 634 : 812 : dlist_push_tail(&reader->outConflicts, &conflict->outLink);
635 : 812 : dlist_push_tail(&writer->inConflicts, &conflict->inLink);
5750 heikki.linnakangas@i 636 : 812 : }
637 : :
638 : : static void
639 : 135 : SetPossibleUnsafeConflict(SERIALIZABLEXACT *roXact,
640 : : SERIALIZABLEXACT *activeXact)
641 : : {
642 : : RWConflict conflict;
643 : :
644 [ - + ]: 135 : Assert(roXact != activeXact);
645 [ - + ]: 135 : Assert(SxactIsReadOnly(roXact));
646 [ - + ]: 135 : Assert(!SxactIsReadOnly(activeXact));
647 : :
1386 andres@anarazel.de 648 [ - + ]: 135 : if (dlist_is_empty(&RWConflictPool->availableList))
5750 heikki.linnakangas@i 649 [ # # ]:UBC 0 : ereport(ERROR,
650 : : (errcode(ERRCODE_OUT_OF_MEMORY),
651 : : errmsg("not enough elements in RWConflictPool to record a potential read/write conflict"),
652 : : errhint("You might need to run fewer transactions at a time or increase \"max_connections\".")));
653 : :
1386 andres@anarazel.de 654 :CBC 135 : conflict = dlist_head_element(RWConflictData, outLink, &RWConflictPool->availableList);
655 : 135 : dlist_delete(&conflict->outLink);
656 : :
5750 heikki.linnakangas@i 657 : 135 : conflict->sxactOut = activeXact;
658 : 135 : conflict->sxactIn = roXact;
1386 andres@anarazel.de 659 : 135 : dlist_push_tail(&activeXact->possibleUnsafeConflicts, &conflict->outLink);
660 : 135 : dlist_push_tail(&roXact->possibleUnsafeConflicts, &conflict->inLink);
5750 heikki.linnakangas@i 661 : 135 : }
662 : :
663 : : static void
664 : 947 : ReleaseRWConflict(RWConflict conflict)
665 : : {
1386 andres@anarazel.de 666 : 947 : dlist_delete(&conflict->inLink);
667 : 947 : dlist_delete(&conflict->outLink);
668 : 947 : dlist_push_tail(&RWConflictPool->availableList, &conflict->outLink);
5750 heikki.linnakangas@i 669 : 947 : }
670 : :
671 : : static void
672 : 3 : FlagSxactUnsafe(SERIALIZABLEXACT *sxact)
673 : : {
674 : : dlist_mutable_iter iter;
675 : :
676 [ - + ]: 3 : Assert(SxactIsReadOnly(sxact));
677 [ - + ]: 3 : Assert(!SxactIsROSafe(sxact));
678 : :
679 : 3 : sxact->flags |= SXACT_FLAG_RO_UNSAFE;
680 : :
681 : : /*
682 : : * We know this isn't a safe snapshot, so we can stop looking for other
683 : : * potential conflicts.
684 : : */
1386 andres@anarazel.de 685 [ + - + + ]: 6 : dlist_foreach_modify(iter, &sxact->possibleUnsafeConflicts)
686 : : {
687 : 3 : RWConflict conflict =
1266 tgl@sss.pgh.pa.us 688 : 3 : dlist_container(RWConflictData, inLink, iter.cur);
689 : :
5750 heikki.linnakangas@i 690 [ - + ]: 3 : Assert(!SxactIsReadOnly(conflict->sxactOut));
691 [ - + ]: 3 : Assert(sxact == conflict->sxactIn);
692 : :
693 : 3 : ReleaseRWConflict(conflict);
694 : : }
695 : 3 : }
696 : :
697 : : /*------------------------------------------------------------------------*/
698 : :
699 : : /*
700 : : * Decide whether a Serial page number is "older" for truncation purposes.
701 : : * Analogous to CLOGPagePrecedes().
702 : : */
703 : : static bool
1072 akorotkov@postgresql 704 : 53431 : SerialPagePrecedesLogically(int64 page1, int64 page2)
705 : : {
706 : : TransactionId xid1;
707 : : TransactionId xid2;
708 : :
2119 noah@leadboat.com 709 : 53431 : xid1 = ((TransactionId) page1) * SERIAL_ENTRIESPERPAGE;
710 : 53431 : xid1 += FirstNormalTransactionId + 1;
711 : 53431 : xid2 = ((TransactionId) page2) * SERIAL_ENTRIESPERPAGE;
712 : 53431 : xid2 += FirstNormalTransactionId + 1;
713 : :
714 [ + + + + ]: 89923 : return (TransactionIdPrecedes(xid1, xid2) &&
715 : 36492 : TransactionIdPrecedes(xid1, xid2 + SERIAL_ENTRIESPERPAGE - 1));
716 : : }
717 : :
718 : : static int
237 heikki.linnakangas@i 719 :UBC 0 : serial_errdetail_for_io_error(const void *opaque_data)
720 : : {
721 : 0 : TransactionId xid = *(const TransactionId *) opaque_data;
722 : :
723 : 0 : return errdetail("Could not access serializable CSN of transaction %u.", xid);
724 : : }
725 : :
726 : : #ifdef USE_ASSERT_CHECKING
727 : : static void
2119 noah@leadboat.com 728 :CBC 1307 : SerialPagePrecedesLogicallyUnitTests(void)
729 : : {
730 : 1307 : int per_page = SERIAL_ENTRIESPERPAGE,
731 : 1307 : offset = per_page / 2;
732 : : int64 newestPage,
733 : : oldestPage,
734 : : headPage,
735 : : targetPage;
736 : : TransactionId newestXact,
737 : : oldestXact;
738 : :
739 : : /* GetNewTransactionId() has assigned the last XID it can safely use. */
740 : 1307 : newestPage = 2 * SLRU_PAGES_PER_SEGMENT - 1; /* nothing special */
741 : 1307 : newestXact = newestPage * per_page + offset;
742 [ - + ]: 1307 : Assert(newestXact / per_page == newestPage);
743 : 1307 : oldestXact = newestXact + 1;
744 : 1307 : oldestXact -= 1U << 31;
745 : 1307 : oldestPage = oldestXact / per_page;
746 : :
747 : : /*
748 : : * In this scenario, the SLRU headPage pertains to the last ~1000 XIDs
749 : : * assigned. oldestXact finishes, ~2B XIDs having elapsed since it
750 : : * started. Further transactions cause us to summarize oldestXact to
751 : : * tailPage. Function must return false so SerialAdd() doesn't zero
752 : : * tailPage (which may contain entries for other old, recently-finished
753 : : * XIDs) and half the SLRU. Reaching this requires burning ~2B XIDs in
754 : : * single-user mode, a negligible possibility.
755 : : */
756 : 1307 : headPage = newestPage;
757 : 1307 : targetPage = oldestPage;
758 [ - + ]: 1307 : Assert(!SerialPagePrecedesLogically(headPage, targetPage));
759 : :
760 : : /*
761 : : * In this scenario, the SLRU headPage pertains to oldestXact. We're
762 : : * summarizing an XID near newestXact. (Assume few other XIDs used
763 : : * SERIALIZABLE, hence the minimal headPage advancement. Assume
764 : : * oldestXact was long-running and only recently reached the SLRU.)
765 : : * Function must return true to make SerialAdd() create targetPage.
766 : : *
767 : : * Today's implementation mishandles this case, but it doesn't matter
768 : : * enough to fix. Verify that the defect affects just one page by
769 : : * asserting correct treatment of its prior page. Reaching this case
770 : : * requires burning ~2B XIDs in single-user mode, a negligible
771 : : * possibility. Moreover, if it does happen, the consequence would be
772 : : * mild, namely a new transaction failing in SimpleLruReadPage().
773 : : */
774 : 1307 : headPage = oldestPage;
775 : 1307 : targetPage = newestPage;
776 [ - + ]: 1307 : Assert(SerialPagePrecedesLogically(headPage, targetPage - 1));
777 : : #if 0
778 : : Assert(SerialPagePrecedesLogically(headPage, targetPage));
779 : : #endif
5750 heikki.linnakangas@i 780 : 1307 : }
781 : : #endif
782 : :
783 : : /*
784 : : * GUC check_hook for serializable_buffers
785 : : */
786 : : bool
981 alvherre@alvh.no-ip. 787 : 1348 : check_serial_buffers(int *newval, void **extra, GucSource source)
788 : : {
789 : 1348 : return check_slru_buffers("serializable_buffers", newval);
790 : : }
791 : :
792 : : /*
793 : : * Record a committed read write serializable xid and the minimum
794 : : * commitSeqNo of any transactions to which this xid had a rw-conflict out.
795 : : * An invalid commitSeqNo means that there were no conflicts out from xid.
796 : : */
797 : : static void
2365 tgl@sss.pgh.pa.us 798 :UBC 0 : SerialAdd(TransactionId xid, SerCommitSeqNo minConflictCommitSeqNo)
799 : : {
800 : : TransactionId tailXid;
801 : : int64 targetPage;
802 : : int slotno;
803 : : int64 firstZeroPage;
804 : : bool isNewPage;
805 : : LWLock *lock;
806 : :
5750 heikki.linnakangas@i 807 [ # # ]: 0 : Assert(TransactionIdIsValid(xid));
808 : :
2365 tgl@sss.pgh.pa.us 809 : 0 : targetPage = SerialPage(xid);
981 alvherre@alvh.no-ip. 810 : 0 : lock = SimpleLruGetBankLock(SerialSlruCtl, targetPage);
811 : :
812 : : /*
813 : : * In this routine, we must hold both SerialControlLock and the SLRU bank
814 : : * lock simultaneously while making the SLRU data catch up with the new
815 : : * state that we determine.
816 : : */
1010 817 : 0 : LWLockAcquire(SerialControlLock, LW_EXCLUSIVE);
818 : :
819 : : /*
820 : : * If 'xid' is older than the global xmin (== tailXid), there's no need to
821 : : * store it, after all. This can happen if the oldest transaction holding
822 : : * back the global xmin just finished, making 'xid' uninteresting, but
823 : : * ClearOldPredicateLocks() has not yet run.
824 : : */
2365 tgl@sss.pgh.pa.us 825 : 0 : tailXid = serialControl->tailXid;
745 heikki.linnakangas@i 826 [ # # # # ]: 0 : if (!TransactionIdIsValid(tailXid) || TransactionIdPrecedes(xid, tailXid))
827 : : {
828 : 0 : LWLockRelease(SerialControlLock);
829 : 0 : return;
830 : : }
831 : :
832 : : /*
833 : : * If the SLRU is currently unused, zero out the whole active region from
834 : : * tailXid to headXid before taking it into use. Otherwise zero out only
835 : : * any new pages that enter the tailXid-headXid range as we advance
836 : : * headXid.
837 : : */
2365 tgl@sss.pgh.pa.us 838 [ # # ]: 0 : if (serialControl->headPage < 0)
839 : : {
840 : 0 : firstZeroPage = SerialPage(tailXid);
5750 heikki.linnakangas@i 841 : 0 : isNewPage = true;
842 : : }
843 : : else
844 : : {
2365 tgl@sss.pgh.pa.us 845 [ # # ]: 0 : firstZeroPage = SerialNextPage(serialControl->headPage);
846 : 0 : isNewPage = SerialPagePrecedesLogically(serialControl->headPage,
847 : : targetPage);
848 : : }
849 : :
850 [ # # ]: 0 : if (!TransactionIdIsValid(serialControl->headXid)
851 [ # # ]: 0 : || TransactionIdFollows(xid, serialControl->headXid))
852 : 0 : serialControl->headXid = xid;
5721 heikki.linnakangas@i 853 [ # # ]: 0 : if (isNewPage)
2365 tgl@sss.pgh.pa.us 854 : 0 : serialControl->headPage = targetPage;
855 : :
5750 heikki.linnakangas@i 856 [ # # ]: 0 : if (isNewPage)
857 : : {
858 : : /* Initialize intervening pages; might involve trading locks */
859 : : for (;;)
860 : : {
946 alvherre@alvh.no-ip. 861 : 0 : lock = SimpleLruGetBankLock(SerialSlruCtl, firstZeroPage);
862 : 0 : LWLockAcquire(lock, LW_EXCLUSIVE);
863 : 0 : slotno = SimpleLruZeroPage(SerialSlruCtl, firstZeroPage);
864 [ # # ]: 0 : if (firstZeroPage == targetPage)
865 : 0 : break;
2365 tgl@sss.pgh.pa.us 866 [ # # ]: 0 : firstZeroPage = SerialNextPage(firstZeroPage);
946 alvherre@alvh.no-ip. 867 : 0 : LWLockRelease(lock);
868 : : }
869 : : }
870 : : else
871 : : {
872 : 0 : LWLockAcquire(lock, LW_EXCLUSIVE);
237 heikki.linnakangas@i 873 : 0 : slotno = SimpleLruReadPage(SerialSlruCtl, targetPage, true, &xid);
874 : : }
875 : :
2365 tgl@sss.pgh.pa.us 876 : 0 : SerialValue(slotno, xid) = minConflictCommitSeqNo;
877 : 0 : SerialSlruCtl->shared->page_dirty[slotno] = true;
878 : :
981 alvherre@alvh.no-ip. 879 : 0 : LWLockRelease(lock);
1010 880 : 0 : LWLockRelease(SerialControlLock);
881 : : }
882 : :
883 : : /*
884 : : * Get the minimum commitSeqNo for any conflict out for the given xid. For
885 : : * a transaction which exists but has no conflict out, InvalidSerCommitSeqNo
886 : : * will be returned.
887 : : */
888 : : static SerCommitSeqNo
2365 tgl@sss.pgh.pa.us 889 :CBC 25 : SerialGetMinConflictCommitSeqNo(TransactionId xid)
890 : : {
891 : : TransactionId headXid;
892 : : TransactionId tailXid;
893 : : SerCommitSeqNo val;
894 : : int slotno;
895 : :
5750 heikki.linnakangas@i 896 [ - + ]: 25 : Assert(TransactionIdIsValid(xid));
897 : :
1010 alvherre@alvh.no-ip. 898 : 25 : LWLockAcquire(SerialControlLock, LW_SHARED);
2365 tgl@sss.pgh.pa.us 899 : 25 : headXid = serialControl->headXid;
900 : 25 : tailXid = serialControl->tailXid;
1010 alvherre@alvh.no-ip. 901 : 25 : LWLockRelease(SerialControlLock);
902 : :
5750 heikki.linnakangas@i 903 [ + - ]: 25 : if (!TransactionIdIsValid(headXid))
904 : 25 : return 0;
905 : :
5750 heikki.linnakangas@i 906 [ # # ]:UBC 0 : Assert(TransactionIdIsValid(tailXid));
907 : :
908 [ # # ]: 0 : if (TransactionIdPrecedes(xid, tailXid)
909 [ # # ]: 0 : || TransactionIdFollows(xid, headXid))
910 : 0 : return 0;
911 : :
912 : : /*
913 : : * The following function must be called without holding SLRU bank lock,
914 : : * but will return with that lock held, which must then be released.
915 : : */
2365 tgl@sss.pgh.pa.us 916 : 0 : slotno = SimpleLruReadPage_ReadOnly(SerialSlruCtl,
237 heikki.linnakangas@i 917 : 0 : SerialPage(xid), &xid);
2365 tgl@sss.pgh.pa.us 918 : 0 : val = SerialValue(slotno, xid);
981 alvherre@alvh.no-ip. 919 : 0 : LWLockRelease(SimpleLruGetBankLock(SerialSlruCtl, SerialPage(xid)));
5750 heikki.linnakangas@i 920 : 0 : return val;
921 : : }
922 : :
923 : : /*
924 : : * Call this whenever there is a new xmin for active serializable
925 : : * transactions. We don't need to keep information on transactions which
926 : : * precede that. InvalidTransactionId means none active, so everything in
927 : : * the SLRU can be discarded.
928 : : */
929 : : static void
2365 tgl@sss.pgh.pa.us 930 :CBC 1747 : SerialSetActiveSerXmin(TransactionId xid)
931 : : {
1010 alvherre@alvh.no-ip. 932 : 1747 : LWLockAcquire(SerialControlLock, LW_EXCLUSIVE);
933 : :
934 : : /*
935 : : * When no sxacts are active, nothing overlaps, set the xid values to
936 : : * invalid to show that there are no valid entries. Don't clear headPage,
937 : : * though. A new xmin might still land on that page, and we don't want to
938 : : * repeatedly zero out the same page.
939 : : */
5750 heikki.linnakangas@i 940 [ + + ]: 1747 : if (!TransactionIdIsValid(xid))
941 : : {
2365 tgl@sss.pgh.pa.us 942 : 864 : serialControl->tailXid = InvalidTransactionId;
943 : 864 : serialControl->headXid = InvalidTransactionId;
1010 alvherre@alvh.no-ip. 944 : 864 : LWLockRelease(SerialControlLock);
5750 heikki.linnakangas@i 945 : 864 : return;
946 : : }
947 : :
948 : : /*
949 : : * When we're recovering prepared transactions, the global xmin might move
950 : : * backwards depending on the order they're recovered. Normally that's not
951 : : * OK, but during recovery no serializable transactions will commit, so
952 : : * the SLRU is empty and we can get away with it.
953 : : */
954 [ - + ]: 883 : if (RecoveryInProgress())
955 : : {
2365 tgl@sss.pgh.pa.us 956 [ # # ]:UBC 0 : Assert(serialControl->headPage < 0);
957 [ # # ]: 0 : if (!TransactionIdIsValid(serialControl->tailXid)
958 [ # # ]: 0 : || TransactionIdPrecedes(xid, serialControl->tailXid))
959 : : {
960 : 0 : serialControl->tailXid = xid;
961 : : }
1010 alvherre@alvh.no-ip. 962 : 0 : LWLockRelease(SerialControlLock);
5750 heikki.linnakangas@i 963 : 0 : return;
964 : : }
965 : :
2365 tgl@sss.pgh.pa.us 966 [ + + - + ]:CBC 883 : Assert(!TransactionIdIsValid(serialControl->tailXid)
967 : : || TransactionIdFollows(xid, serialControl->tailXid));
968 : :
969 : 883 : serialControl->tailXid = xid;
970 : :
1010 alvherre@alvh.no-ip. 971 : 883 : LWLockRelease(SerialControlLock);
972 : : }
973 : :
974 : : /*
975 : : * Perform a checkpoint --- either during shutdown, or on-the-fly
976 : : *
977 : : * We don't have any data that needs to survive a restart, but this is a
978 : : * convenient place to truncate the SLRU.
979 : : */
980 : : void
5721 heikki.linnakangas@i 981 : 2031 : CheckPointPredicate(void)
982 : : {
983 : : int64 truncateCutoffPage;
984 : :
1010 alvherre@alvh.no-ip. 985 : 2031 : LWLockAcquire(SerialControlLock, LW_EXCLUSIVE);
986 : :
987 : : /* Exit quickly if the SLRU is currently not in use. */
2365 tgl@sss.pgh.pa.us 988 [ + - ]: 2031 : if (serialControl->headPage < 0)
989 : : {
1010 alvherre@alvh.no-ip. 990 : 2031 : LWLockRelease(SerialControlLock);
5750 heikki.linnakangas@i 991 : 2031 : return;
992 : : }
993 : :
2365 tgl@sss.pgh.pa.us 994 [ # # ]:UBC 0 : if (TransactionIdIsValid(serialControl->tailXid))
995 : : {
996 : : int64 tailPage;
997 : :
998 : 0 : tailPage = SerialPage(serialControl->tailXid);
999 : :
1000 : : /*
1001 : : * It is possible for the tailXid to be ahead of the headXid. This
1002 : : * occurs if we checkpoint while there are in-progress serializable
1003 : : * transaction(s) advancing the tail but we are yet to summarize the
1004 : : * transactions. In this case, we cutoff up to the headPage and the
1005 : : * next summary will advance the headXid.
1006 : : */
1115 michael@paquier.xyz 1007 [ # # ]: 0 : if (SerialPagePrecedesLogically(tailPage, serialControl->headPage))
1008 : : {
1009 : : /* We can truncate the SLRU up to the page containing tailXid */
1010 : 0 : truncateCutoffPage = tailPage;
1011 : : }
1012 : : else
1013 : 0 : truncateCutoffPage = serialControl->headPage;
1014 : : }
1015 : : else
1016 : : {
1017 : : /*----------
1018 : : * The SLRU is no longer needed. Truncate to head before we set head
1019 : : * invalid.
1020 : : *
1021 : : * XXX: It's possible that the SLRU is not needed again until XID
1022 : : * wrap-around has happened, so that the segment containing headPage
1023 : : * that we leave behind will appear to be new again. In that case it
1024 : : * won't be removed until XID horizon advances enough to make it
1025 : : * current again.
1026 : : *
1027 : : * XXX: This should happen in vac_truncate_clog(), not in checkpoints.
1028 : : * Consider this scenario, starting from a system with no in-progress
1029 : : * transactions and VACUUM FREEZE having maximized oldestXact:
1030 : : * - Start a SERIALIZABLE transaction.
1031 : : * - Start, finish, and summarize a SERIALIZABLE transaction, creating
1032 : : * one SLRU page.
1033 : : * - Consume XIDs to reach xidStopLimit.
1034 : : * - Finish all transactions. Due to the long-running SERIALIZABLE
1035 : : * transaction, earlier checkpoints did not touch headPage. The
1036 : : * next checkpoint will change it, but that checkpoint happens after
1037 : : * the end of the scenario.
1038 : : * - VACUUM to advance XID limits.
1039 : : * - Consume ~2M XIDs, crossing the former xidWrapLimit.
1040 : : * - Start, finish, and summarize a SERIALIZABLE transaction.
1041 : : * SerialAdd() declines to create the targetPage, because headPage
1042 : : * is not regarded as in the past relative to that targetPage. The
1043 : : * transaction instigating the summarize fails in
1044 : : * SimpleLruReadPage().
1045 : : */
1046 : 0 : truncateCutoffPage = serialControl->headPage;
2365 tgl@sss.pgh.pa.us 1047 : 0 : serialControl->headPage = -1;
1048 : : }
1049 : :
1010 alvherre@alvh.no-ip. 1050 : 0 : LWLockRelease(SerialControlLock);
1051 : :
1052 : : /*
1053 : : * Truncate away pages that are no longer required. Note that no
1054 : : * additional locking is required, because this is only called as part of
1055 : : * a checkpoint, and the validity limits have already been determined.
1056 : : */
1115 michael@paquier.xyz 1057 : 0 : SimpleLruTruncate(SerialSlruCtl, truncateCutoffPage);
1058 : :
1059 : : /*
1060 : : * Write dirty SLRU pages to disk
1061 : : *
1062 : : * This is not actually necessary from a correctness point of view. We do
1063 : : * it merely as a debugging aid.
1064 : : *
1065 : : * We're doing this after the truncation to avoid writing pages right
1066 : : * before deleting the file in which they sit, which would be completely
1067 : : * pointless.
1068 : : */
2232 tmunro@postgresql.or 1069 : 0 : SimpleLruWriteAll(SerialSlruCtl, true);
1070 : : }
1071 : :
1072 : : /*------------------------------------------------------------------------*/
1073 : :
1074 : : /*
1075 : : * PredicateLockShmemRequest -- Register the predicate locking data structures.
1076 : : */
1077 : : static void
213 heikki.linnakangas@i 1078 :CBC 1307 : PredicateLockShmemRequest(void *arg)
1079 : : {
1080 : : int64 max_predicate_lock_targets;
1081 : : int64 max_predicate_locks;
1082 : : int64 max_rw_conflicts;
1083 : :
1084 : : /*
1085 : : * Register hash table for PREDICATELOCKTARGET structs. This stores
1086 : : * per-predicate-lock-target information.
1087 : : */
1088 : 1307 : max_predicate_lock_targets = NPREDICATELOCKTARGETENTS();
1089 : :
1090 : 1307 : ShmemRequestHash(.name = "PREDICATELOCKTARGET hash",
1091 : : .nelems = max_predicate_lock_targets,
1092 : : .ptr = &PredicateLockTargetHash,
1093 : : .hash_info.keysize = sizeof(PREDICATELOCKTARGETTAG),
1094 : : .hash_info.entrysize = sizeof(PREDICATELOCKTARGET),
1095 : : .hash_info.num_partitions = NUM_PREDICATELOCK_PARTITIONS,
1096 : : .hash_flags = HASH_ELEM | HASH_BLOBS | HASH_PARTITION | HASH_FIXED_SIZE,
1097 : : );
1098 : :
1099 : : /*
1100 : : * Allocate hash table for PREDICATELOCK structs. This stores per
1101 : : * xact-lock-of-a-target information.
1102 : : *
1103 : : * Assume an average of 2 xacts per target.
1104 : : */
223 1105 : 1307 : max_predicate_locks = max_predicate_lock_targets * 2;
1106 : :
213 1107 : 1307 : ShmemRequestHash(.name = "PREDICATELOCK hash",
1108 : : .nelems = max_predicate_locks,
1109 : : .ptr = &PredicateLockHash,
1110 : : .hash_info.keysize = sizeof(PREDICATELOCKTAG),
1111 : : .hash_info.entrysize = sizeof(PREDICATELOCK),
1112 : : .hash_info.hash = predicatelock_hash,
1113 : : .hash_info.num_partitions = NUM_PREDICATELOCK_PARTITIONS,
1114 : : .hash_flags = HASH_ELEM | HASH_FUNCTION | HASH_PARTITION | HASH_FIXED_SIZE,
1115 : : );
1116 : :
1117 : : /*
1118 : : * Compute size for serializable transaction hashtable.
1119 : : *
1120 : : * Assume an average of 10 predicate locking transactions per backend.
1121 : : * This allows aggressive cleanup while detail is present before data must
1122 : : * be summarized for storage in SLRU and the "dummy" transaction.
1123 : : */
223 1124 : 1307 : max_serializable_xacts = (MaxBackends + max_prepared_xacts) * 10;
1125 : :
1126 : : /*
1127 : : * Register a list to hold information on transactions participating in
1128 : : * predicate locking.
1129 : : */
213 1130 : 1307 : ShmemRequestStruct(.name = "PredXactList",
1131 : : .size = add_size(PredXactListDataSize,
1132 : : (mul_size((Size) max_serializable_xacts,
1133 : : sizeof(SERIALIZABLEXACT)))),
1134 : : .ptr = (void **) &PredXact,
1135 : : );
1136 : :
1137 : : /*
1138 : : * Register hash table for SERIALIZABLEXID structs. This stores per-xid
1139 : : * information for serializable transactions which have accessed data.
1140 : : */
1141 : 1307 : ShmemRequestHash(.name = "SERIALIZABLEXID hash",
1142 : : .nelems = max_serializable_xacts,
1143 : : .ptr = &SerializableXidHash,
1144 : : .hash_info.keysize = sizeof(SERIALIZABLEXIDTAG),
1145 : : .hash_info.entrysize = sizeof(SERIALIZABLEXID),
1146 : : .hash_flags = HASH_ELEM | HASH_BLOBS | HASH_FIXED_SIZE,
1147 : : );
1148 : :
1149 : : /*
1150 : : * Allocate space for tracking rw-conflicts in lists attached to the
1151 : : * transactions.
1152 : : *
1153 : : * Assume an average of 5 conflicts per transaction. Calculations suggest
1154 : : * that this will prevent resource exhaustion in even the most pessimal
1155 : : * loads up to max_connections = 200 with all 200 connections pounding the
1156 : : * database with serializable transactions. Beyond that, there may be
1157 : : * occasional transactions canceled when trying to flag conflicts. That's
1158 : : * probably OK.
1159 : : */
223 1160 : 1307 : max_rw_conflicts = max_serializable_xacts * 5;
1161 : :
213 1162 : 1307 : ShmemRequestStruct(.name = "RWConflictPool",
1163 : : .size = RWConflictPoolHeaderDataSize + mul_size((Size) max_rw_conflicts,
1164 : : RWConflictDataSize),
1165 : : .ptr = (void **) &RWConflictPool,
1166 : : );
1167 : :
1168 : 1307 : ShmemRequestStruct(.name = "FinishedSerializableTransactions",
1169 : : .size = sizeof(dlist_head),
1170 : : .ptr = (void **) &FinishedSerializableTransactions,
1171 : : );
1172 : :
1173 : : /*
1174 : : * Initialize the SLRU storage for old committed serializable
1175 : : * transactions.
1176 : : */
1177 : 1307 : SimpleLruRequest(.desc = &SerialSlruDesc,
1178 : : .name = "serializable",
1179 : : .Dir = "pg_serial",
1180 : : .long_segment_names = false,
1181 : :
1182 : : .nslots = serializable_buffers,
1183 : :
1184 : : .sync_handler = SYNC_HANDLER_NONE,
1185 : : .PagePrecedes = SerialPagePrecedesLogically,
1186 : : .errdetail_for_io_error = serial_errdetail_for_io_error,
1187 : :
1188 : : .buffer_tranche_id = LWTRANCHE_SERIAL_BUFFER,
1189 : : .bank_tranche_id = LWTRANCHE_SERIAL_SLRU,
1190 : : );
1191 : : #ifdef USE_ASSERT_CHECKING
1192 : 1307 : SerialPagePrecedesLogicallyUnitTests();
1193 : : #endif
1194 : :
1195 : 1307 : ShmemRequestStruct(.name = "SerialControlData",
1196 : : .size = sizeof(SerialControlData),
1197 : : .ptr = (void **) &serialControl,
1198 : : );
1199 : 1307 : }
1200 : :
1201 : : static void
1202 : 1303 : PredicateLockShmemInit(void *arg)
1203 : : {
1204 : : int max_rw_conflicts;
1205 : : bool found;
1206 : :
1207 : : /*
1208 : : * Reserve a dummy entry in the hash table; we use it to make sure there's
1209 : : * always one entry available when we need to split or combine a page,
1210 : : * because running out of space there could mean aborting a
1211 : : * non-serializable transaction.
1212 : : */
1213 : 1303 : (void) hash_search(PredicateLockTargetHash, &ScratchTargetTag,
1214 : : HASH_ENTER, &found);
1215 [ - + ]: 1303 : Assert(!found);
1216 : :
1217 : 1303 : dlist_init(&PredXact->availableList);
1218 : 1303 : dlist_init(&PredXact->activeList);
1219 : 1303 : PredXact->SxactGlobalXmin = InvalidTransactionId;
1220 : 1303 : PredXact->SxactGlobalXminCount = 0;
1221 : 1303 : PredXact->WritableSxactCount = 0;
1222 : 1303 : PredXact->LastSxactCommitSeqNo = FirstNormalSerCommitSeqNo - 1;
1223 : 1303 : PredXact->CanPartialClearThrough = 0;
1224 : 1303 : PredXact->HavePartialClearedThrough = 0;
1225 : 1303 : PredXact->element
1226 : 1303 : = (SERIALIZABLEXACT *) ((char *) PredXact + PredXactListDataSize);
1227 : : /* Add all elements to available list, clean. */
1228 [ + + ]: 1193843 : for (int i = 0; i < max_serializable_xacts; i++)
1229 : : {
1230 : 1192540 : LWLockInitialize(&PredXact->element[i].perXactPredicateListLock,
1231 : : LWTRANCHE_PER_XACT_PREDICATE_LIST);
1232 : 1192540 : dlist_push_tail(&PredXact->availableList, &PredXact->element[i].xactLink);
1233 : : }
1234 : 1303 : PredXact->OldCommittedSxact = CreatePredXact();
1235 : 1303 : SetInvalidVirtualTransactionId(PredXact->OldCommittedSxact->vxid);
1236 : 1303 : PredXact->OldCommittedSxact->prepareSeqNo = 0;
1237 : 1303 : PredXact->OldCommittedSxact->commitSeqNo = 0;
1238 : 1303 : PredXact->OldCommittedSxact->SeqNo.lastCommitBeforeSnapshot = 0;
1239 : 1303 : dlist_init(&PredXact->OldCommittedSxact->outConflicts);
1240 : 1303 : dlist_init(&PredXact->OldCommittedSxact->inConflicts);
1241 : 1303 : dlist_init(&PredXact->OldCommittedSxact->predicateLocks);
1242 : 1303 : dlist_node_init(&PredXact->OldCommittedSxact->finishedLink);
1243 : 1303 : dlist_init(&PredXact->OldCommittedSxact->possibleUnsafeConflicts);
1244 : 1303 : PredXact->OldCommittedSxact->topXid = InvalidTransactionId;
1245 : 1303 : PredXact->OldCommittedSxact->finishedBefore = InvalidTransactionId;
1246 : 1303 : PredXact->OldCommittedSxact->xmin = InvalidTransactionId;
1247 : 1303 : PredXact->OldCommittedSxact->flags = SXACT_FLAG_COMMITTED;
1248 : 1303 : PredXact->OldCommittedSxact->pid = 0;
1249 : 1303 : PredXact->OldCommittedSxact->pgprocno = INVALID_PROC_NUMBER;
1250 : :
1251 : : /* Initialize the rw-conflict pool */
1252 : 1303 : dlist_init(&RWConflictPool->availableList);
1253 : 1303 : RWConflictPool->element = (RWConflict) ((char *) RWConflictPool +
1254 : : RWConflictPoolHeaderDataSize);
1255 : :
1256 : 1303 : max_rw_conflicts = max_serializable_xacts * 5;
1257 : :
1258 : : /* Add all elements to available list, clean. */
1259 [ + + ]: 5964003 : for (int i = 0; i < max_rw_conflicts; i++)
1260 : : {
1261 : 5962700 : dlist_push_tail(&RWConflictPool->availableList,
1262 : 5962700 : &RWConflictPool->element[i].outLink);
1263 : : }
1264 : :
1265 : : /* Initialize the list of finished serializable transactions */
1266 : 1303 : dlist_init(FinishedSerializableTransactions);
1267 : :
1268 : : /* Initialize SerialControl to reflect empty SLRU. */
1269 : 1303 : LWLockAcquire(SerialControlLock, LW_EXCLUSIVE);
1270 : 1303 : serialControl->headPage = -1;
1271 : 1303 : serialControl->headXid = InvalidTransactionId;
1272 : 1303 : serialControl->tailXid = InvalidTransactionId;
1273 : 1303 : LWLockRelease(SerialControlLock);
1274 : :
1275 : 1303 : SlruPagePrecedesUnitTests(SerialSlruCtl, SERIAL_ENTRIESPERPAGE);
1276 : :
1277 : : /* This never changes, so let's keep a local copy. */
1278 : 1303 : OldCommittedSxact = PredXact->OldCommittedSxact;
1279 : :
1280 : : /* Pre-calculate the hash and partition lock of the scratch entry */
1281 : 1303 : ScratchTargetTagHash = PredicateLockTargetTagHashCode(&ScratchTargetTag);
1282 : 1303 : ScratchPartitionLock = PredicateLockHashPartitionLock(ScratchTargetTagHash);
1283 : 1303 : }
1284 : :
1285 : : static void
213 heikki.linnakangas@i 1286 :UBC 0 : PredicateLockShmemAttach(void *arg)
1287 : : {
1288 : : /* This never changes, so let's keep a local copy. */
1289 : 0 : OldCommittedSxact = PredXact->OldCommittedSxact;
1290 : :
1291 : : /* Pre-calculate the hash and partition lock of the scratch entry */
1292 : 0 : ScratchTargetTagHash = PredicateLockTargetTagHashCode(&ScratchTargetTag);
1293 : 0 : ScratchPartitionLock = PredicateLockHashPartitionLock(ScratchTargetTagHash);
5750 1294 : 0 : }
1295 : :
1296 : : /*
1297 : : * Compute the hash code associated with a PREDICATELOCKTAG.
1298 : : *
1299 : : * Because we want to use just one set of partition locks for both the
1300 : : * PREDICATELOCKTARGET and PREDICATELOCK hash tables, we have to make sure
1301 : : * that PREDICATELOCKs fall into the same partition number as their
1302 : : * associated PREDICATELOCKTARGETs. dynahash.c expects the partition number
1303 : : * to be the low-order bits of the hash code, and therefore a
1304 : : * PREDICATELOCKTAG's hash code must have the same low-order bits as the
1305 : : * associated PREDICATELOCKTARGETTAG's hash code. We achieve this with this
1306 : : * specialized hash function.
1307 : : */
1308 : : static uint32
1309 : 0 : predicatelock_hash(const void *key, Size keysize)
1310 : : {
5615 tgl@sss.pgh.pa.us 1311 : 0 : const PREDICATELOCKTAG *predicatelocktag = (const PREDICATELOCKTAG *) key;
1312 : : uint32 targethash;
1313 : :
5750 heikki.linnakangas@i 1314 [ # # ]: 0 : Assert(keysize == sizeof(PREDICATELOCKTAG));
1315 : :
1316 : : /* Look into the associated target object, and compute its hash code */
1317 : 0 : targethash = PredicateLockTargetTagHashCode(&predicatelocktag->myTarget->tag);
1318 : :
1319 : 0 : return PredicateLockHashCodeFromTargetHashCode(predicatelocktag, targethash);
1320 : : }
1321 : :
1322 : :
1323 : : /*
1324 : : * GetPredicateLockStatusData
1325 : : * Return a table containing the internal state of the predicate
1326 : : * lock manager for use in pg_lock_status.
1327 : : *
1328 : : * Like GetLockStatusData, this function tries to hold the partition LWLocks
1329 : : * for as short a time as possible by returning two arrays that simply
1330 : : * contain the PREDICATELOCKTARGETTAG and SERIALIZABLEXACT for each lock
1331 : : * table entry. Multiple copies of the same PREDICATELOCKTARGETTAG and
1332 : : * SERIALIZABLEXACT will likely appear.
1333 : : */
1334 : : PredicateLockData *
5750 heikki.linnakangas@i 1335 :CBC 308 : GetPredicateLockStatusData(void)
1336 : : {
1337 : : PredicateLockData *data;
1338 : : int i;
1339 : : int els,
1340 : : el;
1341 : : HASH_SEQ_STATUS seqstat;
1342 : : PREDICATELOCK *predlock;
1343 : :
330 michael@paquier.xyz 1344 : 308 : data = palloc_object(PredicateLockData);
1345 : :
1346 : : /*
1347 : : * To ensure consistency, take simultaneous locks on all partition locks
1348 : : * in ascending order, then SerializableXactHashLock.
1349 : : */
5750 heikki.linnakangas@i 1350 [ + + ]: 5236 : for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
4665 rhaas@postgresql.org 1351 : 4928 : LWLockAcquire(PredicateLockHashPartitionLockByIndex(i), LW_SHARED);
5750 heikki.linnakangas@i 1352 : 308 : LWLockAcquire(SerializableXactHashLock, LW_SHARED);
1353 : :
1354 : : /* Get number of locks and allocate appropriately-sized arrays. */
1355 : 308 : els = hash_get_num_entries(PredicateLockHash);
1356 : 308 : data->nelements = els;
330 michael@paquier.xyz 1357 : 308 : data->locktags = palloc_array(PREDICATELOCKTARGETTAG, els);
1358 : 308 : data->xacts = palloc_array(SERIALIZABLEXACT, els);
1359 : :
1360 : :
1361 : : /* Scan through PredicateLockHash and copy contents */
5750 heikki.linnakangas@i 1362 : 308 : hash_seq_init(&seqstat, PredicateLockHash);
1363 : :
1364 : 308 : el = 0;
1365 : :
1366 [ + + ]: 312 : while ((predlock = (PREDICATELOCK *) hash_seq_search(&seqstat)))
1367 : : {
1368 : 4 : data->locktags[el] = predlock->tag.myTarget->tag;
1369 : 4 : data->xacts[el] = *predlock->tag.myXact;
1370 : 4 : el++;
1371 : : }
1372 : :
1373 [ - + ]: 308 : Assert(el == els);
1374 : :
1375 : : /* Release locks in reverse order */
1376 : 308 : LWLockRelease(SerializableXactHashLock);
1377 [ + + ]: 5236 : for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
4665 rhaas@postgresql.org 1378 : 4928 : LWLockRelease(PredicateLockHashPartitionLockByIndex(i));
1379 : :
5750 heikki.linnakangas@i 1380 : 308 : return data;
1381 : : }
1382 : :
1383 : : /*
1384 : : * Free up shared memory structures by pushing the oldest sxact (the one at
1385 : : * the front of the SummarizeOldestCommittedSxact queue) into summary form.
1386 : : * Each call will free exactly one SERIALIZABLEXACT structure and may also
1387 : : * free one or more of these structures: SERIALIZABLEXID, PREDICATELOCK,
1388 : : * PREDICATELOCKTARGET, RWConflictData.
1389 : : */
1390 : : static void
5750 heikki.linnakangas@i 1391 :UBC 0 : SummarizeOldestCommittedSxact(void)
1392 : : {
1393 : : SERIALIZABLEXACT *sxact;
1394 : :
1395 : 0 : LWLockAcquire(SerializableFinishedListLock, LW_EXCLUSIVE);
1396 : :
1397 : : /*
1398 : : * This function is only called if there are no sxact slots available.
1399 : : * Some of them must belong to old, already-finished transactions, so
1400 : : * there should be something in FinishedSerializableTransactions list that
1401 : : * we can summarize. However, there's a race condition: while we were not
1402 : : * holding any locks, a transaction might have ended and cleaned up all
1403 : : * the finished sxact entries already, freeing up their sxact slots. In
1404 : : * that case, we have nothing to do here. The caller will find one of the
1405 : : * slots released by the other backend when it retries.
1406 : : */
1386 andres@anarazel.de 1407 [ # # ]: 0 : if (dlist_is_empty(FinishedSerializableTransactions))
1408 : : {
5750 heikki.linnakangas@i 1409 : 0 : LWLockRelease(SerializableFinishedListLock);
1410 : 0 : return;
1411 : : }
1412 : :
1413 : : /*
1414 : : * Grab the first sxact off the finished list -- this will be the earliest
1415 : : * commit. Remove it from the list.
1416 : : */
1386 andres@anarazel.de 1417 : 0 : sxact = dlist_head_element(SERIALIZABLEXACT, finishedLink,
1418 : : FinishedSerializableTransactions);
1419 : 0 : dlist_delete_thoroughly(&sxact->finishedLink);
1420 : :
1421 : : /* Add to SLRU summary information. */
5750 heikki.linnakangas@i 1422 [ # # # # ]: 0 : if (TransactionIdIsValid(sxact->topXid) && !SxactIsReadOnly(sxact))
2365 tgl@sss.pgh.pa.us 1423 [ # # ]: 0 : SerialAdd(sxact->topXid, SxactHasConflictOut(sxact)
1424 : : ? sxact->SeqNo.earliestOutConflictCommit : InvalidSerCommitSeqNo);
1425 : :
1426 : : /* Summarize and release the detail. */
5750 heikki.linnakangas@i 1427 : 0 : ReleaseOneSerializableXact(sxact, false, true);
1428 : :
1429 : 0 : LWLockRelease(SerializableFinishedListLock);
1430 : : }
1431 : :
1432 : : /*
1433 : : * GetSafeSnapshot
1434 : : * Obtain and register a snapshot for a READ ONLY DEFERRABLE
1435 : : * transaction. Ensures that the snapshot is "safe", i.e. a
1436 : : * read-only transaction running on it can execute serializably
1437 : : * without further checks. This requires waiting for concurrent
1438 : : * transactions to complete, and retrying with a new snapshot if
1439 : : * one of them could possibly create a conflict.
1440 : : *
1441 : : * As with GetSerializableTransactionSnapshot (which this is a subroutine
1442 : : * for), the passed-in Snapshot pointer should reference a static data
1443 : : * area that can safely be passed to GetSnapshotData.
1444 : : */
1445 : : static Snapshot
5750 heikki.linnakangas@i 1446 :CBC 8 : GetSafeSnapshot(Snapshot origSnapshot)
1447 : : {
1448 : : Snapshot snapshot;
1449 : :
1450 [ + - + - ]: 8 : Assert(XactReadOnly && XactDeferrable);
1451 : :
1452 : : while (true)
1453 : : {
1454 : : /*
1455 : : * GetSerializableTransactionSnapshotInt is going to call
1456 : : * GetSnapshotData, so we need to provide it the static snapshot area
1457 : : * our caller passed to us. The pointer returned is actually the same
1458 : : * one passed to it, but we avoid assuming that here.
1459 : : */
5493 tgl@sss.pgh.pa.us 1460 : 9 : snapshot = GetSerializableTransactionSnapshotInt(origSnapshot,
1461 : : NULL, InvalidPid);
1462 : :
5750 heikki.linnakangas@i 1463 [ + + ]: 9 : if (MySerializableXact == InvalidSerializableXact)
1464 : 6 : return snapshot; /* no concurrent r/w xacts; it's safe */
1465 : :
5627 1466 : 3 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
1467 : :
1468 : : /*
1469 : : * Wait for concurrent transactions to finish. Stop early if one of
1470 : : * them marked us as conflicted.
1471 : : */
1472 : 3 : MySerializableXact->flags |= SXACT_FLAG_DEFERRABLE_WAITING;
1386 andres@anarazel.de 1473 [ + + ]: 6 : while (!(dlist_is_empty(&MySerializableXact->possibleUnsafeConflicts) ||
5750 heikki.linnakangas@i 1474 [ + - ]: 3 : SxactIsROUnsafe(MySerializableXact)))
1475 : : {
5627 1476 : 3 : LWLockRelease(SerializableXactHashLock);
3684 rhaas@postgresql.org 1477 : 3 : ProcWaitForSignal(WAIT_EVENT_SAFE_SNAPSHOT);
5627 heikki.linnakangas@i 1478 : 3 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
1479 : : }
5750 1480 : 3 : MySerializableXact->flags &= ~SXACT_FLAG_DEFERRABLE_WAITING;
1481 : :
1482 [ + + ]: 3 : if (!SxactIsROUnsafe(MySerializableXact))
1483 : : {
5627 1484 : 2 : LWLockRelease(SerializableXactHashLock);
5750 1485 : 2 : break; /* success */
1486 : : }
1487 : :
5627 1488 : 1 : LWLockRelease(SerializableXactHashLock);
1489 : :
1490 : : /* else, need to retry... */
5750 1491 [ - + ]: 1 : ereport(DEBUG2,
1492 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
1493 : : errmsg_internal("deferrable snapshot was unsafe; trying a new one")));
2792 tmunro@postgresql.or 1494 : 1 : ReleasePredicateLocks(false, false);
1495 : : }
1496 : :
1497 : : /*
1498 : : * Now we have a safe snapshot, so we don't need to do any further checks.
1499 : : */
5750 heikki.linnakangas@i 1500 [ - + ]: 2 : Assert(SxactIsROSafe(MySerializableXact));
2792 tmunro@postgresql.or 1501 : 2 : ReleasePredicateLocks(false, true);
1502 : :
5750 heikki.linnakangas@i 1503 : 2 : return snapshot;
1504 : : }
1505 : :
1506 : : /*
1507 : : * GetSafeSnapshotBlockingPids
1508 : : * If the specified process is currently blocked in GetSafeSnapshot,
1509 : : * write the process IDs of all processes that it is blocked by
1510 : : * into the caller-supplied buffer output[]. The list is truncated at
1511 : : * output_size, and the number of PIDs written into the buffer is
1512 : : * returned. Returns zero if the given PID is not currently blocked
1513 : : * in GetSafeSnapshot.
1514 : : */
1515 : : int
3496 tgl@sss.pgh.pa.us 1516 : 2470 : GetSafeSnapshotBlockingPids(int blocked_pid, int *output, int output_size)
1517 : : {
1518 : 2470 : int num_written = 0;
1519 : : dlist_iter iter;
1366 andres@anarazel.de 1520 : 2470 : SERIALIZABLEXACT *blocking_sxact = NULL;
1521 : :
3496 tgl@sss.pgh.pa.us 1522 : 2470 : LWLockAcquire(SerializableXactHashLock, LW_SHARED);
1523 : :
1524 : : /* Find blocked_pid's SERIALIZABLEXACT by linear search. */
1386 andres@anarazel.de 1525 [ + - + + ]: 5221 : dlist_foreach(iter, &PredXact->activeList)
1526 : : {
1366 1527 : 3054 : SERIALIZABLEXACT *sxact =
1528 : 3054 : dlist_container(SERIALIZABLEXACT, xactLink, iter.cur);
1529 : :
3496 tgl@sss.pgh.pa.us 1530 [ + + ]: 3054 : if (sxact->pid == blocked_pid)
1531 : : {
1366 andres@anarazel.de 1532 : 303 : blocking_sxact = sxact;
3496 tgl@sss.pgh.pa.us 1533 : 303 : break;
1534 : : }
1535 : : }
1536 : :
1537 : : /* Did we find it, and is it currently waiting in GetSafeSnapshot? */
1366 andres@anarazel.de 1538 [ + + + + ]: 2470 : if (blocking_sxact != NULL && SxactIsDeferrableWaiting(blocking_sxact))
1539 : : {
1540 : : /* Traverse the list of possible unsafe conflicts collecting PIDs. */
1541 [ + - + - ]: 2 : dlist_foreach(iter, &blocking_sxact->possibleUnsafeConflicts)
1542 : : {
1386 1543 : 2 : RWConflict possibleUnsafeConflict =
1266 tgl@sss.pgh.pa.us 1544 : 2 : dlist_container(RWConflictData, inLink, iter.cur);
1545 : :
3496 1546 : 2 : output[num_written++] = possibleUnsafeConflict->sxactOut->pid;
1547 : :
1366 andres@anarazel.de 1548 [ + - ]: 2 : if (num_written >= output_size)
1549 : 2 : break;
1550 : : }
1551 : : }
1552 : :
3496 tgl@sss.pgh.pa.us 1553 : 2470 : LWLockRelease(SerializableXactHashLock);
1554 : :
1555 : 2470 : return num_written;
1556 : : }
1557 : :
1558 : : /*
1559 : : * Acquire a snapshot that can be used for the current transaction.
1560 : : *
1561 : : * Make sure we have a SERIALIZABLEXACT reference in MySerializableXact.
1562 : : * It should be current for this process and be contained in PredXact.
1563 : : *
1564 : : * The passed-in Snapshot pointer should reference a static data area that
1565 : : * can safely be passed to GetSnapshotData. The return value is actually
1566 : : * always this same pointer; no new snapshot data structure is allocated
1567 : : * within this function.
1568 : : */
1569 : : Snapshot
5519 1570 : 1702 : GetSerializableTransactionSnapshot(Snapshot snapshot)
1571 : : {
5750 heikki.linnakangas@i 1572 [ - + ]: 1702 : Assert(IsolationIsSerializable());
1573 : :
1574 : : /*
1575 : : * Can't use serializable mode while recovery is still active, as it is,
1576 : : * for example, on a hot standby. We could get here despite the check in
1577 : : * check_transaction_isolation() if default_transaction_isolation is set
1578 : : * to serializable, so phrase the hint accordingly.
1579 : : */
5186 tgl@sss.pgh.pa.us 1580 [ - + ]: 1702 : if (RecoveryInProgress())
5186 tgl@sss.pgh.pa.us 1581 [ # # ]:UBC 0 : ereport(ERROR,
1582 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1583 : : errmsg("cannot use serializable mode in a hot standby"),
1584 : : errdetail("\"default_transaction_isolation\" is set to \"serializable\"."),
1585 : : errhint("You can use \"SET default_transaction_isolation = 'repeatable read'\" to change the default.")));
1586 : :
1587 : : /*
1588 : : * A special optimization is available for SERIALIZABLE READ ONLY
1589 : : * DEFERRABLE transactions -- we can wait for a suitable snapshot and
1590 : : * thereby avoid all SSI overhead once it's running.
1591 : : */
5750 heikki.linnakangas@i 1592 [ + + + + ]:CBC 1702 : if (XactReadOnly && XactDeferrable)
1593 : 8 : return GetSafeSnapshot(snapshot);
1594 : :
5493 tgl@sss.pgh.pa.us 1595 : 1694 : return GetSerializableTransactionSnapshotInt(snapshot,
1596 : : NULL, InvalidPid);
1597 : : }
1598 : :
1599 : : /*
1600 : : * Import a snapshot to be used for the current transaction.
1601 : : *
1602 : : * This is nearly the same as GetSerializableTransactionSnapshot, except that
1603 : : * we don't take a new snapshot, but rather use the data we're handed.
1604 : : *
1605 : : * The caller must have verified that the snapshot came from a serializable
1606 : : * transaction; and if we're read-write, the source transaction must not be
1607 : : * read-only.
1608 : : */
1609 : : void
1610 : 13 : SetSerializableTransactionSnapshot(Snapshot snapshot,
1611 : : VirtualTransactionId *sourcevxid,
1612 : : int sourcepid)
1613 : : {
1614 [ - + ]: 13 : Assert(IsolationIsSerializable());
1615 : :
1616 : : /*
1617 : : * If this is called by parallel.c in a parallel worker, we don't want to
1618 : : * create a SERIALIZABLEXACT just yet because the leader's
1619 : : * SERIALIZABLEXACT will be installed with AttachSerializableXact(). We
1620 : : * also don't want to reject SERIALIZABLE READ ONLY DEFERRABLE in this
1621 : : * case, because the leader has already determined that the snapshot it
1622 : : * has passed us is safe. So there is nothing for us to do.
1623 : : */
2792 tmunro@postgresql.or 1624 [ + - ]: 13 : if (IsParallelWorker())
1625 : 13 : return;
1626 : :
1627 : : /*
1628 : : * We do not allow SERIALIZABLE READ ONLY DEFERRABLE transactions to
1629 : : * import snapshots, since there's no way to wait for a safe snapshot when
1630 : : * we're using the snap we're told to. (XXX instead of throwing an error,
1631 : : * we could just ignore the XactDeferrable flag?)
1632 : : */
5493 tgl@sss.pgh.pa.us 1633 [ # # # # ]:UBC 0 : if (XactReadOnly && XactDeferrable)
1634 [ # # ]: 0 : ereport(ERROR,
1635 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1636 : : errmsg("a snapshot-importing transaction must not be READ ONLY DEFERRABLE")));
1637 : :
3431 andres@anarazel.de 1638 : 0 : (void) GetSerializableTransactionSnapshotInt(snapshot, sourcevxid,
1639 : : sourcepid);
1640 : : }
1641 : :
1642 : : /*
1643 : : * Guts of GetSerializableTransactionSnapshot
1644 : : *
1645 : : * If sourcevxid is valid, this is actually an import operation and we should
1646 : : * skip calling GetSnapshotData, because the snapshot contents are already
1647 : : * loaded up. HOWEVER: to avoid race conditions, we must check that the
1648 : : * source xact is still running after we acquire SerializableXactHashLock.
1649 : : * We do that by calling ProcArrayInstallImportedXmin.
1650 : : */
1651 : : static Snapshot
5493 tgl@sss.pgh.pa.us 1652 :CBC 1703 : GetSerializableTransactionSnapshotInt(Snapshot snapshot,
1653 : : VirtualTransactionId *sourcevxid,
1654 : : int sourcepid)
1655 : : {
1656 : : PGPROC *proc;
1657 : : VirtualTransactionId vxid;
1658 : : SERIALIZABLEXACT *sxact,
1659 : : *othersxact;
1660 : :
1661 : : /* We only do this for serializable transactions. Once. */
5750 heikki.linnakangas@i 1662 [ - + ]: 1703 : Assert(MySerializableXact == InvalidSerializableXact);
1663 : :
1664 [ - + ]: 1703 : Assert(!RecoveryInProgress());
1665 : :
1666 : : /*
1667 : : * Since all parts of a serializable transaction must use the same
1668 : : * snapshot, it is too late to establish one after a parallel operation
1669 : : * has begun.
1670 : : */
4207 rhaas@postgresql.org 1671 [ - + ]: 1703 : if (IsInParallelMode())
4207 rhaas@postgresql.org 1672 [ # # ]:UBC 0 : elog(ERROR, "cannot establish serializable snapshot during a parallel operation");
1673 : :
5750 heikki.linnakangas@i 1674 :CBC 1703 : proc = MyProc;
1675 [ - + ]: 1703 : Assert(proc != NULL);
1676 : 1703 : GET_VXID_FROM_PGPROC(vxid, *proc);
1677 : :
1678 : : /*
1679 : : * First we get the sxact structure, which may involve looping and access
1680 : : * to the "finished" list to free a structure for use.
1681 : : *
1682 : : * We must hold SerializableXactHashLock when taking/checking the snapshot
1683 : : * to avoid race conditions, for much the same reasons that
1684 : : * GetSnapshotData takes the ProcArrayLock. Since we might have to
1685 : : * release SerializableXactHashLock to call SummarizeOldestCommittedSxact,
1686 : : * this means we have to create the sxact first, which is a bit annoying
1687 : : * (in particular, an elog(ERROR) in procarray.c would cause us to leak
1688 : : * the sxact). Consider refactoring to avoid this.
1689 : : */
1690 : : #ifdef TEST_SUMMARIZE_SERIAL
1691 : : SummarizeOldestCommittedSxact();
1692 : : #endif
1693 : 1703 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
1694 : : do
1695 : : {
1696 : 1703 : sxact = CreatePredXact();
1697 : : /* If null, push out committed sxact to SLRU summary & retry. */
1698 [ - + ]: 1703 : if (!sxact)
1699 : : {
5750 heikki.linnakangas@i 1700 :UBC 0 : LWLockRelease(SerializableXactHashLock);
1701 : 0 : SummarizeOldestCommittedSxact();
1702 : 0 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
1703 : : }
5750 heikki.linnakangas@i 1704 [ - + ]:CBC 1703 : } while (!sxact);
1705 : :
1706 : : /* Get the snapshot, or check that it's safe to use */
3431 andres@anarazel.de 1707 [ + - ]: 1703 : if (!sourcevxid)
5493 tgl@sss.pgh.pa.us 1708 : 1703 : snapshot = GetSnapshotData(snapshot);
3431 andres@anarazel.de 1709 [ # # ]:UBC 0 : else if (!ProcArrayInstallImportedXmin(snapshot->xmin, sourcevxid))
1710 : : {
5493 tgl@sss.pgh.pa.us 1711 : 0 : ReleasePredXact(sxact);
1712 : 0 : LWLockRelease(SerializableXactHashLock);
1713 [ # # ]: 0 : ereport(ERROR,
1714 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1715 : : errmsg("could not import the requested snapshot"),
1716 : : errdetail("The source process with PID %d is not running anymore.",
1717 : : sourcepid)));
1718 : : }
1719 : :
1720 : : /*
1721 : : * If there are no serializable transactions which are not read-only, we
1722 : : * can "opt out" of predicate locking and conflict checking for a
1723 : : * read-only transaction.
1724 : : *
1725 : : * The reason this is safe is that a read-only transaction can only become
1726 : : * part of a dangerous structure if it overlaps a writable transaction
1727 : : * which in turn overlaps a writable transaction which committed before
1728 : : * the read-only transaction started. A new writable transaction can
1729 : : * overlap this one, but it can't meet the other condition of overlapping
1730 : : * a transaction which committed before this one started.
1731 : : */
5750 heikki.linnakangas@i 1732 [ + + + + ]:CBC 1703 : if (XactReadOnly && PredXact->WritableSxactCount == 0)
1733 : : {
1734 : 116 : ReleasePredXact(sxact);
1735 : 116 : LWLockRelease(SerializableXactHashLock);
1736 : 116 : return snapshot;
1737 : : }
1738 : :
1739 : : /* Initialize the structure. */
1740 : 1587 : sxact->vxid = vxid;
1741 : 1587 : sxact->SeqNo.lastCommitBeforeSnapshot = PredXact->LastSxactCommitSeqNo;
5600 1742 : 1587 : sxact->prepareSeqNo = InvalidSerCommitSeqNo;
5750 1743 : 1587 : sxact->commitSeqNo = InvalidSerCommitSeqNo;
1386 andres@anarazel.de 1744 : 1587 : dlist_init(&(sxact->outConflicts));
1745 : 1587 : dlist_init(&(sxact->inConflicts));
1746 : 1587 : dlist_init(&(sxact->possibleUnsafeConflicts));
5750 heikki.linnakangas@i 1747 : 1587 : sxact->topXid = GetTopTransactionIdIfAny();
1748 : 1587 : sxact->finishedBefore = InvalidTransactionId;
1749 : 1587 : sxact->xmin = snapshot->xmin;
1750 : 1587 : sxact->pid = MyProcPid;
987 1751 : 1587 : sxact->pgprocno = MyProcNumber;
1386 andres@anarazel.de 1752 : 1587 : dlist_init(&sxact->predicateLocks);
1753 : 1587 : dlist_node_init(&sxact->finishedLink);
5750 heikki.linnakangas@i 1754 : 1587 : sxact->flags = 0;
1755 [ + + ]: 1587 : if (XactReadOnly)
1756 : : {
1757 : : dlist_iter iter;
1758 : :
1759 : 108 : sxact->flags |= SXACT_FLAG_READ_ONLY;
1760 : :
1761 : : /*
1762 : : * Register all concurrent r/w transactions as possible conflicts; if
1763 : : * all of them commit without any outgoing conflicts to earlier
1764 : : * transactions then this snapshot can be deemed safe (and we can run
1765 : : * without tracking predicate locks).
1766 : : */
1386 andres@anarazel.de 1767 [ + - + + ]: 473 : dlist_foreach(iter, &PredXact->activeList)
1768 : : {
1769 : 365 : othersxact = dlist_container(SERIALIZABLEXACT, xactLink, iter.cur);
1770 : :
5599 heikki.linnakangas@i 1771 [ + + ]: 365 : if (!SxactIsCommitted(othersxact)
1772 [ + - ]: 244 : && !SxactIsDoomed(othersxact)
1773 [ + + ]: 244 : && !SxactIsReadOnly(othersxact))
1774 : : {
5750 1775 : 135 : SetPossibleUnsafeConflict(sxact, othersxact);
1776 : : }
1777 : : }
1778 : :
1779 : : /*
1780 : : * If we didn't find any possibly unsafe conflicts because every
1781 : : * uncommitted writable transaction turned out to be doomed, then we
1782 : : * can "opt out" immediately. See comments above the earlier check
1783 : : * for PredXact->WritableSxactCount == 0.
1784 : : */
1337 tmunro@postgresql.or 1785 [ - + ]: 108 : if (dlist_is_empty(&sxact->possibleUnsafeConflicts))
1786 : : {
1337 tmunro@postgresql.or 1787 :UBC 0 : ReleasePredXact(sxact);
1788 : 0 : LWLockRelease(SerializableXactHashLock);
1789 : 0 : return snapshot;
1790 : : }
1791 : : }
1792 : : else
1793 : : {
5750 heikki.linnakangas@i 1794 :CBC 1479 : ++(PredXact->WritableSxactCount);
1795 [ - + ]: 1479 : Assert(PredXact->WritableSxactCount <=
1796 : : (MaxBackends + max_prepared_xacts));
1797 : : }
1798 : :
1799 : : /* Maintain serializable global xmin info. */
1337 tmunro@postgresql.or 1800 [ + + ]: 1587 : if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
1801 : : {
1802 [ - + ]: 864 : Assert(PredXact->SxactGlobalXminCount == 0);
1803 : 864 : PredXact->SxactGlobalXmin = snapshot->xmin;
1804 : 864 : PredXact->SxactGlobalXminCount = 1;
1805 : 864 : SerialSetActiveSerXmin(snapshot->xmin);
1806 : : }
1807 [ + + ]: 723 : else if (TransactionIdEquals(snapshot->xmin, PredXact->SxactGlobalXmin))
1808 : : {
1809 [ - + ]: 687 : Assert(PredXact->SxactGlobalXminCount > 0);
1810 : 687 : PredXact->SxactGlobalXminCount++;
1811 : : }
1812 : : else
1813 : : {
1814 [ - + ]: 36 : Assert(TransactionIdFollows(snapshot->xmin, PredXact->SxactGlobalXmin));
1815 : : }
1816 : :
5750 heikki.linnakangas@i 1817 : 1587 : MySerializableXact = sxact;
5627 1818 : 1587 : MyXactDidWrite = false; /* haven't written anything yet */
1819 : :
5750 1820 : 1587 : LWLockRelease(SerializableXactHashLock);
1821 : :
2792 tmunro@postgresql.or 1822 : 1587 : CreateLocalPredicateLockHash();
1823 : :
1824 : 1587 : return snapshot;
1825 : : }
1826 : :
1827 : : static void
1828 : 1600 : CreateLocalPredicateLockHash(void)
1829 : : {
1830 : : HASHCTL hash_ctl;
1831 : :
1832 : : /* Initialize the backend-local hash table of parent locks */
5750 heikki.linnakangas@i 1833 [ - + ]: 1600 : Assert(LocalPredicateLockHash == NULL);
1834 : 1600 : hash_ctl.keysize = sizeof(PREDICATELOCKTARGETTAG);
1835 : 1600 : hash_ctl.entrysize = sizeof(LOCALPREDICATELOCK);
1836 : 1600 : LocalPredicateLockHash = hash_create("Local predicate lock",
1837 : : max_predicate_locks_per_xact,
1838 : : &hash_ctl,
1839 : : HASH_ELEM | HASH_BLOBS);
1840 : 1600 : }
1841 : :
1842 : : /*
1843 : : * Register the top level XID in SerializableXidHash.
1844 : : * Also store it for easy reference in MySerializableXact.
1845 : : */
1846 : : void
5615 1847 : 165653 : RegisterPredicateLockingXid(TransactionId xid)
1848 : : {
1849 : : SERIALIZABLEXIDTAG sxidtag;
1850 : : SERIALIZABLEXID *sxid;
1851 : : bool found;
1852 : :
1853 : : /*
1854 : : * If we're not tracking predicate lock data for this transaction, we
1855 : : * should ignore the request and return quickly.
1856 : : */
5750 1857 [ + + ]: 165653 : if (MySerializableXact == InvalidSerializableXact)
1858 : 164341 : return;
1859 : :
1860 : : /* We should have a valid XID and be at the top level. */
1861 [ - + ]: 1312 : Assert(TransactionIdIsValid(xid));
1862 : :
5627 1863 : 1312 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
1864 : :
1865 : : /* This should only be done once per transaction. */
1866 [ - + ]: 1312 : Assert(MySerializableXact->topXid == InvalidTransactionId);
1867 : :
5750 1868 : 1312 : MySerializableXact->topXid = xid;
1869 : :
1870 : 1312 : sxidtag.xid = xid;
1871 : 1312 : sxid = (SERIALIZABLEXID *) hash_search(SerializableXidHash,
1872 : : &sxidtag,
1873 : : HASH_ENTER, &found);
1874 [ - + ]: 1312 : Assert(!found);
1875 : :
1876 : : /* Initialize the structure. */
5627 1877 : 1312 : sxid->myXact = MySerializableXact;
5750 1878 : 1312 : LWLockRelease(SerializableXactHashLock);
1879 : : }
1880 : :
1881 : :
1882 : : /*
1883 : : * Check whether a particular lock is held by this transaction.
1884 : : *
1885 : : * Important note: this function may return false even if the lock is
1886 : : * being held, because it uses the local lock table which is not
1887 : : * updated if another transaction modifies our lock list (e.g. to
1888 : : * split an index page). It can also return true when a coarser
1889 : : * granularity lock that covers this target is being held. Be careful
1890 : : * to only use this function in circumstances where such errors are
1891 : : * acceptable!
1892 : : */
1893 : : static bool
5615 tgl@sss.pgh.pa.us 1894 : 41992 : PredicateLockExists(const PREDICATELOCKTARGETTAG *targettag)
1895 : : {
1896 : : LOCALPREDICATELOCK *lock;
1897 : :
1898 : : /* check local hash table */
5750 heikki.linnakangas@i 1899 : 41992 : lock = (LOCALPREDICATELOCK *) hash_search(LocalPredicateLockHash,
1900 : : targettag,
1901 : : HASH_FIND, NULL);
1902 : :
1903 [ + + ]: 41992 : if (!lock)
1904 : 12842 : return false;
1905 : :
1906 : : /*
1907 : : * Found entry in the table, but still need to check whether it's actually
1908 : : * held -- it could just be a parent of some held lock.
1909 : : */
1910 : 29150 : return lock->held;
1911 : : }
1912 : :
1913 : : /*
1914 : : * Return the parent lock tag in the lock hierarchy: the next coarser
1915 : : * lock that covers the provided tag.
1916 : : *
1917 : : * Returns true and sets *parent to the parent tag if one exists,
1918 : : * returns false if none exists.
1919 : : */
1920 : : static bool
5615 tgl@sss.pgh.pa.us 1921 : 25546 : GetParentPredicateLockTag(const PREDICATELOCKTARGETTAG *tag,
1922 : : PREDICATELOCKTARGETTAG *parent)
1923 : : {
5750 heikki.linnakangas@i 1924 [ + + + + : 25546 : switch (GET_PREDICATELOCKTARGETTAG_TYPE(*tag))
+ - ]
1925 : : {
1926 : 9031 : case PREDLOCKTAG_RELATION:
1927 : : /* relation locks have no parent lock */
1928 : 9031 : return false;
1929 : :
1930 : 7607 : case PREDLOCKTAG_PAGE:
1931 : : /* parent lock is relation lock */
1932 : 7607 : SET_PREDICATELOCKTARGETTAG_RELATION(*parent,
1933 : : GET_PREDICATELOCKTARGETTAG_DB(*tag),
1934 : : GET_PREDICATELOCKTARGETTAG_RELATION(*tag));
1935 : :
1936 : 7607 : return true;
1937 : :
1938 : 8908 : case PREDLOCKTAG_TUPLE:
1939 : : /* parent lock is page lock */
1940 : 8908 : SET_PREDICATELOCKTARGETTAG_PAGE(*parent,
1941 : : GET_PREDICATELOCKTARGETTAG_DB(*tag),
1942 : : GET_PREDICATELOCKTARGETTAG_RELATION(*tag),
1943 : : GET_PREDICATELOCKTARGETTAG_PAGE(*tag));
1944 : 8908 : return true;
1945 : : }
1946 : :
1947 : : /* not reachable */
5750 heikki.linnakangas@i 1948 :UBC 0 : Assert(false);
1949 : : return false;
1950 : : }
1951 : :
1952 : : /*
1953 : : * Check whether the lock we are considering is already covered by a
1954 : : * coarser lock for our transaction.
1955 : : *
1956 : : * Like PredicateLockExists, this function might return a false
1957 : : * negative, but it will never return a false positive.
1958 : : */
1959 : : static bool
5615 tgl@sss.pgh.pa.us 1960 :CBC 8640 : CoarserLockCovers(const PREDICATELOCKTARGETTAG *newtargettag)
1961 : : {
1962 : : PREDICATELOCKTARGETTAG targettag,
1963 : : parenttag;
1964 : :
5750 heikki.linnakangas@i 1965 : 8640 : targettag = *newtargettag;
1966 : :
1967 : : /* check parents iteratively until no more */
1968 [ + + ]: 13489 : while (GetParentPredicateLockTag(&targettag, &parenttag))
1969 : : {
1970 : 9512 : targettag = parenttag;
1971 [ + + ]: 9512 : if (PredicateLockExists(&targettag))
1972 : 4663 : return true;
1973 : : }
1974 : :
1975 : : /* no more parents to check; lock is not covered */
1976 : 3977 : return false;
1977 : : }
1978 : :
1979 : : /*
1980 : : * Remove the dummy entry from the predicate lock target hash, to free up some
1981 : : * scratch space. The caller must be holding SerializablePredicateListLock,
1982 : : * and must restore the entry with RestoreScratchTarget() before releasing the
1983 : : * lock.
1984 : : *
1985 : : * If lockheld is true, the caller is already holding the partition lock
1986 : : * of the partition containing the scratch entry.
1987 : : */
1988 : : static void
5629 1989 : 28 : RemoveScratchTarget(bool lockheld)
1990 : : {
1991 : : bool found;
1992 : :
2365 tgl@sss.pgh.pa.us 1993 [ - + ]: 28 : Assert(LWLockHeldByMe(SerializablePredicateListLock));
1994 : :
5629 heikki.linnakangas@i 1995 [ - + ]: 28 : if (!lockheld)
5629 heikki.linnakangas@i 1996 :UBC 0 : LWLockAcquire(ScratchPartitionLock, LW_EXCLUSIVE);
5629 heikki.linnakangas@i 1997 :CBC 28 : hash_search_with_hash_value(PredicateLockTargetHash,
1998 : : &ScratchTargetTag,
1999 : : ScratchTargetTagHash,
2000 : : HASH_REMOVE, &found);
2001 [ - + ]: 28 : Assert(found);
2002 [ - + ]: 28 : if (!lockheld)
5629 heikki.linnakangas@i 2003 :UBC 0 : LWLockRelease(ScratchPartitionLock);
5629 heikki.linnakangas@i 2004 :CBC 28 : }
2005 : :
2006 : : /*
2007 : : * Re-insert the dummy entry in predicate lock target hash.
2008 : : */
2009 : : static void
2010 : 28 : RestoreScratchTarget(bool lockheld)
2011 : : {
2012 : : bool found;
2013 : :
2365 tgl@sss.pgh.pa.us 2014 [ - + ]: 28 : Assert(LWLockHeldByMe(SerializablePredicateListLock));
2015 : :
5629 heikki.linnakangas@i 2016 [ - + ]: 28 : if (!lockheld)
5629 heikki.linnakangas@i 2017 :UBC 0 : LWLockAcquire(ScratchPartitionLock, LW_EXCLUSIVE);
5629 heikki.linnakangas@i 2018 :CBC 28 : hash_search_with_hash_value(PredicateLockTargetHash,
2019 : : &ScratchTargetTag,
2020 : : ScratchTargetTagHash,
2021 : : HASH_ENTER, &found);
2022 [ - + ]: 28 : Assert(!found);
2023 [ - + ]: 28 : if (!lockheld)
5629 heikki.linnakangas@i 2024 :UBC 0 : LWLockRelease(ScratchPartitionLock);
5629 heikki.linnakangas@i 2025 :CBC 28 : }
2026 : :
2027 : : /*
2028 : : * Check whether the list of related predicate locks is empty for a
2029 : : * predicate lock target, and remove the target if it is.
2030 : : */
2031 : : static void
5750 2032 : 3971 : RemoveTargetIfNoLongerUsed(PREDICATELOCKTARGET *target, uint32 targettaghash)
2033 : : {
2034 : : PREDICATELOCKTARGET *rmtarget PG_USED_FOR_ASSERTS_ONLY;
2035 : :
2365 tgl@sss.pgh.pa.us 2036 [ - + ]: 3971 : Assert(LWLockHeldByMe(SerializablePredicateListLock));
2037 : :
2038 : : /* Can't remove it until no locks at this target. */
1386 andres@anarazel.de 2039 [ + + ]: 3971 : if (!dlist_is_empty(&target->predicateLocks))
5750 heikki.linnakangas@i 2040 : 979 : return;
2041 : :
2042 : : /* Actually remove the target. */
2043 : 2992 : rmtarget = hash_search_with_hash_value(PredicateLockTargetHash,
2044 : 2992 : &target->tag,
2045 : : targettaghash,
2046 : : HASH_REMOVE, NULL);
2047 [ - + ]: 2992 : Assert(rmtarget == target);
2048 : : }
2049 : :
2050 : : /*
2051 : : * Delete child target locks owned by this process.
2052 : : * This implementation is assuming that the usage of each target tag field
2053 : : * is uniform. No need to make this hard if we don't have to.
2054 : : *
2055 : : * We acquire an LWLock in the case of parallel mode, because worker
2056 : : * backends have access to the leader's SERIALIZABLEXACT. Otherwise,
2057 : : * we aren't acquiring LWLocks for the predicate lock or lock
2058 : : * target structures associated with this transaction unless we're going
2059 : : * to modify them, because no other process is permitted to modify our
2060 : : * locks.
2061 : : */
2062 : : static void
5615 tgl@sss.pgh.pa.us 2063 : 2392 : DeleteChildTargetLocks(const PREDICATELOCKTARGETTAG *newtargettag)
2064 : : {
2065 : : SERIALIZABLEXACT *sxact;
2066 : : PREDICATELOCK *predlock;
2067 : : dlist_mutable_iter iter;
2068 : :
2365 2069 : 2392 : LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
5627 heikki.linnakangas@i 2070 : 2392 : sxact = MySerializableXact;
2792 tmunro@postgresql.or 2071 [ + + ]: 2392 : if (IsInParallelMode())
2365 tgl@sss.pgh.pa.us 2072 : 11 : LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
2073 : :
1386 andres@anarazel.de 2074 [ + - + + ]: 7561 : dlist_foreach_modify(iter, &sxact->predicateLocks)
2075 : : {
2076 : : PREDICATELOCKTAG oldlocktag;
2077 : : PREDICATELOCKTARGET *oldtarget;
2078 : : PREDICATELOCKTARGETTAG oldtargettag;
2079 : :
2080 : 5169 : predlock = dlist_container(PREDICATELOCK, xactLink, iter.cur);
2081 : :
5750 heikki.linnakangas@i 2082 : 5169 : oldlocktag = predlock->tag;
2083 [ - + ]: 5169 : Assert(oldlocktag.myXact == sxact);
2084 : 5169 : oldtarget = oldlocktag.myTarget;
2085 : 5169 : oldtargettag = oldtarget->tag;
2086 : :
2087 [ + + + - : 5169 : if (TargetTagIsCoveredBy(oldtargettag, *newtargettag))
+ + + + +
+ - + +
- ]
2088 : : {
2089 : : uint32 oldtargettaghash;
2090 : : LWLock *partitionLock;
2091 : : PREDICATELOCK *rmpredlock PG_USED_FOR_ASSERTS_ONLY;
2092 : :
2093 : 679 : oldtargettaghash = PredicateLockTargetTagHashCode(&oldtargettag);
2094 : 679 : partitionLock = PredicateLockHashPartitionLock(oldtargettaghash);
2095 : :
2096 : 679 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
2097 : :
1386 andres@anarazel.de 2098 : 679 : dlist_delete(&predlock->xactLink);
2099 : 679 : dlist_delete(&predlock->targetLink);
5750 heikki.linnakangas@i 2100 : 679 : rmpredlock = hash_search_with_hash_value
2101 : : (PredicateLockHash,
2102 : : &oldlocktag,
2103 : 679 : PredicateLockHashCodeFromTargetHashCode(&oldlocktag,
2104 : : oldtargettaghash),
2105 : : HASH_REMOVE, NULL);
2106 [ - + ]: 679 : Assert(rmpredlock == predlock);
2107 : :
2108 : 679 : RemoveTargetIfNoLongerUsed(oldtarget, oldtargettaghash);
2109 : :
2110 : 679 : LWLockRelease(partitionLock);
2111 : :
2112 : 679 : DecrementParentLocks(&oldtargettag);
2113 : : }
2114 : : }
2792 tmunro@postgresql.or 2115 [ + + ]: 2392 : if (IsInParallelMode())
2365 tgl@sss.pgh.pa.us 2116 : 11 : LWLockRelease(&sxact->perXactPredicateListLock);
2117 : 2392 : LWLockRelease(SerializablePredicateListLock);
5750 heikki.linnakangas@i 2118 : 2392 : }
2119 : :
2120 : : /*
2121 : : * Returns the promotion limit for a given predicate lock target. This is the
2122 : : * max number of descendant locks allowed before promoting to the specified
2123 : : * tag. Note that the limit includes non-direct descendants (e.g., both tuples
2124 : : * and pages for a relation lock).
2125 : : *
2126 : : * Currently the default limit is 2 for a page lock, and half of the value of
2127 : : * max_pred_locks_per_transaction - 1 for a relation lock, to match behavior
2128 : : * of earlier releases when upgrading.
2129 : : *
2130 : : * TODO SSI: We should probably add additional GUCs to allow a maximum ratio
2131 : : * of page and tuple locks based on the pages in a relation, and the maximum
2132 : : * ratio of tuple locks to tuples in a page. This would provide more
2133 : : * generally "balanced" allocation of locks to where they are most useful,
2134 : : * while still allowing the absolute numbers to prevent one relation from
2135 : : * tying up all predicate lock resources.
2136 : : */
2137 : : static int
3499 kgrittn@postgresql.o 2138 : 4849 : MaxPredicateChildLocks(const PREDICATELOCKTARGETTAG *tag)
2139 : : {
5750 heikki.linnakangas@i 2140 [ + - + + : 4849 : switch (GET_PREDICATELOCKTARGETTAG_TYPE(*tag))
- - ]
2141 : : {
2142 : 3264 : case PREDLOCKTAG_RELATION:
3499 kgrittn@postgresql.o 2143 : 3264 : return max_predicate_locks_per_relation < 0
2144 : : ? (max_predicate_locks_per_xact
2145 : 3264 : / (-max_predicate_locks_per_relation)) - 1
2146 [ + - ]: 3264 : : max_predicate_locks_per_relation;
2147 : :
5750 heikki.linnakangas@i 2148 : 1585 : case PREDLOCKTAG_PAGE:
3499 kgrittn@postgresql.o 2149 : 1585 : return max_predicate_locks_per_page;
2150 : :
5750 heikki.linnakangas@i 2151 :UBC 0 : case PREDLOCKTAG_TUPLE:
2152 : :
2153 : : /*
2154 : : * not reachable: nothing is finer-granularity than a tuple, so we
2155 : : * should never try to promote to it.
2156 : : */
2157 : 0 : Assert(false);
2158 : : return 0;
2159 : : }
2160 : :
2161 : : /* not reachable */
2162 : 0 : Assert(false);
2163 : : return 0;
2164 : : }
2165 : :
2166 : : /*
2167 : : * For all ancestors of a newly-acquired predicate lock, increment
2168 : : * their child count in the parent hash table. If any of them have
2169 : : * more descendants than their promotion threshold, acquire the
2170 : : * coarsest such lock.
2171 : : *
2172 : : * Returns true if a parent lock was acquired and false otherwise.
2173 : : */
2174 : : static bool
5615 tgl@sss.pgh.pa.us 2175 :CBC 3977 : CheckAndPromotePredicateLockRequest(const PREDICATELOCKTARGETTAG *reqtag)
2176 : : {
2177 : : PREDICATELOCKTARGETTAG targettag,
2178 : : nexttag,
2179 : : promotiontag;
2180 : : LOCALPREDICATELOCK *parentlock;
2181 : : bool found,
2182 : : promote;
2183 : :
5750 heikki.linnakangas@i 2184 : 3977 : promote = false;
2185 : :
2186 : 3977 : targettag = *reqtag;
2187 : :
2188 : : /* check parents iteratively */
2189 [ + + ]: 12803 : while (GetParentPredicateLockTag(&targettag, &nexttag))
2190 : : {
2191 : 4849 : targettag = nexttag;
2192 : 4849 : parentlock = (LOCALPREDICATELOCK *) hash_search(LocalPredicateLockHash,
2193 : : &targettag,
2194 : : HASH_ENTER,
2195 : : &found);
2196 [ + + ]: 4849 : if (!found)
2197 : : {
2198 : 3428 : parentlock->held = false;
2199 : 3428 : parentlock->childLocks = 1;
2200 : : }
2201 : : else
2202 : 1421 : parentlock->childLocks++;
2203 : :
3499 kgrittn@postgresql.o 2204 [ + + ]: 4849 : if (parentlock->childLocks >
2205 : 4849 : MaxPredicateChildLocks(&targettag))
2206 : : {
2207 : : /*
2208 : : * We should promote to this parent lock. Continue to check its
2209 : : * ancestors, however, both to get their child counts right and to
2210 : : * check whether we should just go ahead and promote to one of
2211 : : * them.
2212 : : */
5750 heikki.linnakangas@i 2213 : 173 : promotiontag = targettag;
2214 : 173 : promote = true;
2215 : : }
2216 : : }
2217 : :
2218 [ + + ]: 3977 : if (promote)
2219 : : {
2220 : : /* acquire coarsest ancestor eligible for promotion */
2221 : 173 : PredicateLockAcquire(&promotiontag);
2222 : 173 : return true;
2223 : : }
2224 : : else
2225 : 3804 : return false;
2226 : : }
2227 : :
2228 : : /*
2229 : : * When releasing a lock, decrement the child count on all ancestor
2230 : : * locks.
2231 : : *
2232 : : * This is called only when releasing a lock via
2233 : : * DeleteChildTargetLocks (i.e. when a lock becomes redundant because
2234 : : * we've acquired its parent, possibly due to promotion) or when a new
2235 : : * MVCC write lock makes the predicate lock unnecessary. There's no
2236 : : * point in calling it when locks are released at transaction end, as
2237 : : * this information is no longer needed.
2238 : : */
2239 : : static void
5615 tgl@sss.pgh.pa.us 2240 : 1077 : DecrementParentLocks(const PREDICATELOCKTARGETTAG *targettag)
2241 : : {
2242 : : PREDICATELOCKTARGETTAG parenttag,
2243 : : nexttag;
2244 : :
5750 heikki.linnakangas@i 2245 : 1077 : parenttag = *targettag;
2246 : :
2247 [ + + ]: 3231 : while (GetParentPredicateLockTag(&parenttag, &nexttag))
2248 : : {
2249 : : uint32 targettaghash;
2250 : : LOCALPREDICATELOCK *parentlock,
2251 : : *rmlock PG_USED_FOR_ASSERTS_ONLY;
2252 : :
2253 : 2154 : parenttag = nexttag;
2254 : 2154 : targettaghash = PredicateLockTargetTagHashCode(&parenttag);
2255 : : parentlock = (LOCALPREDICATELOCK *)
2256 : 2154 : hash_search_with_hash_value(LocalPredicateLockHash,
2257 : : &parenttag, targettaghash,
2258 : : HASH_FIND, NULL);
2259 : :
2260 : : /*
2261 : : * There's a small chance the parent lock doesn't exist in the lock
2262 : : * table. This can happen if we prematurely removed it because an
2263 : : * index split caused the child refcount to be off.
2264 : : */
2265 [ - + ]: 2154 : if (parentlock == NULL)
5750 heikki.linnakangas@i 2266 :UBC 0 : continue;
2267 : :
5750 heikki.linnakangas@i 2268 :CBC 2154 : parentlock->childLocks--;
2269 : :
2270 : : /*
2271 : : * Under similar circumstances the parent lock's refcount might be
2272 : : * zero. This only happens if we're holding that lock (otherwise we
2273 : : * would have removed the entry).
2274 : : */
2275 [ - + ]: 2154 : if (parentlock->childLocks < 0)
2276 : : {
5750 heikki.linnakangas@i 2277 [ # # ]:UBC 0 : Assert(parentlock->held);
2278 : 0 : parentlock->childLocks = 0;
2279 : : }
2280 : :
5750 heikki.linnakangas@i 2281 [ + + + + ]:CBC 2154 : if ((parentlock->childLocks == 0) && (!parentlock->held))
2282 : : {
2283 : : rmlock = (LOCALPREDICATELOCK *)
2284 : 784 : hash_search_with_hash_value(LocalPredicateLockHash,
2285 : : &parenttag, targettaghash,
2286 : : HASH_REMOVE, NULL);
2287 [ - + ]: 784 : Assert(rmlock == parentlock);
2288 : : }
2289 : : }
2290 : 1077 : }
2291 : :
2292 : : /*
2293 : : * Indicate that a predicate lock on the given target is held by the
2294 : : * specified transaction. Has no effect if the lock is already held.
2295 : : *
2296 : : * This updates the lock table and the sxact's lock list, and creates
2297 : : * the lock target if necessary, but does *not* do anything related to
2298 : : * granularity promotion or the local lock table. See
2299 : : * PredicateLockAcquire for that.
2300 : : */
2301 : : static void
5615 tgl@sss.pgh.pa.us 2302 : 3977 : CreatePredicateLock(const PREDICATELOCKTARGETTAG *targettag,
2303 : : uint32 targettaghash,
2304 : : SERIALIZABLEXACT *sxact)
2305 : : {
2306 : : PREDICATELOCKTARGET *target;
2307 : : PREDICATELOCKTAG locktag;
2308 : : PREDICATELOCK *lock;
2309 : : LWLock *partitionLock;
2310 : : bool found;
2311 : :
5750 heikki.linnakangas@i 2312 : 3977 : partitionLock = PredicateLockHashPartitionLock(targettaghash);
2313 : :
2365 tgl@sss.pgh.pa.us 2314 : 3977 : LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
2792 tmunro@postgresql.or 2315 [ + + ]: 3977 : if (IsInParallelMode())
2365 tgl@sss.pgh.pa.us 2316 : 16 : LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
5750 heikki.linnakangas@i 2317 : 3977 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
2318 : :
2319 : : /* Make sure that the target is represented. */
2320 : : target = (PREDICATELOCKTARGET *)
2321 : 3977 : hash_search_with_hash_value(PredicateLockTargetHash,
2322 : : targettag, targettaghash,
2323 : : HASH_ENTER_NULL, &found);
2324 [ - + ]: 3977 : if (!target)
5750 heikki.linnakangas@i 2325 [ # # ]:UBC 0 : ereport(ERROR,
2326 : : (errcode(ERRCODE_OUT_OF_MEMORY),
2327 : : errmsg("out of shared memory"),
2328 : : errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
5750 heikki.linnakangas@i 2329 [ + + ]:CBC 3977 : if (!found)
1386 andres@anarazel.de 2330 : 2992 : dlist_init(&target->predicateLocks);
2331 : :
2332 : : /* We've got the sxact and target, make sure they're joined. */
5750 heikki.linnakangas@i 2333 : 3977 : locktag.myTarget = target;
2334 : 3977 : locktag.myXact = sxact;
2335 : : lock = (PREDICATELOCK *)
2336 : 3977 : hash_search_with_hash_value(PredicateLockHash, &locktag,
3424 tgl@sss.pgh.pa.us 2337 : 3977 : PredicateLockHashCodeFromTargetHashCode(&locktag, targettaghash),
2338 : : HASH_ENTER_NULL, &found);
5750 heikki.linnakangas@i 2339 [ - + ]: 3977 : if (!lock)
5750 heikki.linnakangas@i 2340 [ # # ]:UBC 0 : ereport(ERROR,
2341 : : (errcode(ERRCODE_OUT_OF_MEMORY),
2342 : : errmsg("out of shared memory"),
2343 : : errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
2344 : :
5750 heikki.linnakangas@i 2345 [ + + ]:CBC 3977 : if (!found)
2346 : : {
1386 andres@anarazel.de 2347 : 3971 : dlist_push_tail(&target->predicateLocks, &lock->targetLink);
2348 : 3971 : dlist_push_tail(&sxact->predicateLocks, &lock->xactLink);
5687 heikki.linnakangas@i 2349 : 3971 : lock->commitSeqNo = InvalidSerCommitSeqNo;
2350 : : }
2351 : :
5750 2352 : 3977 : LWLockRelease(partitionLock);
2792 tmunro@postgresql.or 2353 [ + + ]: 3977 : if (IsInParallelMode())
2365 tgl@sss.pgh.pa.us 2354 : 16 : LWLockRelease(&sxact->perXactPredicateListLock);
2355 : 3977 : LWLockRelease(SerializablePredicateListLock);
5750 heikki.linnakangas@i 2356 : 3977 : }
2357 : :
2358 : : /*
2359 : : * Acquire a predicate lock on the specified target for the current
2360 : : * connection if not already held. This updates the local lock table
2361 : : * and uses it to implement granularity promotion. It will consolidate
2362 : : * multiple locks into a coarser lock if warranted, and will release
2363 : : * any finer-grained locks covered by the new one.
2364 : : */
2365 : : static void
5615 tgl@sss.pgh.pa.us 2366 : 26165 : PredicateLockAcquire(const PREDICATELOCKTARGETTAG *targettag)
2367 : : {
2368 : : uint32 targettaghash;
2369 : : bool found;
2370 : : LOCALPREDICATELOCK *locallock;
2371 : :
2372 : : /* Do we have the lock already, or a covering lock? */
5750 heikki.linnakangas@i 2373 [ + + ]: 26165 : if (PredicateLockExists(targettag))
2374 : 22188 : return;
2375 : :
2376 [ + + ]: 8640 : if (CoarserLockCovers(targettag))
2377 : 4663 : return;
2378 : :
2379 : : /* the same hash and LW lock apply to the lock target and the local lock. */
2380 : 3977 : targettaghash = PredicateLockTargetTagHashCode(targettag);
2381 : :
2382 : : /* Acquire lock in local table */
2383 : : locallock = (LOCALPREDICATELOCK *)
2384 : 3977 : hash_search_with_hash_value(LocalPredicateLockHash,
2385 : : targettag, targettaghash,
2386 : : HASH_ENTER, &found);
2387 : 3977 : locallock->held = true;
2388 [ + + ]: 3977 : if (!found)
2389 : 3644 : locallock->childLocks = 0;
2390 : :
2391 : : /* Actually create the lock */
5627 2392 : 3977 : CreatePredicateLock(targettag, targettaghash, MySerializableXact);
2393 : :
2394 : : /*
2395 : : * Lock has been acquired. Check whether it should be promoted to a
2396 : : * coarser granularity, or whether there are finer-granularity locks to
2397 : : * clean up.
2398 : : */
5750 2399 [ + + ]: 3977 : if (CheckAndPromotePredicateLockRequest(targettag))
2400 : : {
2401 : : /*
2402 : : * Lock request was promoted to a coarser-granularity lock, and that
2403 : : * lock was acquired. It will delete this lock and any of its
2404 : : * children, so we're done.
2405 : : */
2406 : : }
2407 : : else
2408 : : {
2409 : : /* Clean up any finer-granularity locks */
2410 [ + + ]: 3804 : if (GET_PREDICATELOCKTARGETTAG_TYPE(*targettag) != PREDLOCKTAG_TUPLE)
2411 : 2392 : DeleteChildTargetLocks(targettag);
2412 : : }
2413 : : }
2414 : :
2415 : :
2416 : : /*
2417 : : * PredicateLockRelation
2418 : : *
2419 : : * Gets a predicate lock at the relation level.
2420 : : * Skip if not in full serializable transaction isolation level.
2421 : : * Skip if this is a temporary table.
2422 : : * Clear any finer-grained predicate locks this session has on the relation.
2423 : : */
2424 : : void
5615 2425 : 445931 : PredicateLockRelation(Relation relation, Snapshot snapshot)
2426 : : {
2427 : : PREDICATELOCKTARGETTAG tag;
2428 : :
5622 2429 [ + + ]: 445931 : if (!SerializationNeededForRead(relation, snapshot))
5750 2430 : 445199 : return;
2431 : :
2432 : 732 : SET_PREDICATELOCKTARGETTAG_RELATION(tag,
2433 : : relation->rd_locator.dbOid,
2434 : : relation->rd_id);
2435 : 732 : PredicateLockAcquire(&tag);
2436 : : }
2437 : :
2438 : : /*
2439 : : * PredicateLockPage
2440 : : *
2441 : : * Gets a predicate lock at the page level.
2442 : : * Skip if not in full serializable transaction isolation level.
2443 : : * Skip if this is a temporary table.
2444 : : * Skip if a coarser predicate lock already covers this page.
2445 : : * Clear any finer-grained predicate locks this session has on the relation.
2446 : : */
2447 : : void
5615 2448 : 13411890 : PredicateLockPage(Relation relation, BlockNumber blkno, Snapshot snapshot)
2449 : : {
2450 : : PREDICATELOCKTARGETTAG tag;
2451 : :
5622 2452 [ + + ]: 13411890 : if (!SerializationNeededForRead(relation, snapshot))
5750 2453 : 13392945 : return;
2454 : :
2455 : 18945 : SET_PREDICATELOCKTARGETTAG_PAGE(tag,
2456 : : relation->rd_locator.dbOid,
2457 : : relation->rd_id,
2458 : : blkno);
2459 : 18945 : PredicateLockAcquire(&tag);
2460 : : }
2461 : :
2462 : : /*
2463 : : * PredicateLockTID
2464 : : *
2465 : : * Gets a predicate lock at the tuple level.
2466 : : * Skip if not in full serializable transaction isolation level.
2467 : : * Skip if this is a temporary table.
2468 : : */
2469 : : void
371 peter@eisentraut.org 2470 : 22029053 : PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapshot,
2471 : : TransactionId tuple_xid)
2472 : : {
2473 : : PREDICATELOCKTARGETTAG tag;
2474 : :
5622 heikki.linnakangas@i 2475 [ + + ]: 22029053 : if (!SerializationNeededForRead(relation, snapshot))
5750 2476 : 22022738 : return;
2477 : :
2478 : : /*
2479 : : * Return if this xact wrote it.
2480 : : */
2481 [ + - ]: 6317 : if (relation->rd_index == NULL)
2482 : : {
2483 : : /* If we wrote it; we already have a write lock. */
2473 tmunro@postgresql.or 2484 [ + + ]: 6317 : if (TransactionIdIsCurrentTransactionId(tuple_xid))
2551 2485 : 2 : return;
2486 : : }
2487 : :
2488 : : /*
2489 : : * Do quick-but-not-definitive test for a relation lock first. This will
2490 : : * never cause a return when the relation is *not* locked, but will
2491 : : * occasionally let the check continue when there really *is* a relation
2492 : : * level lock.
2493 : : */
5750 heikki.linnakangas@i 2494 : 6315 : SET_PREDICATELOCKTARGETTAG_RELATION(tag,
2495 : : relation->rd_locator.dbOid,
2496 : : relation->rd_id);
2497 [ - + ]: 6315 : if (PredicateLockExists(&tag))
5750 heikki.linnakangas@i 2498 :UBC 0 : return;
2499 : :
5750 heikki.linnakangas@i 2500 :CBC 6315 : SET_PREDICATELOCKTARGETTAG_TUPLE(tag,
2501 : : relation->rd_locator.dbOid,
2502 : : relation->rd_id,
2503 : : ItemPointerGetBlockNumber(tid),
2504 : : ItemPointerGetOffsetNumber(tid));
2505 : 6315 : PredicateLockAcquire(&tag);
2506 : : }
2507 : :
2508 : :
2509 : : /*
2510 : : * DeleteLockTarget
2511 : : *
2512 : : * Remove a predicate lock target along with any locks held for it.
2513 : : *
2514 : : * Caller must hold SerializablePredicateListLock and the
2515 : : * appropriate hash partition lock for the target.
2516 : : */
2517 : : static void
5750 heikki.linnakangas@i 2518 :UBC 0 : DeleteLockTarget(PREDICATELOCKTARGET *target, uint32 targettaghash)
2519 : : {
2520 : : dlist_mutable_iter iter;
2521 : :
2365 tgl@sss.pgh.pa.us 2522 [ # # ]: 0 : Assert(LWLockHeldByMeInMode(SerializablePredicateListLock,
2523 : : LW_EXCLUSIVE));
5750 heikki.linnakangas@i 2524 [ # # ]: 0 : Assert(LWLockHeldByMe(PredicateLockHashPartitionLock(targettaghash)));
2525 : :
2526 : 0 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
2527 : :
1386 andres@anarazel.de 2528 [ # # # # ]: 0 : dlist_foreach_modify(iter, &target->predicateLocks)
2529 : : {
2530 : 0 : PREDICATELOCK *predlock =
1266 tgl@sss.pgh.pa.us 2531 : 0 : dlist_container(PREDICATELOCK, targetLink, iter.cur);
2532 : : bool found;
2533 : :
1386 andres@anarazel.de 2534 : 0 : dlist_delete(&(predlock->xactLink));
2535 : 0 : dlist_delete(&(predlock->targetLink));
2536 : :
5750 heikki.linnakangas@i 2537 : 0 : hash_search_with_hash_value
2538 : : (PredicateLockHash,
2539 : 0 : &predlock->tag,
2540 : 0 : PredicateLockHashCodeFromTargetHashCode(&predlock->tag,
2541 : : targettaghash),
2542 : : HASH_REMOVE, &found);
2543 [ # # ]: 0 : Assert(found);
2544 : : }
2545 : 0 : LWLockRelease(SerializableXactHashLock);
2546 : :
2547 : : /* Remove the target itself, if possible. */
2548 : 0 : RemoveTargetIfNoLongerUsed(target, targettaghash);
2549 : 0 : }
2550 : :
2551 : :
2552 : : /*
2553 : : * TransferPredicateLocksToNewTarget
2554 : : *
2555 : : * Move or copy all the predicate locks for a lock target, for use by
2556 : : * index page splits/combines and other things that create or replace
2557 : : * lock targets. If 'removeOld' is true, the old locks and the target
2558 : : * will be removed.
2559 : : *
2560 : : * Returns true on success, or false if we ran out of shared memory to
2561 : : * allocate the new target or locks. Guaranteed to always succeed if
2562 : : * removeOld is set (by using the scratch entry in PredicateLockTargetHash
2563 : : * for scratch space).
2564 : : *
2565 : : * Warning: the "removeOld" option should be used only with care,
2566 : : * because this function does not (indeed, can not) update other
2567 : : * backends' LocalPredicateLockHash. If we are only adding new
2568 : : * entries, this is not a problem: the local lock table is used only
2569 : : * as a hint, so missing entries for locks that are held are
2570 : : * OK. Having entries for locks that are no longer held, as can happen
2571 : : * when using "removeOld", is not in general OK. We can only use it
2572 : : * safely when replacing a lock with a coarser-granularity lock that
2573 : : * covers it, or if we are absolutely certain that no one will need to
2574 : : * refer to that lock in the future.
2575 : : *
2576 : : * Caller must hold SerializablePredicateListLock exclusively.
2577 : : */
2578 : : static bool
5615 heikki.linnakangas@i 2579 :LBC (1) : TransferPredicateLocksToNewTarget(PREDICATELOCKTARGETTAG oldtargettag,
2580 : : PREDICATELOCKTARGETTAG newtargettag,
2581 : : bool removeOld)
2582 : : {
2583 : : uint32 oldtargettaghash;
2584 : : LWLock *oldpartitionLock;
2585 : : PREDICATELOCKTARGET *oldtarget;
2586 : : uint32 newtargettaghash;
2587 : : LWLock *newpartitionLock;
2588 : : bool found;
5750 2589 : (1) : bool outOfShmem = false;
2590 : :
2365 tgl@sss.pgh.pa.us 2591 [ # # ]: (1) : Assert(LWLockHeldByMeInMode(SerializablePredicateListLock,
2592 : : LW_EXCLUSIVE));
2593 : :
5750 heikki.linnakangas@i 2594 : (1) : oldtargettaghash = PredicateLockTargetTagHashCode(&oldtargettag);
2595 : (1) : newtargettaghash = PredicateLockTargetTagHashCode(&newtargettag);
2596 : (1) : oldpartitionLock = PredicateLockHashPartitionLock(oldtargettaghash);
2597 : (1) : newpartitionLock = PredicateLockHashPartitionLock(newtargettaghash);
2598 : :
2599 [ # # ]: (1) : if (removeOld)
2600 : : {
2601 : : /*
2602 : : * Remove the dummy entry to give us scratch space, so we know we'll
2603 : : * be able to create the new lock target.
2604 : : */
5629 heikki.linnakangas@i 2605 :UBC 0 : RemoveScratchTarget(false);
2606 : : }
2607 : :
2608 : : /*
2609 : : * We must get the partition locks in ascending sequence to avoid
2610 : : * deadlocks. If old and new partitions are the same, we must request the
2611 : : * lock only once.
2612 : : */
5750 heikki.linnakangas@i 2613 [ # # ]:LBC (1) : if (oldpartitionLock < newpartitionLock)
2614 : : {
5750 heikki.linnakangas@i 2615 :UBC 0 : LWLockAcquire(oldpartitionLock,
2616 : 0 : (removeOld ? LW_EXCLUSIVE : LW_SHARED));
2617 : 0 : LWLockAcquire(newpartitionLock, LW_EXCLUSIVE);
2618 : : }
5750 heikki.linnakangas@i 2619 [ # # ]:LBC (1) : else if (oldpartitionLock > newpartitionLock)
2620 : : {
2621 : (1) : LWLockAcquire(newpartitionLock, LW_EXCLUSIVE);
2622 : (1) : LWLockAcquire(oldpartitionLock,
2623 : (1) : (removeOld ? LW_EXCLUSIVE : LW_SHARED));
2624 : : }
2625 : : else
5750 heikki.linnakangas@i 2626 :UBC 0 : LWLockAcquire(newpartitionLock, LW_EXCLUSIVE);
2627 : :
2628 : : /*
2629 : : * Look for the old target. If not found, that's OK; no predicate locks
2630 : : * are affected, so we can just clean up and return. If it does exist,
2631 : : * walk its list of predicate locks and move or copy them to the new
2632 : : * target.
2633 : : */
5750 heikki.linnakangas@i 2634 :LBC (1) : oldtarget = hash_search_with_hash_value(PredicateLockTargetHash,
2635 : : &oldtargettag,
2636 : : oldtargettaghash,
2637 : : HASH_FIND, NULL);
2638 : :
2639 [ # # ]: (1) : if (oldtarget)
2640 : : {
2641 : : PREDICATELOCKTARGET *newtarget;
2642 : : PREDICATELOCKTAG newpredlocktag;
2643 : : dlist_mutable_iter iter;
2644 : :
5750 heikki.linnakangas@i 2645 :UBC 0 : newtarget = hash_search_with_hash_value(PredicateLockTargetHash,
2646 : : &newtargettag,
2647 : : newtargettaghash,
2648 : : HASH_ENTER_NULL, &found);
2649 : :
2650 [ # # ]: 0 : if (!newtarget)
2651 : : {
2652 : : /* Failed to allocate due to insufficient shmem */
2653 : 0 : outOfShmem = true;
2654 : 0 : goto exit;
2655 : : }
2656 : :
2657 : : /* If we created a new entry, initialize it */
2658 [ # # ]: 0 : if (!found)
1386 andres@anarazel.de 2659 : 0 : dlist_init(&newtarget->predicateLocks);
2660 : :
5739 magnus@hagander.net 2661 : 0 : newpredlocktag.myTarget = newtarget;
2662 : :
2663 : : /*
2664 : : * Loop through all the locks on the old target, replacing them with
2665 : : * locks on the new target.
2666 : : */
5750 heikki.linnakangas@i 2667 : 0 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
2668 : :
1386 andres@anarazel.de 2669 [ # # # # ]: 0 : dlist_foreach_modify(iter, &oldtarget->predicateLocks)
2670 : : {
2671 : 0 : PREDICATELOCK *oldpredlock =
1266 tgl@sss.pgh.pa.us 2672 : 0 : dlist_container(PREDICATELOCK, targetLink, iter.cur);
2673 : : PREDICATELOCK *newpredlock;
5687 heikki.linnakangas@i 2674 : 0 : SerCommitSeqNo oldCommitSeqNo = oldpredlock->commitSeqNo;
2675 : :
5750 2676 : 0 : newpredlocktag.myXact = oldpredlock->tag.myXact;
2677 : :
2678 [ # # ]: 0 : if (removeOld)
2679 : : {
1386 andres@anarazel.de 2680 : 0 : dlist_delete(&(oldpredlock->xactLink));
2681 : 0 : dlist_delete(&(oldpredlock->targetLink));
2682 : :
5750 heikki.linnakangas@i 2683 : 0 : hash_search_with_hash_value
2684 : : (PredicateLockHash,
2685 : 0 : &oldpredlock->tag,
3424 tgl@sss.pgh.pa.us 2686 : 0 : PredicateLockHashCodeFromTargetHashCode(&oldpredlock->tag,
2687 : : oldtargettaghash),
2688 : : HASH_REMOVE, &found);
5750 heikki.linnakangas@i 2689 [ # # ]: 0 : Assert(found);
2690 : : }
2691 : :
2692 : : newpredlock = (PREDICATELOCK *)
5615 tgl@sss.pgh.pa.us 2693 : 0 : hash_search_with_hash_value(PredicateLockHash,
2694 : : &newpredlocktag,
3424 2695 : 0 : PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
2696 : : newtargettaghash),
2697 : : HASH_ENTER_NULL,
2698 : : &found);
5750 heikki.linnakangas@i 2699 [ # # ]: 0 : if (!newpredlock)
2700 : : {
2701 : : /* Out of shared memory. Undo what we've done so far. */
2702 : 0 : LWLockRelease(SerializableXactHashLock);
2703 : 0 : DeleteLockTarget(newtarget, newtargettaghash);
2704 : 0 : outOfShmem = true;
2705 : 0 : goto exit;
2706 : : }
5739 magnus@hagander.net 2707 [ # # ]: 0 : if (!found)
2708 : : {
1386 andres@anarazel.de 2709 : 0 : dlist_push_tail(&(newtarget->predicateLocks),
2710 : : &(newpredlock->targetLink));
2711 : 0 : dlist_push_tail(&(newpredlocktag.myXact->predicateLocks),
2712 : : &(newpredlock->xactLink));
5687 heikki.linnakangas@i 2713 : 0 : newpredlock->commitSeqNo = oldCommitSeqNo;
2714 : : }
2715 : : else
2716 : : {
2717 [ # # ]: 0 : if (newpredlock->commitSeqNo < oldCommitSeqNo)
2718 : 0 : newpredlock->commitSeqNo = oldCommitSeqNo;
2719 : : }
2720 : :
2721 [ # # ]: 0 : Assert(newpredlock->commitSeqNo != 0);
2722 [ # # # # ]: 0 : Assert((newpredlock->commitSeqNo == InvalidSerCommitSeqNo)
2723 : : || (newpredlock->tag.myXact == OldCommittedSxact));
2724 : : }
5750 2725 : 0 : LWLockRelease(SerializableXactHashLock);
2726 : :
2727 [ # # ]: 0 : if (removeOld)
2728 : : {
1386 andres@anarazel.de 2729 [ # # ]: 0 : Assert(dlist_is_empty(&oldtarget->predicateLocks));
5750 heikki.linnakangas@i 2730 : 0 : RemoveTargetIfNoLongerUsed(oldtarget, oldtargettaghash);
2731 : : }
2732 : : }
2733 : :
2734 : :
5750 heikki.linnakangas@i 2735 :LBC (1) : exit:
2736 : : /* Release partition locks in reverse order of acquisition. */
2737 [ # # ]: (1) : if (oldpartitionLock < newpartitionLock)
2738 : : {
5750 heikki.linnakangas@i 2739 :UBC 0 : LWLockRelease(newpartitionLock);
2740 : 0 : LWLockRelease(oldpartitionLock);
2741 : : }
5750 heikki.linnakangas@i 2742 [ # # ]:LBC (1) : else if (oldpartitionLock > newpartitionLock)
2743 : : {
2744 : (1) : LWLockRelease(oldpartitionLock);
2745 : (1) : LWLockRelease(newpartitionLock);
2746 : : }
2747 : : else
5750 heikki.linnakangas@i 2748 :UBC 0 : LWLockRelease(newpartitionLock);
2749 : :
5750 heikki.linnakangas@i 2750 [ # # ]:LBC (1) : if (removeOld)
2751 : : {
2752 : : /* We shouldn't run out of memory if we're moving locks */
5750 heikki.linnakangas@i 2753 [ # # ]:UBC 0 : Assert(!outOfShmem);
2754 : :
2755 : : /* Put the scratch entry back */
5629 2756 : 0 : RestoreScratchTarget(false);
2757 : : }
2758 : :
5750 heikki.linnakangas@i 2759 :LBC (1) : return !outOfShmem;
2760 : : }
2761 : :
2762 : : /*
2763 : : * Drop all predicate locks of any granularity from the specified relation,
2764 : : * which can be a heap relation or an index relation. If 'transfer' is true,
2765 : : * acquire a relation lock on the heap for any transactions with any lock(s)
2766 : : * on the specified relation.
2767 : : *
2768 : : * This requires grabbing a lot of LW locks and scanning the entire lock
2769 : : * target table for matches. That makes this more expensive than most
2770 : : * predicate lock management functions, but it will only be called for DDL
2771 : : * type commands that are expensive anyway, and there are fast returns when
2772 : : * no serializable transactions are active or the relation is temporary.
2773 : : *
2774 : : * We don't use the TransferPredicateLocksToNewTarget function because it
2775 : : * acquires its own locks on the partitions of the two targets involved,
2776 : : * and we'll already be holding all partition locks.
2777 : : *
2778 : : * We can't throw an error from here, because the call could be from a
2779 : : * transaction which is not serializable.
2780 : : *
2781 : : * NOTE: This is currently only called with transfer set to true, but that may
2782 : : * change. If we decide to clean up the locks from a table on commit of a
2783 : : * transaction which executed DROP TABLE, the false condition will be useful.
2784 : : */
2785 : : static void
5615 heikki.linnakangas@i 2786 :CBC 22327 : DropAllPredicateLocksFromTable(Relation relation, bool transfer)
2787 : : {
2788 : : HASH_SEQ_STATUS seqstat;
2789 : : PREDICATELOCKTARGET *oldtarget;
2790 : : PREDICATELOCKTARGET *heaptarget;
2791 : : Oid dbId;
2792 : : Oid relId;
2793 : : Oid heapId;
2794 : : int i;
2795 : : bool isIndex;
2796 : : bool found;
2797 : : uint32 heaptargettaghash;
2798 : :
2799 : : /*
2800 : : * Bail out quickly if there are no serializable transactions running.
2801 : : * It's safe to check this without taking locks because the caller is
2802 : : * holding an ACCESS EXCLUSIVE lock on the relation. No new locks which
2803 : : * would matter here can be acquired while that is held.
2804 : : */
5629 2805 [ + + ]: 22327 : if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
2806 : 22299 : return;
2807 : :
5622 2808 [ + + ]: 46 : if (!PredicateLockingNeededForRelation(relation))
5629 2809 : 18 : return;
2810 : :
1583 rhaas@postgresql.org 2811 : 28 : dbId = relation->rd_locator.dbOid;
5629 heikki.linnakangas@i 2812 : 28 : relId = relation->rd_id;
2813 [ + + ]: 28 : if (relation->rd_index == NULL)
2814 : : {
2815 : 2 : isIndex = false;
2816 : 2 : heapId = relId;
2817 : : }
2818 : : else
2819 : : {
2820 : 26 : isIndex = true;
2821 : 26 : heapId = relation->rd_index->indrelid;
2822 : : }
2823 [ - + ]: 28 : Assert(heapId != InvalidOid);
3424 tgl@sss.pgh.pa.us 2824 [ - + - - ]: 28 : Assert(transfer || !isIndex); /* index OID only makes sense with
2825 : : * transfer */
2826 : :
2827 : : /* Retrieve first time needed, then keep. */
5629 heikki.linnakangas@i 2828 : 28 : heaptargettaghash = 0;
2829 : 28 : heaptarget = NULL;
2830 : :
2831 : : /* Acquire locks on all lock partitions */
2365 tgl@sss.pgh.pa.us 2832 : 28 : LWLockAcquire(SerializablePredicateListLock, LW_EXCLUSIVE);
5629 heikki.linnakangas@i 2833 [ + + ]: 476 : for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
4665 rhaas@postgresql.org 2834 : 448 : LWLockAcquire(PredicateLockHashPartitionLockByIndex(i), LW_EXCLUSIVE);
5629 heikki.linnakangas@i 2835 : 28 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
2836 : :
2837 : : /*
2838 : : * Remove the dummy entry to give us scratch space, so we know we'll be
2839 : : * able to create the new lock target.
2840 : : */
2841 [ + - ]: 28 : if (transfer)
2842 : 28 : RemoveScratchTarget(true);
2843 : :
2844 : : /* Scan through target map */
2845 : 28 : hash_seq_init(&seqstat, PredicateLockTargetHash);
2846 : :
2847 [ + + ]: 49 : while ((oldtarget = (PREDICATELOCKTARGET *) hash_seq_search(&seqstat)))
2848 : : {
2849 : : dlist_mutable_iter iter;
2850 : :
2851 : : /*
2852 : : * Check whether this is a target which needs attention.
2853 : : */
2854 [ + - ]: 21 : if (GET_PREDICATELOCKTARGETTAG_RELATION(oldtarget->tag) != relId)
2855 : 21 : continue; /* wrong relation id */
5629 heikki.linnakangas@i 2856 [ # # ]:UBC 0 : if (GET_PREDICATELOCKTARGETTAG_DB(oldtarget->tag) != dbId)
2857 : 0 : continue; /* wrong database id */
2858 [ # # # # ]: 0 : if (transfer && !isIndex
2859 [ # # # # ]: 0 : && GET_PREDICATELOCKTARGETTAG_TYPE(oldtarget->tag) == PREDLOCKTAG_RELATION)
2860 : 0 : continue; /* already the right lock */
2861 : :
2862 : : /*
2863 : : * If we made it here, we have work to do. We make sure the heap
2864 : : * relation lock exists, then we walk the list of predicate locks for
2865 : : * the old target we found, moving all locks to the heap relation lock
2866 : : * -- unless they already hold that.
2867 : : */
2868 : :
2869 : : /*
2870 : : * First make sure we have the heap relation target. We only need to
2871 : : * do this once.
2872 : : */
2873 [ # # # # ]: 0 : if (transfer && heaptarget == NULL)
2874 : : {
2875 : : PREDICATELOCKTARGETTAG heaptargettag;
2876 : :
2877 : 0 : SET_PREDICATELOCKTARGETTAG_RELATION(heaptargettag, dbId, heapId);
2878 : 0 : heaptargettaghash = PredicateLockTargetTagHashCode(&heaptargettag);
2879 : 0 : heaptarget = hash_search_with_hash_value(PredicateLockTargetHash,
2880 : : &heaptargettag,
2881 : : heaptargettaghash,
2882 : : HASH_ENTER, &found);
2883 [ # # ]: 0 : if (!found)
1386 andres@anarazel.de 2884 : 0 : dlist_init(&heaptarget->predicateLocks);
2885 : : }
2886 : :
2887 : : /*
2888 : : * Loop through all the locks on the old target, replacing them with
2889 : : * locks on the new target.
2890 : : */
2891 [ # # # # ]: 0 : dlist_foreach_modify(iter, &oldtarget->predicateLocks)
2892 : : {
2893 : 0 : PREDICATELOCK *oldpredlock =
1266 tgl@sss.pgh.pa.us 2894 : 0 : dlist_container(PREDICATELOCK, targetLink, iter.cur);
2895 : : PREDICATELOCK *newpredlock;
2896 : : SerCommitSeqNo oldCommitSeqNo;
2897 : : SERIALIZABLEXACT *oldXact;
2898 : :
2899 : : /*
2900 : : * Remove the old lock first. This avoids the chance of running
2901 : : * out of lock structure entries for the hash table.
2902 : : */
5629 heikki.linnakangas@i 2903 : 0 : oldCommitSeqNo = oldpredlock->commitSeqNo;
2904 : 0 : oldXact = oldpredlock->tag.myXact;
2905 : :
1386 andres@anarazel.de 2906 : 0 : dlist_delete(&(oldpredlock->xactLink));
2907 : :
2908 : : /*
2909 : : * No need for retail delete from oldtarget list, we're removing
2910 : : * the whole target anyway.
2911 : : */
5629 heikki.linnakangas@i 2912 : 0 : hash_search(PredicateLockHash,
2913 : 0 : &oldpredlock->tag,
2914 : : HASH_REMOVE, &found);
2915 [ # # ]: 0 : Assert(found);
2916 : :
2917 [ # # ]: 0 : if (transfer)
2918 : : {
2919 : : PREDICATELOCKTAG newpredlocktag;
2920 : :
2921 : 0 : newpredlocktag.myTarget = heaptarget;
2922 : 0 : newpredlocktag.myXact = oldXact;
2923 : : newpredlock = (PREDICATELOCK *)
5615 tgl@sss.pgh.pa.us 2924 : 0 : hash_search_with_hash_value(PredicateLockHash,
2925 : : &newpredlocktag,
3424 2926 : 0 : PredicateLockHashCodeFromTargetHashCode(&newpredlocktag,
2927 : : heaptargettaghash),
2928 : : HASH_ENTER,
2929 : : &found);
5629 heikki.linnakangas@i 2930 [ # # ]: 0 : if (!found)
2931 : : {
1386 andres@anarazel.de 2932 : 0 : dlist_push_tail(&(heaptarget->predicateLocks),
2933 : : &(newpredlock->targetLink));
2934 : 0 : dlist_push_tail(&(newpredlocktag.myXact->predicateLocks),
2935 : : &(newpredlock->xactLink));
5629 heikki.linnakangas@i 2936 : 0 : newpredlock->commitSeqNo = oldCommitSeqNo;
2937 : : }
2938 : : else
2939 : : {
2940 [ # # ]: 0 : if (newpredlock->commitSeqNo < oldCommitSeqNo)
2941 : 0 : newpredlock->commitSeqNo = oldCommitSeqNo;
2942 : : }
2943 : :
2944 [ # # ]: 0 : Assert(newpredlock->commitSeqNo != 0);
2945 [ # # # # ]: 0 : Assert((newpredlock->commitSeqNo == InvalidSerCommitSeqNo)
2946 : : || (newpredlock->tag.myXact == OldCommittedSxact));
2947 : : }
2948 : : }
2949 : :
2950 : 0 : hash_search(PredicateLockTargetHash, &oldtarget->tag, HASH_REMOVE,
2951 : : &found);
2952 [ # # ]: 0 : Assert(found);
2953 : : }
2954 : :
2955 : : /* Put the scratch entry back */
5629 heikki.linnakangas@i 2956 [ + - ]:CBC 28 : if (transfer)
2957 : 28 : RestoreScratchTarget(true);
2958 : :
2959 : : /* Release locks in reverse order */
2960 : 28 : LWLockRelease(SerializableXactHashLock);
2961 [ + + ]: 476 : for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
4665 rhaas@postgresql.org 2962 : 448 : LWLockRelease(PredicateLockHashPartitionLockByIndex(i));
2365 tgl@sss.pgh.pa.us 2963 : 28 : LWLockRelease(SerializablePredicateListLock);
2964 : : }
2965 : :
2966 : : /*
2967 : : * TransferPredicateLocksToHeapRelation
2968 : : * For all transactions, transfer all predicate locks for the given
2969 : : * relation to a single relation lock on the heap.
2970 : : */
2971 : : void
5615 heikki.linnakangas@i 2972 : 22327 : TransferPredicateLocksToHeapRelation(Relation relation)
2973 : : {
5629 2974 : 22327 : DropAllPredicateLocksFromTable(relation, true);
2975 : 22327 : }
2976 : :
2977 : :
2978 : : /*
2979 : : * PredicateLockPageSplit
2980 : : *
2981 : : * Copies any predicate locks for the old page to the new page.
2982 : : * Skip if this is a temporary table or toast table.
2983 : : *
2984 : : * NOTE: A page split (or overflow) affects all serializable transactions,
2985 : : * even if it occurs in the context of another transaction isolation level.
2986 : : *
2987 : : * NOTE: This currently leaves the local copy of the locks without
2988 : : * information on the new lock which is in shared memory. This could cause
2989 : : * problems if enough page splits occur on locked pages without the processes
2990 : : * which hold the locks getting in and noticing.
2991 : : */
2992 : : void
5615 2993 : 37953 : PredicateLockPageSplit(Relation relation, BlockNumber oldblkno,
2994 : : BlockNumber newblkno)
2995 : : {
2996 : : PREDICATELOCKTARGETTAG oldtargettag;
2997 : : PREDICATELOCKTARGETTAG newtargettag;
2998 : : bool success;
2999 : :
3000 : : /*
3001 : : * Bail out quickly if there are no serializable transactions running.
3002 : : *
3003 : : * It's safe to do this check without taking any additional locks. Even if
3004 : : * a serializable transaction starts concurrently, we know it can't take
3005 : : * any SIREAD locks on the page being split because the caller is holding
3006 : : * the associated buffer page lock. Memory reordering isn't an issue; the
3007 : : * memory barrier in the LWLock acquisition guarantees that this read
3008 : : * occurs while the buffer page lock is held.
3009 : : */
5673 rhaas@postgresql.org 3010 [ + + ]: 37953 : if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
3011 : 37953 : return;
3012 : :
5622 heikki.linnakangas@i 3013 [ + - ]: 84 : if (!PredicateLockingNeededForRelation(relation))
5750 3014 : 84 : return;
3015 : :
5750 heikki.linnakangas@i 3016 [ # # ]:LBC (1) : Assert(oldblkno != newblkno);
3017 [ # # ]: (1) : Assert(BlockNumberIsValid(oldblkno));
3018 [ # # ]: (1) : Assert(BlockNumberIsValid(newblkno));
3019 : :
3020 : (1) : SET_PREDICATELOCKTARGETTAG_PAGE(oldtargettag,
3021 : : relation->rd_locator.dbOid,
3022 : : relation->rd_id,
3023 : : oldblkno);
3024 : (1) : SET_PREDICATELOCKTARGETTAG_PAGE(newtargettag,
3025 : : relation->rd_locator.dbOid,
3026 : : relation->rd_id,
3027 : : newblkno);
3028 : :
2365 tgl@sss.pgh.pa.us 3029 : (1) : LWLockAcquire(SerializablePredicateListLock, LW_EXCLUSIVE);
3030 : :
3031 : : /*
3032 : : * Try copying the locks over to the new page's tag, creating it if
3033 : : * necessary.
3034 : : */
5750 heikki.linnakangas@i 3035 : (1) : success = TransferPredicateLocksToNewTarget(oldtargettag,
3036 : : newtargettag,
3037 : : false);
3038 : :
3039 [ # # ]: (1) : if (!success)
3040 : : {
3041 : : /*
3042 : : * No more predicate lock entries are available. Failure isn't an
3043 : : * option here, so promote the page lock to a relation lock.
3044 : : */
3045 : :
3046 : : /* Get the parent relation lock's lock tag */
5750 heikki.linnakangas@i 3047 :UBC 0 : success = GetParentPredicateLockTag(&oldtargettag,
3048 : : &newtargettag);
3049 [ # # ]: 0 : Assert(success);
3050 : :
3051 : : /*
3052 : : * Move the locks to the parent. This shouldn't fail.
3053 : : *
3054 : : * Note that here we are removing locks held by other backends,
3055 : : * leading to a possible inconsistency in their local lock hash table.
3056 : : * This is OK because we're replacing it with a lock that covers the
3057 : : * old one.
3058 : : */
3059 : 0 : success = TransferPredicateLocksToNewTarget(oldtargettag,
3060 : : newtargettag,
3061 : : true);
3062 [ # # ]: 0 : Assert(success);
3063 : : }
3064 : :
2365 tgl@sss.pgh.pa.us 3065 :LBC (1) : LWLockRelease(SerializablePredicateListLock);
3066 : : }
3067 : :
3068 : : /*
3069 : : * PredicateLockPageCombine
3070 : : *
3071 : : * Combines predicate locks for two existing pages.
3072 : : * Skip if this is a temporary table or toast table.
3073 : : *
3074 : : * NOTE: A page combine affects all serializable transactions, even if it
3075 : : * occurs in the context of another transaction isolation level.
3076 : : */
3077 : : void
5615 heikki.linnakangas@i 3078 :CBC 3991 : PredicateLockPageCombine(Relation relation, BlockNumber oldblkno,
3079 : : BlockNumber newblkno)
3080 : : {
3081 : : /*
3082 : : * Page combines differ from page splits in that we ought to be able to
3083 : : * remove the locks on the old page after transferring them to the new
3084 : : * page, instead of duplicating them. However, because we can't edit other
3085 : : * backends' local lock tables, removing the old lock would leave them
3086 : : * with an entry in their LocalPredicateLockHash for a lock they're not
3087 : : * holding, which isn't acceptable. So we wind up having to do the same
3088 : : * work as a page split, acquiring a lock on the new page and keeping the
3089 : : * old page locked too. That can lead to some false positives, but should
3090 : : * be rare in practice.
3091 : : */
5728 3092 : 3991 : PredicateLockPageSplit(relation, oldblkno, newblkno);
5750 3093 : 3991 : }
3094 : :
3095 : : /*
3096 : : * Walk the list of in-progress serializable transactions and find the new
3097 : : * xmin.
3098 : : */
3099 : : static void
3100 : 883 : SetNewSxactGlobalXmin(void)
3101 : : {
3102 : : dlist_iter iter;
3103 : :
3104 [ - + ]: 883 : Assert(LWLockHeldByMe(SerializableXactHashLock));
3105 : :
3106 : 883 : PredXact->SxactGlobalXmin = InvalidTransactionId;
3107 : 883 : PredXact->SxactGlobalXminCount = 0;
3108 : :
1386 andres@anarazel.de 3109 [ + - + + ]: 3367 : dlist_foreach(iter, &PredXact->activeList)
3110 : : {
3111 : 2484 : SERIALIZABLEXACT *sxact =
1266 tgl@sss.pgh.pa.us 3112 : 2484 : dlist_container(SERIALIZABLEXACT, xactLink, iter.cur);
3113 : :
5616 heikki.linnakangas@i 3114 [ + + ]: 2484 : if (!SxactIsRolledBack(sxact)
5750 3115 [ + + ]: 2164 : && !SxactIsCommitted(sxact)
3116 [ + - ]: 19 : && sxact != OldCommittedSxact)
3117 : : {
3118 [ - + ]: 19 : Assert(sxact->xmin != InvalidTransactionId);
3119 [ - + ]: 19 : if (!TransactionIdIsValid(PredXact->SxactGlobalXmin)
5750 heikki.linnakangas@i 3120 [ # # ]:UBC 0 : || TransactionIdPrecedes(sxact->xmin,
3121 : 0 : PredXact->SxactGlobalXmin))
3122 : : {
5750 heikki.linnakangas@i 3123 :CBC 19 : PredXact->SxactGlobalXmin = sxact->xmin;
3124 : 19 : PredXact->SxactGlobalXminCount = 1;
3125 : : }
5750 heikki.linnakangas@i 3126 [ # # ]:UBC 0 : else if (TransactionIdEquals(sxact->xmin,
3127 : : PredXact->SxactGlobalXmin))
3128 : 0 : PredXact->SxactGlobalXminCount++;
3129 : : }
3130 : : }
3131 : :
2365 tgl@sss.pgh.pa.us 3132 :CBC 883 : SerialSetActiveSerXmin(PredXact->SxactGlobalXmin);
5750 heikki.linnakangas@i 3133 : 883 : }
3134 : :
3135 : : /*
3136 : : * ReleasePredicateLocks
3137 : : *
3138 : : * Releases predicate locks based on completion of the current transaction,
3139 : : * whether committed or rolled back. It can also be called for a read only
3140 : : * transaction when it becomes impossible for the transaction to become
3141 : : * part of a dangerous structure.
3142 : : *
3143 : : * We do nothing unless this is a serializable transaction.
3144 : : *
3145 : : * This method must ensure that shared memory hash tables are cleaned
3146 : : * up in some relatively timely fashion.
3147 : : *
3148 : : * If this transaction is committing and is holding any predicate locks,
3149 : : * it must be added to a list of completed serializable transactions still
3150 : : * holding locks.
3151 : : *
3152 : : * If isReadOnlySafe is true, then predicate locks are being released before
3153 : : * the end of the transaction because MySerializableXact has been determined
3154 : : * to be RO_SAFE. In non-parallel mode we can release it completely, but it
3155 : : * in parallel mode we partially release the SERIALIZABLEXACT and keep it
3156 : : * around until the end of the transaction, allowing each backend to clear its
3157 : : * MySerializableXact variable and benefit from the optimization in its own
3158 : : * time.
3159 : : */
3160 : : void
2792 tmunro@postgresql.or 3161 : 430175 : ReleasePredicateLocks(bool isCommit, bool isReadOnlySafe)
3162 : : {
1340 3163 : 430175 : bool partiallyReleasing = false;
3164 : : bool needToClear;
3165 : : SERIALIZABLEXACT *roXact;
3166 : : dlist_mutable_iter iter;
3167 : :
3168 : : /*
3169 : : * We can't trust XactReadOnly here, because a transaction which started
3170 : : * as READ WRITE can show as READ ONLY later, e.g., within
3171 : : * subtransactions. We want to flag a transaction as READ ONLY if it
3172 : : * commits without writing so that de facto READ ONLY transactions get the
3173 : : * benefit of some RO optimizations, so we will use this local variable to
3174 : : * get some cleanup logic right which is based on whether the transaction
3175 : : * was declared READ ONLY at the top level.
3176 : : */
3177 : : bool topLevelIsDeclaredReadOnly;
3178 : :
3179 : : /* We can't be both committing and releasing early due to RO_SAFE. */
2792 3180 [ + + - + ]: 430175 : Assert(!(isCommit && isReadOnlySafe));
3181 : :
3182 : : /* Are we at the end of a transaction, that is, a commit or abort? */
3183 [ + + ]: 430175 : if (!isReadOnlySafe)
3184 : : {
3185 : : /*
3186 : : * Parallel workers mustn't release predicate locks at the end of
3187 : : * their transaction. The leader will do that at the end of its
3188 : : * transaction.
3189 : : */
3190 [ + + ]: 430140 : if (IsParallelWorker())
3191 : : {
3192 : 6129 : ReleasePredicateLocksLocal();
3193 : 428586 : return;
3194 : : }
3195 : :
3196 : : /*
3197 : : * By the time the leader in a parallel query reaches end of
3198 : : * transaction, it has waited for all workers to exit.
3199 : : */
3200 [ - + ]: 424011 : Assert(!ParallelContextActive());
3201 : :
3202 : : /*
3203 : : * If the leader in a parallel query earlier stashed a partially
3204 : : * released SERIALIZABLEXACT for final clean-up at end of transaction
3205 : : * (because workers might still have been accessing it), then it's
3206 : : * time to restore it.
3207 : : */
3208 [ + + ]: 424011 : if (SavedSerializableXact != InvalidSerializableXact)
3209 : : {
3210 [ - + ]: 1 : Assert(MySerializableXact == InvalidSerializableXact);
3211 : 1 : MySerializableXact = SavedSerializableXact;
3212 : 1 : SavedSerializableXact = InvalidSerializableXact;
3213 [ - + ]: 1 : Assert(SxactIsPartiallyReleased(MySerializableXact));
3214 : : }
3215 : : }
3216 : :
5750 heikki.linnakangas@i 3217 [ + + ]: 424046 : if (MySerializableXact == InvalidSerializableXact)
3218 : : {
3219 [ - + ]: 422454 : Assert(LocalPredicateLockHash == NULL);
3220 : 422454 : return;
3221 : : }
3222 : :
4023 kgrittn@postgresql.o 3223 : 1592 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
3224 : :
3225 : : /*
3226 : : * If the transaction is committing, but it has been partially released
3227 : : * already, then treat this as a roll back. It was marked as rolled back.
3228 : : */
2792 tmunro@postgresql.or 3229 [ + + + + ]: 1592 : if (isCommit && SxactIsPartiallyReleased(MySerializableXact))
3230 : 2 : isCommit = false;
3231 : :
3232 : : /*
3233 : : * If we're called in the middle of a transaction because we discovered
3234 : : * that the SXACT_FLAG_RO_SAFE flag was set, then we'll partially release
3235 : : * it (that is, release the predicate locks and conflicts, but not the
3236 : : * SERIALIZABLEXACT itself) if we're the first backend to have noticed.
3237 : : */
3238 [ + + + + ]: 1592 : if (isReadOnlySafe && IsInParallelMode())
3239 : : {
3240 : : /*
3241 : : * The leader needs to stash a pointer to it, so that it can
3242 : : * completely release it at end-of-transaction.
3243 : : */
3244 [ + + ]: 5 : if (!IsParallelWorker())
3245 : 1 : SavedSerializableXact = MySerializableXact;
3246 : :
3247 : : /*
3248 : : * The first backend to reach this condition will partially release
3249 : : * the SERIALIZABLEXACT. All others will just clear their
3250 : : * backend-local state so that they stop doing SSI checks for the rest
3251 : : * of the transaction.
3252 : : */
3253 [ + + ]: 5 : if (SxactIsPartiallyReleased(MySerializableXact))
3254 : : {
3255 : 3 : LWLockRelease(SerializableXactHashLock);
3256 : 3 : ReleasePredicateLocksLocal();
3257 : 3 : return;
3258 : : }
3259 : : else
3260 : : {
3261 : 2 : MySerializableXact->flags |= SXACT_FLAG_PARTIALLY_RELEASED;
1340 3262 : 2 : partiallyReleasing = true;
3263 : : /* ... and proceed to perform the partial release below. */
3264 : : }
3265 : : }
5750 heikki.linnakangas@i 3266 [ + + - + ]: 1589 : Assert(!isCommit || SxactIsPrepared(MySerializableXact));
5622 3267 [ + + - + ]: 1589 : Assert(!isCommit || !SxactIsDoomed(MySerializableXact));
5750 3268 [ - + ]: 1589 : Assert(!SxactIsCommitted(MySerializableXact));
2792 tmunro@postgresql.or 3269 [ + + - + ]: 1589 : Assert(SxactIsPartiallyReleased(MySerializableXact)
3270 : : || !SxactIsRolledBack(MySerializableXact));
3271 : :
3272 : : /* may not be serializable during COMMIT/ROLLBACK PREPARED */
4023 kgrittn@postgresql.o 3273 [ + + - + ]: 1589 : Assert(MySerializableXact->pid == 0 || IsolationIsSerializable());
3274 : :
3275 : : /* We'd better not already be on the cleanup list. */
5627 heikki.linnakangas@i 3276 [ - + ]: 1589 : Assert(!SxactIsOnFinishedList(MySerializableXact));
3277 : :
5750 3278 : 1589 : topLevelIsDeclaredReadOnly = SxactIsReadOnly(MySerializableXact);
3279 : :
3280 : : /*
3281 : : * We don't hold XidGenLock lock here, assuming that TransactionId is
3282 : : * atomic!
3283 : : *
3284 : : * If this value is changing, we don't care that much whether we get the
3285 : : * old or new value -- it is just used to determine how far
3286 : : * SxactGlobalXmin must advance before this transaction can be fully
3287 : : * cleaned up. The worst that could happen is we wait for one more
3288 : : * transaction to complete before freeing some RAM; correctness of visible
3289 : : * behavior is not affected.
3290 : : */
1063 3291 : 1589 : MySerializableXact->finishedBefore = XidFromFullTransactionId(TransamVariables->nextXid);
3292 : :
3293 : : /*
3294 : : * If it's not a commit it's either a rollback or a read-only transaction
3295 : : * flagged SXACT_FLAG_RO_SAFE, and we can clear our locks immediately.
3296 : : */
5750 3297 [ + + ]: 1589 : if (isCommit)
3298 : : {
3299 : 1244 : MySerializableXact->flags |= SXACT_FLAG_COMMITTED;
3300 : 1244 : MySerializableXact->commitSeqNo = ++(PredXact->LastSxactCommitSeqNo);
3301 : : /* Recognize implicit read-only transaction (commit without write). */
5627 3302 [ + + ]: 1244 : if (!MyXactDidWrite)
5750 3303 : 238 : MySerializableXact->flags |= SXACT_FLAG_READ_ONLY;
3304 : : }
3305 : : else
3306 : : {
3307 : : /*
3308 : : * The DOOMED flag indicates that we intend to roll back this
3309 : : * transaction and so it should not cause serialization failures for
3310 : : * other transactions that conflict with it. Note that this flag might
3311 : : * already be set, if another backend marked this transaction for
3312 : : * abort.
3313 : : *
3314 : : * The ROLLED_BACK flag further indicates that ReleasePredicateLocks
3315 : : * has been called, and so the SerializableXact is eligible for
3316 : : * cleanup. This means it should not be considered when calculating
3317 : : * SxactGlobalXmin.
3318 : : */
2737 tmunro@postgresql.or 3319 : 345 : MySerializableXact->flags |= SXACT_FLAG_DOOMED;
5616 heikki.linnakangas@i 3320 : 345 : MySerializableXact->flags |= SXACT_FLAG_ROLLED_BACK;
3321 : :
3322 : : /*
3323 : : * If the transaction was previously prepared, but is now failing due
3324 : : * to a ROLLBACK PREPARED or (hopefully very rare) error after the
3325 : : * prepare, clear the prepared flag. This simplifies conflict
3326 : : * checking.
3327 : : */
5600 3328 : 345 : MySerializableXact->flags &= ~SXACT_FLAG_PREPARED;
3329 : : }
3330 : :
5750 3331 [ + + ]: 1589 : if (!topLevelIsDeclaredReadOnly)
3332 : : {
3333 [ - + ]: 1479 : Assert(PredXact->WritableSxactCount > 0);
3334 [ + + ]: 1479 : if (--(PredXact->WritableSxactCount) == 0)
3335 : : {
3336 : : /*
3337 : : * Release predicate locks and rw-conflicts in for all committed
3338 : : * transactions. There are no longer any transactions which might
3339 : : * conflict with the locks and no chance for new transactions to
3340 : : * overlap. Similarly, existing conflicts in can't cause pivots,
3341 : : * and any conflicts in which could have completed a dangerous
3342 : : * structure would already have caused a rollback, so any
3343 : : * remaining ones must be benign.
3344 : : */
3345 : 874 : PredXact->CanPartialClearThrough = PredXact->LastSxactCommitSeqNo;
3346 : : }
3347 : : }
3348 : : else
3349 : : {
3350 : : /*
3351 : : * Read-only transactions: clear the list of transactions that might
3352 : : * make us unsafe. Note that we use 'inLink' for the iteration as
3353 : : * opposed to 'outLink' for the r/w xacts.
3354 : : */
1386 andres@anarazel.de 3355 [ + - + + ]: 152 : dlist_foreach_modify(iter, &MySerializableXact->possibleUnsafeConflicts)
3356 : : {
3357 : 42 : RWConflict possibleUnsafeConflict =
1266 tgl@sss.pgh.pa.us 3358 : 42 : dlist_container(RWConflictData, inLink, iter.cur);
3359 : :
5750 heikki.linnakangas@i 3360 [ - + ]: 42 : Assert(!SxactIsReadOnly(possibleUnsafeConflict->sxactOut));
3361 [ - + ]: 42 : Assert(MySerializableXact == possibleUnsafeConflict->sxactIn);
3362 : :
3363 : 42 : ReleaseRWConflict(possibleUnsafeConflict);
3364 : : }
3365 : : }
3366 : :
3367 : : /* Check for conflict out to old committed transactions. */
3368 [ + + ]: 1589 : if (isCommit
3369 [ + + ]: 1244 : && !SxactIsReadOnly(MySerializableXact)
3370 [ - + ]: 1006 : && SxactHasSummaryConflictOut(MySerializableXact))
3371 : : {
3372 : : /*
3373 : : * we don't know which old committed transaction we conflicted with,
3374 : : * so be conservative and use FirstNormalSerCommitSeqNo here
3375 : : */
5750 heikki.linnakangas@i 3376 :UBC 0 : MySerializableXact->SeqNo.earliestOutConflictCommit =
3377 : : FirstNormalSerCommitSeqNo;
3378 : 0 : MySerializableXact->flags |= SXACT_FLAG_CONFLICT_OUT;
3379 : : }
3380 : :
3381 : : /*
3382 : : * Release all outConflicts to committed transactions. If we're rolling
3383 : : * back clear them all. Set SXACT_FLAG_CONFLICT_OUT if any point to
3384 : : * previously committed transactions.
3385 : : */
1386 andres@anarazel.de 3386 [ + - + + ]:CBC 2296 : dlist_foreach_modify(iter, &MySerializableXact->outConflicts)
3387 : : {
3388 : 707 : RWConflict conflict =
3389 : : dlist_container(RWConflictData, outLink, iter.cur);
3390 : :
5750 heikki.linnakangas@i 3391 [ + + ]: 707 : if (isCommit
3392 [ + + ]: 460 : && !SxactIsReadOnly(MySerializableXact)
3393 [ + + ]: 352 : && SxactIsCommitted(conflict->sxactIn))
3394 : : {
3395 [ - + ]: 96 : if ((MySerializableXact->flags & SXACT_FLAG_CONFLICT_OUT) == 0
5600 heikki.linnakangas@i 3396 [ # # ]:UBC 0 : || conflict->sxactIn->prepareSeqNo < MySerializableXact->SeqNo.earliestOutConflictCommit)
5600 heikki.linnakangas@i 3397 :CBC 96 : MySerializableXact->SeqNo.earliestOutConflictCommit = conflict->sxactIn->prepareSeqNo;
5750 3398 : 96 : MySerializableXact->flags |= SXACT_FLAG_CONFLICT_OUT;
3399 : : }
3400 : :
3401 [ + + ]: 707 : if (!isCommit
3402 [ + + ]: 460 : || SxactIsCommitted(conflict->sxactIn)
3403 [ - + ]: 342 : || (conflict->sxactIn->SeqNo.lastCommitBeforeSnapshot >= PredXact->LastSxactCommitSeqNo))
3404 : 365 : ReleaseRWConflict(conflict);
3405 : : }
3406 : :
3407 : : /*
3408 : : * Release all inConflicts from committed and read-only transactions. If
3409 : : * we're rolling back, clear them all.
3410 : : */
1386 andres@anarazel.de 3411 [ + - + + ]: 2381 : dlist_foreach_modify(iter, &MySerializableXact->inConflicts)
3412 : : {
3413 : 792 : RWConflict conflict =
1266 tgl@sss.pgh.pa.us 3414 : 792 : dlist_container(RWConflictData, inLink, iter.cur);
3415 : :
5750 heikki.linnakangas@i 3416 [ + + ]: 792 : if (!isCommit
3417 [ + + ]: 610 : || SxactIsCommitted(conflict->sxactOut)
3418 [ + + ]: 425 : || SxactIsReadOnly(conflict->sxactOut))
3419 : 447 : ReleaseRWConflict(conflict);
3420 : : }
3421 : :
3422 [ + + ]: 1589 : if (!topLevelIsDeclaredReadOnly)
3423 : : {
3424 : : /*
3425 : : * Remove ourselves from the list of possible conflicts for concurrent
3426 : : * READ ONLY transactions, flagging them as unsafe if we have a
3427 : : * conflict out. If any are waiting DEFERRABLE transactions, wake them
3428 : : * up if they are known safe or known unsafe.
3429 : : */
1386 andres@anarazel.de 3430 [ + - + + ]: 1572 : dlist_foreach_modify(iter, &MySerializableXact->possibleUnsafeConflicts)
3431 : : {
3432 : 93 : RWConflict possibleUnsafeConflict =
3433 : : dlist_container(RWConflictData, outLink, iter.cur);
3434 : :
5750 heikki.linnakangas@i 3435 : 93 : roXact = possibleUnsafeConflict->sxactIn;
3436 [ - + ]: 93 : Assert(MySerializableXact == possibleUnsafeConflict->sxactOut);
3437 [ - + ]: 93 : Assert(SxactIsReadOnly(roXact));
3438 : :
3439 : : /* Mark conflicted if necessary. */
3440 [ + + ]: 93 : if (isCommit
5627 3441 [ + + ]: 90 : && MyXactDidWrite
5750 3442 [ + + ]: 85 : && SxactHasConflictOut(MySerializableXact)
3443 : 13 : && (MySerializableXact->SeqNo.earliestOutConflictCommit
3444 [ + + ]: 13 : <= roXact->SeqNo.lastCommitBeforeSnapshot))
3445 : : {
3446 : : /*
3447 : : * This releases possibleUnsafeConflict (as well as all other
3448 : : * possible conflicts for roXact)
3449 : : */
3450 : 3 : FlagSxactUnsafe(roXact);
3451 : : }
3452 : : else
3453 : : {
3454 : 90 : ReleaseRWConflict(possibleUnsafeConflict);
3455 : :
3456 : : /*
3457 : : * If we were the last possible conflict, flag it safe. The
3458 : : * transaction can now safely release its predicate locks (but
3459 : : * that transaction's backend has to do that itself).
3460 : : */
1386 andres@anarazel.de 3461 [ + + ]: 90 : if (dlist_is_empty(&roXact->possibleUnsafeConflicts))
5750 heikki.linnakangas@i 3462 : 67 : roXact->flags |= SXACT_FLAG_RO_SAFE;
3463 : : }
3464 : :
3465 : : /*
3466 : : * Wake up the process for a waiting DEFERRABLE transaction if we
3467 : : * now know it's either safe or conflicted.
3468 : : */
3469 [ + + ]: 93 : if (SxactIsDeferrableWaiting(roXact) &&
3470 [ + + + + ]: 4 : (SxactIsROUnsafe(roXact) || SxactIsROSafe(roXact)))
1785 tmunro@postgresql.or 3471 : 3 : ProcSendSignal(roXact->pgprocno);
3472 : : }
3473 : : }
3474 : :
3475 : : /*
3476 : : * Check whether it's time to clean up old transactions. This can only be
3477 : : * done when the last serializable transaction with the oldest xmin among
3478 : : * serializable transactions completes. We then find the "new oldest"
3479 : : * xmin and purge any transactions which finished before this transaction
3480 : : * was launched.
3481 : : *
3482 : : * For parallel queries in read-only transactions, it might run twice. We
3483 : : * only release the reference on the first call.
3484 : : */
5750 heikki.linnakangas@i 3485 : 1589 : needToClear = false;
1340 tmunro@postgresql.or 3486 [ + + ]: 1589 : if ((partiallyReleasing ||
3487 [ + + ]: 1587 : !SxactIsPartiallyReleased(MySerializableXact)) &&
3488 [ + + ]: 1587 : TransactionIdEquals(MySerializableXact->xmin,
3489 : : PredXact->SxactGlobalXmin))
3490 : : {
5750 heikki.linnakangas@i 3491 [ - + ]: 1570 : Assert(PredXact->SxactGlobalXminCount > 0);
3492 [ + + ]: 1570 : if (--(PredXact->SxactGlobalXminCount) == 0)
3493 : : {
3494 : 883 : SetNewSxactGlobalXmin();
3495 : 883 : needToClear = true;
3496 : : }
3497 : : }
3498 : :
3499 : 1589 : LWLockRelease(SerializableXactHashLock);
3500 : :
3501 : 1589 : LWLockAcquire(SerializableFinishedListLock, LW_EXCLUSIVE);
3502 : :
3503 : : /* Add this to the list of transactions to check for later cleanup. */
3504 [ + + ]: 1589 : if (isCommit)
1386 andres@anarazel.de 3505 : 1244 : dlist_push_tail(FinishedSerializableTransactions,
3506 : 1244 : &MySerializableXact->finishedLink);
3507 : :
3508 : : /*
3509 : : * If we're releasing a RO_SAFE transaction in parallel mode, we'll only
3510 : : * partially release it. That's necessary because other backends may have
3511 : : * a reference to it. The leader will release the SERIALIZABLEXACT itself
3512 : : * at the end of the transaction after workers have stopped running.
3513 : : */
5750 heikki.linnakangas@i 3514 [ + + ]: 1589 : if (!isCommit)
2792 tmunro@postgresql.or 3515 : 345 : ReleaseOneSerializableXact(MySerializableXact,
3516 [ + + + + ]: 345 : isReadOnlySafe && IsInParallelMode(),
3517 : 345 : false);
3518 : :
5750 heikki.linnakangas@i 3519 : 1589 : LWLockRelease(SerializableFinishedListLock);
3520 : :
3521 [ + + ]: 1589 : if (needToClear)
3522 : 883 : ClearOldPredicateLocks();
3523 : :
2792 tmunro@postgresql.or 3524 : 1589 : ReleasePredicateLocksLocal();
3525 : : }
3526 : :
3527 : : static void
3528 : 7721 : ReleasePredicateLocksLocal(void)
3529 : : {
5750 heikki.linnakangas@i 3530 : 7721 : MySerializableXact = InvalidSerializableXact;
5627 3531 : 7721 : MyXactDidWrite = false;
3532 : :
3533 : : /* Delete per-transaction lock table */
5750 3534 [ + + ]: 7721 : if (LocalPredicateLockHash != NULL)
3535 : : {
3536 : 1587 : hash_destroy(LocalPredicateLockHash);
3537 : 1587 : LocalPredicateLockHash = NULL;
3538 : : }
3539 : 7721 : }
3540 : :
3541 : : /*
3542 : : * Clear old predicate locks, belonging to committed transactions that are no
3543 : : * longer interesting to any in-progress transaction.
3544 : : */
3545 : : static void
3546 : 883 : ClearOldPredicateLocks(void)
3547 : : {
3548 : : dlist_mutable_iter iter;
3549 : :
3550 : : /*
3551 : : * Loop through finished transactions. They are in commit order, so we can
3552 : : * stop as soon as we find one that's still interesting.
3553 : : */
3554 : 883 : LWLockAcquire(SerializableFinishedListLock, LW_EXCLUSIVE);
3555 : 883 : LWLockAcquire(SerializableXactHashLock, LW_SHARED);
1386 andres@anarazel.de 3556 [ + - + + ]: 2135 : dlist_foreach_modify(iter, FinishedSerializableTransactions)
3557 : : {
3558 : 1261 : SERIALIZABLEXACT *finishedSxact =
1266 tgl@sss.pgh.pa.us 3559 : 1261 : dlist_container(SERIALIZABLEXACT, finishedLink, iter.cur);
3560 : :
5750 heikki.linnakangas@i 3561 [ + + ]: 1261 : if (!TransactionIdIsValid(PredXact->SxactGlobalXmin)
3562 [ + + ]: 28 : || TransactionIdPrecedesOrEquals(finishedSxact->finishedBefore,
3563 : 28 : PredXact->SxactGlobalXmin))
3564 : : {
3565 : : /*
3566 : : * This transaction committed before any in-progress transaction
3567 : : * took its snapshot. It's no longer interesting.
3568 : : */
3569 : 1244 : LWLockRelease(SerializableXactHashLock);
1386 andres@anarazel.de 3570 : 1244 : dlist_delete_thoroughly(&finishedSxact->finishedLink);
5750 heikki.linnakangas@i 3571 : 1244 : ReleaseOneSerializableXact(finishedSxact, false, false);
3572 : 1244 : LWLockAcquire(SerializableXactHashLock, LW_SHARED);
3573 : : }
3574 [ + - ]: 17 : else if (finishedSxact->commitSeqNo > PredXact->HavePartialClearedThrough
3424 tgl@sss.pgh.pa.us 3575 [ + + ]: 17 : && finishedSxact->commitSeqNo <= PredXact->CanPartialClearThrough)
3576 : : {
3577 : : /*
3578 : : * Any active transactions that took their snapshot before this
3579 : : * transaction committed are read-only, so we can clear part of
3580 : : * its state.
3581 : : */
5750 heikki.linnakangas@i 3582 : 8 : LWLockRelease(SerializableXactHashLock);
3583 : :
5405 3584 [ - + ]: 8 : if (SxactIsReadOnly(finishedSxact))
3585 : : {
3586 : : /* A read-only transaction can be removed entirely */
1386 andres@anarazel.de 3587 :UBC 0 : dlist_delete_thoroughly(&(finishedSxact->finishedLink));
5405 heikki.linnakangas@i 3588 : 0 : ReleaseOneSerializableXact(finishedSxact, false, false);
3589 : : }
3590 : : else
3591 : : {
3592 : : /*
3593 : : * A read-write transaction can only be partially cleared. We
3594 : : * need to keep the SERIALIZABLEXACT but can release the
3595 : : * SIREAD locks and conflicts in.
3596 : : */
5405 heikki.linnakangas@i 3597 :CBC 8 : ReleaseOneSerializableXact(finishedSxact, true, false);
3598 : : }
3599 : :
5750 3600 : 8 : PredXact->HavePartialClearedThrough = finishedSxact->commitSeqNo;
3601 : 8 : LWLockAcquire(SerializableXactHashLock, LW_SHARED);
3602 : : }
3603 : : else
3604 : : {
3605 : : /* Still interesting. */
3606 : : break;
3607 : : }
3608 : : }
3609 : 883 : LWLockRelease(SerializableXactHashLock);
3610 : :
3611 : : /*
3612 : : * Loop through predicate locks on dummy transaction for summarized data.
3613 : : */
2365 tgl@sss.pgh.pa.us 3614 : 883 : LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
1386 andres@anarazel.de 3615 [ + - - + ]: 883 : dlist_foreach_modify(iter, &OldCommittedSxact->predicateLocks)
3616 : : {
1386 andres@anarazel.de 3617 :UBC 0 : PREDICATELOCK *predlock =
1266 tgl@sss.pgh.pa.us 3618 : 0 : dlist_container(PREDICATELOCK, xactLink, iter.cur);
3619 : : bool canDoPartialCleanup;
3620 : :
5750 heikki.linnakangas@i 3621 : 0 : LWLockAcquire(SerializableXactHashLock, LW_SHARED);
5687 3622 [ # # ]: 0 : Assert(predlock->commitSeqNo != 0);
3623 [ # # ]: 0 : Assert(predlock->commitSeqNo != InvalidSerCommitSeqNo);
5750 3624 : 0 : canDoPartialCleanup = (predlock->commitSeqNo <= PredXact->CanPartialClearThrough);
3625 : 0 : LWLockRelease(SerializableXactHashLock);
3626 : :
3627 : : /*
3628 : : * If this lock originally belonged to an old enough transaction, we
3629 : : * can release it.
3630 : : */
3631 [ # # ]: 0 : if (canDoPartialCleanup)
3632 : : {
3633 : : PREDICATELOCKTAG tag;
3634 : : PREDICATELOCKTARGET *target;
3635 : : PREDICATELOCKTARGETTAG targettag;
3636 : : uint32 targettaghash;
3637 : : LWLock *partitionLock;
3638 : :
3639 : 0 : tag = predlock->tag;
3640 : 0 : target = tag.myTarget;
3641 : 0 : targettag = target->tag;
3642 : 0 : targettaghash = PredicateLockTargetTagHashCode(&targettag);
3643 : 0 : partitionLock = PredicateLockHashPartitionLock(targettaghash);
3644 : :
3645 : 0 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
3646 : :
1386 andres@anarazel.de 3647 : 0 : dlist_delete(&(predlock->targetLink));
3648 : 0 : dlist_delete(&(predlock->xactLink));
3649 : :
5750 heikki.linnakangas@i 3650 : 0 : hash_search_with_hash_value(PredicateLockHash, &tag,
3424 tgl@sss.pgh.pa.us 3651 : 0 : PredicateLockHashCodeFromTargetHashCode(&tag,
3652 : : targettaghash),
3653 : : HASH_REMOVE, NULL);
5750 heikki.linnakangas@i 3654 : 0 : RemoveTargetIfNoLongerUsed(target, targettaghash);
3655 : :
3656 : 0 : LWLockRelease(partitionLock);
3657 : : }
3658 : : }
3659 : :
2365 tgl@sss.pgh.pa.us 3660 :CBC 883 : LWLockRelease(SerializablePredicateListLock);
5750 heikki.linnakangas@i 3661 : 883 : LWLockRelease(SerializableFinishedListLock);
3662 : 883 : }
3663 : :
3664 : : /*
3665 : : * This is the normal way to delete anything from any of the predicate
3666 : : * locking hash tables. Given a transaction which we know can be deleted:
3667 : : * delete all predicate locks held by that transaction and any predicate
3668 : : * lock targets which are now unreferenced by a lock; delete all conflicts
3669 : : * for the transaction; delete all xid values for the transaction; then
3670 : : * delete the transaction.
3671 : : *
3672 : : * When the partial flag is set, we can release all predicate locks and
3673 : : * in-conflict information -- we've established that there are no longer
3674 : : * any overlapping read write transactions for which this transaction could
3675 : : * matter -- but keep the transaction entry itself and any outConflicts.
3676 : : *
3677 : : * When the summarize flag is set, we've run short of room for sxact data
3678 : : * and must summarize to the SLRU. Predicate locks are transferred to a
3679 : : * dummy "old" transaction, with duplicate locks on a single target
3680 : : * collapsing to a single lock with the "latest" commitSeqNo from among
3681 : : * the conflicting locks..
3682 : : */
3683 : : static void
3684 : 1597 : ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial,
3685 : : bool summarize)
3686 : : {
3687 : : SERIALIZABLEXIDTAG sxidtag;
3688 : : dlist_mutable_iter iter;
3689 : :
3690 [ - + ]: 1597 : Assert(sxact != NULL);
5616 3691 [ + + - + ]: 1597 : Assert(SxactIsRolledBack(sxact) || SxactIsCommitted(sxact));
5405 3692 [ + + - + ]: 1597 : Assert(partial || !SxactIsOnFinishedList(sxact));
5750 3693 [ - + ]: 1597 : Assert(LWLockHeldByMe(SerializableFinishedListLock));
3694 : :
3695 : : /*
3696 : : * First release all the predicate locks held by this xact (or transfer
3697 : : * them to OldCommittedSxact if summarize is true)
3698 : : */
2365 tgl@sss.pgh.pa.us 3699 : 1597 : LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
2792 tmunro@postgresql.or 3700 [ + + ]: 1597 : if (IsInParallelMode())
2365 tgl@sss.pgh.pa.us 3701 : 3 : LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
1386 andres@anarazel.de 3702 [ + - + + ]: 4491 : dlist_foreach_modify(iter, &sxact->predicateLocks)
3703 : : {
3704 : 2894 : PREDICATELOCK *predlock =
1266 tgl@sss.pgh.pa.us 3705 : 2894 : dlist_container(PREDICATELOCK, xactLink, iter.cur);
3706 : : PREDICATELOCKTAG tag;
3707 : : PREDICATELOCKTARGET *target;
3708 : : PREDICATELOCKTARGETTAG targettag;
3709 : : uint32 targettaghash;
3710 : : LWLock *partitionLock;
3711 : :
5750 heikki.linnakangas@i 3712 : 2894 : tag = predlock->tag;
3713 : 2894 : target = tag.myTarget;
3714 : 2894 : targettag = target->tag;
3715 : 2894 : targettaghash = PredicateLockTargetTagHashCode(&targettag);
3716 : 2894 : partitionLock = PredicateLockHashPartitionLock(targettaghash);
3717 : :
3718 : 2894 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
3719 : :
1386 andres@anarazel.de 3720 : 2894 : dlist_delete(&predlock->targetLink);
3721 : :
5750 heikki.linnakangas@i 3722 : 2894 : hash_search_with_hash_value(PredicateLockHash, &tag,
3424 tgl@sss.pgh.pa.us 3723 : 2894 : PredicateLockHashCodeFromTargetHashCode(&tag,
3724 : : targettaghash),
3725 : : HASH_REMOVE, NULL);
5750 heikki.linnakangas@i 3726 [ - + ]: 2894 : if (summarize)
3727 : : {
3728 : : bool found;
3729 : :
3730 : : /* Fold into dummy transaction list. */
5750 heikki.linnakangas@i 3731 :UBC 0 : tag.myXact = OldCommittedSxact;
3732 : 0 : predlock = hash_search_with_hash_value(PredicateLockHash, &tag,
3424 tgl@sss.pgh.pa.us 3733 : 0 : PredicateLockHashCodeFromTargetHashCode(&tag,
3734 : : targettaghash),
3735 : : HASH_ENTER_NULL, &found);
5750 heikki.linnakangas@i 3736 [ # # ]: 0 : if (!predlock)
3737 [ # # ]: 0 : ereport(ERROR,
3738 : : (errcode(ERRCODE_OUT_OF_MEMORY),
3739 : : errmsg("out of shared memory"),
3740 : : errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
3741 [ # # ]: 0 : if (found)
3742 : : {
5687 3743 [ # # ]: 0 : Assert(predlock->commitSeqNo != 0);
3744 [ # # ]: 0 : Assert(predlock->commitSeqNo != InvalidSerCommitSeqNo);
5750 3745 [ # # ]: 0 : if (predlock->commitSeqNo < sxact->commitSeqNo)
3746 : 0 : predlock->commitSeqNo = sxact->commitSeqNo;
3747 : : }
3748 : : else
3749 : : {
1386 andres@anarazel.de 3750 : 0 : dlist_push_tail(&target->predicateLocks,
3751 : : &predlock->targetLink);
3752 : 0 : dlist_push_tail(&OldCommittedSxact->predicateLocks,
3753 : : &predlock->xactLink);
5750 heikki.linnakangas@i 3754 : 0 : predlock->commitSeqNo = sxact->commitSeqNo;
3755 : : }
3756 : : }
3757 : : else
5750 heikki.linnakangas@i 3758 :CBC 2894 : RemoveTargetIfNoLongerUsed(target, targettaghash);
3759 : :
3760 : 2894 : LWLockRelease(partitionLock);
3761 : : }
3762 : :
3763 : : /*
3764 : : * Rather than retail removal, just re-init the head after we've run
3765 : : * through the list.
3766 : : */
1386 andres@anarazel.de 3767 : 1597 : dlist_init(&sxact->predicateLocks);
3768 : :
2792 tmunro@postgresql.or 3769 [ + + ]: 1597 : if (IsInParallelMode())
2365 tgl@sss.pgh.pa.us 3770 : 3 : LWLockRelease(&sxact->perXactPredicateListLock);
3771 : 1597 : LWLockRelease(SerializablePredicateListLock);
3772 : :
5750 heikki.linnakangas@i 3773 : 1597 : sxidtag.xid = sxact->topXid;
3774 : 1597 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
3775 : :
3776 : : /* Release all outConflicts (unless 'partial' is true) */
3777 [ + + ]: 1597 : if (!partial)
3778 : : {
1386 andres@anarazel.de 3779 [ + - - + ]: 1587 : dlist_foreach_modify(iter, &sxact->outConflicts)
3780 : : {
1386 andres@anarazel.de 3781 :UBC 0 : RWConflict conflict =
3782 : : dlist_container(RWConflictData, outLink, iter.cur);
3783 : :
5750 heikki.linnakangas@i 3784 [ # # ]: 0 : if (summarize)
3785 : 0 : conflict->sxactIn->flags |= SXACT_FLAG_SUMMARY_CONFLICT_IN;
3786 : 0 : ReleaseRWConflict(conflict);
3787 : : }
3788 : : }
3789 : :
3790 : : /* Release all inConflicts. */
1386 andres@anarazel.de 3791 [ + - - + ]:CBC 1597 : dlist_foreach_modify(iter, &sxact->inConflicts)
3792 : : {
1386 andres@anarazel.de 3793 :UBC 0 : RWConflict conflict =
1266 tgl@sss.pgh.pa.us 3794 : 0 : dlist_container(RWConflictData, inLink, iter.cur);
3795 : :
5750 heikki.linnakangas@i 3796 [ # # ]: 0 : if (summarize)
3797 : 0 : conflict->sxactOut->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
3798 : 0 : ReleaseRWConflict(conflict);
3799 : : }
3800 : :
3801 : : /* Finally, get rid of the xid and the record of the transaction itself. */
5750 heikki.linnakangas@i 3802 [ + + ]:CBC 1597 : if (!partial)
3803 : : {
3804 [ + + ]: 1587 : if (sxidtag.xid != InvalidTransactionId)
3805 : 1312 : hash_search(SerializableXidHash, &sxidtag, HASH_REMOVE, NULL);
3806 : 1587 : ReleasePredXact(sxact);
3807 : : }
3808 : :
3809 : 1597 : LWLockRelease(SerializableXactHashLock);
3810 : 1597 : }
3811 : :
3812 : : /*
3813 : : * Tests whether the given top level transaction is concurrent with
3814 : : * (overlaps) our current transaction.
3815 : : *
3816 : : * We need to identify the top level transaction for SSI, anyway, so pass
3817 : : * that to this function to save the overhead of checking the snapshot's
3818 : : * subxip array.
3819 : : */
3820 : : static bool
3821 : 545 : XidIsConcurrent(TransactionId xid)
3822 : : {
3823 : : Snapshot snap;
3824 : :
3825 [ - + ]: 545 : Assert(TransactionIdIsValid(xid));
3826 [ - + ]: 545 : Assert(!TransactionIdEquals(xid, GetTopTransactionIdIfAny()));
3827 : :
3828 : 545 : snap = GetTransactionSnapshot();
3829 : :
3830 [ - + ]: 545 : if (TransactionIdPrecedes(xid, snap->xmin))
5750 heikki.linnakangas@i 3831 :UBC 0 : return false;
3832 : :
5750 heikki.linnakangas@i 3833 [ + + ]:CBC 545 : if (TransactionIdFollowsOrEquals(xid, snap->xmax))
3834 : 532 : return true;
3835 : :
1505 michael@paquier.xyz 3836 : 13 : return pg_lfind32(xid, snap->xip, snap->xcnt);
3837 : : }
3838 : :
3839 : : bool
2473 tmunro@postgresql.or 3840 : 44056665 : CheckForSerializableConflictOutNeeded(Relation relation, Snapshot snapshot)
3841 : : {
3842 [ + + ]: 44056665 : if (!SerializationNeededForRead(relation, snapshot))
3843 : 44048063 : return false;
3844 : :
3845 : : /* Check if someone else has already decided that we need to die */
3846 [ - + ]: 8602 : if (SxactIsDoomed(MySerializableXact))
3847 : : {
2473 tmunro@postgresql.or 3848 [ # # ]:UBC 0 : ereport(ERROR,
3849 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3850 : : errmsg("could not serialize access due to read/write dependencies among transactions"),
3851 : : errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict out checking."),
3852 : : errhint("The transaction might succeed if retried.")));
3853 : : }
3854 : :
2473 tmunro@postgresql.or 3855 :CBC 8602 : return true;
3856 : : }
3857 : :
3858 : : /*
3859 : : * CheckForSerializableConflictOut
3860 : : * A table AM is reading a tuple that has been modified. If it determines
3861 : : * that the tuple version it is reading is not visible to us, it should
3862 : : * pass in the top level xid of the transaction that created it.
3863 : : * Otherwise, if it determines that it is visible to us but it has been
3864 : : * deleted or there is a newer version available due to an update, it
3865 : : * should pass in the top level xid of the modifying transaction.
3866 : : *
3867 : : * This function will check for overlap with our own transaction. If the given
3868 : : * xid is also serializable and the transactions overlap (i.e., they cannot see
3869 : : * each other's writes), then we have a conflict out.
3870 : : */
3871 : : void
3872 : 580 : CheckForSerializableConflictOut(Relation relation, TransactionId xid, Snapshot snapshot)
3873 : : {
3874 : : SERIALIZABLEXIDTAG sxidtag;
3875 : : SERIALIZABLEXID *sxid;
3876 : : SERIALIZABLEXACT *sxact;
3877 : :
5622 heikki.linnakangas@i 3878 [ - + ]: 580 : if (!SerializationNeededForRead(relation, snapshot))
5750 3879 : 205 : return;
3880 : :
3881 : : /* Check if someone else has already decided that we need to die */
5622 3882 [ - + ]: 580 : if (SxactIsDoomed(MySerializableXact))
3883 : : {
5750 heikki.linnakangas@i 3884 [ # # ]:UBC 0 : ereport(ERROR,
3885 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3886 : : errmsg("could not serialize access due to read/write dependencies among transactions"),
3887 : : errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict out checking."),
3888 : : errhint("The transaction might succeed if retried.")));
3889 : : }
5750 heikki.linnakangas@i 3890 [ - + ]:CBC 580 : Assert(TransactionIdIsValid(xid));
3891 : :
3892 [ - + ]: 580 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
5750 heikki.linnakangas@i 3893 :UBC 0 : return;
3894 : :
3895 : : /*
3896 : : * Find sxact or summarized info for the top level xid.
3897 : : */
5750 heikki.linnakangas@i 3898 :CBC 580 : sxidtag.xid = xid;
3899 : 580 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
3900 : : sxid = (SERIALIZABLEXID *)
3901 : 580 : hash_search(SerializableXidHash, &sxidtag, HASH_FIND, NULL);
3902 [ + + ]: 580 : if (!sxid)
3903 : : {
3904 : : /*
3905 : : * Transaction not found in "normal" SSI structures. Check whether it
3906 : : * got pushed out to SLRU storage for "old committed" transactions.
3907 : : */
3908 : : SerCommitSeqNo conflictCommitSeqNo;
3909 : :
2365 tgl@sss.pgh.pa.us 3910 : 25 : conflictCommitSeqNo = SerialGetMinConflictCommitSeqNo(xid);
5750 heikki.linnakangas@i 3911 [ - + ]: 25 : if (conflictCommitSeqNo != 0)
3912 : : {
5750 heikki.linnakangas@i 3913 [ # # ]:UBC 0 : if (conflictCommitSeqNo != InvalidSerCommitSeqNo
3914 [ # # ]: 0 : && (!SxactIsReadOnly(MySerializableXact)
3915 : 0 : || conflictCommitSeqNo
3916 [ # # ]: 0 : <= MySerializableXact->SeqNo.lastCommitBeforeSnapshot))
3917 [ # # ]: 0 : ereport(ERROR,
3918 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3919 : : errmsg("could not serialize access due to read/write dependencies among transactions"),
3920 : : errdetail_internal("Reason code: Canceled on conflict out to old pivot %u.", xid),
3921 : : errhint("The transaction might succeed if retried.")));
3922 : :
3923 [ # # ]: 0 : if (SxactHasSummaryConflictIn(MySerializableXact)
1386 andres@anarazel.de 3924 [ # # ]: 0 : || !dlist_is_empty(&MySerializableXact->inConflicts))
5750 heikki.linnakangas@i 3925 [ # # ]: 0 : ereport(ERROR,
3926 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3927 : : errmsg("could not serialize access due to read/write dependencies among transactions"),
3928 : : errdetail_internal("Reason code: Canceled on identification as a pivot, with conflict out to old committed transaction %u.", xid),
3929 : : errhint("The transaction might succeed if retried.")));
3930 : :
3931 : 0 : MySerializableXact->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
3932 : : }
3933 : :
3934 : : /* It's not serializable or otherwise not important. */
5750 heikki.linnakangas@i 3935 :CBC 25 : LWLockRelease(SerializableXactHashLock);
3936 : 25 : return;
3937 : : }
3938 : 555 : sxact = sxid->myXact;
3939 [ - + ]: 555 : Assert(TransactionIdEquals(sxact->topXid, xid));
5622 3940 [ + - + + ]: 555 : if (sxact == MySerializableXact || SxactIsDoomed(sxact))
3941 : : {
3942 : : /* Can't conflict with ourself or a transaction that will roll back. */
5750 3943 : 4 : LWLockRelease(SerializableXactHashLock);
3944 : 4 : return;
3945 : : }
3946 : :
3947 : : /*
3948 : : * We have a conflict out to a transaction which has a conflict out to a
3949 : : * summarized transaction. That summarized transaction must have
3950 : : * committed first, and we can't tell when it committed in relation to our
3951 : : * snapshot acquisition, so something needs to be canceled.
3952 : : */
3953 [ - + ]: 551 : if (SxactHasSummaryConflictOut(sxact))
3954 : : {
5750 heikki.linnakangas@i 3955 [ # # ]:UBC 0 : if (!SxactIsPrepared(sxact))
3956 : : {
5622 3957 : 0 : sxact->flags |= SXACT_FLAG_DOOMED;
5750 3958 : 0 : LWLockRelease(SerializableXactHashLock);
3959 : 0 : return;
3960 : : }
3961 : : else
3962 : : {
3963 : 0 : LWLockRelease(SerializableXactHashLock);
3964 [ # # ]: 0 : ereport(ERROR,
3965 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3966 : : errmsg("could not serialize access due to read/write dependencies among transactions"),
3967 : : errdetail_internal("Reason code: Canceled on conflict out to old pivot."),
3968 : : errhint("The transaction might succeed if retried.")));
3969 : : }
3970 : : }
3971 : :
3972 : : /*
3973 : : * If this is a read-only transaction and the writing transaction has
3974 : : * committed, and it doesn't have a rw-conflict to a transaction which
3975 : : * committed before it, no conflict.
3976 : : */
5750 heikki.linnakangas@i 3977 [ + + ]:CBC 551 : if (SxactIsReadOnly(MySerializableXact)
3978 [ + + ]: 119 : && SxactIsCommitted(sxact)
3979 [ + - ]: 8 : && !SxactHasSummaryConflictOut(sxact)
3980 [ + + ]: 8 : && (!SxactHasConflictOut(sxact)
3981 [ - + ]: 2 : || MySerializableXact->SeqNo.lastCommitBeforeSnapshot < sxact->SeqNo.earliestOutConflictCommit))
3982 : : {
3983 : : /* Read-only transaction will appear to run first. No conflict. */
3984 : 6 : LWLockRelease(SerializableXactHashLock);
3985 : 6 : return;
3986 : : }
3987 : :
3988 [ - + ]: 545 : if (!XidIsConcurrent(xid))
3989 : : {
3990 : : /* This write was already in our snapshot; no conflict. */
5750 heikki.linnakangas@i 3991 :UBC 0 : LWLockRelease(SerializableXactHashLock);
3992 : 0 : return;
3993 : : }
3994 : :
5627 heikki.linnakangas@i 3995 [ + + ]:CBC 545 : if (RWConflictExists(MySerializableXact, sxact))
3996 : : {
3997 : : /* We don't want duplicate conflict records in the list. */
5750 3998 : 170 : LWLockRelease(SerializableXactHashLock);
3999 : 170 : return;
4000 : : }
4001 : :
4002 : : /*
4003 : : * Flag the conflict. But first, if this conflict creates a dangerous
4004 : : * structure, ereport an error.
4005 : : */
5627 4006 : 375 : FlagRWConflict(MySerializableXact, sxact);
5750 4007 : 362 : LWLockRelease(SerializableXactHashLock);
4008 : : }
4009 : :
4010 : : /*
4011 : : * Check a particular target for rw-dependency conflict in. A subroutine of
4012 : : * CheckForSerializableConflictIn().
4013 : : */
4014 : : static void
4015 : 7613 : CheckTargetForConflictsIn(PREDICATELOCKTARGETTAG *targettag)
4016 : : {
4017 : : uint32 targettaghash;
4018 : : LWLock *partitionLock;
4019 : : PREDICATELOCKTARGET *target;
5649 rhaas@postgresql.org 4020 : 7613 : PREDICATELOCK *mypredlock = NULL;
4021 : : PREDICATELOCKTAG mypredlocktag;
4022 : : dlist_mutable_iter iter;
4023 : :
5750 heikki.linnakangas@i 4024 [ - + ]: 7613 : Assert(MySerializableXact != InvalidSerializableXact);
4025 : :
4026 : : /*
4027 : : * The same hash and LW lock apply to the lock target and the lock itself.
4028 : : */
4029 : 7613 : targettaghash = PredicateLockTargetTagHashCode(targettag);
4030 : 7613 : partitionLock = PredicateLockHashPartitionLock(targettaghash);
4031 : 7613 : LWLockAcquire(partitionLock, LW_SHARED);
4032 : : target = (PREDICATELOCKTARGET *)
4033 : 7613 : hash_search_with_hash_value(PredicateLockTargetHash,
4034 : : targettag, targettaghash,
4035 : : HASH_FIND, NULL);
4036 [ + + ]: 7613 : if (!target)
4037 : : {
4038 : : /* Nothing has this target locked; we're done here. */
4039 : 5702 : LWLockRelease(partitionLock);
5728 4040 : 5702 : return;
4041 : : }
4042 : :
4043 : : /*
4044 : : * Each lock for an overlapping transaction represents a conflict: a
4045 : : * rw-dependency in to this transaction.
4046 : : */
5750 4047 : 1911 : LWLockAcquire(SerializableXactHashLock, LW_SHARED);
4048 : :
1386 andres@anarazel.de 4049 [ + - + + ]: 4301 : dlist_foreach_modify(iter, &target->predicateLocks)
4050 : : {
4051 : 2463 : PREDICATELOCK *predlock =
1266 tgl@sss.pgh.pa.us 4052 : 2463 : dlist_container(PREDICATELOCK, targetLink, iter.cur);
1386 andres@anarazel.de 4053 : 2463 : SERIALIZABLEXACT *sxact = predlock->tag.myXact;
4054 : :
5750 heikki.linnakangas@i 4055 [ + + ]: 2463 : if (sxact == MySerializableXact)
4056 : : {
4057 : : /*
4058 : : * If we're getting a write lock on a tuple, we don't need a
4059 : : * predicate (SIREAD) lock on the same tuple. We can safely remove
4060 : : * our SIREAD lock, but we'll defer doing so until after the loop
4061 : : * because that requires upgrading to an exclusive partition lock.
4062 : : *
4063 : : * We can't use this optimization within a subtransaction because
4064 : : * the subtransaction could roll back, and we would be left
4065 : : * without any lock at the top level.
4066 : : */
5690 rhaas@postgresql.org 4067 [ + - ]: 1587 : if (!IsSubTransaction()
4068 [ + + ]: 1587 : && GET_PREDICATELOCKTARGETTAG_OFFSET(*targettag))
4069 : : {
5649 4070 : 405 : mypredlock = predlock;
4071 : 405 : mypredlocktag = predlock->tag;
4072 : : }
4073 : : }
5622 heikki.linnakangas@i 4074 [ + - ]: 876 : else if (!SxactIsDoomed(sxact)
5750 4075 [ + + ]: 876 : && (!SxactIsCommitted(sxact)
4076 [ + + ]: 94 : || TransactionIdPrecedes(GetTransactionSnapshot()->xmin,
4077 : : sxact->finishedBefore))
5627 4078 [ + + ]: 867 : && !RWConflictExists(sxact, MySerializableXact))
4079 : : {
5750 4080 : 523 : LWLockRelease(SerializableXactHashLock);
4081 : 523 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
4082 : :
4083 : : /*
4084 : : * Re-check after getting exclusive lock because the other
4085 : : * transaction may have flagged a conflict.
4086 : : */
5622 4087 [ + - ]: 523 : if (!SxactIsDoomed(sxact)
5693 rhaas@postgresql.org 4088 [ + + ]: 523 : && (!SxactIsCommitted(sxact)
4089 [ + - ]: 83 : || TransactionIdPrecedes(GetTransactionSnapshot()->xmin,
4090 : : sxact->finishedBefore))
5627 heikki.linnakangas@i 4091 [ + - ]: 523 : && !RWConflictExists(sxact, MySerializableXact))
4092 : : {
4093 : 523 : FlagRWConflict(sxact, MySerializableXact);
4094 : : }
4095 : :
5750 4096 : 450 : LWLockRelease(SerializableXactHashLock);
4097 : 450 : LWLockAcquire(SerializableXactHashLock, LW_SHARED);
4098 : : }
4099 : : }
4100 : 1838 : LWLockRelease(SerializableXactHashLock);
4101 : 1838 : LWLockRelease(partitionLock);
4102 : :
4103 : : /*
4104 : : * If we found one of our own SIREAD locks to remove, remove it now.
4105 : : *
4106 : : * At this point our transaction already has a RowExclusiveLock on the
4107 : : * relation, so we are OK to drop the predicate lock on the tuple, if
4108 : : * found, without fearing that another write against the tuple will occur
4109 : : * before the MVCC information makes it to the buffer.
4110 : : */
5649 rhaas@postgresql.org 4111 [ + + ]: 1838 : if (mypredlock != NULL)
4112 : : {
4113 : : uint32 predlockhashcode;
4114 : : PREDICATELOCK *rmpredlock;
4115 : :
2365 tgl@sss.pgh.pa.us 4116 : 398 : LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
2792 tmunro@postgresql.or 4117 [ - + ]: 398 : if (IsInParallelMode())
2365 tgl@sss.pgh.pa.us 4118 :UBC 0 : LWLockAcquire(&MySerializableXact->perXactPredicateListLock, LW_EXCLUSIVE);
5649 rhaas@postgresql.org 4119 :CBC 398 : LWLockAcquire(partitionLock, LW_EXCLUSIVE);
4120 : 398 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
4121 : :
4122 : : /*
4123 : : * Remove the predicate lock from shared memory, if it wasn't removed
4124 : : * while the locks were released. One way that could happen is from
4125 : : * autovacuum cleaning up an index.
4126 : : */
4127 : 398 : predlockhashcode = PredicateLockHashCodeFromTargetHashCode
4128 : : (&mypredlocktag, targettaghash);
4129 : : rmpredlock = (PREDICATELOCK *)
4130 : 398 : hash_search_with_hash_value(PredicateLockHash,
4131 : : &mypredlocktag,
4132 : : predlockhashcode,
4133 : : HASH_FIND, NULL);
4134 [ + - ]: 398 : if (rmpredlock != NULL)
4135 : : {
4136 [ - + ]: 398 : Assert(rmpredlock == mypredlock);
4137 : :
1386 andres@anarazel.de 4138 : 398 : dlist_delete(&(mypredlock->targetLink));
4139 : 398 : dlist_delete(&(mypredlock->xactLink));
4140 : :
4141 : : rmpredlock = (PREDICATELOCK *)
5649 rhaas@postgresql.org 4142 : 398 : hash_search_with_hash_value(PredicateLockHash,
4143 : : &mypredlocktag,
4144 : : predlockhashcode,
4145 : : HASH_REMOVE, NULL);
4146 [ - + ]: 398 : Assert(rmpredlock == mypredlock);
4147 : :
4148 : 398 : RemoveTargetIfNoLongerUsed(target, targettaghash);
4149 : : }
4150 : :
4151 : 398 : LWLockRelease(SerializableXactHashLock);
4152 : 398 : LWLockRelease(partitionLock);
2792 tmunro@postgresql.or 4153 [ - + ]: 398 : if (IsInParallelMode())
2365 tgl@sss.pgh.pa.us 4154 :UBC 0 : LWLockRelease(&MySerializableXact->perXactPredicateListLock);
2365 tgl@sss.pgh.pa.us 4155 :CBC 398 : LWLockRelease(SerializablePredicateListLock);
4156 : :
5649 rhaas@postgresql.org 4157 [ + - ]: 398 : if (rmpredlock != NULL)
4158 : : {
4159 : : /*
4160 : : * Remove entry in local lock table if it exists. It's OK if it
4161 : : * doesn't exist; that means the lock was transferred to a new
4162 : : * target by a different backend.
4163 : : */
4164 : 398 : hash_search_with_hash_value(LocalPredicateLockHash,
4165 : : targettag, targettaghash,
4166 : : HASH_REMOVE, NULL);
4167 : :
4168 : 398 : DecrementParentLocks(targettag);
4169 : : }
4170 : : }
4171 : : }
4172 : :
4173 : : /*
4174 : : * CheckForSerializableConflictIn
4175 : : * We are writing the given tuple. If that indicates a rw-conflict
4176 : : * in from another serializable transaction, take appropriate action.
4177 : : *
4178 : : * Skip checking for any granularity for which a parameter is missing.
4179 : : *
4180 : : * A tuple update or delete is in conflict if we have a predicate lock
4181 : : * against the relation or page in which the tuple exists, or against the
4182 : : * tuple itself.
4183 : : */
4184 : : void
371 peter@eisentraut.org 4185 : 24817295 : CheckForSerializableConflictIn(Relation relation, const ItemPointerData *tid, BlockNumber blkno)
4186 : : {
4187 : : PREDICATELOCKTARGETTAG targettag;
4188 : :
5622 heikki.linnakangas@i 4189 [ + + ]: 24817295 : if (!SerializationNeededForWrite(relation))
5750 4190 : 24812797 : return;
4191 : :
4192 : : /* Check if someone else has already decided that we need to die */
5622 4193 [ + + ]: 4498 : if (SxactIsDoomed(MySerializableXact))
5750 4194 [ + - ]: 1 : ereport(ERROR,
4195 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
4196 : : errmsg("could not serialize access due to read/write dependencies among transactions"),
4197 : : errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict in checking."),
4198 : : errhint("The transaction might succeed if retried.")));
4199 : :
4200 : : /*
4201 : : * We're doing a write which might cause rw-conflicts now or later.
4202 : : * Memorize that fact.
4203 : : */
5627 4204 : 4497 : MyXactDidWrite = true;
4205 : :
4206 : : /*
4207 : : * It is important that we check for locks from the finest granularity to
4208 : : * the coarsest granularity, so that granularity promotion doesn't cause
4209 : : * us to miss a lock. The new (coarser) lock will be acquired before the
4210 : : * old (finer) locks are released.
4211 : : *
4212 : : * It is not possible to take and hold a lock across the checks for all
4213 : : * granularities because each target could be in a separate partition.
4214 : : */
2473 tmunro@postgresql.or 4215 [ + + ]: 4497 : if (tid != NULL)
4216 : : {
5750 heikki.linnakangas@i 4217 : 662 : SET_PREDICATELOCKTARGETTAG_TUPLE(targettag,
4218 : : relation->rd_locator.dbOid,
4219 : : relation->rd_id,
4220 : : ItemPointerGetBlockNumber(tid),
4221 : : ItemPointerGetOffsetNumber(tid));
4222 : 662 : CheckTargetForConflictsIn(&targettag);
4223 : : }
4224 : :
2473 tmunro@postgresql.or 4225 [ + + ]: 4473 : if (blkno != InvalidBlockNumber)
4226 : : {
5750 heikki.linnakangas@i 4227 : 2508 : SET_PREDICATELOCKTARGETTAG_PAGE(targettag,
4228 : : relation->rd_locator.dbOid,
4229 : : relation->rd_id,
4230 : : blkno);
4231 : 2508 : CheckTargetForConflictsIn(&targettag);
4232 : : }
4233 : :
4234 : 4443 : SET_PREDICATELOCKTARGETTAG_RELATION(targettag,
4235 : : relation->rd_locator.dbOid,
4236 : : relation->rd_id);
4237 : 4443 : CheckTargetForConflictsIn(&targettag);
4238 : : }
4239 : :
4240 : : /*
4241 : : * CheckTableForSerializableConflictIn
4242 : : * The entire table is going through a DDL-style logical mass delete
4243 : : * like TRUNCATE or DROP TABLE. If that causes a rw-conflict in from
4244 : : * another serializable transaction, take appropriate action.
4245 : : *
4246 : : * While these operations do not operate entirely within the bounds of
4247 : : * snapshot isolation, they can occur inside a serializable transaction, and
4248 : : * will logically occur after any reads which saw rows which were destroyed
4249 : : * by these operations, so we do what we can to serialize properly under
4250 : : * SSI.
4251 : : *
4252 : : * The relation passed in must be a heap relation. Any predicate lock of any
4253 : : * granularity on the heap will cause a rw-conflict in to this transaction.
4254 : : * Predicate locks on indexes do not matter because they only exist to guard
4255 : : * against conflicting inserts into the index, and this is a mass *delete*.
4256 : : * When a table is truncated or dropped, the index will also be truncated
4257 : : * or dropped, and we'll deal with locks on the index when that happens.
4258 : : *
4259 : : * Dropping or truncating a table also needs to drop any existing predicate
4260 : : * locks on heap tuples or pages, because they're about to go away. This
4261 : : * should be done before altering the predicate locks because the transaction
4262 : : * could be rolled back because of a conflict, in which case the lock changes
4263 : : * are not needed. (At the moment, we don't actually bother to drop the
4264 : : * existing locks on a dropped or truncated table at the moment. That might
4265 : : * lead to some false positives, but it doesn't seem worth the trouble.)
4266 : : */
4267 : : void
5615 4268 : 34516 : CheckTableForSerializableConflictIn(Relation relation)
4269 : : {
4270 : : HASH_SEQ_STATUS seqstat;
4271 : : PREDICATELOCKTARGET *target;
4272 : : Oid dbId;
4273 : : Oid heapId;
4274 : : int i;
4275 : :
4276 : : /*
4277 : : * Bail out quickly if there are no serializable transactions running.
4278 : : * It's safe to check this without taking locks because the caller is
4279 : : * holding an ACCESS EXCLUSIVE lock on the relation. No new locks which
4280 : : * would matter here can be acquired while that is held.
4281 : : */
5629 4282 [ + + ]: 34516 : if (!TransactionIdIsValid(PredXact->SxactGlobalXmin))
4283 : 34514 : return;
4284 : :
5622 4285 [ + + ]: 115 : if (!SerializationNeededForWrite(relation))
5629 4286 : 113 : return;
4287 : :
4288 : : /*
4289 : : * We're doing a write which might cause rw-conflicts now or later.
4290 : : * Memorize that fact.
4291 : : */
5627 4292 : 2 : MyXactDidWrite = true;
4293 : :
5629 4294 [ - + ]: 2 : Assert(relation->rd_index == NULL); /* not an index relation */
4295 : :
1583 rhaas@postgresql.org 4296 : 2 : dbId = relation->rd_locator.dbOid;
5629 heikki.linnakangas@i 4297 : 2 : heapId = relation->rd_id;
4298 : :
2365 tgl@sss.pgh.pa.us 4299 : 2 : LWLockAcquire(SerializablePredicateListLock, LW_EXCLUSIVE);
5629 heikki.linnakangas@i 4300 [ + + ]: 34 : for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
4665 rhaas@postgresql.org 4301 : 32 : LWLockAcquire(PredicateLockHashPartitionLockByIndex(i), LW_SHARED);
4023 kgrittn@postgresql.o 4302 : 2 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
4303 : :
4304 : : /* Scan through target list */
5629 heikki.linnakangas@i 4305 : 2 : hash_seq_init(&seqstat, PredicateLockTargetHash);
4306 : :
4307 [ + + ]: 4 : while ((target = (PREDICATELOCKTARGET *) hash_seq_search(&seqstat)))
4308 : : {
4309 : : dlist_mutable_iter iter;
4310 : :
4311 : : /*
4312 : : * Check whether this is a target which needs attention.
4313 : : */
4314 [ + - ]: 2 : if (GET_PREDICATELOCKTARGETTAG_RELATION(target->tag) != heapId)
4315 : 2 : continue; /* wrong relation id */
5629 heikki.linnakangas@i 4316 [ # # ]:UBC 0 : if (GET_PREDICATELOCKTARGETTAG_DB(target->tag) != dbId)
4317 : 0 : continue; /* wrong database id */
4318 : :
4319 : : /*
4320 : : * Loop through locks for this target and flag conflicts.
4321 : : */
1386 andres@anarazel.de 4322 [ # # # # ]: 0 : dlist_foreach_modify(iter, &target->predicateLocks)
4323 : : {
4324 : 0 : PREDICATELOCK *predlock =
1266 tgl@sss.pgh.pa.us 4325 : 0 : dlist_container(PREDICATELOCK, targetLink, iter.cur);
4326 : :
5629 heikki.linnakangas@i 4327 [ # # ]: 0 : if (predlock->tag.myXact != MySerializableXact
3424 tgl@sss.pgh.pa.us 4328 [ # # ]: 0 : && !RWConflictExists(predlock->tag.myXact, MySerializableXact))
4329 : : {
5627 heikki.linnakangas@i 4330 : 0 : FlagRWConflict(predlock->tag.myXact, MySerializableXact);
4331 : : }
4332 : : }
4333 : : }
4334 : :
4335 : : /* Release locks in reverse order */
5629 heikki.linnakangas@i 4336 :CBC 2 : LWLockRelease(SerializableXactHashLock);
4337 [ + + ]: 34 : for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
4665 rhaas@postgresql.org 4338 : 32 : LWLockRelease(PredicateLockHashPartitionLockByIndex(i));
2365 tgl@sss.pgh.pa.us 4339 : 2 : LWLockRelease(SerializablePredicateListLock);
4340 : : }
4341 : :
4342 : :
4343 : : /*
4344 : : * Flag a rw-dependency between two serializable transactions.
4345 : : *
4346 : : * The caller is responsible for ensuring that we have a LW lock on
4347 : : * the transaction hash table.
4348 : : */
4349 : : static void
5750 heikki.linnakangas@i 4350 : 898 : FlagRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
4351 : : {
4352 [ - + ]: 898 : Assert(reader != writer);
4353 : :
4354 : : /* First, see if this conflict causes failure. */
4355 : 898 : OnConflict_CheckForSerializationFailure(reader, writer);
4356 : :
4357 : : /* Actually do the conflict flagging. */
4358 [ - + ]: 812 : if (reader == OldCommittedSxact)
5750 heikki.linnakangas@i 4359 :UBC 0 : writer->flags |= SXACT_FLAG_SUMMARY_CONFLICT_IN;
5750 heikki.linnakangas@i 4360 [ - + ]:CBC 812 : else if (writer == OldCommittedSxact)
5750 heikki.linnakangas@i 4361 :UBC 0 : reader->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
4362 : : else
5750 heikki.linnakangas@i 4363 :CBC 812 : SetRWConflict(reader, writer);
4364 : 812 : }
4365 : :
4366 : : /*----------------------------------------------------------------------------
4367 : : * We are about to add a RW-edge to the dependency graph - check that we don't
4368 : : * introduce a dangerous structure by doing so, and abort one of the
4369 : : * transactions if so.
4370 : : *
4371 : : * A serialization failure can only occur if there is a dangerous structure
4372 : : * in the dependency graph:
4373 : : *
4374 : : * Tin ------> Tpivot ------> Tout
4375 : : * rw rw
4376 : : *
4377 : : * Furthermore, Tout must commit first.
4378 : : *
4379 : : * One more optimization is that if Tin is declared READ ONLY (or commits
4380 : : * without writing), we can only have a problem if Tout committed before Tin
4381 : : * acquired its snapshot.
4382 : : *----------------------------------------------------------------------------
4383 : : */
4384 : : static void
5615 tgl@sss.pgh.pa.us 4385 : 898 : OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader,
4386 : : SERIALIZABLEXACT *writer)
4387 : : {
4388 : : bool failure;
4389 : :
5750 heikki.linnakangas@i 4390 [ - + ]: 898 : Assert(LWLockHeldByMe(SerializableXactHashLock));
4391 : :
4392 : 898 : failure = false;
4393 : :
4394 : : /*------------------------------------------------------------------------
4395 : : * Check for already-committed writer with rw-conflict out flagged
4396 : : * (conflict-flag on W means that T2 committed before W):
4397 : : *
4398 : : * R ------> W ------> T2
4399 : : * rw rw
4400 : : *
4401 : : * That is a dangerous structure, so we must abort. (Since the writer
4402 : : * has already committed, we must be the reader)
4403 : : *------------------------------------------------------------------------
4404 : : */
4405 [ + + ]: 898 : if (SxactIsCommitted(writer)
3424 tgl@sss.pgh.pa.us 4406 [ + + - + ]: 26 : && (SxactHasConflictOut(writer) || SxactHasSummaryConflictOut(writer)))
5750 heikki.linnakangas@i 4407 : 2 : failure = true;
4408 : :
4409 : : /*------------------------------------------------------------------------
4410 : : * Check whether the writer has become a pivot with an out-conflict
4411 : : * committed transaction (T2), and T2 committed first:
4412 : : *
4413 : : * R ------> W ------> T2
4414 : : * rw rw
4415 : : *
4416 : : * Because T2 must've committed first, there is no anomaly if:
4417 : : * - the reader committed before T2
4418 : : * - the writer committed before T2
4419 : : * - the reader is a READ ONLY transaction and the reader was concurrent
4420 : : * with T2 (= reader acquired its snapshot before T2 committed)
4421 : : *
4422 : : * We also handle the case that T2 is prepared but not yet committed
4423 : : * here. In that case T2 has already checked for conflicts, so if it
4424 : : * commits first, making the above conflict real, it's too late for it
4425 : : * to abort.
4426 : : *------------------------------------------------------------------------
4427 : : */
1386 andres@anarazel.de 4428 [ + + - + ]: 898 : if (!failure && SxactHasSummaryConflictOut(writer))
1386 andres@anarazel.de 4429 :UBC 0 : failure = true;
1386 andres@anarazel.de 4430 [ + + ]:CBC 898 : else if (!failure)
4431 : : {
4432 : : dlist_iter iter;
4433 : :
4434 [ + - + + ]: 1118 : dlist_foreach(iter, &writer->outConflicts)
4435 : : {
4436 : 303 : RWConflict conflict =
4437 : : dlist_container(RWConflictData, outLink, iter.cur);
5638 heikki.linnakangas@i 4438 : 303 : SERIALIZABLEXACT *t2 = conflict->sxactIn;
4439 : :
5600 4440 [ + + ]: 303 : if (SxactIsPrepared(t2)
5638 4441 [ + + ]: 87 : && (!SxactIsCommitted(reader)
5600 4442 [ + - ]: 70 : || t2->prepareSeqNo <= reader->commitSeqNo)
5638 4443 [ - + ]: 87 : && (!SxactIsCommitted(writer)
5600 heikki.linnakangas@i 4444 [ # # ]:UBC 0 : || t2->prepareSeqNo <= writer->commitSeqNo)
5638 heikki.linnakangas@i 4445 [ + + ]:CBC 87 : && (!SxactIsReadOnly(reader)
3424 tgl@sss.pgh.pa.us 4446 [ + + ]: 12 : || t2->prepareSeqNo <= reader->SeqNo.lastCommitBeforeSnapshot))
4447 : : {
5750 heikki.linnakangas@i 4448 : 81 : failure = true;
4449 : 81 : break;
4450 : : }
4451 : : }
4452 : : }
4453 : :
4454 : : /*------------------------------------------------------------------------
4455 : : * Check whether the reader has become a pivot with a writer
4456 : : * that's committed (or prepared):
4457 : : *
4458 : : * T0 ------> R ------> W
4459 : : * rw rw
4460 : : *
4461 : : * Because W must've committed first for an anomaly to occur, there is no
4462 : : * anomaly if:
4463 : : * - T0 committed before the writer
4464 : : * - T0 is READ ONLY, and overlaps the writer
4465 : : *------------------------------------------------------------------------
4466 : : */
5600 4467 [ + + + + : 898 : if (!failure && SxactIsPrepared(writer) && !SxactIsReadOnly(reader))
+ - ]
4468 : : {
5638 4469 [ - + ]: 26 : if (SxactHasSummaryConflictIn(reader))
4470 : : {
5750 heikki.linnakangas@i 4471 :UBC 0 : failure = true;
4472 : : }
4473 : : else
4474 : : {
4475 : : dlist_iter iter;
4476 : :
4477 : : /*
4478 : : * The unconstify is needed as we have no const version of
4479 : : * dlist_foreach().
4480 : : */
1386 andres@anarazel.de 4481 [ + - + + ]:CBC 26 : dlist_foreach(iter, &unconstify(SERIALIZABLEXACT *, reader)->inConflicts)
4482 : : {
4483 : 11 : const RWConflict conflict =
1266 tgl@sss.pgh.pa.us 4484 : 11 : dlist_container(RWConflictData, inLink, iter.cur);
1386 andres@anarazel.de 4485 : 11 : const SERIALIZABLEXACT *t0 = conflict->sxactOut;
4486 : :
4487 [ + - ]: 11 : if (!SxactIsDoomed(t0)
4488 [ + - ]: 11 : && (!SxactIsCommitted(t0)
4489 [ + - ]: 11 : || t0->commitSeqNo >= writer->prepareSeqNo)
4490 [ - + ]: 11 : && (!SxactIsReadOnly(t0)
1386 andres@anarazel.de 4491 [ # # ]:UBC 0 : || t0->SeqNo.lastCommitBeforeSnapshot >= writer->prepareSeqNo))
4492 : : {
1386 andres@anarazel.de 4493 :CBC 11 : failure = true;
4494 : 11 : break;
4495 : : }
4496 : : }
4497 : : }
4498 : : }
4499 : :
5750 heikki.linnakangas@i 4500 [ + + ]: 898 : if (failure)
4501 : : {
4502 : : /*
4503 : : * We have to kill a transaction to avoid a possible anomaly from
4504 : : * occurring. If the writer is us, we can just ereport() to cause a
4505 : : * transaction abort. Otherwise we flag the writer for termination,
4506 : : * causing it to abort when it tries to commit. However, if the writer
4507 : : * is a prepared transaction, already prepared, we can't abort it
4508 : : * anymore, so we have to kill the reader instead.
4509 : : */
4510 [ + + ]: 94 : if (MySerializableXact == writer)
4511 : : {
4512 : 73 : LWLockRelease(SerializableXactHashLock);
4513 [ + - ]: 73 : ereport(ERROR,
4514 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
4515 : : errmsg("could not serialize access due to read/write dependencies among transactions"),
4516 : : errdetail_internal("Reason code: Canceled on identification as a pivot, during write."),
4517 : : errhint("The transaction might succeed if retried.")));
4518 : : }
4519 [ + + ]: 21 : else if (SxactIsPrepared(writer))
4520 : : {
4521 : 13 : LWLockRelease(SerializableXactHashLock);
4522 : :
4523 : : /* if we're not the writer, we have to be the reader */
5638 4524 [ - + ]: 13 : Assert(MySerializableXact == reader);
5750 4525 [ + - ]: 13 : ereport(ERROR,
4526 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
4527 : : errmsg("could not serialize access due to read/write dependencies among transactions"),
4528 : : errdetail_internal("Reason code: Canceled on conflict out to pivot %u, during read.", writer->topXid),
4529 : : errhint("The transaction might succeed if retried.")));
4530 : : }
5622 4531 : 8 : writer->flags |= SXACT_FLAG_DOOMED;
4532 : : }
5750 4533 : 812 : }
4534 : :
4535 : : /*
4536 : : * PreCommit_CheckForSerializationFailure
4537 : : * Check for dangerous structures in a serializable transaction
4538 : : * at commit.
4539 : : *
4540 : : * We're checking for a dangerous structure as each conflict is recorded.
4541 : : * The only way we could have a problem at commit is if this is the "out"
4542 : : * side of a pivot, and neither the "in" side nor the pivot has yet
4543 : : * committed.
4544 : : *
4545 : : * If a dangerous structure is found, the pivot (the near conflict) is
4546 : : * marked for death, because rolling back another transaction might mean
4547 : : * that we fail without ever making progress. This transaction is
4548 : : * committing writes, so letting it commit ensures progress. If we
4549 : : * canceled the far conflict, it might immediately fail again on retry.
4550 : : */
4551 : : void
4552 : 392477 : PreCommit_CheckForSerializationFailure(void)
4553 : : {
4554 : : dlist_iter near_iter;
4555 : :
4556 [ + + ]: 392477 : if (MySerializableXact == InvalidSerializableXact)
4557 : 391063 : return;
4558 : :
4559 [ - + ]: 1414 : Assert(IsolationIsSerializable());
4560 : :
4561 : 1414 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
4562 : :
4563 : : /*
4564 : : * Check if someone else has already decided that we need to die. Since
4565 : : * we set our own DOOMED flag when partially releasing, ignore in that
4566 : : * case.
4567 : : */
1340 tmunro@postgresql.or 4568 [ + + ]: 1414 : if (SxactIsDoomed(MySerializableXact) &&
4569 [ + + ]: 161 : !SxactIsPartiallyReleased(MySerializableXact))
4570 : : {
5750 heikki.linnakangas@i 4571 : 160 : LWLockRelease(SerializableXactHashLock);
4572 [ + - ]: 160 : ereport(ERROR,
4573 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
4574 : : errmsg("could not serialize access due to read/write dependencies among transactions"),
4575 : : errdetail_internal("Reason code: Canceled on identification as a pivot, during commit attempt."),
4576 : : errhint("The transaction might succeed if retried.")));
4577 : : }
4578 : :
1386 andres@anarazel.de 4579 [ + - + + ]: 1867 : dlist_foreach(near_iter, &MySerializableXact->inConflicts)
4580 : : {
4581 : 613 : RWConflict nearConflict =
1266 tgl@sss.pgh.pa.us 4582 : 613 : dlist_container(RWConflictData, inLink, near_iter.cur);
4583 : :
5750 heikki.linnakangas@i 4584 [ + + ]: 613 : if (!SxactIsCommitted(nearConflict->sxactOut)
5622 4585 [ + - ]: 428 : && !SxactIsDoomed(nearConflict->sxactOut))
4586 : : {
4587 : : dlist_iter far_iter;
4588 : :
1386 andres@anarazel.de 4589 [ + - + + ]: 458 : dlist_foreach(far_iter, &nearConflict->sxactOut->inConflicts)
4590 : : {
4591 : 187 : RWConflict farConflict =
1266 tgl@sss.pgh.pa.us 4592 : 187 : dlist_container(RWConflictData, inLink, far_iter.cur);
4593 : :
5750 heikki.linnakangas@i 4594 [ + + ]: 187 : if (farConflict->sxactOut == MySerializableXact
4595 [ + + ]: 42 : || (!SxactIsCommitted(farConflict->sxactOut)
4596 [ + + ]: 24 : && !SxactIsReadOnly(farConflict->sxactOut)
5622 4597 [ + - ]: 12 : && !SxactIsDoomed(farConflict->sxactOut)))
4598 : : {
4599 : : /*
4600 : : * Normally, we kill the pivot transaction to make sure we
4601 : : * make progress if the failing transaction is retried.
4602 : : * However, we can't kill it if it's already prepared, so
4603 : : * in that case we commit suicide instead.
4604 : : */
5616 4605 [ - + ]: 157 : if (SxactIsPrepared(nearConflict->sxactOut))
4606 : : {
5616 heikki.linnakangas@i 4607 :UBC 0 : LWLockRelease(SerializableXactHashLock);
4608 [ # # ]: 0 : ereport(ERROR,
4609 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
4610 : : errmsg("could not serialize access due to read/write dependencies among transactions"),
4611 : : errdetail_internal("Reason code: Canceled on commit attempt with conflict in from prepared pivot."),
4612 : : errhint("The transaction might succeed if retried.")));
4613 : : }
5622 heikki.linnakangas@i 4614 :CBC 157 : nearConflict->sxactOut->flags |= SXACT_FLAG_DOOMED;
5750 4615 : 157 : break;
4616 : : }
4617 : : }
4618 : : }
4619 : : }
4620 : :
5600 4621 : 1254 : MySerializableXact->prepareSeqNo = ++(PredXact->LastSxactCommitSeqNo);
5750 4622 : 1254 : MySerializableXact->flags |= SXACT_FLAG_PREPARED;
4623 : :
4624 : 1254 : LWLockRelease(SerializableXactHashLock);
4625 : : }
4626 : :
4627 : : /*------------------------------------------------------------------------*/
4628 : :
4629 : : /*
4630 : : * Two-phase commit support
4631 : : */
4632 : :
4633 : : /*
4634 : : * AtPrepare_PredicateLocks
4635 : : * Do the preparatory work for a PREPARE: make 2PC state file
4636 : : * records for all predicate locks currently held.
4637 : : */
4638 : : void
4639 : 308 : AtPrepare_PredicateLocks(void)
4640 : : {
4641 : : SERIALIZABLEXACT *sxact;
4642 : : TwoPhasePredicateRecord record;
4643 : : TwoPhasePredicateXactRecord *xactRecord;
4644 : : TwoPhasePredicateLockRecord *lockRecord;
4645 : : dlist_iter iter;
4646 : :
5627 4647 : 308 : sxact = MySerializableXact;
5750 4648 : 308 : xactRecord = &(record.data.xactRecord);
4649 : 308 : lockRecord = &(record.data.lockRecord);
4650 : :
4651 [ + + ]: 308 : if (MySerializableXact == InvalidSerializableXact)
4652 : 295 : return;
4653 : :
4654 : : /* Generate an xact record for our SERIALIZABLEXACT */
4655 : 13 : record.type = TWOPHASEPREDICATERECORD_XACT;
4656 : 13 : xactRecord->xmin = MySerializableXact->xmin;
4657 : 13 : xactRecord->flags = MySerializableXact->flags;
4658 : :
4659 : : /*
4660 : : * Note that we don't include the list of conflicts in our out in the
4661 : : * statefile, because new conflicts can be added even after the
4662 : : * transaction prepares. We'll just make a conservative assumption during
4663 : : * recovery instead.
4664 : : */
4665 : :
4666 : 13 : RegisterTwoPhaseRecord(TWOPHASE_RM_PREDICATELOCK_ID, 0,
4667 : : &record, sizeof(record));
4668 : :
4669 : : /*
4670 : : * Generate a lock record for each lock.
4671 : : *
4672 : : * To do this, we need to walk the predicate lock list in our sxact rather
4673 : : * than using the local predicate lock table because the latter is not
4674 : : * guaranteed to be accurate.
4675 : : */
2365 tgl@sss.pgh.pa.us 4676 : 13 : LWLockAcquire(SerializablePredicateListLock, LW_SHARED);
4677 : :
4678 : : /*
4679 : : * No need to take sxact->perXactPredicateListLock in parallel mode
4680 : : * because there cannot be any parallel workers running while we are
4681 : : * preparing a transaction.
4682 : : */
2792 tmunro@postgresql.or 4683 [ + - - + ]: 13 : Assert(!IsParallelWorker() && !ParallelContextActive());
4684 : :
1386 andres@anarazel.de 4685 [ + - + + ]: 23 : dlist_foreach(iter, &sxact->predicateLocks)
4686 : : {
4687 : 10 : PREDICATELOCK *predlock =
1266 tgl@sss.pgh.pa.us 4688 : 10 : dlist_container(PREDICATELOCK, xactLink, iter.cur);
4689 : :
5750 heikki.linnakangas@i 4690 : 10 : record.type = TWOPHASEPREDICATERECORD_LOCK;
4691 : 10 : lockRecord->target = predlock->tag.myTarget->tag;
4692 : :
4693 : 10 : RegisterTwoPhaseRecord(TWOPHASE_RM_PREDICATELOCK_ID, 0,
4694 : : &record, sizeof(record));
4695 : : }
4696 : :
2365 tgl@sss.pgh.pa.us 4697 : 13 : LWLockRelease(SerializablePredicateListLock);
4698 : : }
4699 : :
4700 : : /*
4701 : : * PostPrepare_PredicateLocks
4702 : : * Clean up after successful PREPARE. Unlike the non-predicate
4703 : : * lock manager, we do not need to transfer locks to a dummy
4704 : : * PGPROC because our SERIALIZABLEXACT will stay around
4705 : : * anyway. We only need to clean up our local state.
4706 : : */
4707 : : void
486 michael@paquier.xyz 4708 : 308 : PostPrepare_PredicateLocks(FullTransactionId fxid)
4709 : : {
5750 heikki.linnakangas@i 4710 [ + + ]: 308 : if (MySerializableXact == InvalidSerializableXact)
4711 : 295 : return;
4712 : :
4713 [ - + ]: 13 : Assert(SxactIsPrepared(MySerializableXact));
4714 : :
4715 : 13 : MySerializableXact->pid = 0;
977 4716 : 13 : MySerializableXact->pgprocno = INVALID_PROC_NUMBER;
4717 : :
5750 4718 : 13 : hash_destroy(LocalPredicateLockHash);
4719 : 13 : LocalPredicateLockHash = NULL;
4720 : :
4721 : 13 : MySerializableXact = InvalidSerializableXact;
5627 4722 : 13 : MyXactDidWrite = false;
4723 : : }
4724 : :
4725 : : /*
4726 : : * PredicateLockTwoPhaseFinish
4727 : : * Release a prepared transaction's predicate locks once it
4728 : : * commits or aborts.
4729 : : */
4730 : : void
486 michael@paquier.xyz 4731 : 315 : PredicateLockTwoPhaseFinish(FullTransactionId fxid, bool isCommit)
4732 : : {
4733 : : SERIALIZABLEXID *sxid;
4734 : : SERIALIZABLEXIDTAG sxidtag;
4735 : :
4736 : 315 : sxidtag.xid = XidFromFullTransactionId(fxid);
4737 : :
5750 heikki.linnakangas@i 4738 : 315 : LWLockAcquire(SerializableXactHashLock, LW_SHARED);
4739 : : sxid = (SERIALIZABLEXID *)
4740 : 315 : hash_search(SerializableXidHash, &sxidtag, HASH_FIND, NULL);
4741 : 315 : LWLockRelease(SerializableXactHashLock);
4742 : :
4743 : : /* xid will not be found if it wasn't a serializable transaction */
4744 [ + + ]: 315 : if (sxid == NULL)
4745 : 302 : return;
4746 : :
4747 : : /* Release its locks */
4748 : 13 : MySerializableXact = sxid->myXact;
5627 4749 : 13 : MyXactDidWrite = true; /* conservatively assume that we wrote
4750 : : * something */
2792 tmunro@postgresql.or 4751 : 13 : ReleasePredicateLocks(isCommit, false);
4752 : : }
4753 : :
4754 : : /*
4755 : : * Re-acquire a predicate lock belonging to a transaction that was prepared.
4756 : : */
4757 : : void
486 michael@paquier.xyz 4758 :UBC 0 : predicatelock_twophase_recover(FullTransactionId fxid, uint16 info,
4759 : : void *recdata, uint32 len)
4760 : : {
4761 : : TwoPhasePredicateRecord *record;
4762 : 0 : TransactionId xid = XidFromFullTransactionId(fxid);
4763 : :
5750 heikki.linnakangas@i 4764 [ # # ]: 0 : Assert(len == sizeof(TwoPhasePredicateRecord));
4765 : :
4766 : 0 : record = (TwoPhasePredicateRecord *) recdata;
4767 : :
4768 [ # # # # ]: 0 : Assert((record->type == TWOPHASEPREDICATERECORD_XACT) ||
4769 : : (record->type == TWOPHASEPREDICATERECORD_LOCK));
4770 : :
4771 [ # # ]: 0 : if (record->type == TWOPHASEPREDICATERECORD_XACT)
4772 : : {
4773 : : /* Per-transaction record. Set up a SERIALIZABLEXACT. */
4774 : : TwoPhasePredicateXactRecord *xactRecord;
4775 : : SERIALIZABLEXACT *sxact;
4776 : : SERIALIZABLEXID *sxid;
4777 : : SERIALIZABLEXIDTAG sxidtag;
4778 : : bool found;
4779 : :
4780 : 0 : xactRecord = (TwoPhasePredicateXactRecord *) &record->data.xactRecord;
4781 : :
4782 : 0 : LWLockAcquire(SerializableXactHashLock, LW_EXCLUSIVE);
4783 : 0 : sxact = CreatePredXact();
4784 [ # # ]: 0 : if (!sxact)
4785 [ # # ]: 0 : ereport(ERROR,
4786 : : (errcode(ERRCODE_OUT_OF_MEMORY),
4787 : : errmsg("out of shared memory")));
4788 : :
4789 : : /* vxid for a prepared xact is INVALID_PROC_NUMBER/xid; no pid */
977 4790 : 0 : sxact->vxid.procNumber = INVALID_PROC_NUMBER;
5750 4791 : 0 : sxact->vxid.localTransactionId = (LocalTransactionId) xid;
4792 : 0 : sxact->pid = 0;
977 4793 : 0 : sxact->pgprocno = INVALID_PROC_NUMBER;
4794 : :
4795 : : /* a prepared xact hasn't committed yet */
5600 4796 : 0 : sxact->prepareSeqNo = RecoverySerCommitSeqNo;
5750 4797 : 0 : sxact->commitSeqNo = InvalidSerCommitSeqNo;
4798 : 0 : sxact->finishedBefore = InvalidTransactionId;
4799 : :
4800 : 0 : sxact->SeqNo.lastCommitBeforeSnapshot = RecoverySerCommitSeqNo;
4801 : :
4802 : : /*
4803 : : * Don't need to track this; no transactions running at the time the
4804 : : * recovered xact started are still active, except possibly other
4805 : : * prepared xacts and we don't care whether those are RO_SAFE or not.
4806 : : */
1386 andres@anarazel.de 4807 : 0 : dlist_init(&(sxact->possibleUnsafeConflicts));
4808 : :
4809 : 0 : dlist_init(&(sxact->predicateLocks));
4810 : 0 : dlist_node_init(&sxact->finishedLink);
4811 : :
5750 heikki.linnakangas@i 4812 : 0 : sxact->topXid = xid;
4813 : 0 : sxact->xmin = xactRecord->xmin;
4814 : 0 : sxact->flags = xactRecord->flags;
4815 [ # # ]: 0 : Assert(SxactIsPrepared(sxact));
4816 [ # # ]: 0 : if (!SxactIsReadOnly(sxact))
4817 : : {
4818 : 0 : ++(PredXact->WritableSxactCount);
4819 [ # # ]: 0 : Assert(PredXact->WritableSxactCount <=
4820 : : (MaxBackends + max_prepared_xacts));
4821 : : }
4822 : :
4823 : : /*
4824 : : * We don't know whether the transaction had any conflicts or not, so
4825 : : * we'll conservatively assume that it had both a conflict in and a
4826 : : * conflict out, and represent that with the summary conflict flags.
4827 : : */
1386 andres@anarazel.de 4828 : 0 : dlist_init(&(sxact->outConflicts));
4829 : 0 : dlist_init(&(sxact->inConflicts));
5363 heikki.linnakangas@i 4830 : 0 : sxact->flags |= SXACT_FLAG_SUMMARY_CONFLICT_IN;
4831 : 0 : sxact->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
4832 : :
4833 : : /* Register the transaction's xid */
5750 4834 : 0 : sxidtag.xid = xid;
4835 : 0 : sxid = (SERIALIZABLEXID *) hash_search(SerializableXidHash,
4836 : : &sxidtag,
4837 : : HASH_ENTER, &found);
5691 rhaas@postgresql.org 4838 [ # # ]: 0 : Assert(sxid != NULL);
5750 heikki.linnakangas@i 4839 [ # # ]: 0 : Assert(!found);
338 peter@eisentraut.org 4840 : 0 : sxid->myXact = sxact;
4841 : :
4842 : : /*
4843 : : * Update global xmin. Note that this is a special case compared to
4844 : : * registering a normal transaction, because the global xmin might go
4845 : : * backwards. That's OK, because until recovery is over we're not
4846 : : * going to complete any transactions or create any non-prepared
4847 : : * transactions, so there's no danger of throwing away.
4848 : : */
5750 heikki.linnakangas@i 4849 [ # # # # ]: 0 : if ((!TransactionIdIsValid(PredXact->SxactGlobalXmin)) ||
4850 : 0 : (TransactionIdFollows(PredXact->SxactGlobalXmin, sxact->xmin)))
4851 : : {
4852 : 0 : PredXact->SxactGlobalXmin = sxact->xmin;
4853 : 0 : PredXact->SxactGlobalXminCount = 1;
2365 tgl@sss.pgh.pa.us 4854 : 0 : SerialSetActiveSerXmin(sxact->xmin);
4855 : : }
5750 heikki.linnakangas@i 4856 [ # # ]: 0 : else if (TransactionIdEquals(sxact->xmin, PredXact->SxactGlobalXmin))
4857 : : {
4858 [ # # ]: 0 : Assert(PredXact->SxactGlobalXminCount > 0);
4859 : 0 : PredXact->SxactGlobalXminCount++;
4860 : : }
4861 : :
4862 : 0 : LWLockRelease(SerializableXactHashLock);
4863 : : }
4864 [ # # ]: 0 : else if (record->type == TWOPHASEPREDICATERECORD_LOCK)
4865 : : {
4866 : : /* Lock record. Recreate the PREDICATELOCK */
4867 : : TwoPhasePredicateLockRecord *lockRecord;
4868 : : SERIALIZABLEXID *sxid;
4869 : : SERIALIZABLEXACT *sxact;
4870 : : SERIALIZABLEXIDTAG sxidtag;
4871 : : uint32 targettaghash;
4872 : :
4873 : 0 : lockRecord = (TwoPhasePredicateLockRecord *) &record->data.lockRecord;
4874 : 0 : targettaghash = PredicateLockTargetTagHashCode(&lockRecord->target);
4875 : :
4876 : 0 : LWLockAcquire(SerializableXactHashLock, LW_SHARED);
4877 : 0 : sxidtag.xid = xid;
4878 : : sxid = (SERIALIZABLEXID *)
4879 : 0 : hash_search(SerializableXidHash, &sxidtag, HASH_FIND, NULL);
4880 : 0 : LWLockRelease(SerializableXactHashLock);
4881 : :
4882 [ # # ]: 0 : Assert(sxid != NULL);
4883 : 0 : sxact = sxid->myXact;
4884 [ # # ]: 0 : Assert(sxact != InvalidSerializableXact);
4885 : :
4886 : 0 : CreatePredicateLock(&lockRecord->target, targettaghash, sxact);
4887 : : }
4888 : 0 : }
4889 : :
4890 : : /*
4891 : : * Prepare to share the current SERIALIZABLEXACT with parallel workers.
4892 : : * Return a handle object that can be used by AttachSerializableXact() in a
4893 : : * parallel worker.
4894 : : */
4895 : : SerializableXactHandle
2792 tmunro@postgresql.or 4896 :CBC 674 : ShareSerializableXact(void)
4897 : : {
4898 : 674 : return MySerializableXact;
4899 : : }
4900 : :
4901 : : /*
4902 : : * Allow parallel workers to import the leader's SERIALIZABLEXACT.
4903 : : */
4904 : : void
4905 : 2043 : AttachSerializableXact(SerializableXactHandle handle)
4906 : : {
4907 : :
4908 [ - + ]: 2043 : Assert(MySerializableXact == InvalidSerializableXact);
4909 : :
4910 : 2043 : MySerializableXact = (SERIALIZABLEXACT *) handle;
4911 [ + + ]: 2043 : if (MySerializableXact != InvalidSerializableXact)
4912 : 13 : CreateLocalPredicateLockHash();
4913 : 2043 : }
|