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 * predicate lock reporting
156 * GetPredicateLockStatusData(void)
157 * PageIsPredicateLocked(Relation relation, BlockNumber blkno)
158 *
159 * predicate lock maintenance
160 * GetSerializableTransactionSnapshot(Snapshot snapshot)
161 * SetSerializableTransactionSnapshot(Snapshot snapshot,
162 * VirtualTransactionId *sourcevxid)
163 * RegisterPredicateLockingXid(void)
164 * PredicateLockRelation(Relation relation, Snapshot snapshot)
165 * PredicateLockPage(Relation relation, BlockNumber blkno,
166 * Snapshot snapshot)
167 * PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapshot,
168 * TransactionId tuple_xid)
169 * PredicateLockPageSplit(Relation relation, BlockNumber oldblkno,
170 * BlockNumber newblkno)
171 * PredicateLockPageCombine(Relation relation, BlockNumber oldblkno,
172 * BlockNumber newblkno)
173 * TransferPredicateLocksToHeapRelation(Relation relation)
174 * ReleasePredicateLocks(bool isCommit, bool isReadOnlySafe)
175 *
176 * conflict detection (may also trigger rollback)
177 * CheckForSerializableConflictOut(Relation relation, TransactionId xid,
178 * Snapshot snapshot)
179 * CheckForSerializableConflictIn(Relation relation, const ItemPointerData *tid,
180 * BlockNumber blkno)
181 * CheckTableForSerializableConflictIn(Relation relation)
182 *
183 * final rollback checking
184 * PreCommit_CheckForSerializationFailure(void)
185 *
186 * two-phase commit support
187 * AtPrepare_PredicateLocks(void);
188 * PostPrepare_PredicateLocks(TransactionId xid);
189 * PredicateLockTwoPhaseFinish(FullTransactionId fxid, bool isCommit);
190 * predicatelock_twophase_recover(FullTransactionId fxid, uint16 info,
191 * void *recdata, uint32 len);
192 */
193
194#include "postgres.h"
195
196#include "access/parallel.h"
197#include "access/slru.h"
198#include "access/transam.h"
199#include "access/twophase.h"
200#include "access/twophase_rmgr.h"
201#include "access/xact.h"
202#include "access/xlog.h"
203#include "miscadmin.h"
204#include "pgstat.h"
205#include "port/pg_lfind.h"
206#include "storage/predicate.h"
208#include "storage/proc.h"
209#include "storage/procarray.h"
210#include "storage/shmem.h"
211#include "storage/subsystems.h"
212#include "utils/guc_hooks.h"
213#include "utils/rel.h"
214#include "utils/snapmgr.h"
215#include "utils/wait_event.h"
216
217/* Uncomment the next line to test the graceful degradation code. */
218/* #define TEST_SUMMARIZE_SERIAL */
219
220/*
221 * Test the most selective fields first, for performance.
222 *
223 * a is covered by b if all of the following hold:
224 * 1) a.database = b.database
225 * 2) a.relation = b.relation
226 * 3) b.offset is invalid (b is page-granularity or higher)
227 * 4) either of the following:
228 * 4a) a.offset is valid (a is tuple-granularity) and a.page = b.page
229 * or 4b) a.offset is invalid and b.page is invalid (a is
230 * page-granularity and b is relation-granularity
231 */
232#define TargetTagIsCoveredBy(covered_target, covering_target) \
233 ((GET_PREDICATELOCKTARGETTAG_RELATION(covered_target) == /* (2) */ \
234 GET_PREDICATELOCKTARGETTAG_RELATION(covering_target)) \
235 && (GET_PREDICATELOCKTARGETTAG_OFFSET(covering_target) == \
236 InvalidOffsetNumber) /* (3) */ \
237 && (((GET_PREDICATELOCKTARGETTAG_OFFSET(covered_target) != \
238 InvalidOffsetNumber) /* (4a) */ \
239 && (GET_PREDICATELOCKTARGETTAG_PAGE(covering_target) == \
240 GET_PREDICATELOCKTARGETTAG_PAGE(covered_target))) \
241 || ((GET_PREDICATELOCKTARGETTAG_PAGE(covering_target) == \
242 InvalidBlockNumber) /* (4b) */ \
243 && (GET_PREDICATELOCKTARGETTAG_PAGE(covered_target) \
244 != InvalidBlockNumber))) \
245 && (GET_PREDICATELOCKTARGETTAG_DB(covered_target) == /* (1) */ \
246 GET_PREDICATELOCKTARGETTAG_DB(covering_target)))
247
248/*
249 * The predicate locking target and lock shared hash tables are partitioned to
250 * reduce contention. To determine which partition a given target belongs to,
251 * compute the tag's hash code with PredicateLockTargetTagHashCode(), then
252 * apply one of these macros.
253 * NB: NUM_PREDICATELOCK_PARTITIONS must be a power of 2!
254 */
255#define PredicateLockHashPartition(hashcode) \
256 ((hashcode) % NUM_PREDICATELOCK_PARTITIONS)
257#define PredicateLockHashPartitionLock(hashcode) \
258 (&MainLWLockArray[PREDICATELOCK_MANAGER_LWLOCK_OFFSET + \
259 PredicateLockHashPartition(hashcode)].lock)
260#define PredicateLockHashPartitionLockByIndex(i) \
261 (&MainLWLockArray[PREDICATELOCK_MANAGER_LWLOCK_OFFSET + (i)].lock)
262
263#define NPREDICATELOCKTARGETENTS() \
264 mul_size(max_predicate_locks_per_xact, add_size(MaxBackends, max_prepared_xacts))
265
266#define SxactIsOnFinishedList(sxact) (!dlist_node_is_detached(&(sxact)->finishedLink))
267
268/*
269 * Note that a sxact is marked "prepared" once it has passed
270 * PreCommit_CheckForSerializationFailure, even if it isn't using
271 * 2PC. This is the point at which it can no longer be aborted.
272 *
273 * The PREPARED flag remains set after commit, so SxactIsCommitted
274 * implies SxactIsPrepared.
275 */
276#define SxactIsCommitted(sxact) (((sxact)->flags & SXACT_FLAG_COMMITTED) != 0)
277#define SxactIsPrepared(sxact) (((sxact)->flags & SXACT_FLAG_PREPARED) != 0)
278#define SxactIsRolledBack(sxact) (((sxact)->flags & SXACT_FLAG_ROLLED_BACK) != 0)
279#define SxactIsDoomed(sxact) (((sxact)->flags & SXACT_FLAG_DOOMED) != 0)
280#define SxactIsReadOnly(sxact) (((sxact)->flags & SXACT_FLAG_READ_ONLY) != 0)
281#define SxactHasSummaryConflictIn(sxact) (((sxact)->flags & SXACT_FLAG_SUMMARY_CONFLICT_IN) != 0)
282#define SxactHasSummaryConflictOut(sxact) (((sxact)->flags & SXACT_FLAG_SUMMARY_CONFLICT_OUT) != 0)
283/*
284 * The following macro actually means that the specified transaction has a
285 * conflict out *to a transaction which committed ahead of it*. It's hard
286 * to get that into a name of a reasonable length.
287 */
288#define SxactHasConflictOut(sxact) (((sxact)->flags & SXACT_FLAG_CONFLICT_OUT) != 0)
289#define SxactIsDeferrableWaiting(sxact) (((sxact)->flags & SXACT_FLAG_DEFERRABLE_WAITING) != 0)
290#define SxactIsROSafe(sxact) (((sxact)->flags & SXACT_FLAG_RO_SAFE) != 0)
291#define SxactIsROUnsafe(sxact) (((sxact)->flags & SXACT_FLAG_RO_UNSAFE) != 0)
292#define SxactIsPartiallyReleased(sxact) (((sxact)->flags & SXACT_FLAG_PARTIALLY_RELEASED) != 0)
293
294/*
295 * Compute the hash code associated with a PREDICATELOCKTARGETTAG.
296 *
297 * To avoid unnecessary recomputations of the hash code, we try to do this
298 * just once per function, and then pass it around as needed. Aside from
299 * passing the hashcode to hash_search_with_hash_value(), we can extract
300 * the lock partition number from the hashcode.
301 */
302#define PredicateLockTargetTagHashCode(predicatelocktargettag) \
303 get_hash_value(PredicateLockTargetHash, predicatelocktargettag)
304
305/*
306 * Given a predicate lock tag, and the hash for its target,
307 * compute the lock hash.
308 *
309 * To make the hash code also depend on the transaction, we xor the sxid
310 * struct's address into the hash code, left-shifted so that the
311 * partition-number bits don't change. Since this is only a hash, we
312 * don't care if we lose high-order bits of the address; use an
313 * intermediate variable to suppress cast-pointer-to-int warnings.
314 */
315#define PredicateLockHashCodeFromTargetHashCode(predicatelocktag, targethash) \
316 ((targethash) ^ ((uint32) PointerGetDatum((predicatelocktag)->myXact)) \
317 << LOG2_NUM_PREDICATELOCK_PARTITIONS)
318
319
320/*
321 * The SLRU buffer area through which we access the old xids.
322 */
324static int serial_errdetail_for_io_error(const void *opaque_data);
325
327
328#define SerialSlruCtl (&SerialSlruDesc)
329
330#define SERIAL_PAGESIZE BLCKSZ
331#define SERIAL_ENTRYSIZE sizeof(SerCommitSeqNo)
332#define SERIAL_ENTRIESPERPAGE (SERIAL_PAGESIZE / SERIAL_ENTRYSIZE)
333
334/*
335 * Set maximum pages based on the number needed to track all transactions.
336 */
337#define SERIAL_MAX_PAGE (MaxTransactionId / SERIAL_ENTRIESPERPAGE)
338
339#define SerialNextPage(page) (((page) >= SERIAL_MAX_PAGE) ? 0 : (page) + 1)
340
341#define SerialValue(slotno, xid) (*((SerCommitSeqNo *) \
342 (SerialSlruCtl->shared->page_buffer[slotno] + \
343 ((((uint32) (xid)) % SERIAL_ENTRIESPERPAGE) * SERIAL_ENTRYSIZE))))
344
345#define SerialPage(xid) (((uint32) (xid)) / SERIAL_ENTRIESPERPAGE)
346
347typedef struct SerialControlData
348{
349 int64 headPage; /* newest initialized page */
350 TransactionId headXid; /* newest valid Xid in the SLRU */
351 TransactionId tailXid; /* oldest xmin we might be interested in */
353
355
357
358/*
359 * When the oldest committed transaction on the "finished" list is moved to
360 * SLRU, its predicate locks will be moved to this "dummy" transaction,
361 * collapsing duplicate targets. When a duplicate is found, the later
362 * commitSeqNo is used.
363 */
365
366
367/*
368 * These configuration variables are used to set the predicate lock table size
369 * and to control promotion of predicate locks to coarser granularity in an
370 * attempt to degrade performance (mostly as false positive serialization
371 * failure) gracefully in the face of memory pressure.
372 */
373int max_predicate_locks_per_xact; /* in guc_tables.c */
374int max_predicate_locks_per_relation; /* in guc_tables.c */
375int max_predicate_locks_per_page; /* in guc_tables.c */
376
377/*
378 * This provides a list of objects in order to track transactions
379 * participating in predicate locking. Entries in the list are fixed size,
380 * and reside in shared memory. The memory address of an entry must remain
381 * fixed during its lifetime. The list will be protected from concurrent
382 * update externally; no provision is made in this code to manage that. The
383 * number of entries in the list, and the size allowed for each entry is
384 * fixed upon creation.
385 */
387
388static void PredicateLockShmemRequest(void *arg);
389static void PredicateLockShmemInit(void *arg);
390static void PredicateLockShmemAttach(void *arg);
391
397
398
399/*
400 * This provides a pool of RWConflict data elements to use in conflict lists
401 * between transactions.
402 */
404
405/*
406 * The predicate locking hash tables are in shared memory.
407 * Each backend keeps pointers to them.
408 */
413
414/*
415 * Tag for a dummy entry in PredicateLockTargetHash. By temporarily removing
416 * this entry, you can ensure that there's enough scratch space available for
417 * inserting one entry in the hash table. This is an otherwise-invalid tag.
418 */
419static const PREDICATELOCKTARGETTAG ScratchTargetTag = {0, 0, 0, 0};
422
423/*
424 * The local hash table used to determine when to combine multiple fine-
425 * grained locks into a single courser-grained lock.
426 */
428
429/*
430 * Keep a pointer to the currently-running serializable transaction (if any)
431 * for quick reference. Also, remember if we have written anything that could
432 * cause a rw-conflict.
433 */
435static bool MyXactDidWrite = false;
436
437/*
438 * The SXACT_FLAG_RO_UNSAFE optimization might lead us to release
439 * MySerializableXact early. If that happens in a parallel query, the leader
440 * needs to defer the destruction of the SERIALIZABLEXACT until end of
441 * transaction, because the workers still have a reference to it. In that
442 * case, the leader stores it here.
443 */
445
447
448/* local functions */
449
450static SERIALIZABLEXACT *CreatePredXact(void);
452
453static bool RWConflictExists(const SERIALIZABLEXACT *reader, const SERIALIZABLEXACT *writer);
458
462
463static uint32 predicatelock_hash(const void *key, Size keysize);
464
465static void SummarizeOldestCommittedSxact(void);
469 int sourcepid);
472 PREDICATELOCKTARGETTAG *parent);
474static void RemoveScratchTarget(bool lockheld);
475static void RestoreScratchTarget(bool lockheld);
488 bool removeOld);
490static void DropAllPredicateLocksFromTable(Relation relation,
491 bool transfer);
492static void SetNewSxactGlobalXmin(void);
493static void ClearOldPredicateLocks(void);
494static void ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial,
495 bool summarize);
496static bool XidIsConcurrent(TransactionId xid);
501static void CreateLocalPredicateLockHash(void);
502static void ReleasePredicateLocksLocal(void);
503
504
505/*------------------------------------------------------------------------*/
506
507/*
508 * Does this relation participate in predicate locking? Temporary and system
509 * relations are exempt.
510 */
511static inline bool
513{
514 return !(relation->rd_id < FirstUnpinnedObjectId ||
515 RelationUsesLocalBuffers(relation));
516}
517
518/*
519 * When a public interface method is called for a read, this is the test to
520 * see if we should do a quick return.
521 *
522 * Note: this function has side-effects! If this transaction has been flagged
523 * as RO-safe since the last call, we release all predicate locks and reset
524 * MySerializableXact. That makes subsequent calls to return quickly.
525 *
526 * This is marked as 'inline' to eliminate the function call overhead in the
527 * common case that serialization is not needed.
528 */
529static inline bool
531{
532 /* Nothing to do if this is not a serializable transaction */
534 return false;
535
536 /*
537 * Don't acquire locks or conflict when scanning with a special snapshot.
538 * This excludes things like CLUSTER and REINDEX. They use the wholesale
539 * functions TransferPredicateLocksToHeapRelation() and
540 * CheckTableForSerializableConflictIn() to participate in serialization,
541 * but the scans involved don't need serialization.
542 */
543 if (!IsMVCCSnapshot(snapshot))
544 return false;
545
546 /*
547 * Check if we have just become "RO-safe". If we have, immediately release
548 * all locks as they're not needed anymore. This also resets
549 * MySerializableXact, so that subsequent calls to this function can exit
550 * quickly.
551 *
552 * A transaction is flagged as RO_SAFE if all concurrent R/W transactions
553 * commit without having conflicts out to an earlier snapshot, thus
554 * ensuring that no conflicts are possible for this transaction.
555 */
557 {
558 ReleasePredicateLocks(false, true);
559 return false;
560 }
561
562 /* Check if the relation doesn't participate in predicate locking */
564 return false;
565
566 return true; /* no excuse to skip predicate locking */
567}
568
569/*
570 * Like SerializationNeededForRead(), but called on writes.
571 * The logic is the same, but there is no snapshot and we can't be RO-safe.
572 */
573static inline bool
575{
576 /* Nothing to do if this is not a serializable transaction */
578 return false;
579
580 /* Check if the relation doesn't participate in predicate locking */
582 return false;
583
584 return true; /* no excuse to skip predicate locking */
585}
586
587
588/*------------------------------------------------------------------------*/
589
590/*
591 * These functions are a simple implementation of a list for this specific
592 * type of struct. If there is ever a generalized shared memory list, we
593 * should probably switch to that.
594 */
595static SERIALIZABLEXACT *
608
609static void
617
618/*------------------------------------------------------------------------*/
619
620/*
621 * These functions manage primitive access to the RWConflict pool and lists.
622 */
623static bool
625{
626 dlist_iter iter;
627
628 Assert(reader != writer);
629
630 /* Check the ends of the purported conflict first. */
631 if (SxactIsDoomed(reader)
633 || dlist_is_empty(&reader->outConflicts)
634 || dlist_is_empty(&writer->inConflicts))
635 return false;
636
637 /*
638 * A conflict is possible; walk the list to find out.
639 *
640 * The unconstify is needed as we have no const version of
641 * dlist_foreach().
642 */
643 dlist_foreach(iter, &unconstify(SERIALIZABLEXACT *, reader)->outConflicts)
644 {
646 dlist_container(RWConflictData, outLink, iter.cur);
647
648 if (conflict->sxactIn == writer)
649 return true;
650 }
651
652 /* No conflict found. */
653 return false;
654}
655
656static void
658{
660
661 Assert(reader != writer);
662 Assert(!RWConflictExists(reader, writer));
663
667 errmsg("not enough elements in RWConflictPool to record a read/write conflict"),
668 errhint("You might need to run fewer transactions at a time or increase \"max_connections\".")));
669
671 dlist_delete(&conflict->outLink);
672
673 conflict->sxactOut = reader;
674 conflict->sxactIn = writer;
675 dlist_push_tail(&reader->outConflicts, &conflict->outLink);
676 dlist_push_tail(&writer->inConflicts, &conflict->inLink);
677}
678
679static void
682{
684
688
692 errmsg("not enough elements in RWConflictPool to record a potential read/write conflict"),
693 errhint("You might need to run fewer transactions at a time or increase \"max_connections\".")));
694
696 dlist_delete(&conflict->outLink);
697
698 conflict->sxactOut = activeXact;
699 conflict->sxactIn = roXact;
700 dlist_push_tail(&activeXact->possibleUnsafeConflicts, &conflict->outLink);
701 dlist_push_tail(&roXact->possibleUnsafeConflicts, &conflict->inLink);
702}
703
704static void
711
712static void
714{
716
719
720 sxact->flags |= SXACT_FLAG_RO_UNSAFE;
721
722 /*
723 * We know this isn't a safe snapshot, so we can stop looking for other
724 * potential conflicts.
725 */
726 dlist_foreach_modify(iter, &sxact->possibleUnsafeConflicts)
727 {
729 dlist_container(RWConflictData, inLink, iter.cur);
730
731 Assert(!SxactIsReadOnly(conflict->sxactOut));
732 Assert(sxact == conflict->sxactIn);
733
735 }
736}
737
738/*------------------------------------------------------------------------*/
739
740/*
741 * Decide whether a Serial page number is "older" for truncation purposes.
742 * Analogous to CLOGPagePrecedes().
743 */
744static bool
758
759static int
761{
762 TransactionId xid = *(const TransactionId *) opaque_data;
763
764 return errdetail("Could not access serializable CSN of transaction %u.", xid);
765}
766
767#ifdef USE_ASSERT_CHECKING
768static void
770{
772 offset = per_page / 2;
775 headPage,
778 oldestXact;
779
780 /* GetNewTransactionId() has assigned the last XID it can safely use. */
781 newestPage = 2 * SLRU_PAGES_PER_SEGMENT - 1; /* nothing special */
782 newestXact = newestPage * per_page + offset;
784 oldestXact = newestXact + 1;
785 oldestXact -= 1U << 31;
786 oldestPage = oldestXact / per_page;
787
788 /*
789 * In this scenario, the SLRU headPage pertains to the last ~1000 XIDs
790 * assigned. oldestXact finishes, ~2B XIDs having elapsed since it
791 * started. Further transactions cause us to summarize oldestXact to
792 * tailPage. Function must return false so SerialAdd() doesn't zero
793 * tailPage (which may contain entries for other old, recently-finished
794 * XIDs) and half the SLRU. Reaching this requires burning ~2B XIDs in
795 * single-user mode, a negligible possibility.
796 */
800
801 /*
802 * In this scenario, the SLRU headPage pertains to oldestXact. We're
803 * summarizing an XID near newestXact. (Assume few other XIDs used
804 * SERIALIZABLE, hence the minimal headPage advancement. Assume
805 * oldestXact was long-running and only recently reached the SLRU.)
806 * Function must return true to make SerialAdd() create targetPage.
807 *
808 * Today's implementation mishandles this case, but it doesn't matter
809 * enough to fix. Verify that the defect affects just one page by
810 * asserting correct treatment of its prior page. Reaching this case
811 * requires burning ~2B XIDs in single-user mode, a negligible
812 * possibility. Moreover, if it does happen, the consequence would be
813 * mild, namely a new transaction failing in SimpleLruReadPage().
814 */
818#if 0
820#endif
821}
822#endif
823
824/*
825 * GUC check_hook for serializable_buffers
826 */
827bool
829{
830 return check_slru_buffers("serializable_buffers", newval);
831}
832
833/*
834 * Record a committed read write serializable xid and the minimum
835 * commitSeqNo of any transactions to which this xid had a rw-conflict out.
836 * An invalid commitSeqNo means that there were no conflicts out from xid.
837 */
838static void
840{
843 int slotno;
845 bool isNewPage;
846 LWLock *lock;
847
849
850 targetPage = SerialPage(xid);
852
853 /*
854 * In this routine, we must hold both SerialControlLock and the SLRU bank
855 * lock simultaneously while making the SLRU data catch up with the new
856 * state that we determine.
857 */
859
860 /*
861 * If 'xid' is older than the global xmin (== tailXid), there's no need to
862 * store it, after all. This can happen if the oldest transaction holding
863 * back the global xmin just finished, making 'xid' uninteresting, but
864 * ClearOldPredicateLocks() has not yet run.
865 */
868 {
870 return;
871 }
872
873 /*
874 * If the SLRU is currently unused, zero out the whole active region from
875 * tailXid to headXid before taking it into use. Otherwise zero out only
876 * any new pages that enter the tailXid-headXid range as we advance
877 * headXid.
878 */
879 if (serialControl->headPage < 0)
880 {
882 isNewPage = true;
883 }
884 else
885 {
888 targetPage);
889 }
890
893 serialControl->headXid = xid;
894 if (isNewPage)
896
897 if (isNewPage)
898 {
899 /* Initialize intervening pages; might involve trading locks */
900 for (;;)
901 {
906 break;
908 LWLockRelease(lock);
909 }
910 }
911 else
912 {
915 }
916
918 SerialSlruCtl->shared->page_dirty[slotno] = true;
919
920 LWLockRelease(lock);
922}
923
924/*
925 * Get the minimum commitSeqNo for any conflict out for the given xid. For
926 * a transaction which exists but has no conflict out, InvalidSerCommitSeqNo
927 * will be returned.
928 */
929static SerCommitSeqNo
931{
935 int slotno;
936
938
943
945 return 0;
946
948
951 return 0;
952
953 /*
954 * The following function must be called without holding SLRU bank lock,
955 * but will return with that lock held, which must then be released.
956 */
958 SerialPage(xid), &xid);
959 val = SerialValue(slotno, xid);
961 return val;
962}
963
964/*
965 * Call this whenever there is a new xmin for active serializable
966 * transactions. We don't need to keep information on transactions which
967 * precede that. InvalidTransactionId means none active, so everything in
968 * the SLRU can be discarded.
969 */
970static void
972{
974
975 /*
976 * When no sxacts are active, nothing overlaps, set the xid values to
977 * invalid to show that there are no valid entries. Don't clear headPage,
978 * though. A new xmin might still land on that page, and we don't want to
979 * repeatedly zero out the same page.
980 */
981 if (!TransactionIdIsValid(xid))
982 {
986 return;
987 }
988
989 /*
990 * When we're recovering prepared transactions, the global xmin might move
991 * backwards depending on the order they're recovered. Normally that's not
992 * OK, but during recovery no serializable transactions will commit, so
993 * the SLRU is empty and we can get away with it.
994 */
995 if (RecoveryInProgress())
996 {
1000 {
1001 serialControl->tailXid = xid;
1002 }
1004 return;
1005 }
1006
1009
1010 serialControl->tailXid = xid;
1011
1013}
1014
1015/*
1016 * Perform a checkpoint --- either during shutdown, or on-the-fly
1017 *
1018 * We don't have any data that needs to survive a restart, but this is a
1019 * convenient place to truncate the SLRU.
1020 */
1021void
1023{
1025
1027
1028 /* Exit quickly if the SLRU is currently not in use. */
1029 if (serialControl->headPage < 0)
1030 {
1032 return;
1033 }
1034
1036 {
1038
1040
1041 /*
1042 * It is possible for the tailXid to be ahead of the headXid. This
1043 * occurs if we checkpoint while there are in-progress serializable
1044 * transaction(s) advancing the tail but we are yet to summarize the
1045 * transactions. In this case, we cutoff up to the headPage and the
1046 * next summary will advance the headXid.
1047 */
1049 {
1050 /* We can truncate the SLRU up to the page containing tailXid */
1052 }
1053 else
1055 }
1056 else
1057 {
1058 /*----------
1059 * The SLRU is no longer needed. Truncate to head before we set head
1060 * invalid.
1061 *
1062 * XXX: It's possible that the SLRU is not needed again until XID
1063 * wrap-around has happened, so that the segment containing headPage
1064 * that we leave behind will appear to be new again. In that case it
1065 * won't be removed until XID horizon advances enough to make it
1066 * current again.
1067 *
1068 * XXX: This should happen in vac_truncate_clog(), not in checkpoints.
1069 * Consider this scenario, starting from a system with no in-progress
1070 * transactions and VACUUM FREEZE having maximized oldestXact:
1071 * - Start a SERIALIZABLE transaction.
1072 * - Start, finish, and summarize a SERIALIZABLE transaction, creating
1073 * one SLRU page.
1074 * - Consume XIDs to reach xidStopLimit.
1075 * - Finish all transactions. Due to the long-running SERIALIZABLE
1076 * transaction, earlier checkpoints did not touch headPage. The
1077 * next checkpoint will change it, but that checkpoint happens after
1078 * the end of the scenario.
1079 * - VACUUM to advance XID limits.
1080 * - Consume ~2M XIDs, crossing the former xidWrapLimit.
1081 * - Start, finish, and summarize a SERIALIZABLE transaction.
1082 * SerialAdd() declines to create the targetPage, because headPage
1083 * is not regarded as in the past relative to that targetPage. The
1084 * transaction instigating the summarize fails in
1085 * SimpleLruReadPage().
1086 */
1088 serialControl->headPage = -1;
1089 }
1090
1092
1093 /*
1094 * Truncate away pages that are no longer required. Note that no
1095 * additional locking is required, because this is only called as part of
1096 * a checkpoint, and the validity limits have already been determined.
1097 */
1099
1100 /*
1101 * Write dirty SLRU pages to disk
1102 *
1103 * This is not actually necessary from a correctness point of view. We do
1104 * it merely as a debugging aid.
1105 *
1106 * We're doing this after the truncation to avoid writing pages right
1107 * before deleting the file in which they sit, which would be completely
1108 * pointless.
1109 */
1111}
1112
1113/*------------------------------------------------------------------------*/
1114
1115/*
1116 * PredicateLockShmemRequest -- Register the predicate locking data structures.
1117 */
1118static void
1120{
1124
1125 /*
1126 * Register hash table for PREDICATELOCKTARGET structs. This stores
1127 * per-predicate-lock-target information.
1128 */
1130
1131 ShmemRequestHash(.name = "PREDICATELOCKTARGET hash",
1134 .hash_info.keysize = sizeof(PREDICATELOCKTARGETTAG),
1135 .hash_info.entrysize = sizeof(PREDICATELOCKTARGET),
1136 .hash_info.num_partitions = NUM_PREDICATELOCK_PARTITIONS,
1138 );
1139
1140 /*
1141 * Allocate hash table for PREDICATELOCK structs. This stores per
1142 * xact-lock-of-a-target information.
1143 *
1144 * Assume an average of 2 xacts per target.
1145 */
1147
1148 ShmemRequestHash(.name = "PREDICATELOCK hash",
1149 .nelems = max_predicate_locks,
1150 .ptr = &PredicateLockHash,
1151 .hash_info.keysize = sizeof(PREDICATELOCKTAG),
1152 .hash_info.entrysize = sizeof(PREDICATELOCK),
1153 .hash_info.hash = predicatelock_hash,
1154 .hash_info.num_partitions = NUM_PREDICATELOCK_PARTITIONS,
1156 );
1157
1158 /*
1159 * Compute size for serializable transaction hashtable. Note these
1160 * calculations must agree with PredicateLockShmemSize!
1161 *
1162 * Assume an average of 10 predicate locking transactions per backend.
1163 * This allows aggressive cleanup while detail is present before data must
1164 * be summarized for storage in SLRU and the "dummy" transaction.
1165 */
1167
1168 /*
1169 * Register a list to hold information on transactions participating in
1170 * predicate locking.
1171 */
1172 ShmemRequestStruct(.name = "PredXactList",
1175 sizeof(SERIALIZABLEXACT)))),
1176 .ptr = (void **) &PredXact,
1177 );
1178
1179 /*
1180 * Register hash table for SERIALIZABLEXID structs. This stores per-xid
1181 * information for serializable transactions which have accessed data.
1182 */
1183 ShmemRequestHash(.name = "SERIALIZABLEXID hash",
1184 .nelems = max_serializable_xacts,
1185 .ptr = &SerializableXidHash,
1186 .hash_info.keysize = sizeof(SERIALIZABLEXIDTAG),
1187 .hash_info.entrysize = sizeof(SERIALIZABLEXID),
1188 .hash_flags = HASH_ELEM | HASH_BLOBS | HASH_FIXED_SIZE,
1189 );
1190
1191 /*
1192 * Allocate space for tracking rw-conflicts in lists attached to the
1193 * transactions.
1194 *
1195 * Assume an average of 5 conflicts per transaction. Calculations suggest
1196 * that this will prevent resource exhaustion in even the most pessimal
1197 * loads up to max_connections = 200 with all 200 connections pounding the
1198 * database with serializable transactions. Beyond that, there may be
1199 * occasional transactions canceled when trying to flag conflicts. That's
1200 * probably OK.
1201 */
1203
1204 ShmemRequestStruct(.name = "RWConflictPool",
1207 .ptr = (void **) &RWConflictPool,
1208 );
1209
1210 ShmemRequestStruct(.name = "FinishedSerializableTransactions",
1211 .size = sizeof(dlist_head),
1212 .ptr = (void **) &FinishedSerializableTransactions,
1213 );
1214
1215 /*
1216 * Initialize the SLRU storage for old committed serializable
1217 * transactions.
1218 */
1220 .name = "serializable",
1221 .Dir = "pg_serial",
1222 .long_segment_names = false,
1223
1224 .nslots = serializable_buffers,
1225
1226 .sync_handler = SYNC_HANDLER_NONE,
1227 .PagePrecedes = SerialPagePrecedesLogically,
1228 .errdetail_for_io_error = serial_errdetail_for_io_error,
1229
1230 .buffer_tranche_id = LWTRANCHE_SERIAL_BUFFER,
1231 .bank_tranche_id = LWTRANCHE_SERIAL_SLRU,
1232 );
1233#ifdef USE_ASSERT_CHECKING
1235#endif
1236
1237 ShmemRequestStruct(.name = "SerialControlData",
1238 .size = sizeof(SerialControlData),
1239 .ptr = (void **) &serialControl,
1240 );
1241}
1242
1243static void
1245{
1246 int max_rw_conflicts;
1247 bool found;
1248
1249 /*
1250 * Reserve a dummy entry in the hash table; we use it to make sure there's
1251 * always one entry available when we need to split or combine a page,
1252 * because running out of space there could mean aborting a
1253 * non-serializable transaction.
1254 */
1256 HASH_ENTER, &found);
1257 Assert(!found);
1258
1269 /* Add all elements to available list, clean. */
1270 for (int i = 0; i < max_serializable_xacts; i++)
1271 {
1275 }
1292
1293 /* Initialize the rw-conflict pool */
1297
1299
1300 /* Add all elements to available list, clean. */
1301 for (int i = 0; i < max_rw_conflicts; i++)
1302 {
1305 }
1306
1307 /* Initialize the list of finished serializable transactions */
1309
1310 /* Initialize SerialControl to reflect empty SLRU. */
1312 serialControl->headPage = -1;
1316
1318
1319 /* This never changes, so let's keep a local copy. */
1321
1322 /* Pre-calculate the hash and partition lock of the scratch entry */
1325}
1326
1327static void
1329{
1330 /* This never changes, so let's keep a local copy. */
1332
1333 /* Pre-calculate the hash and partition lock of the scratch entry */
1336}
1337
1338/*
1339 * Compute the hash code associated with a PREDICATELOCKTAG.
1340 *
1341 * Because we want to use just one set of partition locks for both the
1342 * PREDICATELOCKTARGET and PREDICATELOCK hash tables, we have to make sure
1343 * that PREDICATELOCKs fall into the same partition number as their
1344 * associated PREDICATELOCKTARGETs. dynahash.c expects the partition number
1345 * to be the low-order bits of the hash code, and therefore a
1346 * PREDICATELOCKTAG's hash code must have the same low-order bits as the
1347 * associated PREDICATELOCKTARGETTAG's hash code. We achieve this with this
1348 * specialized hash function.
1349 */
1350static uint32
1351predicatelock_hash(const void *key, Size keysize)
1352{
1353 const PREDICATELOCKTAG *predicatelocktag = (const PREDICATELOCKTAG *) key;
1355
1356 Assert(keysize == sizeof(PREDICATELOCKTAG));
1357
1358 /* Look into the associated target object, and compute its hash code */
1360
1362}
1363
1364
1365/*
1366 * GetPredicateLockStatusData
1367 * Return a table containing the internal state of the predicate
1368 * lock manager for use in pg_lock_status.
1369 *
1370 * Like GetLockStatusData, this function tries to hold the partition LWLocks
1371 * for as short a time as possible by returning two arrays that simply
1372 * contain the PREDICATELOCKTARGETTAG and SERIALIZABLEXACT for each lock
1373 * table entry. Multiple copies of the same PREDICATELOCKTARGETTAG and
1374 * SERIALIZABLEXACT will likely appear.
1375 */
1378{
1380 int i;
1381 int els,
1382 el;
1385
1387
1388 /*
1389 * To ensure consistency, take simultaneous locks on all partition locks
1390 * in ascending order, then SerializableXactHashLock.
1391 */
1392 for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
1395
1396 /* Get number of locks and allocate appropriately-sized arrays. */
1398 data->nelements = els;
1401
1402
1403 /* Scan through PredicateLockHash and copy contents */
1405
1406 el = 0;
1407
1409 {
1410 data->locktags[el] = predlock->tag.myTarget->tag;
1411 data->xacts[el] = *predlock->tag.myXact;
1412 el++;
1413 }
1414
1415 Assert(el == els);
1416
1417 /* Release locks in reverse order */
1419 for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
1421
1422 return data;
1423}
1424
1425/*
1426 * Free up shared memory structures by pushing the oldest sxact (the one at
1427 * the front of the SummarizeOldestCommittedSxact queue) into summary form.
1428 * Each call will free exactly one SERIALIZABLEXACT structure and may also
1429 * free one or more of these structures: SERIALIZABLEXID, PREDICATELOCK,
1430 * PREDICATELOCKTARGET, RWConflictData.
1431 */
1432static void
1434{
1436
1438
1439 /*
1440 * This function is only called if there are no sxact slots available.
1441 * Some of them must belong to old, already-finished transactions, so
1442 * there should be something in FinishedSerializableTransactions list that
1443 * we can summarize. However, there's a race condition: while we were not
1444 * holding any locks, a transaction might have ended and cleaned up all
1445 * the finished sxact entries already, freeing up their sxact slots. In
1446 * that case, we have nothing to do here. The caller will find one of the
1447 * slots released by the other backend when it retries.
1448 */
1450 {
1452 return;
1453 }
1454
1455 /*
1456 * Grab the first sxact off the finished list -- this will be the earliest
1457 * commit. Remove it from the list.
1458 */
1461 dlist_delete_thoroughly(&sxact->finishedLink);
1462
1463 /* Add to SLRU summary information. */
1466 ? sxact->SeqNo.earliestOutConflictCommit : InvalidSerCommitSeqNo);
1467
1468 /* Summarize and release the detail. */
1469 ReleaseOneSerializableXact(sxact, false, true);
1470
1472}
1473
1474/*
1475 * GetSafeSnapshot
1476 * Obtain and register a snapshot for a READ ONLY DEFERRABLE
1477 * transaction. Ensures that the snapshot is "safe", i.e. a
1478 * read-only transaction running on it can execute serializably
1479 * without further checks. This requires waiting for concurrent
1480 * transactions to complete, and retrying with a new snapshot if
1481 * one of them could possibly create a conflict.
1482 *
1483 * As with GetSerializableTransactionSnapshot (which this is a subroutine
1484 * for), the passed-in Snapshot pointer should reference a static data
1485 * area that can safely be passed to GetSnapshotData.
1486 */
1487static Snapshot
1489{
1490 Snapshot snapshot;
1491
1493
1494 while (true)
1495 {
1496 /*
1497 * GetSerializableTransactionSnapshotInt is going to call
1498 * GetSnapshotData, so we need to provide it the static snapshot area
1499 * our caller passed to us. The pointer returned is actually the same
1500 * one passed to it, but we avoid assuming that here.
1501 */
1503 NULL, InvalidPid);
1504
1506 return snapshot; /* no concurrent r/w xacts; it's safe */
1507
1509
1510 /*
1511 * Wait for concurrent transactions to finish. Stop early if one of
1512 * them marked us as conflicted.
1513 */
1517 {
1521 }
1523
1525 {
1527 break; /* success */
1528 }
1529
1531
1532 /* else, need to retry... */
1535 errmsg_internal("deferrable snapshot was unsafe; trying a new one")));
1536 ReleasePredicateLocks(false, false);
1537 }
1538
1539 /*
1540 * Now we have a safe snapshot, so we don't need to do any further checks.
1541 */
1543 ReleasePredicateLocks(false, true);
1544
1545 return snapshot;
1546}
1547
1548/*
1549 * GetSafeSnapshotBlockingPids
1550 * If the specified process is currently blocked in GetSafeSnapshot,
1551 * write the process IDs of all processes that it is blocked by
1552 * into the caller-supplied buffer output[]. The list is truncated at
1553 * output_size, and the number of PIDs written into the buffer is
1554 * returned. Returns zero if the given PID is not currently blocked
1555 * in GetSafeSnapshot.
1556 */
1557int
1559{
1560 int num_written = 0;
1561 dlist_iter iter;
1563
1565
1566 /* Find blocked_pid's SERIALIZABLEXACT by linear search. */
1568 {
1570 dlist_container(SERIALIZABLEXACT, xactLink, iter.cur);
1571
1572 if (sxact->pid == blocked_pid)
1573 {
1575 break;
1576 }
1577 }
1578
1579 /* Did we find it, and is it currently waiting in GetSafeSnapshot? */
1581 {
1582 /* Traverse the list of possible unsafe conflicts collecting PIDs. */
1583 dlist_foreach(iter, &blocking_sxact->possibleUnsafeConflicts)
1584 {
1586 dlist_container(RWConflictData, inLink, iter.cur);
1587
1588 output[num_written++] = possibleUnsafeConflict->sxactOut->pid;
1589
1590 if (num_written >= output_size)
1591 break;
1592 }
1593 }
1594
1596
1597 return num_written;
1598}
1599
1600/*
1601 * Acquire a snapshot that can be used for the current transaction.
1602 *
1603 * Make sure we have a SERIALIZABLEXACT reference in MySerializableXact.
1604 * It should be current for this process and be contained in PredXact.
1605 *
1606 * The passed-in Snapshot pointer should reference a static data area that
1607 * can safely be passed to GetSnapshotData. The return value is actually
1608 * always this same pointer; no new snapshot data structure is allocated
1609 * within this function.
1610 */
1613{
1615
1616 /*
1617 * Can't use serializable mode while recovery is still active, as it is,
1618 * for example, on a hot standby. We could get here despite the check in
1619 * check_transaction_isolation() if default_transaction_isolation is set
1620 * to serializable, so phrase the hint accordingly.
1621 */
1622 if (RecoveryInProgress())
1623 ereport(ERROR,
1625 errmsg("cannot use serializable mode in a hot standby"),
1626 errdetail("\"default_transaction_isolation\" is set to \"serializable\"."),
1627 errhint("You can use \"SET default_transaction_isolation = 'repeatable read'\" to change the default.")));
1628
1629 /*
1630 * A special optimization is available for SERIALIZABLE READ ONLY
1631 * DEFERRABLE transactions -- we can wait for a suitable snapshot and
1632 * thereby avoid all SSI overhead once it's running.
1633 */
1635 return GetSafeSnapshot(snapshot);
1636
1638 NULL, InvalidPid);
1639}
1640
1641/*
1642 * Import a snapshot to be used for the current transaction.
1643 *
1644 * This is nearly the same as GetSerializableTransactionSnapshot, except that
1645 * we don't take a new snapshot, but rather use the data we're handed.
1646 *
1647 * The caller must have verified that the snapshot came from a serializable
1648 * transaction; and if we're read-write, the source transaction must not be
1649 * read-only.
1650 */
1651void
1654 int sourcepid)
1655{
1657
1658 /*
1659 * If this is called by parallel.c in a parallel worker, we don't want to
1660 * create a SERIALIZABLEXACT just yet because the leader's
1661 * SERIALIZABLEXACT will be installed with AttachSerializableXact(). We
1662 * also don't want to reject SERIALIZABLE READ ONLY DEFERRABLE in this
1663 * case, because the leader has already determined that the snapshot it
1664 * has passed us is safe. So there is nothing for us to do.
1665 */
1666 if (IsParallelWorker())
1667 return;
1668
1669 /*
1670 * We do not allow SERIALIZABLE READ ONLY DEFERRABLE transactions to
1671 * import snapshots, since there's no way to wait for a safe snapshot when
1672 * we're using the snap we're told to. (XXX instead of throwing an error,
1673 * we could just ignore the XactDeferrable flag?)
1674 */
1676 ereport(ERROR,
1678 errmsg("a snapshot-importing transaction must not be READ ONLY DEFERRABLE")));
1679
1681 sourcepid);
1682}
1683
1684/*
1685 * Guts of GetSerializableTransactionSnapshot
1686 *
1687 * If sourcevxid is valid, this is actually an import operation and we should
1688 * skip calling GetSnapshotData, because the snapshot contents are already
1689 * loaded up. HOWEVER: to avoid race conditions, we must check that the
1690 * source xact is still running after we acquire SerializableXactHashLock.
1691 * We do that by calling ProcArrayInstallImportedXmin.
1692 */
1693static Snapshot
1696 int sourcepid)
1697{
1698 PGPROC *proc;
1701 *othersxact;
1702
1703 /* We only do this for serializable transactions. Once. */
1705
1707
1708 /*
1709 * Since all parts of a serializable transaction must use the same
1710 * snapshot, it is too late to establish one after a parallel operation
1711 * has begun.
1712 */
1713 if (IsInParallelMode())
1714 elog(ERROR, "cannot establish serializable snapshot during a parallel operation");
1715
1716 proc = MyProc;
1717 Assert(proc != NULL);
1718 GET_VXID_FROM_PGPROC(vxid, *proc);
1719
1720 /*
1721 * First we get the sxact structure, which may involve looping and access
1722 * to the "finished" list to free a structure for use.
1723 *
1724 * We must hold SerializableXactHashLock when taking/checking the snapshot
1725 * to avoid race conditions, for much the same reasons that
1726 * GetSnapshotData takes the ProcArrayLock. Since we might have to
1727 * release SerializableXactHashLock to call SummarizeOldestCommittedSxact,
1728 * this means we have to create the sxact first, which is a bit annoying
1729 * (in particular, an elog(ERROR) in procarray.c would cause us to leak
1730 * the sxact). Consider refactoring to avoid this.
1731 */
1732#ifdef TEST_SUMMARIZE_SERIAL
1734#endif
1736 do
1737 {
1739 /* If null, push out committed sxact to SLRU summary & retry. */
1740 if (!sxact)
1741 {
1745 }
1746 } while (!sxact);
1747
1748 /* Get the snapshot, or check that it's safe to use */
1749 if (!sourcevxid)
1750 snapshot = GetSnapshotData(snapshot);
1751 else if (!ProcArrayInstallImportedXmin(snapshot->xmin, sourcevxid))
1752 {
1755 ereport(ERROR,
1757 errmsg("could not import the requested snapshot"),
1758 errdetail("The source process with PID %d is not running anymore.",
1759 sourcepid)));
1760 }
1761
1762 /*
1763 * If there are no serializable transactions which are not read-only, we
1764 * can "opt out" of predicate locking and conflict checking for a
1765 * read-only transaction.
1766 *
1767 * The reason this is safe is that a read-only transaction can only become
1768 * part of a dangerous structure if it overlaps a writable transaction
1769 * which in turn overlaps a writable transaction which committed before
1770 * the read-only transaction started. A new writable transaction can
1771 * overlap this one, but it can't meet the other condition of overlapping
1772 * a transaction which committed before this one started.
1773 */
1775 {
1778 return snapshot;
1779 }
1780
1781 /* Initialize the structure. */
1782 sxact->vxid = vxid;
1783 sxact->SeqNo.lastCommitBeforeSnapshot = PredXact->LastSxactCommitSeqNo;
1784 sxact->prepareSeqNo = InvalidSerCommitSeqNo;
1785 sxact->commitSeqNo = InvalidSerCommitSeqNo;
1786 dlist_init(&(sxact->outConflicts));
1787 dlist_init(&(sxact->inConflicts));
1788 dlist_init(&(sxact->possibleUnsafeConflicts));
1789 sxact->topXid = GetTopTransactionIdIfAny();
1790 sxact->finishedBefore = InvalidTransactionId;
1791 sxact->xmin = snapshot->xmin;
1792 sxact->pid = MyProcPid;
1793 sxact->pgprocno = MyProcNumber;
1794 dlist_init(&sxact->predicateLocks);
1795 dlist_node_init(&sxact->finishedLink);
1796 sxact->flags = 0;
1797 if (XactReadOnly)
1798 {
1799 dlist_iter iter;
1800
1801 sxact->flags |= SXACT_FLAG_READ_ONLY;
1802
1803 /*
1804 * Register all concurrent r/w transactions as possible conflicts; if
1805 * all of them commit without any outgoing conflicts to earlier
1806 * transactions then this snapshot can be deemed safe (and we can run
1807 * without tracking predicate locks).
1808 */
1810 {
1812
1816 {
1818 }
1819 }
1820
1821 /*
1822 * If we didn't find any possibly unsafe conflicts because every
1823 * uncommitted writable transaction turned out to be doomed, then we
1824 * can "opt out" immediately. See comments above the earlier check
1825 * for PredXact->WritableSxactCount == 0.
1826 */
1827 if (dlist_is_empty(&sxact->possibleUnsafeConflicts))
1828 {
1831 return snapshot;
1832 }
1833 }
1834 else
1835 {
1839 }
1840
1841 /* Maintain serializable global xmin info. */
1843 {
1845 PredXact->SxactGlobalXmin = snapshot->xmin;
1847 SerialSetActiveSerXmin(snapshot->xmin);
1848 }
1849 else if (TransactionIdEquals(snapshot->xmin, PredXact->SxactGlobalXmin))
1850 {
1853 }
1854 else
1855 {
1857 }
1858
1860 MyXactDidWrite = false; /* haven't written anything yet */
1861
1863
1865
1866 return snapshot;
1867}
1868
1869static void
1871{
1873
1874 /* Initialize the backend-local hash table of parent locks */
1876 hash_ctl.keysize = sizeof(PREDICATELOCKTARGETTAG);
1877 hash_ctl.entrysize = sizeof(LOCALPREDICATELOCK);
1878 LocalPredicateLockHash = hash_create("Local predicate lock",
1880 &hash_ctl,
1882}
1883
1884/*
1885 * Register the top level XID in SerializableXidHash.
1886 * Also store it for easy reference in MySerializableXact.
1887 */
1888void
1890{
1893 bool found;
1894
1895 /*
1896 * If we're not tracking predicate lock data for this transaction, we
1897 * should ignore the request and return quickly.
1898 */
1900 return;
1901
1902 /* We should have a valid XID and be at the top level. */
1904
1906
1907 /* This should only be done once per transaction. */
1909
1911
1912 sxidtag.xid = xid;
1914 &sxidtag,
1915 HASH_ENTER, &found);
1916 Assert(!found);
1917
1918 /* Initialize the structure. */
1919 sxid->myXact = MySerializableXact;
1921}
1922
1923
1924/*
1925 * Check whether there are any predicate locks held by any transaction
1926 * for the page at the given block number.
1927 *
1928 * Note that the transaction may be completed but not yet subject to
1929 * cleanup due to overlapping serializable transactions. This must
1930 * return valid information regardless of transaction isolation level.
1931 *
1932 * Also note that this doesn't check for a conflicting relation lock,
1933 * just a lock specifically on the given page.
1934 *
1935 * One use is to support proper behavior during GiST index vacuum.
1936 */
1937bool
1961
1962
1963/*
1964 * Check whether a particular lock is held by this transaction.
1965 *
1966 * Important note: this function may return false even if the lock is
1967 * being held, because it uses the local lock table which is not
1968 * updated if another transaction modifies our lock list (e.g. to
1969 * split an index page). It can also return true when a coarser
1970 * granularity lock that covers this target is being held. Be careful
1971 * to only use this function in circumstances where such errors are
1972 * acceptable!
1973 */
1974static bool
1976{
1977 LOCALPREDICATELOCK *lock;
1978
1979 /* check local hash table */
1981 targettag,
1982 HASH_FIND, NULL);
1983
1984 if (!lock)
1985 return false;
1986
1987 /*
1988 * Found entry in the table, but still need to check whether it's actually
1989 * held -- it could just be a parent of some held lock.
1990 */
1991 return lock->held;
1992}
1993
1994/*
1995 * Return the parent lock tag in the lock hierarchy: the next coarser
1996 * lock that covers the provided tag.
1997 *
1998 * Returns true and sets *parent to the parent tag if one exists,
1999 * returns false if none exists.
2000 */
2001static bool
2003 PREDICATELOCKTARGETTAG *parent)
2004{
2005 switch (GET_PREDICATELOCKTARGETTAG_TYPE(*tag))
2006 {
2008 /* relation locks have no parent lock */
2009 return false;
2010
2011 case PREDLOCKTAG_PAGE:
2012 /* parent lock is relation lock */
2016
2017 return true;
2018
2019 case PREDLOCKTAG_TUPLE:
2020 /* parent lock is page lock */
2025 return true;
2026 }
2027
2028 /* not reachable */
2029 Assert(false);
2030 return false;
2031}
2032
2033/*
2034 * Check whether the lock we are considering is already covered by a
2035 * coarser lock for our transaction.
2036 *
2037 * Like PredicateLockExists, this function might return a false
2038 * negative, but it will never return a false positive.
2039 */
2040static bool
2042{
2044 parenttag;
2045
2047
2048 /* check parents iteratively until no more */
2050 {
2053 return true;
2054 }
2055
2056 /* no more parents to check; lock is not covered */
2057 return false;
2058}
2059
2060/*
2061 * Remove the dummy entry from the predicate lock target hash, to free up some
2062 * scratch space. The caller must be holding SerializablePredicateListLock,
2063 * and must restore the entry with RestoreScratchTarget() before releasing the
2064 * lock.
2065 *
2066 * If lockheld is true, the caller is already holding the partition lock
2067 * of the partition containing the scratch entry.
2068 */
2069static void
2086
2087/*
2088 * Re-insert the dummy entry in predicate lock target hash.
2089 */
2090static void
2107
2108/*
2109 * Check whether the list of related predicate locks is empty for a
2110 * predicate lock target, and remove the target if it is.
2111 */
2112static void
2114{
2116
2118
2119 /* Can't remove it until no locks at this target. */
2120 if (!dlist_is_empty(&target->predicateLocks))
2121 return;
2122
2123 /* Actually remove the target. */
2125 &target->tag,
2127 HASH_REMOVE, NULL);
2128 Assert(rmtarget == target);
2129}
2130
2131/*
2132 * Delete child target locks owned by this process.
2133 * This implementation is assuming that the usage of each target tag field
2134 * is uniform. No need to make this hard if we don't have to.
2135 *
2136 * We acquire an LWLock in the case of parallel mode, because worker
2137 * backends have access to the leader's SERIALIZABLEXACT. Otherwise,
2138 * we aren't acquiring LWLocks for the predicate lock or lock
2139 * target structures associated with this transaction unless we're going
2140 * to modify them, because no other process is permitted to modify our
2141 * locks.
2142 */
2143static void
2145{
2148 dlist_mutable_iter iter;
2149
2152 if (IsInParallelMode())
2153 LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
2154
2155 dlist_foreach_modify(iter, &sxact->predicateLocks)
2156 {
2160
2161 predlock = dlist_container(PREDICATELOCK, xactLink, iter.cur);
2162
2163 oldlocktag = predlock->tag;
2164 Assert(oldlocktag.myXact == sxact);
2165 oldtarget = oldlocktag.myTarget;
2166 oldtargettag = oldtarget->tag;
2167
2169 {
2173
2176
2178
2179 dlist_delete(&predlock->xactLink);
2180 dlist_delete(&predlock->targetLink);
2183 &oldlocktag,
2186 HASH_REMOVE, NULL);
2188
2190
2192
2194 }
2195 }
2196 if (IsInParallelMode())
2197 LWLockRelease(&sxact->perXactPredicateListLock);
2199}
2200
2201/*
2202 * Returns the promotion limit for a given predicate lock target. This is the
2203 * max number of descendant locks allowed before promoting to the specified
2204 * tag. Note that the limit includes non-direct descendants (e.g., both tuples
2205 * and pages for a relation lock).
2206 *
2207 * Currently the default limit is 2 for a page lock, and half of the value of
2208 * max_pred_locks_per_transaction - 1 for a relation lock, to match behavior
2209 * of earlier releases when upgrading.
2210 *
2211 * TODO SSI: We should probably add additional GUCs to allow a maximum ratio
2212 * of page and tuple locks based on the pages in a relation, and the maximum
2213 * ratio of tuple locks to tuples in a page. This would provide more
2214 * generally "balanced" allocation of locks to where they are most useful,
2215 * while still allowing the absolute numbers to prevent one relation from
2216 * tying up all predicate lock resources.
2217 */
2218static int
2220{
2221 switch (GET_PREDICATELOCKTARGETTAG_TYPE(*tag))
2222 {
2228
2229 case PREDLOCKTAG_PAGE:
2231
2232 case PREDLOCKTAG_TUPLE:
2233
2234 /*
2235 * not reachable: nothing is finer-granularity than a tuple, so we
2236 * should never try to promote to it.
2237 */
2238 Assert(false);
2239 return 0;
2240 }
2241
2242 /* not reachable */
2243 Assert(false);
2244 return 0;
2245}
2246
2247/*
2248 * For all ancestors of a newly-acquired predicate lock, increment
2249 * their child count in the parent hash table. If any of them have
2250 * more descendants than their promotion threshold, acquire the
2251 * coarsest such lock.
2252 *
2253 * Returns true if a parent lock was acquired and false otherwise.
2254 */
2255static bool
2257{
2259 nexttag,
2262 bool found,
2263 promote;
2264
2265 promote = false;
2266
2267 targettag = *reqtag;
2268
2269 /* check parents iteratively */
2271 {
2274 &targettag,
2275 HASH_ENTER,
2276 &found);
2277 if (!found)
2278 {
2279 parentlock->held = false;
2280 parentlock->childLocks = 1;
2281 }
2282 else
2283 parentlock->childLocks++;
2284
2285 if (parentlock->childLocks >
2287 {
2288 /*
2289 * We should promote to this parent lock. Continue to check its
2290 * ancestors, however, both to get their child counts right and to
2291 * check whether we should just go ahead and promote to one of
2292 * them.
2293 */
2295 promote = true;
2296 }
2297 }
2298
2299 if (promote)
2300 {
2301 /* acquire coarsest ancestor eligible for promotion */
2303 return true;
2304 }
2305 else
2306 return false;
2307}
2308
2309/*
2310 * When releasing a lock, decrement the child count on all ancestor
2311 * locks.
2312 *
2313 * This is called only when releasing a lock via
2314 * DeleteChildTargetLocks (i.e. when a lock becomes redundant because
2315 * we've acquired its parent, possibly due to promotion) or when a new
2316 * MVCC write lock makes the predicate lock unnecessary. There's no
2317 * point in calling it when locks are released at transaction end, as
2318 * this information is no longer needed.
2319 */
2320static void
2322{
2324 nexttag;
2325
2327
2329 {
2333
2339 HASH_FIND, NULL);
2340
2341 /*
2342 * There's a small chance the parent lock doesn't exist in the lock
2343 * table. This can happen if we prematurely removed it because an
2344 * index split caused the child refcount to be off.
2345 */
2346 if (parentlock == NULL)
2347 continue;
2348
2349 parentlock->childLocks--;
2350
2351 /*
2352 * Under similar circumstances the parent lock's refcount might be
2353 * zero. This only happens if we're holding that lock (otherwise we
2354 * would have removed the entry).
2355 */
2356 if (parentlock->childLocks < 0)
2357 {
2358 Assert(parentlock->held);
2359 parentlock->childLocks = 0;
2360 }
2361
2362 if ((parentlock->childLocks == 0) && (!parentlock->held))
2363 {
2367 HASH_REMOVE, NULL);
2369 }
2370 }
2371}
2372
2373/*
2374 * Indicate that a predicate lock on the given target is held by the
2375 * specified transaction. Has no effect if the lock is already held.
2376 *
2377 * This updates the lock table and the sxact's lock list, and creates
2378 * the lock target if necessary, but does *not* do anything related to
2379 * granularity promotion or the local lock table. See
2380 * PredicateLockAcquire for that.
2381 */
2382static void
2386{
2387 PREDICATELOCKTARGET *target;
2388 PREDICATELOCKTAG locktag;
2389 PREDICATELOCK *lock;
2391 bool found;
2392
2394
2396 if (IsInParallelMode())
2397 LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
2399
2400 /* Make sure that the target is represented. */
2401 target = (PREDICATELOCKTARGET *)
2404 HASH_ENTER_NULL, &found);
2405 if (!target)
2406 ereport(ERROR,
2408 errmsg("out of shared memory"),
2409 errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
2410 if (!found)
2411 dlist_init(&target->predicateLocks);
2412
2413 /* We've got the sxact and target, make sure they're joined. */
2414 locktag.myTarget = target;
2415 locktag.myXact = sxact;
2416 lock = (PREDICATELOCK *)
2419 HASH_ENTER_NULL, &found);
2420 if (!lock)
2421 ereport(ERROR,
2423 errmsg("out of shared memory"),
2424 errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
2425
2426 if (!found)
2427 {
2428 dlist_push_tail(&target->predicateLocks, &lock->targetLink);
2429 dlist_push_tail(&sxact->predicateLocks, &lock->xactLink);
2431 }
2432
2434 if (IsInParallelMode())
2435 LWLockRelease(&sxact->perXactPredicateListLock);
2437}
2438
2439/*
2440 * Acquire a predicate lock on the specified target for the current
2441 * connection if not already held. This updates the local lock table
2442 * and uses it to implement granularity promotion. It will consolidate
2443 * multiple locks into a coarser lock if warranted, and will release
2444 * any finer-grained locks covered by the new one.
2445 */
2446static void
2448{
2450 bool found;
2452
2453 /* Do we have the lock already, or a covering lock? */
2455 return;
2456
2458 return;
2459
2460 /* the same hash and LW lock apply to the lock target and the local lock. */
2462
2463 /* Acquire lock in local table */
2467 HASH_ENTER, &found);
2468 locallock->held = true;
2469 if (!found)
2470 locallock->childLocks = 0;
2471
2472 /* Actually create the lock */
2474
2475 /*
2476 * Lock has been acquired. Check whether it should be promoted to a
2477 * coarser granularity, or whether there are finer-granularity locks to
2478 * clean up.
2479 */
2481 {
2482 /*
2483 * Lock request was promoted to a coarser-granularity lock, and that
2484 * lock was acquired. It will delete this lock and any of its
2485 * children, so we're done.
2486 */
2487 }
2488 else
2489 {
2490 /* Clean up any finer-granularity locks */
2493 }
2494}
2495
2496
2497/*
2498 * PredicateLockRelation
2499 *
2500 * Gets a predicate lock at the relation level.
2501 * Skip if not in full serializable transaction isolation level.
2502 * Skip if this is a temporary table.
2503 * Clear any finer-grained predicate locks this session has on the relation.
2504 */
2505void
2507{
2509
2510 if (!SerializationNeededForRead(relation, snapshot))
2511 return;
2512
2514 relation->rd_locator.dbOid,
2515 relation->rd_id);
2517}
2518
2519/*
2520 * PredicateLockPage
2521 *
2522 * Gets a predicate lock at the page level.
2523 * Skip if not in full serializable transaction isolation level.
2524 * Skip if this is a temporary table.
2525 * Skip if a coarser predicate lock already covers this page.
2526 * Clear any finer-grained predicate locks this session has on the relation.
2527 */
2528void
2530{
2532
2533 if (!SerializationNeededForRead(relation, snapshot))
2534 return;
2535
2537 relation->rd_locator.dbOid,
2538 relation->rd_id,
2539 blkno);
2541}
2542
2543/*
2544 * PredicateLockTID
2545 *
2546 * Gets a predicate lock at the tuple level.
2547 * Skip if not in full serializable transaction isolation level.
2548 * Skip if this is a temporary table.
2549 */
2550void
2551PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapshot,
2553{
2555
2556 if (!SerializationNeededForRead(relation, snapshot))
2557 return;
2558
2559 /*
2560 * Return if this xact wrote it.
2561 */
2562 if (relation->rd_index == NULL)
2563 {
2564 /* If we wrote it; we already have a write lock. */
2566 return;
2567 }
2568
2569 /*
2570 * Do quick-but-not-definitive test for a relation lock first. This will
2571 * never cause a return when the relation is *not* locked, but will
2572 * occasionally let the check continue when there really *is* a relation
2573 * level lock.
2574 */
2576 relation->rd_locator.dbOid,
2577 relation->rd_id);
2578 if (PredicateLockExists(&tag))
2579 return;
2580
2582 relation->rd_locator.dbOid,
2583 relation->rd_id,
2587}
2588
2589
2590/*
2591 * DeleteLockTarget
2592 *
2593 * Remove a predicate lock target along with any locks held for it.
2594 *
2595 * Caller must hold SerializablePredicateListLock and the
2596 * appropriate hash partition lock for the target.
2597 */
2598static void
2600{
2601 dlist_mutable_iter iter;
2602
2604 LW_EXCLUSIVE));
2606
2608
2609 dlist_foreach_modify(iter, &target->predicateLocks)
2610 {
2612 dlist_container(PREDICATELOCK, targetLink, iter.cur);
2613 bool found;
2614
2615 dlist_delete(&(predlock->xactLink));
2616 dlist_delete(&(predlock->targetLink));
2617
2620 &predlock->tag,
2623 HASH_REMOVE, &found);
2624 Assert(found);
2625 }
2627
2628 /* Remove the target itself, if possible. */
2630}
2631
2632
2633/*
2634 * TransferPredicateLocksToNewTarget
2635 *
2636 * Move or copy all the predicate locks for a lock target, for use by
2637 * index page splits/combines and other things that create or replace
2638 * lock targets. If 'removeOld' is true, the old locks and the target
2639 * will be removed.
2640 *
2641 * Returns true on success, or false if we ran out of shared memory to
2642 * allocate the new target or locks. Guaranteed to always succeed if
2643 * removeOld is set (by using the scratch entry in PredicateLockTargetHash
2644 * for scratch space).
2645 *
2646 * Warning: the "removeOld" option should be used only with care,
2647 * because this function does not (indeed, can not) update other
2648 * backends' LocalPredicateLockHash. If we are only adding new
2649 * entries, this is not a problem: the local lock table is used only
2650 * as a hint, so missing entries for locks that are held are
2651 * OK. Having entries for locks that are no longer held, as can happen
2652 * when using "removeOld", is not in general OK. We can only use it
2653 * safely when replacing a lock with a coarser-granularity lock that
2654 * covers it, or if we are absolutely certain that no one will need to
2655 * refer to that lock in the future.
2656 *
2657 * Caller must hold SerializablePredicateListLock exclusively.
2658 */
2659static bool
2662 bool removeOld)
2663{
2669 bool found;
2670 bool outOfShmem = false;
2671
2673 LW_EXCLUSIVE));
2674
2679
2680 if (removeOld)
2681 {
2682 /*
2683 * Remove the dummy entry to give us scratch space, so we know we'll
2684 * be able to create the new lock target.
2685 */
2686 RemoveScratchTarget(false);
2687 }
2688
2689 /*
2690 * We must get the partition locks in ascending sequence to avoid
2691 * deadlocks. If old and new partitions are the same, we must request the
2692 * lock only once.
2693 */
2695 {
2699 }
2701 {
2705 }
2706 else
2708
2709 /*
2710 * Look for the old target. If not found, that's OK; no predicate locks
2711 * are affected, so we can just clean up and return. If it does exist,
2712 * walk its list of predicate locks and move or copy them to the new
2713 * target.
2714 */
2716 &oldtargettag,
2718 HASH_FIND, NULL);
2719
2720 if (oldtarget)
2721 {
2724 dlist_mutable_iter iter;
2725
2727 &newtargettag,
2729 HASH_ENTER_NULL, &found);
2730
2731 if (!newtarget)
2732 {
2733 /* Failed to allocate due to insufficient shmem */
2734 outOfShmem = true;
2735 goto exit;
2736 }
2737
2738 /* If we created a new entry, initialize it */
2739 if (!found)
2740 dlist_init(&newtarget->predicateLocks);
2741
2742 newpredlocktag.myTarget = newtarget;
2743
2744 /*
2745 * Loop through all the locks on the old target, replacing them with
2746 * locks on the new target.
2747 */
2749
2750 dlist_foreach_modify(iter, &oldtarget->predicateLocks)
2751 {
2753 dlist_container(PREDICATELOCK, targetLink, iter.cur);
2756
2757 newpredlocktag.myXact = oldpredlock->tag.myXact;
2758
2759 if (removeOld)
2760 {
2761 dlist_delete(&(oldpredlock->xactLink));
2762 dlist_delete(&(oldpredlock->targetLink));
2763
2766 &oldpredlock->tag,
2769 HASH_REMOVE, &found);
2770 Assert(found);
2771 }
2772
2779 &found);
2780 if (!newpredlock)
2781 {
2782 /* Out of shared memory. Undo what we've done so far. */
2785 outOfShmem = true;
2786 goto exit;
2787 }
2788 if (!found)
2789 {
2790 dlist_push_tail(&(newtarget->predicateLocks),
2791 &(newpredlock->targetLink));
2792 dlist_push_tail(&(newpredlocktag.myXact->predicateLocks),
2793 &(newpredlock->xactLink));
2794 newpredlock->commitSeqNo = oldCommitSeqNo;
2795 }
2796 else
2797 {
2798 if (newpredlock->commitSeqNo < oldCommitSeqNo)
2799 newpredlock->commitSeqNo = oldCommitSeqNo;
2800 }
2801
2802 Assert(newpredlock->commitSeqNo != 0);
2803 Assert((newpredlock->commitSeqNo == InvalidSerCommitSeqNo)
2804 || (newpredlock->tag.myXact == OldCommittedSxact));
2805 }
2807
2808 if (removeOld)
2809 {
2810 Assert(dlist_is_empty(&oldtarget->predicateLocks));
2812 }
2813 }
2814
2815
2816exit:
2817 /* Release partition locks in reverse order of acquisition. */
2819 {
2822 }
2824 {
2827 }
2828 else
2830
2831 if (removeOld)
2832 {
2833 /* We shouldn't run out of memory if we're moving locks */
2835
2836 /* Put the scratch entry back */
2837 RestoreScratchTarget(false);
2838 }
2839
2840 return !outOfShmem;
2841}
2842
2843/*
2844 * Drop all predicate locks of any granularity from the specified relation,
2845 * which can be a heap relation or an index relation. If 'transfer' is true,
2846 * acquire a relation lock on the heap for any transactions with any lock(s)
2847 * on the specified relation.
2848 *
2849 * This requires grabbing a lot of LW locks and scanning the entire lock
2850 * target table for matches. That makes this more expensive than most
2851 * predicate lock management functions, but it will only be called for DDL
2852 * type commands that are expensive anyway, and there are fast returns when
2853 * no serializable transactions are active or the relation is temporary.
2854 *
2855 * We don't use the TransferPredicateLocksToNewTarget function because it
2856 * acquires its own locks on the partitions of the two targets involved,
2857 * and we'll already be holding all partition locks.
2858 *
2859 * We can't throw an error from here, because the call could be from a
2860 * transaction which is not serializable.
2861 *
2862 * NOTE: This is currently only called with transfer set to true, but that may
2863 * change. If we decide to clean up the locks from a table on commit of a
2864 * transaction which executed DROP TABLE, the false condition will be useful.
2865 */
2866static void
2868{
2872 Oid dbId;
2873 Oid relId;
2874 Oid heapId;
2875 int i;
2876 bool isIndex;
2877 bool found;
2879
2880 /*
2881 * Bail out quickly if there are no serializable transactions running.
2882 * It's safe to check this without taking locks because the caller is
2883 * holding an ACCESS EXCLUSIVE lock on the relation. No new locks which
2884 * would matter here can be acquired while that is held.
2885 */
2887 return;
2888
2889 if (!PredicateLockingNeededForRelation(relation))
2890 return;
2891
2892 dbId = relation->rd_locator.dbOid;
2893 relId = relation->rd_id;
2894 if (relation->rd_index == NULL)
2895 {
2896 isIndex = false;
2897 heapId = relId;
2898 }
2899 else
2900 {
2901 isIndex = true;
2902 heapId = relation->rd_index->indrelid;
2903 }
2905 Assert(transfer || !isIndex); /* index OID only makes sense with
2906 * transfer */
2907
2908 /* Retrieve first time needed, then keep. */
2910 heaptarget = NULL;
2911
2912 /* Acquire locks on all lock partitions */
2914 for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
2917
2918 /*
2919 * Remove the dummy entry to give us scratch space, so we know we'll be
2920 * able to create the new lock target.
2921 */
2922 if (transfer)
2923 RemoveScratchTarget(true);
2924
2925 /* Scan through target map */
2927
2929 {
2930 dlist_mutable_iter iter;
2931
2932 /*
2933 * Check whether this is a target which needs attention.
2934 */
2936 continue; /* wrong relation id */
2937 if (GET_PREDICATELOCKTARGETTAG_DB(oldtarget->tag) != dbId)
2938 continue; /* wrong database id */
2939 if (transfer && !isIndex
2941 continue; /* already the right lock */
2942
2943 /*
2944 * If we made it here, we have work to do. We make sure the heap
2945 * relation lock exists, then we walk the list of predicate locks for
2946 * the old target we found, moving all locks to the heap relation lock
2947 * -- unless they already hold that.
2948 */
2949
2950 /*
2951 * First make sure we have the heap relation target. We only need to
2952 * do this once.
2953 */
2954 if (transfer && heaptarget == NULL)
2955 {
2957
2963 HASH_ENTER, &found);
2964 if (!found)
2965 dlist_init(&heaptarget->predicateLocks);
2966 }
2967
2968 /*
2969 * Loop through all the locks on the old target, replacing them with
2970 * locks on the new target.
2971 */
2972 dlist_foreach_modify(iter, &oldtarget->predicateLocks)
2973 {
2975 dlist_container(PREDICATELOCK, targetLink, iter.cur);
2979
2980 /*
2981 * Remove the old lock first. This avoids the chance of running
2982 * out of lock structure entries for the hash table.
2983 */
2985 oldXact = oldpredlock->tag.myXact;
2986
2987 dlist_delete(&(oldpredlock->xactLink));
2988
2989 /*
2990 * No need for retail delete from oldtarget list, we're removing
2991 * the whole target anyway.
2992 */
2994 &oldpredlock->tag,
2995 HASH_REMOVE, &found);
2996 Assert(found);
2997
2998 if (transfer)
2999 {
3001
3003 newpredlocktag.myXact = oldXact;
3009 HASH_ENTER,
3010 &found);
3011 if (!found)
3012 {
3013 dlist_push_tail(&(heaptarget->predicateLocks),
3014 &(newpredlock->targetLink));
3015 dlist_push_tail(&(newpredlocktag.myXact->predicateLocks),
3016 &(newpredlock->xactLink));
3017 newpredlock->commitSeqNo = oldCommitSeqNo;
3018 }
3019 else
3020 {
3021 if (newpredlock->commitSeqNo < oldCommitSeqNo)
3022 newpredlock->commitSeqNo = oldCommitSeqNo;
3023 }
3024
3025 Assert(newpredlock->commitSeqNo != 0);
3026 Assert((newpredlock->commitSeqNo == InvalidSerCommitSeqNo)
3027 || (newpredlock->tag.myXact == OldCommittedSxact));
3028 }
3029 }
3030
3032 &found);
3033 Assert(found);
3034 }
3035
3036 /* Put the scratch entry back */
3037 if (transfer)
3039
3040 /* Release locks in reverse order */
3042 for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
3045}
3046
3047/*
3048 * TransferPredicateLocksToHeapRelation
3049 * For all transactions, transfer all predicate locks for the given
3050 * relation to a single relation lock on the heap.
3051 */
3052void
3057
3058
3059/*
3060 * PredicateLockPageSplit
3061 *
3062 * Copies any predicate locks for the old page to the new page.
3063 * Skip if this is a temporary table or toast table.
3064 *
3065 * NOTE: A page split (or overflow) affects all serializable transactions,
3066 * even if it occurs in the context of another transaction isolation level.
3067 *
3068 * NOTE: This currently leaves the local copy of the locks without
3069 * information on the new lock which is in shared memory. This could cause
3070 * problems if enough page splits occur on locked pages without the processes
3071 * which hold the locks getting in and noticing.
3072 */
3073void
3076{
3079 bool success;
3080
3081 /*
3082 * Bail out quickly if there are no serializable transactions running.
3083 *
3084 * It's safe to do this check without taking any additional locks. Even if
3085 * a serializable transaction starts concurrently, we know it can't take
3086 * any SIREAD locks on the page being split because the caller is holding
3087 * the associated buffer page lock. Memory reordering isn't an issue; the
3088 * memory barrier in the LWLock acquisition guarantees that this read
3089 * occurs while the buffer page lock is held.
3090 */
3092 return;
3093
3094 if (!PredicateLockingNeededForRelation(relation))
3095 return;
3096
3100
3102 relation->rd_locator.dbOid,
3103 relation->rd_id,
3104 oldblkno);
3106 relation->rd_locator.dbOid,
3107 relation->rd_id,
3108 newblkno);
3109
3111
3112 /*
3113 * Try copying the locks over to the new page's tag, creating it if
3114 * necessary.
3115 */
3118 false);
3119
3120 if (!success)
3121 {
3122 /*
3123 * No more predicate lock entries are available. Failure isn't an
3124 * option here, so promote the page lock to a relation lock.
3125 */
3126
3127 /* Get the parent relation lock's lock tag */
3129 &newtargettag);
3130 Assert(success);
3131
3132 /*
3133 * Move the locks to the parent. This shouldn't fail.
3134 *
3135 * Note that here we are removing locks held by other backends,
3136 * leading to a possible inconsistency in their local lock hash table.
3137 * This is OK because we're replacing it with a lock that covers the
3138 * old one.
3139 */
3142 true);
3143 Assert(success);
3144 }
3145
3147}
3148
3149/*
3150 * PredicateLockPageCombine
3151 *
3152 * Combines predicate locks for two existing pages.
3153 * Skip if this is a temporary table or toast table.
3154 *
3155 * NOTE: A page combine affects all serializable transactions, even if it
3156 * occurs in the context of another transaction isolation level.
3157 */
3158void
3161{
3162 /*
3163 * Page combines differ from page splits in that we ought to be able to
3164 * remove the locks on the old page after transferring them to the new
3165 * page, instead of duplicating them. However, because we can't edit other
3166 * backends' local lock tables, removing the old lock would leave them
3167 * with an entry in their LocalPredicateLockHash for a lock they're not
3168 * holding, which isn't acceptable. So we wind up having to do the same
3169 * work as a page split, acquiring a lock on the new page and keeping the
3170 * old page locked too. That can lead to some false positives, but should
3171 * be rare in practice.
3172 */
3174}
3175
3176/*
3177 * Walk the list of in-progress serializable transactions and find the new
3178 * xmin.
3179 */
3180static void
3215
3216/*
3217 * ReleasePredicateLocks
3218 *
3219 * Releases predicate locks based on completion of the current transaction,
3220 * whether committed or rolled back. It can also be called for a read only
3221 * transaction when it becomes impossible for the transaction to become
3222 * part of a dangerous structure.
3223 *
3224 * We do nothing unless this is a serializable transaction.
3225 *
3226 * This method must ensure that shared memory hash tables are cleaned
3227 * up in some relatively timely fashion.
3228 *
3229 * If this transaction is committing and is holding any predicate locks,
3230 * it must be added to a list of completed serializable transactions still
3231 * holding locks.
3232 *
3233 * If isReadOnlySafe is true, then predicate locks are being released before
3234 * the end of the transaction because MySerializableXact has been determined
3235 * to be RO_SAFE. In non-parallel mode we can release it completely, but it
3236 * in parallel mode we partially release the SERIALIZABLEXACT and keep it
3237 * around until the end of the transaction, allowing each backend to clear its
3238 * MySerializableXact variable and benefit from the optimization in its own
3239 * time.
3240 */
3241void
3243{
3244 bool partiallyReleasing = false;
3245 bool needToClear;
3247 dlist_mutable_iter iter;
3248
3249 /*
3250 * We can't trust XactReadOnly here, because a transaction which started
3251 * as READ WRITE can show as READ ONLY later, e.g., within
3252 * subtransactions. We want to flag a transaction as READ ONLY if it
3253 * commits without writing so that de facto READ ONLY transactions get the
3254 * benefit of some RO optimizations, so we will use this local variable to
3255 * get some cleanup logic right which is based on whether the transaction
3256 * was declared READ ONLY at the top level.
3257 */
3259
3260 /* We can't be both committing and releasing early due to RO_SAFE. */
3262
3263 /* Are we at the end of a transaction, that is, a commit or abort? */
3264 if (!isReadOnlySafe)
3265 {
3266 /*
3267 * Parallel workers mustn't release predicate locks at the end of
3268 * their transaction. The leader will do that at the end of its
3269 * transaction.
3270 */
3271 if (IsParallelWorker())
3272 {
3274 return;
3275 }
3276
3277 /*
3278 * By the time the leader in a parallel query reaches end of
3279 * transaction, it has waited for all workers to exit.
3280 */
3282
3283 /*
3284 * If the leader in a parallel query earlier stashed a partially
3285 * released SERIALIZABLEXACT for final clean-up at end of transaction
3286 * (because workers might still have been accessing it), then it's
3287 * time to restore it.
3288 */
3290 {
3295 }
3296 }
3297
3299 {
3301 return;
3302 }
3303
3305
3306 /*
3307 * If the transaction is committing, but it has been partially released
3308 * already, then treat this as a roll back. It was marked as rolled back.
3309 */
3311 isCommit = false;
3312
3313 /*
3314 * If we're called in the middle of a transaction because we discovered
3315 * that the SXACT_FLAG_RO_SAFE flag was set, then we'll partially release
3316 * it (that is, release the predicate locks and conflicts, but not the
3317 * SERIALIZABLEXACT itself) if we're the first backend to have noticed.
3318 */
3320 {
3321 /*
3322 * The leader needs to stash a pointer to it, so that it can
3323 * completely release it at end-of-transaction.
3324 */
3325 if (!IsParallelWorker())
3327
3328 /*
3329 * The first backend to reach this condition will partially release
3330 * the SERIALIZABLEXACT. All others will just clear their
3331 * backend-local state so that they stop doing SSI checks for the rest
3332 * of the transaction.
3333 */
3335 {
3338 return;
3339 }
3340 else
3341 {
3343 partiallyReleasing = true;
3344 /* ... and proceed to perform the partial release below. */
3345 }
3346 }
3352
3353 /* may not be serializable during COMMIT/ROLLBACK PREPARED */
3355
3356 /* We'd better not already be on the cleanup list. */
3358
3360
3361 /*
3362 * We don't hold XidGenLock lock here, assuming that TransactionId is
3363 * atomic!
3364 *
3365 * If this value is changing, we don't care that much whether we get the
3366 * old or new value -- it is just used to determine how far
3367 * SxactGlobalXmin must advance before this transaction can be fully
3368 * cleaned up. The worst that could happen is we wait for one more
3369 * transaction to complete before freeing some RAM; correctness of visible
3370 * behavior is not affected.
3371 */
3373
3374 /*
3375 * If it's not a commit it's either a rollback or a read-only transaction
3376 * flagged SXACT_FLAG_RO_SAFE, and we can clear our locks immediately.
3377 */
3378 if (isCommit)
3379 {
3382 /* Recognize implicit read-only transaction (commit without write). */
3383 if (!MyXactDidWrite)
3385 }
3386 else
3387 {
3388 /*
3389 * The DOOMED flag indicates that we intend to roll back this
3390 * transaction and so it should not cause serialization failures for
3391 * other transactions that conflict with it. Note that this flag might
3392 * already be set, if another backend marked this transaction for
3393 * abort.
3394 *
3395 * The ROLLED_BACK flag further indicates that ReleasePredicateLocks
3396 * has been called, and so the SerializableXact is eligible for
3397 * cleanup. This means it should not be considered when calculating
3398 * SxactGlobalXmin.
3399 */
3402
3403 /*
3404 * If the transaction was previously prepared, but is now failing due
3405 * to a ROLLBACK PREPARED or (hopefully very rare) error after the
3406 * prepare, clear the prepared flag. This simplifies conflict
3407 * checking.
3408 */
3410 }
3411
3413 {
3415 if (--(PredXact->WritableSxactCount) == 0)
3416 {
3417 /*
3418 * Release predicate locks and rw-conflicts in for all committed
3419 * transactions. There are no longer any transactions which might
3420 * conflict with the locks and no chance for new transactions to
3421 * overlap. Similarly, existing conflicts in can't cause pivots,
3422 * and any conflicts in which could have completed a dangerous
3423 * structure would already have caused a rollback, so any
3424 * remaining ones must be benign.
3425 */
3427 }
3428 }
3429 else
3430 {
3431 /*
3432 * Read-only transactions: clear the list of transactions that might
3433 * make us unsafe. Note that we use 'inLink' for the iteration as
3434 * opposed to 'outLink' for the r/w xacts.
3435 */
3437 {
3439 dlist_container(RWConflictData, inLink, iter.cur);
3440
3443
3445 }
3446 }
3447
3448 /* Check for conflict out to old committed transactions. */
3449 if (isCommit
3452 {
3453 /*
3454 * we don't know which old committed transaction we conflicted with,
3455 * so be conservative and use FirstNormalSerCommitSeqNo here
3456 */
3460 }
3461
3462 /*
3463 * Release all outConflicts to committed transactions. If we're rolling
3464 * back clear them all. Set SXACT_FLAG_CONFLICT_OUT if any point to
3465 * previously committed transactions.
3466 */
3468 {
3470 dlist_container(RWConflictData, outLink, iter.cur);
3471
3472 if (isCommit
3474 && SxactIsCommitted(conflict->sxactIn))
3475 {
3477 || conflict->sxactIn->prepareSeqNo < MySerializableXact->SeqNo.earliestOutConflictCommit)
3480 }
3481
3482 if (!isCommit
3483 || SxactIsCommitted(conflict->sxactIn)
3484 || (conflict->sxactIn->SeqNo.lastCommitBeforeSnapshot >= PredXact->LastSxactCommitSeqNo))
3486 }
3487
3488 /*
3489 * Release all inConflicts from committed and read-only transactions. If
3490 * we're rolling back, clear them all.
3491 */
3493 {
3495 dlist_container(RWConflictData, inLink, iter.cur);
3496
3497 if (!isCommit
3498 || SxactIsCommitted(conflict->sxactOut)
3499 || SxactIsReadOnly(conflict->sxactOut))
3501 }
3502
3504 {
3505 /*
3506 * Remove ourselves from the list of possible conflicts for concurrent
3507 * READ ONLY transactions, flagging them as unsafe if we have a
3508 * conflict out. If any are waiting DEFERRABLE transactions, wake them
3509 * up if they are known safe or known unsafe.
3510 */
3512 {
3514 dlist_container(RWConflictData, outLink, iter.cur);
3515
3516 roXact = possibleUnsafeConflict->sxactIn;
3519
3520 /* Mark conflicted if necessary. */
3521 if (isCommit
3525 <= roXact->SeqNo.lastCommitBeforeSnapshot))
3526 {
3527 /*
3528 * This releases possibleUnsafeConflict (as well as all other
3529 * possible conflicts for roXact)
3530 */
3532 }
3533 else
3534 {
3536
3537 /*
3538 * If we were the last possible conflict, flag it safe. The
3539 * transaction can now safely release its predicate locks (but
3540 * that transaction's backend has to do that itself).
3541 */
3542 if (dlist_is_empty(&roXact->possibleUnsafeConflicts))
3543 roXact->flags |= SXACT_FLAG_RO_SAFE;
3544 }
3545
3546 /*
3547 * Wake up the process for a waiting DEFERRABLE transaction if we
3548 * now know it's either safe or conflicted.
3549 */
3552 ProcSendSignal(roXact->pgprocno);
3553 }
3554 }
3555
3556 /*
3557 * Check whether it's time to clean up old transactions. This can only be
3558 * done when the last serializable transaction with the oldest xmin among
3559 * serializable transactions completes. We then find the "new oldest"
3560 * xmin and purge any transactions which finished before this transaction
3561 * was launched.
3562 *
3563 * For parallel queries in read-only transactions, it might run twice. We
3564 * only release the reference on the first call.
3565 */
3566 needToClear = false;
3567 if ((partiallyReleasing ||
3571 {
3573 if (--(PredXact->SxactGlobalXminCount) == 0)
3574 {
3576 needToClear = true;
3577 }
3578 }
3579
3581
3583
3584 /* Add this to the list of transactions to check for later cleanup. */
3585 if (isCommit)
3588
3589 /*
3590 * If we're releasing a RO_SAFE transaction in parallel mode, we'll only
3591 * partially release it. That's necessary because other backends may have
3592 * a reference to it. The leader will release the SERIALIZABLEXACT itself
3593 * at the end of the transaction after workers have stopped running.
3594 */
3595 if (!isCommit)
3598 false);
3599
3601
3602 if (needToClear)
3604
3606}
3607
3608static void
3610{
3612 MyXactDidWrite = false;
3613
3614 /* Delete per-transaction lock table */
3616 {
3619 }
3620}
3621
3622/*
3623 * Clear old predicate locks, belonging to committed transactions that are no
3624 * longer interesting to any in-progress transaction.
3625 */
3626static void
3628{
3629 dlist_mutable_iter iter;
3630
3631 /*
3632 * Loop through finished transactions. They are in commit order, so we can
3633 * stop as soon as we find one that's still interesting.
3634 */
3638 {
3640 dlist_container(SERIALIZABLEXACT, finishedLink, iter.cur);
3641
3645 {
3646 /*
3647 * This transaction committed before any in-progress transaction
3648 * took its snapshot. It's no longer interesting.
3649 */
3651 dlist_delete_thoroughly(&finishedSxact->finishedLink);
3654 }
3655 else if (finishedSxact->commitSeqNo > PredXact->HavePartialClearedThrough
3656 && finishedSxact->commitSeqNo <= PredXact->CanPartialClearThrough)
3657 {
3658 /*
3659 * Any active transactions that took their snapshot before this
3660 * transaction committed are read-only, so we can clear part of
3661 * its state.
3662 */
3664
3666 {
3667 /* A read-only transaction can be removed entirely */
3668 dlist_delete_thoroughly(&(finishedSxact->finishedLink));
3670 }
3671 else
3672 {
3673 /*
3674 * A read-write transaction can only be partially cleared. We
3675 * need to keep the SERIALIZABLEXACT but can release the
3676 * SIREAD locks and conflicts in.
3677 */
3679 }
3680
3683 }
3684 else
3685 {
3686 /* Still interesting. */
3687 break;
3688 }
3689 }
3691
3692 /*
3693 * Loop through predicate locks on dummy transaction for summarized data.
3694 */
3697 {
3699 dlist_container(PREDICATELOCK, xactLink, iter.cur);
3701
3703 Assert(predlock->commitSeqNo != 0);
3704 Assert(predlock->commitSeqNo != InvalidSerCommitSeqNo);
3707
3708 /*
3709 * If this lock originally belonged to an old enough transaction, we
3710 * can release it.
3711 */
3713 {
3714 PREDICATELOCKTAG tag;
3715 PREDICATELOCKTARGET *target;
3719
3720 tag = predlock->tag;
3721 target = tag.myTarget;
3722 targettag = target->tag;
3725
3727
3728 dlist_delete(&(predlock->targetLink));
3729 dlist_delete(&(predlock->xactLink));
3730
3734 HASH_REMOVE, NULL);
3736
3738 }
3739 }
3740
3743}
3744
3745/*
3746 * This is the normal way to delete anything from any of the predicate
3747 * locking hash tables. Given a transaction which we know can be deleted:
3748 * delete all predicate locks held by that transaction and any predicate
3749 * lock targets which are now unreferenced by a lock; delete all conflicts
3750 * for the transaction; delete all xid values for the transaction; then
3751 * delete the transaction.
3752 *
3753 * When the partial flag is set, we can release all predicate locks and
3754 * in-conflict information -- we've established that there are no longer
3755 * any overlapping read write transactions for which this transaction could
3756 * matter -- but keep the transaction entry itself and any outConflicts.
3757 *
3758 * When the summarize flag is set, we've run short of room for sxact data
3759 * and must summarize to the SLRU. Predicate locks are transferred to a
3760 * dummy "old" transaction, with duplicate locks on a single target
3761 * collapsing to a single lock with the "latest" commitSeqNo from among
3762 * the conflicting locks..
3763 */
3764static void
3766 bool summarize)
3767{
3769 dlist_mutable_iter iter;
3770
3771 Assert(sxact != NULL);
3773 Assert(partial || !SxactIsOnFinishedList(sxact));
3775
3776 /*
3777 * First release all the predicate locks held by this xact (or transfer
3778 * them to OldCommittedSxact if summarize is true)
3779 */
3781 if (IsInParallelMode())
3782 LWLockAcquire(&sxact->perXactPredicateListLock, LW_EXCLUSIVE);
3783 dlist_foreach_modify(iter, &sxact->predicateLocks)
3784 {
3786 dlist_container(PREDICATELOCK, xactLink, iter.cur);
3787 PREDICATELOCKTAG tag;
3788 PREDICATELOCKTARGET *target;
3792
3793 tag = predlock->tag;
3794 target = tag.myTarget;
3795 targettag = target->tag;
3798
3800
3801 dlist_delete(&predlock->targetLink);
3802
3806 HASH_REMOVE, NULL);
3807 if (summarize)
3808 {
3809 bool found;
3810
3811 /* Fold into dummy transaction list. */
3816 HASH_ENTER_NULL, &found);
3817 if (!predlock)
3818 ereport(ERROR,
3820 errmsg("out of shared memory"),
3821 errhint("You might need to increase \"%s\".", "max_pred_locks_per_transaction")));
3822 if (found)
3823 {
3824 Assert(predlock->commitSeqNo != 0);
3825 Assert(predlock->commitSeqNo != InvalidSerCommitSeqNo);
3826 if (predlock->commitSeqNo < sxact->commitSeqNo)
3827 predlock->commitSeqNo = sxact->commitSeqNo;
3828 }
3829 else
3830 {
3832 &predlock->targetLink);
3834 &predlock->xactLink);
3835 predlock->commitSeqNo = sxact->commitSeqNo;
3836 }
3837 }
3838 else
3840
3842 }
3843
3844 /*
3845 * Rather than retail removal, just re-init the head after we've run
3846 * through the list.
3847 */
3848 dlist_init(&sxact->predicateLocks);
3849
3850 if (IsInParallelMode())
3851 LWLockRelease(&sxact->perXactPredicateListLock);
3853
3854 sxidtag.xid = sxact->topXid;
3856
3857 /* Release all outConflicts (unless 'partial' is true) */
3858 if (!partial)
3859 {
3860 dlist_foreach_modify(iter, &sxact->outConflicts)
3861 {
3863 dlist_container(RWConflictData, outLink, iter.cur);
3864
3865 if (summarize)
3866 conflict->sxactIn->flags |= SXACT_FLAG_SUMMARY_CONFLICT_IN;
3868 }
3869 }
3870
3871 /* Release all inConflicts. */
3872 dlist_foreach_modify(iter, &sxact->inConflicts)
3873 {
3875 dlist_container(RWConflictData, inLink, iter.cur);
3876
3877 if (summarize)
3878 conflict->sxactOut->flags |= SXACT_FLAG_SUMMARY_CONFLICT_OUT;
3880 }
3881
3882 /* Finally, get rid of the xid and the record of the transaction itself. */
3883 if (!partial)
3884 {
3885 if (sxidtag.xid != InvalidTransactionId)
3888 }
3889
3891}
3892
3893/*
3894 * Tests whether the given top level transaction is concurrent with
3895 * (overlaps) our current transaction.
3896 *
3897 * We need to identify the top level transaction for SSI, anyway, so pass
3898 * that to this function to save the overhead of checking the snapshot's
3899 * subxip array.
3900 */
3901static bool
3903{
3904 Snapshot snap;
3905
3908
3910
3911 if (TransactionIdPrecedes(xid, snap->xmin))
3912 return false;
3913
3914 if (TransactionIdFollowsOrEquals(xid, snap->xmax))
3915 return true;
3916
3917 return pg_lfind32(xid, snap->xip, snap->xcnt);
3918}
3919
3920bool
3922{
3923 if (!SerializationNeededForRead(relation, snapshot))
3924 return false;
3925
3926 /* Check if someone else has already decided that we need to die */
3928 {
3929 ereport(ERROR,
3931 errmsg("could not serialize access due to read/write dependencies among transactions"),
3932 errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict out checking."),
3933 errhint("The transaction might succeed if retried.")));
3934 }
3935
3936 return true;
3937}
3938
3939/*
3940 * CheckForSerializableConflictOut
3941 * A table AM is reading a tuple that has been modified. If it determines
3942 * that the tuple version it is reading is not visible to us, it should
3943 * pass in the top level xid of the transaction that created it.
3944 * Otherwise, if it determines that it is visible to us but it has been
3945 * deleted or there is a newer version available due to an update, it
3946 * should pass in the top level xid of the modifying transaction.
3947 *
3948 * This function will check for overlap with our own transaction. If the given
3949 * xid is also serializable and the transactions overlap (i.e., they cannot see
3950 * each other's writes), then we have a conflict out.
3951 */
3952void
3954{
3958
3959 if (!SerializationNeededForRead(relation, snapshot))
3960 return;
3961
3962 /* Check if someone else has already decided that we need to die */
3964 {
3965 ereport(ERROR,
3967 errmsg("could not serialize access due to read/write dependencies among transactions"),
3968 errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict out checking."),
3969 errhint("The transaction might succeed if retried.")));
3970 }
3972
3974 return;
3975
3976 /*
3977 * Find sxact or summarized info for the top level xid.
3978 */
3979 sxidtag.xid = xid;
3981 sxid = (SERIALIZABLEXID *)
3983 if (!sxid)
3984 {
3985 /*
3986 * Transaction not found in "normal" SSI structures. Check whether it
3987 * got pushed out to SLRU storage for "old committed" transactions.
3988 */
3990
3992 if (conflictCommitSeqNo != 0)
3993 {
3998 ereport(ERROR,
4000 errmsg("could not serialize access due to read/write dependencies among transactions"),
4001 errdetail_internal("Reason code: Canceled on conflict out to old pivot %u.", xid),
4002 errhint("The transaction might succeed if retried.")));
4003
4006 ereport(ERROR,
4008 errmsg("could not serialize access due to read/write dependencies among transactions"),
4009 errdetail_internal("Reason code: Canceled on identification as a pivot, with conflict out to old committed transaction %u.", xid),
4010 errhint("The transaction might succeed if retried.")));
4011
4013 }
4014
4015 /* It's not serializable or otherwise not important. */
4017 return;
4018 }
4019 sxact = sxid->myXact;
4020 Assert(TransactionIdEquals(sxact->topXid, xid));
4022 {
4023 /* Can't conflict with ourself or a transaction that will roll back. */
4025 return;
4026 }
4027
4028 /*
4029 * We have a conflict out to a transaction which has a conflict out to a
4030 * summarized transaction. That summarized transaction must have
4031 * committed first, and we can't tell when it committed in relation to our
4032 * snapshot acquisition, so something needs to be canceled.
4033 */
4035 {
4036 if (!SxactIsPrepared(sxact))
4037 {
4038 sxact->flags |= SXACT_FLAG_DOOMED;
4040 return;
4041 }
4042 else
4043 {
4045 ereport(ERROR,
4047 errmsg("could not serialize access due to read/write dependencies among transactions"),
4048 errdetail_internal("Reason code: Canceled on conflict out to old pivot."),
4049 errhint("The transaction might succeed if retried.")));
4050 }
4051 }
4052
4053 /*
4054 * If this is a read-only transaction and the writing transaction has
4055 * committed, and it doesn't have a rw-conflict to a transaction which
4056 * committed before it, no conflict.
4057 */
4062 || MySerializableXact->SeqNo.lastCommitBeforeSnapshot < sxact->SeqNo.earliestOutConflictCommit))
4063 {
4064 /* Read-only transaction will appear to run first. No conflict. */
4066 return;
4067 }
4068
4069 if (!XidIsConcurrent(xid))
4070 {
4071 /* This write was already in our snapshot; no conflict. */
4073 return;
4074 }
4075
4077 {
4078 /* We don't want duplicate conflict records in the list. */
4080 return;
4081 }
4082
4083 /*
4084 * Flag the conflict. But first, if this conflict creates a dangerous
4085 * structure, ereport an error.
4086 */
4089}
4090
4091/*
4092 * Check a particular target for rw-dependency conflict in. A subroutine of
4093 * CheckForSerializableConflictIn().
4094 */
4095static void
4097{
4100 PREDICATELOCKTARGET *target;
4103 dlist_mutable_iter iter;
4104
4106
4107 /*
4108 * The same hash and LW lock apply to the lock target and the lock itself.
4109 */
4113 target = (PREDICATELOCKTARGET *)
4116 HASH_FIND, NULL);
4117 if (!target)
4118 {
4119 /* Nothing has this target locked; we're done here. */
4121 return;
4122 }
4123
4124 /*
4125 * Each lock for an overlapping transaction represents a conflict: a
4126 * rw-dependency in to this transaction.
4127 */
4129
4130 dlist_foreach_modify(iter, &target->predicateLocks)
4131 {
4133 dlist_container(PREDICATELOCK, targetLink, iter.cur);
4134 SERIALIZABLEXACT *sxact = predlock->tag.myXact;
4135
4137 {
4138 /*
4139 * If we're getting a write lock on a tuple, we don't need a
4140 * predicate (SIREAD) lock on the same tuple. We can safely remove
4141 * our SIREAD lock, but we'll defer doing so until after the loop
4142 * because that requires upgrading to an exclusive partition lock.
4143 *
4144 * We can't use this optimization within a subtransaction because
4145 * the subtransaction could roll back, and we would be left
4146 * without any lock at the top level.
4147 */
4148 if (!IsSubTransaction()
4150 {
4152 mypredlocktag = predlock->tag;
4153 }
4154 }
4155 else if (!SxactIsDoomed(sxact)
4158 sxact->finishedBefore))
4160 {
4163
4164 /*
4165 * Re-check after getting exclusive lock because the other
4166 * transaction may have flagged a conflict.
4167 */
4168 if (!SxactIsDoomed(sxact)
4171 sxact->finishedBefore))
4173 {
4175 }
4176
4179 }
4180 }
4183
4184 /*
4185 * If we found one of our own SIREAD locks to remove, remove it now.
4186 *
4187 * At this point our transaction already has a RowExclusiveLock on the
4188 * relation, so we are OK to drop the predicate lock on the tuple, if
4189 * found, without fearing that another write against the tuple will occur
4190 * before the MVCC information makes it to the buffer.
4191 */
4192 if (mypredlock != NULL)
4193 {
4196
4198 if (IsInParallelMode())
4202
4203 /*
4204 * Remove the predicate lock from shared memory, if it wasn't removed
4205 * while the locks were released. One way that could happen is from
4206 * autovacuum cleaning up an index.
4207 */
4214 HASH_FIND, NULL);
4215 if (rmpredlock != NULL)
4216 {
4218
4219 dlist_delete(&(mypredlock->targetLink));
4220 dlist_delete(&(mypredlock->xactLink));
4221
4226 HASH_REMOVE, NULL);
4228
4230 }
4231
4234 if (IsInParallelMode())
4237
4238 if (rmpredlock != NULL)
4239 {
4240 /*
4241 * Remove entry in local lock table if it exists. It's OK if it
4242 * doesn't exist; that means the lock was transferred to a new
4243 * target by a different backend.
4244 */
4247 HASH_REMOVE, NULL);
4248
4250 }
4251 }
4252}
4253
4254/*
4255 * CheckForSerializableConflictIn
4256 * We are writing the given tuple. If that indicates a rw-conflict
4257 * in from another serializable transaction, take appropriate action.
4258 *
4259 * Skip checking for any granularity for which a parameter is missing.
4260 *
4261 * A tuple update or delete is in conflict if we have a predicate lock
4262 * against the relation or page in which the tuple exists, or against the
4263 * tuple itself.
4264 */
4265void
4267{
4269
4270 if (!SerializationNeededForWrite(relation))
4271 return;
4272
4273 /* Check if someone else has already decided that we need to die */
4275 ereport(ERROR,
4277 errmsg("could not serialize access due to read/write dependencies among transactions"),
4278 errdetail_internal("Reason code: Canceled on identification as a pivot, during conflict in checking."),
4279 errhint("The transaction might succeed if retried.")));
4280
4281 /*
4282 * We're doing a write which might cause rw-conflicts now or later.
4283 * Memorize that fact.
4284 */
4285 MyXactDidWrite = true;
4286
4287 /*
4288 * It is important that we check for locks from the finest granularity to
4289 * the coarsest granularity, so that granularity promotion doesn't cause
4290 * us to miss a lock. The new (coarser) lock will be acquired before the
4291 * old (finer) locks are released.
4292 *
4293 * It is not possible to take and hold a lock across the checks for all
4294 * granularities because each target could be in a separate partition.
4295 */
4296 if (tid != NULL)
4297 {
4299 relation->rd_locator.dbOid,
4300 relation->rd_id,
4304 }
4305
4306 if (blkno != InvalidBlockNumber)
4307 {
4309 relation->rd_locator.dbOid,
4310 relation->rd_id,
4311 blkno);
4313 }
4314
4316 relation->rd_locator.dbOid,
4317 relation->rd_id);
4319}
4320
4321/*
4322 * CheckTableForSerializableConflictIn
4323 * The entire table is going through a DDL-style logical mass delete
4324 * like TRUNCATE or DROP TABLE. If that causes a rw-conflict in from
4325 * another serializable transaction, take appropriate action.
4326 *
4327 * While these operations do not operate entirely within the bounds of
4328 * snapshot isolation, they can occur inside a serializable transaction, and
4329 * will logically occur after any reads which saw rows which were destroyed
4330 * by these operations, so we do what we can to serialize properly under
4331 * SSI.
4332 *
4333 * The relation passed in must be a heap relation. Any predicate lock of any
4334 * granularity on the heap will cause a rw-conflict in to this transaction.
4335 * Predicate locks on indexes do not matter because they only exist to guard
4336 * against conflicting inserts into the index, and this is a mass *delete*.
4337 * When a table is truncated or dropped, the index will also be truncated
4338 * or dropped, and we'll deal with locks on the index when that happens.
4339 *
4340 * Dropping or truncating a table also needs to drop any existing predicate
4341 * locks on heap tuples or pages, because they're about to go away. This
4342 * should be done before altering the predicate locks because the transaction
4343 * could be rolled back because of a conflict, in which case the lock changes
4344 * are not needed. (At the moment, we don't actually bother to drop the
4345 * existing locks on a dropped or truncated table at the moment. That might
4346 * lead to some false positives, but it doesn't seem worth the trouble.)
4347 */
4348void
4350{
4352 PREDICATELOCKTARGET *target;
4353 Oid dbId;
4354 Oid heapId;
4355 int i;
4356
4357 /*
4358 * Bail out quickly if there are no serializable transactions running.
4359 * It's safe to check this without taking locks because the caller is
4360 * holding an ACCESS EXCLUSIVE lock on the relation. No new locks which
4361 * would matter here can be acquired while that is held.
4362 */
4364 return;
4365
4366 if (!SerializationNeededForWrite(relation))
4367 return;
4368
4369 /*
4370 * We're doing a write which might cause rw-conflicts now or later.
4371 * Memorize that fact.
4372 */
4373 MyXactDidWrite = true;
4374
4375 Assert(relation->rd_index == NULL); /* not an index relation */
4376
4377 dbId = relation->rd_locator.dbOid;
4378 heapId = relation->rd_id;
4379
4381 for (i = 0; i < NUM_PREDICATELOCK_PARTITIONS; i++)
4384
4385 /* Scan through target list */
4387
4388 while ((target = (PREDICATELOCKTARGET *) hash_seq_search(&seqstat)))
4389 {
4390 dlist_mutable_iter iter;
4391
4392 /*
4393 * Check whether this is a target which needs attention.
4394 */
4396 continue; /* wrong relation id */
4397 if (GET_PREDICATELOCKTARGETTAG_DB(target->tag) != dbId)
4398 continue; /* wrong database id */
4399
4400 /*
4401 * Loop through locks for this target and flag conflicts.
4402 */
4403 dlist_foreach_modify(iter, &target->predicateLocks)
4404 {
4406 dlist_container(PREDICATELOCK, targetLink, iter.cur);
4407
4408 if (predlock->tag.myXact != MySerializableXact
4410 {
4412 }
4413 }
4414 }
4415
4416 /* Release locks in reverse order */
4418 for (i = NUM_PREDICATELOCK_PARTITIONS - 1; i >= 0; i--)
4421}
4422
4423
4424/*
4425 * Flag a rw-dependency between two serializable transactions.
4426 *
4427 * The caller is responsible for ensuring that we have a LW lock on
4428 * the transaction hash table.
4429 */
4430static void
4432{
4433 Assert(reader != writer);
4434
4435 /* First, see if this conflict causes failure. */
4437
4438 /* Actually do the conflict flagging. */
4439 if (reader == OldCommittedSxact)
4441 else if (writer == OldCommittedSxact)
4443 else
4444 SetRWConflict(reader, writer);
4445}
4446
4447/*----------------------------------------------------------------------------
4448 * We are about to add a RW-edge to the dependency graph - check that we don't
4449 * introduce a dangerous structure by doing so, and abort one of the
4450 * transactions if so.
4451 *
4452 * A serialization failure can only occur if there is a dangerous structure
4453 * in the dependency graph:
4454 *
4455 * Tin ------> Tpivot ------> Tout
4456 * rw rw
4457 *
4458 * Furthermore, Tout must commit first.
4459 *
4460 * One more optimization is that if Tin is declared READ ONLY (or commits
4461 * without writing), we can only have a problem if Tout committed before Tin
4462 * acquired its snapshot.
4463 *----------------------------------------------------------------------------
4464 */
4465static void
4468{
4469 bool failure;
4470
4472
4473 failure = false;
4474
4475 /*------------------------------------------------------------------------
4476 * Check for already-committed writer with rw-conflict out flagged
4477 * (conflict-flag on W means that T2 committed before W):
4478 *
4479 * R ------> W ------> T2
4480 * rw rw
4481 *
4482 * That is a dangerous structure, so we must abort. (Since the writer
4483 * has already committed, we must be the reader)
4484 *------------------------------------------------------------------------
4485 */
4488 failure = true;
4489
4490 /*------------------------------------------------------------------------
4491 * Check whether the writer has become a pivot with an out-conflict
4492 * committed transaction (T2), and T2 committed first:
4493 *
4494 * R ------> W ------> T2
4495 * rw rw
4496 *
4497 * Because T2 must've committed first, there is no anomaly if:
4498 * - the reader committed before T2
4499 * - the writer committed before T2
4500 * - the reader is a READ ONLY transaction and the reader was concurrent
4501 * with T2 (= reader acquired its snapshot before T2 committed)
4502 *
4503 * We also handle the case that T2 is prepared but not yet committed
4504 * here. In that case T2 has already checked for conflicts, so if it
4505 * commits first, making the above conflict real, it's too late for it
4506 * to abort.
4507 *------------------------------------------------------------------------
4508 */
4510 failure = true;
4511 else if (!failure)
4512 {
4513 dlist_iter iter;
4514
4515 dlist_foreach(iter, &writer->outConflicts)
4516 {
4518 dlist_container(RWConflictData, outLink, iter.cur);
4519 SERIALIZABLEXACT *t2 = conflict->sxactIn;
4520
4521 if (SxactIsPrepared(t2)
4522 && (!SxactIsCommitted(reader)
4523 || t2->prepareSeqNo <= reader->commitSeqNo)
4525 || t2->prepareSeqNo <= writer->commitSeqNo)
4526 && (!SxactIsReadOnly(reader)
4527 || t2->prepareSeqNo <= reader->SeqNo.lastCommitBeforeSnapshot))
4528 {
4529 failure = true;
4530 break;
4531 }
4532 }
4533 }
4534
4535 /*------------------------------------------------------------------------
4536 * Check whether the reader has become a pivot with a writer
4537 * that's committed (or prepared):
4538 *
4539 * T0 ------> R ------> W
4540 * rw rw
4541 *
4542 * Because W must've committed first for an anomaly to occur, there is no
4543 * anomaly if:
4544 * - T0 committed before the writer
4545 * - T0 is READ ONLY, and overlaps the writer
4546 *------------------------------------------------------------------------
4547 */
4548 if (!failure && SxactIsPrepared(writer) && !SxactIsReadOnly(reader))
4549 {
4550 if (SxactHasSummaryConflictIn(reader))
4551 {
4552 failure = true;
4553 }
4554 else
4555 {
4556 dlist_iter iter;
4557
4558 /*
4559 * The unconstify is needed as we have no const version of
4560 * dlist_foreach().
4561 */
4562 dlist_foreach(iter, &unconstify(SERIALIZABLEXACT *, reader)->inConflicts)
4563 {
4564 const RWConflict conflict =
4565 dlist_container(RWConflictData, inLink, iter.cur);
4566 const SERIALIZABLEXACT *t0 = conflict->sxactOut;
4567
4568 if (!SxactIsDoomed(t0)
4569 && (!SxactIsCommitted(t0)
4570 || t0->commitSeqNo >= writer->prepareSeqNo)
4571 && (!SxactIsReadOnly(t0)
4572 || t0->SeqNo.lastCommitBeforeSnapshot >= writer->prepareSeqNo))
4573 {
4574 failure = true;
4575 break;
4576 }
4577 }
4578 }
4579 }
4580
4581 if (failure)
4582 {
4583 /*
4584 * We have to kill a transaction to avoid a possible anomaly from
4585 * occurring. If the writer is us, we can just ereport() to cause a
4586 * transaction abort. Otherwise we flag the writer for termination,
4587 * causing it to abort when it tries to commit. However, if the writer
4588 * is a prepared transaction, already prepared, we can't abort it
4589 * anymore, so we have to kill the reader instead.
4590 */
4592 {
4594 ereport(ERROR,
4596 errmsg("could not serialize access due to read/write dependencies among transactions"),
4597 errdetail_internal("Reason code: Canceled on identification as a pivot, during write."),
4598 errhint("The transaction might succeed if retried.")));
4599 }
4600 else if (SxactIsPrepared(writer))
4601 {
4603
4604 /* if we're not the writer, we have to be the reader */
4605 Assert(MySerializableXact == reader);
4606 ereport(ERROR,
4608 errmsg("could not serialize access due to read/write dependencies among transactions"),
4609 errdetail_internal("Reason code: Canceled on conflict out to pivot %u, during read.", writer->topXid),
4610 errhint("The transaction might succeed if retried.")));
4611 }
4612 writer->flags |= SXACT_FLAG_DOOMED;
4613 }
4614}
4615
4616/*
4617 * PreCommit_CheckForSerializationFailure
4618 * Check for dangerous structures in a serializable transaction
4619 * at commit.
4620 *
4621 * We're checking for a dangerous structure as each conflict is recorded.
4622 * The only way we could have a problem at commit is if this is the "out"
4623 * side of a pivot, and neither the "in" side nor the pivot has yet
4624 * committed.
4625 *
4626 * If a dangerous structure is found, the pivot (the near conflict) is
4627 * marked for death, because rolling back another transaction might mean
4628 * that we fail without ever making progress. This transaction is
4629 * committing writes, so letting it commit ensures progress. If we
4630 * canceled the far conflict, it might immediately fail again on retry.
4631 */
4632void
4634{
4636
4638 return;
4639
4641
4643
4644 /*
4645 * Check if someone else has already decided that we need to die. Since
4646 * we set our own DOOMED flag when partially releasing, ignore in that
4647 * case.
4648 */
4651 {
4653 ereport(ERROR,
4655 errmsg("could not serialize access due to read/write dependencies among transactions"),
4656 errdetail_internal("Reason code: Canceled on identification as a pivot, during commit attempt."),
4657 errhint("The transaction might succeed if retried.")));
4658 }
4659
4661 {
4664
4665 if (!SxactIsCommitted(nearConflict->sxactOut)
4666 && !SxactIsDoomed(nearConflict->sxactOut))
4667 {
4669
4670 dlist_foreach(far_iter, &nearConflict->sxactOut->inConflicts)
4671 {
4674
4675 if (farConflict->sxactOut == MySerializableXact
4676 || (!SxactIsCommitted(farConflict->sxactOut)
4677 && !SxactIsReadOnly(farConflict->sxactOut)
4678 && !SxactIsDoomed(farConflict->sxactOut)))
4679 {
4680 /*
4681 * Normally, we kill the pivot transaction to make sure we
4682 * make progress if the failing transaction is retried.
4683 * However, we can't kill it if it's already prepared, so
4684 * in that case we commit suicide instead.
4685 */
4686 if (SxactIsPrepared(nearConflict->sxactOut))
4687 {
4689 ereport(ERROR,
4691 errmsg("could not serialize access due to read/write dependencies among transactions"),
4692 errdetail_internal("Reason code: Canceled on commit attempt with conflict in from prepared pivot."),
4693 errhint("The transaction might succeed if retried.")));
4694 }
4695 nearConflict->sxactOut->flags |= SXACT_FLAG_DOOMED;
4696 break;
4697 }
4698 }
4699 }
4700 }
4701
4704
4706}
4707
4708/*------------------------------------------------------------------------*/
4709
4710/*
4711 * Two-phase commit support
4712 */
4713
4714/*
4715 * AtPrepare_Locks
4716 * Do the preparatory work for a PREPARE: make 2PC state file
4717 * records for all predicate locks currently held.
4718 */
4719void
4721{
4724 TwoPhasePredicateXactRecord *xactRecord;
4725 TwoPhasePredicateLockRecord *lockRecord;
4726 dlist_iter iter;
4727
4729 xactRecord = &(record.data.xactRecord);
4730 lockRecord = &(record.data.lockRecord);
4731
4733 return;
4734
4735 /* Generate an xact record for our SERIALIZABLEXACT */
4737 xactRecord->xmin = MySerializableXact->xmin;
4738 xactRecord->flags = MySerializableXact->flags;
4739
4740 /*
4741 * Note that we don't include the list of conflicts in our out in the
4742 * statefile, because new conflicts can be added even after the
4743 * transaction prepares. We'll just make a conservative assumption during
4744 * recovery instead.
4745 */
4746
4748 &record, sizeof(record));
4749
4750 /*
4751 * Generate a lock record for each lock.
4752 *
4753 * To do this, we need to walk the predicate lock list in our sxact rather
4754 * than using the local predicate lock table because the latter is not
4755 * guaranteed to be accurate.
4756 */
4758
4759 /*
4760 * No need to take sxact->perXactPredicateListLock in parallel mode
4761 * because there cannot be any parallel workers running while we are
4762 * preparing a transaction.
4763 */
4765
4766 dlist_foreach(iter, &sxact->predicateLocks)
4767 {
4769 dlist_container(PREDICATELOCK, xactLink, iter.cur);
4770
4772 lockRecord->target = predlock->tag.myTarget->tag;
4773
4775 &record, sizeof(record));
4776 }
4777
4779}
4780
4781/*
4782 * PostPrepare_Locks
4783 * Clean up after successful PREPARE. Unlike the non-predicate
4784 * lock manager, we do not need to transfer locks to a dummy
4785 * PGPROC because our SERIALIZABLEXACT will stay around
4786 * anyway. We only need to clean up our local state.
4787 */
4788void
4805
4806/*
4807 * PredicateLockTwoPhaseFinish
4808 * Release a prepared transaction's predicate locks once it
4809 * commits or aborts.
4810 */
4811void
4813{
4816
4818
4820 sxid = (SERIALIZABLEXID *)
4823
4824 /* xid will not be found if it wasn't a serializable transaction */
4825 if (sxid == NULL)
4826 return;
4827
4828 /* Release its locks */
4829 MySerializableXact = sxid->myXact;
4830 MyXactDidWrite = true; /* conservatively assume that we wrote
4831 * something */
4833}
4834
4835/*
4836 * Re-acquire a predicate lock belonging to a transaction that was prepared.
4837 */
4838void
4840 void *recdata, uint32 len)
4841{
4844
4846
4847 record = (TwoPhasePredicateRecord *) recdata;
4848
4850 (record->type == TWOPHASEPREDICATERECORD_LOCK));
4851
4852 if (record->type == TWOPHASEPREDICATERECORD_XACT)
4853 {
4854 /* Per-transaction record. Set up a SERIALIZABLEXACT. */
4855 TwoPhasePredicateXactRecord *xactRecord;
4859 bool found;
4860
4861 xactRecord = (TwoPhasePredicateXactRecord *) &record->data.xactRecord;
4862
4865 if (!sxact)
4866 ereport(ERROR,
4868 errmsg("out of shared memory")));
4869
4870 /* vxid for a prepared xact is INVALID_PROC_NUMBER/xid; no pid */
4871 sxact->vxid.procNumber = INVALID_PROC_NUMBER;
4872 sxact->vxid.localTransactionId = (LocalTransactionId) xid;
4873 sxact->pid = 0;
4874 sxact->pgprocno = INVALID_PROC_NUMBER;
4875
4876 /* a prepared xact hasn't committed yet */
4877 sxact->prepareSeqNo = RecoverySerCommitSeqNo;
4878 sxact->commitSeqNo = InvalidSerCommitSeqNo;
4879 sxact->finishedBefore = InvalidTransactionId;
4880
4881 sxact->SeqNo.lastCommitBeforeSnapshot = RecoverySerCommitSeqNo;
4882
4883 /*
4884 * Don't need to track this; no transactions running at the time the
4885 * recovered xact started are still active, except possibly other
4886 * prepared xacts and we don't care whether those are RO_SAFE or not.
4887 */
4888 dlist_init(&(sxact->possibleUnsafeConflicts));
4889
4890 dlist_init(&(sxact->predicateLocks));
4891 dlist_node_init(&sxact->finishedLink);
4892
4893 sxact->topXid = xid;
4894 sxact->xmin = xactRecord->xmin;
4895 sxact->flags = xactRecord->flags;
4897 if (!SxactIsReadOnly(sxact))
4898 {
4902 }
4903
4904 /*
4905 * We don't know whether the transaction had any conflicts or not, so
4906 * we'll conservatively assume that it had both a conflict in and a
4907 * conflict out, and represent that with the summary conflict flags.
4908 */
4909 dlist_init(&(sxact->outConflicts));
4910 dlist_init(&(sxact->inConflicts));
4913
4914 /* Register the transaction's xid */
4915 sxidtag.xid = xid;
4917 &sxidtag,
4918 HASH_ENTER, &found);
4919 Assert(sxid != NULL);
4920 Assert(!found);
4921 sxid->myXact = sxact;
4922
4923 /*
4924 * Update global xmin. Note that this is a special case compared to
4925 * registering a normal transaction, because the global xmin might go
4926 * backwards. That's OK, because until recovery is over we're not
4927 * going to complete any transactions or create any non-prepared
4928 * transactions, so there's no danger of throwing away.
4929 */
4932 {
4936 }
4938 {
4941 }
4942
4944 }
4945 else if (record->type == TWOPHASEPREDICATERECORD_LOCK)
4946 {
4947 /* Lock record. Recreate the PREDICATELOCK */
4948 TwoPhasePredicateLockRecord *lockRecord;
4953
4954 lockRecord = (TwoPhasePredicateLockRecord *) &record->data.lockRecord;
4956
4958 sxidtag.xid = xid;
4959 sxid = (SERIALIZABLEXID *)
4962
4963 Assert(sxid != NULL);
4964 sxact = sxid->myXact;
4966
4968 }
4969}
4970
4971/*
4972 * Prepare to share the current SERIALIZABLEXACT with parallel workers.
4973 * Return a handle object that can be used by AttachSerializableXact() in a
4974 * parallel worker.
4975 */
4978{
4979 return MySerializableXact;
4980}
4981
4982/*
4983 * Allow parallel workers to import the leader's SERIALIZABLEXACT.
4984 */
4985void
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:1325
#define PG_USED_FOR_ASSERTS_ONLY
Definition c.h:249
#define Assert(condition)
Definition c.h:943
int64_t int64
Definition c.h:621
uint16_t uint16
Definition c.h:623
uint32_t uint32
Definition c.h:624
uint32 LocalTransactionId
Definition c.h:738
uint32 TransactionId
Definition c.h:736
size_t Size
Definition c.h:689
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
void hash_destroy(HTAB *hashp)
Definition dynahash.c:802
void * hash_search_with_hash_value(HTAB *hashp, const void *keyPtr, uint32 hashvalue, HASHACTION action, bool *foundPtr)
Definition dynahash.c:902
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1352
int64 hash_get_num_entries(HTAB *hashp)
Definition dynahash.c:1273
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1317
Datum arg
Definition elog.c:1322
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:30
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
#define palloc_object(type)
Definition fe_memutils.h:74
#define palloc_array(type, count)
Definition fe_memutils.h:76
int MyProcPid
Definition globals.c:49
ProcNumber MyProcNumber
Definition globals.c:92
int MaxBackends
Definition globals.c:149
int serializable_buffers
Definition globals.c:168
#define newval
GucSource
Definition guc.h:112
@ HASH_FIND
Definition hsearch.h:108
@ HASH_REMOVE
Definition hsearch.h:110
@ HASH_ENTER
Definition hsearch.h:109
@ HASH_ENTER_NULL
Definition hsearch.h:111
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_FUNCTION
Definition hsearch.h:93
#define HASH_BLOBS
Definition hsearch.h:92
#define HASH_FIXED_SIZE
Definition hsearch.h:100
#define HASH_PARTITION
Definition hsearch.h:87
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:188
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:80
#define SetInvalidVirtualTransactionId(vxid)
Definition lock.h:77
bool LWLockHeldByMe(LWLock *lock)
Definition lwlock.c:1885
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1150
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1929
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition lwlock.c:670
@ LW_SHARED
Definition lwlock.h:105
@ LW_EXCLUSIVE
Definition lwlock.h:104
#define NUM_PREDICATELOCK_PARTITIONS
Definition lwlock.h:91
#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:1377
void CheckPointPredicate(void)
Definition predicate.c:1022
void PredicateLockPageSplit(Relation relation, BlockNumber oldblkno, BlockNumber newblkno)
Definition predicate.c:3074
static void DecrementParentLocks(const PREDICATELOCKTARGETTAG *targettag)
Definition predicate.c:2321
static HTAB * PredicateLockHash
Definition predicate.c:411
static void SetPossibleUnsafeConflict(SERIALIZABLEXACT *roXact, SERIALIZABLEXACT *activeXact)
Definition predicate.c:680
#define PredicateLockTargetTagHashCode(predicatelocktargettag)
Definition predicate.c:302
static void SetNewSxactGlobalXmin(void)
Definition predicate.c:3181
void CheckForSerializableConflictIn(Relation relation, const ItemPointerData *tid, BlockNumber blkno)
Definition predicate.c:4266
#define SerialPage(xid)
Definition predicate.c:345
static void ReleasePredXact(SERIALIZABLEXACT *sxact)
Definition predicate.c:610
static void PredicateLockShmemInit(void *arg)
Definition predicate.c:1244
void SetSerializableTransactionSnapshot(Snapshot snapshot, VirtualTransactionId *sourcevxid, int sourcepid)
Definition predicate.c:1652
static bool RWConflictExists(const SERIALIZABLEXACT *reader, const SERIALIZABLEXACT *writer)
Definition predicate.c:624
static bool PredicateLockingNeededForRelation(Relation relation)
Definition predicate.c:512
static bool SerializationNeededForRead(Relation relation, Snapshot snapshot)
Definition predicate.c:530
static Snapshot GetSafeSnapshot(Snapshot origSnapshot)
Definition predicate.c:1488
#define SxactIsCommitted(sxact)
Definition predicate.c:276
static SerialControl serialControl
Definition predicate.c:356
void PredicateLockPage(Relation relation, BlockNumber blkno, Snapshot snapshot)
Definition predicate.c:2529
#define SxactIsROUnsafe(sxact)
Definition predicate.c:291
static Snapshot GetSerializableTransactionSnapshotInt(Snapshot snapshot, VirtualTransactionId *sourcevxid, int sourcepid)
Definition predicate.c:1694
static LWLock * ScratchPartitionLock
Definition predicate.c:421
static void PredicateLockAcquire(const PREDICATELOCKTARGETTAG *targettag)
Definition predicate.c:2447
#define SxactIsDeferrableWaiting(sxact)
Definition predicate.c:289
static void ReleasePredicateLocksLocal(void)
Definition predicate.c:3609
static HTAB * LocalPredicateLockHash
Definition predicate.c:427
int max_predicate_locks_per_page
Definition predicate.c:375
struct SerialControlData * SerialControl
Definition predicate.c:354
static PredXactList PredXact
Definition predicate.c:386
static void SetRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
Definition predicate.c:657
int GetSafeSnapshotBlockingPids(int blocked_pid, int *output, int output_size)
Definition predicate.c:1558
static uint32 ScratchTargetTagHash
Definition predicate.c:420
static void RemoveTargetIfNoLongerUsed(PREDICATELOCKTARGET *target, uint32 targettaghash)
Definition predicate.c:2113
static uint32 predicatelock_hash(const void *key, Size keysize)
Definition predicate.c:1351
void CheckForSerializableConflictOut(Relation relation, TransactionId xid, Snapshot snapshot)
Definition predicate.c:3953
static int64 max_serializable_xacts
Definition predicate.c:446
#define SxactIsReadOnly(sxact)
Definition predicate.c:280
#define SerialNextPage(page)
Definition predicate.c:339
static void DropAllPredicateLocksFromTable(Relation relation, bool transfer)
Definition predicate.c:2867
bool PageIsPredicateLocked(Relation relation, BlockNumber blkno)
Definition predicate.c:1938
static int serial_errdetail_for_io_error(const void *opaque_data)
Definition predicate.c:760
static void CreatePredicateLock(const PREDICATELOCKTARGETTAG *targettag, uint32 targettaghash, SERIALIZABLEXACT *sxact)
Definition predicate.c:2383
static void SerialAdd(TransactionId xid, SerCommitSeqNo minConflictCommitSeqNo)
Definition predicate.c:839
static void ClearOldPredicateLocks(void)
Definition predicate.c:3627
#define SxactHasSummaryConflictIn(sxact)
Definition predicate.c:281
static SERIALIZABLEXACT * CreatePredXact(void)
Definition predicate.c:596
static bool GetParentPredicateLockTag(const PREDICATELOCKTARGETTAG *tag, PREDICATELOCKTARGETTAG *parent)
Definition predicate.c:2002
#define PredicateLockHashCodeFromTargetHashCode(predicatelocktag, targethash)
Definition predicate.c:315
static void RestoreScratchTarget(bool lockheld)
Definition predicate.c:2091
#define SerialValue(slotno, xid)
Definition predicate.c:341
static void DeleteChildTargetLocks(const PREDICATELOCKTARGETTAG *newtargettag)
Definition predicate.c:2144
static void DeleteLockTarget(PREDICATELOCKTARGET *target, uint32 targettaghash)
Definition predicate.c:2599
void PredicateLockTwoPhaseFinish(FullTransactionId fxid, bool isCommit)
Definition predicate.c:4812
void predicatelock_twophase_recover(FullTransactionId fxid, uint16 info, void *recdata, uint32 len)
Definition predicate.c:4839
static SlruDesc SerialSlruDesc
Definition predicate.c:326
static SERIALIZABLEXACT * OldCommittedSxact
Definition predicate.c:364
#define SxactHasConflictOut(sxact)
Definition predicate.c:288
static bool MyXactDidWrite
Definition predicate.c:435
static int MaxPredicateChildLocks(const PREDICATELOCKTARGETTAG *tag)
Definition predicate.c:2219
static void FlagSxactUnsafe(SERIALIZABLEXACT *sxact)
Definition predicate.c:713
static void PredicateLockShmemRequest(void *arg)
Definition predicate.c:1119
void CheckTableForSerializableConflictIn(Relation relation)
Definition predicate.c:4349
#define SxactIsPrepared(sxact)
Definition predicate.c:277
void AttachSerializableXact(SerializableXactHandle handle)
Definition predicate.c:4986
SerializableXactHandle ShareSerializableXact(void)
Definition predicate.c:4977
static bool PredicateLockExists(const PREDICATELOCKTARGETTAG *targettag)
Definition predicate.c:1975
static void RemoveScratchTarget(bool lockheld)
Definition predicate.c:2070
#define SxactIsOnFinishedList(sxact)
Definition predicate.c:266
#define SxactIsPartiallyReleased(sxact)
Definition predicate.c:292
static void SerialSetActiveSerXmin(TransactionId xid)
Definition predicate.c:971
static dlist_head * FinishedSerializableTransactions
Definition predicate.c:412
static bool SerializationNeededForWrite(Relation relation)
Definition predicate.c:574
static HTAB * SerializableXidHash
Definition predicate.c:409
static bool CheckAndPromotePredicateLockRequest(const PREDICATELOCKTARGETTAG *reqtag)
Definition predicate.c:2256
void PredicateLockPageCombine(Relation relation, BlockNumber oldblkno, BlockNumber newblkno)
Definition predicate.c:3159
static bool SerialPagePrecedesLogically(int64 page1, int64 page2)
Definition predicate.c:745
static void CheckTargetForConflictsIn(PREDICATELOCKTARGETTAG *targettag)
Definition predicate.c:4096
int max_predicate_locks_per_relation
Definition predicate.c:374
#define SxactIsROSafe(sxact)
Definition predicate.c:290
void PreCommit_CheckForSerializationFailure(void)
Definition predicate.c:4633
void ReleasePredicateLocks(bool isCommit, bool isReadOnlySafe)
Definition predicate.c:3242
static void FlagRWConflict(SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
Definition predicate.c:4431
static const PREDICATELOCKTARGETTAG ScratchTargetTag
Definition predicate.c:419
#define PredicateLockHashPartitionLockByIndex(i)
Definition predicate.c:260
static void OnConflict_CheckForSerializationFailure(const SERIALIZABLEXACT *reader, SERIALIZABLEXACT *writer)
Definition predicate.c:4466
static bool CoarserLockCovers(const PREDICATELOCKTARGETTAG *newtargettag)
Definition predicate.c:2041
void PredicateLockRelation(Relation relation, Snapshot snapshot)
Definition predicate.c:2506
static SERIALIZABLEXACT * MySerializableXact
Definition predicate.c:434
void PredicateLockTID(Relation relation, const ItemPointerData *tid, Snapshot snapshot, TransactionId tuple_xid)
Definition predicate.c:2551
#define SxactIsDoomed(sxact)
Definition predicate.c:279
#define NPREDICATELOCKTARGETENTS()
Definition predicate.c:263
static SerCommitSeqNo SerialGetMinConflictCommitSeqNo(TransactionId xid)
Definition predicate.c:930
static void SummarizeOldestCommittedSxact(void)
Definition predicate.c:1433
const ShmemCallbacks PredicateLockShmemCallbacks
Definition predicate.c:392
bool check_serial_buffers(int *newval, void **extra, GucSource source)
Definition predicate.c:828
void PostPrepare_PredicateLocks(FullTransactionId fxid)
Definition predicate.c:4789
#define TargetTagIsCoveredBy(covered_target, covering_target)
Definition predicate.c:232
static RWConflictPoolHeader RWConflictPool
Definition predicate.c:403
static void ReleaseRWConflict(RWConflict conflict)
Definition predicate.c:705
static bool TransferPredicateLocksToNewTarget(PREDICATELOCKTARGETTAG oldtargettag, PREDICATELOCKTARGETTAG newtargettag, bool removeOld)
Definition predicate.c:2660
void AtPrepare_PredicateLocks(void)
Definition predicate.c:4720
void RegisterPredicateLockingXid(TransactionId xid)
Definition predicate.c:1889
#define PredicateLockHashPartitionLock(hashcode)
Definition predicate.c:257
#define SERIAL_ENTRIESPERPAGE
Definition predicate.c:332
static bool XidIsConcurrent(TransactionId xid)
Definition predicate.c:3902
static void ReleaseOneSerializableXact(SERIALIZABLEXACT *sxact, bool partial, bool summarize)
Definition predicate.c:3765
static HTAB * PredicateLockTargetHash
Definition predicate.c:410
bool CheckForSerializableConflictOutNeeded(Relation relation, Snapshot snapshot)
Definition predicate.c:3921
#define SxactIsRolledBack(sxact)
Definition predicate.c:278
static SERIALIZABLEXACT * SavedSerializableXact
Definition predicate.c:444
#define SxactHasSummaryConflictOut(sxact)
Definition predicate.c:282
static void PredicateLockShmemAttach(void *arg)
Definition predicate.c:1328
void TransferPredicateLocksToHeapRelation(Relation relation)
Definition predicate.c:3053
static void CreateLocalPredicateLockHash(void)
Definition predicate.c:1870
#define SerialSlruCtl
Definition predicate.c:328
int max_predicate_locks_per_xact
Definition predicate.c:373
Snapshot GetSerializableTransactionSnapshot(Snapshot snapshot)
Definition predicate.c:1612
void * SerializableXactHandle
Definition predicate.h:39
#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:2114
bool ProcArrayInstallImportedXmin(TransactionId xmin, VirtualTransactionId *sourcevxid)
Definition procarray.c:2471
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
#define RelationUsesLocalBuffers(relation)
Definition rel.h:648
bool ShmemAddrIsValid(const void *addr)
Definition shmem.c:850
Size add_size(Size s1, Size s2)
Definition shmem.c:1048
Size mul_size(Size s1, Size s2)
Definition shmem.c:1063
#define ShmemRequestHash(...)
Definition shmem.h:179
#define ShmemRequestStruct(...)
Definition shmem.h:176
int SimpleLruReadPage_ReadOnly(SlruDesc *ctl, int64 pageno, const void *opaque_data)
Definition slru.c:654
void SimpleLruTruncate(SlruDesc *ctl, int64 cutoffPage)
Definition slru.c:1458
int SimpleLruZeroPage(SlruDesc *ctl, int64 pageno)
Definition slru.c:397
void SimpleLruWriteAll(SlruDesc *ctl, bool allow_redirtied)
Definition slru.c:1372
int SimpleLruReadPage(SlruDesc *ctl, int64 pageno, bool write_ok, const void *opaque_data)
Definition slru.c:550
bool check_slru_buffers(const char *name, int *newval)
Definition slru.c:377
#define SlruPagePrecedesUnitTests(ctl, per_page)
Definition slru.h:233
#define SimpleLruRequest(...)
Definition slru.h:218
static LWLock * SimpleLruGetBankLock(SlruDesc *ctl, int64 pageno)
Definition slru.h:207
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
#define IsMVCCSnapshot(snapshot)
Definition snapmgr.h:59
void ProcSendSignal(ProcNumber procNumber)
Definition proc.c:2027
PGPROC * MyProc
Definition proc.c:71
void ProcWaitForSignal(uint32 wait_event_info)
Definition proc.c:2015
Size keysize
Definition dynahash.c:241
Definition proc.h:179
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::@134 SeqNo
TransactionId finishedBefore
SerCommitSeqNo earliestOutConflictCommit
TransactionId headXid
Definition predicate.c:350
TransactionId tailXid
Definition predicate.c:351
ShmemRequestCallback request_fn
Definition shmem.h:133
TransactionId xmin
Definition snapshot.h:153
FullTransactionId nextXid
Definition transam.h:220
PREDICATELOCKTARGETTAG target
TwoPhasePredicateRecordType type
TwoPhasePredicateLockRecord lockRecord
union TwoPhasePredicateRecord::@135 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:1277
int max_prepared_xacts
Definition twophase.c:118
#define TWOPHASE_RM_PREDICATELOCK_ID
TransamVariablesData * TransamVariables
Definition varsup.c:37
const char * name
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:5095
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition xact.c:943
bool IsInParallelMode(void)
Definition xact.c:1119
#define IsolationIsSerializable()
Definition xact.h:53
bool RecoveryInProgress(void)
Definition xlog.c:6830