LCOV - code coverage report
Current view: top level - src/backend/storage/lmgr - predicate.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 1029 1376 74.8 %
Date: 2020-06-01 09:07:10 Functions: 65 72 90.3 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13