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