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