LCOV - code coverage report
Current view: top level - src/backend/storage/lmgr - predicate.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 73.6 % 1276 939
Test Date: 2026-11-14 00:16:44 Functions: 88.7 % 71 63
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 62.3 % 818 510

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

Generated by: LCOV version 2.0-1