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