PostgreSQL Source Code git master
Loading...
Searching...
No Matches
predicate.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * predicate.c
4 * POSTGRES predicate locking
5 * to support full serializable transaction isolation
6 *
7 *
8 * The approach taken is to implement Serializable Snapshot Isolation (SSI)
9 * as initially described in this paper:
10 *
11 * Michael J. Cahill, Uwe Röhm, and Alan D. Fekete. 2008.
12 * Serializable isolation for snapshot databases.
13 * In SIGMOD '08: Proceedings of the 2008 ACM SIGMOD
14 * international conference on Management of data,
15 * pages 729-738, New York, NY, USA. ACM.
16 * http://doi.acm.org/10.1145/1376616.1376690
17 *
18 * and further elaborated in Cahill's doctoral thesis:
19 *
20 * Michael James Cahill. 2009.
21 * Serializable Isolation for Snapshot Databases.
22 * Sydney Digital Theses.
23 * University of Sydney, School of Information Technologies.
24 * http://hdl.handle.net/2123/5353
25 *
26 *
27 * Predicate locks for Serializable Snapshot Isolation (SSI) are SIREAD
28 * locks, which are so different from normal locks that a distinct set of
29 * structures is required to handle them. They are needed to detect
30 * rw-conflicts when the read happens before the write. (When the write
31 * occurs first, the reading transaction can check for a conflict by
32 * examining the MVCC data.)
33 *
34 * (1) Besides tuples actually read, they must cover ranges of tuples
35 * which would have been read based on the predicate. This will
36 * require modelling the predicates through locks against database
37 * objects such as pages, index ranges, or entire tables.
38 *
39 * (2) They must be kept in RAM for quick access. Because of this, it
40 * isn't possible to always maintain tuple-level granularity -- when
41 * the space allocated to store these approaches exhaustion, a
42 * request for a lock may need to scan for situations where a single
43 * transaction holds many fine-grained locks which can be coalesced
44 * into a single coarser-grained lock.
45 *
46 * (3) They never block anything; they are more like flags than locks
47 * in that regard; although they refer to database objects and are
48 * used to identify rw-conflicts with normal write locks.
49 *
50 * (4) While they are associated with a transaction, they must survive
51 * a successful COMMIT of that transaction, and remain until all
52 * overlapping transactions complete. This even means that they
53 * must survive termination of the transaction's process. If a
54 * top level transaction is rolled back, however, it is immediately
55 * flagged so that it can be ignored, and its SIREAD locks can be
56 * released any time after that.
57 *
58 * (5) The only transactions which create SIREAD locks or check for
59 * conflicts with them are serializable transactions.
60 *
61 * (6) When a write lock for a top level transaction is found to cover
62 * an existing SIREAD lock for the same transaction, the SIREAD lock
63 * can be deleted.
64 *
65 * (7) A write from a serializable transaction must ensure that an xact
66 * record exists for the transaction, with the same lifespan (until
67 * all concurrent transaction complete or the transaction is rolled
68 * back) so that rw-dependencies to that transaction can be
69 * detected.
70 *
71 * We use an optimization for read-only transactions. Under certain
72 * circumstances, a read-only transaction's snapshot can be shown to
73 * never have conflicts with other transactions. This is referred to
74 * as a "safe" snapshot (and one known not to be is "unsafe").
75 * However, it can't be determined whether a snapshot is safe until
76 * all concurrent read/write transactions complete.
77 *
78 * Once a read-only transaction is known to have a safe snapshot, it
79 * can release its predicate locks and exempt itself from further
80 * predicate lock tracking. READ ONLY DEFERRABLE transactions run only
81 * on safe snapshots, waiting as necessary for one to be available.
82 *
83 *
84 * Lightweight locks to manage access to the predicate locking shared
85 * memory objects must be taken in this order, and should be released in
86 * reverse order:
87 *
88 * SerializableFinishedListLock
89 * - Protects the list of transactions which have completed but which
90 * may yet matter because they overlap still-active transactions.
91 *
92 * SerializablePredicateListLock
93 * - Protects the linked list of locks held by a transaction. Note
94 * that the locks themselves are also covered by the partition
95 * locks of their respective lock targets; this lock only affects
96 * the linked list connecting the locks related to a transaction.
97 * - All transactions share this single lock (with no partitioning).
98 * - There is never a need for a process other than the one running
99 * an active transaction to walk the list of locks held by that
100 * transaction, except parallel query workers sharing the leader's
101 * transaction. In the parallel case, an extra per-sxact lock is
102 * taken; see below.
103 * - It is relatively infrequent that another process needs to
104 * modify the list for a transaction, but it does happen for such
105 * things as index page splits for pages with predicate locks and
106 * freeing of predicate locked pages by a vacuum process. When
107 * removing a lock in such cases, the lock itself contains the
108 * pointers needed to remove it from the list. When adding a
109 * lock in such cases, the lock can be added using the anchor in
110 * the transaction structure. Neither requires walking the list.
111 * - Cleaning up the list for a terminated transaction is sometimes
112 * not done on a retail basis, in which case no lock is required.
113 * - Due to the above, a process accessing its active transaction's
114 * list always uses a shared lock, regardless of whether it is
115 * walking or maintaining the list. This improves concurrency
116 * for the common access patterns.
117 * - A process which needs to alter the list of a transaction other
118 * than its own active transaction must acquire an exclusive
119 * lock.
120 *
121 * SERIALIZABLEXACT's member 'perXactPredicateListLock'
122 * - Protects the linked list of predicate locks held by a transaction.
123 * Only needed for parallel mode, where multiple backends share the
124 * same SERIALIZABLEXACT object. Not needed if
125 * SerializablePredicateListLock is held exclusively.
126 *
127 * PredicateLockHashPartitionLock(hashcode)
128 * - The same lock protects a target, all locks on that target, and
129 * the linked list of locks on the target.
130 * - When more than one is needed, acquire in ascending address order.
131 * - When all are needed (rare), acquire in ascending index order with
132 * PredicateLockHashPartitionLockByIndex(index).
133 *
134 * SerializableXactHashLock
135 * - Protects both PredXact and SerializableXidHash.
136 *
137 * SerialControlLock
138 * - Protects SerialControlData members
139 *
140 * SLRU per-bank locks
141 * - Protects SerialSlruCtl
142 *
143 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
144 * Portions Copyright (c) 1994, Regents of the University of California
145 *
146 *
147 * IDENTIFICATION
148 * src/backend/storage/lmgr/predicate.c
149 *
150 *-------------------------------------------------------------------------
151 */
152/*
153 * 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, const ItemPointerData *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, const ItemPointerData *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(FullTransactionId fxid, 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"
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#include "utils/wait_event.h"
218
219/* Uncomment the next line to test the graceful degradation code. */
220/* #define TEST_SUMMARIZE_SERIAL */
221
222/*
223 * Test the most selective fields first, for performance.
224 *
225 * a is covered by b if all of the following hold:
226 * 1) a.database = b.database
227 * 2) a.relation = b.relation
228 * 3) b.offset is invalid (b is page-granularity or higher)
229 * 4) either of the following:
230 * 4a) a.offset is valid (a is tuple-granularity) and a.page = b.page
231 * or 4b) a.offset is invalid and b.page is invalid (a is
232 * page-granularity and b is relation-granularity
233 */
234#define TargetTagIsCoveredBy(covered_target, covering_target) \
235 ((GET_PREDICATELOCKTARGETTAG_RELATION(covered_target) == /* (2) */ \
236 GET_PREDICATELOCKTARGETTAG_RELATION(covering_target)) \
237 && (GET_PREDICATELOCKTARGETTAG_OFFSET(covering_target) == \
238 InvalidOffsetNumber) /* (3) */ \
239 && (((GET_PREDICATELOCKTARGETTAG_OFFSET(covered_target) != \
240 InvalidOffsetNumber) /* (4a) */ \
241 && (GET_PREDICATELOCKTARGETTAG_PAGE(covering_target) == \
242 GET_PREDICATELOCKTARGETTAG_PAGE(covered_target))) \
243 || ((GET_PREDICATELOCKTARGETTAG_PAGE(covering_target) == \
244 InvalidBlockNumber) /* (4b) */ \
245 && (GET_PREDICATELOCKTARGETTAG_PAGE(covered_target) \
246 != InvalidBlockNumber))) \
247 && (GET_PREDICATELOCKTARGETTAG_DB(covered_target) == /* (1) */ \
248 GET_PREDICATELOCKTARGETTAG_DB(covering_target)))
249
250/*
251 * The predicate locking target and lock shared hash tables are partitioned to
252 * reduce contention. To determine which partition a given target belongs to,
253 * compute the tag's hash code with PredicateLockTargetTagHashCode(), then
254 * apply one of these macros.
255 * NB: NUM_PREDICATELOCK_PARTITIONS must be a power of 2!
256 */
257#define PredicateLockHashPartition(hashcode) \
258 ((hashcode) % NUM_PREDICATELOCK_PARTITIONS)
259#define PredicateLockHashPartitionLock(hashcode) \
260 (&MainLWLockArray[PREDICATELOCK_MANAGER_LWLOCK_OFFSET + \
261 PredicateLockHashPartition(hashcode)].lock)
262#define PredicateLockHashPartitionLockByIndex(i) \
263 (&MainLWLockArray[PREDICATELOCK_MANAGER_LWLOCK_OFFSET + (i)].lock)
264
265#define NPREDICATELOCKTARGETENTS() \
266 mul_size(max_predicate_locks_per_xact, add_size(MaxBackends, max_prepared_xacts))
267
268#define SxactIsOnFinishedList(sxact) (!dlist_node_is_detached(&(sxact)->finishedLink))
269
270/*
271 * Note that a sxact is marked "prepared" once it has passed
272 * PreCommit_CheckForSerializationFailure, even if it isn't using
273 * 2PC. This is the point at which it can no longer be aborted.
274 *
275 * The PREPARED flag remains set after commit, so SxactIsCommitted
276 * implies SxactIsPrepared.
277 */
278#define SxactIsCommitted(sxact) (((sxact)->flags & SXACT_FLAG_COMMITTED) != 0)
279#define SxactIsPrepared(sxact) (((sxact)->flags & SXACT_FLAG_PREPARED) != 0)
280#define SxactIsRolledBack(sxact) (((sxact)->flags & SXACT_FLAG_ROLLED_BACK) != 0)
281#define SxactIsDoomed(sxact) (((sxact)->flags & SXACT_FLAG_DOOMED) != 0)
282#define SxactIsReadOnly(sxact) (((sxact)->flags & SXACT_FLAG_READ_ONLY) != 0)
283#define SxactHasSummaryConflictIn(sxact) (((sxact)->flags & SXACT_FLAG_SUMMARY_CONFLICT_IN) != 0)
284#define SxactHasSummaryConflictOut(sxact) (((sxact)->flags & SXACT_FLAG_SUMMARY_CONFLICT_OUT) != 0)
285/*
286 * The following macro actually means that the specified transaction has a
287 * conflict out *to a transaction which committed ahead of it*. It's hard
288 * to get that into a name of a reasonable length.
289 */
290#define SxactHasConflictOut(sxact) (((sxact)->flags & SXACT_FLAG_CONFLICT_OUT) != 0)
291#define SxactIsDeferrableWaiting(sxact) (((sxact)->flags & SXACT_FLAG_DEFERRABLE_WAITING) != 0)
292#define SxactIsROSafe(sxact) (((sxact)->flags & SXACT_FLAG_RO_SAFE) != 0)
293#define SxactIsROUnsafe(sxact) (((sxact)->flags & SXACT_FLAG_RO_UNSAFE) != 0)
294#define SxactIsPartiallyReleased(sxact) (((sxact)->flags & SXACT_FLAG_PARTIALLY_RELEASED) != 0)
295
296/*
297 * Compute the hash code associated with a PREDICATELOCKTARGETTAG.
298 *
299 * To avoid unnecessary recomputations of the hash code, we try to do this
300 * just once per function, and then pass it around as needed. Aside from
301 * passing the hashcode to hash_search_with_hash_value(), we can extract
302 * the lock partition number from the hashcode.
303 */
304#define PredicateLockTargetTagHashCode(predicatelocktargettag) \
305 get_hash_value(PredicateLockTargetHash, predicatelocktargettag)
306
307/*
308 * Given a predicate lock tag, and the hash for its target,
309 * compute the lock hash.
310 *
311 * To make the hash code also depend on the transaction, we xor the sxid
312 * struct's address into the hash code, left-shifted so that the
313 * partition-number bits don't change. Since this is only a hash, we
314 * don't care if we lose high-order bits of the address; use an
315 * intermediate variable to suppress cast-pointer-to-int warnings.
316 */
317#define PredicateLockHashCodeFromTargetHashCode(predicatelocktag, targethash) \
318 ((targethash) ^ ((uint32) PointerGetDatum((predicatelocktag)->myXact)) \
319 << LOG2_NUM_PREDICATELOCK_PARTITIONS)
320
321
322/*
323 * The SLRU buffer area through which we access the old xids.
324 */
326
327#define SerialSlruCtl (&SerialSlruCtlData)
328
329#define SERIAL_PAGESIZE BLCKSZ
330#define SERIAL_ENTRYSIZE sizeof(SerCommitSeqNo)
331#define SERIAL_ENTRIESPERPAGE (SERIAL_PAGESIZE / SERIAL_ENTRYSIZE)
332
333/*
334 * Set maximum pages based on the number needed to track all transactions.
335 */
336#define SERIAL_MAX_PAGE (MaxTransactionId / SERIAL_ENTRIESPERPAGE)
337
338#define SerialNextPage(page) (((page) >= SERIAL_MAX_PAGE) ? 0 : (page) + 1)
339
340#define SerialValue(slotno, xid) (*((SerCommitSeqNo *) \
341 (SerialSlruCtl->shared->page_buffer[slotno] + \
342 ((((uint32) (xid)) % SERIAL_ENTRIESPERPAGE) * SERIAL_ENTRYSIZE))))
343
344#define SerialPage(xid) (((uint32) (xid)) / SERIAL_ENTRIESPERPAGE)
345
346typedef struct SerialControlData
347{
348 int64 headPage; /* newest initialized page */
349 TransactionId headXid; /* newest valid Xid in the SLRU */
350 TransactionId tailXid; /* oldest xmin we might be interested in */
352
354
356
357/*
358 * When the oldest committed transaction on the "finished" list is moved to
359 * SLRU, its predicate locks will be moved to this "dummy" transaction,
360 * collapsing duplicate targets. When a duplicate is found, the later
361 * commitSeqNo is used.
362 */
364
365
366/*
367 * These configuration variables are used to set the predicate lock table size
368 * and to control promotion of predicate locks to coarser granularity in an
369 * attempt to degrade performance (mostly as false positive serialization
370 * failure) gracefully in the face of memory pressure.
371 */
372int max_predicate_locks_per_xact; /* in guc_tables.c */
373int max_predicate_locks_per_relation; /* in guc_tables.c */
374int max_predicate_locks_per_page; /* in guc_tables.c */
375
376/*
377 * This provides a list of objects in order to track transactions
378 * participating in predicate locking. Entries in the list are fixed size,
379 * and reside in shared memory. The memory address of an entry must remain
380 * fixed during its lifetime. The list will be protected from concurrent
381 * update externally; no provision is made in this code to manage that. The
382 * number of entries in the list, and the size allowed for each entry is
383 * fixed upon creation.
384 */
386
387/*
388 * This provides a pool of RWConflict data elements to use in conflict lists
389 * between transactions.
390 */
392
393/*
394 * The predicate locking hash tables are in shared memory.
395 * Each backend keeps pointers to them.
396 */
401
402/*
403 * Tag for a dummy entry in PredicateLockTargetHash. By temporarily removing
404 * this entry, you can ensure that there's enough scratch space available for
405 * inserting one entry in the hash table. This is an otherwise-invalid tag.
406 */
407static const PREDICATELOCKTARGETTAG ScratchTargetTag = {0, 0, 0, 0};
410
411/*
412 * The local hash table used to determine when to combine multiple fine-
413 * grained locks into a single courser-grained lock.
414 */
416
417/*
418 * Keep a pointer to the currently-running serializable transaction (if any)
419 * for quick reference. Also, remember if we have written anything that could
420 * cause a rw-conflict.
421 */
423static bool MyXactDidWrite = false;
424
425/*
426 * The SXACT_FLAG_RO_UNSAFE optimization might lead us to release
427 * MySerializableXact early. If that happens in a parallel query, the leader
428 * needs to defer the destruction of the SERIALIZABLEXACT until end of
429 * transaction, because the workers still have a reference to it. In that
430 * case, the leader stores it here.
431 */
433
434/* local functions */
435
436static SERIALIZABLEXACT *CreatePredXact(void);
438
439static bool RWConflictExists(const SERIALIZABLEXACT *reader, const SERIALIZABLEXACT *writer);
444
446static void SerialInit(void);
450
451static uint32 predicatelock_hash(const void *key, Size keysize);
452static void SummarizeOldestCommittedSxact(void);
456 int sourcepid);
459 PREDICATELOCKTARGETTAG *parent);
461static void RemoveScratchTarget(bool lockheld);
462static void RestoreScratchTarget(bool lockheld);
475 bool removeOld);
477static void DropAllPredicateLocksFromTable(Relation relation,
478 bool transfer);
479static void SetNewSxactGlobalXmin(void);
480static void ClearOldPredicateLocks(void);
481static void ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial,
482 bool summarize);
483static bool XidIsConcurrent(TransactionId xid);
488static void CreateLocalPredicateLockHash(void);
489static void ReleasePredicateLocksLocal(void);
490
491
492/*------------------------------------------------------------------------*/
493
494/*
495 * Does this relation participate in predicate locking? Temporary and system
496 * relations are exempt.
497 */
498static inline bool
500{
501 return !(relation->rd_id < FirstUnpinnedObjectId ||
502 RelationUsesLocalBuffers(relation));
503}
504
505/*
506 * When a public interface method is called for a read, this is the test to
507 * see if we should do a quick return.
508 *
509 * Note: this function has side-effects! If this transaction has been flagged
510 * as RO-safe since the last call, we release all predicate locks and reset
511 * MySerializableXact. That makes subsequent calls to return quickly.
512 *
513 * This is marked as 'inline' to eliminate the function call overhead in the
514 * common case that serialization is not needed.
515 */
516static inline bool
518{
519 /* Nothing to do if this is not a serializable transaction */
521 return false;
522
523 /*
524 * Don't acquire locks or conflict when scanning with a special snapshot.
525 * This excludes things like CLUSTER and REINDEX. They use the wholesale
526 * functions TransferPredicateLocksToHeapRelation() and
527 * CheckTableForSerializableConflictIn() to participate in serialization,
528 * but the scans involved don't need serialization.
529 */
530 if (!IsMVCCSnapshot(snapshot))
531 return false;
532
533 /*
534 * Check if we have just become "RO-safe". If we have, immediately release
535 * all locks as they're not needed anymore. This also resets
536 * MySerializableXact, so that subsequent calls to this function can exit
537 * quickly.
538 *
539 * A transaction is flagged as RO_SAFE if all concurrent R/W transactions
540 * commit without having conflicts out to an earlier snapshot, thus
541 * ensuring that no conflicts are possible for this transaction.
542 */
544 {
545 ReleasePredicateLocks(false, true);
546 return false;
547 }
548
549 /* Check if the relation doesn't participate in predicate locking */
551 return false;
552
553 return true; /* no excuse to skip predicate locking */
554}
555
556/*
557 * Like SerializationNeededForRead(), but called on writes.
558 * The logic is the same, but there is no snapshot and we can't be RO-safe.
559 */
560static inline bool
562{
563 /* Nothing to do if this is not a serializable transaction */
565 return false;
566
567 /* Check if the relation doesn't participate in predicate locking */
569 return false;
570
571 return true; /* no excuse to skip predicate locking */
572}
573
574
575/*------------------------------------------------------------------------*/
576
577/*
578 * These functions are a simple implementation of a list for this specific
579 * type of struct. If there is ever a generalized shared memory list, we
580 * should probably switch to that.
581 */
582static SERIALIZABLEXACT *
595
596static void
604
605/*------------------------------------------------------------------------*/
606
607/*
608 * These functions manage primitive access to the RWConflict pool and lists.
609 */
610static bool
612{
613 dlist_iter iter;
614
615 Assert(reader != writer);
616
617 /* Check the ends of the purported conflict first. */
618 if (SxactIsDoomed(reader)
620 || dlist_is_empty(&reader->outConflicts)
621 || dlist_is_empty(&writer->inConflicts))
622 return false;
623
624 /*
625 * A conflict is possible; walk the list to find out.
626 *
627 * The unconstify is needed as we have no const version of
628 * dlist_foreach().
629 */
630 dlist_foreach(iter, &unconstify(SERIALIZABLEXACT *, reader)->outConflicts)
631 {
633 dlist_container(RWConflictData, outLink, iter.cur);
634
635 if (conflict->sxactIn == writer)
636 return true;
637 }
638
639 /* No conflict found. */
640 return false;
641}
642
643static void
645{
647
648 Assert(reader != writer);
649 Assert(!RWConflictExists(reader, writer));
650
654 errmsg("not enough elements in RWConflictPool to record a read/write conflict"),
655 errhint("You might need to run fewer transactions at a time or increase \"max_connections\".")));
656
658 dlist_delete(&conflict->outLink);
659
660 conflict->sxactOut = reader;
661 conflict->sxactIn = writer;
662 dlist_push_tail(&reader->outConflicts, &conflict->outLink);
663 dlist_push_tail(&writer->inConflicts, &conflict->inLink);
664}
665
666static void
669{
671
675
679 errmsg("not enough elements in RWConflictPool to record a potential read/write conflict"),
680 errhint("You might need to run fewer transactions at a time or increase \"max_connections\".")));
681
683 dlist_delete(&conflict->outLink);
684
685 conflict->sxactOut = activeXact;
686 conflict->sxactIn = roXact;
687 dlist_push_tail(&activeXact->possibleUnsafeConflicts, &conflict->outLink);
688 dlist_push_tail(&roXact->possibleUnsafeConflicts, &conflict->inLink);
689}
690
691static void
698
699static void
701{
703
706
707 sxact->flags |= SXACT_FLAG_RO_UNSAFE;
708
709 /*
710 * We know this isn't a safe snapshot, so we can stop looking for other
711 * potential conflicts.
712 */
713 dlist_foreach_modify(iter, &sxact->possibleUnsafeConflicts)
714 {
716 dlist_container(RWConflictData, inLink, iter.cur);
717
718 Assert(!SxactIsReadOnly(conflict->sxactOut));
719 Assert(sxact == conflict->sxactIn);
720
722 }
723}
724
725/*------------------------------------------------------------------------*/
726
727/*
728 * Decide whether a Serial page number is "older" for truncation purposes.
729 * Analogous to CLOGPagePrecedes().
730 */
731static bool
745
746#ifdef USE_ASSERT_CHECKING
747static void
749{
751 offset = per_page / 2;
754 headPage,
757 oldestXact;
758
759 /* GetNewTransactionId() has assigned the last XID it can safely use. */
760 newestPage = 2 * SLRU_PAGES_PER_SEGMENT - 1; /* nothing special */
761 newestXact = newestPage * per_page + offset;
763 oldestXact = newestXact + 1;
764 oldestXact -= 1U << 31;
765 oldestPage = oldestXact / per_page;
766
767 /*
768 * In this scenario, the SLRU headPage pertains to the last ~1000 XIDs
769 * assigned. oldestXact finishes, ~2B XIDs having elapsed since it
770 * started. Further transactions cause us to summarize oldestXact to
771 * tailPage. Function must return false so SerialAdd() doesn't zero
772 * tailPage (which may contain entries for other old, recently-finished
773 * XIDs) and half the SLRU. Reaching this requires burning ~2B XIDs in
774 * single-user mode, a negligible possibility.
775 */
779
780 /*
781 * In this scenario, the SLRU headPage pertains to oldestXact. We're
782 * summarizing an XID near newestXact. (Assume few other XIDs used
783 * SERIALIZABLE, hence the minimal headPage advancement. Assume
784 * oldestXact was long-running and only recently reached the SLRU.)
785 * Function must return true to make SerialAdd() create targetPage.
786 *
787 * Today's implementation mishandles this case, but it doesn't matter
788 * enough to fix. Verify that the defect affects just one page by
789 * asserting correct treatment of its prior page. Reaching this case
790 * requires burning ~2B XIDs in single-user mode, a negligible
791 * possibility. Moreover, if it does happen, the consequence would be
792 * mild, namely a new transaction failing in SimpleLruReadPage().
793 */
797#if 0
799#endif
800}
801#endif
802
803/*
804 * Initialize for the tracking of old serializable committed xids.
805 */
806static void
808{
809 bool found;
810
811 /*
812 * Set up SLRU management of the pg_serial data.
813 */
815 SimpleLruInit(SerialSlruCtl, "serializable",
816 serializable_buffers, 0, "pg_serial",
818 SYNC_HANDLER_NONE, false);
819#ifdef USE_ASSERT_CHECKING
821#endif
823
824 /*
825 * Create or attach to the SerialControl structure.
826 */
828 ShmemInitStruct("SerialControlData", sizeof(SerialControlData), &found);
829
830 Assert(found == IsUnderPostmaster);
831 if (!found)
832 {
833 /*
834 * Set control information to reflect empty SLRU.
835 */
841 }
842}
843
844/*
845 * GUC check_hook for serializable_buffers
846 */
847bool
849{
850 return check_slru_buffers("serializable_buffers", newval);
851}
852
853/*
854 * Record a committed read write serializable xid and the minimum
855 * commitSeqNo of any transactions to which this xid had a rw-conflict out.
856 * An invalid commitSeqNo means that there were no conflicts out from xid.
857 */
858static void
860{
863 int slotno;
865 bool isNewPage;
866 LWLock *lock;
867
869
870 targetPage = SerialPage(xid);
872
873 /*
874 * In this routine, we must hold both SerialControlLock and the SLRU bank
875 * lock simultaneously while making the SLRU data catch up with the new
876 * state that we determine.
877 */
879
880 /*
881 * If 'xid' is older than the global xmin (== tailXid), there's no need to
882 * store it, after all. This can happen if the oldest transaction holding
883 * back the global xmin just finished, making 'xid' uninteresting, but
884 * ClearOldPredicateLocks() has not yet run.
885 */
888 {
890 return;
891 }
892
893 /*
894 * If the SLRU is currently unused, zero out the whole active region from
895 * tailXid to headXid before taking it into use. Otherwise zero out only
896 * any new pages that enter the tailXid-headXid range as we advance
897 * headXid.
898 */
899 if (serialControl->headPage < 0)
900 {
902 isNewPage = true;
903 }
904 else
905 {
908 targetPage);
909 }
910
913 serialControl->headXid = xid;
914 if (isNewPage)
916
917 if (isNewPage)
918 {
919 /* Initialize intervening pages; might involve trading locks */
920 for (;;)
921 {
926 break;
928 LWLockRelease(lock);
929 }
930 }
931 else
932 {
935 }
936
938 SerialSlruCtl->shared->page_dirty[slotno] = true;
939
940 LWLockRelease(lock);
942}
943
944/*
945 * Get the minimum commitSeqNo for any conflict out for the given xid. For
946 * a transaction which exists but has no conflict out, InvalidSerCommitSeqNo
947 * will be returned.
948 */
949static SerCommitSeqNo
951{
955 int slotno;
956
958
963
965 return 0;
966
968
971 return 0;
972
973 /*
974 * The following function must be called without holding SLRU bank lock,
975 * but will return with that lock held, which must then be released.
976 */
978 SerialPage(xid), xid);
979 val = SerialValue(slotno, xid);
981 return val;
982}
983
984/*
985 * Call this whenever there is a new xmin for active serializable
986 * transactions. We don't need to keep information on transactions which
987 * precede that. InvalidTransactionId means none active, so everything in
988 * the SLRU can be discarded.
989 */
990static void
992{
994
995 /*
996 * When no sxacts are active, nothing overlaps, set the xid values to
997 * invalid to show that there are no valid entries. Don't clear headPage,
998 * though. A new xmin might still land on that page, and we don't want to
999 * repeatedly zero out the same page.
1000 */
1001 if (!TransactionIdIsValid(xid))
1002 {
1006 return;
1007 }
1008
1009 /*
1010 * When we're recovering prepared transactions, the global xmin might move
1011 * backwards depending on the order they're recovered. Normally that's not
1012 * OK, but during recovery no serializable transactions will commit, so
1013 * the SLRU is empty and we can get away with it.
1014 */
1015 if (RecoveryInProgress())
1016 {
1020 {
1021 serialControl->tailXid = xid;
1022 }
1024 return;
1025 }
1026
1029
1030 serialControl->tailXid = xid;
1031
1033}
1034
1035/*
1036 * Perform a checkpoint --- either during shutdown, or on-the-fly
1037 *
1038 * We don't have any data that needs to survive a restart, but this is a
1039 * convenient place to truncate the SLRU.
1040 */
1041void
1043{
1045
1047
1048 /* Exit quickly if the SLRU is currently not in use. */
1049 if (serialControl->headPage < 0)
1050 {
1052 return;
1053 }
1054
1056 {
1058
1060
1061 /*
1062 * It is possible for the tailXid to be ahead of the headXid. This
1063 * occurs if we checkpoint while there are in-progress serializable
1064 * transaction(s) advancing the tail but we are yet to summarize the
1065 * transactions. In this case, we cutoff up to the headPage and the
1066 * next summary will advance the headXid.
1067 */
1069 {
1070 /* We can truncate the SLRU up to the page containing tailXid */
1072 }
1073 else
1075 }
1076 else
1077 {
1078 /*----------
1079 * The SLRU is no longer needed. Truncate to head before we set head
1080 * invalid.
1081 *
1082 * XXX: It's possible that the SLRU is not needed again until XID
1083 * wrap-around has happened, so that the segment containing headPage
1084 * that we leave behind will appear to be new again. In that case it
1085 * won't be removed until XID horizon advances enough to make it
1086 * current again.
1087 *
1088 * XXX: This should happen in vac_truncate_clog(), not in checkpoints.
1089 * Consider this scenario, starting from a system with no in-progress
1090 * transactions and VACUUM FREEZE having maximized oldestXact:
1091 * - Start a SERIALIZABLE transaction.
1092 * - Start, finish, and summarize a SERIALIZABLE transaction, creating
1093 * one SLRU page.
1094 * - Consume XIDs to reach xidStopLimit.
1095 * - Finish all transactions. Due to the long-running SERIALIZABLE
1096 * transaction, earlier checkpoints did not touch headPage. The
1097 * next checkpoint will change it, but that checkpoint happens after
1098 * the end of the scenario.
1099 * - VACUUM to advance XID limits.
1100 * - Consume ~2M XIDs, crossing the former xidWrapLimit.
1101 * - Start, finish, and summarize a SERIALIZABLE transaction.
1102 * SerialAdd() declines to create the targetPage, because headPage
1103 * is not regarded as in the past relative to that targetPage. The
1104 * transaction instigating the summarize fails in
1105 * SimpleLruReadPage().
1106 */
1108 serialControl->headPage = -1;
1109 }
1110
1112
1113 /*
1114 * Truncate away pages that are no longer required. Note that no
1115 * additional locking is required, because this is only called as part of
1116 * a checkpoint, and the validity limits have already been determined.
1117 */
1119
1120 /*
1121 * Write dirty SLRU pages to disk
1122 *
1123 * This is not actually necessary from a correctness point of view. We do
1124 * it merely as a debugging aid.
1125 *
1126 * We're doing this after the truncation to avoid writing pages right
1127 * before deleting the file in which they sit, which would be completely
1128 * pointless.
1129 */
1131}
1132
1133/*------------------------------------------------------------------------*/
1134
1135/*
1136 * PredicateLockShmemInit -- Initialize the predicate locking data structures.
1137 *
1138 * This is called from CreateSharedMemoryAndSemaphores(), which see for
1139 * more comments. In the normal postmaster case, the shared hash tables
1140 * are created here. Backends inherit the pointers
1141 * to the shared tables via fork(). In the EXEC_BACKEND case, each
1142 * backend re-executes this code to obtain pointers to the already existing
1143 * shared hash tables.
1144 */
1145void
1147{
1148 HASHCTL info;
1151 bool found;
1152
1153#ifndef EXEC_BACKEND
1155#endif
1156
1157 /*
1158 * Compute size of predicate lock target hashtable. Note these
1159 * calculations must agree with PredicateLockShmemSize!
1160 */
1162
1163 /*
1164 * Allocate hash table for PREDICATELOCKTARGET structs. This stores
1165 * per-predicate-lock-target information.
1166 */
1167 info.keysize = sizeof(PREDICATELOCKTARGETTAG);
1168 info.entrysize = sizeof(PREDICATELOCKTARGET);
1170
1171 PredicateLockTargetHash = ShmemInitHash("PREDICATELOCKTARGET hash",
1174 &info,
1177
1178 /*
1179 * Reserve a dummy entry in the hash table; we use it to make sure there's
1180 * always one entry available when we need to split or combine a page,
1181 * because running out of space there could mean aborting a
1182 * non-serializable transaction.
1183 */
1184 if (!IsUnderPostmaster)
1185 {
1187 HASH_ENTER, &found);
1188 Assert(!found);
1189 }
1190
1191 /* Pre-calculate the hash and partition lock of the scratch entry */
1194
1195 /*
1196 * Allocate hash table for PREDICATELOCK structs. This stores per
1197 * xact-lock-of-a-target information.
1198 */
1199 info.keysize = sizeof(PREDICATELOCKTAG);
1200 info.entrysize = sizeof(PREDICATELOCK);
1201 info.hash = predicatelock_hash;
1203
1204 /* Assume an average of 2 xacts per target */
1205 max_table_size *= 2;
1206
1207 PredicateLockHash = ShmemInitHash("PREDICATELOCK hash",
1210 &info,
1213
1214 /*
1215 * Compute size for serializable transaction hashtable. Note these
1216 * calculations must agree with PredicateLockShmemSize!
1217 */
1219
1220 /*
1221 * Allocate a list to hold information on transactions participating in
1222 * predicate locking.
1223 *
1224 * Assume an average of 10 predicate locking transactions per backend.
1225 * This allows aggressive cleanup while detail is present before data must
1226 * be summarized for storage in SLRU and the "dummy" transaction.
1227 */
1228 max_table_size *= 10;
1229
1232 sizeof(SERIALIZABLEXACT))));
1233
1234 PredXact = ShmemInitStruct("PredXactList",
1236 &found);
1237 Assert(found == IsUnderPostmaster);
1238 if (!found)
1239 {
1240 int i;
1241
1242 /* clean everything, both the header and the element */
1244
1255 /* Add all elements to available list, clean. */
1256 for (i = 0; i < max_table_size; i++)
1257 {
1261 }
1278 }
1279 /* This never changes, so let's keep a local copy. */
1281
1282 /*
1283 * Allocate hash table for SERIALIZABLEXID structs. This stores per-xid
1284 * information for serializable transactions which have accessed data.
1285 */
1286 info.keysize = sizeof(SERIALIZABLEXIDTAG);
1287 info.entrysize = sizeof(SERIALIZABLEXID);
1288
1289 SerializableXidHash = ShmemInitHash("SERIALIZABLEXID hash",
1292 &info,
1295
1296 /*
1297 * Allocate space for tracking rw-conflicts in lists attached to the
1298 * transactions.
1299 *
1300 * Assume an average of 5 conflicts per transaction. Calculations suggest
1301 * that this will prevent resource exhaustion in even the most pessimal
1302 * loads up to max_connections = 200 with all 200 connections pounding the
1303 * database with serializable transactions. Beyond that, there may be
1304 * occasional transactions canceled when trying to flag conflicts. That's
1305 * probably OK.
1306 */
1307 max_table_size *= 5;
1308
1312
1313 RWConflictPool = ShmemInitStruct("RWConflictPool",
1315 &found);
1316 Assert(found == IsUnderPostmaster);
1317 if (!found)
1318 {
1319 int i;
1320
1321 /* clean everything, including the elements */
1323
1327 /* Add all elements to available list, clean. */
1328 for (i = 0; i < max_table_size; i++)
1329 {
1332 }
1333 }
1334
1335 /*
1336 * Create or attach to the header for the list of finished serializable
1337 * transactions.
1338 */
1340 ShmemInitStruct("FinishedSerializableTransactions",
1341 sizeof(dlist_head),
1342 &found);
1343 Assert(found == IsUnderPostmaster);
1344 if (!found)
1346
1347 /*
1348 * Initialize the SLRU storage for old committed serializable
1349 * transactions.
1350 */
1351 SerialInit();
1352}
1353
1354/*
1355 * Estimate shared-memory space used for predicate lock table
1356 */
1357Size
1359{
1360 Size size = 0;
1361 long max_table_size;
1362
1363 /* predicate lock target hash table */
1366 sizeof(PREDICATELOCKTARGET)));
1367
1368 /* predicate lock hash table */
1369 max_table_size *= 2;
1371 sizeof(PREDICATELOCK)));
1372
1373 /*
1374 * Since NPREDICATELOCKTARGETENTS is only an estimate, add 10% safety
1375 * margin.
1376 */
1377 size = add_size(size, size / 10);
1378
1379 /* transaction list */
1381 max_table_size *= 10;
1382 size = add_size(size, PredXactListDataSize);
1383 size = add_size(size, mul_size((Size) max_table_size,
1384 sizeof(SERIALIZABLEXACT)));
1385
1386 /* transaction xid table */
1388 sizeof(SERIALIZABLEXID)));
1389
1390 /* rw-conflict pool */
1391 max_table_size *= 5;
1393 size = add_size(size, mul_size((Size) max_table_size,
1395
1396 /* Head for list of finished serializable transactions. */
1397 size = add_size(size, sizeof(dlist_head));
1398
1399 /* Shared memory structures for SLRU tracking of old committed xids. */
1400 size = add_size(size, sizeof(SerialControlData));
1402
1403 return size;
1404}
1405
1406
1407/*
1408 * Compute the hash code associated with a PREDICATELOCKTAG.
1409 *
1410 * Because we want to use just one set of partition locks for both the
1411 * PREDICATELOCKTARGET and PREDICATELOCK hash tables, we have to make sure
1412 * that PREDICATELOCKs fall into the same partition number as their
1413 * associated PREDICATELOCKTARGETs. dynahash.c expects the partition number
1414 * to be the low-order bits of the hash code, and therefore a
1415 * PREDICATELOCKTAG's hash code must have the same low-order bits as the
1416 * associated PREDICATELOCKTARGETTAG's hash code. We achieve this with this
1417 * specialized hash function.
1418 */
1419static uint32
1420predicatelock_hash(const void *key, Size keysize)
1421{
1422 const PREDICATELOCKTAG *predicatelocktag = (const PREDICATELOCKTAG *) key;
1424
1425 Assert(keysize == sizeof(PREDICATELOCKTAG));
1426
1427 /* Look into the associated target object, and compute its hash code */
1429
1431}
1432
1433
1434/*
1435 * GetPredicateLockStatusData
1436 * Return a table containing the internal state of the predicate
1437 * lock manager for use in pg_lock_status.
1438 *
1439 * Like GetLockStatusData, this function tries to hold the partition LWLocks
1440 * for as short a time as possible by returning two arrays that simply
1441 * contain the PREDICATELOCKTARGETTAG and SERIALIZABLEXACT for each lock
1442 * table entry. Multiple copies of the same PREDICATELOCKTARGETTAG and
1443 * SERIALIZABLEXACT will likely appear.
1444 */
1447{
1449 int i;
1450 int els,
1451 el;
1454
1456
1457 /*
1458 * To ensure consistency, take simultaneous locks on all partition locks
1459 * in ascending order, then SerializableXactHashLock.
1460 */
1461 for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
1464
1465 /* Get number of locks and allocate appropriately-sized arrays. */
1467 data->nelements = els;
1470
1471
1472 /* Scan through PredicateLockHash and copy contents */
1474
1475 el = 0;
1476
1478 {
1479 data->locktags[el] = predlock->tag.myTarget->tag;
1480 data->xacts[el] = *predlock->tag.myXact;
1481 el++;
1482 }
1483
1484 Assert(el == els);
1485
1486 /* Release locks in reverse order */
1488 for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
1490
1491 return data;
1492}
1493
1494/*
1495 * Free up shared memory structures by pushing the oldest sxact (the one at
1496 * the front of the SummarizeOldestCommittedSxact queue) into summary form.
1497 * Each call will free exactly one SERIALIZABLEXACT structure and may also
1498 * free one or more of these structures: SERIALIZABLEXID, PREDICATELOCK,
1499 * PREDICATELOCKTARGET, RWConflictData.
1500 */
1501static void
1503{
1505
1507
1508 /*
1509 * This function is only called if there are no sxact slots available.
1510 * Some of them must belong to old, already-finished transactions, so
1511 * there should be something in FinishedSerializableTransactions list that
1512 * we can summarize. However, there's a race condition: while we were not
1513 * holding any locks, a transaction might have ended and cleaned up all
1514 * the finished sxact entries already, freeing up their sxact slots. In
1515 * that case, we have nothing to do here. The caller will find one of the
1516 * slots released by the other backend when it retries.
1517 */
1519 {
1521 return;
1522 }
1523
1524 /*
1525 * Grab the first sxact off the finished list -- this will be the earliest
1526 * commit. Remove it from the list.
1527 */
1530 dlist_delete_thoroughly(&sxact->finishedLink);
1531
1532 /* Add to SLRU summary information. */
1535 ? sxact->SeqNo.earliestOutConflictCommit : InvalidSerCommitSeqNo);
1536
1537 /* Summarize and release the detail. */
1538 ReleaseOneSerializableXact(sxact, false, true);
1539
1541}
1542
1543/*
1544 * GetSafeSnapshot
1545 * Obtain and register a snapshot for a READ ONLY DEFERRABLE
1546 * transaction. Ensures that the snapshot is "safe", i.e. a
1547 * read-only transaction running on it can execute serializably
1548 * without further checks. This requires waiting for concurrent
1549 * transactions to complete, and retrying with a new snapshot if
1550 * one of them could possibly create a conflict.
1551 *
1552 * As with GetSerializableTransactionSnapshot (which this is a subroutine
1553 * for), the passed-in Snapshot pointer should reference a static data
1554 * area that can safely be passed to GetSnapshotData.
1555 */
1556static Snapshot
1558{
1559 Snapshot snapshot;
1560
1562
1563 while (true)
1564 {
1565 /*
1566 * GetSerializableTransactionSnapshotInt is going to call
1567 * GetSnapshotData, so we need to provide it the static snapshot area
1568 * our caller passed to us. The pointer returned is actually the same
1569 * one passed to it, but we avoid assuming that here.
1570 */
1572 NULL, InvalidPid);
1573
1575 return snapshot; /* no concurrent r/w xacts; it's safe */
1576
1578
1579 /*
1580 * Wait for concurrent transactions to finish. Stop early if one of
1581 * them marked us as conflicted.
1582 */
1586 {
1590 }
1592
1594 {
1596 break; /* success */
1597 }
1598
1600
1601 /* else, need to retry... */
1604 errmsg_internal("deferrable snapshot was unsafe; trying a new one")));
1605 ReleasePredicateLocks(false, false);
1606 }
1607
1608 /*
1609 * Now we have a safe snapshot, so we don't need to do any further checks.
1610 */
1612 ReleasePredicateLocks(false, true);
1613
1614 return snapshot;
1615}
1616
1617/*
1618 * GetSafeSnapshotBlockingPids
1619 * If the specified process is currently blocked in GetSafeSnapshot,
1620 * write the process IDs of all processes that it is blocked by
1621 * into the caller-supplied buffer output[]. The list is truncated at
1622 * output_size, and the number of PIDs written into the buffer is
1623 * returned. Returns zero if the given PID is not currently blocked
1624 * in GetSafeSnapshot.
1625 */
1626int
1628{
1629 int num_written = 0;
1630 dlist_iter iter;
1632
1634
1635 /* Find blocked_pid's SERIALIZABLEXACT by linear search. */
1637 {
1639 dlist_container(SERIALIZABLEXACT, xactLink, iter.cur);
1640
1641 if (sxact->pid == blocked_pid)
1642 {
1644 break;
1645 }
1646 }
1647
1648 /* Did we find it, and is it currently waiting in GetSafeSnapshot? */
1650 {
1651 /* Traverse the list of possible unsafe conflicts collecting PIDs. */
1652 dlist_foreach(iter, &blocking_sxact->possibleUnsafeConflicts)
1653 {
1655 dlist_container(RWConflictData, inLink, iter.cur);
1656
1657 output[num_written++] = possibleUnsafeConflict->sxactOut->pid;
1658
1659 if (num_written >= output_size)
1660 break;
1661 }
1662 }
1663
1665
1666 return num_written;
1667}
1668
1669/*
1670 * Acquire a snapshot that can be used for the current transaction.
1671 *
1672 * Make sure we have a SERIALIZABLEXACT reference in MySerializableXact.
1673 * It should be current for this process and be contained in PredXact.
1674 *
1675 * The passed-in Snapshot pointer should reference a static data area that
1676 * can safely be passed to GetSnapshotData. The return value is actually
1677 * always this same pointer; no new snapshot data structure is allocated
1678 * within this function.
1679 */
1682{
1684
1685 /*
1686 * Can't use serializable mode while recovery is still active, as it is,
1687 * for example, on a hot standby. We could get here despite the check in
1688 * check_transaction_isolation() if default_transaction_isolation is set
1689 * to serializable, so phrase the hint accordingly.
1690 */
1691 if (RecoveryInProgress())
1692 ereport(ERROR,
1694 errmsg("cannot use serializable mode in a hot standby"),
1695 errdetail("\"default_transaction_isolation\" is set to \"serializable\"."),
1696 errhint("You can use \"SET default_transaction_isolation = 'repeatable read'\" to change the default.")));
1697
1698 /*
1699 * A special optimization is available for SERIALIZABLE READ ONLY
1700 * DEFERRABLE transactions -- we can wait for a suitable snapshot and
1701 * thereby avoid all SSI overhead once it's running.
1702 */
1704 return GetSafeSnapshot(snapshot);
1705
1707 NULL, InvalidPid);
1708}
1709
1710/*
1711 * Import a snapshot to be used for the current transaction.
1712 *
1713 * This is nearly the same as GetSerializableTransactionSnapshot, except that
1714 * we don't take a new snapshot, but rather use the data we're handed.
1715 *
1716 * The caller must have verified that the snapshot came from a serializable
1717 * transaction; and if we're read-write, the source transaction must not be
1718 * read-only.
1719 */
1720void
1723 int sourcepid)
1724{
1726
1727 /*
1728 * If this is called by parallel.c in a parallel worker, we don't want to
1729 * create a SERIALIZABLEXACT just yet because the leader's
1730 * SERIALIZABLEXACT will be installed with AttachSerializableXact(). We
1731 * also don't want to reject SERIALIZABLE READ ONLY DEFERRABLE in this
1732 * case, because the leader has already determined that the snapshot it
1733 * has passed us is safe. So there is nothing for us to do.
1734 */
1735 if (IsParallelWorker())
1736 return;
1737
1738 /*
1739 * We do not allow SERIALIZABLE READ ONLY DEFERRABLE transactions to
1740 * import snapshots, since there's no way to wait for a safe snapshot when
1741 * we're using the snap we're told to. (XXX instead of throwing an error,
1742 * we could just ignore the XactDeferrable flag?)
1743 */
1745 ereport(ERROR,
1747 errmsg("a snapshot-importing transaction must not be READ ONLY DEFERRABLE")));
1748
1750 sourcepid);
1751}
1752
1753/*
1754 * Guts of GetSerializableTransactionSnapshot
1755 *
1756 * If sourcevxid is valid, this is actually an import operation and we should
1757 * skip calling GetSnapshotData, because the snapshot contents are already
1758 * loaded up. HOWEVER: to avoid race conditions, we must check that the
1759 * source xact is still running after we acquire SerializableXactHashLock.
1760 * We do that by calling ProcArrayInstallImportedXmin.
1761 */
1762static Snapshot
1765 int sourcepid)
1766{
1767 PGPROC *proc;
1770 *othersxact;
1771
1772 /* We only do this for serializable transactions. Once. */
1774
1776
1777 /*
1778 * Since all parts of a serializable transaction must use the same
1779 * snapshot, it is too late to establish one after a parallel operation
1780 * has begun.
1781 */
1782 if (IsInParallelMode())
1783 elog(ERROR, "cannot establish serializable snapshot during a parallel operation");
1784
1785 proc = MyProc;
1786 Assert(proc != NULL);
1787 GET_VXID_FROM_PGPROC(vxid, *proc);
1788
1789 /*
1790 * First we get the sxact structure, which may involve looping and access
1791 * to the "finished" list to free a structure for use.
1792 *
1793 * We must hold SerializableXactHashLock when taking/checking the snapshot
1794 * to avoid race conditions, for much the same reasons that
1795 * GetSnapshotData takes the ProcArrayLock. Since we might have to
1796 * release SerializableXactHashLock to call SummarizeOldestCommittedSxact,
1797 * this means we have to create the sxact first, which is a bit annoying
1798 * (in particular, an elog(ERROR) in procarray.c would cause us to leak
1799 * the sxact). Consider refactoring to avoid this.
1800 */
1801#ifdef TEST_SUMMARIZE_SERIAL
1803#endif
1805 do
1806 {
1808 /* If null, push out committed sxact to SLRU summary & retry. */
1809 if (!sxact)
1810 {
1814 }
1815 } while (!sxact);
1816
1817 /* Get the snapshot, or check that it's safe to use */
1818 if (!sourcevxid)
1819 snapshot = GetSnapshotData(snapshot);
1820 else if (!ProcArrayInstallImportedXmin(snapshot->xmin, sourcevxid))
1821 {
1824 ereport(ERROR,
1826 errmsg("could not import the requested snapshot"),
1827 errdetail("The source process with PID %d is not running anymore.",
1828 sourcepid)));
1829 }
1830
1831 /*
1832 * If there are no serializable transactions which are not read-only, we
1833 * can "opt out" of predicate locking and conflict checking for a
1834 * read-only transaction.
1835 *
1836 * The reason this is safe is that a read-only transaction can only become
1837 * part of a dangerous structure if it overlaps a writable transaction
1838 * which in turn overlaps a writable transaction which committed before
1839 * the read-only transaction started. A new writable transaction can
1840 * overlap this one, but it can't meet the other condition of overlapping
1841 * a transaction which committed before this one started.
1842 */
1844 {
1847 return snapshot;
1848 }
1849
1850 /* Initialize the structure. */
1851 sxact->vxid = vxid;
1852 sxact->SeqNo.lastCommitBeforeSnapshot = PredXact->LastSxactCommitSeqNo;
1853 sxact->prepareSeqNo = InvalidSerCommitSeqNo;
1854 sxact->commitSeqNo = InvalidSerCommitSeqNo;
1855 dlist_init(&(sxact->outConflicts));
1856 dlist_init(&(sxact->inConflicts));
1857 dlist_init(&(sxact->possibleUnsafeConflicts));
1858 sxact->topXid = GetTopTransactionIdIfAny();
1859 sxact->finishedBefore = InvalidTransactionId;
1860 sxact->xmin = snapshot->xmin;
1861 sxact->pid = MyProcPid;
1862 sxact->pgprocno = MyProcNumber;
1863 dlist_init(&sxact->predicateLocks);
1864 dlist_node_init(&sxact->finishedLink);
1865 sxact->flags = 0;
1866 if (XactReadOnly)
1867 {
1868 dlist_iter iter;
1869
1870 sxact->flags |= SXACT_FLAG_READ_ONLY;
1871
1872 /*
1873 * Register all concurrent r/w transactions as possible conflicts; if
1874 * all of them commit without any outgoing conflicts to earlier
1875 * transactions then this snapshot can be deemed safe (and we can run
1876 * without tracking predicate locks).
1877 */
1879 {
1881
1885 {
1887 }
1888 }
1889
1890 /*
1891 * If we didn't find any possibly unsafe conflicts because every
1892 * uncommitted writable transaction turned out to be doomed, then we
1893 * can "opt out" immediately. See comments above the earlier check
1894 * for PredXact->WritableSxactCount == 0.
1895 */
1896 if (dlist_is_empty(&sxact->possibleUnsafeConflicts))
1897 {
1900 return snapshot;
1901 }
1902 }
1903 else
1904 {
1908 }
1909
1910 /* Maintain serializable global xmin info. */
1912 {
1914 PredXact->SxactGlobalXmin = snapshot->xmin;
1916 SerialSetActiveSerXmin(snapshot->xmin);
1917 }
1918 else if (TransactionIdEquals(snapshot->xmin, PredXact->SxactGlobalXmin))
1919 {
1922 }
1923 else
1924 {
1926 }
1927
1929 MyXactDidWrite = false; /* haven't written anything yet */
1930
1932
1934
1935 return snapshot;
1936}
1937
1938static void
1940{
1942
1943 /* Initialize the backend-local hash table of parent locks */
1945 hash_ctl.keysize = sizeof(PREDICATELOCKTARGETTAG);
1946 hash_ctl.entrysize = sizeof(LOCALPREDICATELOCK);
1947 LocalPredicateLockHash = hash_create("Local predicate lock",
1949 &hash_ctl,
1951}
1952
1953/*
1954 * Register the top level XID in SerializableXidHash.
1955 * Also store it for easy reference in MySerializableXact.
1956 */
1957void
1959{
1962 bool found;
1963
1964 /*
1965 * If we're not tracking predicate lock data for this transaction, we
1966 * should ignore the request and return quickly.
1967 */
1969 return;
1970
1971 /* We should have a valid XID and be at the top level. */
1973
1975
1976 /* This should only be done once per transaction. */
1978
1980
1981 sxidtag.xid = xid;
1983 &sxidtag,
1984 HASH_ENTER, &found);
1985 Assert(!found);
1986
1987 /* Initialize the structure. */
1988 sxid->myXact = MySerializableXact;
1990}
1991
1992
1993/*
1994 * Check whether there are any predicate locks held by any transaction
1995 * for the page at the given block number.
1996 *
1997 * Note that the transaction may be completed but not yet subject to
1998 * cleanup due to overlapping serializable transactions. This must
1999 * return valid information regardless of transaction isolation level.
2000 *
2001 * Also note that this doesn't check for a conflicting relation lock,
2002 * just a lock specifically on the given page.
2003 *
2004 * One use is to support proper behavior during GiST index vacuum.
2005 */
2006bool
2030
2031
2032/*
2033 * Check whether a particular lock is held by this transaction.
2034 *
2035 * Important note: this function may return false even if the lock is
2036 * being held, because it uses the local lock table which is not
2037 * updated if another transaction modifies our lock list (e.g. to
2038 * split an index page). It can also return true when a coarser
2039 * granularity lock that covers this target is being held. Be careful
2040 * to only use this function in circumstances where such errors are
2041 * acceptable!
2042 */
2043static bool
2045{
2046 LOCALPREDICATELOCK *lock;
2047
2048 /* check local hash table */
2050 targettag,
2051 HASH_FIND, NULL);
2052
2053 if (!lock)
2054 return false;
2055
2056 /*
2057 * Found entry in the table, but still need to check whether it's actually
2058 * held -- it could just be a parent of some held lock.
2059 */
2060 return lock->held;
2061}
2062
2063/*
2064 * Return the parent lock tag in the lock hierarchy: the next coarser
2065 * lock that covers the provided tag.
2066 *
2067 * Returns true and sets *parent to the parent tag if one exists,
2068 * returns false if none exists.
2069 */
2070static bool
2072 PREDICATELOCKTARGETTAG *parent)
2073{
2074 switch (GET_PREDICATELOCKTARGETTAG_TYPE(*tag))
2075 {
2077 /* relation locks have no parent lock */
2078 return false;
2079
2080 case PREDLOCKTAG_PAGE:
2081 /* parent lock is relation lock */
2085
2086 return true;
2087
2088 case PREDLOCKTAG_TUPLE:
2089 /* parent lock is page lock */
2094 return true;
2095 }
2096
2097 /* not reachable */
2098 Assert(false);
2099 return false;
2100}
2101
2102/*
2103 * Check whether the lock we are considering is already covered by a
2104 * coarser lock for our transaction.
2105 *
2106 * Like PredicateLockExists, this function might return a false
2107 * negative, but it will never return a false positive.
2108 */
2109static bool
2111{
2113 parenttag;
2114
2116
2117 /* check parents iteratively until no more */
2119 {
2122 return true;
2123 }
2124
2125 /* no more parents to check; lock is not covered */
2126 return false;
2127}
2128
2129/*
2130 * Remove the dummy entry from the predicate lock target hash, to free up some
2131 * scratch space. The caller must be holding SerializablePredicateListLock,
2132 * and must restore the entry with RestoreScratchTarget() before releasing the
2133 * lock.
2134 *
2135 * If lockheld is true, the caller is already holding the partition lock
2136 * of the partition containing the scratch entry.
2137 */
2138static void
2155
2156/*
2157 * Re-insert the dummy entry in predicate lock target hash.
2158 */
2159static void
2176
2177/*
2178 * Check whether the list of related predicate locks is empty for a
2179 * predicate lock target, and remove the target if it is.
2180 */
2181static void
2183{
2185
2187
2188 /* Can't remove it until no locks at this target. */
2189 if (!dlist_is_empty(&target->predicateLocks))
2190 return;
2191
2192 /* Actually remove the target. */
2194 &target->tag,
2196 HASH_REMOVE, NULL);
2197 Assert(rmtarget == target);
2198}
2199
2200/*
2201 * Delete child target locks owned by this process.
2202 * This implementation is assuming that the usage of each target tag field
2203 * is uniform. No need to make this hard if we don't have to.
2204 *
2205 * We acquire an LWLock in the case of parallel mode, because worker
2206 * backends have access to the leader's SERIALIZABLEXACT. Otherwise,
2207 * we aren't acquiring LWLocks for the predicate lock or lock
2208 * target structures associated with this transaction unless we're going
2209 * to modify them, because no other process is permitted to modify our
2210 * locks.
2211 */
2212static void
2214{
2217 dlist_mutable_iter iter;
2218
2221 if (IsInParallelMode())
2222 LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
2223
2224 dlist_foreach_modify(iter, &sxact->predicateLocks)
2225 {
2229
2230 predlock = dlist_container(PREDICATELOCK, xactLink, iter.cur);
2231
2232 oldlocktag = predlock->tag;
2233 Assert(oldlocktag.myXact == sxact);
2234 oldtarget = oldlocktag.myTarget;
2235 oldtargettag = oldtarget->tag;
2236
2238 {
2242
2245
2247
2248 dlist_delete(&predlock->xactLink);
2249 dlist_delete(&predlock->targetLink);
2252 &oldlocktag,
2255 HASH_REMOVE, NULL);
2257
2259
2261
2263 }
2264 }
2265 if (IsInParallelMode())
2266 LWLockRelease(&sxact->perXactPredicateListLock);
2268}
2269
2270/*
2271 * Returns the promotion limit for a given predicate lock target. This is the
2272 * max number of descendant locks allowed before promoting to the specified
2273 * tag. Note that the limit includes non-direct descendants (e.g., both tuples
2274 * and pages for a relation lock).
2275 *
2276 * Currently the default limit is 2 for a page lock, and half of the value of
2277 * max_pred_locks_per_transaction - 1 for a relation lock, to match behavior
2278 * of earlier releases when upgrading.
2279 *
2280 * TODO SSI: We should probably add additional GUCs to allow a maximum ratio
2281 * of page and tuple locks based on the pages in a relation, and the maximum
2282 * ratio of tuple locks to tuples in a page. This would provide more
2283 * generally "balanced" allocation of locks to where they are most useful,
2284 * while still allowing the absolute numbers to prevent one relation from
2285 * tying up all predicate lock resources.
2286 */
2287static int
2289{
2290 switch (GET_PREDICATELOCKTARGETTAG_TYPE(*tag))
2291 {
2297
2298 case PREDLOCKTAG_PAGE:
2300
2301 case PREDLOCKTAG_TUPLE:
2302
2303 /*
2304 * not reachable: nothing is finer-granularity than a tuple, so we
2305 * should never try to promote to it.
2306 */
2307 Assert(false);
2308 return 0;
2309 }
2310
2311 /* not reachable */
2312 Assert(false);
2313 return 0;
2314}
2315
2316/*
2317 * For all ancestors of a newly-acquired predicate lock, increment
2318 * their child count in the parent hash table. If any of them have
2319 * more descendants than their promotion threshold, acquire the
2320 * coarsest such lock.
2321 *
2322 * Returns true if a parent lock was acquired and false otherwise.
2323 */
2324static bool
2326{
2328 nexttag,
2331 bool found,
2332 promote;
2333
2334 promote = false;
2335
2336 targettag = *reqtag;
2337
2338 /* check parents iteratively */
2340 {
2343 &targettag,
2344 HASH_ENTER,
2345 &found);
2346 if (!found)
2347 {
2348 parentlock->held = false;
2349 parentlock->childLocks = 1;
2350 }
2351 else
2352 parentlock->childLocks++;
2353
2354 if (parentlock->childLocks >
2356 {
2357 /*
2358 * We should promote to this parent lock. Continue to check its
2359 * ancestors, however, both to get their child counts right and to
2360 * check whether we should just go ahead and promote to one of
2361 * them.
2362 */
2364 promote = true;
2365 }
2366 }
2367
2368 if (promote)
2369 {
2370 /* acquire coarsest ancestor eligible for promotion */
2372 return true;
2373 }
2374 else
2375 return false;
2376}
2377
2378/*
2379 * When releasing a lock, decrement the child count on all ancestor
2380 * locks.
2381 *
2382 * This is called only when releasing a lock via
2383 * DeleteChildTargetLocks (i.e. when a lock becomes redundant because
2384 * we've acquired its parent, possibly due to promotion) or when a new
2385 * MVCC write lock makes the predicate lock unnecessary. There's no
2386 * point in calling it when locks are released at transaction end, as
2387 * this information is no longer needed.
2388 */
2389static void
2391{
2393 nexttag;
2394
2396
2398 {
2402
2408 HASH_FIND, NULL);
2409
2410 /*
2411 * There's a small chance the parent lock doesn't exist in the lock
2412 * table. This can happen if we prematurely removed it because an
2413 * index split caused the child refcount to be off.
2414 */
2415 if (parentlock == NULL)
2416 continue;
2417
2418 parentlock->childLocks--;
2419
2420 /*
2421 * Under similar circumstances the parent lock's refcount might be
2422 * zero. This only happens if we're holding that lock (otherwise we
2423 * would have removed the entry).
2424 */
2425 if (parentlock->childLocks < 0)
2426 {
2427 Assert(parentlock->held);
2428 parentlock->childLocks = 0;
2429 }
2430
2431 if ((parentlock->childLocks == 0) && (!parentlock->held))
2432 {
2436 HASH_REMOVE, NULL);
2438 }
2439 }
2440}
2441
2442/*
2443 * Indicate that a predicate lock on the given target is held by the
2444 * specified transaction. Has no effect if the lock is already held.
2445 *
2446 * This updates the lock table and the sxact's lock list, and creates
2447 * the lock target if necessary, but does *not* do anything related to
2448 * granularity promotion or the local lock table. See
2449 * PredicateLockAcquire for that.
2450 */
2451static void
2455{
2456 PREDICATELOCKTARGET *target;
2457 PREDICATELOCKTAG locktag;
2458 PREDICATELOCK *lock;
2460 bool found;
2461
2463
2465 if (IsInParallelMode())
2466 LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
2468
2469 /* Make sure that the target is represented. */
2470 target = (PREDICATELOCKTARGET *)
2473 HASH_ENTER_NULL, &found);
2474 if (!target)
2475 ereport(ERROR,
2477 errmsg("out of shared memory"),
2478 errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
2479 if (!found)
2480 dlist_init(&target->predicateLocks);
2481
2482 /* We've got the sxact and target, make sure they're joined. */
2483 locktag.myTarget = target;
2484 locktag.myXact = sxact;
2485 lock = (PREDICATELOCK *)
2488 HASH_ENTER_NULL, &found);
2489 if (!lock)
2490 ereport(ERROR,
2492 errmsg("out of shared memory"),
2493 errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
2494
2495 if (!found)
2496 {
2497 dlist_push_tail(&target->predicateLocks, &lock->targetLink);
2498 dlist_push_tail(&sxact->predicateLocks, &lock->xactLink);
2500 }
2501
2503 if (IsInParallelMode())
2504 LWLockRelease(&sxact->perXactPredicateListLock);
2506}
2507
2508/*
2509 * Acquire a predicate lock on the specified target for the current
2510 * connection if not already held. This updates the local lock table
2511 * and uses it to implement granularity promotion. It will consolidate
2512 * multiple locks into a coarser lock if warranted, and will release
2513 * any finer-grained locks covered by the new one.
2514 */
2515static void
2517{
2519 bool found;
2521
2522 /* Do we have the lock already, or a covering lock? */
2524 return;
2525
2527 return;
2528
2529 /* the same hash and LW lock apply to the lock target and the local lock. */
2531
2532 /* Acquire lock in local table */
2536 HASH_ENTER, &found);
2537 locallock->held = true;
2538 if (!found)
2539 locallock->childLocks = 0;
2540
2541 /* Actually create the lock */
2543
2544 /*
2545 * Lock has been acquired. Check whether it should be promoted to a
2546 * coarser granularity, or whether there are finer-granularity locks to
2547 * clean up.
2548 */
2550 {
2551 /*
2552 * Lock request was promoted to a coarser-granularity lock, and that
2553 * lock was acquired. It will delete this lock and any of its
2554 * children, so we're done.
2555 */
2556 }
2557 else
2558 {
2559 /* Clean up any finer-granularity locks */
2562 }
2563}
2564
2565
2566/*
2567 * PredicateLockRelation
2568 *
2569 * Gets a predicate lock at the relation level.
2570 * Skip if not in full serializable transaction isolation level.
2571 * Skip if this is a temporary table.
2572 * Clear any finer-grained predicate locks this session has on the relation.
2573 */
2574void
2576{
2578
2579 if (!SerializationNeededForRead(relation, snapshot))
2580 return;
2581
2583 relation->rd_locator.dbOid,
2584 relation->rd_id);
2586}
2587
2588/*
2589 * PredicateLockPage
2590 *
2591 * Gets a predicate lock at the page level.
2592 * Skip if not in full serializable transaction isolation level.
2593 * Skip if this is a temporary table.
2594 * Skip if a coarser predicate lock already covers this page.
2595 * Clear any finer-grained predicate locks this session has on the relation.
2596 */
2597void
2599{
2601
2602 if (!SerializationNeededForRead(relation, snapshot))
2603 return;
2604
2606 relation->rd_locator.dbOid,
2607 relation->rd_id,
2608 blkno);
2610}
2611
2612/*
2613 * PredicateLockTID
2614 *
2615 * Gets a predicate lock at the tuple level.
2616 * Skip if not in full serializable transaction isolation level.
2617 * Skip if this is a temporary table.
2618 */
2619void
2620PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapshot,
2622{
2624
2625 if (!SerializationNeededForRead(relation, snapshot))
2626 return;
2627
2628 /*
2629 * Return if this xact wrote it.
2630 */
2631 if (relation->rd_index == NULL)
2632 {
2633 /* If we wrote it; we already have a write lock. */
2635 return;
2636 }
2637
2638 /*
2639 * Do quick-but-not-definitive test for a relation lock first. This will
2640 * never cause a return when the relation is *not* locked, but will
2641 * occasionally let the check continue when there really *is* a relation
2642 * level lock.
2643 */
2645 relation->rd_locator.dbOid,
2646 relation->rd_id);
2647 if (PredicateLockExists(&tag))
2648 return;
2649
2651 relation->rd_locator.dbOid,
2652 relation->rd_id,
2656}
2657
2658
2659/*
2660 * DeleteLockTarget
2661 *
2662 * Remove a predicate lock target along with any locks held for it.
2663 *
2664 * Caller must hold SerializablePredicateListLock and the
2665 * appropriate hash partition lock for the target.
2666 */
2667static void
2669{
2670 dlist_mutable_iter iter;
2671
2673 LW_EXCLUSIVE));
2675
2677
2678 dlist_foreach_modify(iter, &target->predicateLocks)
2679 {
2681 dlist_container(PREDICATELOCK, targetLink, iter.cur);
2682 bool found;
2683
2684 dlist_delete(&(predlock->xactLink));
2685 dlist_delete(&(predlock->targetLink));
2686
2689 &predlock->tag,
2692 HASH_REMOVE, &found);
2693 Assert(found);
2694 }
2696
2697 /* Remove the target itself, if possible. */
2699}
2700
2701
2702/*
2703 * TransferPredicateLocksToNewTarget
2704 *
2705 * Move or copy all the predicate locks for a lock target, for use by
2706 * index page splits/combines and other things that create or replace
2707 * lock targets. If 'removeOld' is true, the old locks and the target
2708 * will be removed.
2709 *
2710 * Returns true on success, or false if we ran out of shared memory to
2711 * allocate the new target or locks. Guaranteed to always succeed if
2712 * removeOld is set (by using the scratch entry in PredicateLockTargetHash
2713 * for scratch space).
2714 *
2715 * Warning: the "removeOld" option should be used only with care,
2716 * because this function does not (indeed, can not) update other
2717 * backends' LocalPredicateLockHash. If we are only adding new
2718 * entries, this is not a problem: the local lock table is used only
2719 * as a hint, so missing entries for locks that are held are
2720 * OK. Having entries for locks that are no longer held, as can happen
2721 * when using "removeOld", is not in general OK. We can only use it
2722 * safely when replacing a lock with a coarser-granularity lock that
2723 * covers it, or if we are absolutely certain that no one will need to
2724 * refer to that lock in the future.
2725 *
2726 * Caller must hold SerializablePredicateListLock exclusively.
2727 */
2728static bool
2731 bool removeOld)
2732{
2738 bool found;
2739 bool outOfShmem = false;
2740
2742 LW_EXCLUSIVE));
2743
2748
2749 if (removeOld)
2750 {
2751 /*
2752 * Remove the dummy entry to give us scratch space, so we know we'll
2753 * be able to create the new lock target.
2754 */
2755 RemoveScratchTarget(false);
2756 }
2757
2758 /*
2759 * We must get the partition locks in ascending sequence to avoid
2760 * deadlocks. If old and new partitions are the same, we must request the
2761 * lock only once.
2762 */
2764 {
2768 }
2770 {
2774 }
2775 else
2777
2778 /*
2779 * Look for the old target. If not found, that's OK; no predicate locks
2780 * are affected, so we can just clean up and return. If it does exist,
2781 * walk its list of predicate locks and move or copy them to the new
2782 * target.
2783 */
2785 &oldtargettag,
2787 HASH_FIND, NULL);
2788
2789 if (oldtarget)
2790 {
2793 dlist_mutable_iter iter;
2794
2796 &newtargettag,
2798 HASH_ENTER_NULL, &found);
2799
2800 if (!newtarget)
2801 {
2802 /* Failed to allocate due to insufficient shmem */
2803 outOfShmem = true;
2804 goto exit;
2805 }
2806
2807 /* If we created a new entry, initialize it */
2808 if (!found)
2809 dlist_init(&newtarget->predicateLocks);
2810
2811 newpredlocktag.myTarget = newtarget;
2812
2813 /*
2814 * Loop through all the locks on the old target, replacing them with
2815 * locks on the new target.
2816 */
2818
2819 dlist_foreach_modify(iter, &oldtarget->predicateLocks)
2820 {
2822 dlist_container(PREDICATELOCK, targetLink, iter.cur);
2825
2826 newpredlocktag.myXact = oldpredlock->tag.myXact;
2827
2828 if (removeOld)
2829 {
2830 dlist_delete(&(oldpredlock->xactLink));
2831 dlist_delete(&(oldpredlock->targetLink));
2832
2835 &oldpredlock->tag,
2838 HASH_REMOVE, &found);
2839 Assert(found);
2840 }
2841
2848 &found);
2849 if (!newpredlock)
2850 {
2851 /* Out of shared memory. Undo what we've done so far. */
2854 outOfShmem = true;
2855 goto exit;
2856 }
2857 if (!found)
2858 {
2859 dlist_push_tail(&(newtarget->predicateLocks),
2860 &(newpredlock->targetLink));
2861 dlist_push_tail(&(newpredlocktag.myXact->predicateLocks),
2862 &(newpredlock->xactLink));
2863 newpredlock->commitSeqNo = oldCommitSeqNo;
2864 }
2865 else
2866 {
2867 if (newpredlock->commitSeqNo < oldCommitSeqNo)
2868 newpredlock->commitSeqNo = oldCommitSeqNo;
2869 }
2870
2871 Assert(newpredlock->commitSeqNo != 0);
2872 Assert((newpredlock->commitSeqNo == InvalidSerCommitSeqNo)
2873 || (newpredlock->tag.myXact == OldCommittedSxact));
2874 }
2876
2877 if (removeOld)
2878 {
2879 Assert(dlist_is_empty(&oldtarget->predicateLocks));
2881 }
2882 }
2883
2884
2885exit:
2886 /* Release partition locks in reverse order of acquisition. */
2888 {
2891 }
2893 {
2896 }
2897 else
2899
2900 if (removeOld)
2901 {
2902 /* We shouldn't run out of memory if we're moving locks */
2904
2905 /* Put the scratch entry back */
2906 RestoreScratchTarget(false);
2907 }
2908
2909 return !outOfShmem;
2910}
2911
2912/*
2913 * Drop all predicate locks of any granularity from the specified relation,
2914 * which can be a heap relation or an index relation. If 'transfer' is true,
2915 * acquire a relation lock on the heap for any transactions with any lock(s)
2916 * on the specified relation.
2917 *
2918 * This requires grabbing a lot of LW locks and scanning the entire lock
2919 * target table for matches. That makes this more expensive than most
2920 * predicate lock management functions, but it will only be called for DDL
2921 * type commands that are expensive anyway, and there are fast returns when
2922 * no serializable transactions are active or the relation is temporary.
2923 *
2924 * We don't use the TransferPredicateLocksToNewTarget function because it
2925 * acquires its own locks on the partitions of the two targets involved,
2926 * and we'll already be holding all partition locks.
2927 *
2928 * We can't throw an error from here, because the call could be from a
2929 * transaction which is not serializable.
2930 *
2931 * NOTE: This is currently only called with transfer set to true, but that may
2932 * change. If we decide to clean up the locks from a table on commit of a
2933 * transaction which executed DROP TABLE, the false condition will be useful.
2934 */
2935static void
2937{
2941 Oid dbId;
2942 Oid relId;
2943 Oid heapId;
2944 int i;
2945 bool isIndex;
2946 bool found;
2948
2949 /*
2950 * Bail out quickly if there are no serializable transactions running.
2951 * It's safe to check this without taking locks because the caller is
2952 * holding an ACCESS EXCLUSIVE lock on the relation. No new locks which
2953 * would matter here can be acquired while that is held.
2954 */
2956 return;
2957
2958 if (!PredicateLockingNeededForRelation(relation))
2959 return;
2960
2961 dbId = relation->rd_locator.dbOid;
2962 relId = relation->rd_id;
2963 if (relation->rd_index == NULL)
2964 {
2965 isIndex = false;
2966 heapId = relId;
2967 }
2968 else
2969 {
2970 isIndex = true;
2971 heapId = relation->rd_index->indrelid;
2972 }
2974 Assert(transfer || !isIndex); /* index OID only makes sense with
2975 * transfer */
2976
2977 /* Retrieve first time needed, then keep. */
2979 heaptarget = NULL;
2980
2981 /* Acquire locks on all lock partitions */
2983 for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
2986
2987 /*
2988 * Remove the dummy entry to give us scratch space, so we know we'll be
2989 * able to create the new lock target.
2990 */
2991 if (transfer)
2992 RemoveScratchTarget(true);
2993
2994 /* Scan through target map */
2996
2998 {
2999 dlist_mutable_iter iter;
3000
3001 /*
3002 * Check whether this is a target which needs attention.
3003 */
3005 continue; /* wrong relation id */
3006 if (GET_PREDICATELOCKTARGETTAG_DB(oldtarget->tag) != dbId)
3007 continue; /* wrong database id */
3008 if (transfer && !isIndex
3010 continue; /* already the right lock */
3011
3012 /*
3013 * If we made it here, we have work to do. We make sure the heap
3014 * relation lock exists, then we walk the list of predicate locks for
3015 * the old target we found, moving all locks to the heap relation lock
3016 * -- unless they already hold that.
3017 */
3018
3019 /*
3020 * First make sure we have the heap relation target. We only need to
3021 * do this once.
3022 */
3023 if (transfer && heaptarget == NULL)
3024 {
3026
3032 HASH_ENTER, &found);
3033 if (!found)
3034 dlist_init(&heaptarget->predicateLocks);
3035 }
3036
3037 /*
3038 * Loop through all the locks on the old target, replacing them with
3039 * locks on the new target.
3040 */
3041 dlist_foreach_modify(iter, &oldtarget->predicateLocks)
3042 {
3044 dlist_container(PREDICATELOCK, targetLink, iter.cur);
3048
3049 /*
3050 * Remove the old lock first. This avoids the chance of running
3051 * out of lock structure entries for the hash table.
3052 */
3054 oldXact = oldpredlock->tag.myXact;
3055
3056 dlist_delete(&(oldpredlock->xactLink));
3057
3058 /*
3059 * No need for retail delete from oldtarget list, we're removing
3060 * the whole target anyway.
3061 */
3063 &oldpredlock->tag,
3064 HASH_REMOVE, &found);
3065 Assert(found);
3066
3067 if (transfer)
3068 {
3070
3072 newpredlocktag.myXact = oldXact;
3078 HASH_ENTER,
3079 &found);
3080 if (!found)
3081 {
3082 dlist_push_tail(&(heaptarget->predicateLocks),
3083 &(newpredlock->targetLink));
3084 dlist_push_tail(&(newpredlocktag.myXact->predicateLocks),
3085 &(newpredlock->xactLink));
3086 newpredlock->commitSeqNo = oldCommitSeqNo;
3087 }
3088 else
3089 {
3090 if (newpredlock->commitSeqNo < oldCommitSeqNo)
3091 newpredlock->commitSeqNo = oldCommitSeqNo;
3092 }
3093
3094 Assert(newpredlock->commitSeqNo != 0);
3095 Assert((newpredlock->commitSeqNo == InvalidSerCommitSeqNo)
3096 || (newpredlock->tag.myXact == OldCommittedSxact));
3097 }
3098 }
3099
3101 &found);
3102 Assert(found);
3103 }
3104
3105 /* Put the scratch entry back */
3106 if (transfer)
3108
3109 /* Release locks in reverse order */
3111 for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
3114}
3115
3116/*
3117 * TransferPredicateLocksToHeapRelation
3118 * For all transactions, transfer all predicate locks for the given
3119 * relation to a single relation lock on the heap.
3120 */
3121void
3126
3127
3128/*
3129 * PredicateLockPageSplit
3130 *
3131 * Copies any predicate locks for the old page to the new page.
3132 * Skip if this is a temporary table or toast table.
3133 *
3134 * NOTE: A page split (or overflow) affects all serializable transactions,
3135 * even if it occurs in the context of another transaction isolation level.
3136 *
3137 * NOTE: This currently leaves the local copy of the locks without
3138 * information on the new lock which is in shared memory. This could cause
3139 * problems if enough page splits occur on locked pages without the processes
3140 * which hold the locks getting in and noticing.
3141 */
3142void
3145{
3148 bool success;
3149
3150 /*
3151 * Bail out quickly if there are no serializable transactions running.
3152 *
3153 * It's safe to do this check without taking any additional locks. Even if
3154 * a serializable transaction starts concurrently, we know it can't take
3155 * any SIREAD locks on the page being split because the caller is holding
3156 * the associated buffer page lock. Memory reordering isn't an issue; the
3157 * memory barrier in the LWLock acquisition guarantees that this read
3158 * occurs while the buffer page lock is held.
3159 */
3161 return;
3162
3163 if (!PredicateLockingNeededForRelation(relation))
3164 return;
3165
3169
3171 relation->rd_locator.dbOid,
3172 relation->rd_id,
3173 oldblkno);
3175 relation->rd_locator.dbOid,
3176 relation->rd_id,
3177 newblkno);
3178
3180
3181 /*
3182 * Try copying the locks over to the new page's tag, creating it if
3183 * necessary.
3184 */
3187 false);
3188
3189 if (!success)
3190 {
3191 /*
3192 * No more predicate lock entries are available. Failure isn't an
3193 * option here, so promote the page lock to a relation lock.
3194 */
3195
3196 /* Get the parent relation lock's lock tag */
3198 &newtargettag);
3199 Assert(success);
3200
3201 /*
3202 * Move the locks to the parent. This shouldn't fail.
3203 *
3204 * Note that here we are removing locks held by other backends,
3205 * leading to a possible inconsistency in their local lock hash table.
3206 * This is OK because we're replacing it with a lock that covers the
3207 * old one.
3208 */
3211 true);
3212 Assert(success);
3213 }
3214
3216}
3217
3218/*
3219 * PredicateLockPageCombine
3220 *
3221 * Combines predicate locks for two existing pages.
3222 * Skip if this is a temporary table or toast table.
3223 *
3224 * NOTE: A page combine affects all serializable transactions, even if it
3225 * occurs in the context of another transaction isolation level.
3226 */
3227void
3230{
3231 /*
3232 * Page combines differ from page splits in that we ought to be able to
3233 * remove the locks on the old page after transferring them to the new
3234 * page, instead of duplicating them. However, because we can't edit other
3235 * backends' local lock tables, removing the old lock would leave them
3236 * with an entry in their LocalPredicateLockHash for a lock they're not
3237 * holding, which isn't acceptable. So we wind up having to do the same
3238 * work as a page split, acquiring a lock on the new page and keeping the
3239 * old page locked too. That can lead to some false positives, but should
3240 * be rare in practice.
3241 */
3243}
3244
3245/*
3246 * Walk the list of in-progress serializable transactions and find the new
3247 * xmin.
3248 */
3249static void
3284
3285/*
3286 * ReleasePredicateLocks
3287 *
3288 * Releases predicate locks based on completion of the current transaction,
3289 * whether committed or rolled back. It can also be called for a read only
3290 * transaction when it becomes impossible for the transaction to become
3291 * part of a dangerous structure.
3292 *
3293 * We do nothing unless this is a serializable transaction.
3294 *
3295 * This method must ensure that shared memory hash tables are cleaned
3296 * up in some relatively timely fashion.
3297 *
3298 * If this transaction is committing and is holding any predicate locks,
3299 * it must be added to a list of completed serializable transactions still
3300 * holding locks.
3301 *
3302 * If isReadOnlySafe is true, then predicate locks are being released before
3303 * the end of the transaction because MySerializableXact has been determined
3304 * to be RO_SAFE. In non-parallel mode we can release it completely, but it
3305 * in parallel mode we partially release the SERIALIZABLEXACT and keep it
3306 * around until the end of the transaction, allowing each backend to clear its
3307 * MySerializableXact variable and benefit from the optimization in its own
3308 * time.
3309 */
3310void
3312{
3313 bool partiallyReleasing = false;
3314 bool needToClear;
3316 dlist_mutable_iter iter;
3317
3318 /*
3319 * We can't trust XactReadOnly here, because a transaction which started
3320 * as READ WRITE can show as READ ONLY later, e.g., within
3321 * subtransactions. We want to flag a transaction as READ ONLY if it
3322 * commits without writing so that de facto READ ONLY transactions get the
3323 * benefit of some RO optimizations, so we will use this local variable to
3324 * get some cleanup logic right which is based on whether the transaction
3325 * was declared READ ONLY at the top level.
3326 */
3328
3329 /* We can't be both committing and releasing early due to RO_SAFE. */
3331
3332 /* Are we at the end of a transaction, that is, a commit or abort? */
3333 if (!isReadOnlySafe)
3334 {
3335 /*
3336 * Parallel workers mustn't release predicate locks at the end of
3337 * their transaction. The leader will do that at the end of its
3338 * transaction.
3339 */
3340 if (IsParallelWorker())
3341 {
3343 return;
3344 }
3345
3346 /*
3347 * By the time the leader in a parallel query reaches end of
3348 * transaction, it has waited for all workers to exit.
3349 */
3351
3352 /*
3353 * If the leader in a parallel query earlier stashed a partially
3354 * released SERIALIZABLEXACT for final clean-up at end of transaction
3355 * (because workers might still have been accessing it), then it's
3356 * time to restore it.
3357 */
3359 {
3364 }
3365 }
3366
3368 {
3370 return;
3371 }
3372
3374
3375 /*
3376 * If the transaction is committing, but it has been partially released
3377 * already, then treat this as a roll back. It was marked as rolled back.
3378 */
3380 isCommit = false;
3381
3382 /*
3383 * If we're called in the middle of a transaction because we discovered
3384 * that the SXACT_FLAG_RO_SAFE flag was set, then we'll partially release
3385 * it (that is, release the predicate locks and conflicts, but not the
3386 * SERIALIZABLEXACT itself) if we're the first backend to have noticed.
3387 */
3389 {
3390 /*
3391 * The leader needs to stash a pointer to it, so that it can
3392 * completely release it at end-of-transaction.
3393 */
3394 if (!IsParallelWorker())
3396
3397 /*
3398 * The first backend to reach this condition will partially release
3399 * the SERIALIZABLEXACT. All others will just clear their
3400 * backend-local state so that they stop doing SSI checks for the rest
3401 * of the transaction.
3402 */
3404 {
3407 return;
3408 }
3409 else
3410 {
3412 partiallyReleasing = true;
3413 /* ... and proceed to perform the partial release below. */
3414 }
3415 }
3421
3422 /* may not be serializable during COMMIT/ROLLBACK PREPARED */
3424
3425 /* We'd better not already be on the cleanup list. */
3427
3429
3430 /*
3431 * We don't hold XidGenLock lock here, assuming that TransactionId is
3432 * atomic!
3433 *
3434 * If this value is changing, we don't care that much whether we get the
3435 * old or new value -- it is just used to determine how far
3436 * SxactGlobalXmin must advance before this transaction can be fully
3437 * cleaned up. The worst that could happen is we wait for one more
3438 * transaction to complete before freeing some RAM; correctness of visible
3439 * behavior is not affected.
3440 */
3442
3443 /*
3444 * If it's not a commit it's either a rollback or a read-only transaction
3445 * flagged SXACT_FLAG_RO_SAFE, and we can clear our locks immediately.
3446 */
3447 if (isCommit)
3448 {
3451 /* Recognize implicit read-only transaction (commit without write). */
3452 if (!MyXactDidWrite)
3454 }
3455 else
3456 {
3457 /*
3458 * The DOOMED flag indicates that we intend to roll back this
3459 * transaction and so it should not cause serialization failures for
3460 * other transactions that conflict with it. Note that this flag might
3461 * already be set, if another backend marked this transaction for
3462 * abort.
3463 *
3464 * The ROLLED_BACK flag further indicates that ReleasePredicateLocks
3465 * has been called, and so the SerializableXact is eligible for
3466 * cleanup. This means it should not be considered when calculating
3467 * SxactGlobalXmin.
3468 */
3471
3472 /*
3473 * If the transaction was previously prepared, but is now failing due
3474 * to a ROLLBACK PREPARED or (hopefully very rare) error after the
3475 * prepare, clear the prepared flag. This simplifies conflict
3476 * checking.
3477 */
3479 }
3480
3482 {
3484 if (--(PredXact->WritableSxactCount) == 0)
3485 {
3486 /*
3487 * Release predicate locks and rw-conflicts in for all committed
3488 * transactions. There are no longer any transactions which might
3489 * conflict with the locks and no chance for new transactions to
3490 * overlap. Similarly, existing conflicts in can't cause pivots,
3491 * and any conflicts in which could have completed a dangerous
3492 * structure would already have caused a rollback, so any
3493 * remaining ones must be benign.
3494 */
3496 }
3497 }
3498 else
3499 {
3500 /*
3501 * Read-only transactions: clear the list of transactions that might
3502 * make us unsafe. Note that we use 'inLink' for the iteration as
3503 * opposed to 'outLink' for the r/w xacts.
3504 */
3506 {
3508 dlist_container(RWConflictData, inLink, iter.cur);
3509
3512
3514 }
3515 }
3516
3517 /* Check for conflict out to old committed transactions. */
3518 if (isCommit
3521 {
3522 /*
3523 * we don't know which old committed transaction we conflicted with,
3524 * so be conservative and use FirstNormalSerCommitSeqNo here
3525 */
3529 }
3530
3531 /*
3532 * Release all outConflicts to committed transactions. If we're rolling
3533 * back clear them all. Set SXACT_FLAG_CONFLICT_OUT if any point to
3534 * previously committed transactions.
3535 */
3537 {
3539 dlist_container(RWConflictData, outLink, iter.cur);
3540
3541 if (isCommit
3543 && SxactIsCommitted(conflict->sxactIn))
3544 {
3546 || conflict->sxactIn->prepareSeqNo < MySerializableXact->SeqNo.earliestOutConflictCommit)
3549 }
3550
3551 if (!isCommit
3552 || SxactIsCommitted(conflict->sxactIn)
3553 || (conflict->sxactIn->SeqNo.lastCommitBeforeSnapshot >= PredXact->LastSxactCommitSeqNo))
3555 }
3556
3557 /*
3558 * Release all inConflicts from committed and read-only transactions. If
3559 * we're rolling back, clear them all.
3560 */
3562 {
3564 dlist_container(RWConflictData, inLink, iter.cur);
3565
3566 if (!isCommit
3567 || SxactIsCommitted(conflict->sxactOut)
3568 || SxactIsReadOnly(conflict->sxactOut))
3570 }
3571
3573 {
3574 /*
3575 * Remove ourselves from the list of possible conflicts for concurrent
3576 * READ ONLY transactions, flagging them as unsafe if we have a
3577 * conflict out. If any are waiting DEFERRABLE transactions, wake them
3578 * up if they are known safe or known unsafe.
3579 */
3581 {
3583 dlist_container(RWConflictData, outLink, iter.cur);
3584
3585 roXact = possibleUnsafeConflict->sxactIn;
3588
3589 /* Mark conflicted if necessary. */
3590 if (isCommit
3594 <= roXact->SeqNo.lastCommitBeforeSnapshot))
3595 {
3596 /*
3597 * This releases possibleUnsafeConflict (as well as all other
3598 * possible conflicts for roXact)
3599 */
3601 }
3602 else
3603 {
3605
3606 /*
3607 * If we were the last possible conflict, flag it safe. The
3608 * transaction can now safely release its predicate locks (but
3609 * that transaction's backend has to do that itself).
3610 */
3611 if (dlist_is_empty(&roXact->possibleUnsafeConflicts))
3612 roXact->flags |= SXACT_FLAG_RO_SAFE;
3613 }
3614
3615 /*
3616 * Wake up the process for a waiting DEFERRABLE transaction if we
3617 * now know it's either safe or conflicted.
3618 */
3621 ProcSendSignal(roXact->pgprocno);
3622 }
3623 }
3624
3625 /*
3626 * Check whether it's time to clean up old transactions. This can only be
3627 * done when the last serializable transaction with the oldest xmin among
3628 * serializable transactions completes. We then find the "new oldest"
3629 * xmin and purge any transactions which finished before this transaction
3630 * was launched.
3631 *
3632 * For parallel queries in read-only transactions, it might run twice. We
3633 * only release the reference on the first call.
3634 */
3635 needToClear = false;
3636 if ((partiallyReleasing ||
3640 {
3642 if (--(PredXact->SxactGlobalXminCount) == 0)
3643 {
3645 needToClear = true;
3646 }
3647 }
3648
3650
3652
3653 /* Add this to the list of transactions to check for later cleanup. */
3654 if (isCommit)
3657
3658 /*
3659 * If we're releasing a RO_SAFE transaction in parallel mode, we'll only
3660 * partially release it. That's necessary because other backends may have
3661 * a reference to it. The leader will release the SERIALIZABLEXACT itself
3662 * at the end of the transaction after workers have stopped running.
3663 */
3664 if (!isCommit)
3667 false);
3668
3670
3671 if (needToClear)
3673
3675}
3676
3677static void
3679{
3681 MyXactDidWrite = false;
3682
3683 /* Delete per-transaction lock table */
3685 {
3688 }
3689}
3690
3691/*
3692 * Clear old predicate locks, belonging to committed transactions that are no
3693 * longer interesting to any in-progress transaction.
3694 */
3695static void
3697{
3698 dlist_mutable_iter iter;
3699
3700 /*
3701 * Loop through finished transactions. They are in commit order, so we can
3702 * stop as soon as we find one that's still interesting.
3703 */
3707 {
3709 dlist_container(SERIALIZABLEXACT, finishedLink, iter.cur);
3710
3714 {
3715 /*
3716 * This transaction committed before any in-progress transaction
3717 * took its snapshot. It's no longer interesting.
3718 */
3720 dlist_delete_thoroughly(&finishedSxact->finishedLink);
3723 }
3724 else if (finishedSxact->commitSeqNo > PredXact->HavePartialClearedThrough
3725 && finishedSxact->commitSeqNo <= PredXact->CanPartialClearThrough)
3726 {
3727 /*
3728 * Any active transactions that took their snapshot before this
3729 * transaction committed are read-only, so we can clear part of
3730 * its state.
3731 */
3733
3735 {
3736 /* A read-only transaction can be removed entirely */
3737 dlist_delete_thoroughly(&(finishedSxact->finishedLink));
3739 }
3740 else
3741 {
3742 /*
3743 * A read-write transaction can only be partially cleared. We
3744 * need to keep the SERIALIZABLEXACT but can release the
3745 * SIREAD locks and conflicts in.
3746 */
3748 }
3749
3752 }
3753 else
3754 {
3755 /* Still interesting. */
3756 break;
3757 }
3758 }
3760
3761 /*
3762 * Loop through predicate locks on dummy transaction for summarized data.
3763 */
3766 {
3768 dlist_container(PREDICATELOCK, xactLink, iter.cur);
3770
3772 Assert(predlock->commitSeqNo != 0);
3773 Assert(predlock->commitSeqNo != InvalidSerCommitSeqNo);
3776
3777 /*
3778 * If this lock originally belonged to an old enough transaction, we
3779 * can release it.
3780 */
3782 {
3783 PREDICATELOCKTAG tag;
3784 PREDICATELOCKTARGET *target;
3788
3789 tag = predlock->tag;
3790 target = tag.myTarget;
3791 targettag = target->tag;
3794
3796
3797 dlist_delete(&(predlock->targetLink));
3798 dlist_delete(&(predlock->xactLink));
3799
3803 HASH_REMOVE, NULL);
3805
3807 }
3808 }
3809
3812}
3813
3814/*
3815 * This is the normal way to delete anything from any of the predicate
3816 * locking hash tables. Given a transaction which we know can be deleted:
3817 * delete all predicate locks held by that transaction and any predicate
3818 * lock targets which are now unreferenced by a lock; delete all conflicts
3819 * for the transaction; delete all xid values for the transaction; then
3820 * delete the transaction.
3821 *
3822 * When the partial flag is set, we can release all predicate locks and
3823 * in-conflict information -- we've established that there are no longer
3824 * any overlapping read write transactions for which this transaction could
3825 * matter -- but keep the transaction entry itself and any outConflicts.
3826 *
3827 * When the summarize flag is set, we've run short of room for sxact data
3828 * and must summarize to the SLRU. Predicate locks are transferred to a
3829 * dummy "old" transaction, with duplicate locks on a single target
3830 * collapsing to a single lock with the "latest" commitSeqNo from among
3831 * the conflicting locks..
3832 */
3833static void
3835 bool summarize)
3836{
3838 dlist_mutable_iter iter;
3839
3840 Assert(sxact != NULL);
3842 Assert(partial || !SxactIsOnFinishedList(sxact));
3844
3845 /*
3846 * First release all the predicate locks held by this xact (or transfer
3847 * them to OldCommittedSxact if summarize is true)
3848 */
3850 if (IsInParallelMode())
3851 LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
3852 dlist_foreach_modify(iter, &sxact->predicateLocks)
3853 {
3855 dlist_container(PREDICATELOCK, xactLink, iter.cur);
3856 PREDICATELOCKTAG tag;
3857 PREDICATELOCKTARGET *target;
3861
3862 tag = predlock->tag;
3863 target = tag.myTarget;
3864 targettag = target->tag;
3867
3869
3870 dlist_delete(&predlock->targetLink);
3871
3875 HASH_REMOVE, NULL);
3876 if (summarize)
3877 {
3878 bool found;
3879
3880 /* Fold into dummy transaction list. */
3885 HASH_ENTER_NULL, &found);
3886 if (!predlock)
3887 ereport(ERROR,
3889 errmsg("out of shared memory"),
3890 errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
3891 if (found)
3892 {
3893 Assert(predlock->commitSeqNo != 0);
3894 Assert(predlock->commitSeqNo != InvalidSerCommitSeqNo);
3895 if (predlock->commitSeqNo < sxact->commitSeqNo)
3896 predlock->commitSeqNo = sxact->commitSeqNo;
3897 }
3898 else
3899 {
3901 &predlock->targetLink);
3903 &predlock->xactLink);
3904 predlock->commitSeqNo = sxact->commitSeqNo;
3905 }
3906 }
3907 else
3909
3911 }
3912
3913 /*
3914 * Rather than retail removal, just re-init the head after we've run
3915 * through the list.
3916 */
3917 dlist_init(&sxact->predicateLocks);
3918
3919 if (IsInParallelMode())
3920 LWLockRelease(&sxact->perXactPredicateListLock);
3922
3923 sxidtag.xid = sxact->topXid;
3925
3926 /* Release all outConflicts (unless 'partial' is true) */
3927 if (!partial)
3928 {
3929 dlist_foreach_modify(iter, &sxact->outConflicts)
3930 {
3932 dlist_container(RWConflictData, outLink, iter.cur);
3933
3934 if (summarize)
3935 conflict->sxactIn->flags |= SXACT_FLAG_SUMMARY_CONFLICT_IN;
3937 }
3938 }
3939
3940 /* Release all inConflicts. */
3941 dlist_foreach_modify(iter, &sxact->inConflicts)
3942 {
3944 dlist_container(RWConflictData, inLink, iter.cur);
3945
3946 if (summarize)
3947 conflict->sxactOut->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
3949 }
3950
3951 /* Finally, get rid of the xid and the record of the transaction itself. */
3952 if (!partial)
3953 {
3954 if (sxidtag.xid != InvalidTransactionId)
3957 }
3958
3960}
3961
3962/*
3963 * Tests whether the given top level transaction is concurrent with
3964 * (overlaps) our current transaction.
3965 *
3966 * We need to identify the top level transaction for SSI, anyway, so pass
3967 * that to this function to save the overhead of checking the snapshot's
3968 * subxip array.
3969 */
3970static bool
3972{
3973 Snapshot snap;
3974
3977
3979
3980 if (TransactionIdPrecedes(xid, snap->xmin))
3981 return false;
3982
3983 if (TransactionIdFollowsOrEquals(xid, snap->xmax))
3984 return true;
3985
3986 return pg_lfind32(xid, snap->xip, snap->xcnt);
3987}
3988
3989bool
3991{
3992 if (!SerializationNeededForRead(relation, snapshot))
3993 return false;
3994
3995 /* Check if someone else has already decided that we need to die */
3997 {
3998 ereport(ERROR,
4000 errmsg("could not serialize access due to read/write dependencies among transactions"),
4001 errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict out checking."),
4002 errhint("The transaction might succeed if retried.")));
4003 }
4004
4005 return true;
4006}
4007
4008/*
4009 * CheckForSerializableConflictOut
4010 * A table AM is reading a tuple that has been modified. If it determines
4011 * that the tuple version it is reading is not visible to us, it should
4012 * pass in the top level xid of the transaction that created it.
4013 * Otherwise, if it determines that it is visible to us but it has been
4014 * deleted or there is a newer version available due to an update, it
4015 * should pass in the top level xid of the modifying transaction.
4016 *
4017 * This function will check for overlap with our own transaction. If the given
4018 * xid is also serializable and the transactions overlap (i.e., they cannot see
4019 * each other's writes), then we have a conflict out.
4020 */
4021void
4023{
4027
4028 if (!SerializationNeededForRead(relation, snapshot))
4029 return;
4030
4031 /* Check if someone else has already decided that we need to die */
4033 {
4034 ereport(ERROR,
4036 errmsg("could not serialize access due to read/write dependencies among transactions"),
4037 errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict out checking."),
4038 errhint("The transaction might succeed if retried.")));
4039 }
4041
4043 return;
4044
4045 /*
4046 * Find sxact or summarized info for the top level xid.
4047 */
4048 sxidtag.xid = xid;
4050 sxid = (SERIALIZABLEXID *)
4052 if (!sxid)
4053 {
4054 /*
4055 * Transaction not found in "normal" SSI structures. Check whether it
4056 * got pushed out to SLRU storage for "old committed" transactions.
4057 */
4059
4061 if (conflictCommitSeqNo != 0)
4062 {
4067 ereport(ERROR,
4069 errmsg("could not serialize access due to read/write dependencies among transactions"),
4070 errdetail_internal("Reason code: Canceled on conflict out to old pivot %u.", xid),
4071 errhint("The transaction might succeed if retried.")));
4072
4075 ereport(ERROR,
4077 errmsg("could not serialize access due to read/write dependencies among transactions"),
4078 errdetail_internal("Reason code: Canceled on identification as a pivot, with conflict out to old committed transaction %u.", xid),
4079 errhint("The transaction might succeed if retried.")));
4080
4082 }
4083
4084 /* It's not serializable or otherwise not important. */
4086 return;
4087 }
4088 sxact = sxid->myXact;
4089 Assert(TransactionIdEquals(sxact->topXid, xid));
4091 {
4092 /* Can't conflict with ourself or a transaction that will roll back. */
4094 return;
4095 }
4096
4097 /*
4098 * We have a conflict out to a transaction which has a conflict out to a
4099 * summarized transaction. That summarized transaction must have
4100 * committed first, and we can't tell when it committed in relation to our
4101 * snapshot acquisition, so something needs to be canceled.
4102 */
4104 {
4105 if (!SxactIsPrepared(sxact))
4106 {
4107 sxact->flags |= SXACT_FLAG_DOOMED;
4109 return;
4110 }
4111 else
4112 {
4114 ereport(ERROR,
4116 errmsg("could not serialize access due to read/write dependencies among transactions"),
4117 errdetail_internal("Reason code: Canceled on conflict out to old pivot."),
4118 errhint("The transaction might succeed if retried.")));
4119 }
4120 }
4121
4122 /*
4123 * If this is a read-only transaction and the writing transaction has
4124 * committed, and it doesn't have a rw-conflict to a transaction which
4125 * committed before it, no conflict.
4126 */
4131 || MySerializableXact->SeqNo.lastCommitBeforeSnapshot < sxact->SeqNo.earliestOutConflictCommit))
4132 {
4133 /* Read-only transaction will appear to run first. No conflict. */
4135 return;
4136 }
4137
4138 if (!XidIsConcurrent(xid))
4139 {
4140 /* This write was already in our snapshot; no conflict. */
4142 return;
4143 }
4144
4146 {
4147 /* We don't want duplicate conflict records in the list. */
4149 return;
4150 }
4151
4152 /*
4153 * Flag the conflict. But first, if this conflict creates a dangerous
4154 * structure, ereport an error.
4155 */
4158}
4159
4160/*
4161 * Check a particular target for rw-dependency conflict in. A subroutine of
4162 * CheckForSerializableConflictIn().
4163 */
4164static void
4166{
4169 PREDICATELOCKTARGET *target;
4172 dlist_mutable_iter iter;
4173
4175
4176 /*
4177 * The same hash and LW lock apply to the lock target and the lock itself.
4178 */
4182 target = (PREDICATELOCKTARGET *)
4185 HASH_FIND, NULL);
4186 if (!target)
4187 {
4188 /* Nothing has this target locked; we're done here. */
4190 return;
4191 }
4192
4193 /*
4194 * Each lock for an overlapping transaction represents a conflict: a
4195 * rw-dependency in to this transaction.
4196 */
4198
4199 dlist_foreach_modify(iter, &target->predicateLocks)
4200 {
4202 dlist_container(PREDICATELOCK, targetLink, iter.cur);
4203 SERIALIZABLEXACT *sxact = predlock->tag.myXact;
4204
4206 {
4207 /*
4208 * If we're getting a write lock on a tuple, we don't need a
4209 * predicate (SIREAD) lock on the same tuple. We can safely remove
4210 * our SIREAD lock, but we'll defer doing so until after the loop
4211 * because that requires upgrading to an exclusive partition lock.
4212 *
4213 * We can't use this optimization within a subtransaction because
4214 * the subtransaction could roll back, and we would be left
4215 * without any lock at the top level.
4216 */
4217 if (!IsSubTransaction()
4219 {
4221 mypredlocktag = predlock->tag;
4222 }
4223 }
4224 else if (!SxactIsDoomed(sxact)
4227 sxact->finishedBefore))
4229 {
4232
4233 /*
4234 * Re-check after getting exclusive lock because the other
4235 * transaction may have flagged a conflict.
4236 */
4237 if (!SxactIsDoomed(sxact)
4240 sxact->finishedBefore))
4242 {
4244 }
4245
4248 }
4249 }
4252
4253 /*
4254 * If we found one of our own SIREAD locks to remove, remove it now.
4255 *
4256 * At this point our transaction already has a RowExclusiveLock on the
4257 * relation, so we are OK to drop the predicate lock on the tuple, if
4258 * found, without fearing that another write against the tuple will occur
4259 * before the MVCC information makes it to the buffer.
4260 */
4261 if (mypredlock != NULL)
4262 {
4265
4267 if (IsInParallelMode())
4271
4272 /*
4273 * Remove the predicate lock from shared memory, if it wasn't removed
4274 * while the locks were released. One way that could happen is from
4275 * autovacuum cleaning up an index.
4276 */
4283 HASH_FIND, NULL);
4284 if (rmpredlock != NULL)
4285 {
4287
4288 dlist_delete(&(mypredlock->targetLink));
4289 dlist_delete(&(mypredlock->xactLink));
4290
4295 HASH_REMOVE, NULL);
4297
4299 }
4300
4303 if (IsInParallelMode())
4306
4307 if (rmpredlock != NULL)
4308 {
4309 /*
4310 * Remove entry in local lock table if it exists. It's OK if it
4311 * doesn't exist; that means the lock was transferred to a new
4312 * target by a different backend.
4313 */
4316 HASH_REMOVE, NULL);
4317
4319 }
4320 }
4321}
4322
4323/*
4324 * CheckForSerializableConflictIn
4325 * We are writing the given tuple. If that indicates a rw-conflict
4326 * in from another serializable transaction, take appropriate action.
4327 *
4328 * Skip checking for any granularity for which a parameter is missing.
4329 *
4330 * A tuple update or delete is in conflict if we have a predicate lock
4331 * against the relation or page in which the tuple exists, or against the
4332 * tuple itself.
4333 */
4334void
4336{
4338
4339 if (!SerializationNeededForWrite(relation))
4340 return;
4341
4342 /* Check if someone else has already decided that we need to die */
4344 ereport(ERROR,
4346 errmsg("could not serialize access due to read/write dependencies among transactions"),
4347 errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict in checking."),
4348 errhint("The transaction might succeed if retried.")));
4349
4350 /*
4351 * We're doing a write which might cause rw-conflicts now or later.
4352 * Memorize that fact.
4353 */
4354 MyXactDidWrite = true;
4355
4356 /*
4357 * It is important that we check for locks from the finest granularity to
4358 * the coarsest granularity, so that granularity promotion doesn't cause
4359 * us to miss a lock. The new (coarser) lock will be acquired before the
4360 * old (finer) locks are released.
4361 *
4362 * It is not possible to take and hold a lock across the checks for all
4363 * granularities because each target could be in a separate partition.
4364 */
4365 if (tid != NULL)
4366 {
4368 relation->rd_locator.dbOid,
4369 relation->rd_id,
4373 }
4374
4375 if (blkno != InvalidBlockNumber)
4376 {
4378 relation->rd_locator.dbOid,
4379 relation->rd_id,
4380 blkno);
4382 }
4383
4385 relation->rd_locator.dbOid,
4386 relation->rd_id);
4388}
4389
4390/*
4391 * CheckTableForSerializableConflictIn
4392 * The entire table is going through a DDL-style logical mass delete
4393 * like TRUNCATE or DROP TABLE. If that causes a rw-conflict in from
4394 * another serializable transaction, take appropriate action.
4395 *
4396 * While these operations do not operate entirely within the bounds of
4397 * snapshot isolation, they can occur inside a serializable transaction, and
4398 * will logically occur after any reads which saw rows which were destroyed
4399 * by these operations, so we do what we can to serialize properly under
4400 * SSI.
4401 *
4402 * The relation passed in must be a heap relation. Any predicate lock of any
4403 * granularity on the heap will cause a rw-conflict in to this transaction.
4404 * Predicate locks on indexes do not matter because they only exist to guard
4405 * against conflicting inserts into the index, and this is a mass *delete*.
4406 * When a table is truncated or dropped, the index will also be truncated
4407 * or dropped, and we'll deal with locks on the index when that happens.
4408 *
4409 * Dropping or truncating a table also needs to drop any existing predicate
4410 * locks on heap tuples or pages, because they're about to go away. This
4411 * should be done before altering the predicate locks because the transaction
4412 * could be rolled back because of a conflict, in which case the lock changes
4413 * are not needed. (At the moment, we don't actually bother to drop the
4414 * existing locks on a dropped or truncated table at the moment. That might
4415 * lead to some false positives, but it doesn't seem worth the trouble.)
4416 */
4417void
4419{
4421 PREDICATELOCKTARGET *target;
4422 Oid dbId;
4423 Oid heapId;
4424 int i;
4425
4426 /*
4427 * Bail out quickly if there are no serializable transactions running.
4428 * It's safe to check this without taking locks because the caller is
4429 * holding an ACCESS EXCLUSIVE lock on the relation. No new locks which
4430 * would matter here can be acquired while that is held.
4431 */
4433 return;
4434
4435 if (!SerializationNeededForWrite(relation))
4436 return;
4437
4438 /*
4439 * We're doing a write which might cause rw-conflicts now or later.
4440 * Memorize that fact.
4441 */
4442 MyXactDidWrite = true;
4443
4444 Assert(relation->rd_index == NULL); /* not an index relation */
4445
4446 dbId = relation->rd_locator.dbOid;
4447 heapId = relation->rd_id;
4448
4450 for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
4453
4454 /* Scan through target list */
4456
4457 while ((target = (PREDICATELOCKTARGET *) hash_seq_search(&seqstat)))
4458 {
4459 dlist_mutable_iter iter;
4460
4461 /*
4462 * Check whether this is a target which needs attention.
4463 */
4465 continue; /* wrong relation id */
4466 if (GET_PREDICATELOCKTARGETTAG_DB(target->tag) != dbId)
4467 continue; /* wrong database id */
4468
4469 /*
4470 * Loop through locks for this target and flag conflicts.
4471 */
4472 dlist_foreach_modify(iter, &target->predicateLocks)
4473 {
4475 dlist_container(PREDICATELOCK, targetLink, iter.cur);
4476
4477 if (predlock->tag.myXact != MySerializableXact
4479 {
4481 }
4482 }
4483 }
4484
4485 /* Release locks in reverse order */
4487 for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
4490}
4491
4492
4493/*
4494 * Flag a rw-dependency between two serializable transactions.
4495 *
4496 * The caller is responsible for ensuring that we have a LW lock on
4497 * the transaction hash table.
4498 */
4499static void
4501{
4502 Assert(reader != writer);
4503
4504 /* First, see if this conflict causes failure. */
4506
4507 /* Actually do the conflict flagging. */
4508 if (reader == OldCommittedSxact)
4510 else if (writer == OldCommittedSxact)
4512 else
4513 SetRWConflict(reader, writer);
4514}
4515
4516/*----------------------------------------------------------------------------
4517 * We are about to add a RW-edge to the dependency graph - check that we don't
4518 * introduce a dangerous structure by doing so, and abort one of the
4519 * transactions if so.
4520 *
4521 * A serialization failure can only occur if there is a dangerous structure
4522 * in the dependency graph:
4523 *
4524 * Tin ------> Tpivot ------> Tout
4525 * rw rw
4526 *
4527 * Furthermore, Tout must commit first.
4528 *
4529 * One more optimization is that if Tin is declared READ ONLY (or commits
4530 * without writing), we can only have a problem if Tout committed before Tin
4531 * acquired its snapshot.
4532 *----------------------------------------------------------------------------
4533 */
4534static void
4537{
4538 bool failure;
4539
4541
4542 failure = false;
4543
4544 /*------------------------------------------------------------------------
4545 * Check for already-committed writer with rw-conflict out flagged
4546 * (conflict-flag on W means that T2 committed before W):
4547 *
4548 * R ------> W ------> T2
4549 * rw rw
4550 *
4551 * That is a dangerous structure, so we must abort. (Since the writer
4552 * has already committed, we must be the reader)
4553 *------------------------------------------------------------------------
4554 */
4557 failure = true;
4558
4559 /*------------------------------------------------------------------------
4560 * Check whether the writer has become a pivot with an out-conflict
4561 * committed transaction (T2), and T2 committed first:
4562 *
4563 * R ------> W ------> T2
4564 * rw rw
4565 *
4566 * Because T2 must've committed first, there is no anomaly if:
4567 * - the reader committed before T2
4568 * - the writer committed before T2
4569 * - the reader is a READ ONLY transaction and the reader was concurrent
4570 * with T2 (= reader acquired its snapshot before T2 committed)
4571 *
4572 * We also handle the case that T2 is prepared but not yet committed
4573 * here. In that case T2 has already checked for conflicts, so if it
4574 * commits first, making the above conflict real, it's too late for it
4575 * to abort.
4576 *------------------------------------------------------------------------
4577 */
4579 failure = true;
4580 else if (!failure)
4581 {
4582 dlist_iter iter;
4583
4584 dlist_foreach(iter, &writer->outConflicts)
4585 {
4587 dlist_container(RWConflictData, outLink, iter.cur);
4588 SERIALIZABLEXACT *t2 = conflict->sxactIn;
4589
4590 if (SxactIsPrepared(t2)
4591 && (!SxactIsCommitted(reader)
4592 || t2->prepareSeqNo <= reader->commitSeqNo)
4594 || t2->prepareSeqNo <= writer->commitSeqNo)
4595 && (!SxactIsReadOnly(reader)
4596 || t2->prepareSeqNo <= reader->SeqNo.lastCommitBeforeSnapshot))
4597 {
4598 failure = true;
4599 break;
4600 }
4601 }
4602 }
4603
4604 /*------------------------------------------------------------------------
4605 * Check whether the reader has become a pivot with a writer
4606 * that's committed (or prepared):
4607 *
4608 * T0 ------> R ------> W
4609 * rw rw
4610 *
4611 * Because W must've committed first for an anomaly to occur, there is no
4612 * anomaly if:
4613 * - T0 committed before the writer
4614 * - T0 is READ ONLY, and overlaps the writer
4615 *------------------------------------------------------------------------
4616 */
4617 if (!failure && SxactIsPrepared(writer) && !SxactIsReadOnly(reader))
4618 {
4619 if (SxactHasSummaryConflictIn(reader))
4620 {
4621 failure = true;
4622 }
4623 else
4624 {
4625 dlist_iter iter;
4626
4627 /*
4628 * The unconstify is needed as we have no const version of
4629 * dlist_foreach().
4630 */
4631 dlist_foreach(iter, &unconstify(SERIALIZABLEXACT *, reader)->inConflicts)
4632 {
4633 const RWConflict conflict =
4634 dlist_container(RWConflictData, inLink, iter.cur);
4635 const SERIALIZABLEXACT *t0 = conflict->sxactOut;
4636
4637 if (!SxactIsDoomed(t0)
4638 && (!SxactIsCommitted(t0)
4639 || t0->commitSeqNo >= writer->prepareSeqNo)
4640 && (!SxactIsReadOnly(t0)
4641 || t0->SeqNo.lastCommitBeforeSnapshot >= writer->prepareSeqNo))
4642 {
4643 failure = true;
4644 break;
4645 }
4646 }
4647 }
4648 }
4649
4650 if (failure)
4651 {
4652 /*
4653 * We have to kill a transaction to avoid a possible anomaly from
4654 * occurring. If the writer is us, we can just ereport() to cause a
4655 * transaction abort. Otherwise we flag the writer for termination,
4656 * causing it to abort when it tries to commit. However, if the writer
4657 * is a prepared transaction, already prepared, we can't abort it
4658 * anymore, so we have to kill the reader instead.
4659 */
4661 {
4663 ereport(ERROR,
4665 errmsg("could not serialize access due to read/write dependencies among transactions"),
4666 errdetail_internal("Reason code: Canceled on identification as a pivot, during write."),
4667 errhint("The transaction might succeed if retried.")));
4668 }
4669 else if (SxactIsPrepared(writer))
4670 {
4672
4673 /* if we're not the writer, we have to be the reader */
4674 Assert(MySerializableXact == reader);
4675 ereport(ERROR,
4677 errmsg("could not serialize access due to read/write dependencies among transactions"),
4678 errdetail_internal("Reason code: Canceled on conflict out to pivot %u, during read.", writer->topXid),
4679 errhint("The transaction might succeed if retried.")));
4680 }
4681 writer->flags |= SXACT_FLAG_DOOMED;
4682 }
4683}
4684
4685/*
4686 * PreCommit_CheckForSerializationFailure
4687 * Check for dangerous structures in a serializable transaction
4688 * at commit.
4689 *
4690 * We're checking for a dangerous structure as each conflict is recorded.
4691 * The only way we could have a problem at commit is if this is the "out"
4692 * side of a pivot, and neither the "in" side nor the pivot has yet
4693 * committed.
4694 *
4695 * If a dangerous structure is found, the pivot (the near conflict) is
4696 * marked for death, because rolling back another transaction might mean
4697 * that we fail without ever making progress. This transaction is
4698 * committing writes, so letting it commit ensures progress. If we
4699 * canceled the far conflict, it might immediately fail again on retry.
4700 */
4701void
4703{
4705
4707 return;
4708
4710
4712
4713 /*
4714 * Check if someone else has already decided that we need to die. Since
4715 * we set our own DOOMED flag when partially releasing, ignore in that
4716 * case.
4717 */
4720 {
4722 ereport(ERROR,
4724 errmsg("could not serialize access due to read/write dependencies among transactions"),
4725 errdetail_internal("Reason code: Canceled on identification as a pivot, during commit attempt."),
4726 errhint("The transaction might succeed if retried.")));
4727 }
4728
4730 {
4733
4734 if (!SxactIsCommitted(nearConflict->sxactOut)
4735 && !SxactIsDoomed(nearConflict->sxactOut))
4736 {
4738
4739 dlist_foreach(far_iter, &nearConflict->sxactOut->inConflicts)
4740 {
4743
4744 if (farConflict->sxactOut == MySerializableXact
4745 || (!SxactIsCommitted(farConflict->sxactOut)
4746 && !SxactIsReadOnly(farConflict->sxactOut)
4747 && !SxactIsDoomed(farConflict->sxactOut)))
4748 {
4749 /*
4750 * Normally, we kill the pivot transaction to make sure we
4751 * make progress if the failing transaction is retried.
4752 * However, we can't kill it if it's already prepared, so
4753 * in that case we commit suicide instead.
4754 */
4755 if (SxactIsPrepared(nearConflict->sxactOut))
4756 {
4758 ereport(ERROR,
4760 errmsg("could not serialize access due to read/write dependencies among transactions"),
4761 errdetail_internal("Reason code: Canceled on commit attempt with conflict in from prepared pivot."),
4762 errhint("The transaction might succeed if retried.")));
4763 }
4764 nearConflict->sxactOut->flags |= SXACT_FLAG_DOOMED;
4765 break;
4766 }
4767 }
4768 }
4769 }
4770
4773
4775}
4776
4777/*------------------------------------------------------------------------*/
4778
4779/*
4780 * Two-phase commit support
4781 */
4782
4783/*
4784 * AtPrepare_Locks
4785 * Do the preparatory work for a PREPARE: make 2PC state file
4786 * records for all predicate locks currently held.
4787 */
4788void
4790{
4793 TwoPhasePredicateXactRecord *xactRecord;
4794 TwoPhasePredicateLockRecord *lockRecord;
4795 dlist_iter iter;
4796
4798 xactRecord = &(record.data.xactRecord);
4799 lockRecord = &(record.data.lockRecord);
4800
4802 return;
4803
4804 /* Generate an xact record for our SERIALIZABLEXACT */
4806 xactRecord->xmin = MySerializableXact->xmin;
4807 xactRecord->flags = MySerializableXact->flags;
4808
4809 /*
4810 * Note that we don't include the list of conflicts in our out in the
4811 * statefile, because new conflicts can be added even after the
4812 * transaction prepares. We'll just make a conservative assumption during
4813 * recovery instead.
4814 */
4815
4817 &record, sizeof(record));
4818
4819 /*
4820 * Generate a lock record for each lock.
4821 *
4822 * To do this, we need to walk the predicate lock list in our sxact rather
4823 * than using the local predicate lock table because the latter is not
4824 * guaranteed to be accurate.
4825 */
4827
4828 /*
4829 * No need to take sxact->perXactPredicateListLock in parallel mode
4830 * because there cannot be any parallel workers running while we are
4831 * preparing a transaction.
4832 */
4834
4835 dlist_foreach(iter, &sxact->predicateLocks)
4836 {
4838 dlist_container(PREDICATELOCK, xactLink, iter.cur);
4839
4841 lockRecord->target = predlock->tag.myTarget->tag;
4842
4844 &record, sizeof(record));
4845 }
4846
4848}
4849
4850/*
4851 * PostPrepare_Locks
4852 * Clean up after successful PREPARE. Unlike the non-predicate
4853 * lock manager, we do not need to transfer locks to a dummy
4854 * PGPROC because our SERIALIZABLEXACT will stay around
4855 * anyway. We only need to clean up our local state.
4856 */
4857void
4874
4875/*
4876 * PredicateLockTwoPhaseFinish
4877 * Release a prepared transaction's predicate locks once it
4878 * commits or aborts.
4879 */
4880void
4882{
4885
4887
4889 sxid = (SERIALIZABLEXID *)
4892
4893 /* xid will not be found if it wasn't a serializable transaction */
4894 if (sxid == NULL)
4895 return;
4896
4897 /* Release its locks */
4898 MySerializableXact = sxid->myXact;
4899 MyXactDidWrite = true; /* conservatively assume that we wrote
4900 * something */
4902}
4903
4904/*
4905 * Re-acquire a predicate lock belonging to a transaction that was prepared.
4906 */
4907void
4909 void *recdata, uint32 len)
4910{
4913
4915
4916 record = (TwoPhasePredicateRecord *) recdata;
4917
4919 (record->type == TWOPHASEPREDICATERECORD_LOCK));
4920
4921 if (record->type == TWOPHASEPREDICATERECORD_XACT)
4922 {
4923 /* Per-transaction record. Set up a SERIALIZABLEXACT. */
4924 TwoPhasePredicateXactRecord *xactRecord;
4928 bool found;
4929
4930 xactRecord = (TwoPhasePredicateXactRecord *) &record->data.xactRecord;
4931
4934 if (!sxact)
4935 ereport(ERROR,
4937 errmsg("out of shared memory")));
4938
4939 /* vxid for a prepared xact is INVALID_PROC_NUMBER/xid; no pid */
4940 sxact->vxid.procNumber = INVALID_PROC_NUMBER;
4941 sxact->vxid.localTransactionId = (LocalTransactionId) xid;
4942 sxact->pid = 0;
4943 sxact->pgprocno = INVALID_PROC_NUMBER;
4944
4945 /* a prepared xact hasn't committed yet */
4946 sxact->prepareSeqNo = RecoverySerCommitSeqNo;
4947 sxact->commitSeqNo = InvalidSerCommitSeqNo;
4948 sxact->finishedBefore = InvalidTransactionId;
4949
4950 sxact->SeqNo.lastCommitBeforeSnapshot = RecoverySerCommitSeqNo;
4951
4952 /*
4953 * Don't need to track this; no transactions running at the time the
4954 * recovered xact started are still active, except possibly other
4955 * prepared xacts and we don't care whether those are RO_SAFE or not.
4956 */
4957 dlist_init(&(sxact->possibleUnsafeConflicts));
4958
4959 dlist_init(&(sxact->predicateLocks));
4960 dlist_node_init(&sxact->finishedLink);
4961
4962 sxact->topXid = xid;
4963 sxact->xmin = xactRecord->xmin;
4964 sxact->flags = xactRecord->flags;
4966 if (!SxactIsReadOnly(sxact))
4967 {
4971 }
4972
4973 /*
4974 * We don't know whether the transaction had any conflicts or not, so
4975 * we'll conservatively assume that it had both a conflict in and a
4976 * conflict out, and represent that with the summary conflict flags.
4977 */
4978 dlist_init(&(sxact->outConflicts));
4979 dlist_init(&(sxact->inConflicts));
4982
4983 /* Register the transaction's xid */
4984 sxidtag.xid = xid;
4986 &sxidtag,
4987 HASH_ENTER, &found);
4988 Assert(sxid != NULL);
4989 Assert(!found);
4990 sxid->myXact = sxact;
4991
4992 /*
4993 * Update global xmin. Note that this is a special case compared to
4994 * registering a normal transaction, because the global xmin might go
4995 * backwards. That's OK, because until recovery is over we're not
4996 * going to complete any transactions or create any non-prepared
4997 * transactions, so there's no danger of throwing away.
4998 */
5001 {
5005 }
5007 {
5010 }
5011
5013 }
5014 else if (record->type == TWOPHASEPREDICATERECORD_LOCK)
5015 {
5016 /* Lock record. Recreate the PREDICATELOCK */
5017 TwoPhasePredicateLockRecord *lockRecord;
5022
5023 lockRecord = (TwoPhasePredicateLockRecord *) &record->data.lockRecord;
5025
5027 sxidtag.xid = xid;
5028 sxid = (SERIALIZABLEXID *)
5031
5032 Assert(sxid != NULL);
5033 sxact = sxid->myXact;
5035
5037 }
5038}
5039
5040/*
5041 * Prepare to share the current SERIALIZABLEXACT with parallel workers.
5042 * Return a handle object that can be used by AttachSerializableXact() in a
5043 * parallel worker.
5044 */
5047{
5048 return MySerializableXact;
5049}
5050
5051/*
5052 * Allow parallel workers to import the leader's SERIALIZABLEXACT.
5053 */
5054void
bool ParallelContextActive(void)
Definition parallel.c:1033
uint32 BlockNumber
Definition block.h:31
#define InvalidBlockNumber
Definition block.h:33
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition block.h:71
#define unconstify(underlying_type, expr)
Definition c.h:1288
#define PG_USED_FOR_ASSERTS_ONLY
Definition c.h:235
#define Assert(condition)
Definition c.h:906
int64_t int64
Definition c.h:576
uint16_t uint16
Definition c.h:578
uint32_t uint32
Definition c.h:579
uint32 LocalTransactionId
Definition c.h:701
uint32 TransactionId
Definition c.h:699
size_t Size
Definition c.h:652
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:952
Size hash_estimate_size(int64 num_entries, Size entrysize)
Definition dynahash.c:783
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:358
void hash_destroy(HTAB *hashp)
Definition dynahash.c:865
void * hash_search_with_hash_value(HTAB *hashp, const void *keyPtr, uint32 hashvalue, HASHACTION action, bool *foundPtr)
Definition dynahash.c:965
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1415
int64 hash_get_num_entries(HTAB *hashp)
Definition dynahash.c:1336
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1380
int errcode(int sqlerrcode)
Definition elog.c:874
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
int errhint(const char *fmt,...) pg_attribute_printf(1
int errdetail(const char *fmt,...) pg_attribute_printf(1
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define DEBUG2
Definition elog.h:29
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
#define palloc_object(type)
Definition fe_memutils.h:74
#define palloc_array(type, count)
Definition fe_memutils.h:76
int MyProcPid
Definition globals.c:47
ProcNumber MyProcNumber
Definition globals.c:90
bool IsUnderPostmaster
Definition globals.c:120
int MaxBackends
Definition globals.c:146
int serializable_buffers
Definition globals.c:165
#define newval
GucSource
Definition guc.h:112
@ HASH_FIND
Definition hsearch.h:113
@ HASH_REMOVE
Definition hsearch.h:115
@ HASH_ENTER
Definition hsearch.h:114
@ HASH_ENTER_NULL
Definition hsearch.h:116
#define HASH_ELEM
Definition hsearch.h:95
#define HASH_FUNCTION
Definition hsearch.h:98
#define HASH_BLOBS
Definition hsearch.h:97
#define HASH_FIXED_SIZE
Definition hsearch.h:105
#define HASH_PARTITION
Definition hsearch.h:92
static dlist_node * dlist_pop_head_node(dlist_head *head)
Definition ilist.h:450
#define dlist_foreach(iter, lhead)
Definition ilist.h:623
static void dlist_init(dlist_head *head)
Definition ilist.h:314
#define dlist_head_element(type, membername, lhead)
Definition ilist.h:603
static void dlist_delete_thoroughly(dlist_node *node)
Definition ilist.h:416
static void dlist_delete(dlist_node *node)
Definition ilist.h:405
#define dlist_foreach_modify(iter, lhead)
Definition ilist.h:640
static bool dlist_is_empty(const dlist_head *head)
Definition ilist.h:336
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition ilist.h:364
static void dlist_node_init(dlist_node *node)
Definition ilist.h:325
#define dlist_container(type, membername, ptr)
Definition ilist.h:593
#define IsParallelWorker()
Definition parallel.h:62
FILE * output
long val
Definition informix.c:689
static bool success
Definition initdb.c:187
int i
Definition isn.c:77
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition itemptr.h:124
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition itemptr.h:103
#define GET_VXID_FROM_PGPROC(vxid_dst, proc)
Definition lock.h:79
#define SetInvalidVirtualTransactionId(vxid)
Definition lock.h:76
bool LWLockHeldByMe(LWLock *lock)
Definition lwlock.c:1912
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1177
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1956
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1794
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition lwlock.c:699
@ LW_SHARED
Definition lwlock.h:113
@ LW_EXCLUSIVE
Definition lwlock.h:112
#define NUM_PREDICATELOCK_PARTITIONS
Definition lwlock.h:99
#define InvalidPid
Definition miscadmin.h:32
static char * errmsg
#define SLRU_PAGES_PER_SEGMENT
const void size_t len
const void * data
static bool pg_lfind32(uint32 key, const uint32 *base, uint32 nelem)
Definition pg_lfind.h:153
static rewind_source * source
Definition pg_rewind.c:89
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition pgbench.c:77
#define InvalidOid
unsigned int Oid
PredicateLockData * GetPredicateLockStatusData(void)
Definition predicate.c:1446
void CheckPointPredicate(void)
Definition predicate.c:1042
void PredicateLockPageSplit(Relation relation, BlockNumber oldblkno, BlockNumber newblkno)
Definition predicate.c:3143
static void DecrementParentLocks(const PREDICATELOCKTARGETTAG *targettag)
Definition predicate.c:2390
static HTAB * PredicateLockHash
Definition predicate.c:399
static void SetPossibleUnsafeConflict(SERIALIZABLEXACT *roXact, SERIALIZABLEXACT *activeXact)
Definition predicate.c:667
#define PredicateLockTargetTagHashCode(predicatelocktargettag)
Definition predicate.c:304
static void SetNewSxactGlobalXmin(void)
Definition predicate.c:3250
void CheckForSerializableConflictIn(Relation relation, const ItemPointerData *tid, BlockNumber blkno)
Definition predicate.c:4335
#define SerialPage(xid)
Definition predicate.c:344
static void ReleasePredXact(SERIALIZABLEXACT *sxact)
Definition predicate.c:597
void SetSerializableTransactionSnapshot(Snapshot snapshot, VirtualTransactionId *sourcevxid, int sourcepid)
Definition predicate.c:1721
static bool RWConflictExists(const SERIALIZABLEXACT *reader, const SERIALIZABLEXACT *writer)
Definition predicate.c:611
static bool PredicateLockingNeededForRelation(Relation relation)
Definition predicate.c:499
static bool SerializationNeededForRead(Relation relation, Snapshot snapshot)
Definition predicate.c:517
static Snapshot GetSafeSnapshot(Snapshot origSnapshot)
Definition predicate.c:1557
#define SxactIsCommitted(sxact)
Definition predicate.c:278
static SerialControl serialControl
Definition predicate.c:355
void PredicateLockPage(Relation relation, BlockNumber blkno, Snapshot snapshot)
Definition predicate.c:2598
#define SxactIsROUnsafe(sxact)
Definition predicate.c:293
static Snapshot GetSerializableTransactionSnapshotInt(Snapshot snapshot, VirtualTransactionId *sourcevxid, int sourcepid)
Definition predicate.c:1763
static LWLock * ScratchPartitionLock
Definition predicate.c:409
static void PredicateLockAcquire(const PREDICATELOCKTARGETTAG *targettag)
Definition predicate.c:2516
#define SxactIsDeferrableWaiting(sxact)
Definition predicate.c:291
static void ReleasePredicateLocksLocal(void)
Definition predicate.c:3678
static HTAB * LocalPredicateLockHash
Definition predicate.c:415
int max_predicate_locks_per_page
Definition predicate.c:374
struct SerialControlData * SerialControl
Definition predicate.c:353
static PredXactList PredXact
Definition predicate.c:385
static void SetRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
Definition predicate.c:644
int GetSafeSnapshotBlockingPids(int blocked_pid, int *output, int output_size)
Definition predicate.c:1627
static uint32 ScratchTargetTagHash
Definition predicate.c:408
static void RemoveTargetIfNoLongerUsed(PREDICATELOCKTARGET *target, uint32 targettaghash)
Definition predicate.c:2182
static uint32 predicatelock_hash(const void *key, Size keysize)
Definition predicate.c:1420
void CheckForSerializableConflictOut(Relation relation, TransactionId xid, Snapshot snapshot)
Definition predicate.c:4022
#define SxactIsReadOnly(sxact)
Definition predicate.c:282
#define SerialNextPage(page)
Definition predicate.c:338
static void DropAllPredicateLocksFromTable(Relation relation, bool transfer)
Definition predicate.c:2936
bool PageIsPredicateLocked(Relation relation, BlockNumber blkno)
Definition predicate.c:2007
static SlruCtlData SerialSlruCtlData
Definition predicate.c:325
static void CreatePredicateLock(const PREDICATELOCKTARGETTAG *targettag, uint32 targettaghash, SERIALIZABLEXACT *sxact)
Definition predicate.c:2452
static void SerialAdd(TransactionId xid, SerCommitSeqNo minConflictCommitSeqNo)
Definition predicate.c:859
static void ClearOldPredicateLocks(void)
Definition predicate.c:3696
#define SxactHasSummaryConflictIn(sxact)
Definition predicate.c:283
static SERIALIZABLEXACT * CreatePredXact(void)
Definition predicate.c:583
static bool GetParentPredicateLockTag(const PREDICATELOCKTARGETTAG *tag, PREDICATELOCKTARGETTAG *parent)
Definition predicate.c:2071
#define PredicateLockHashCodeFromTargetHashCode(predicatelocktag, targethash)
Definition predicate.c:317
static void RestoreScratchTarget(bool lockheld)
Definition predicate.c:2160
#define SerialValue(slotno, xid)
Definition predicate.c:340
static void DeleteChildTargetLocks(const PREDICATELOCKTARGETTAG *newtargettag)
Definition predicate.c:2213
static void DeleteLockTarget(PREDICATELOCKTARGET *target, uint32 targettaghash)
Definition predicate.c:2668
void PredicateLockTwoPhaseFinish(FullTransactionId fxid, bool isCommit)
Definition predicate.c:4881
void predicatelock_twophase_recover(FullTransactionId fxid, uint16 info, void *recdata, uint32 len)
Definition predicate.c:4908
static SERIALIZABLEXACT * OldCommittedSxact
Definition predicate.c:363
#define SxactHasConflictOut(sxact)
Definition predicate.c:290
static bool MyXactDidWrite
Definition predicate.c:423
static int MaxPredicateChildLocks(const PREDICATELOCKTARGETTAG *tag)
Definition predicate.c:2288
static void FlagSxactUnsafe(SERIALIZABLEXACT *sxact)
Definition predicate.c:700
static void SerialInit(void)
Definition predicate.c:807
void CheckTableForSerializableConflictIn(Relation relation)
Definition predicate.c:4418
#define SxactIsPrepared(sxact)
Definition predicate.c:279
void AttachSerializableXact(SerializableXactHandle handle)
Definition predicate.c:5055
SerializableXactHandle ShareSerializableXact(void)
Definition predicate.c:5046
static bool PredicateLockExists(const PREDICATELOCKTARGETTAG *targettag)
Definition predicate.c:2044
static void RemoveScratchTarget(bool lockheld)
Definition predicate.c:2139
#define SxactIsOnFinishedList(sxact)
Definition predicate.c:268
#define SxactIsPartiallyReleased(sxact)
Definition predicate.c:294
static void SerialSetActiveSerXmin(TransactionId xid)
Definition predicate.c:991
static dlist_head * FinishedSerializableTransactions
Definition predicate.c:400
static bool SerializationNeededForWrite(Relation relation)
Definition predicate.c:561
static HTAB * SerializableXidHash
Definition predicate.c:397
static bool CheckAndPromotePredicateLockRequest(const PREDICATELOCKTARGETTAG *reqtag)
Definition predicate.c:2325
void PredicateLockPageCombine(Relation relation, BlockNumber oldblkno, BlockNumber newblkno)
Definition predicate.c:3228
static bool SerialPagePrecedesLogically(int64 page1, int64 page2)
Definition predicate.c:732
static void CheckTargetForConflictsIn(PREDICATELOCKTARGETTAG *targettag)
Definition predicate.c:4165
int max_predicate_locks_per_relation
Definition predicate.c:373
#define SxactIsROSafe(sxact)
Definition predicate.c:292
void PreCommit_CheckForSerializationFailure(void)
Definition predicate.c:4702
void ReleasePredicateLocks(bool isCommit, bool isReadOnlySafe)
Definition predicate.c:3311
static void FlagRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
Definition predicate.c:4500
static const PREDICATELOCKTARGETTAG ScratchTargetTag
Definition predicate.c:407
#define PredicateLockHashPartitionLockByIndex(i)
Definition predicate.c:262
static void OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
Definition predicate.c:4535
static bool CoarserLockCovers(const PREDICATELOCKTARGETTAG *newtargettag)
Definition predicate.c:2110
void PredicateLockRelation(Relation relation, Snapshot snapshot)
Definition predicate.c:2575
static SERIALIZABLEXACT * MySerializableXact
Definition predicate.c:422
void PredicateLockShmemInit(void)
Definition predicate.c:1146
void PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapshot, TransactionId tuple_xid)
Definition predicate.c:2620
Size PredicateLockShmemSize(void)
Definition predicate.c:1358
#define SxactIsDoomed(sxact)
Definition predicate.c:281
#define NPREDICATELOCKTARGETENTS()
Definition predicate.c:265
static SerCommitSeqNo SerialGetMinConflictCommitSeqNo(TransactionId xid)
Definition predicate.c:950
static void SummarizeOldestCommittedSxact(void)
Definition predicate.c:1502
bool check_serial_buffers(int *newval, void **extra, GucSource source)
Definition predicate.c:848
void PostPrepare_PredicateLocks(FullTransactionId fxid)
Definition predicate.c:4858
#define TargetTagIsCoveredBy(covered_target, covering_target)
Definition predicate.c:234
static RWConflictPoolHeader RWConflictPool
Definition predicate.c:391
static void ReleaseRWConflict(RWConflict conflict)
Definition predicate.c:692
static bool TransferPredicateLocksToNewTarget(PREDICATELOCKTARGETTAG oldtargettag, PREDICATELOCKTARGETTAG newtargettag, bool removeOld)
Definition predicate.c:2729
void AtPrepare_PredicateLocks(void)
Definition predicate.c:4789
void RegisterPredicateLockingXid(TransactionId xid)
Definition predicate.c:1958
#define PredicateLockHashPartitionLock(hashcode)
Definition predicate.c:259
#define SERIAL_ENTRIESPERPAGE
Definition predicate.c:331
static bool XidIsConcurrent(TransactionId xid)
Definition predicate.c:3971
static void ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial, bool summarize)
Definition predicate.c:3834
static HTAB * PredicateLockTargetHash
Definition predicate.c:398
bool CheckForSerializableConflictOutNeeded(Relation relation, Snapshot snapshot)
Definition predicate.c:3990
#define SxactIsRolledBack(sxact)
Definition predicate.c:280
static SERIALIZABLEXACT * SavedSerializableXact
Definition predicate.c:432
#define SxactHasSummaryConflictOut(sxact)
Definition predicate.c:284
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition predicate.c:3122
static void CreateLocalPredicateLockHash(void)
Definition predicate.c:1939
#define SerialSlruCtl
Definition predicate.c:327
int max_predicate_locks_per_xact
Definition predicate.c:372
Snapshot GetSerializableTransactionSnapshot(Snapshot snapshot)
Definition predicate.c:1681
void * SerializableXactHandle
Definition predicate.h:34
#define RWConflictDataSize
#define SXACT_FLAG_DEFERRABLE_WAITING
#define SXACT_FLAG_SUMMARY_CONFLICT_IN
@ TWOPHASEPREDICATERECORD_XACT
@ TWOPHASEPREDICATERECORD_LOCK
#define FirstNormalSerCommitSeqNo
#define InvalidSerCommitSeqNo
@ PREDLOCKTAG_RELATION
@ PREDLOCKTAG_PAGE
@ PREDLOCKTAG_TUPLE
#define SXACT_FLAG_CONFLICT_OUT
#define PredXactListDataSize
#define SXACT_FLAG_READ_ONLY
#define SXACT_FLAG_DOOMED
#define GET_PREDICATELOCKTARGETTAG_DB(locktag)
#define GET_PREDICATELOCKTARGETTAG_RELATION(locktag)
#define RWConflictPoolHeaderDataSize
#define InvalidSerializableXact
#define SET_PREDICATELOCKTARGETTAG_PAGE(locktag, dboid, reloid, blocknum)
#define RecoverySerCommitSeqNo
struct RWConflictData * RWConflict
#define GET_PREDICATELOCKTARGETTAG_TYPE(locktag)
#define SET_PREDICATELOCKTARGETTAG_RELATION(locktag, dboid, reloid)
uint64 SerCommitSeqNo
#define SXACT_FLAG_ROLLED_BACK
#define SXACT_FLAG_COMMITTED
#define SXACT_FLAG_RO_UNSAFE
#define SXACT_FLAG_PREPARED
#define SET_PREDICATELOCKTARGETTAG_TUPLE(locktag, dboid, reloid, blocknum, offnum)
#define SXACT_FLAG_PARTIALLY_RELEASED
#define GET_PREDICATELOCKTARGETTAG_PAGE(locktag)
#define SXACT_FLAG_RO_SAFE
#define SXACT_FLAG_SUMMARY_CONFLICT_OUT
#define GET_PREDICATELOCKTARGETTAG_OFFSET(locktag)
static int fb(int x)
Snapshot GetSnapshotData(Snapshot snapshot)
Definition procarray.c:2127
bool ProcArrayInstallImportedXmin(TransactionId xmin, VirtualTransactionId *sourcevxid)
Definition procarray.c:2484
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
#define RelationUsesLocalBuffers(relation)
Definition rel.h:646
bool ShmemAddrIsValid(const void *addr)
Definition shmem.c:265
Size add_size(Size s1, Size s2)
Definition shmem.c:482
Size mul_size(Size s1, Size s2)
Definition shmem.c:497
HTAB * ShmemInitHash(const char *name, int64 init_size, int64 max_size, HASHCTL *infoP, int hash_flags)
Definition shmem.c:323
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:378
void SimpleLruInit(SlruCtl ctl, const char *name, int nslots, int nlsns, const char *subdir, int buffer_tranche_id, int bank_tranche_id, SyncRequestHandler sync_handler, bool long_segment_names)
Definition slru.c:253
int SimpleLruReadPage_ReadOnly(SlruCtl ctl, int64 pageno, TransactionId xid)
Definition slru.c:631
void SimpleLruWriteAll(SlruCtl ctl, bool allow_redirtied)
Definition slru.c:1348
int SimpleLruReadPage(SlruCtl ctl, int64 pageno, bool write_ok, TransactionId xid)
Definition slru.c:528
int SimpleLruZeroPage(SlruCtl ctl, int64 pageno)
Definition slru.c:376
void SimpleLruTruncate(SlruCtl ctl, int64 cutoffPage)
Definition slru.c:1434
Size SimpleLruShmemSize(int nslots, int nlsns)
Definition slru.c:199
bool check_slru_buffers(const char *name, int *newval)
Definition slru.c:356
static LWLock * SimpleLruGetBankLock(SlruCtl ctl, int64 pageno)
Definition slru.h:160
#define SlruPagePrecedesUnitTests(ctl, per_page)
Definition slru.h:185
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
#define IsMVCCSnapshot(snapshot)
Definition snapmgr.h:55
void ProcSendSignal(ProcNumber procNumber)
Definition proc.c:1984
PGPROC * MyProc
Definition proc.c:68
void ProcWaitForSignal(uint32 wait_event_info)
Definition proc.c:1972
Size keysize
Definition hsearch.h:75
HashValueFunc hash
Definition hsearch.h:78
Size entrysize
Definition hsearch.h:76
int64 num_partitions
Definition hsearch.h:68
Definition proc.h:176
SERIALIZABLEXACT * myXact
PREDICATELOCKTARGET * myTarget
PREDICATELOCKTARGETTAG tag
SerCommitSeqNo commitSeqNo
SERIALIZABLEXACT * element
SerCommitSeqNo LastSxactCommitSeqNo
SerCommitSeqNo CanPartialClearThrough
SERIALIZABLEXACT * OldCommittedSxact
SerCommitSeqNo HavePartialClearedThrough
TransactionId SxactGlobalXmin
Form_pg_index rd_index
Definition rel.h:192
Oid rd_id
Definition rel.h:113
RelFileLocator rd_locator
Definition rel.h:57
VirtualTransactionId vxid
SerCommitSeqNo lastCommitBeforeSnapshot
dlist_head possibleUnsafeConflicts
SerCommitSeqNo prepareSeqNo
SerCommitSeqNo commitSeqNo
union SERIALIZABLEXACT::@131 SeqNo
TransactionId finishedBefore
SerCommitSeqNo earliestOutConflictCommit
TransactionId headXid
Definition predicate.c:349
TransactionId tailXid
Definition predicate.c:350
TransactionId xmin
Definition snapshot.h:153
FullTransactionId nextXid
Definition transam.h:220
PREDICATELOCKTARGETTAG target
TwoPhasePredicateRecordType type
TwoPhasePredicateLockRecord lockRecord
union TwoPhasePredicateRecord::@132 data
TwoPhasePredicateXactRecord xactRecord
dlist_node * cur
Definition ilist.h:179
dlist_node * cur
Definition ilist.h:200
@ SYNC_HANDLER_NONE
Definition sync.h:42
static bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition transam.h:297
#define FirstUnpinnedObjectId
Definition transam.h:196
#define InvalidTransactionId
Definition transam.h:31
static bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition transam.h:282
static bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition transam.h:312
#define TransactionIdEquals(id1, id2)
Definition transam.h:43
#define XidFromFullTransactionId(x)
Definition transam.h:48
#define FirstNormalTransactionId
Definition transam.h:34
#define TransactionIdIsValid(xid)
Definition transam.h:41
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition twophase.c:1273
int max_prepared_xacts
Definition twophase.c:117
#define TWOPHASE_RM_PREDICATELOCK_ID
TransamVariablesData * TransamVariables
Definition varsup.c:34
bool XactDeferrable
Definition xact.c:87
bool XactReadOnly
Definition xact.c:84
TransactionId GetTopTransactionIdIfAny(void)
Definition xact.c:443
bool IsSubTransaction(void)
Definition xact.c:5067
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition xact.c:943
bool IsInParallelMode(void)
Definition xact.c:1091
#define IsolationIsSerializable()
Definition xact.h:53
bool RecoveryInProgress(void)
Definition xlog.c:6444