LCOV - code coverage report
Current view: top level - src/backend/access/heap - heapam.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 91.7 % 2736 2510
Test Date: 2026-03-01 01:14:39 Functions: 100.0 % 82 82
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /*-------------------------------------------------------------------------
       2              :  *
       3              :  * heapam.c
       4              :  *    heap access method code
       5              :  *
       6              :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7              :  * Portions Copyright (c) 1994, Regents of the University of California
       8              :  *
       9              :  *
      10              :  * IDENTIFICATION
      11              :  *    src/backend/access/heap/heapam.c
      12              :  *
      13              :  *
      14              :  * INTERFACE ROUTINES
      15              :  *      heap_beginscan  - begin relation scan
      16              :  *      heap_rescan     - restart a relation scan
      17              :  *      heap_endscan    - end relation scan
      18              :  *      heap_getnext    - retrieve next tuple in scan
      19              :  *      heap_fetch      - retrieve tuple with given tid
      20              :  *      heap_insert     - insert tuple into a relation
      21              :  *      heap_multi_insert - insert multiple tuples into a relation
      22              :  *      heap_delete     - delete a tuple from a relation
      23              :  *      heap_update     - replace a tuple in a relation with another tuple
      24              :  *
      25              :  * NOTES
      26              :  *    This file contains the heap_ routines which implement
      27              :  *    the POSTGRES heap access method used for all POSTGRES
      28              :  *    relations.
      29              :  *
      30              :  *-------------------------------------------------------------------------
      31              :  */
      32              : #include "postgres.h"
      33              : 
      34              : #include "access/heapam.h"
      35              : #include "access/heaptoast.h"
      36              : #include "access/hio.h"
      37              : #include "access/multixact.h"
      38              : #include "access/subtrans.h"
      39              : #include "access/syncscan.h"
      40              : #include "access/valid.h"
      41              : #include "access/visibilitymap.h"
      42              : #include "access/xloginsert.h"
      43              : #include "catalog/pg_database.h"
      44              : #include "catalog/pg_database_d.h"
      45              : #include "commands/vacuum.h"
      46              : #include "pgstat.h"
      47              : #include "port/pg_bitutils.h"
      48              : #include "storage/lmgr.h"
      49              : #include "storage/predicate.h"
      50              : #include "storage/proc.h"
      51              : #include "storage/procarray.h"
      52              : #include "utils/datum.h"
      53              : #include "utils/injection_point.h"
      54              : #include "utils/inval.h"
      55              : #include "utils/spccache.h"
      56              : #include "utils/syscache.h"
      57              : 
      58              : 
      59              : static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
      60              :                                      TransactionId xid, CommandId cid, int options);
      61              : static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
      62              :                                   Buffer newbuf, HeapTuple oldtup,
      63              :                                   HeapTuple newtup, HeapTuple old_key_tuple,
      64              :                                   bool all_visible_cleared, bool new_all_visible_cleared);
      65              : #ifdef USE_ASSERT_CHECKING
      66              : static void check_lock_if_inplace_updateable_rel(Relation relation,
      67              :                                                  const ItemPointerData *otid,
      68              :                                                  HeapTuple newtup);
      69              : static void check_inplace_rel_lock(HeapTuple oldtup);
      70              : #endif
      71              : static Bitmapset *HeapDetermineColumnsInfo(Relation relation,
      72              :                                            Bitmapset *interesting_cols,
      73              :                                            Bitmapset *external_cols,
      74              :                                            HeapTuple oldtup, HeapTuple newtup,
      75              :                                            bool *has_external);
      76              : static bool heap_acquire_tuplock(Relation relation, const ItemPointerData *tid,
      77              :                                  LockTupleMode mode, LockWaitPolicy wait_policy,
      78              :                                  bool *have_tuple_lock);
      79              : static inline BlockNumber heapgettup_advance_block(HeapScanDesc scan,
      80              :                                                    BlockNumber block,
      81              :                                                    ScanDirection dir);
      82              : static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan,
      83              :                                                         ScanDirection dir);
      84              : static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
      85              :                                       uint16 old_infomask2, TransactionId add_to_xmax,
      86              :                                       LockTupleMode mode, bool is_update,
      87              :                                       TransactionId *result_xmax, uint16 *result_infomask,
      88              :                                       uint16 *result_infomask2);
      89              : static TM_Result heap_lock_updated_tuple(Relation rel,
      90              :                                          uint16 prior_infomask,
      91              :                                          TransactionId prior_raw_xmax,
      92              :                                          const ItemPointerData *prior_ctid,
      93              :                                          TransactionId xid,
      94              :                                          LockTupleMode mode);
      95              : static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
      96              :                                    uint16 *new_infomask2);
      97              : static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax,
      98              :                                              uint16 t_infomask);
      99              : static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
     100              :                                     LockTupleMode lockmode, bool *current_is_member);
     101              : static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
     102              :                             Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
     103              :                             int *remaining);
     104              : static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
     105              :                                        uint16 infomask, Relation rel, int *remaining,
     106              :                                        bool logLockFailure);
     107              : static void index_delete_sort(TM_IndexDeleteOp *delstate);
     108              : static int  bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate);
     109              : static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
     110              : static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
     111              :                                         bool *copy);
     112              : 
     113              : 
     114              : /*
     115              :  * This table lists the heavyweight lock mode that corresponds to each tuple
     116              :  * lock mode, as well as one or two corresponding MultiXactStatus values:
     117              :  * .lockstatus to merely lock tuples, and .updstatus to update them.  The
     118              :  * latter is set to -1 if the corresponding tuple lock mode does not allow
     119              :  * updating tuples -- see get_mxact_status_for_lock().
     120              :  *
     121              :  * These interact with InplaceUpdateTupleLock, an alias for ExclusiveLock.
     122              :  *
     123              :  * Don't look at lockstatus/updstatus directly!  Use get_mxact_status_for_lock
     124              :  * instead.
     125              :  */
     126              : static const struct
     127              : {
     128              :     LOCKMODE    hwlock;
     129              :     int         lockstatus;
     130              :     int         updstatus;
     131              : }           tupleLockExtraInfo[] =
     132              : 
     133              : {
     134              :     [LockTupleKeyShare] = {
     135              :         .hwlock = AccessShareLock,
     136              :         .lockstatus = MultiXactStatusForKeyShare,
     137              :         /* KeyShare does not allow updating tuples */
     138              :         .updstatus = -1
     139              :     },
     140              :     [LockTupleShare] = {
     141              :         .hwlock = RowShareLock,
     142              :         .lockstatus = MultiXactStatusForShare,
     143              :         /* Share does not allow updating tuples */
     144              :         .updstatus = -1
     145              :     },
     146              :     [LockTupleNoKeyExclusive] = {
     147              :         .hwlock = ExclusiveLock,
     148              :         .lockstatus = MultiXactStatusForNoKeyUpdate,
     149              :         .updstatus = MultiXactStatusNoKeyUpdate
     150              :     },
     151              :     [LockTupleExclusive] = {
     152              :         .hwlock = AccessExclusiveLock,
     153              :         .lockstatus = MultiXactStatusForUpdate,
     154              :         .updstatus = MultiXactStatusUpdate
     155              :     }
     156              : };
     157              : 
     158              : /* Get the LOCKMODE for a given MultiXactStatus */
     159              : #define LOCKMODE_from_mxstatus(status) \
     160              :             (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
     161              : 
     162              : /*
     163              :  * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
     164              :  * This is more readable than having every caller translate it to lock.h's
     165              :  * LOCKMODE.
     166              :  */
     167              : #define LockTupleTuplock(rel, tup, mode) \
     168              :     LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
     169              : #define UnlockTupleTuplock(rel, tup, mode) \
     170              :     UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
     171              : #define ConditionalLockTupleTuplock(rel, tup, mode, log) \
     172              :     ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock, (log))
     173              : 
     174              : #ifdef USE_PREFETCH
     175              : /*
     176              :  * heap_index_delete_tuples and index_delete_prefetch_buffer use this
     177              :  * structure to coordinate prefetching activity
     178              :  */
     179              : typedef struct
     180              : {
     181              :     BlockNumber cur_hblkno;
     182              :     int         next_item;
     183              :     int         ndeltids;
     184              :     TM_IndexDelete *deltids;
     185              : } IndexDeletePrefetchState;
     186              : #endif
     187              : 
     188              : /* heap_index_delete_tuples bottom-up index deletion costing constants */
     189              : #define BOTTOMUP_MAX_NBLOCKS            6
     190              : #define BOTTOMUP_TOLERANCE_NBLOCKS      3
     191              : 
     192              : /*
     193              :  * heap_index_delete_tuples uses this when determining which heap blocks it
     194              :  * must visit to help its bottom-up index deletion caller
     195              :  */
     196              : typedef struct IndexDeleteCounts
     197              : {
     198              :     int16       npromisingtids; /* Number of "promising" TIDs in group */
     199              :     int16       ntids;          /* Number of TIDs in group */
     200              :     int16       ifirsttid;      /* Offset to group's first deltid */
     201              : } IndexDeleteCounts;
     202              : 
     203              : /*
     204              :  * This table maps tuple lock strength values for each particular
     205              :  * MultiXactStatus value.
     206              :  */
     207              : static const int MultiXactStatusLock[MaxMultiXactStatus + 1] =
     208              : {
     209              :     LockTupleKeyShare,          /* ForKeyShare */
     210              :     LockTupleShare,             /* ForShare */
     211              :     LockTupleNoKeyExclusive,    /* ForNoKeyUpdate */
     212              :     LockTupleExclusive,         /* ForUpdate */
     213              :     LockTupleNoKeyExclusive,    /* NoKeyUpdate */
     214              :     LockTupleExclusive          /* Update */
     215              : };
     216              : 
     217              : /* Get the LockTupleMode for a given MultiXactStatus */
     218              : #define TUPLOCK_from_mxstatus(status) \
     219              :             (MultiXactStatusLock[(status)])
     220              : 
     221              : /*
     222              :  * Check that we have a valid snapshot if we might need TOAST access.
     223              :  */
     224              : static inline void
     225     10604512 : AssertHasSnapshotForToast(Relation rel)
     226              : {
     227              : #ifdef USE_ASSERT_CHECKING
     228              : 
     229              :     /* bootstrap mode in particular breaks this rule */
     230              :     if (!IsNormalProcessingMode())
     231              :         return;
     232              : 
     233              :     /* if the relation doesn't have a TOAST table, we are good */
     234              :     if (!OidIsValid(rel->rd_rel->reltoastrelid))
     235              :         return;
     236              : 
     237              :     Assert(HaveRegisteredOrActiveSnapshot());
     238              : 
     239              : #endif                          /* USE_ASSERT_CHECKING */
     240     10604512 : }
     241              : 
     242              : /* ----------------------------------------------------------------
     243              :  *                       heap support routines
     244              :  * ----------------------------------------------------------------
     245              :  */
     246              : 
     247              : /*
     248              :  * Streaming read API callback for parallel sequential scans. Returns the next
     249              :  * block the caller wants from the read stream or InvalidBlockNumber when done.
     250              :  */
     251              : static BlockNumber
     252       101761 : heap_scan_stream_read_next_parallel(ReadStream *stream,
     253              :                                     void *callback_private_data,
     254              :                                     void *per_buffer_data)
     255              : {
     256       101761 :     HeapScanDesc scan = (HeapScanDesc) callback_private_data;
     257              : 
     258              :     Assert(ScanDirectionIsForward(scan->rs_dir));
     259              :     Assert(scan->rs_base.rs_parallel);
     260              : 
     261       101761 :     if (unlikely(!scan->rs_inited))
     262              :     {
     263              :         /* parallel scan */
     264         1698 :         table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
     265         1698 :                                                  scan->rs_parallelworkerdata,
     266         1698 :                                                  (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel,
     267              :                                                  scan->rs_startblock,
     268              :                                                  scan->rs_numblocks);
     269              : 
     270              :         /* may return InvalidBlockNumber if there are no more blocks */
     271         3396 :         scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
     272         1698 :                                                                     scan->rs_parallelworkerdata,
     273         1698 :                                                                     (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
     274         1698 :         scan->rs_inited = true;
     275              :     }
     276              :     else
     277              :     {
     278       100063 :         scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
     279       100063 :                                                                     scan->rs_parallelworkerdata, (ParallelBlockTableScanDesc)
     280       100063 :                                                                     scan->rs_base.rs_parallel);
     281              :     }
     282              : 
     283       101761 :     return scan->rs_prefetch_block;
     284              : }
     285              : 
     286              : /*
     287              :  * Streaming read API callback for serial sequential and TID range scans.
     288              :  * Returns the next block the caller wants from the read stream or
     289              :  * InvalidBlockNumber when done.
     290              :  */
     291              : static BlockNumber
     292      4088702 : heap_scan_stream_read_next_serial(ReadStream *stream,
     293              :                                   void *callback_private_data,
     294              :                                   void *per_buffer_data)
     295              : {
     296      4088702 :     HeapScanDesc scan = (HeapScanDesc) callback_private_data;
     297              : 
     298      4088702 :     if (unlikely(!scan->rs_inited))
     299              :     {
     300      1203516 :         scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
     301      1203516 :         scan->rs_inited = true;
     302              :     }
     303              :     else
     304      2885186 :         scan->rs_prefetch_block = heapgettup_advance_block(scan,
     305              :                                                            scan->rs_prefetch_block,
     306              :                                                            scan->rs_dir);
     307              : 
     308      4088702 :     return scan->rs_prefetch_block;
     309              : }
     310              : 
     311              : /*
     312              :  * Read stream API callback for bitmap heap scans.
     313              :  * Returns the next block the caller wants from the read stream or
     314              :  * InvalidBlockNumber when done.
     315              :  */
     316              : static BlockNumber
     317       218245 : bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data,
     318              :                             void *per_buffer_data)
     319              : {
     320       218245 :     TBMIterateResult *tbmres = per_buffer_data;
     321       218245 :     BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) private_data;
     322       218245 :     HeapScanDesc hscan = (HeapScanDesc) bscan;
     323       218245 :     TableScanDesc sscan = &hscan->rs_base;
     324              : 
     325              :     for (;;)
     326              :     {
     327       218245 :         CHECK_FOR_INTERRUPTS();
     328              : 
     329              :         /* no more entries in the bitmap */
     330       218245 :         if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
     331        13262 :             return InvalidBlockNumber;
     332              : 
     333              :         /*
     334              :          * Ignore any claimed entries past what we think is the end of the
     335              :          * relation. It may have been extended after the start of our scan (we
     336              :          * only hold an AccessShareLock, and it could be inserts from this
     337              :          * backend).  We don't take this optimization in SERIALIZABLE
     338              :          * isolation though, as we need to examine all invisible tuples
     339              :          * reachable by the index.
     340              :          */
     341       204983 :         if (!IsolationIsSerializable() &&
     342       204874 :             tbmres->blockno >= hscan->rs_nblocks)
     343            0 :             continue;
     344              : 
     345       204983 :         return tbmres->blockno;
     346              :     }
     347              : 
     348              :     /* not reachable */
     349              :     Assert(false);
     350              : }
     351              : 
     352              : /* ----------------
     353              :  *      initscan - scan code common to heap_beginscan and heap_rescan
     354              :  * ----------------
     355              :  */
     356              : static void
     357      1228580 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
     358              : {
     359      1228580 :     ParallelBlockTableScanDesc bpscan = NULL;
     360              :     bool        allow_strat;
     361              :     bool        allow_sync;
     362              : 
     363              :     /*
     364              :      * Determine the number of blocks we have to scan.
     365              :      *
     366              :      * It is sufficient to do this once at scan start, since any tuples added
     367              :      * while the scan is in progress will be invisible to my snapshot anyway.
     368              :      * (That is not true when using a non-MVCC snapshot.  However, we couldn't
     369              :      * guarantee to return tuples added after scan start anyway, since they
     370              :      * might go into pages we already scanned.  To guarantee consistent
     371              :      * results for a non-MVCC snapshot, the caller must hold some higher-level
     372              :      * lock that ensures the interesting tuple(s) won't change.)
     373              :      */
     374      1228580 :     if (scan->rs_base.rs_parallel != NULL)
     375              :     {
     376         2233 :         bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
     377         2233 :         scan->rs_nblocks = bpscan->phs_nblocks;
     378              :     }
     379              :     else
     380      1226347 :         scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_base.rs_rd);
     381              : 
     382              :     /*
     383              :      * If the table is large relative to NBuffers, use a bulk-read access
     384              :      * strategy and enable synchronized scanning (see syncscan.c).  Although
     385              :      * the thresholds for these features could be different, we make them the
     386              :      * same so that there are only two behaviors to tune rather than four.
     387              :      * (However, some callers need to be able to disable one or both of these
     388              :      * behaviors, independently of the size of the table; also there is a GUC
     389              :      * variable that can disable synchronized scanning.)
     390              :      *
     391              :      * Note that table_block_parallelscan_initialize has a very similar test;
     392              :      * if you change this, consider changing that one, too.
     393              :      */
     394      1228578 :     if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
     395      1221243 :         scan->rs_nblocks > NBuffers / 4)
     396              :     {
     397        13772 :         allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
     398        13772 :         allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
     399              :     }
     400              :     else
     401      1214806 :         allow_strat = allow_sync = false;
     402              : 
     403      1228578 :     if (allow_strat)
     404              :     {
     405              :         /* During a rescan, keep the previous strategy object. */
     406        12447 :         if (scan->rs_strategy == NULL)
     407        12264 :             scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
     408              :     }
     409              :     else
     410              :     {
     411      1216131 :         if (scan->rs_strategy != NULL)
     412            0 :             FreeAccessStrategy(scan->rs_strategy);
     413      1216131 :         scan->rs_strategy = NULL;
     414              :     }
     415              : 
     416      1228578 :     if (scan->rs_base.rs_parallel != NULL)
     417              :     {
     418              :         /* For parallel scan, believe whatever ParallelTableScanDesc says. */
     419         2233 :         if (scan->rs_base.rs_parallel->phs_syncscan)
     420            2 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
     421              :         else
     422         2231 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
     423              : 
     424              :         /*
     425              :          * If not rescanning, initialize the startblock.  Finding the actual
     426              :          * start location is done in table_block_parallelscan_startblock_init,
     427              :          * based on whether an alternative start location has been set with
     428              :          * heap_setscanlimits, or using the syncscan location, when syncscan
     429              :          * is enabled.
     430              :          */
     431         2233 :         if (!keep_startblock)
     432         2119 :             scan->rs_startblock = InvalidBlockNumber;
     433              :     }
     434              :     else
     435              :     {
     436      1226345 :         if (keep_startblock)
     437              :         {
     438              :             /*
     439              :              * When rescanning, we want to keep the previous startblock
     440              :              * setting, so that rewinding a cursor doesn't generate surprising
     441              :              * results.  Reset the active syncscan setting, though.
     442              :              */
     443       823303 :             if (allow_sync && synchronize_seqscans)
     444           50 :                 scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
     445              :             else
     446       823253 :                 scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
     447              :         }
     448       403042 :         else if (allow_sync && synchronize_seqscans)
     449              :         {
     450           69 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
     451           69 :             scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
     452              :         }
     453              :         else
     454              :         {
     455       402973 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
     456       402973 :             scan->rs_startblock = 0;
     457              :         }
     458              :     }
     459              : 
     460      1228578 :     scan->rs_numblocks = InvalidBlockNumber;
     461      1228578 :     scan->rs_inited = false;
     462      1228578 :     scan->rs_ctup.t_data = NULL;
     463      1228578 :     ItemPointerSetInvalid(&scan->rs_ctup.t_self);
     464      1228578 :     scan->rs_cbuf = InvalidBuffer;
     465      1228578 :     scan->rs_cblock = InvalidBlockNumber;
     466      1228578 :     scan->rs_ntuples = 0;
     467      1228578 :     scan->rs_cindex = 0;
     468              : 
     469              :     /*
     470              :      * Initialize to ForwardScanDirection because it is most common and
     471              :      * because heap scans go forward before going backward (e.g. CURSORs).
     472              :      */
     473      1228578 :     scan->rs_dir = ForwardScanDirection;
     474      1228578 :     scan->rs_prefetch_block = InvalidBlockNumber;
     475              : 
     476              :     /* page-at-a-time fields are always invalid when not rs_inited */
     477              : 
     478              :     /*
     479              :      * copy the scan key, if appropriate
     480              :      */
     481      1228578 :     if (key != NULL && scan->rs_base.rs_nkeys > 0)
     482       229536 :         memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
     483              : 
     484              :     /*
     485              :      * Currently, we only have a stats counter for sequential heap scans (but
     486              :      * e.g for bitmap scans the underlying bitmap index scans will be counted,
     487              :      * and for sample scans we update stats for tuple fetches).
     488              :      */
     489      1228578 :     if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
     490      1204777 :         pgstat_count_heap_scan(scan->rs_base.rs_rd);
     491      1228578 : }
     492              : 
     493              : /*
     494              :  * heap_setscanlimits - restrict range of a heapscan
     495              :  *
     496              :  * startBlk is the page to start at
     497              :  * numBlks is number of pages to scan (InvalidBlockNumber means "all")
     498              :  */
     499              : void
     500         2881 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
     501              : {
     502         2881 :     HeapScanDesc scan = (HeapScanDesc) sscan;
     503              : 
     504              :     Assert(!scan->rs_inited);    /* else too late to change */
     505              :     /* else rs_startblock is significant */
     506              :     Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
     507              : 
     508              :     /* Check startBlk is valid (but allow case of zero blocks...) */
     509              :     Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
     510              : 
     511         2881 :     scan->rs_startblock = startBlk;
     512         2881 :     scan->rs_numblocks = numBlks;
     513         2881 : }
     514              : 
     515              : /*
     516              :  * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
     517              :  * multiple times, with constant arguments for all_visible,
     518              :  * check_serializable.
     519              :  */
     520              : pg_attribute_always_inline
     521              : static int
     522      2874562 : page_collect_tuples(HeapScanDesc scan, Snapshot snapshot,
     523              :                     Page page, Buffer buffer,
     524              :                     BlockNumber block, int lines,
     525              :                     bool all_visible, bool check_serializable)
     526              : {
     527      2874562 :     Oid         relid = RelationGetRelid(scan->rs_base.rs_rd);
     528      2874562 :     int         ntup = 0;
     529      2874562 :     int         nvis = 0;
     530              :     BatchMVCCState batchmvcc;
     531              : 
     532              :     /* page at a time should have been disabled otherwise */
     533              :     Assert(IsMVCCSnapshot(snapshot));
     534              : 
     535              :     /* first find all tuples on the page */
     536    146553167 :     for (OffsetNumber lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
     537              :     {
     538    143678605 :         ItemId      lpp = PageGetItemId(page, lineoff);
     539              :         HeapTuple   tup;
     540              : 
     541    143678605 :         if (unlikely(!ItemIdIsNormal(lpp)))
     542     30394695 :             continue;
     543              : 
     544              :         /*
     545              :          * If the page is not all-visible or we need to check serializability,
     546              :          * maintain enough state to be able to refind the tuple efficiently,
     547              :          * without again first needing to fetch the item and then via that the
     548              :          * tuple.
     549              :          */
     550    113283910 :         if (!all_visible || check_serializable)
     551              :         {
     552     67077683 :             tup = &batchmvcc.tuples[ntup];
     553              : 
     554     67077683 :             tup->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
     555     67077683 :             tup->t_len = ItemIdGetLength(lpp);
     556     67077683 :             tup->t_tableOid = relid;
     557     67077683 :             ItemPointerSet(&(tup->t_self), block, lineoff);
     558              :         }
     559              : 
     560              :         /*
     561              :          * If the page is all visible, these fields otherwise won't be
     562              :          * populated in loop below.
     563              :          */
     564    113283910 :         if (all_visible)
     565              :         {
     566     46206227 :             if (check_serializable)
     567              :             {
     568            0 :                 batchmvcc.visible[ntup] = true;
     569              :             }
     570     46206227 :             scan->rs_vistuples[ntup] = lineoff;
     571              :         }
     572              : 
     573    113283910 :         ntup++;
     574              :     }
     575              : 
     576              :     Assert(ntup <= MaxHeapTuplesPerPage);
     577              : 
     578              :     /*
     579              :      * Unless the page is all visible, test visibility for all tuples one go.
     580              :      * That is considerably more efficient than calling
     581              :      * HeapTupleSatisfiesMVCC() one-by-one.
     582              :      */
     583      2874562 :     if (all_visible)
     584      1092183 :         nvis = ntup;
     585              :     else
     586      1782379 :         nvis = HeapTupleSatisfiesMVCCBatch(snapshot, buffer,
     587              :                                            ntup,
     588              :                                            &batchmvcc,
     589      1782379 :                                            scan->rs_vistuples);
     590              : 
     591              :     /*
     592              :      * So far we don't have batch API for testing serializabilty, so do so
     593              :      * one-by-one.
     594              :      */
     595      2874562 :     if (check_serializable)
     596              :     {
     597         2045 :         for (int i = 0; i < ntup; i++)
     598              :         {
     599         1421 :             HeapCheckForSerializableConflictOut(batchmvcc.visible[i],
     600              :                                                 scan->rs_base.rs_rd,
     601              :                                                 &batchmvcc.tuples[i],
     602              :                                                 buffer, snapshot);
     603              :         }
     604              :     }
     605              : 
     606      2874554 :     return nvis;
     607              : }
     608              : 
     609              : /*
     610              :  * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
     611              :  *
     612              :  * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
     613              :  * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
     614              :  */
     615              : void
     616      2874562 : heap_prepare_pagescan(TableScanDesc sscan)
     617              : {
     618      2874562 :     HeapScanDesc scan = (HeapScanDesc) sscan;
     619      2874562 :     Buffer      buffer = scan->rs_cbuf;
     620      2874562 :     BlockNumber block = scan->rs_cblock;
     621              :     Snapshot    snapshot;
     622              :     Page        page;
     623              :     int         lines;
     624              :     bool        all_visible;
     625              :     bool        check_serializable;
     626              : 
     627              :     Assert(BufferGetBlockNumber(buffer) == block);
     628              : 
     629              :     /* ensure we're not accidentally being used when not in pagemode */
     630              :     Assert(scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE);
     631      2874562 :     snapshot = scan->rs_base.rs_snapshot;
     632              : 
     633              :     /*
     634              :      * Prune and repair fragmentation for the whole page, if possible.
     635              :      */
     636      2874562 :     heap_page_prune_opt(scan->rs_base.rs_rd, buffer);
     637              : 
     638              :     /*
     639              :      * We must hold share lock on the buffer content while examining tuple
     640              :      * visibility.  Afterwards, however, the tuples we have found to be
     641              :      * visible are guaranteed good as long as we hold the buffer pin.
     642              :      */
     643      2874562 :     LockBuffer(buffer, BUFFER_LOCK_SHARE);
     644              : 
     645      2874562 :     page = BufferGetPage(buffer);
     646      2874562 :     lines = PageGetMaxOffsetNumber(page);
     647              : 
     648              :     /*
     649              :      * If the all-visible flag indicates that all tuples on the page are
     650              :      * visible to everyone, we can skip the per-tuple visibility tests.
     651              :      *
     652              :      * Note: In hot standby, a tuple that's already visible to all
     653              :      * transactions on the primary might still be invisible to a read-only
     654              :      * transaction in the standby. We partly handle this problem by tracking
     655              :      * the minimum xmin of visible tuples as the cut-off XID while marking a
     656              :      * page all-visible on the primary and WAL log that along with the
     657              :      * visibility map SET operation. In hot standby, we wait for (or abort)
     658              :      * all transactions that can potentially may not see one or more tuples on
     659              :      * the page. That's how index-only scans work fine in hot standby. A
     660              :      * crucial difference between index-only scans and heap scans is that the
     661              :      * index-only scan completely relies on the visibility map where as heap
     662              :      * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
     663              :      * the page-level flag can be trusted in the same way, because it might
     664              :      * get propagated somehow without being explicitly WAL-logged, e.g. via a
     665              :      * full page write. Until we can prove that beyond doubt, let's check each
     666              :      * tuple for visibility the hard way.
     667              :      */
     668      2874562 :     all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
     669              :     check_serializable =
     670      2874562 :         CheckForSerializableConflictOutNeeded(scan->rs_base.rs_rd, snapshot);
     671              : 
     672              :     /*
     673              :      * We call page_collect_tuples() with constant arguments, to get the
     674              :      * compiler to constant fold the constant arguments. Separate calls with
     675              :      * constant arguments, rather than variables, are needed on several
     676              :      * compilers to actually perform constant folding.
     677              :      */
     678      2874562 :     if (likely(all_visible))
     679              :     {
     680      1092183 :         if (likely(!check_serializable))
     681      1092183 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
     682              :                                                    block, lines, true, false);
     683              :         else
     684            0 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
     685              :                                                    block, lines, true, true);
     686              :     }
     687              :     else
     688              :     {
     689      1782379 :         if (likely(!check_serializable))
     690      1781747 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
     691              :                                                    block, lines, false, false);
     692              :         else
     693          632 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
     694              :                                                    block, lines, false, true);
     695              :     }
     696              : 
     697      2874554 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
     698      2874554 : }
     699              : 
     700              : /*
     701              :  * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
     702              :  *
     703              :  * Read the next block of the scan relation from the read stream and save it
     704              :  * in the scan descriptor.  It is already pinned.
     705              :  */
     706              : static inline void
     707      3998321 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
     708              : {
     709              :     Assert(scan->rs_read_stream);
     710              : 
     711              :     /* release previous scan buffer, if any */
     712      3998321 :     if (BufferIsValid(scan->rs_cbuf))
     713              :     {
     714      2793106 :         ReleaseBuffer(scan->rs_cbuf);
     715      2793106 :         scan->rs_cbuf = InvalidBuffer;
     716              :     }
     717              : 
     718              :     /*
     719              :      * Be sure to check for interrupts at least once per page.  Checks at
     720              :      * higher code levels won't be able to stop a seqscan that encounters many
     721              :      * pages' worth of consecutive dead tuples.
     722              :      */
     723      3998321 :     CHECK_FOR_INTERRUPTS();
     724              : 
     725              :     /*
     726              :      * If the scan direction is changing, reset the prefetch block to the
     727              :      * current block. Otherwise, we will incorrectly prefetch the blocks
     728              :      * between the prefetch block and the current block again before
     729              :      * prefetching blocks in the new, correct scan direction.
     730              :      */
     731      3998319 :     if (unlikely(scan->rs_dir != dir))
     732              :     {
     733           77 :         scan->rs_prefetch_block = scan->rs_cblock;
     734           77 :         read_stream_reset(scan->rs_read_stream);
     735              :     }
     736              : 
     737      3998319 :     scan->rs_dir = dir;
     738              : 
     739      3998319 :     scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
     740      3998293 :     if (BufferIsValid(scan->rs_cbuf))
     741      2962937 :         scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
     742      3998293 : }
     743              : 
     744              : /*
     745              :  * heapgettup_initial_block - return the first BlockNumber to scan
     746              :  *
     747              :  * Returns InvalidBlockNumber when there are no blocks to scan.  This can
     748              :  * occur with empty tables and in parallel scans when parallel workers get all
     749              :  * of the pages before we can get a chance to get our first page.
     750              :  */
     751              : static pg_noinline BlockNumber
     752      1203516 : heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
     753              : {
     754              :     Assert(!scan->rs_inited);
     755              :     Assert(scan->rs_base.rs_parallel == NULL);
     756              : 
     757              :     /* When there are no pages to scan, return InvalidBlockNumber */
     758      1203516 :     if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
     759       706894 :         return InvalidBlockNumber;
     760              : 
     761       496622 :     if (ScanDirectionIsForward(dir))
     762              :     {
     763       496590 :         return scan->rs_startblock;
     764              :     }
     765              :     else
     766              :     {
     767              :         /*
     768              :          * Disable reporting to syncscan logic in a backwards scan; it's not
     769              :          * very likely anyone else is doing the same thing at the same time,
     770              :          * and much more likely that we'll just bollix things for forward
     771              :          * scanners.
     772              :          */
     773           32 :         scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
     774              : 
     775              :         /*
     776              :          * Start from last page of the scan.  Ensure we take into account
     777              :          * rs_numblocks if it's been adjusted by heap_setscanlimits().
     778              :          */
     779           32 :         if (scan->rs_numblocks != InvalidBlockNumber)
     780            3 :             return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
     781              : 
     782           29 :         if (scan->rs_startblock > 0)
     783            0 :             return scan->rs_startblock - 1;
     784              : 
     785           29 :         return scan->rs_nblocks - 1;
     786              :     }
     787              : }
     788              : 
     789              : 
     790              : /*
     791              :  * heapgettup_start_page - helper function for heapgettup()
     792              :  *
     793              :  * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
     794              :  * to the number of tuples on this page.  Also set *lineoff to the first
     795              :  * offset to scan with forward scans getting the first offset and backward
     796              :  * getting the final offset on the page.
     797              :  */
     798              : static Page
     799        92650 : heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
     800              :                       OffsetNumber *lineoff)
     801              : {
     802              :     Page        page;
     803              : 
     804              :     Assert(scan->rs_inited);
     805              :     Assert(BufferIsValid(scan->rs_cbuf));
     806              : 
     807              :     /* Caller is responsible for ensuring buffer is locked if needed */
     808        92650 :     page = BufferGetPage(scan->rs_cbuf);
     809              : 
     810        92650 :     *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
     811              : 
     812        92650 :     if (ScanDirectionIsForward(dir))
     813        92650 :         *lineoff = FirstOffsetNumber;
     814              :     else
     815            0 :         *lineoff = (OffsetNumber) (*linesleft);
     816              : 
     817              :     /* lineoff now references the physically previous or next tid */
     818        92650 :     return page;
     819              : }
     820              : 
     821              : 
     822              : /*
     823              :  * heapgettup_continue_page - helper function for heapgettup()
     824              :  *
     825              :  * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
     826              :  * to the number of tuples left to scan on this page.  Also set *lineoff to
     827              :  * the next offset to scan according to the ScanDirection in 'dir'.
     828              :  */
     829              : static inline Page
     830      7486857 : heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
     831              :                          OffsetNumber *lineoff)
     832              : {
     833              :     Page        page;
     834              : 
     835              :     Assert(scan->rs_inited);
     836              :     Assert(BufferIsValid(scan->rs_cbuf));
     837              : 
     838              :     /* Caller is responsible for ensuring buffer is locked if needed */
     839      7486857 :     page = BufferGetPage(scan->rs_cbuf);
     840              : 
     841      7486857 :     if (ScanDirectionIsForward(dir))
     842              :     {
     843      7486857 :         *lineoff = OffsetNumberNext(scan->rs_coffset);
     844      7486857 :         *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
     845              :     }
     846              :     else
     847              :     {
     848              :         /*
     849              :          * The previous returned tuple may have been vacuumed since the
     850              :          * previous scan when we use a non-MVCC snapshot, so we must
     851              :          * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
     852              :          */
     853            0 :         *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
     854            0 :         *linesleft = *lineoff;
     855              :     }
     856              : 
     857              :     /* lineoff now references the physically previous or next tid */
     858      7486857 :     return page;
     859              : }
     860              : 
     861              : /*
     862              :  * heapgettup_advance_block - helper for heap_fetch_next_buffer()
     863              :  *
     864              :  * Given the current block number, the scan direction, and various information
     865              :  * contained in the scan descriptor, calculate the BlockNumber to scan next
     866              :  * and return it.  If there are no further blocks to scan, return
     867              :  * InvalidBlockNumber to indicate this fact to the caller.
     868              :  *
     869              :  * This should not be called to determine the initial block number -- only for
     870              :  * subsequent blocks.
     871              :  *
     872              :  * This also adjusts rs_numblocks when a limit has been imposed by
     873              :  * heap_setscanlimits().
     874              :  */
     875              : static inline BlockNumber
     876      2885186 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
     877              : {
     878              :     Assert(scan->rs_base.rs_parallel == NULL);
     879              : 
     880      2885186 :     if (likely(ScanDirectionIsForward(dir)))
     881              :     {
     882      2885127 :         block++;
     883              : 
     884              :         /* wrap back to the start of the heap */
     885      2885127 :         if (block >= scan->rs_nblocks)
     886       391453 :             block = 0;
     887              : 
     888              :         /*
     889              :          * Report our new scan position for synchronization purposes. We don't
     890              :          * do that when moving backwards, however. That would just mess up any
     891              :          * other forward-moving scanners.
     892              :          *
     893              :          * Note: we do this before checking for end of scan so that the final
     894              :          * state of the position hint is back at the start of the rel.  That's
     895              :          * not strictly necessary, but otherwise when you run the same query
     896              :          * multiple times the starting position would shift a little bit
     897              :          * backwards on every invocation, which is confusing. We don't
     898              :          * guarantee any specific ordering in general, though.
     899              :          */
     900      2885127 :         if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
     901        11015 :             ss_report_location(scan->rs_base.rs_rd, block);
     902              : 
     903              :         /* we're done if we're back at where we started */
     904      2885127 :         if (block == scan->rs_startblock)
     905       391412 :             return InvalidBlockNumber;
     906              : 
     907              :         /* check if the limit imposed by heap_setscanlimits() is met */
     908      2493715 :         if (scan->rs_numblocks != InvalidBlockNumber)
     909              :         {
     910         2486 :             if (--scan->rs_numblocks == 0)
     911         1548 :                 return InvalidBlockNumber;
     912              :         }
     913              : 
     914      2492167 :         return block;
     915              :     }
     916              :     else
     917              :     {
     918              :         /* we're done if the last block is the start position */
     919           59 :         if (block == scan->rs_startblock)
     920           59 :             return InvalidBlockNumber;
     921              : 
     922              :         /* check if the limit imposed by heap_setscanlimits() is met */
     923            0 :         if (scan->rs_numblocks != InvalidBlockNumber)
     924              :         {
     925            0 :             if (--scan->rs_numblocks == 0)
     926            0 :                 return InvalidBlockNumber;
     927              :         }
     928              : 
     929              :         /* wrap to the end of the heap when the last page was page 0 */
     930            0 :         if (block == 0)
     931            0 :             block = scan->rs_nblocks;
     932              : 
     933            0 :         block--;
     934              : 
     935            0 :         return block;
     936              :     }
     937              : }
     938              : 
     939              : /* ----------------
     940              :  *      heapgettup - fetch next heap tuple
     941              :  *
     942              :  *      Initialize the scan if not already done; then advance to the next
     943              :  *      tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
     944              :  *      or set scan->rs_ctup.t_data = NULL if no more tuples.
     945              :  *
     946              :  * Note: the reason nkeys/key are passed separately, even though they are
     947              :  * kept in the scan descriptor, is that the caller may not want us to check
     948              :  * the scankeys.
     949              :  *
     950              :  * Note: when we fall off the end of the scan in either direction, we
     951              :  * reset rs_inited.  This means that a further request with the same
     952              :  * scan direction will restart the scan, which is a bit odd, but a
     953              :  * request with the opposite scan direction will start a fresh scan
     954              :  * in the proper direction.  The latter is required behavior for cursors,
     955              :  * while the former case is generally undefined behavior in Postgres
     956              :  * so we don't care too much.
     957              :  * ----------------
     958              :  */
     959              : static void
     960      7507934 : heapgettup(HeapScanDesc scan,
     961              :            ScanDirection dir,
     962              :            int nkeys,
     963              :            ScanKey key)
     964              : {
     965      7507934 :     HeapTuple   tuple = &(scan->rs_ctup);
     966              :     Page        page;
     967              :     OffsetNumber lineoff;
     968              :     int         linesleft;
     969              : 
     970      7507934 :     if (likely(scan->rs_inited))
     971              :     {
     972              :         /* continue from previously returned page/tuple */
     973      7486857 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
     974      7486857 :         page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
     975      7486857 :         goto continue_page;
     976              :     }
     977              : 
     978              :     /*
     979              :      * advance the scan until we find a qualifying tuple or run out of stuff
     980              :      * to scan
     981              :      */
     982              :     while (true)
     983              :     {
     984       113579 :         heap_fetch_next_buffer(scan, dir);
     985              : 
     986              :         /* did we run out of blocks to scan? */
     987       113579 :         if (!BufferIsValid(scan->rs_cbuf))
     988        20929 :             break;
     989              : 
     990              :         Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
     991              : 
     992        92650 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
     993        92650 :         page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
     994      7579507 : continue_page:
     995              : 
     996              :         /*
     997              :          * Only continue scanning the page while we have lines left.
     998              :          *
     999              :          * Note that this protects us from accessing line pointers past
    1000              :          * PageGetMaxOffsetNumber(); both for forward scans when we resume the
    1001              :          * table scan, and for when we start scanning a new page.
    1002              :          */
    1003      7619646 :         for (; linesleft > 0; linesleft--, lineoff += dir)
    1004              :         {
    1005              :             bool        visible;
    1006      7527144 :             ItemId      lpp = PageGetItemId(page, lineoff);
    1007              : 
    1008      7527144 :             if (!ItemIdIsNormal(lpp))
    1009        34921 :                 continue;
    1010              : 
    1011      7492223 :             tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
    1012      7492223 :             tuple->t_len = ItemIdGetLength(lpp);
    1013      7492223 :             ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
    1014              : 
    1015      7492223 :             visible = HeapTupleSatisfiesVisibility(tuple,
    1016              :                                                    scan->rs_base.rs_snapshot,
    1017              :                                                    scan->rs_cbuf);
    1018              : 
    1019      7492223 :             HeapCheckForSerializableConflictOut(visible, scan->rs_base.rs_rd,
    1020              :                                                 tuple, scan->rs_cbuf,
    1021              :                                                 scan->rs_base.rs_snapshot);
    1022              : 
    1023              :             /* skip tuples not visible to this snapshot */
    1024      7492223 :             if (!visible)
    1025         5218 :                 continue;
    1026              : 
    1027              :             /* skip any tuples that don't match the scan key */
    1028      7487005 :             if (key != NULL &&
    1029            0 :                 !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
    1030              :                              nkeys, key))
    1031            0 :                 continue;
    1032              : 
    1033      7487005 :             LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
    1034      7487005 :             scan->rs_coffset = lineoff;
    1035      7487005 :             return;
    1036              :         }
    1037              : 
    1038              :         /*
    1039              :          * if we get here, it means we've exhausted the items on this page and
    1040              :          * it's time to move to the next.
    1041              :          */
    1042        92502 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
    1043              :     }
    1044              : 
    1045              :     /* end of scan */
    1046        20929 :     if (BufferIsValid(scan->rs_cbuf))
    1047            0 :         ReleaseBuffer(scan->rs_cbuf);
    1048              : 
    1049        20929 :     scan->rs_cbuf = InvalidBuffer;
    1050        20929 :     scan->rs_cblock = InvalidBlockNumber;
    1051        20929 :     scan->rs_prefetch_block = InvalidBlockNumber;
    1052        20929 :     tuple->t_data = NULL;
    1053        20929 :     scan->rs_inited = false;
    1054              : }
    1055              : 
    1056              : /* ----------------
    1057              :  *      heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
    1058              :  *
    1059              :  *      Same API as heapgettup, but used in page-at-a-time mode
    1060              :  *
    1061              :  * The internal logic is much the same as heapgettup's too, but there are some
    1062              :  * differences: we do not take the buffer content lock (that only needs to
    1063              :  * happen inside heap_prepare_pagescan), and we iterate through just the
    1064              :  * tuples listed in rs_vistuples[] rather than all tuples on the page.  Notice
    1065              :  * that lineindex is 0-based, where the corresponding loop variable lineoff in
    1066              :  * heapgettup is 1-based.
    1067              :  * ----------------
    1068              :  */
    1069              : static void
    1070     52262697 : heapgettup_pagemode(HeapScanDesc scan,
    1071              :                     ScanDirection dir,
    1072              :                     int nkeys,
    1073              :                     ScanKey key)
    1074              : {
    1075     52262697 :     HeapTuple   tuple = &(scan->rs_ctup);
    1076              :     Page        page;
    1077              :     uint32      lineindex;
    1078              :     uint32      linesleft;
    1079              : 
    1080     52262697 :     if (likely(scan->rs_inited))
    1081              :     {
    1082              :         /* continue from previously returned page/tuple */
    1083     51078559 :         page = BufferGetPage(scan->rs_cbuf);
    1084              : 
    1085     51078559 :         lineindex = scan->rs_cindex + dir;
    1086     51078559 :         if (ScanDirectionIsForward(dir))
    1087     51078230 :             linesleft = scan->rs_ntuples - lineindex;
    1088              :         else
    1089          329 :             linesleft = scan->rs_cindex;
    1090              :         /* lineindex now references the next or previous visible tid */
    1091              : 
    1092     51078559 :         goto continue_page;
    1093              :     }
    1094              : 
    1095              :     /*
    1096              :      * advance the scan until we find a qualifying tuple or run out of stuff
    1097              :      * to scan
    1098              :      */
    1099              :     while (true)
    1100              :     {
    1101      3884742 :         heap_fetch_next_buffer(scan, dir);
    1102              : 
    1103              :         /* did we run out of blocks to scan? */
    1104      3884714 :         if (!BufferIsValid(scan->rs_cbuf))
    1105      1014427 :             break;
    1106              : 
    1107              :         Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
    1108              : 
    1109              :         /* prune the page and determine visible tuple offsets */
    1110      2870287 :         heap_prepare_pagescan((TableScanDesc) scan);
    1111      2870279 :         page = BufferGetPage(scan->rs_cbuf);
    1112      2870279 :         linesleft = scan->rs_ntuples;
    1113      2870279 :         lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
    1114              : 
    1115              :         /* block is the same for all tuples, set it once outside the loop */
    1116      2870279 :         ItemPointerSetBlockNumber(&tuple->t_self, scan->rs_cblock);
    1117              : 
    1118              :         /* lineindex now references the next or previous visible tid */
    1119     53948838 : continue_page:
    1120              : 
    1121    104531195 :         for (; linesleft > 0; linesleft--, lineindex += dir)
    1122              :         {
    1123              :             ItemId      lpp;
    1124              :             OffsetNumber lineoff;
    1125              : 
    1126              :             Assert(lineindex < scan->rs_ntuples);
    1127    101830591 :             lineoff = scan->rs_vistuples[lineindex];
    1128    101830591 :             lpp = PageGetItemId(page, lineoff);
    1129              :             Assert(ItemIdIsNormal(lpp));
    1130              : 
    1131    101830591 :             tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
    1132    101830591 :             tuple->t_len = ItemIdGetLength(lpp);
    1133    101830591 :             ItemPointerSetOffsetNumber(&tuple->t_self, lineoff);
    1134              : 
    1135              :             /* skip any tuples that don't match the scan key */
    1136    101830591 :             if (key != NULL &&
    1137     50996971 :                 !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
    1138              :                              nkeys, key))
    1139     50582357 :                 continue;
    1140              : 
    1141     51248234 :             scan->rs_cindex = lineindex;
    1142     51248234 :             return;
    1143              :         }
    1144              :     }
    1145              : 
    1146              :     /* end of scan */
    1147      1014427 :     if (BufferIsValid(scan->rs_cbuf))
    1148            0 :         ReleaseBuffer(scan->rs_cbuf);
    1149      1014427 :     scan->rs_cbuf = InvalidBuffer;
    1150      1014427 :     scan->rs_cblock = InvalidBlockNumber;
    1151      1014427 :     scan->rs_prefetch_block = InvalidBlockNumber;
    1152      1014427 :     tuple->t_data = NULL;
    1153      1014427 :     scan->rs_inited = false;
    1154              : }
    1155              : 
    1156              : 
    1157              : /* ----------------------------------------------------------------
    1158              :  *                   heap access method interface
    1159              :  * ----------------------------------------------------------------
    1160              :  */
    1161              : 
    1162              : 
    1163              : TableScanDesc
    1164       405163 : heap_beginscan(Relation relation, Snapshot snapshot,
    1165              :                int nkeys, ScanKey key,
    1166              :                ParallelTableScanDesc parallel_scan,
    1167              :                uint32 flags)
    1168              : {
    1169              :     HeapScanDesc scan;
    1170              : 
    1171              :     /*
    1172              :      * increment relation ref count while scanning relation
    1173              :      *
    1174              :      * This is just to make really sure the relcache entry won't go away while
    1175              :      * the scan has a pointer to it.  Caller should be holding the rel open
    1176              :      * anyway, so this is redundant in all normal scenarios...
    1177              :      */
    1178       405163 :     RelationIncrementReferenceCount(relation);
    1179              : 
    1180              :     /*
    1181              :      * allocate and initialize scan descriptor
    1182              :      */
    1183       405163 :     if (flags & SO_TYPE_BITMAPSCAN)
    1184              :     {
    1185        11170 :         BitmapHeapScanDesc bscan = palloc_object(BitmapHeapScanDescData);
    1186              : 
    1187              :         /*
    1188              :          * Bitmap Heap scans do not have any fields that a normal Heap Scan
    1189              :          * does not have, so no special initializations required here.
    1190              :          */
    1191        11170 :         scan = (HeapScanDesc) bscan;
    1192              :     }
    1193              :     else
    1194       393993 :         scan = (HeapScanDesc) palloc_object(HeapScanDescData);
    1195              : 
    1196       405163 :     scan->rs_base.rs_rd = relation;
    1197       405163 :     scan->rs_base.rs_snapshot = snapshot;
    1198       405163 :     scan->rs_base.rs_nkeys = nkeys;
    1199       405163 :     scan->rs_base.rs_flags = flags;
    1200       405163 :     scan->rs_base.rs_parallel = parallel_scan;
    1201       405163 :     scan->rs_strategy = NULL;    /* set in initscan */
    1202       405163 :     scan->rs_cbuf = InvalidBuffer;
    1203              : 
    1204              :     /*
    1205              :      * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
    1206              :      */
    1207       405163 :     if (!(snapshot && IsMVCCSnapshot(snapshot)))
    1208        30017 :         scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
    1209              : 
    1210              :     /* Check that a historic snapshot is not used for non-catalog tables */
    1211       405163 :     if (snapshot &&
    1212       396223 :         IsHistoricMVCCSnapshot(snapshot) &&
    1213          669 :         !RelationIsAccessibleInLogicalDecoding(relation))
    1214              :     {
    1215            0 :         ereport(ERROR,
    1216              :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
    1217              :                  errmsg("cannot query non-catalog table \"%s\" during logical decoding",
    1218              :                         RelationGetRelationName(relation))));
    1219              :     }
    1220              : 
    1221              :     /*
    1222              :      * For seqscan and sample scans in a serializable transaction, acquire a
    1223              :      * predicate lock on the entire relation. This is required not only to
    1224              :      * lock all the matching tuples, but also to conflict with new insertions
    1225              :      * into the table. In an indexscan, we take page locks on the index pages
    1226              :      * covering the range specified in the scan qual, but in a heap scan there
    1227              :      * is nothing more fine-grained to lock. A bitmap scan is a different
    1228              :      * story, there we have already scanned the index and locked the index
    1229              :      * pages covering the predicate. But in that case we still have to lock
    1230              :      * any matching heap tuples. For sample scan we could optimize the locking
    1231              :      * to be at least page-level granularity, but we'd need to add per-tuple
    1232              :      * locking for that.
    1233              :      */
    1234       405163 :     if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN))
    1235              :     {
    1236              :         /*
    1237              :          * Ensure a missing snapshot is noticed reliably, even if the
    1238              :          * isolation mode means predicate locking isn't performed (and
    1239              :          * therefore the snapshot isn't used here).
    1240              :          */
    1241              :         Assert(snapshot);
    1242       383670 :         PredicateLockRelation(relation, snapshot);
    1243              :     }
    1244              : 
    1245              :     /* we only need to set this up once */
    1246       405163 :     scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
    1247              : 
    1248              :     /*
    1249              :      * Allocate memory to keep track of page allocation for parallel workers
    1250              :      * when doing a parallel scan.
    1251              :      */
    1252       405163 :     if (parallel_scan != NULL)
    1253         2119 :         scan->rs_parallelworkerdata = palloc_object(ParallelBlockTableScanWorkerData);
    1254              :     else
    1255       403044 :         scan->rs_parallelworkerdata = NULL;
    1256              : 
    1257              :     /*
    1258              :      * we do this here instead of in initscan() because heap_rescan also calls
    1259              :      * initscan() and we don't want to allocate memory again
    1260              :      */
    1261       405163 :     if (nkeys > 0)
    1262       229536 :         scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
    1263              :     else
    1264       175627 :         scan->rs_base.rs_key = NULL;
    1265              : 
    1266       405163 :     initscan(scan, key, false);
    1267              : 
    1268       405161 :     scan->rs_read_stream = NULL;
    1269              : 
    1270              :     /*
    1271              :      * Set up a read stream for sequential scans and TID range scans. This
    1272              :      * should be done after initscan() because initscan() allocates the
    1273              :      * BufferAccessStrategy object passed to the read stream API.
    1274              :      */
    1275       405161 :     if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
    1276        21566 :         scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
    1277       384585 :     {
    1278              :         ReadStreamBlockNumberCB cb;
    1279              : 
    1280       384585 :         if (scan->rs_base.rs_parallel)
    1281         2119 :             cb = heap_scan_stream_read_next_parallel;
    1282              :         else
    1283       382466 :             cb = heap_scan_stream_read_next_serial;
    1284              : 
    1285              :         /* ---
    1286              :          * It is safe to use batchmode as the only locks taken by `cb`
    1287              :          * are never taken while waiting for IO:
    1288              :          * - SyncScanLock is used in the non-parallel case
    1289              :          * - in the parallel case, only spinlocks and atomics are used
    1290              :          * ---
    1291              :          */
    1292       384585 :         scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_SEQUENTIAL |
    1293              :                                                           READ_STREAM_USE_BATCHING,
    1294              :                                                           scan->rs_strategy,
    1295              :                                                           scan->rs_base.rs_rd,
    1296              :                                                           MAIN_FORKNUM,
    1297              :                                                           cb,
    1298              :                                                           scan,
    1299              :                                                           0);
    1300              :     }
    1301        20576 :     else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
    1302              :     {
    1303        11170 :         scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_DEFAULT |
    1304              :                                                           READ_STREAM_USE_BATCHING,
    1305              :                                                           scan->rs_strategy,
    1306              :                                                           scan->rs_base.rs_rd,
    1307              :                                                           MAIN_FORKNUM,
    1308              :                                                           bitmapheap_stream_read_next,
    1309              :                                                           scan,
    1310              :                                                           sizeof(TBMIterateResult));
    1311              :     }
    1312              : 
    1313              : 
    1314       405161 :     return (TableScanDesc) scan;
    1315              : }
    1316              : 
    1317              : void
    1318       823417 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
    1319              :             bool allow_strat, bool allow_sync, bool allow_pagemode)
    1320              : {
    1321       823417 :     HeapScanDesc scan = (HeapScanDesc) sscan;
    1322              : 
    1323       823417 :     if (set_params)
    1324              :     {
    1325           15 :         if (allow_strat)
    1326           15 :             scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
    1327              :         else
    1328            0 :             scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
    1329              : 
    1330           15 :         if (allow_sync)
    1331            6 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
    1332              :         else
    1333            9 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
    1334              : 
    1335           15 :         if (allow_pagemode && scan->rs_base.rs_snapshot &&
    1336           15 :             IsMVCCSnapshot(scan->rs_base.rs_snapshot))
    1337           15 :             scan->rs_base.rs_flags |= SO_ALLOW_PAGEMODE;
    1338              :         else
    1339            0 :             scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
    1340              :     }
    1341              : 
    1342              :     /*
    1343              :      * unpin scan buffers
    1344              :      */
    1345       823417 :     if (BufferIsValid(scan->rs_cbuf))
    1346              :     {
    1347         1732 :         ReleaseBuffer(scan->rs_cbuf);
    1348         1732 :         scan->rs_cbuf = InvalidBuffer;
    1349              :     }
    1350              : 
    1351              :     /*
    1352              :      * SO_TYPE_BITMAPSCAN would be cleaned up here, but it does not hold any
    1353              :      * additional data vs a normal HeapScan
    1354              :      */
    1355              : 
    1356              :     /*
    1357              :      * The read stream is reset on rescan. This must be done before
    1358              :      * initscan(), as some state referred to by read_stream_reset() is reset
    1359              :      * in initscan().
    1360              :      */
    1361       823417 :     if (scan->rs_read_stream)
    1362       823399 :         read_stream_reset(scan->rs_read_stream);
    1363              : 
    1364              :     /*
    1365              :      * reinitialize scan descriptor
    1366              :      */
    1367       823417 :     initscan(scan, key, true);
    1368       823417 : }
    1369              : 
    1370              : void
    1371       402741 : heap_endscan(TableScanDesc sscan)
    1372              : {
    1373       402741 :     HeapScanDesc scan = (HeapScanDesc) sscan;
    1374              : 
    1375              :     /* Note: no locking manipulations needed */
    1376              : 
    1377              :     /*
    1378              :      * unpin scan buffers
    1379              :      */
    1380       402741 :     if (BufferIsValid(scan->rs_cbuf))
    1381       166433 :         ReleaseBuffer(scan->rs_cbuf);
    1382              : 
    1383              :     /*
    1384              :      * Must free the read stream before freeing the BufferAccessStrategy.
    1385              :      */
    1386       402741 :     if (scan->rs_read_stream)
    1387       393388 :         read_stream_end(scan->rs_read_stream);
    1388              : 
    1389              :     /*
    1390              :      * decrement relation reference count and free scan descriptor storage
    1391              :      */
    1392       402741 :     RelationDecrementReferenceCount(scan->rs_base.rs_rd);
    1393              : 
    1394       402741 :     if (scan->rs_base.rs_key)
    1395       229506 :         pfree(scan->rs_base.rs_key);
    1396              : 
    1397       402741 :     if (scan->rs_strategy != NULL)
    1398        12256 :         FreeAccessStrategy(scan->rs_strategy);
    1399              : 
    1400       402741 :     if (scan->rs_parallelworkerdata != NULL)
    1401         2119 :         pfree(scan->rs_parallelworkerdata);
    1402              : 
    1403       402741 :     if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
    1404        41194 :         UnregisterSnapshot(scan->rs_base.rs_snapshot);
    1405              : 
    1406       402741 :     pfree(scan);
    1407       402741 : }
    1408              : 
    1409              : HeapTuple
    1410     10001168 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
    1411              : {
    1412     10001168 :     HeapScanDesc scan = (HeapScanDesc) sscan;
    1413              : 
    1414              :     /*
    1415              :      * This is still widely used directly, without going through table AM, so
    1416              :      * add a safety check.  It's possible we should, at a later point,
    1417              :      * downgrade this to an assert. The reason for checking the AM routine,
    1418              :      * rather than the AM oid, is that this allows to write regression tests
    1419              :      * that create another AM reusing the heap handler.
    1420              :      */
    1421     10001168 :     if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
    1422            0 :         ereport(ERROR,
    1423              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1424              :                  errmsg_internal("only heap AM is supported")));
    1425              : 
    1426              :     /* Note: no locking manipulations needed */
    1427              : 
    1428     10001168 :     if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
    1429      2977942 :         heapgettup_pagemode(scan, direction,
    1430      2977942 :                             scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
    1431              :     else
    1432      7023226 :         heapgettup(scan, direction,
    1433      7023226 :                    scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
    1434              : 
    1435     10001168 :     if (scan->rs_ctup.t_data == NULL)
    1436        68155 :         return NULL;
    1437              : 
    1438              :     /*
    1439              :      * if we get here it means we have a new current scan tuple, so point to
    1440              :      * the proper return buffer and return the tuple.
    1441              :      */
    1442              : 
    1443      9933013 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
    1444              : 
    1445      9933013 :     return &scan->rs_ctup;
    1446              : }
    1447              : 
    1448              : bool
    1449     49763734 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
    1450              : {
    1451     49763734 :     HeapScanDesc scan = (HeapScanDesc) sscan;
    1452              : 
    1453              :     /* Note: no locking manipulations needed */
    1454              : 
    1455     49763734 :     if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
    1456     49279026 :         heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
    1457              :     else
    1458       484708 :         heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
    1459              : 
    1460     49763706 :     if (scan->rs_ctup.t_data == NULL)
    1461              :     {
    1462       967097 :         ExecClearTuple(slot);
    1463       967097 :         return false;
    1464              :     }
    1465              : 
    1466              :     /*
    1467              :      * if we get here it means we have a new current scan tuple, so point to
    1468              :      * the proper return buffer and return the tuple.
    1469              :      */
    1470              : 
    1471     48796609 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
    1472              : 
    1473     48796609 :     ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
    1474              :                              scan->rs_cbuf);
    1475     48796609 :     return true;
    1476              : }
    1477              : 
    1478              : void
    1479         1035 : heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
    1480              :                   ItemPointer maxtid)
    1481              : {
    1482         1035 :     HeapScanDesc scan = (HeapScanDesc) sscan;
    1483              :     BlockNumber startBlk;
    1484              :     BlockNumber numBlks;
    1485              :     ItemPointerData highestItem;
    1486              :     ItemPointerData lowestItem;
    1487              : 
    1488              :     /*
    1489              :      * For relations without any pages, we can simply leave the TID range
    1490              :      * unset.  There will be no tuples to scan, therefore no tuples outside
    1491              :      * the given TID range.
    1492              :      */
    1493         1035 :     if (scan->rs_nblocks == 0)
    1494           24 :         return;
    1495              : 
    1496              :     /*
    1497              :      * Set up some ItemPointers which point to the first and last possible
    1498              :      * tuples in the heap.
    1499              :      */
    1500         1029 :     ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
    1501         1029 :     ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
    1502              : 
    1503              :     /*
    1504              :      * If the given maximum TID is below the highest possible TID in the
    1505              :      * relation, then restrict the range to that, otherwise we scan to the end
    1506              :      * of the relation.
    1507              :      */
    1508         1029 :     if (ItemPointerCompare(maxtid, &highestItem) < 0)
    1509          130 :         ItemPointerCopy(maxtid, &highestItem);
    1510              : 
    1511              :     /*
    1512              :      * If the given minimum TID is above the lowest possible TID in the
    1513              :      * relation, then restrict the range to only scan for TIDs above that.
    1514              :      */
    1515         1029 :     if (ItemPointerCompare(mintid, &lowestItem) > 0)
    1516          911 :         ItemPointerCopy(mintid, &lowestItem);
    1517              : 
    1518              :     /*
    1519              :      * Check for an empty range and protect from would be negative results
    1520              :      * from the numBlks calculation below.
    1521              :      */
    1522         1029 :     if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
    1523              :     {
    1524              :         /* Set an empty range of blocks to scan */
    1525           18 :         heap_setscanlimits(sscan, 0, 0);
    1526           18 :         return;
    1527              :     }
    1528              : 
    1529              :     /*
    1530              :      * Calculate the first block and the number of blocks we must scan. We
    1531              :      * could be more aggressive here and perform some more validation to try
    1532              :      * and further narrow the scope of blocks to scan by checking if the
    1533              :      * lowestItem has an offset above MaxOffsetNumber.  In this case, we could
    1534              :      * advance startBlk by one.  Likewise, if highestItem has an offset of 0
    1535              :      * we could scan one fewer blocks.  However, such an optimization does not
    1536              :      * seem worth troubling over, currently.
    1537              :      */
    1538         1011 :     startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
    1539              : 
    1540         1011 :     numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
    1541         1011 :         ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
    1542              : 
    1543              :     /* Set the start block and number of blocks to scan */
    1544         1011 :     heap_setscanlimits(sscan, startBlk, numBlks);
    1545              : 
    1546              :     /* Finally, set the TID range in sscan */
    1547         1011 :     ItemPointerCopy(&lowestItem, &sscan->st.tidrange.rs_mintid);
    1548         1011 :     ItemPointerCopy(&highestItem, &sscan->st.tidrange.rs_maxtid);
    1549              : }
    1550              : 
    1551              : bool
    1552         5636 : heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
    1553              :                           TupleTableSlot *slot)
    1554              : {
    1555         5636 :     HeapScanDesc scan = (HeapScanDesc) sscan;
    1556         5636 :     ItemPointer mintid = &sscan->st.tidrange.rs_mintid;
    1557         5636 :     ItemPointer maxtid = &sscan->st.tidrange.rs_maxtid;
    1558              : 
    1559              :     /* Note: no locking manipulations needed */
    1560              :     for (;;)
    1561              :     {
    1562         5729 :         if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
    1563         5729 :             heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
    1564              :         else
    1565            0 :             heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
    1566              : 
    1567         5721 :         if (scan->rs_ctup.t_data == NULL)
    1568              :         {
    1569          104 :             ExecClearTuple(slot);
    1570          104 :             return false;
    1571              :         }
    1572              : 
    1573              :         /*
    1574              :          * heap_set_tidrange will have used heap_setscanlimits to limit the
    1575              :          * range of pages we scan to only ones that can contain the TID range
    1576              :          * we're scanning for.  Here we must filter out any tuples from these
    1577              :          * pages that are outside of that range.
    1578              :          */
    1579         5617 :         if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
    1580              :         {
    1581           93 :             ExecClearTuple(slot);
    1582              : 
    1583              :             /*
    1584              :              * When scanning backwards, the TIDs will be in descending order.
    1585              :              * Future tuples in this direction will be lower still, so we can
    1586              :              * just return false to indicate there will be no more tuples.
    1587              :              */
    1588           93 :             if (ScanDirectionIsBackward(direction))
    1589            0 :                 return false;
    1590              : 
    1591           93 :             continue;
    1592              :         }
    1593              : 
    1594              :         /*
    1595              :          * Likewise for the final page, we must filter out TIDs greater than
    1596              :          * maxtid.
    1597              :          */
    1598         5524 :         if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
    1599              :         {
    1600           56 :             ExecClearTuple(slot);
    1601              : 
    1602              :             /*
    1603              :              * When scanning forward, the TIDs will be in ascending order.
    1604              :              * Future tuples in this direction will be higher still, so we can
    1605              :              * just return false to indicate there will be no more tuples.
    1606              :              */
    1607           56 :             if (ScanDirectionIsForward(direction))
    1608           56 :                 return false;
    1609            0 :             continue;
    1610              :         }
    1611              : 
    1612         5468 :         break;
    1613              :     }
    1614              : 
    1615              :     /*
    1616              :      * if we get here it means we have a new current scan tuple, so point to
    1617              :      * the proper return buffer and return the tuple.
    1618              :      */
    1619         5468 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
    1620              : 
    1621         5468 :     ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
    1622         5468 :     return true;
    1623              : }
    1624              : 
    1625              : /*
    1626              :  *  heap_fetch      - retrieve tuple with given tid
    1627              :  *
    1628              :  * On entry, tuple->t_self is the TID to fetch.  We pin the buffer holding
    1629              :  * the tuple, fill in the remaining fields of *tuple, and check the tuple
    1630              :  * against the specified snapshot.
    1631              :  *
    1632              :  * If successful (tuple found and passes snapshot time qual), then *userbuf
    1633              :  * is set to the buffer holding the tuple and true is returned.  The caller
    1634              :  * must unpin the buffer when done with the tuple.
    1635              :  *
    1636              :  * If the tuple is not found (ie, item number references a deleted slot),
    1637              :  * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
    1638              :  * and false is returned.
    1639              :  *
    1640              :  * If the tuple is found but fails the time qual check, then the behavior
    1641              :  * depends on the keep_buf parameter.  If keep_buf is false, the results
    1642              :  * are the same as for the tuple-not-found case.  If keep_buf is true,
    1643              :  * then tuple->t_data and *userbuf are returned as for the success case,
    1644              :  * and again the caller must unpin the buffer; but false is returned.
    1645              :  *
    1646              :  * heap_fetch does not follow HOT chains: only the exact TID requested will
    1647              :  * be fetched.
    1648              :  *
    1649              :  * It is somewhat inconsistent that we ereport() on invalid block number but
    1650              :  * return false on invalid item number.  There are a couple of reasons though.
    1651              :  * One is that the caller can relatively easily check the block number for
    1652              :  * validity, but cannot check the item number without reading the page
    1653              :  * himself.  Another is that when we are following a t_ctid link, we can be
    1654              :  * reasonably confident that the page number is valid (since VACUUM shouldn't
    1655              :  * truncate off the destination page without having killed the referencing
    1656              :  * tuple first), but the item number might well not be good.
    1657              :  */
    1658              : bool
    1659       181413 : heap_fetch(Relation relation,
    1660              :            Snapshot snapshot,
    1661              :            HeapTuple tuple,
    1662              :            Buffer *userbuf,
    1663              :            bool keep_buf)
    1664              : {
    1665       181413 :     ItemPointer tid = &(tuple->t_self);
    1666              :     ItemId      lp;
    1667              :     Buffer      buffer;
    1668              :     Page        page;
    1669              :     OffsetNumber offnum;
    1670              :     bool        valid;
    1671              : 
    1672              :     /*
    1673              :      * Fetch and pin the appropriate page of the relation.
    1674              :      */
    1675       181413 :     buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
    1676              : 
    1677              :     /*
    1678              :      * Need share lock on buffer to examine tuple commit status.
    1679              :      */
    1680       181405 :     LockBuffer(buffer, BUFFER_LOCK_SHARE);
    1681       181405 :     page = BufferGetPage(buffer);
    1682              : 
    1683              :     /*
    1684              :      * We'd better check for out-of-range offnum in case of VACUUM since the
    1685              :      * TID was obtained.
    1686              :      */
    1687       181405 :     offnum = ItemPointerGetOffsetNumber(tid);
    1688       181405 :     if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
    1689              :     {
    1690            3 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    1691            3 :         ReleaseBuffer(buffer);
    1692            3 :         *userbuf = InvalidBuffer;
    1693            3 :         tuple->t_data = NULL;
    1694            3 :         return false;
    1695              :     }
    1696              : 
    1697              :     /*
    1698              :      * get the item line pointer corresponding to the requested tid
    1699              :      */
    1700       181402 :     lp = PageGetItemId(page, offnum);
    1701              : 
    1702              :     /*
    1703              :      * Must check for deleted tuple.
    1704              :      */
    1705       181402 :     if (!ItemIdIsNormal(lp))
    1706              :     {
    1707          331 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    1708          331 :         ReleaseBuffer(buffer);
    1709          331 :         *userbuf = InvalidBuffer;
    1710          331 :         tuple->t_data = NULL;
    1711          331 :         return false;
    1712              :     }
    1713              : 
    1714              :     /*
    1715              :      * fill in *tuple fields
    1716              :      */
    1717       181071 :     tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
    1718       181071 :     tuple->t_len = ItemIdGetLength(lp);
    1719       181071 :     tuple->t_tableOid = RelationGetRelid(relation);
    1720              : 
    1721              :     /*
    1722              :      * check tuple visibility, then release lock
    1723              :      */
    1724       181071 :     valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
    1725              : 
    1726       181071 :     if (valid)
    1727       181018 :         PredicateLockTID(relation, &(tuple->t_self), snapshot,
    1728       181018 :                          HeapTupleHeaderGetXmin(tuple->t_data));
    1729              : 
    1730       181071 :     HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
    1731              : 
    1732       181071 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    1733              : 
    1734       181071 :     if (valid)
    1735              :     {
    1736              :         /*
    1737              :          * All checks passed, so return the tuple as valid. Caller is now
    1738              :          * responsible for releasing the buffer.
    1739              :          */
    1740       181018 :         *userbuf = buffer;
    1741              : 
    1742       181018 :         return true;
    1743              :     }
    1744              : 
    1745              :     /* Tuple failed time qual, but maybe caller wants to see it anyway. */
    1746           53 :     if (keep_buf)
    1747           34 :         *userbuf = buffer;
    1748              :     else
    1749              :     {
    1750           19 :         ReleaseBuffer(buffer);
    1751           19 :         *userbuf = InvalidBuffer;
    1752           19 :         tuple->t_data = NULL;
    1753              :     }
    1754              : 
    1755           53 :     return false;
    1756              : }
    1757              : 
    1758              : /*
    1759              :  *  heap_hot_search_buffer  - search HOT chain for tuple satisfying snapshot
    1760              :  *
    1761              :  * On entry, *tid is the TID of a tuple (either a simple tuple, or the root
    1762              :  * of a HOT chain), and buffer is the buffer holding this tuple.  We search
    1763              :  * for the first chain member satisfying the given snapshot.  If one is
    1764              :  * found, we update *tid to reference that tuple's offset number, and
    1765              :  * return true.  If no match, return false without modifying *tid.
    1766              :  *
    1767              :  * heapTuple is a caller-supplied buffer.  When a match is found, we return
    1768              :  * the tuple here, in addition to updating *tid.  If no match is found, the
    1769              :  * contents of this buffer on return are undefined.
    1770              :  *
    1771              :  * If all_dead is not NULL, we check non-visible tuples to see if they are
    1772              :  * globally dead; *all_dead is set true if all members of the HOT chain
    1773              :  * are vacuumable, false if not.
    1774              :  *
    1775              :  * Unlike heap_fetch, the caller must already have pin and (at least) share
    1776              :  * lock on the buffer; it is still pinned/locked at exit.
    1777              :  */
    1778              : bool
    1779     23415186 : heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer,
    1780              :                        Snapshot snapshot, HeapTuple heapTuple,
    1781              :                        bool *all_dead, bool first_call)
    1782              : {
    1783     23415186 :     Page        page = BufferGetPage(buffer);
    1784     23415186 :     TransactionId prev_xmax = InvalidTransactionId;
    1785              :     BlockNumber blkno;
    1786              :     OffsetNumber offnum;
    1787              :     bool        at_chain_start;
    1788              :     bool        valid;
    1789              :     bool        skip;
    1790     23415186 :     GlobalVisState *vistest = NULL;
    1791              : 
    1792              :     /* If this is not the first call, previous call returned a (live!) tuple */
    1793     23415186 :     if (all_dead)
    1794     20039019 :         *all_dead = first_call;
    1795              : 
    1796     23415186 :     blkno = ItemPointerGetBlockNumber(tid);
    1797     23415186 :     offnum = ItemPointerGetOffsetNumber(tid);
    1798     23415186 :     at_chain_start = first_call;
    1799     23415186 :     skip = !first_call;
    1800              : 
    1801              :     /* XXX: we should assert that a snapshot is pushed or registered */
    1802              :     Assert(TransactionIdIsValid(RecentXmin));
    1803              :     Assert(BufferGetBlockNumber(buffer) == blkno);
    1804              : 
    1805              :     /* Scan through possible multiple members of HOT-chain */
    1806              :     for (;;)
    1807      1744249 :     {
    1808              :         ItemId      lp;
    1809              : 
    1810              :         /* check for bogus TID */
    1811     25159435 :         if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
    1812              :             break;
    1813              : 
    1814     25159435 :         lp = PageGetItemId(page, offnum);
    1815              : 
    1816              :         /* check for unused, dead, or redirected items */
    1817     25159435 :         if (!ItemIdIsNormal(lp))
    1818              :         {
    1819              :             /* We should only see a redirect at start of chain */
    1820       907402 :             if (ItemIdIsRedirected(lp) && at_chain_start)
    1821              :             {
    1822              :                 /* Follow the redirect */
    1823       537281 :                 offnum = ItemIdGetRedirect(lp);
    1824       537281 :                 at_chain_start = false;
    1825       537281 :                 continue;
    1826              :             }
    1827              :             /* else must be end of chain */
    1828       370121 :             break;
    1829              :         }
    1830              : 
    1831              :         /*
    1832              :          * Update heapTuple to point to the element of the HOT chain we're
    1833              :          * currently investigating. Having t_self set correctly is important
    1834              :          * because the SSI checks and the *Satisfies routine for historical
    1835              :          * MVCC snapshots need the correct tid to decide about the visibility.
    1836              :          */
    1837     24252033 :         heapTuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
    1838     24252033 :         heapTuple->t_len = ItemIdGetLength(lp);
    1839     24252033 :         heapTuple->t_tableOid = RelationGetRelid(relation);
    1840     24252033 :         ItemPointerSet(&heapTuple->t_self, blkno, offnum);
    1841              : 
    1842              :         /*
    1843              :          * Shouldn't see a HEAP_ONLY tuple at chain start.
    1844              :          */
    1845     24252033 :         if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
    1846            0 :             break;
    1847              : 
    1848              :         /*
    1849              :          * The xmin should match the previous xmax value, else chain is
    1850              :          * broken.
    1851              :          */
    1852     25459001 :         if (TransactionIdIsValid(prev_xmax) &&
    1853      1206968 :             !TransactionIdEquals(prev_xmax,
    1854              :                                  HeapTupleHeaderGetXmin(heapTuple->t_data)))
    1855            0 :             break;
    1856              : 
    1857              :         /*
    1858              :          * When first_call is true (and thus, skip is initially false) we'll
    1859              :          * return the first tuple we find.  But on later passes, heapTuple
    1860              :          * will initially be pointing to the tuple we returned last time.
    1861              :          * Returning it again would be incorrect (and would loop forever), so
    1862              :          * we skip it and return the next match we find.
    1863              :          */
    1864     24252033 :         if (!skip)
    1865              :         {
    1866              :             /* If it's visible per the snapshot, we must return it */
    1867     24163051 :             valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
    1868     24163051 :             HeapCheckForSerializableConflictOut(valid, relation, heapTuple,
    1869              :                                                 buffer, snapshot);
    1870              : 
    1871     24163046 :             if (valid)
    1872              :             {
    1873     16803032 :                 ItemPointerSetOffsetNumber(tid, offnum);
    1874     16803032 :                 PredicateLockTID(relation, &heapTuple->t_self, snapshot,
    1875     16803032 :                                  HeapTupleHeaderGetXmin(heapTuple->t_data));
    1876     16803032 :                 if (all_dead)
    1877     13720895 :                     *all_dead = false;
    1878     16803032 :                 return true;
    1879              :             }
    1880              :         }
    1881      7448996 :         skip = false;
    1882              : 
    1883              :         /*
    1884              :          * If we can't see it, maybe no one else can either.  At caller
    1885              :          * request, check whether all chain members are dead to all
    1886              :          * transactions.
    1887              :          *
    1888              :          * Note: if you change the criterion here for what is "dead", fix the
    1889              :          * planner's get_actual_variable_range() function to match.
    1890              :          */
    1891      7448996 :         if (all_dead && *all_dead)
    1892              :         {
    1893      6484094 :             if (!vistest)
    1894      6362362 :                 vistest = GlobalVisTestFor(relation);
    1895              : 
    1896      6484094 :             if (!HeapTupleIsSurelyDead(heapTuple, vistest))
    1897      6125168 :                 *all_dead = false;
    1898              :         }
    1899              : 
    1900              :         /*
    1901              :          * Check to see if HOT chain continues past this tuple; if so fetch
    1902              :          * the next offnum and loop around.
    1903              :          */
    1904      7448996 :         if (HeapTupleIsHotUpdated(heapTuple))
    1905              :         {
    1906              :             Assert(ItemPointerGetBlockNumber(&heapTuple->t_data->t_ctid) ==
    1907              :                    blkno);
    1908      1206968 :             offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
    1909      1206968 :             at_chain_start = false;
    1910      1206968 :             prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
    1911              :         }
    1912              :         else
    1913      6242028 :             break;              /* end of chain */
    1914              :     }
    1915              : 
    1916      6612149 :     return false;
    1917              : }
    1918              : 
    1919              : /*
    1920              :  *  heap_get_latest_tid -  get the latest tid of a specified tuple
    1921              :  *
    1922              :  * Actually, this gets the latest version that is visible according to the
    1923              :  * scan's snapshot.  Create a scan using SnapshotDirty to get the very latest,
    1924              :  * possibly uncommitted version.
    1925              :  *
    1926              :  * *tid is both an input and an output parameter: it is updated to
    1927              :  * show the latest version of the row.  Note that it will not be changed
    1928              :  * if no version of the row passes the snapshot test.
    1929              :  */
    1930              : void
    1931          150 : heap_get_latest_tid(TableScanDesc sscan,
    1932              :                     ItemPointer tid)
    1933              : {
    1934          150 :     Relation    relation = sscan->rs_rd;
    1935          150 :     Snapshot    snapshot = sscan->rs_snapshot;
    1936              :     ItemPointerData ctid;
    1937              :     TransactionId priorXmax;
    1938              : 
    1939              :     /*
    1940              :      * table_tuple_get_latest_tid() verified that the passed in tid is valid.
    1941              :      * Assume that t_ctid links are valid however - there shouldn't be invalid
    1942              :      * ones in the table.
    1943              :      */
    1944              :     Assert(ItemPointerIsValid(tid));
    1945              : 
    1946              :     /*
    1947              :      * Loop to chase down t_ctid links.  At top of loop, ctid is the tuple we
    1948              :      * need to examine, and *tid is the TID we will return if ctid turns out
    1949              :      * to be bogus.
    1950              :      *
    1951              :      * Note that we will loop until we reach the end of the t_ctid chain.
    1952              :      * Depending on the snapshot passed, there might be at most one visible
    1953              :      * version of the row, but we don't try to optimize for that.
    1954              :      */
    1955          150 :     ctid = *tid;
    1956          150 :     priorXmax = InvalidTransactionId;   /* cannot check first XMIN */
    1957              :     for (;;)
    1958           45 :     {
    1959              :         Buffer      buffer;
    1960              :         Page        page;
    1961              :         OffsetNumber offnum;
    1962              :         ItemId      lp;
    1963              :         HeapTupleData tp;
    1964              :         bool        valid;
    1965              : 
    1966              :         /*
    1967              :          * Read, pin, and lock the page.
    1968              :          */
    1969          195 :         buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
    1970          195 :         LockBuffer(buffer, BUFFER_LOCK_SHARE);
    1971          195 :         page = BufferGetPage(buffer);
    1972              : 
    1973              :         /*
    1974              :          * Check for bogus item number.  This is not treated as an error
    1975              :          * condition because it can happen while following a t_ctid link. We
    1976              :          * just assume that the prior tid is OK and return it unchanged.
    1977              :          */
    1978          195 :         offnum = ItemPointerGetOffsetNumber(&ctid);
    1979          195 :         if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
    1980              :         {
    1981            0 :             UnlockReleaseBuffer(buffer);
    1982            0 :             break;
    1983              :         }
    1984          195 :         lp = PageGetItemId(page, offnum);
    1985          195 :         if (!ItemIdIsNormal(lp))
    1986              :         {
    1987            0 :             UnlockReleaseBuffer(buffer);
    1988            0 :             break;
    1989              :         }
    1990              : 
    1991              :         /* OK to access the tuple */
    1992          195 :         tp.t_self = ctid;
    1993          195 :         tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
    1994          195 :         tp.t_len = ItemIdGetLength(lp);
    1995          195 :         tp.t_tableOid = RelationGetRelid(relation);
    1996              : 
    1997              :         /*
    1998              :          * After following a t_ctid link, we might arrive at an unrelated
    1999              :          * tuple.  Check for XMIN match.
    2000              :          */
    2001          240 :         if (TransactionIdIsValid(priorXmax) &&
    2002           45 :             !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
    2003              :         {
    2004            0 :             UnlockReleaseBuffer(buffer);
    2005            0 :             break;
    2006              :         }
    2007              : 
    2008              :         /*
    2009              :          * Check tuple visibility; if visible, set it as the new result
    2010              :          * candidate.
    2011              :          */
    2012          195 :         valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
    2013          195 :         HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
    2014          195 :         if (valid)
    2015          138 :             *tid = ctid;
    2016              : 
    2017              :         /*
    2018              :          * If there's a valid t_ctid link, follow it, else we're done.
    2019              :          */
    2020          276 :         if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
    2021          138 :             HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
    2022          114 :             HeapTupleHeaderIndicatesMovedPartitions(tp.t_data) ||
    2023           57 :             ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
    2024              :         {
    2025          150 :             UnlockReleaseBuffer(buffer);
    2026          150 :             break;
    2027              :         }
    2028              : 
    2029           45 :         ctid = tp.t_data->t_ctid;
    2030           45 :         priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
    2031           45 :         UnlockReleaseBuffer(buffer);
    2032              :     }                           /* end of loop */
    2033          150 : }
    2034              : 
    2035              : 
    2036              : /*
    2037              :  * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
    2038              :  *
    2039              :  * This is called after we have waited for the XMAX transaction to terminate.
    2040              :  * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
    2041              :  * be set on exit.  If the transaction committed, we set the XMAX_COMMITTED
    2042              :  * hint bit if possible --- but beware that that may not yet be possible,
    2043              :  * if the transaction committed asynchronously.
    2044              :  *
    2045              :  * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
    2046              :  * even if it commits.
    2047              :  *
    2048              :  * Hence callers should look only at XMAX_INVALID.
    2049              :  *
    2050              :  * Note this is not allowed for tuples whose xmax is a multixact.
    2051              :  */
    2052              : static void
    2053          227 : UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
    2054              : {
    2055              :     Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
    2056              :     Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
    2057              : 
    2058          227 :     if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
    2059              :     {
    2060          402 :         if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
    2061          176 :             TransactionIdDidCommit(xid))
    2062          149 :             HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
    2063              :                                  xid);
    2064              :         else
    2065           77 :             HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
    2066              :                                  InvalidTransactionId);
    2067              :     }
    2068          227 : }
    2069              : 
    2070              : 
    2071              : /*
    2072              :  * GetBulkInsertState - prepare status object for a bulk insert
    2073              :  */
    2074              : BulkInsertState
    2075         2712 : GetBulkInsertState(void)
    2076              : {
    2077              :     BulkInsertState bistate;
    2078              : 
    2079         2712 :     bistate = (BulkInsertState) palloc_object(BulkInsertStateData);
    2080         2712 :     bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
    2081         2712 :     bistate->current_buf = InvalidBuffer;
    2082         2712 :     bistate->next_free = InvalidBlockNumber;
    2083         2712 :     bistate->last_free = InvalidBlockNumber;
    2084         2712 :     bistate->already_extended_by = 0;
    2085         2712 :     return bistate;
    2086              : }
    2087              : 
    2088              : /*
    2089              :  * FreeBulkInsertState - clean up after finishing a bulk insert
    2090              :  */
    2091              : void
    2092         2567 : FreeBulkInsertState(BulkInsertState bistate)
    2093              : {
    2094         2567 :     if (bistate->current_buf != InvalidBuffer)
    2095         2013 :         ReleaseBuffer(bistate->current_buf);
    2096         2567 :     FreeAccessStrategy(bistate->strategy);
    2097         2567 :     pfree(bistate);
    2098         2567 : }
    2099              : 
    2100              : /*
    2101              :  * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
    2102              :  */
    2103              : void
    2104        80758 : ReleaseBulkInsertStatePin(BulkInsertState bistate)
    2105              : {
    2106        80758 :     if (bistate->current_buf != InvalidBuffer)
    2107        30021 :         ReleaseBuffer(bistate->current_buf);
    2108        80758 :     bistate->current_buf = InvalidBuffer;
    2109              : 
    2110              :     /*
    2111              :      * Despite the name, we also reset bulk relation extension state.
    2112              :      * Otherwise we can end up erroring out due to looking for free space in
    2113              :      * ->next_free of one partition, even though ->next_free was set when
    2114              :      * extending another partition. It could obviously also be bad for
    2115              :      * efficiency to look at existing blocks at offsets from another
    2116              :      * partition, even if we don't error out.
    2117              :      */
    2118        80758 :     bistate->next_free = InvalidBlockNumber;
    2119        80758 :     bistate->last_free = InvalidBlockNumber;
    2120        80758 : }
    2121              : 
    2122              : 
    2123              : /*
    2124              :  *  heap_insert     - insert tuple into a heap
    2125              :  *
    2126              :  * The new tuple is stamped with current transaction ID and the specified
    2127              :  * command ID.
    2128              :  *
    2129              :  * See table_tuple_insert for comments about most of the input flags, except
    2130              :  * that this routine directly takes a tuple rather than a slot.
    2131              :  *
    2132              :  * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
    2133              :  * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
    2134              :  * implement table_tuple_insert_speculative().
    2135              :  *
    2136              :  * On return the header fields of *tup are updated to match the stored tuple;
    2137              :  * in particular tup->t_self receives the actual TID where the tuple was
    2138              :  * stored.  But note that any toasting of fields within the tuple data is NOT
    2139              :  * reflected into *tup.
    2140              :  */
    2141              : void
    2142      8391325 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
    2143              :             int options, BulkInsertState bistate)
    2144              : {
    2145      8391325 :     TransactionId xid = GetCurrentTransactionId();
    2146              :     HeapTuple   heaptup;
    2147              :     Buffer      buffer;
    2148      8391317 :     Buffer      vmbuffer = InvalidBuffer;
    2149      8391317 :     bool        all_visible_cleared = false;
    2150              : 
    2151              :     /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
    2152              :     Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
    2153              :            RelationGetNumberOfAttributes(relation));
    2154              : 
    2155      8391317 :     AssertHasSnapshotForToast(relation);
    2156              : 
    2157              :     /*
    2158              :      * Fill in tuple header fields and toast the tuple if necessary.
    2159              :      *
    2160              :      * Note: below this point, heaptup is the data we actually intend to store
    2161              :      * into the relation; tup is the caller's original untoasted data.
    2162              :      */
    2163      8391317 :     heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
    2164              : 
    2165              :     /*
    2166              :      * Find buffer to insert this tuple into.  If the page is all visible,
    2167              :      * this will also pin the requisite visibility map page.
    2168              :      */
    2169      8391317 :     buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
    2170              :                                        InvalidBuffer, options, bistate,
    2171              :                                        &vmbuffer, NULL,
    2172              :                                        0);
    2173              : 
    2174              :     /*
    2175              :      * We're about to do the actual insert -- but check for conflict first, to
    2176              :      * avoid possibly having to roll back work we've just done.
    2177              :      *
    2178              :      * This is safe without a recheck as long as there is no possibility of
    2179              :      * another process scanning the page between this check and the insert
    2180              :      * being visible to the scan (i.e., an exclusive buffer content lock is
    2181              :      * continuously held from this point until the tuple insert is visible).
    2182              :      *
    2183              :      * For a heap insert, we only need to check for table-level SSI locks. Our
    2184              :      * new tuple can't possibly conflict with existing tuple locks, and heap
    2185              :      * page locks are only consolidated versions of tuple locks; they do not
    2186              :      * lock "gaps" as index page locks do.  So we don't need to specify a
    2187              :      * buffer when making the call, which makes for a faster check.
    2188              :      */
    2189      8391317 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
    2190              : 
    2191              :     /* NO EREPORT(ERROR) from here till changes are logged */
    2192      8391305 :     START_CRIT_SECTION();
    2193              : 
    2194      8391305 :     RelationPutHeapTuple(relation, buffer, heaptup,
    2195      8391305 :                          (options & HEAP_INSERT_SPECULATIVE) != 0);
    2196              : 
    2197      8391305 :     if (PageIsAllVisible(BufferGetPage(buffer)))
    2198              :     {
    2199         7590 :         all_visible_cleared = true;
    2200         7590 :         PageClearAllVisible(BufferGetPage(buffer));
    2201         7590 :         visibilitymap_clear(relation,
    2202         7590 :                             ItemPointerGetBlockNumber(&(heaptup->t_self)),
    2203              :                             vmbuffer, VISIBILITYMAP_VALID_BITS);
    2204              :     }
    2205              : 
    2206              :     /*
    2207              :      * XXX Should we set PageSetPrunable on this page ?
    2208              :      *
    2209              :      * The inserting transaction may eventually abort thus making this tuple
    2210              :      * DEAD and hence available for pruning. Though we don't want to optimize
    2211              :      * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
    2212              :      * aborted tuple will never be pruned until next vacuum is triggered.
    2213              :      *
    2214              :      * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
    2215              :      */
    2216              : 
    2217      8391305 :     MarkBufferDirty(buffer);
    2218              : 
    2219              :     /* XLOG stuff */
    2220      8391305 :     if (RelationNeedsWAL(relation))
    2221              :     {
    2222              :         xl_heap_insert xlrec;
    2223              :         xl_heap_header xlhdr;
    2224              :         XLogRecPtr  recptr;
    2225      7501599 :         Page        page = BufferGetPage(buffer);
    2226      7501599 :         uint8       info = XLOG_HEAP_INSERT;
    2227      7501599 :         int         bufflags = 0;
    2228              : 
    2229              :         /*
    2230              :          * If this is a catalog, we need to transmit combo CIDs to properly
    2231              :          * decode, so log that as well.
    2232              :          */
    2233      7501599 :         if (RelationIsAccessibleInLogicalDecoding(relation))
    2234         3433 :             log_heap_new_cid(relation, heaptup);
    2235              : 
    2236              :         /*
    2237              :          * If this is the single and first tuple on page, we can reinit the
    2238              :          * page instead of restoring the whole thing.  Set flag, and hide
    2239              :          * buffer references from XLogInsert.
    2240              :          */
    2241      7598527 :         if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
    2242        96928 :             PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
    2243              :         {
    2244        95883 :             info |= XLOG_HEAP_INIT_PAGE;
    2245        95883 :             bufflags |= REGBUF_WILL_INIT;
    2246              :         }
    2247              : 
    2248      7501599 :         xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
    2249      7501599 :         xlrec.flags = 0;
    2250      7501599 :         if (all_visible_cleared)
    2251         7587 :             xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
    2252      7501599 :         if (options & HEAP_INSERT_SPECULATIVE)
    2253         2112 :             xlrec.flags |= XLH_INSERT_IS_SPECULATIVE;
    2254              :         Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
    2255              : 
    2256              :         /*
    2257              :          * For logical decoding, we need the tuple even if we're doing a full
    2258              :          * page write, so make sure it's included even if we take a full-page
    2259              :          * image. (XXX We could alternatively store a pointer into the FPW).
    2260              :          */
    2261      7501599 :         if (RelationIsLogicallyLogged(relation) &&
    2262       250516 :             !(options & HEAP_INSERT_NO_LOGICAL))
    2263              :         {
    2264       250489 :             xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
    2265       250489 :             bufflags |= REGBUF_KEEP_DATA;
    2266              : 
    2267       250489 :             if (IsToastRelation(relation))
    2268         1786 :                 xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
    2269              :         }
    2270              : 
    2271      7501599 :         XLogBeginInsert();
    2272      7501599 :         XLogRegisterData(&xlrec, SizeOfHeapInsert);
    2273              : 
    2274      7501599 :         xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
    2275      7501599 :         xlhdr.t_infomask = heaptup->t_data->t_infomask;
    2276      7501599 :         xlhdr.t_hoff = heaptup->t_data->t_hoff;
    2277              : 
    2278              :         /*
    2279              :          * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
    2280              :          * write the whole page to the xlog, we don't need to store
    2281              :          * xl_heap_header in the xlog.
    2282              :          */
    2283      7501599 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
    2284      7501599 :         XLogRegisterBufData(0, &xlhdr, SizeOfHeapHeader);
    2285              :         /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
    2286      7501599 :         XLogRegisterBufData(0,
    2287      7501599 :                             (char *) heaptup->t_data + SizeofHeapTupleHeader,
    2288      7501599 :                             heaptup->t_len - SizeofHeapTupleHeader);
    2289              : 
    2290              :         /* filtering by origin on a row level is much more efficient */
    2291      7501599 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
    2292              : 
    2293      7501599 :         recptr = XLogInsert(RM_HEAP_ID, info);
    2294              : 
    2295      7501599 :         PageSetLSN(page, recptr);
    2296              :     }
    2297              : 
    2298      8391305 :     END_CRIT_SECTION();
    2299              : 
    2300      8391305 :     UnlockReleaseBuffer(buffer);
    2301      8391305 :     if (vmbuffer != InvalidBuffer)
    2302         7871 :         ReleaseBuffer(vmbuffer);
    2303              : 
    2304              :     /*
    2305              :      * If tuple is cacheable, mark it for invalidation from the caches in case
    2306              :      * we abort.  Note it is OK to do this after releasing the buffer, because
    2307              :      * the heaptup data structure is all in local memory, not in the shared
    2308              :      * buffer.
    2309              :      */
    2310      8391305 :     CacheInvalidateHeapTuple(relation, heaptup, NULL);
    2311              : 
    2312              :     /* Note: speculative insertions are counted too, even if aborted later */
    2313      8391305 :     pgstat_count_heap_insert(relation, 1);
    2314              : 
    2315              :     /*
    2316              :      * If heaptup is a private copy, release it.  Don't forget to copy t_self
    2317              :      * back to the caller's image, too.
    2318              :      */
    2319      8391305 :     if (heaptup != tup)
    2320              :     {
    2321        18470 :         tup->t_self = heaptup->t_self;
    2322        18470 :         heap_freetuple(heaptup);
    2323              :     }
    2324      8391305 : }
    2325              : 
    2326              : /*
    2327              :  * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
    2328              :  * tuple header fields and toasts the tuple if necessary.  Returns a toasted
    2329              :  * version of the tuple if it was toasted, or the original tuple if not. Note
    2330              :  * that in any case, the header fields are also set in the original tuple.
    2331              :  */
    2332              : static HeapTuple
    2333      9899341 : heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
    2334              :                     CommandId cid, int options)
    2335              : {
    2336              :     /*
    2337              :      * To allow parallel inserts, we need to ensure that they are safe to be
    2338              :      * performed in workers. We have the infrastructure to allow parallel
    2339              :      * inserts in general except for the cases where inserts generate a new
    2340              :      * CommandId (eg. inserts into a table having a foreign key column).
    2341              :      */
    2342      9899341 :     if (IsParallelWorker())
    2343            0 :         ereport(ERROR,
    2344              :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
    2345              :                  errmsg("cannot insert tuples in a parallel worker")));
    2346              : 
    2347      9899341 :     tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
    2348      9899341 :     tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
    2349      9899341 :     tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
    2350      9899341 :     HeapTupleHeaderSetXmin(tup->t_data, xid);
    2351      9899341 :     if (options & HEAP_INSERT_FROZEN)
    2352       102088 :         HeapTupleHeaderSetXminFrozen(tup->t_data);
    2353              : 
    2354      9899341 :     HeapTupleHeaderSetCmin(tup->t_data, cid);
    2355      9899341 :     HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
    2356      9899341 :     tup->t_tableOid = RelationGetRelid(relation);
    2357              : 
    2358              :     /*
    2359              :      * If the new tuple is too big for storage or contains already toasted
    2360              :      * out-of-line attributes from some other relation, invoke the toaster.
    2361              :      */
    2362      9899341 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
    2363        31494 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
    2364              :     {
    2365              :         /* toast table entries should never be recursively toasted */
    2366              :         Assert(!HeapTupleHasExternal(tup));
    2367        31446 :         return tup;
    2368              :     }
    2369      9867895 :     else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
    2370        18522 :         return heap_toast_insert_or_update(relation, tup, NULL, options);
    2371              :     else
    2372      9849373 :         return tup;
    2373              : }
    2374              : 
    2375              : /*
    2376              :  * Helper for heap_multi_insert() that computes the number of entire pages
    2377              :  * that inserting the remaining heaptuples requires. Used to determine how
    2378              :  * much the relation needs to be extended by.
    2379              :  */
    2380              : static int
    2381       381437 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
    2382              : {
    2383       381437 :     size_t      page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
    2384       381437 :     int         npages = 1;
    2385              : 
    2386      2483268 :     for (int i = done; i < ntuples; i++)
    2387              :     {
    2388      2101831 :         size_t      tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
    2389              : 
    2390      2101831 :         if (page_avail < tup_sz)
    2391              :         {
    2392        15637 :             npages++;
    2393        15637 :             page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
    2394              :         }
    2395      2101831 :         page_avail -= tup_sz;
    2396              :     }
    2397              : 
    2398       381437 :     return npages;
    2399              : }
    2400              : 
    2401              : /*
    2402              :  *  heap_multi_insert   - insert multiple tuples into a heap
    2403              :  *
    2404              :  * This is like heap_insert(), but inserts multiple tuples in one operation.
    2405              :  * That's faster than calling heap_insert() in a loop, because when multiple
    2406              :  * tuples can be inserted on a single page, we can write just a single WAL
    2407              :  * record covering all of them, and only need to lock/unlock the page once.
    2408              :  *
    2409              :  * Note: this leaks memory into the current memory context. You can create a
    2410              :  * temporary context before calling this, if that's a problem.
    2411              :  */
    2412              : void
    2413       374842 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
    2414              :                   CommandId cid, int options, BulkInsertState bistate)
    2415              : {
    2416       374842 :     TransactionId xid = GetCurrentTransactionId();
    2417              :     HeapTuple  *heaptuples;
    2418              :     int         i;
    2419              :     int         ndone;
    2420              :     PGAlignedBlock scratch;
    2421              :     Page        page;
    2422       374842 :     Buffer      vmbuffer = InvalidBuffer;
    2423              :     bool        needwal;
    2424              :     Size        saveFreeSpace;
    2425       374842 :     bool        need_tuple_data = RelationIsLogicallyLogged(relation);
    2426       374842 :     bool        need_cids = RelationIsAccessibleInLogicalDecoding(relation);
    2427       374842 :     bool        starting_with_empty_page = false;
    2428       374842 :     int         npages = 0;
    2429       374842 :     int         npages_used = 0;
    2430              : 
    2431              :     /* currently not needed (thus unsupported) for heap_multi_insert() */
    2432              :     Assert(!(options & HEAP_INSERT_NO_LOGICAL));
    2433              : 
    2434       374842 :     AssertHasSnapshotForToast(relation);
    2435              : 
    2436       374842 :     needwal = RelationNeedsWAL(relation);
    2437       374842 :     saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
    2438              :                                                    HEAP_DEFAULT_FILLFACTOR);
    2439              : 
    2440              :     /* Toast and set header data in all the slots */
    2441       374842 :     heaptuples = palloc(ntuples * sizeof(HeapTuple));
    2442      1882866 :     for (i = 0; i < ntuples; i++)
    2443              :     {
    2444              :         HeapTuple   tuple;
    2445              : 
    2446      1508024 :         tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
    2447      1508024 :         slots[i]->tts_tableOid = RelationGetRelid(relation);
    2448      1508024 :         tuple->t_tableOid = slots[i]->tts_tableOid;
    2449      1508024 :         heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
    2450              :                                             options);
    2451              :     }
    2452              : 
    2453              :     /*
    2454              :      * We're about to do the actual inserts -- but check for conflict first,
    2455              :      * to minimize the possibility of having to roll back work we've just
    2456              :      * done.
    2457              :      *
    2458              :      * A check here does not definitively prevent a serialization anomaly;
    2459              :      * that check MUST be done at least past the point of acquiring an
    2460              :      * exclusive buffer content lock on every buffer that will be affected,
    2461              :      * and MAY be done after all inserts are reflected in the buffers and
    2462              :      * those locks are released; otherwise there is a race condition.  Since
    2463              :      * multiple buffers can be locked and unlocked in the loop below, and it
    2464              :      * would not be feasible to identify and lock all of those buffers before
    2465              :      * the loop, we must do a final check at the end.
    2466              :      *
    2467              :      * The check here could be omitted with no loss of correctness; it is
    2468              :      * present strictly as an optimization.
    2469              :      *
    2470              :      * For heap inserts, we only need to check for table-level SSI locks. Our
    2471              :      * new tuples can't possibly conflict with existing tuple locks, and heap
    2472              :      * page locks are only consolidated versions of tuple locks; they do not
    2473              :      * lock "gaps" as index page locks do.  So we don't need to specify a
    2474              :      * buffer when making the call, which makes for a faster check.
    2475              :      */
    2476       374842 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
    2477              : 
    2478       374842 :     ndone = 0;
    2479       764485 :     while (ndone < ntuples)
    2480              :     {
    2481              :         Buffer      buffer;
    2482       389643 :         bool        all_visible_cleared = false;
    2483       389643 :         bool        all_frozen_set = false;
    2484              :         int         nthispage;
    2485              : 
    2486       389643 :         CHECK_FOR_INTERRUPTS();
    2487              : 
    2488              :         /*
    2489              :          * Compute number of pages needed to fit the to-be-inserted tuples in
    2490              :          * the worst case.  This will be used to determine how much to extend
    2491              :          * the relation by in RelationGetBufferForTuple(), if needed.  If we
    2492              :          * filled a prior page from scratch, we can just update our last
    2493              :          * computation, but if we started with a partially filled page,
    2494              :          * recompute from scratch, the number of potentially required pages
    2495              :          * can vary due to tuples needing to fit onto the page, page headers
    2496              :          * etc.
    2497              :          */
    2498       389643 :         if (ndone == 0 || !starting_with_empty_page)
    2499              :         {
    2500       381437 :             npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
    2501              :                                              saveFreeSpace);
    2502       381437 :             npages_used = 0;
    2503              :         }
    2504              :         else
    2505         8206 :             npages_used++;
    2506              : 
    2507              :         /*
    2508              :          * Find buffer where at least the next tuple will fit.  If the page is
    2509              :          * all-visible, this will also pin the requisite visibility map page.
    2510              :          *
    2511              :          * Also pin visibility map page if COPY FREEZE inserts tuples into an
    2512              :          * empty page. See all_frozen_set below.
    2513              :          */
    2514       389643 :         buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
    2515              :                                            InvalidBuffer, options, bistate,
    2516              :                                            &vmbuffer, NULL,
    2517              :                                            npages - npages_used);
    2518       389643 :         page = BufferGetPage(buffer);
    2519              : 
    2520       389643 :         starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
    2521              : 
    2522       389643 :         if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
    2523              :         {
    2524         1661 :             all_frozen_set = true;
    2525              :             /* Lock the vmbuffer before entering the critical section */
    2526         1661 :             LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
    2527              :         }
    2528              : 
    2529              :         /* NO EREPORT(ERROR) from here till changes are logged */
    2530       389643 :         START_CRIT_SECTION();
    2531              : 
    2532              :         /*
    2533              :          * RelationGetBufferForTuple has ensured that the first tuple fits.
    2534              :          * Put that on the page, and then as many other tuples as fit.
    2535              :          */
    2536       389643 :         RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
    2537              : 
    2538              :         /*
    2539              :          * For logical decoding we need combo CIDs to properly decode the
    2540              :          * catalog.
    2541              :          */
    2542       389643 :         if (needwal && need_cids)
    2543         5063 :             log_heap_new_cid(relation, heaptuples[ndone]);
    2544              : 
    2545      1508024 :         for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
    2546              :         {
    2547      1133182 :             HeapTuple   heaptup = heaptuples[ndone + nthispage];
    2548              : 
    2549      1133182 :             if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
    2550        14801 :                 break;
    2551              : 
    2552      1118381 :             RelationPutHeapTuple(relation, buffer, heaptup, false);
    2553              : 
    2554              :             /*
    2555              :              * For logical decoding we need combo CIDs to properly decode the
    2556              :              * catalog.
    2557              :              */
    2558      1118381 :             if (needwal && need_cids)
    2559         4738 :                 log_heap_new_cid(relation, heaptup);
    2560              :         }
    2561              : 
    2562              :         /*
    2563              :          * If the page is all visible, need to clear that, unless we're only
    2564              :          * going to add further frozen rows to it.
    2565              :          *
    2566              :          * If we're only adding already frozen rows to a previously empty
    2567              :          * page, mark it as all-frozen and update the visibility map. We're
    2568              :          * already holding a pin on the vmbuffer.
    2569              :          */
    2570       389643 :         if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
    2571              :         {
    2572         3610 :             all_visible_cleared = true;
    2573         3610 :             PageClearAllVisible(page);
    2574         3610 :             visibilitymap_clear(relation,
    2575              :                                 BufferGetBlockNumber(buffer),
    2576              :                                 vmbuffer, VISIBILITYMAP_VALID_BITS);
    2577              :         }
    2578       386033 :         else if (all_frozen_set)
    2579              :         {
    2580         1661 :             PageSetAllVisible(page);
    2581         1661 :             visibilitymap_set_vmbits(BufferGetBlockNumber(buffer),
    2582              :                                      vmbuffer,
    2583              :                                      VISIBILITYMAP_ALL_VISIBLE |
    2584              :                                      VISIBILITYMAP_ALL_FROZEN,
    2585              :                                      relation->rd_locator);
    2586              :         }
    2587              : 
    2588              :         /*
    2589              :          * XXX Should we set PageSetPrunable on this page ? See heap_insert()
    2590              :          */
    2591              : 
    2592       389643 :         MarkBufferDirty(buffer);
    2593              : 
    2594              :         /* XLOG stuff */
    2595       389643 :         if (needwal)
    2596              :         {
    2597              :             XLogRecPtr  recptr;
    2598              :             xl_heap_multi_insert *xlrec;
    2599       385820 :             uint8       info = XLOG_HEAP2_MULTI_INSERT;
    2600              :             char       *tupledata;
    2601              :             int         totaldatalen;
    2602       385820 :             char       *scratchptr = scratch.data;
    2603              :             bool        init;
    2604       385820 :             int         bufflags = 0;
    2605              : 
    2606              :             /*
    2607              :              * If the page was previously empty, we can reinit the page
    2608              :              * instead of restoring the whole thing.
    2609              :              */
    2610       385820 :             init = starting_with_empty_page;
    2611              : 
    2612              :             /* allocate xl_heap_multi_insert struct from the scratch area */
    2613       385820 :             xlrec = (xl_heap_multi_insert *) scratchptr;
    2614       385820 :             scratchptr += SizeOfHeapMultiInsert;
    2615              : 
    2616              :             /*
    2617              :              * Allocate offsets array. Unless we're reinitializing the page,
    2618              :              * in that case the tuples are stored in order starting at
    2619              :              * FirstOffsetNumber and we don't need to store the offsets
    2620              :              * explicitly.
    2621              :              */
    2622       385820 :             if (!init)
    2623       372762 :                 scratchptr += nthispage * sizeof(OffsetNumber);
    2624              : 
    2625              :             /* the rest of the scratch space is used for tuple data */
    2626       385820 :             tupledata = scratchptr;
    2627              : 
    2628              :             /* check that the mutually exclusive flags are not both set */
    2629              :             Assert(!(all_visible_cleared && all_frozen_set));
    2630              : 
    2631       385820 :             xlrec->flags = 0;
    2632       385820 :             if (all_visible_cleared)
    2633         3610 :                 xlrec->flags = XLH_INSERT_ALL_VISIBLE_CLEARED;
    2634              : 
    2635              :             /*
    2636              :              * We don't have to worry about including a conflict xid in the
    2637              :              * WAL record, as HEAP_INSERT_FROZEN intentionally violates
    2638              :              * visibility rules.
    2639              :              */
    2640       385820 :             if (all_frozen_set)
    2641           17 :                 xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
    2642              : 
    2643       385820 :             xlrec->ntuples = nthispage;
    2644              : 
    2645              :             /*
    2646              :              * Write out an xl_multi_insert_tuple and the tuple data itself
    2647              :              * for each tuple.
    2648              :              */
    2649      1688394 :             for (i = 0; i < nthispage; i++)
    2650              :             {
    2651      1302574 :                 HeapTuple   heaptup = heaptuples[ndone + i];
    2652              :                 xl_multi_insert_tuple *tuphdr;
    2653              :                 int         datalen;
    2654              : 
    2655      1302574 :                 if (!init)
    2656       777737 :                     xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
    2657              :                 /* xl_multi_insert_tuple needs two-byte alignment. */
    2658      1302574 :                 tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
    2659      1302574 :                 scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
    2660              : 
    2661      1302574 :                 tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
    2662      1302574 :                 tuphdr->t_infomask = heaptup->t_data->t_infomask;
    2663      1302574 :                 tuphdr->t_hoff = heaptup->t_data->t_hoff;
    2664              : 
    2665              :                 /* write bitmap [+ padding] [+ oid] + data */
    2666      1302574 :                 datalen = heaptup->t_len - SizeofHeapTupleHeader;
    2667      1302574 :                 memcpy(scratchptr,
    2668      1302574 :                        (char *) heaptup->t_data + SizeofHeapTupleHeader,
    2669              :                        datalen);
    2670      1302574 :                 tuphdr->datalen = datalen;
    2671      1302574 :                 scratchptr += datalen;
    2672              :             }
    2673       385820 :             totaldatalen = scratchptr - tupledata;
    2674              :             Assert((scratchptr - scratch.data) < BLCKSZ);
    2675              : 
    2676       385820 :             if (need_tuple_data)
    2677           72 :                 xlrec->flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
    2678              : 
    2679              :             /*
    2680              :              * Signal that this is the last xl_heap_multi_insert record
    2681              :              * emitted by this call to heap_multi_insert(). Needed for logical
    2682              :              * decoding so it knows when to cleanup temporary data.
    2683              :              */
    2684       385820 :             if (ndone + nthispage == ntuples)
    2685       374428 :                 xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
    2686              : 
    2687       385820 :             if (init)
    2688              :             {
    2689        13058 :                 info |= XLOG_HEAP_INIT_PAGE;
    2690        13058 :                 bufflags |= REGBUF_WILL_INIT;
    2691              :             }
    2692              : 
    2693              :             /*
    2694              :              * If we're doing logical decoding, include the new tuple data
    2695              :              * even if we take a full-page image of the page.
    2696              :              */
    2697       385820 :             if (need_tuple_data)
    2698           72 :                 bufflags |= REGBUF_KEEP_DATA;
    2699              : 
    2700       385820 :             XLogBeginInsert();
    2701       385820 :             XLogRegisterData(xlrec, tupledata - scratch.data);
    2702       385820 :             XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
    2703       385820 :             if (all_frozen_set)
    2704           17 :                 XLogRegisterBuffer(1, vmbuffer, 0);
    2705              : 
    2706       385820 :             XLogRegisterBufData(0, tupledata, totaldatalen);
    2707              : 
    2708              :             /* filtering by origin on a row level is much more efficient */
    2709       385820 :             XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
    2710              : 
    2711       385820 :             recptr = XLogInsert(RM_HEAP2_ID, info);
    2712              : 
    2713       385820 :             PageSetLSN(page, recptr);
    2714       385820 :             if (all_frozen_set)
    2715              :             {
    2716              :                 Assert(BufferIsDirty(vmbuffer));
    2717           17 :                 PageSetLSN(BufferGetPage(vmbuffer), recptr);
    2718              :             }
    2719              :         }
    2720              : 
    2721       389643 :         END_CRIT_SECTION();
    2722              : 
    2723       389643 :         if (all_frozen_set)
    2724         1661 :             LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
    2725              : 
    2726       389643 :         UnlockReleaseBuffer(buffer);
    2727       389643 :         ndone += nthispage;
    2728              : 
    2729              :         /*
    2730              :          * NB: Only release vmbuffer after inserting all tuples - it's fairly
    2731              :          * likely that we'll insert into subsequent heap pages that are likely
    2732              :          * to use the same vm page.
    2733              :          */
    2734              :     }
    2735              : 
    2736              :     /* We're done with inserting all tuples, so release the last vmbuffer. */
    2737       374842 :     if (vmbuffer != InvalidBuffer)
    2738         3689 :         ReleaseBuffer(vmbuffer);
    2739              : 
    2740              :     /*
    2741              :      * We're done with the actual inserts.  Check for conflicts again, to
    2742              :      * ensure that all rw-conflicts in to these inserts are detected.  Without
    2743              :      * this final check, a sequential scan of the heap may have locked the
    2744              :      * table after the "before" check, missing one opportunity to detect the
    2745              :      * conflict, and then scanned the table before the new tuples were there,
    2746              :      * missing the other chance to detect the conflict.
    2747              :      *
    2748              :      * For heap inserts, we only need to check for table-level SSI locks. Our
    2749              :      * new tuples can't possibly conflict with existing tuple locks, and heap
    2750              :      * page locks are only consolidated versions of tuple locks; they do not
    2751              :      * lock "gaps" as index page locks do.  So we don't need to specify a
    2752              :      * buffer when making the call.
    2753              :      */
    2754       374842 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
    2755              : 
    2756              :     /*
    2757              :      * If tuples are cacheable, mark them for invalidation from the caches in
    2758              :      * case we abort.  Note it is OK to do this after releasing the buffer,
    2759              :      * because the heaptuples data structure is all in local memory, not in
    2760              :      * the shared buffer.
    2761              :      */
    2762       374842 :     if (IsCatalogRelation(relation))
    2763              :     {
    2764      1279245 :         for (i = 0; i < ntuples; i++)
    2765       905633 :             CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
    2766              :     }
    2767              : 
    2768              :     /* copy t_self fields back to the caller's slots */
    2769      1882866 :     for (i = 0; i < ntuples; i++)
    2770      1508024 :         slots[i]->tts_tid = heaptuples[i]->t_self;
    2771              : 
    2772       374842 :     pgstat_count_heap_insert(relation, ntuples);
    2773       374842 : }
    2774              : 
    2775              : /*
    2776              :  *  simple_heap_insert - insert a tuple
    2777              :  *
    2778              :  * Currently, this routine differs from heap_insert only in supplying
    2779              :  * a default command ID and not allowing access to the speedup options.
    2780              :  *
    2781              :  * This should be used rather than using heap_insert directly in most places
    2782              :  * where we are modifying system catalogs.
    2783              :  */
    2784              : void
    2785       934869 : simple_heap_insert(Relation relation, HeapTuple tup)
    2786              : {
    2787       934869 :     heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
    2788       934869 : }
    2789              : 
    2790              : /*
    2791              :  * Given infomask/infomask2, compute the bits that must be saved in the
    2792              :  * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
    2793              :  * xl_heap_lock_updated WAL records.
    2794              :  *
    2795              :  * See fix_infomask_from_infobits.
    2796              :  */
    2797              : static uint8
    2798      2063286 : compute_infobits(uint16 infomask, uint16 infomask2)
    2799              : {
    2800              :     return
    2801      2063286 :         ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
    2802      2063286 :         ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
    2803      2063286 :         ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
    2804              :     /* note we ignore HEAP_XMAX_SHR_LOCK here */
    2805      4126572 :         ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
    2806              :         ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
    2807      2063286 :          XLHL_KEYS_UPDATED : 0);
    2808              : }
    2809              : 
    2810              : /*
    2811              :  * Given two versions of the same t_infomask for a tuple, compare them and
    2812              :  * return whether the relevant status for a tuple Xmax has changed.  This is
    2813              :  * used after a buffer lock has been released and reacquired: we want to ensure
    2814              :  * that the tuple state continues to be the same it was when we previously
    2815              :  * examined it.
    2816              :  *
    2817              :  * Note the Xmax field itself must be compared separately.
    2818              :  */
    2819              : static inline bool
    2820         5386 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
    2821              : {
    2822         5386 :     const uint16 interesting =
    2823              :         HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
    2824              : 
    2825         5386 :     if ((new_infomask & interesting) != (old_infomask & interesting))
    2826           16 :         return true;
    2827              : 
    2828         5370 :     return false;
    2829              : }
    2830              : 
    2831              : /*
    2832              :  *  heap_delete - delete a tuple
    2833              :  *
    2834              :  * See table_tuple_delete() for an explanation of the parameters, except that
    2835              :  * this routine directly takes a tuple rather than a slot.
    2836              :  *
    2837              :  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
    2838              :  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
    2839              :  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
    2840              :  * generated by another transaction).
    2841              :  */
    2842              : TM_Result
    2843      1527443 : heap_delete(Relation relation, const ItemPointerData *tid,
    2844              :             CommandId cid, Snapshot crosscheck, bool wait,
    2845              :             TM_FailureData *tmfd, bool changingPart)
    2846              : {
    2847              :     TM_Result   result;
    2848      1527443 :     TransactionId xid = GetCurrentTransactionId();
    2849              :     ItemId      lp;
    2850              :     HeapTupleData tp;
    2851              :     Page        page;
    2852              :     BlockNumber block;
    2853              :     Buffer      buffer;
    2854      1527443 :     Buffer      vmbuffer = InvalidBuffer;
    2855              :     TransactionId new_xmax;
    2856              :     uint16      new_infomask,
    2857              :                 new_infomask2;
    2858      1527443 :     bool        have_tuple_lock = false;
    2859              :     bool        iscombo;
    2860      1527443 :     bool        all_visible_cleared = false;
    2861      1527443 :     HeapTuple   old_key_tuple = NULL;   /* replica identity of the tuple */
    2862      1527443 :     bool        old_key_copied = false;
    2863              : 
    2864              :     Assert(ItemPointerIsValid(tid));
    2865              : 
    2866      1527443 :     AssertHasSnapshotForToast(relation);
    2867              : 
    2868              :     /*
    2869              :      * Forbid this during a parallel operation, lest it allocate a combo CID.
    2870              :      * Other workers might need that combo CID for visibility checks, and we
    2871              :      * have no provision for broadcasting it to them.
    2872              :      */
    2873      1527443 :     if (IsInParallelMode())
    2874            0 :         ereport(ERROR,
    2875              :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
    2876              :                  errmsg("cannot delete tuples during a parallel operation")));
    2877              : 
    2878      1527443 :     block = ItemPointerGetBlockNumber(tid);
    2879      1527443 :     buffer = ReadBuffer(relation, block);
    2880      1527443 :     page = BufferGetPage(buffer);
    2881              : 
    2882              :     /*
    2883              :      * Before locking the buffer, pin the visibility map page if it appears to
    2884              :      * be necessary.  Since we haven't got the lock yet, someone else might be
    2885              :      * in the middle of changing this, so we'll need to recheck after we have
    2886              :      * the lock.
    2887              :      */
    2888      1527443 :     if (PageIsAllVisible(page))
    2889          243 :         visibilitymap_pin(relation, block, &vmbuffer);
    2890              : 
    2891      1527443 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    2892              : 
    2893      1527443 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
    2894              :     Assert(ItemIdIsNormal(lp));
    2895              : 
    2896      1527443 :     tp.t_tableOid = RelationGetRelid(relation);
    2897      1527443 :     tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
    2898      1527443 :     tp.t_len = ItemIdGetLength(lp);
    2899      1527443 :     tp.t_self = *tid;
    2900              : 
    2901            1 : l1:
    2902              : 
    2903              :     /*
    2904              :      * If we didn't pin the visibility map page and the page has become all
    2905              :      * visible while we were busy locking the buffer, we'll have to unlock and
    2906              :      * re-lock, to avoid holding the buffer lock across an I/O.  That's a bit
    2907              :      * unfortunate, but hopefully shouldn't happen often.
    2908              :      */
    2909      1527444 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
    2910              :     {
    2911            0 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    2912            0 :         visibilitymap_pin(relation, block, &vmbuffer);
    2913            0 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    2914              :     }
    2915              : 
    2916      1527444 :     result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
    2917              : 
    2918      1527444 :     if (result == TM_Invisible)
    2919              :     {
    2920            0 :         UnlockReleaseBuffer(buffer);
    2921            0 :         ereport(ERROR,
    2922              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2923              :                  errmsg("attempted to delete invisible tuple")));
    2924              :     }
    2925      1527444 :     else if (result == TM_BeingModified && wait)
    2926              :     {
    2927              :         TransactionId xwait;
    2928              :         uint16      infomask;
    2929              : 
    2930              :         /* must copy state data before unlocking buffer */
    2931        40561 :         xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
    2932        40561 :         infomask = tp.t_data->t_infomask;
    2933              : 
    2934              :         /*
    2935              :          * Sleep until concurrent transaction ends -- except when there's a
    2936              :          * single locker and it's our own transaction.  Note we don't care
    2937              :          * which lock mode the locker has, because we need the strongest one.
    2938              :          *
    2939              :          * Before sleeping, we need to acquire tuple lock to establish our
    2940              :          * priority for the tuple (see heap_lock_tuple).  LockTuple will
    2941              :          * release us when we are next-in-line for the tuple.
    2942              :          *
    2943              :          * If we are forced to "start over" below, we keep the tuple lock;
    2944              :          * this arranges that we stay at the head of the line while rechecking
    2945              :          * tuple state.
    2946              :          */
    2947        40561 :         if (infomask & HEAP_XMAX_IS_MULTI)
    2948              :         {
    2949            8 :             bool        current_is_member = false;
    2950              : 
    2951            8 :             if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
    2952              :                                         LockTupleExclusive, &current_is_member))
    2953              :             {
    2954            8 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    2955              : 
    2956              :                 /*
    2957              :                  * Acquire the lock, if necessary (but skip it when we're
    2958              :                  * requesting a lock and already have one; avoids deadlock).
    2959              :                  */
    2960            8 :                 if (!current_is_member)
    2961            6 :                     heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
    2962              :                                          LockWaitBlock, &have_tuple_lock);
    2963              : 
    2964              :                 /* wait for multixact */
    2965            8 :                 MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
    2966              :                                 relation, &(tp.t_self), XLTW_Delete,
    2967              :                                 NULL);
    2968            8 :                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    2969              : 
    2970              :                 /*
    2971              :                  * If xwait had just locked the tuple then some other xact
    2972              :                  * could update this tuple before we get to this point.  Check
    2973              :                  * for xmax change, and start over if so.
    2974              :                  *
    2975              :                  * We also must start over if we didn't pin the VM page, and
    2976              :                  * the page has become all visible.
    2977              :                  */
    2978           16 :                 if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
    2979           16 :                     xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
    2980            8 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
    2981              :                                          xwait))
    2982            0 :                     goto l1;
    2983              :             }
    2984              : 
    2985              :             /*
    2986              :              * You might think the multixact is necessarily done here, but not
    2987              :              * so: it could have surviving members, namely our own xact or
    2988              :              * other subxacts of this backend.  It is legal for us to delete
    2989              :              * the tuple in either case, however (the latter case is
    2990              :              * essentially a situation of upgrading our former shared lock to
    2991              :              * exclusive).  We don't bother changing the on-disk hint bits
    2992              :              * since we are about to overwrite the xmax altogether.
    2993              :              */
    2994              :         }
    2995        40553 :         else if (!TransactionIdIsCurrentTransactionId(xwait))
    2996              :         {
    2997              :             /*
    2998              :              * Wait for regular transaction to end; but first, acquire tuple
    2999              :              * lock.
    3000              :              */
    3001           52 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    3002           52 :             heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
    3003              :                                  LockWaitBlock, &have_tuple_lock);
    3004           52 :             XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
    3005           48 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    3006              : 
    3007              :             /*
    3008              :              * xwait is done, but if xwait had just locked the tuple then some
    3009              :              * other xact could update this tuple before we get to this point.
    3010              :              * Check for xmax change, and start over if so.
    3011              :              *
    3012              :              * We also must start over if we didn't pin the VM page, and the
    3013              :              * page has become all visible.
    3014              :              */
    3015           96 :             if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
    3016           95 :                 xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
    3017           47 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
    3018              :                                      xwait))
    3019            1 :                 goto l1;
    3020              : 
    3021              :             /* Otherwise check if it committed or aborted */
    3022           47 :             UpdateXmaxHintBits(tp.t_data, buffer, xwait);
    3023              :         }
    3024              : 
    3025              :         /*
    3026              :          * We may overwrite if previous xmax aborted, or if it committed but
    3027              :          * only locked the tuple without updating it.
    3028              :          */
    3029        81092 :         if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
    3030        40567 :             HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
    3031           31 :             HeapTupleHeaderIsOnlyLocked(tp.t_data))
    3032        40529 :             result = TM_Ok;
    3033           27 :         else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
    3034           23 :             result = TM_Updated;
    3035              :         else
    3036            4 :             result = TM_Deleted;
    3037              :     }
    3038              : 
    3039              :     /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
    3040              :     if (result != TM_Ok)
    3041              :     {
    3042              :         Assert(result == TM_SelfModified ||
    3043              :                result == TM_Updated ||
    3044              :                result == TM_Deleted ||
    3045              :                result == TM_BeingModified);
    3046              :         Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
    3047              :         Assert(result != TM_Updated ||
    3048              :                !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
    3049              :     }
    3050              : 
    3051      1527439 :     if (crosscheck != InvalidSnapshot && result == TM_Ok)
    3052              :     {
    3053              :         /* Perform additional check for transaction-snapshot mode RI updates */
    3054            1 :         if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
    3055            1 :             result = TM_Updated;
    3056              :     }
    3057              : 
    3058      1527439 :     if (result != TM_Ok)
    3059              :     {
    3060           62 :         tmfd->ctid = tp.t_data->t_ctid;
    3061           62 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
    3062           62 :         if (result == TM_SelfModified)
    3063           21 :             tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
    3064              :         else
    3065           41 :             tmfd->cmax = InvalidCommandId;
    3066           62 :         UnlockReleaseBuffer(buffer);
    3067           62 :         if (have_tuple_lock)
    3068           27 :             UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
    3069           62 :         if (vmbuffer != InvalidBuffer)
    3070            0 :             ReleaseBuffer(vmbuffer);
    3071           62 :         return result;
    3072              :     }
    3073              : 
    3074              :     /*
    3075              :      * We're about to do the actual delete -- check for conflict first, to
    3076              :      * avoid possibly having to roll back work we've just done.
    3077              :      *
    3078              :      * This is safe without a recheck as long as there is no possibility of
    3079              :      * another process scanning the page between this check and the delete
    3080              :      * being visible to the scan (i.e., an exclusive buffer content lock is
    3081              :      * continuously held from this point until the tuple delete is visible).
    3082              :      */
    3083      1527377 :     CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
    3084              : 
    3085              :     /* replace cid with a combo CID if necessary */
    3086      1527363 :     HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
    3087              : 
    3088              :     /*
    3089              :      * Compute replica identity tuple before entering the critical section so
    3090              :      * we don't PANIC upon a memory allocation failure.
    3091              :      */
    3092      1527363 :     old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
    3093              : 
    3094              :     /*
    3095              :      * If this is the first possibly-multixact-able operation in the current
    3096              :      * transaction, set my per-backend OldestMemberMXactId setting. We can be
    3097              :      * certain that the transaction will never become a member of any older
    3098              :      * MultiXactIds than that.  (We have to do this even if we end up just
    3099              :      * using our own TransactionId below, since some other backend could
    3100              :      * incorporate our XID into a MultiXact immediately afterwards.)
    3101              :      */
    3102      1527363 :     MultiXactIdSetOldestMember();
    3103              : 
    3104      1527363 :     compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
    3105      1527363 :                               tp.t_data->t_infomask, tp.t_data->t_infomask2,
    3106              :                               xid, LockTupleExclusive, true,
    3107              :                               &new_xmax, &new_infomask, &new_infomask2);
    3108              : 
    3109      1527363 :     START_CRIT_SECTION();
    3110              : 
    3111              :     /*
    3112              :      * If this transaction commits, the tuple will become DEAD sooner or
    3113              :      * later.  Set flag that this page is a candidate for pruning once our xid
    3114              :      * falls below the OldestXmin horizon.  If the transaction finally aborts,
    3115              :      * the subsequent page pruning will be a no-op and the hint will be
    3116              :      * cleared.
    3117              :      */
    3118      1527363 :     PageSetPrunable(page, xid);
    3119              : 
    3120      1527363 :     if (PageIsAllVisible(page))
    3121              :     {
    3122          243 :         all_visible_cleared = true;
    3123          243 :         PageClearAllVisible(page);
    3124          243 :         visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
    3125              :                             vmbuffer, VISIBILITYMAP_VALID_BITS);
    3126              :     }
    3127              : 
    3128              :     /* store transaction information of xact deleting the tuple */
    3129      1527363 :     tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
    3130      1527363 :     tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
    3131      1527363 :     tp.t_data->t_infomask |= new_infomask;
    3132      1527363 :     tp.t_data->t_infomask2 |= new_infomask2;
    3133      1527363 :     HeapTupleHeaderClearHotUpdated(tp.t_data);
    3134      1527363 :     HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
    3135      1527363 :     HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
    3136              :     /* Make sure there is no forward chain link in t_ctid */
    3137      1527363 :     tp.t_data->t_ctid = tp.t_self;
    3138              : 
    3139              :     /* Signal that this is actually a move into another partition */
    3140      1527363 :     if (changingPart)
    3141          493 :         HeapTupleHeaderSetMovedPartitions(tp.t_data);
    3142              : 
    3143      1527363 :     MarkBufferDirty(buffer);
    3144              : 
    3145              :     /*
    3146              :      * XLOG stuff
    3147              :      *
    3148              :      * NB: heap_abort_speculative() uses the same xlog record and replay
    3149              :      * routines.
    3150              :      */
    3151      1527363 :     if (RelationNeedsWAL(relation))
    3152              :     {
    3153              :         xl_heap_delete xlrec;
    3154              :         xl_heap_header xlhdr;
    3155              :         XLogRecPtr  recptr;
    3156              : 
    3157              :         /*
    3158              :          * For logical decode we need combo CIDs to properly decode the
    3159              :          * catalog
    3160              :          */
    3161      1464769 :         if (RelationIsAccessibleInLogicalDecoding(relation))
    3162         6291 :             log_heap_new_cid(relation, &tp);
    3163              : 
    3164      1464769 :         xlrec.flags = 0;
    3165      1464769 :         if (all_visible_cleared)
    3166          243 :             xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
    3167      1464769 :         if (changingPart)
    3168          493 :             xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
    3169      2929538 :         xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
    3170      1464769 :                                               tp.t_data->t_infomask2);
    3171      1464769 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
    3172      1464769 :         xlrec.xmax = new_xmax;
    3173              : 
    3174      1464769 :         if (old_key_tuple != NULL)
    3175              :         {
    3176        47018 :             if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
    3177          132 :                 xlrec.flags |= XLH_DELETE_CONTAINS_OLD_TUPLE;
    3178              :             else
    3179        46886 :                 xlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;
    3180              :         }
    3181              : 
    3182      1464769 :         XLogBeginInsert();
    3183      1464769 :         XLogRegisterData(&xlrec, SizeOfHeapDelete);
    3184              : 
    3185      1464769 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
    3186              : 
    3187              :         /*
    3188              :          * Log replica identity of the deleted tuple if there is one
    3189              :          */
    3190      1464769 :         if (old_key_tuple != NULL)
    3191              :         {
    3192        47018 :             xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
    3193        47018 :             xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
    3194        47018 :             xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
    3195              : 
    3196        47018 :             XLogRegisterData(&xlhdr, SizeOfHeapHeader);
    3197        47018 :             XLogRegisterData((char *) old_key_tuple->t_data
    3198              :                              + SizeofHeapTupleHeader,
    3199        47018 :                              old_key_tuple->t_len
    3200              :                              - SizeofHeapTupleHeader);
    3201              :         }
    3202              : 
    3203              :         /* filtering by origin on a row level is much more efficient */
    3204      1464769 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
    3205              : 
    3206      1464769 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
    3207              : 
    3208      1464769 :         PageSetLSN(page, recptr);
    3209              :     }
    3210              : 
    3211      1527363 :     END_CRIT_SECTION();
    3212              : 
    3213      1527363 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    3214              : 
    3215      1527363 :     if (vmbuffer != InvalidBuffer)
    3216          243 :         ReleaseBuffer(vmbuffer);
    3217              : 
    3218              :     /*
    3219              :      * If the tuple has toasted out-of-line attributes, we need to delete
    3220              :      * those items too.  We have to do this before releasing the buffer
    3221              :      * because we need to look at the contents of the tuple, but it's OK to
    3222              :      * release the content lock on the buffer first.
    3223              :      */
    3224      1529946 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
    3225         2593 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
    3226              :     {
    3227              :         /* toast table entries should never be recursively toasted */
    3228              :         Assert(!HeapTupleHasExternal(&tp));
    3229              :     }
    3230      1524780 :     else if (HeapTupleHasExternal(&tp))
    3231          294 :         heap_toast_delete(relation, &tp, false);
    3232              : 
    3233              :     /*
    3234              :      * Mark tuple for invalidation from system caches at next command
    3235              :      * boundary. We have to do this before releasing the buffer because we
    3236              :      * need to look at the contents of the tuple.
    3237              :      */
    3238      1527363 :     CacheInvalidateHeapTuple(relation, &tp, NULL);
    3239              : 
    3240              :     /* Now we can release the buffer */
    3241      1527363 :     ReleaseBuffer(buffer);
    3242              : 
    3243              :     /*
    3244              :      * Release the lmgr tuple lock, if we had it.
    3245              :      */
    3246      1527363 :     if (have_tuple_lock)
    3247           26 :         UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
    3248              : 
    3249      1527363 :     pgstat_count_heap_delete(relation);
    3250              : 
    3251      1527363 :     if (old_key_tuple != NULL && old_key_copied)
    3252        46887 :         heap_freetuple(old_key_tuple);
    3253              : 
    3254      1527363 :     return TM_Ok;
    3255              : }
    3256              : 
    3257              : /*
    3258              :  *  simple_heap_delete - delete a tuple
    3259              :  *
    3260              :  * This routine may be used to delete a tuple when concurrent updates of
    3261              :  * the target tuple are not expected (for example, because we have a lock
    3262              :  * on the relation associated with the tuple).  Any failure is reported
    3263              :  * via ereport().
    3264              :  */
    3265              : void
    3266       661464 : simple_heap_delete(Relation relation, const ItemPointerData *tid)
    3267              : {
    3268              :     TM_Result   result;
    3269              :     TM_FailureData tmfd;
    3270              : 
    3271       661464 :     result = heap_delete(relation, tid,
    3272              :                          GetCurrentCommandId(true), InvalidSnapshot,
    3273              :                          true /* wait for commit */ ,
    3274              :                          &tmfd, false /* changingPart */ );
    3275       661464 :     switch (result)
    3276              :     {
    3277            0 :         case TM_SelfModified:
    3278              :             /* Tuple was already updated in current command? */
    3279            0 :             elog(ERROR, "tuple already updated by self");
    3280              :             break;
    3281              : 
    3282       661464 :         case TM_Ok:
    3283              :             /* done successfully */
    3284       661464 :             break;
    3285              : 
    3286            0 :         case TM_Updated:
    3287            0 :             elog(ERROR, "tuple concurrently updated");
    3288              :             break;
    3289              : 
    3290            0 :         case TM_Deleted:
    3291            0 :             elog(ERROR, "tuple concurrently deleted");
    3292              :             break;
    3293              : 
    3294            0 :         default:
    3295            0 :             elog(ERROR, "unrecognized heap_delete status: %u", result);
    3296              :             break;
    3297              :     }
    3298       661464 : }
    3299              : 
    3300              : /*
    3301              :  *  heap_update - replace a tuple
    3302              :  *
    3303              :  * See table_tuple_update() for an explanation of the parameters, except that
    3304              :  * this routine directly takes a tuple rather than a slot.
    3305              :  *
    3306              :  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
    3307              :  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
    3308              :  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
    3309              :  * generated by another transaction).
    3310              :  */
    3311              : TM_Result
    3312       310910 : heap_update(Relation relation, const ItemPointerData *otid, HeapTuple newtup,
    3313              :             CommandId cid, Snapshot crosscheck, bool wait,
    3314              :             TM_FailureData *tmfd, LockTupleMode *lockmode,
    3315              :             TU_UpdateIndexes *update_indexes)
    3316              : {
    3317              :     TM_Result   result;
    3318       310910 :     TransactionId xid = GetCurrentTransactionId();
    3319              :     Bitmapset  *hot_attrs;
    3320              :     Bitmapset  *sum_attrs;
    3321              :     Bitmapset  *key_attrs;
    3322              :     Bitmapset  *id_attrs;
    3323              :     Bitmapset  *interesting_attrs;
    3324              :     Bitmapset  *modified_attrs;
    3325              :     ItemId      lp;
    3326              :     HeapTupleData oldtup;
    3327              :     HeapTuple   heaptup;
    3328       310910 :     HeapTuple   old_key_tuple = NULL;
    3329       310910 :     bool        old_key_copied = false;
    3330              :     Page        page;
    3331              :     BlockNumber block;
    3332              :     MultiXactStatus mxact_status;
    3333              :     Buffer      buffer,
    3334              :                 newbuf,
    3335       310910 :                 vmbuffer = InvalidBuffer,
    3336       310910 :                 vmbuffer_new = InvalidBuffer;
    3337              :     bool        need_toast;
    3338              :     Size        newtupsize,
    3339              :                 pagefree;
    3340       310910 :     bool        have_tuple_lock = false;
    3341              :     bool        iscombo;
    3342       310910 :     bool        use_hot_update = false;
    3343       310910 :     bool        summarized_update = false;
    3344              :     bool        key_intact;
    3345       310910 :     bool        all_visible_cleared = false;
    3346       310910 :     bool        all_visible_cleared_new = false;
    3347              :     bool        checked_lockers;
    3348              :     bool        locker_remains;
    3349       310910 :     bool        id_has_external = false;
    3350              :     TransactionId xmax_new_tuple,
    3351              :                 xmax_old_tuple;
    3352              :     uint16      infomask_old_tuple,
    3353              :                 infomask2_old_tuple,
    3354              :                 infomask_new_tuple,
    3355              :                 infomask2_new_tuple;
    3356              : 
    3357              :     Assert(ItemPointerIsValid(otid));
    3358              : 
    3359              :     /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
    3360              :     Assert(HeapTupleHeaderGetNatts(newtup->t_data) <=
    3361              :            RelationGetNumberOfAttributes(relation));
    3362              : 
    3363       310910 :     AssertHasSnapshotForToast(relation);
    3364              : 
    3365              :     /*
    3366              :      * Forbid this during a parallel operation, lest it allocate a combo CID.
    3367              :      * Other workers might need that combo CID for visibility checks, and we
    3368              :      * have no provision for broadcasting it to them.
    3369              :      */
    3370       310910 :     if (IsInParallelMode())
    3371            0 :         ereport(ERROR,
    3372              :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
    3373              :                  errmsg("cannot update tuples during a parallel operation")));
    3374              : 
    3375              : #ifdef USE_ASSERT_CHECKING
    3376              :     check_lock_if_inplace_updateable_rel(relation, otid, newtup);
    3377              : #endif
    3378              : 
    3379              :     /*
    3380              :      * Fetch the list of attributes to be checked for various operations.
    3381              :      *
    3382              :      * For HOT considerations, this is wasted effort if we fail to update or
    3383              :      * have to put the new tuple on a different page.  But we must compute the
    3384              :      * list before obtaining buffer lock --- in the worst case, if we are
    3385              :      * doing an update on one of the relevant system catalogs, we could
    3386              :      * deadlock if we try to fetch the list later.  In any case, the relcache
    3387              :      * caches the data so this is usually pretty cheap.
    3388              :      *
    3389              :      * We also need columns used by the replica identity and columns that are
    3390              :      * considered the "key" of rows in the table.
    3391              :      *
    3392              :      * Note that we get copies of each bitmap, so we need not worry about
    3393              :      * relcache flush happening midway through.
    3394              :      */
    3395       310910 :     hot_attrs = RelationGetIndexAttrBitmap(relation,
    3396              :                                            INDEX_ATTR_BITMAP_HOT_BLOCKING);
    3397       310910 :     sum_attrs = RelationGetIndexAttrBitmap(relation,
    3398              :                                            INDEX_ATTR_BITMAP_SUMMARIZED);
    3399       310910 :     key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
    3400       310910 :     id_attrs = RelationGetIndexAttrBitmap(relation,
    3401              :                                           INDEX_ATTR_BITMAP_IDENTITY_KEY);
    3402       310910 :     interesting_attrs = NULL;
    3403       310910 :     interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
    3404       310910 :     interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
    3405       310910 :     interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
    3406       310910 :     interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
    3407              : 
    3408       310910 :     block = ItemPointerGetBlockNumber(otid);
    3409       310910 :     INJECTION_POINT("heap_update-before-pin", NULL);
    3410       310910 :     buffer = ReadBuffer(relation, block);
    3411       310910 :     page = BufferGetPage(buffer);
    3412              : 
    3413              :     /*
    3414              :      * Before locking the buffer, pin the visibility map page if it appears to
    3415              :      * be necessary.  Since we haven't got the lock yet, someone else might be
    3416              :      * in the middle of changing this, so we'll need to recheck after we have
    3417              :      * the lock.
    3418              :      */
    3419       310910 :     if (PageIsAllVisible(page))
    3420         1604 :         visibilitymap_pin(relation, block, &vmbuffer);
    3421              : 
    3422       310910 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    3423              : 
    3424       310910 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
    3425              : 
    3426              :     /*
    3427              :      * Usually, a buffer pin and/or snapshot blocks pruning of otid, ensuring
    3428              :      * we see LP_NORMAL here.  When the otid origin is a syscache, we may have
    3429              :      * neither a pin nor a snapshot.  Hence, we may see other LP_ states, each
    3430              :      * of which indicates concurrent pruning.
    3431              :      *
    3432              :      * Failing with TM_Updated would be most accurate.  However, unlike other
    3433              :      * TM_Updated scenarios, we don't know the successor ctid in LP_UNUSED and
    3434              :      * LP_DEAD cases.  While the distinction between TM_Updated and TM_Deleted
    3435              :      * does matter to SQL statements UPDATE and MERGE, those SQL statements
    3436              :      * hold a snapshot that ensures LP_NORMAL.  Hence, the choice between
    3437              :      * TM_Updated and TM_Deleted affects only the wording of error messages.
    3438              :      * Settle on TM_Deleted, for two reasons.  First, it avoids complicating
    3439              :      * the specification of when tmfd->ctid is valid.  Second, it creates
    3440              :      * error log evidence that we took this branch.
    3441              :      *
    3442              :      * Since it's possible to see LP_UNUSED at otid, it's also possible to see
    3443              :      * LP_NORMAL for a tuple that replaced LP_UNUSED.  If it's a tuple for an
    3444              :      * unrelated row, we'll fail with "duplicate key value violates unique".
    3445              :      * XXX if otid is the live, newer version of the newtup row, we'll discard
    3446              :      * changes originating in versions of this catalog row after the version
    3447              :      * the caller got from syscache.  See syscache-update-pruned.spec.
    3448              :      */
    3449       310910 :     if (!ItemIdIsNormal(lp))
    3450              :     {
    3451              :         Assert(RelationSupportsSysCache(RelationGetRelid(relation)));
    3452              : 
    3453            1 :         UnlockReleaseBuffer(buffer);
    3454              :         Assert(!have_tuple_lock);
    3455            1 :         if (vmbuffer != InvalidBuffer)
    3456            1 :             ReleaseBuffer(vmbuffer);
    3457            1 :         tmfd->ctid = *otid;
    3458            1 :         tmfd->xmax = InvalidTransactionId;
    3459            1 :         tmfd->cmax = InvalidCommandId;
    3460            1 :         *update_indexes = TU_None;
    3461              : 
    3462            1 :         bms_free(hot_attrs);
    3463            1 :         bms_free(sum_attrs);
    3464            1 :         bms_free(key_attrs);
    3465            1 :         bms_free(id_attrs);
    3466              :         /* modified_attrs not yet initialized */
    3467            1 :         bms_free(interesting_attrs);
    3468            1 :         return TM_Deleted;
    3469              :     }
    3470              : 
    3471              :     /*
    3472              :      * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
    3473              :      * properly.
    3474              :      */
    3475       310909 :     oldtup.t_tableOid = RelationGetRelid(relation);
    3476       310909 :     oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
    3477       310909 :     oldtup.t_len = ItemIdGetLength(lp);
    3478       310909 :     oldtup.t_self = *otid;
    3479              : 
    3480              :     /* the new tuple is ready, except for this: */
    3481       310909 :     newtup->t_tableOid = RelationGetRelid(relation);
    3482              : 
    3483              :     /*
    3484              :      * Determine columns modified by the update.  Additionally, identify
    3485              :      * whether any of the unmodified replica identity key attributes in the
    3486              :      * old tuple is externally stored or not.  This is required because for
    3487              :      * such attributes the flattened value won't be WAL logged as part of the
    3488              :      * new tuple so we must include it as part of the old_key_tuple.  See
    3489              :      * ExtractReplicaIdentity.
    3490              :      */
    3491       310909 :     modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
    3492              :                                               id_attrs, &oldtup,
    3493              :                                               newtup, &id_has_external);
    3494              : 
    3495              :     /*
    3496              :      * If we're not updating any "key" column, we can grab a weaker lock type.
    3497              :      * This allows for more concurrency when we are running simultaneously
    3498              :      * with foreign key checks.
    3499              :      *
    3500              :      * Note that if a column gets detoasted while executing the update, but
    3501              :      * the value ends up being the same, this test will fail and we will use
    3502              :      * the stronger lock.  This is acceptable; the important case to optimize
    3503              :      * is updates that don't manipulate key columns, not those that
    3504              :      * serendipitously arrive at the same key values.
    3505              :      */
    3506       310909 :     if (!bms_overlap(modified_attrs, key_attrs))
    3507              :     {
    3508       306586 :         *lockmode = LockTupleNoKeyExclusive;
    3509       306586 :         mxact_status = MultiXactStatusNoKeyUpdate;
    3510       306586 :         key_intact = true;
    3511              : 
    3512              :         /*
    3513              :          * If this is the first possibly-multixact-able operation in the
    3514              :          * current transaction, set my per-backend OldestMemberMXactId
    3515              :          * setting. We can be certain that the transaction will never become a
    3516              :          * member of any older MultiXactIds than that.  (We have to do this
    3517              :          * even if we end up just using our own TransactionId below, since
    3518              :          * some other backend could incorporate our XID into a MultiXact
    3519              :          * immediately afterwards.)
    3520              :          */
    3521       306586 :         MultiXactIdSetOldestMember();
    3522              :     }
    3523              :     else
    3524              :     {
    3525         4323 :         *lockmode = LockTupleExclusive;
    3526         4323 :         mxact_status = MultiXactStatusUpdate;
    3527         4323 :         key_intact = false;
    3528              :     }
    3529              : 
    3530              :     /*
    3531              :      * Note: beyond this point, use oldtup not otid to refer to old tuple.
    3532              :      * otid may very well point at newtup->t_self, which we will overwrite
    3533              :      * with the new tuple's location, so there's great risk of confusion if we
    3534              :      * use otid anymore.
    3535              :      */
    3536              : 
    3537            1 : l2:
    3538       310910 :     checked_lockers = false;
    3539       310910 :     locker_remains = false;
    3540       310910 :     result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
    3541              : 
    3542              :     /* see below about the "no wait" case */
    3543              :     Assert(result != TM_BeingModified || wait);
    3544              : 
    3545       310910 :     if (result == TM_Invisible)
    3546              :     {
    3547            0 :         UnlockReleaseBuffer(buffer);
    3548            0 :         ereport(ERROR,
    3549              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3550              :                  errmsg("attempted to update invisible tuple")));
    3551              :     }
    3552       310910 :     else if (result == TM_BeingModified && wait)
    3553              :     {
    3554              :         TransactionId xwait;
    3555              :         uint16      infomask;
    3556        36111 :         bool        can_continue = false;
    3557              : 
    3558              :         /*
    3559              :          * XXX note that we don't consider the "no wait" case here.  This
    3560              :          * isn't a problem currently because no caller uses that case, but it
    3561              :          * should be fixed if such a caller is introduced.  It wasn't a
    3562              :          * problem previously because this code would always wait, but now
    3563              :          * that some tuple locks do not conflict with one of the lock modes we
    3564              :          * use, it is possible that this case is interesting to handle
    3565              :          * specially.
    3566              :          *
    3567              :          * This may cause failures with third-party code that calls
    3568              :          * heap_update directly.
    3569              :          */
    3570              : 
    3571              :         /* must copy state data before unlocking buffer */
    3572        36111 :         xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
    3573        36111 :         infomask = oldtup.t_data->t_infomask;
    3574              : 
    3575              :         /*
    3576              :          * Now we have to do something about the existing locker.  If it's a
    3577              :          * multi, sleep on it; we might be awakened before it is completely
    3578              :          * gone (or even not sleep at all in some cases); we need to preserve
    3579              :          * it as locker, unless it is gone completely.
    3580              :          *
    3581              :          * If it's not a multi, we need to check for sleeping conditions
    3582              :          * before actually going to sleep.  If the update doesn't conflict
    3583              :          * with the locks, we just continue without sleeping (but making sure
    3584              :          * it is preserved).
    3585              :          *
    3586              :          * Before sleeping, we need to acquire tuple lock to establish our
    3587              :          * priority for the tuple (see heap_lock_tuple).  LockTuple will
    3588              :          * release us when we are next-in-line for the tuple.  Note we must
    3589              :          * not acquire the tuple lock until we're sure we're going to sleep;
    3590              :          * otherwise we're open for race conditions with other transactions
    3591              :          * holding the tuple lock which sleep on us.
    3592              :          *
    3593              :          * If we are forced to "start over" below, we keep the tuple lock;
    3594              :          * this arranges that we stay at the head of the line while rechecking
    3595              :          * tuple state.
    3596              :          */
    3597        36111 :         if (infomask & HEAP_XMAX_IS_MULTI)
    3598              :         {
    3599              :             TransactionId update_xact;
    3600              :             int         remain;
    3601          179 :             bool        current_is_member = false;
    3602              : 
    3603          179 :             if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
    3604              :                                         *lockmode, &current_is_member))
    3605              :             {
    3606            8 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    3607              : 
    3608              :                 /*
    3609              :                  * Acquire the lock, if necessary (but skip it when we're
    3610              :                  * requesting a lock and already have one; avoids deadlock).
    3611              :                  */
    3612            8 :                 if (!current_is_member)
    3613            0 :                     heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
    3614              :                                          LockWaitBlock, &have_tuple_lock);
    3615              : 
    3616              :                 /* wait for multixact */
    3617            8 :                 MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
    3618              :                                 relation, &oldtup.t_self, XLTW_Update,
    3619              :                                 &remain);
    3620            8 :                 checked_lockers = true;
    3621            8 :                 locker_remains = remain != 0;
    3622            8 :                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    3623              : 
    3624              :                 /*
    3625              :                  * If xwait had just locked the tuple then some other xact
    3626              :                  * could update this tuple before we get to this point.  Check
    3627              :                  * for xmax change, and start over if so.
    3628              :                  */
    3629            8 :                 if (xmax_infomask_changed(oldtup.t_data->t_infomask,
    3630            8 :                                           infomask) ||
    3631            8 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
    3632              :                                          xwait))
    3633            0 :                     goto l2;
    3634              :             }
    3635              : 
    3636              :             /*
    3637              :              * Note that the multixact may not be done by now.  It could have
    3638              :              * surviving members; our own xact or other subxacts of this
    3639              :              * backend, and also any other concurrent transaction that locked
    3640              :              * the tuple with LockTupleKeyShare if we only got
    3641              :              * LockTupleNoKeyExclusive.  If this is the case, we have to be
    3642              :              * careful to mark the updated tuple with the surviving members in
    3643              :              * Xmax.
    3644              :              *
    3645              :              * Note that there could have been another update in the
    3646              :              * MultiXact. In that case, we need to check whether it committed
    3647              :              * or aborted. If it aborted we are safe to update it again;
    3648              :              * otherwise there is an update conflict, and we have to return
    3649              :              * TableTuple{Deleted, Updated} below.
    3650              :              *
    3651              :              * In the LockTupleExclusive case, we still need to preserve the
    3652              :              * surviving members: those would include the tuple locks we had
    3653              :              * before this one, which are important to keep in case this
    3654              :              * subxact aborts.
    3655              :              */
    3656          179 :             if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
    3657            8 :                 update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
    3658              :             else
    3659          171 :                 update_xact = InvalidTransactionId;
    3660              : 
    3661              :             /*
    3662              :              * There was no UPDATE in the MultiXact; or it aborted. No
    3663              :              * TransactionIdIsInProgress() call needed here, since we called
    3664              :              * MultiXactIdWait() above.
    3665              :              */
    3666          187 :             if (!TransactionIdIsValid(update_xact) ||
    3667            8 :                 TransactionIdDidAbort(update_xact))
    3668          172 :                 can_continue = true;
    3669              :         }
    3670        35932 :         else if (TransactionIdIsCurrentTransactionId(xwait))
    3671              :         {
    3672              :             /*
    3673              :              * The only locker is ourselves; we can avoid grabbing the tuple
    3674              :              * lock here, but must preserve our locking information.
    3675              :              */
    3676        35823 :             checked_lockers = true;
    3677        35823 :             locker_remains = true;
    3678        35823 :             can_continue = true;
    3679              :         }
    3680          109 :         else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
    3681              :         {
    3682              :             /*
    3683              :              * If it's just a key-share locker, and we're not changing the key
    3684              :              * columns, we don't need to wait for it to end; but we need to
    3685              :              * preserve it as locker.
    3686              :              */
    3687           29 :             checked_lockers = true;
    3688           29 :             locker_remains = true;
    3689           29 :             can_continue = true;
    3690              :         }
    3691              :         else
    3692              :         {
    3693              :             /*
    3694              :              * Wait for regular transaction to end; but first, acquire tuple
    3695              :              * lock.
    3696              :              */
    3697           80 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    3698           80 :             heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
    3699              :                                  LockWaitBlock, &have_tuple_lock);
    3700           80 :             XactLockTableWait(xwait, relation, &oldtup.t_self,
    3701              :                               XLTW_Update);
    3702           80 :             checked_lockers = true;
    3703           80 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    3704              : 
    3705              :             /*
    3706              :              * xwait is done, but if xwait had just locked the tuple then some
    3707              :              * other xact could update this tuple before we get to this point.
    3708              :              * Check for xmax change, and start over if so.
    3709              :              */
    3710          159 :             if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
    3711           79 :                 !TransactionIdEquals(xwait,
    3712              :                                      HeapTupleHeaderGetRawXmax(oldtup.t_data)))
    3713            1 :                 goto l2;
    3714              : 
    3715              :             /* Otherwise check if it committed or aborted */
    3716           79 :             UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
    3717           79 :             if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
    3718           22 :                 can_continue = true;
    3719              :         }
    3720              : 
    3721        36110 :         if (can_continue)
    3722        36046 :             result = TM_Ok;
    3723           64 :         else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
    3724           59 :             result = TM_Updated;
    3725              :         else
    3726            5 :             result = TM_Deleted;
    3727              :     }
    3728              : 
    3729              :     /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
    3730              :     if (result != TM_Ok)
    3731              :     {
    3732              :         Assert(result == TM_SelfModified ||
    3733              :                result == TM_Updated ||
    3734              :                result == TM_Deleted ||
    3735              :                result == TM_BeingModified);
    3736              :         Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
    3737              :         Assert(result != TM_Updated ||
    3738              :                !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
    3739              :     }
    3740              : 
    3741       310909 :     if (crosscheck != InvalidSnapshot && result == TM_Ok)
    3742              :     {
    3743              :         /* Perform additional check for transaction-snapshot mode RI updates */
    3744            1 :         if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
    3745            1 :             result = TM_Updated;
    3746              :     }
    3747              : 
    3748       310909 :     if (result != TM_Ok)
    3749              :     {
    3750          162 :         tmfd->ctid = oldtup.t_data->t_ctid;
    3751          162 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
    3752          162 :         if (result == TM_SelfModified)
    3753           52 :             tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
    3754              :         else
    3755          110 :             tmfd->cmax = InvalidCommandId;
    3756          162 :         UnlockReleaseBuffer(buffer);
    3757          162 :         if (have_tuple_lock)
    3758           57 :             UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
    3759          162 :         if (vmbuffer != InvalidBuffer)
    3760            0 :             ReleaseBuffer(vmbuffer);
    3761          162 :         *update_indexes = TU_None;
    3762              : 
    3763          162 :         bms_free(hot_attrs);
    3764          162 :         bms_free(sum_attrs);
    3765          162 :         bms_free(key_attrs);
    3766          162 :         bms_free(id_attrs);
    3767          162 :         bms_free(modified_attrs);
    3768          162 :         bms_free(interesting_attrs);
    3769          162 :         return result;
    3770              :     }
    3771              : 
    3772              :     /*
    3773              :      * If we didn't pin the visibility map page and the page has become all
    3774              :      * visible while we were busy locking the buffer, or during some
    3775              :      * subsequent window during which we had it unlocked, we'll have to unlock
    3776              :      * and re-lock, to avoid holding the buffer lock across an I/O.  That's a
    3777              :      * bit unfortunate, especially since we'll now have to recheck whether the
    3778              :      * tuple has been locked or updated under us, but hopefully it won't
    3779              :      * happen very often.
    3780              :      */
    3781       310747 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
    3782              :     {
    3783            0 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    3784            0 :         visibilitymap_pin(relation, block, &vmbuffer);
    3785            0 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    3786            0 :         goto l2;
    3787              :     }
    3788              : 
    3789              :     /* Fill in transaction status data */
    3790              : 
    3791              :     /*
    3792              :      * If the tuple we're updating is locked, we need to preserve the locking
    3793              :      * info in the old tuple's Xmax.  Prepare a new Xmax value for this.
    3794              :      */
    3795       310747 :     compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
    3796       310747 :                               oldtup.t_data->t_infomask,
    3797       310747 :                               oldtup.t_data->t_infomask2,
    3798              :                               xid, *lockmode, true,
    3799              :                               &xmax_old_tuple, &infomask_old_tuple,
    3800              :                               &infomask2_old_tuple);
    3801              : 
    3802              :     /*
    3803              :      * And also prepare an Xmax value for the new copy of the tuple.  If there
    3804              :      * was no xmax previously, or there was one but all lockers are now gone,
    3805              :      * then use InvalidTransactionId; otherwise, get the xmax from the old
    3806              :      * tuple.  (In rare cases that might also be InvalidTransactionId and yet
    3807              :      * not have the HEAP_XMAX_INVALID bit set; that's fine.)
    3808              :      */
    3809       346771 :     if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
    3810        72048 :         HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
    3811        35853 :         (checked_lockers && !locker_remains))
    3812       274723 :         xmax_new_tuple = InvalidTransactionId;
    3813              :     else
    3814        36024 :         xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
    3815              : 
    3816       310747 :     if (!TransactionIdIsValid(xmax_new_tuple))
    3817              :     {
    3818       274723 :         infomask_new_tuple = HEAP_XMAX_INVALID;
    3819       274723 :         infomask2_new_tuple = 0;
    3820              :     }
    3821              :     else
    3822              :     {
    3823              :         /*
    3824              :          * If we found a valid Xmax for the new tuple, then the infomask bits
    3825              :          * to use on the new tuple depend on what was there on the old one.
    3826              :          * Note that since we're doing an update, the only possibility is that
    3827              :          * the lockers had FOR KEY SHARE lock.
    3828              :          */
    3829        36024 :         if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
    3830              :         {
    3831          172 :             GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
    3832              :                                    &infomask2_new_tuple);
    3833              :         }
    3834              :         else
    3835              :         {
    3836        35852 :             infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
    3837        35852 :             infomask2_new_tuple = 0;
    3838              :         }
    3839              :     }
    3840              : 
    3841              :     /*
    3842              :      * Prepare the new tuple with the appropriate initial values of Xmin and
    3843              :      * Xmax, as well as initial infomask bits as computed above.
    3844              :      */
    3845       310747 :     newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
    3846       310747 :     newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
    3847       310747 :     HeapTupleHeaderSetXmin(newtup->t_data, xid);
    3848       310747 :     HeapTupleHeaderSetCmin(newtup->t_data, cid);
    3849       310747 :     newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
    3850       310747 :     newtup->t_data->t_infomask2 |= infomask2_new_tuple;
    3851       310747 :     HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
    3852              : 
    3853              :     /*
    3854              :      * Replace cid with a combo CID if necessary.  Note that we already put
    3855              :      * the plain cid into the new tuple.
    3856              :      */
    3857       310747 :     HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
    3858              : 
    3859              :     /*
    3860              :      * If the toaster needs to be activated, OR if the new tuple will not fit
    3861              :      * on the same page as the old, then we need to release the content lock
    3862              :      * (but not the pin!) on the old tuple's buffer while we are off doing
    3863              :      * TOAST and/or table-file-extension work.  We must mark the old tuple to
    3864              :      * show that it's locked, else other processes may try to update it
    3865              :      * themselves.
    3866              :      *
    3867              :      * We need to invoke the toaster if there are already any out-of-line
    3868              :      * toasted values present, or if the new tuple is over-threshold.
    3869              :      */
    3870       310747 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
    3871            0 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
    3872              :     {
    3873              :         /* toast table entries should never be recursively toasted */
    3874              :         Assert(!HeapTupleHasExternal(&oldtup));
    3875              :         Assert(!HeapTupleHasExternal(newtup));
    3876            0 :         need_toast = false;
    3877              :     }
    3878              :     else
    3879       931852 :         need_toast = (HeapTupleHasExternal(&oldtup) ||
    3880       621105 :                       HeapTupleHasExternal(newtup) ||
    3881       310334 :                       newtup->t_len > TOAST_TUPLE_THRESHOLD);
    3882              : 
    3883       310747 :     pagefree = PageGetHeapFreeSpace(page);
    3884              : 
    3885       310747 :     newtupsize = MAXALIGN(newtup->t_len);
    3886              : 
    3887       310747 :     if (need_toast || newtupsize > pagefree)
    3888       150781 :     {
    3889              :         TransactionId xmax_lock_old_tuple;
    3890              :         uint16      infomask_lock_old_tuple,
    3891              :                     infomask2_lock_old_tuple;
    3892       150781 :         bool        cleared_all_frozen = false;
    3893              : 
    3894              :         /*
    3895              :          * To prevent concurrent sessions from updating the tuple, we have to
    3896              :          * temporarily mark it locked, while we release the page-level lock.
    3897              :          *
    3898              :          * To satisfy the rule that any xid potentially appearing in a buffer
    3899              :          * written out to disk, we unfortunately have to WAL log this
    3900              :          * temporary modification.  We can reuse xl_heap_lock for this
    3901              :          * purpose.  If we crash/error before following through with the
    3902              :          * actual update, xmax will be of an aborted transaction, allowing
    3903              :          * other sessions to proceed.
    3904              :          */
    3905              : 
    3906              :         /*
    3907              :          * Compute xmax / infomask appropriate for locking the tuple. This has
    3908              :          * to be done separately from the combo that's going to be used for
    3909              :          * updating, because the potentially created multixact would otherwise
    3910              :          * be wrong.
    3911              :          */
    3912       150781 :         compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
    3913       150781 :                                   oldtup.t_data->t_infomask,
    3914       150781 :                                   oldtup.t_data->t_infomask2,
    3915              :                                   xid, *lockmode, false,
    3916              :                                   &xmax_lock_old_tuple, &infomask_lock_old_tuple,
    3917              :                                   &infomask2_lock_old_tuple);
    3918              : 
    3919              :         Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
    3920              : 
    3921       150781 :         START_CRIT_SECTION();
    3922              : 
    3923              :         /* Clear obsolete visibility flags ... */
    3924       150781 :         oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
    3925       150781 :         oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
    3926       150781 :         HeapTupleClearHotUpdated(&oldtup);
    3927              :         /* ... and store info about transaction updating this tuple */
    3928              :         Assert(TransactionIdIsValid(xmax_lock_old_tuple));
    3929       150781 :         HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
    3930       150781 :         oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
    3931       150781 :         oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
    3932       150781 :         HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
    3933              : 
    3934              :         /* temporarily make it look not-updated, but locked */
    3935       150781 :         oldtup.t_data->t_ctid = oldtup.t_self;
    3936              : 
    3937              :         /*
    3938              :          * Clear all-frozen bit on visibility map if needed. We could
    3939              :          * immediately reset ALL_VISIBLE, but given that the WAL logging
    3940              :          * overhead would be unchanged, that doesn't seem necessarily
    3941              :          * worthwhile.
    3942              :          */
    3943       151760 :         if (PageIsAllVisible(page) &&
    3944          979 :             visibilitymap_clear(relation, block, vmbuffer,
    3945              :                                 VISIBILITYMAP_ALL_FROZEN))
    3946          815 :             cleared_all_frozen = true;
    3947              : 
    3948       150781 :         MarkBufferDirty(buffer);
    3949              : 
    3950       150781 :         if (RelationNeedsWAL(relation))
    3951              :         {
    3952              :             xl_heap_lock xlrec;
    3953              :             XLogRecPtr  recptr;
    3954              : 
    3955       140652 :             XLogBeginInsert();
    3956       140652 :             XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
    3957              : 
    3958       140652 :             xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
    3959       140652 :             xlrec.xmax = xmax_lock_old_tuple;
    3960       281304 :             xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
    3961       140652 :                                                   oldtup.t_data->t_infomask2);
    3962       140652 :             xlrec.flags =
    3963       140652 :                 cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
    3964       140652 :             XLogRegisterData(&xlrec, SizeOfHeapLock);
    3965       140652 :             recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
    3966       140652 :             PageSetLSN(page, recptr);
    3967              :         }
    3968              : 
    3969       150781 :         END_CRIT_SECTION();
    3970              : 
    3971       150781 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    3972              : 
    3973              :         /*
    3974              :          * Let the toaster do its thing, if needed.
    3975              :          *
    3976              :          * Note: below this point, heaptup is the data we actually intend to
    3977              :          * store into the relation; newtup is the caller's original untoasted
    3978              :          * data.
    3979              :          */
    3980       150781 :         if (need_toast)
    3981              :         {
    3982              :             /* Note we always use WAL and FSM during updates */
    3983         1710 :             heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
    3984         1710 :             newtupsize = MAXALIGN(heaptup->t_len);
    3985              :         }
    3986              :         else
    3987       149071 :             heaptup = newtup;
    3988              : 
    3989              :         /*
    3990              :          * Now, do we need a new page for the tuple, or not?  This is a bit
    3991              :          * tricky since someone else could have added tuples to the page while
    3992              :          * we weren't looking.  We have to recheck the available space after
    3993              :          * reacquiring the buffer lock.  But don't bother to do that if the
    3994              :          * former amount of free space is still not enough; it's unlikely
    3995              :          * there's more free now than before.
    3996              :          *
    3997              :          * What's more, if we need to get a new page, we will need to acquire
    3998              :          * buffer locks on both old and new pages.  To avoid deadlock against
    3999              :          * some other backend trying to get the same two locks in the other
    4000              :          * order, we must be consistent about the order we get the locks in.
    4001              :          * We use the rule "lock the lower-numbered page of the relation
    4002              :          * first".  To implement this, we must do RelationGetBufferForTuple
    4003              :          * while not holding the lock on the old page, and we must rely on it
    4004              :          * to get the locks on both pages in the correct order.
    4005              :          *
    4006              :          * Another consideration is that we need visibility map page pin(s) if
    4007              :          * we will have to clear the all-visible flag on either page.  If we
    4008              :          * call RelationGetBufferForTuple, we rely on it to acquire any such
    4009              :          * pins; but if we don't, we have to handle that here.  Hence we need
    4010              :          * a loop.
    4011              :          */
    4012              :         for (;;)
    4013              :         {
    4014       150781 :             if (newtupsize > pagefree)
    4015              :             {
    4016              :                 /* It doesn't fit, must use RelationGetBufferForTuple. */
    4017       150217 :                 newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
    4018              :                                                    buffer, 0, NULL,
    4019              :                                                    &vmbuffer_new, &vmbuffer,
    4020              :                                                    0);
    4021              :                 /* We're all done. */
    4022       150217 :                 break;
    4023              :             }
    4024              :             /* Acquire VM page pin if needed and we don't have it. */
    4025          564 :             if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
    4026            0 :                 visibilitymap_pin(relation, block, &vmbuffer);
    4027              :             /* Re-acquire the lock on the old tuple's page. */
    4028          564 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    4029              :             /* Re-check using the up-to-date free space */
    4030          564 :             pagefree = PageGetHeapFreeSpace(page);
    4031          564 :             if (newtupsize > pagefree ||
    4032          564 :                 (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
    4033              :             {
    4034              :                 /*
    4035              :                  * Rats, it doesn't fit anymore, or somebody just now set the
    4036              :                  * all-visible flag.  We must now unlock and loop to avoid
    4037              :                  * deadlock.  Fortunately, this path should seldom be taken.
    4038              :                  */
    4039            0 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    4040              :             }
    4041              :             else
    4042              :             {
    4043              :                 /* We're all done. */
    4044          564 :                 newbuf = buffer;
    4045          564 :                 break;
    4046              :             }
    4047              :         }
    4048              :     }
    4049              :     else
    4050              :     {
    4051              :         /* No TOAST work needed, and it'll fit on same page */
    4052       159966 :         newbuf = buffer;
    4053       159966 :         heaptup = newtup;
    4054              :     }
    4055              : 
    4056              :     /*
    4057              :      * We're about to do the actual update -- check for conflict first, to
    4058              :      * avoid possibly having to roll back work we've just done.
    4059              :      *
    4060              :      * This is safe without a recheck as long as there is no possibility of
    4061              :      * another process scanning the pages between this check and the update
    4062              :      * being visible to the scan (i.e., exclusive buffer content lock(s) are
    4063              :      * continuously held from this point until the tuple update is visible).
    4064              :      *
    4065              :      * For the new tuple the only check needed is at the relation level, but
    4066              :      * since both tuples are in the same relation and the check for oldtup
    4067              :      * will include checking the relation level, there is no benefit to a
    4068              :      * separate check for the new tuple.
    4069              :      */
    4070       310747 :     CheckForSerializableConflictIn(relation, &oldtup.t_self,
    4071              :                                    BufferGetBlockNumber(buffer));
    4072              : 
    4073              :     /*
    4074              :      * At this point newbuf and buffer are both pinned and locked, and newbuf
    4075              :      * has enough space for the new tuple.  If they are the same buffer, only
    4076              :      * one pin is held.
    4077              :      */
    4078              : 
    4079       310735 :     if (newbuf == buffer)
    4080              :     {
    4081              :         /*
    4082              :          * Since the new tuple is going into the same page, we might be able
    4083              :          * to do a HOT update.  Check if any of the index columns have been
    4084              :          * changed.
    4085              :          */
    4086       160518 :         if (!bms_overlap(modified_attrs, hot_attrs))
    4087              :         {
    4088       148123 :             use_hot_update = true;
    4089              : 
    4090              :             /*
    4091              :              * If none of the columns that are used in hot-blocking indexes
    4092              :              * were updated, we can apply HOT, but we do still need to check
    4093              :              * if we need to update the summarizing indexes, and update those
    4094              :              * indexes if the columns were updated, or we may fail to detect
    4095              :              * e.g. value bound changes in BRIN minmax indexes.
    4096              :              */
    4097       148123 :             if (bms_overlap(modified_attrs, sum_attrs))
    4098         1641 :                 summarized_update = true;
    4099              :         }
    4100              :     }
    4101              :     else
    4102              :     {
    4103              :         /* Set a hint that the old page could use prune/defrag */
    4104       150217 :         PageSetFull(page);
    4105              :     }
    4106              : 
    4107              :     /*
    4108              :      * Compute replica identity tuple before entering the critical section so
    4109              :      * we don't PANIC upon a memory allocation failure.
    4110              :      * ExtractReplicaIdentity() will return NULL if nothing needs to be
    4111              :      * logged.  Pass old key required as true only if the replica identity key
    4112              :      * columns are modified or it has external data.
    4113              :      */
    4114       310735 :     old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
    4115       310735 :                                            bms_overlap(modified_attrs, id_attrs) ||
    4116              :                                            id_has_external,
    4117       310735 :                                            &old_key_copied);
    4118              : 
    4119              :     /* NO EREPORT(ERROR) from here till changes are logged */
    4120       310735 :     START_CRIT_SECTION();
    4121              : 
    4122              :     /*
    4123              :      * If this transaction commits, the old tuple will become DEAD sooner or
    4124              :      * later.  Set flag that this page is a candidate for pruning once our xid
    4125              :      * falls below the OldestXmin horizon.  If the transaction finally aborts,
    4126              :      * the subsequent page pruning will be a no-op and the hint will be
    4127              :      * cleared.
    4128              :      *
    4129              :      * XXX Should we set hint on newbuf as well?  If the transaction aborts,
    4130              :      * there would be a prunable tuple in the newbuf; but for now we choose
    4131              :      * not to optimize for aborts.  Note that heap_xlog_update must be kept in
    4132              :      * sync if this decision changes.
    4133              :      */
    4134       310735 :     PageSetPrunable(page, xid);
    4135              : 
    4136       310735 :     if (use_hot_update)
    4137              :     {
    4138              :         /* Mark the old tuple as HOT-updated */
    4139       148123 :         HeapTupleSetHotUpdated(&oldtup);
    4140              :         /* And mark the new tuple as heap-only */
    4141       148123 :         HeapTupleSetHeapOnly(heaptup);
    4142              :         /* Mark the caller's copy too, in case different from heaptup */
    4143       148123 :         HeapTupleSetHeapOnly(newtup);
    4144              :     }
    4145              :     else
    4146              :     {
    4147              :         /* Make sure tuples are correctly marked as not-HOT */
    4148       162612 :         HeapTupleClearHotUpdated(&oldtup);
    4149       162612 :         HeapTupleClearHeapOnly(heaptup);
    4150       162612 :         HeapTupleClearHeapOnly(newtup);
    4151              :     }
    4152              : 
    4153       310735 :     RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
    4154              : 
    4155              : 
    4156              :     /* Clear obsolete visibility flags, possibly set by ourselves above... */
    4157       310735 :     oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
    4158       310735 :     oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
    4159              :     /* ... and store info about transaction updating this tuple */
    4160              :     Assert(TransactionIdIsValid(xmax_old_tuple));
    4161       310735 :     HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
    4162       310735 :     oldtup.t_data->t_infomask |= infomask_old_tuple;
    4163       310735 :     oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
    4164       310735 :     HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
    4165              : 
    4166              :     /* record address of new tuple in t_ctid of old one */
    4167       310735 :     oldtup.t_data->t_ctid = heaptup->t_self;
    4168              : 
    4169              :     /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
    4170       310735 :     if (PageIsAllVisible(BufferGetPage(buffer)))
    4171              :     {
    4172         1603 :         all_visible_cleared = true;
    4173         1603 :         PageClearAllVisible(BufferGetPage(buffer));
    4174         1603 :         visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
    4175              :                             vmbuffer, VISIBILITYMAP_VALID_BITS);
    4176              :     }
    4177       310735 :     if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
    4178              :     {
    4179          926 :         all_visible_cleared_new = true;
    4180          926 :         PageClearAllVisible(BufferGetPage(newbuf));
    4181          926 :         visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
    4182              :                             vmbuffer_new, VISIBILITYMAP_VALID_BITS);
    4183              :     }
    4184              : 
    4185       310735 :     if (newbuf != buffer)
    4186       150217 :         MarkBufferDirty(newbuf);
    4187       310735 :     MarkBufferDirty(buffer);
    4188              : 
    4189              :     /* XLOG stuff */
    4190       310735 :     if (RelationNeedsWAL(relation))
    4191              :     {
    4192              :         XLogRecPtr  recptr;
    4193              : 
    4194              :         /*
    4195              :          * For logical decoding we need combo CIDs to properly decode the
    4196              :          * catalog.
    4197              :          */
    4198       299371 :         if (RelationIsAccessibleInLogicalDecoding(relation))
    4199              :         {
    4200         2568 :             log_heap_new_cid(relation, &oldtup);
    4201         2568 :             log_heap_new_cid(relation, heaptup);
    4202              :         }
    4203              : 
    4204       299371 :         recptr = log_heap_update(relation, buffer,
    4205              :                                  newbuf, &oldtup, heaptup,
    4206              :                                  old_key_tuple,
    4207              :                                  all_visible_cleared,
    4208              :                                  all_visible_cleared_new);
    4209       299371 :         if (newbuf != buffer)
    4210              :         {
    4211       140094 :             PageSetLSN(BufferGetPage(newbuf), recptr);
    4212              :         }
    4213       299371 :         PageSetLSN(BufferGetPage(buffer), recptr);
    4214              :     }
    4215              : 
    4216       310735 :     END_CRIT_SECTION();
    4217              : 
    4218       310735 :     if (newbuf != buffer)
    4219       150217 :         LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
    4220       310735 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    4221              : 
    4222              :     /*
    4223              :      * Mark old tuple for invalidation from system caches at next command
    4224              :      * boundary, and mark the new tuple for invalidation in case we abort. We
    4225              :      * have to do this before releasing the buffer because oldtup is in the
    4226              :      * buffer.  (heaptup is all in local memory, but it's necessary to process
    4227              :      * both tuple versions in one call to inval.c so we can avoid redundant
    4228              :      * sinval messages.)
    4229              :      */
    4230       310735 :     CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
    4231              : 
    4232              :     /* Now we can release the buffer(s) */
    4233       310735 :     if (newbuf != buffer)
    4234       150217 :         ReleaseBuffer(newbuf);
    4235       310735 :     ReleaseBuffer(buffer);
    4236       310735 :     if (BufferIsValid(vmbuffer_new))
    4237          926 :         ReleaseBuffer(vmbuffer_new);
    4238       310735 :     if (BufferIsValid(vmbuffer))
    4239         1603 :         ReleaseBuffer(vmbuffer);
    4240              : 
    4241              :     /*
    4242              :      * Release the lmgr tuple lock, if we had it.
    4243              :      */
    4244       310735 :     if (have_tuple_lock)
    4245           22 :         UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
    4246              : 
    4247       310735 :     pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
    4248              : 
    4249              :     /*
    4250              :      * If heaptup is a private copy, release it.  Don't forget to copy t_self
    4251              :      * back to the caller's image, too.
    4252              :      */
    4253       310735 :     if (heaptup != newtup)
    4254              :     {
    4255         1662 :         newtup->t_self = heaptup->t_self;
    4256         1662 :         heap_freetuple(heaptup);
    4257              :     }
    4258              : 
    4259              :     /*
    4260              :      * If it is a HOT update, the update may still need to update summarized
    4261              :      * indexes, lest we fail to update those summaries and get incorrect
    4262              :      * results (for example, minmax bounds of the block may change with this
    4263              :      * update).
    4264              :      */
    4265       310735 :     if (use_hot_update)
    4266              :     {
    4267       148123 :         if (summarized_update)
    4268         1641 :             *update_indexes = TU_Summarizing;
    4269              :         else
    4270       146482 :             *update_indexes = TU_None;
    4271              :     }
    4272              :     else
    4273       162612 :         *update_indexes = TU_All;
    4274              : 
    4275       310735 :     if (old_key_tuple != NULL && old_key_copied)
    4276           84 :         heap_freetuple(old_key_tuple);
    4277              : 
    4278       310735 :     bms_free(hot_attrs);
    4279       310735 :     bms_free(sum_attrs);
    4280       310735 :     bms_free(key_attrs);
    4281       310735 :     bms_free(id_attrs);
    4282       310735 :     bms_free(modified_attrs);
    4283       310735 :     bms_free(interesting_attrs);
    4284              : 
    4285       310735 :     return TM_Ok;
    4286              : }
    4287              : 
    4288              : #ifdef USE_ASSERT_CHECKING
    4289              : /*
    4290              :  * Confirm adequate lock held during heap_update(), per rules from
    4291              :  * README.tuplock section "Locking to write inplace-updated tables".
    4292              :  */
    4293              : static void
    4294              : check_lock_if_inplace_updateable_rel(Relation relation,
    4295              :                                      const ItemPointerData *otid,
    4296              :                                      HeapTuple newtup)
    4297              : {
    4298              :     /* LOCKTAG_TUPLE acceptable for any catalog */
    4299              :     switch (RelationGetRelid(relation))
    4300              :     {
    4301              :         case RelationRelationId:
    4302              :         case DatabaseRelationId:
    4303              :             {
    4304              :                 LOCKTAG     tuptag;
    4305              : 
    4306              :                 SET_LOCKTAG_TUPLE(tuptag,
    4307              :                                   relation->rd_lockInfo.lockRelId.dbId,
    4308              :                                   relation->rd_lockInfo.lockRelId.relId,
    4309              :                                   ItemPointerGetBlockNumber(otid),
    4310              :                                   ItemPointerGetOffsetNumber(otid));
    4311              :                 if (LockHeldByMe(&tuptag, InplaceUpdateTupleLock, false))
    4312              :                     return;
    4313              :             }
    4314              :             break;
    4315              :         default:
    4316              :             Assert(!IsInplaceUpdateRelation(relation));
    4317              :             return;
    4318              :     }
    4319              : 
    4320              :     switch (RelationGetRelid(relation))
    4321              :     {
    4322              :         case RelationRelationId:
    4323              :             {
    4324              :                 /* LOCKTAG_TUPLE or LOCKTAG_RELATION ok */
    4325              :                 Form_pg_class classForm = (Form_pg_class) GETSTRUCT(newtup);
    4326              :                 Oid         relid = classForm->oid;
    4327              :                 Oid         dbid;
    4328              :                 LOCKTAG     tag;
    4329              : 
    4330              :                 if (IsSharedRelation(relid))
    4331              :                     dbid = InvalidOid;
    4332              :                 else
    4333              :                     dbid = MyDatabaseId;
    4334              : 
    4335              :                 if (classForm->relkind == RELKIND_INDEX)
    4336              :                 {
    4337              :                     Relation    irel = index_open(relid, AccessShareLock);
    4338              : 
    4339              :                     SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
    4340              :                     index_close(irel, AccessShareLock);
    4341              :                 }
    4342              :                 else
    4343              :                     SET_LOCKTAG_RELATION(tag, dbid, relid);
    4344              : 
    4345              :                 if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, false) &&
    4346              :                     !LockHeldByMe(&tag, ShareRowExclusiveLock, true))
    4347              :                     elog(WARNING,
    4348              :                          "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
    4349              :                          NameStr(classForm->relname),
    4350              :                          relid,
    4351              :                          classForm->relkind,
    4352              :                          ItemPointerGetBlockNumber(otid),
    4353              :                          ItemPointerGetOffsetNumber(otid));
    4354              :             }
    4355              :             break;
    4356              :         case DatabaseRelationId:
    4357              :             {
    4358              :                 /* LOCKTAG_TUPLE required */
    4359              :                 Form_pg_database dbForm = (Form_pg_database) GETSTRUCT(newtup);
    4360              : 
    4361              :                 elog(WARNING,
    4362              :                      "missing lock on database \"%s\" (OID %u) @ TID (%u,%u)",
    4363              :                      NameStr(dbForm->datname),
    4364              :                      dbForm->oid,
    4365              :                      ItemPointerGetBlockNumber(otid),
    4366              :                      ItemPointerGetOffsetNumber(otid));
    4367              :             }
    4368              :             break;
    4369              :     }
    4370              : }
    4371              : 
    4372              : /*
    4373              :  * Confirm adequate relation lock held, per rules from README.tuplock section
    4374              :  * "Locking to write inplace-updated tables".
    4375              :  */
    4376              : static void
    4377              : check_inplace_rel_lock(HeapTuple oldtup)
    4378              : {
    4379              :     Form_pg_class classForm = (Form_pg_class) GETSTRUCT(oldtup);
    4380              :     Oid         relid = classForm->oid;
    4381              :     Oid         dbid;
    4382              :     LOCKTAG     tag;
    4383              : 
    4384              :     if (IsSharedRelation(relid))
    4385              :         dbid = InvalidOid;
    4386              :     else
    4387              :         dbid = MyDatabaseId;
    4388              : 
    4389              :     if (classForm->relkind == RELKIND_INDEX)
    4390              :     {
    4391              :         Relation    irel = index_open(relid, AccessShareLock);
    4392              : 
    4393              :         SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
    4394              :         index_close(irel, AccessShareLock);
    4395              :     }
    4396              :     else
    4397              :         SET_LOCKTAG_RELATION(tag, dbid, relid);
    4398              : 
    4399              :     if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, true))
    4400              :         elog(WARNING,
    4401              :              "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
    4402              :              NameStr(classForm->relname),
    4403              :              relid,
    4404              :              classForm->relkind,
    4405              :              ItemPointerGetBlockNumber(&oldtup->t_self),
    4406              :              ItemPointerGetOffsetNumber(&oldtup->t_self));
    4407              : }
    4408              : #endif
    4409              : 
    4410              : /*
    4411              :  * Check if the specified attribute's values are the same.  Subroutine for
    4412              :  * HeapDetermineColumnsInfo.
    4413              :  */
    4414              : static bool
    4415       760531 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
    4416              :                  bool isnull1, bool isnull2)
    4417              : {
    4418              :     /*
    4419              :      * If one value is NULL and other is not, then they are certainly not
    4420              :      * equal
    4421              :      */
    4422       760531 :     if (isnull1 != isnull2)
    4423           45 :         return false;
    4424              : 
    4425              :     /*
    4426              :      * If both are NULL, they can be considered equal.
    4427              :      */
    4428       760486 :     if (isnull1)
    4429         4991 :         return true;
    4430              : 
    4431              :     /*
    4432              :      * We do simple binary comparison of the two datums.  This may be overly
    4433              :      * strict because there can be multiple binary representations for the
    4434              :      * same logical value.  But we should be OK as long as there are no false
    4435              :      * positives.  Using a type-specific equality operator is messy because
    4436              :      * there could be multiple notions of equality in different operator
    4437              :      * classes; furthermore, we cannot safely invoke user-defined functions
    4438              :      * while holding exclusive buffer lock.
    4439              :      */
    4440       755495 :     if (attrnum <= 0)
    4441              :     {
    4442              :         /* The only allowed system columns are OIDs, so do this */
    4443            0 :         return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
    4444              :     }
    4445              :     else
    4446              :     {
    4447              :         CompactAttribute *att;
    4448              : 
    4449              :         Assert(attrnum <= tupdesc->natts);
    4450       755495 :         att = TupleDescCompactAttr(tupdesc, attrnum - 1);
    4451       755495 :         return datumIsEqual(value1, value2, att->attbyval, att->attlen);
    4452              :     }
    4453              : }
    4454              : 
    4455              : /*
    4456              :  * Check which columns are being updated.
    4457              :  *
    4458              :  * Given an updated tuple, determine (and return into the output bitmapset),
    4459              :  * from those listed as interesting, the set of columns that changed.
    4460              :  *
    4461              :  * has_external indicates if any of the unmodified attributes (from those
    4462              :  * listed as interesting) of the old tuple is a member of external_cols and is
    4463              :  * stored externally.
    4464              :  */
    4465              : static Bitmapset *
    4466       310909 : HeapDetermineColumnsInfo(Relation relation,
    4467              :                          Bitmapset *interesting_cols,
    4468              :                          Bitmapset *external_cols,
    4469              :                          HeapTuple oldtup, HeapTuple newtup,
    4470              :                          bool *has_external)
    4471              : {
    4472              :     int         attidx;
    4473       310909 :     Bitmapset  *modified = NULL;
    4474       310909 :     TupleDesc   tupdesc = RelationGetDescr(relation);
    4475              : 
    4476       310909 :     attidx = -1;
    4477      1071440 :     while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
    4478              :     {
    4479              :         /* attidx is zero-based, attrnum is the normal attribute number */
    4480       760531 :         AttrNumber  attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
    4481              :         Datum       value1,
    4482              :                     value2;
    4483              :         bool        isnull1,
    4484              :                     isnull2;
    4485              : 
    4486              :         /*
    4487              :          * If it's a whole-tuple reference, say "not equal".  It's not really
    4488              :          * worth supporting this case, since it could only succeed after a
    4489              :          * no-op update, which is hardly a case worth optimizing for.
    4490              :          */
    4491       760531 :         if (attrnum == 0)
    4492              :         {
    4493            0 :             modified = bms_add_member(modified, attidx);
    4494       730521 :             continue;
    4495              :         }
    4496              : 
    4497              :         /*
    4498              :          * Likewise, automatically say "not equal" for any system attribute
    4499              :          * other than tableOID; we cannot expect these to be consistent in a
    4500              :          * HOT chain, or even to be set correctly yet in the new tuple.
    4501              :          */
    4502       760531 :         if (attrnum < 0)
    4503              :         {
    4504            0 :             if (attrnum != TableOidAttributeNumber)
    4505              :             {
    4506            0 :                 modified = bms_add_member(modified, attidx);
    4507            0 :                 continue;
    4508              :             }
    4509              :         }
    4510              : 
    4511              :         /*
    4512              :          * Extract the corresponding values.  XXX this is pretty inefficient
    4513              :          * if there are many indexed columns.  Should we do a single
    4514              :          * heap_deform_tuple call on each tuple, instead?   But that doesn't
    4515              :          * work for system columns ...
    4516              :          */
    4517       760531 :         value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
    4518       760531 :         value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
    4519              : 
    4520       760531 :         if (!heap_attr_equals(tupdesc, attrnum, value1,
    4521              :                               value2, isnull1, isnull2))
    4522              :         {
    4523        27278 :             modified = bms_add_member(modified, attidx);
    4524        27278 :             continue;
    4525              :         }
    4526              : 
    4527              :         /*
    4528              :          * No need to check attributes that can't be stored externally. Note
    4529              :          * that system attributes can't be stored externally.
    4530              :          */
    4531       733253 :         if (attrnum < 0 || isnull1 ||
    4532       728262 :             TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
    4533       703243 :             continue;
    4534              : 
    4535              :         /*
    4536              :          * Check if the old tuple's attribute is stored externally and is a
    4537              :          * member of external_cols.
    4538              :          */
    4539        30015 :         if (VARATT_IS_EXTERNAL((varlena *) DatumGetPointer(value1)) &&
    4540            5 :             bms_is_member(attidx, external_cols))
    4541            2 :             *has_external = true;
    4542              :     }
    4543              : 
    4544       310909 :     return modified;
    4545              : }
    4546              : 
    4547              : /*
    4548              :  *  simple_heap_update - replace a tuple
    4549              :  *
    4550              :  * This routine may be used to update a tuple when concurrent updates of
    4551              :  * the target tuple are not expected (for example, because we have a lock
    4552              :  * on the relation associated with the tuple).  Any failure is reported
    4553              :  * via ereport().
    4554              :  */
    4555              : void
    4556       116165 : simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup,
    4557              :                    TU_UpdateIndexes *update_indexes)
    4558              : {
    4559              :     TM_Result   result;
    4560              :     TM_FailureData tmfd;
    4561              :     LockTupleMode lockmode;
    4562              : 
    4563       116165 :     result = heap_update(relation, otid, tup,
    4564              :                          GetCurrentCommandId(true), InvalidSnapshot,
    4565              :                          true /* wait for commit */ ,
    4566              :                          &tmfd, &lockmode, update_indexes);
    4567       116165 :     switch (result)
    4568              :     {
    4569            0 :         case TM_SelfModified:
    4570              :             /* Tuple was already updated in current command? */
    4571            0 :             elog(ERROR, "tuple already updated by self");
    4572              :             break;
    4573              : 
    4574       116164 :         case TM_Ok:
    4575              :             /* done successfully */
    4576       116164 :             break;
    4577              : 
    4578            0 :         case TM_Updated:
    4579            0 :             elog(ERROR, "tuple concurrently updated");
    4580              :             break;
    4581              : 
    4582            1 :         case TM_Deleted:
    4583            1 :             elog(ERROR, "tuple concurrently deleted");
    4584              :             break;
    4585              : 
    4586            0 :         default:
    4587            0 :             elog(ERROR, "unrecognized heap_update status: %u", result);
    4588              :             break;
    4589              :     }
    4590       116164 : }
    4591              : 
    4592              : 
    4593              : /*
    4594              :  * Return the MultiXactStatus corresponding to the given tuple lock mode.
    4595              :  */
    4596              : static MultiXactStatus
    4597       115442 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
    4598              : {
    4599              :     int         retval;
    4600              : 
    4601       115442 :     if (is_update)
    4602          215 :         retval = tupleLockExtraInfo[mode].updstatus;
    4603              :     else
    4604       115227 :         retval = tupleLockExtraInfo[mode].lockstatus;
    4605              : 
    4606       115442 :     if (retval == -1)
    4607            0 :         elog(ERROR, "invalid lock tuple mode %d/%s", mode,
    4608              :              is_update ? "true" : "false");
    4609              : 
    4610       115442 :     return (MultiXactStatus) retval;
    4611              : }
    4612              : 
    4613              : /*
    4614              :  *  heap_lock_tuple - lock a tuple in shared or exclusive mode
    4615              :  *
    4616              :  * Note that this acquires a buffer pin, which the caller must release.
    4617              :  *
    4618              :  * Input parameters:
    4619              :  *  relation: relation containing tuple (caller must hold suitable lock)
    4620              :  *  cid: current command ID (used for visibility test, and stored into
    4621              :  *      tuple's cmax if lock is successful)
    4622              :  *  mode: indicates if shared or exclusive tuple lock is desired
    4623              :  *  wait_policy: what to do if tuple lock is not available
    4624              :  *  follow_updates: if true, follow the update chain to also lock descendant
    4625              :  *      tuples.
    4626              :  *
    4627              :  * Output parameters:
    4628              :  *  *tuple: all fields filled in
    4629              :  *  *buffer: set to buffer holding tuple (pinned but not locked at exit)
    4630              :  *  *tmfd: filled in failure cases (see below)
    4631              :  *
    4632              :  * Function results are the same as the ones for table_tuple_lock().
    4633              :  *
    4634              :  * In the failure cases other than TM_Invisible, the routine fills
    4635              :  * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
    4636              :  * if necessary), and t_cmax (the last only for TM_SelfModified,
    4637              :  * since we cannot obtain cmax from a combo CID generated by another
    4638              :  * transaction).
    4639              :  * See comments for struct TM_FailureData for additional info.
    4640              :  *
    4641              :  * See README.tuplock for a thorough explanation of this mechanism.
    4642              :  */
    4643              : TM_Result
    4644       158474 : heap_lock_tuple(Relation relation, HeapTuple tuple,
    4645              :                 CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
    4646              :                 bool follow_updates,
    4647              :                 Buffer *buffer, TM_FailureData *tmfd)
    4648              : {
    4649              :     TM_Result   result;
    4650       158474 :     ItemPointer tid = &(tuple->t_self);
    4651              :     ItemId      lp;
    4652              :     Page        page;
    4653       158474 :     Buffer      vmbuffer = InvalidBuffer;
    4654              :     BlockNumber block;
    4655              :     TransactionId xid,
    4656              :                 xmax;
    4657              :     uint16      old_infomask,
    4658              :                 new_infomask,
    4659              :                 new_infomask2;
    4660       158474 :     bool        first_time = true;
    4661       158474 :     bool        skip_tuple_lock = false;
    4662       158474 :     bool        have_tuple_lock = false;
    4663       158474 :     bool        cleared_all_frozen = false;
    4664              : 
    4665       158474 :     *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
    4666       158474 :     block = ItemPointerGetBlockNumber(tid);
    4667              : 
    4668              :     /*
    4669              :      * Before locking the buffer, pin the visibility map page if it appears to
    4670              :      * be necessary.  Since we haven't got the lock yet, someone else might be
    4671              :      * in the middle of changing this, so we'll need to recheck after we have
    4672              :      * the lock.
    4673              :      */
    4674       158474 :     if (PageIsAllVisible(BufferGetPage(*buffer)))
    4675         1666 :         visibilitymap_pin(relation, block, &vmbuffer);
    4676              : 
    4677       158474 :     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    4678              : 
    4679       158474 :     page = BufferGetPage(*buffer);
    4680       158474 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
    4681              :     Assert(ItemIdIsNormal(lp));
    4682              : 
    4683       158474 :     tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
    4684       158474 :     tuple->t_len = ItemIdGetLength(lp);
    4685       158474 :     tuple->t_tableOid = RelationGetRelid(relation);
    4686              : 
    4687           16 : l3:
    4688       158490 :     result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
    4689              : 
    4690       158490 :     if (result == TM_Invisible)
    4691              :     {
    4692              :         /*
    4693              :          * This is possible, but only when locking a tuple for ON CONFLICT DO
    4694              :          * SELECT/UPDATE.  We return this value here rather than throwing an
    4695              :          * error in order to give that case the opportunity to throw a more
    4696              :          * specific error.
    4697              :          */
    4698           21 :         result = TM_Invisible;
    4699           21 :         goto out_locked;
    4700              :     }
    4701       158469 :     else if (result == TM_BeingModified ||
    4702        77258 :              result == TM_Updated ||
    4703              :              result == TM_Deleted)
    4704              :     {
    4705              :         TransactionId xwait;
    4706              :         uint16      infomask;
    4707              :         uint16      infomask2;
    4708              :         bool        require_sleep;
    4709              :         ItemPointerData t_ctid;
    4710              : 
    4711              :         /* must copy state data before unlocking buffer */
    4712        81212 :         xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
    4713        81212 :         infomask = tuple->t_data->t_infomask;
    4714        81212 :         infomask2 = tuple->t_data->t_infomask2;
    4715        81212 :         ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
    4716              : 
    4717        81212 :         LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
    4718              : 
    4719              :         /*
    4720              :          * If any subtransaction of the current top transaction already holds
    4721              :          * a lock as strong as or stronger than what we're requesting, we
    4722              :          * effectively hold the desired lock already.  We *must* succeed
    4723              :          * without trying to take the tuple lock, else we will deadlock
    4724              :          * against anyone wanting to acquire a stronger lock.
    4725              :          *
    4726              :          * Note we only do this the first time we loop on the HTSU result;
    4727              :          * there is no point in testing in subsequent passes, because
    4728              :          * evidently our own transaction cannot have acquired a new lock after
    4729              :          * the first time we checked.
    4730              :          */
    4731        81212 :         if (first_time)
    4732              :         {
    4733        81201 :             first_time = false;
    4734              : 
    4735        81201 :             if (infomask & HEAP_XMAX_IS_MULTI)
    4736              :             {
    4737              :                 int         i;
    4738              :                 int         nmembers;
    4739              :                 MultiXactMember *members;
    4740              : 
    4741              :                 /*
    4742              :                  * We don't need to allow old multixacts here; if that had
    4743              :                  * been the case, HeapTupleSatisfiesUpdate would have returned
    4744              :                  * MayBeUpdated and we wouldn't be here.
    4745              :                  */
    4746              :                 nmembers =
    4747        73302 :                     GetMultiXactIdMembers(xwait, &members, false,
    4748        73302 :                                           HEAP_XMAX_IS_LOCKED_ONLY(infomask));
    4749              : 
    4750      1422680 :                 for (i = 0; i < nmembers; i++)
    4751              :                 {
    4752              :                     /* only consider members of our own transaction */
    4753      1349392 :                     if (!TransactionIdIsCurrentTransactionId(members[i].xid))
    4754      1349343 :                         continue;
    4755              : 
    4756           49 :                     if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
    4757              :                     {
    4758           14 :                         pfree(members);
    4759           14 :                         result = TM_Ok;
    4760           14 :                         goto out_unlocked;
    4761              :                     }
    4762              :                     else
    4763              :                     {
    4764              :                         /*
    4765              :                          * Disable acquisition of the heavyweight tuple lock.
    4766              :                          * Otherwise, when promoting a weaker lock, we might
    4767              :                          * deadlock with another locker that has acquired the
    4768              :                          * heavyweight tuple lock and is waiting for our
    4769              :                          * transaction to finish.
    4770              :                          *
    4771              :                          * Note that in this case we still need to wait for
    4772              :                          * the multixact if required, to avoid acquiring
    4773              :                          * conflicting locks.
    4774              :                          */
    4775           35 :                         skip_tuple_lock = true;
    4776              :                     }
    4777              :                 }
    4778              : 
    4779        73288 :                 if (members)
    4780        73288 :                     pfree(members);
    4781              :             }
    4782         7899 :             else if (TransactionIdIsCurrentTransactionId(xwait))
    4783              :             {
    4784         6577 :                 switch (mode)
    4785              :                 {
    4786          176 :                     case LockTupleKeyShare:
    4787              :                         Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
    4788              :                                HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
    4789              :                                HEAP_XMAX_IS_EXCL_LOCKED(infomask));
    4790          176 :                         result = TM_Ok;
    4791          176 :                         goto out_unlocked;
    4792           24 :                     case LockTupleShare:
    4793           30 :                         if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
    4794            6 :                             HEAP_XMAX_IS_EXCL_LOCKED(infomask))
    4795              :                         {
    4796           18 :                             result = TM_Ok;
    4797           18 :                             goto out_unlocked;
    4798              :                         }
    4799            6 :                         break;
    4800           72 :                     case LockTupleNoKeyExclusive:
    4801           72 :                         if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
    4802              :                         {
    4803           60 :                             result = TM_Ok;
    4804           60 :                             goto out_unlocked;
    4805              :                         }
    4806           12 :                         break;
    4807         6305 :                     case LockTupleExclusive:
    4808         6305 :                         if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
    4809         1265 :                             infomask2 & HEAP_KEYS_UPDATED)
    4810              :                         {
    4811         1244 :                             result = TM_Ok;
    4812         1244 :                             goto out_unlocked;
    4813              :                         }
    4814         5061 :                         break;
    4815              :                 }
    4816              :             }
    4817              :         }
    4818              : 
    4819              :         /*
    4820              :          * Initially assume that we will have to wait for the locking
    4821              :          * transaction(s) to finish.  We check various cases below in which
    4822              :          * this can be turned off.
    4823              :          */
    4824        79700 :         require_sleep = true;
    4825        79700 :         if (mode == LockTupleKeyShare)
    4826              :         {
    4827              :             /*
    4828              :              * If we're requesting KeyShare, and there's no update present, we
    4829              :              * don't need to wait.  Even if there is an update, we can still
    4830              :              * continue if the key hasn't been modified.
    4831              :              *
    4832              :              * However, if there are updates, we need to walk the update chain
    4833              :              * to mark future versions of the row as locked, too.  That way,
    4834              :              * if somebody deletes that future version, we're protected
    4835              :              * against the key going away.  This locking of future versions
    4836              :              * could block momentarily, if a concurrent transaction is
    4837              :              * deleting a key; or it could return a value to the effect that
    4838              :              * the transaction deleting the key has already committed.  So we
    4839              :              * do this before re-locking the buffer; otherwise this would be
    4840              :              * prone to deadlocks.
    4841              :              *
    4842              :              * Note that the TID we're locking was grabbed before we unlocked
    4843              :              * the buffer.  For it to change while we're not looking, the
    4844              :              * other properties we're testing for below after re-locking the
    4845              :              * buffer would also change, in which case we would restart this
    4846              :              * loop above.
    4847              :              */
    4848        73863 :             if (!(infomask2 & HEAP_KEYS_UPDATED))
    4849              :             {
    4850              :                 bool        updated;
    4851              : 
    4852        73820 :                 updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
    4853              : 
    4854              :                 /*
    4855              :                  * If there are updates, follow the update chain; bail out if
    4856              :                  * that cannot be done.
    4857              :                  */
    4858        73820 :                 if (follow_updates && updated &&
    4859         2169 :                     !ItemPointerEquals(&tuple->t_self, &t_ctid))
    4860              :                 {
    4861              :                     TM_Result   res;
    4862              : 
    4863         2169 :                     res = heap_lock_updated_tuple(relation,
    4864              :                                                   infomask, xwait, &t_ctid,
    4865              :                                                   GetCurrentTransactionId(),
    4866              :                                                   mode);
    4867         2169 :                     if (res != TM_Ok)
    4868              :                     {
    4869            6 :                         result = res;
    4870              :                         /* recovery code expects to have buffer lock held */
    4871            6 :                         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    4872          198 :                         goto failed;
    4873              :                     }
    4874              :                 }
    4875              : 
    4876        73814 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    4877              : 
    4878              :                 /*
    4879              :                  * Make sure it's still an appropriate lock, else start over.
    4880              :                  * Also, if it wasn't updated before we released the lock, but
    4881              :                  * is updated now, we start over too; the reason is that we
    4882              :                  * now need to follow the update chain to lock the new
    4883              :                  * versions.
    4884              :                  */
    4885        73814 :                 if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
    4886         2151 :                     ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
    4887         2151 :                      !updated))
    4888           16 :                     goto l3;
    4889              : 
    4890              :                 /* Things look okay, so we can skip sleeping */
    4891        73814 :                 require_sleep = false;
    4892              : 
    4893              :                 /*
    4894              :                  * Note we allow Xmax to change here; other updaters/lockers
    4895              :                  * could have modified it before we grabbed the buffer lock.
    4896              :                  * However, this is not a problem, because with the recheck we
    4897              :                  * just did we ensure that they still don't conflict with the
    4898              :                  * lock we want.
    4899              :                  */
    4900              :             }
    4901              :         }
    4902         5837 :         else if (mode == LockTupleShare)
    4903              :         {
    4904              :             /*
    4905              :              * If we're requesting Share, we can similarly avoid sleeping if
    4906              :              * there's no update and no exclusive lock present.
    4907              :              */
    4908          443 :             if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
    4909          443 :                 !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
    4910              :             {
    4911          437 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    4912              : 
    4913              :                 /*
    4914              :                  * Make sure it's still an appropriate lock, else start over.
    4915              :                  * See above about allowing xmax to change.
    4916              :                  */
    4917          874 :                 if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
    4918          437 :                     HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
    4919            0 :                     goto l3;
    4920          437 :                 require_sleep = false;
    4921              :             }
    4922              :         }
    4923         5394 :         else if (mode == LockTupleNoKeyExclusive)
    4924              :         {
    4925              :             /*
    4926              :              * If we're requesting NoKeyExclusive, we might also be able to
    4927              :              * avoid sleeping; just ensure that there no conflicting lock
    4928              :              * already acquired.
    4929              :              */
    4930          172 :             if (infomask & HEAP_XMAX_IS_MULTI)
    4931              :             {
    4932           26 :                 if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
    4933              :                                              mode, NULL))
    4934              :                 {
    4935              :                     /*
    4936              :                      * No conflict, but if the xmax changed under us in the
    4937              :                      * meantime, start over.
    4938              :                      */
    4939           13 :                     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    4940           26 :                     if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
    4941           13 :                         !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
    4942              :                                              xwait))
    4943            0 :                         goto l3;
    4944              : 
    4945              :                     /* otherwise, we're good */
    4946           13 :                     require_sleep = false;
    4947              :                 }
    4948              :             }
    4949          146 :             else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
    4950              :             {
    4951           18 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    4952              : 
    4953              :                 /* if the xmax changed in the meantime, start over */
    4954           36 :                 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
    4955           18 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
    4956              :                                          xwait))
    4957            0 :                     goto l3;
    4958              :                 /* otherwise, we're good */
    4959           18 :                 require_sleep = false;
    4960              :             }
    4961              :         }
    4962              : 
    4963              :         /*
    4964              :          * As a check independent from those above, we can also avoid sleeping
    4965              :          * if the current transaction is the sole locker of the tuple.  Note
    4966              :          * that the strength of the lock already held is irrelevant; this is
    4967              :          * not about recording the lock in Xmax (which will be done regardless
    4968              :          * of this optimization, below).  Also, note that the cases where we
    4969              :          * hold a lock stronger than we are requesting are already handled
    4970              :          * above by not doing anything.
    4971              :          *
    4972              :          * Note we only deal with the non-multixact case here; MultiXactIdWait
    4973              :          * is well equipped to deal with this situation on its own.
    4974              :          */
    4975        85066 :         if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
    4976         5372 :             TransactionIdIsCurrentTransactionId(xwait))
    4977              :         {
    4978              :             /* ... but if the xmax changed in the meantime, start over */
    4979         5061 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    4980        10122 :             if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
    4981         5061 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
    4982              :                                      xwait))
    4983            0 :                 goto l3;
    4984              :             Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
    4985         5061 :             require_sleep = false;
    4986              :         }
    4987              : 
    4988              :         /*
    4989              :          * Time to sleep on the other transaction/multixact, if necessary.
    4990              :          *
    4991              :          * If the other transaction is an update/delete that's already
    4992              :          * committed, then sleeping cannot possibly do any good: if we're
    4993              :          * required to sleep, get out to raise an error instead.
    4994              :          *
    4995              :          * By here, we either have already acquired the buffer exclusive lock,
    4996              :          * or we must wait for the locking transaction or multixact; so below
    4997              :          * we ensure that we grab buffer lock after the sleep.
    4998              :          */
    4999        79694 :         if (require_sleep && (result == TM_Updated || result == TM_Deleted))
    5000              :         {
    5001          154 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    5002          154 :             goto failed;
    5003              :         }
    5004        79540 :         else if (require_sleep)
    5005              :         {
    5006              :             /*
    5007              :              * Acquire tuple lock to establish our priority for the tuple, or
    5008              :              * die trying.  LockTuple will release us when we are next-in-line
    5009              :              * for the tuple.  We must do this even if we are share-locking,
    5010              :              * but not if we already have a weaker lock on the tuple.
    5011              :              *
    5012              :              * If we are forced to "start over" below, we keep the tuple lock;
    5013              :              * this arranges that we stay at the head of the line while
    5014              :              * rechecking tuple state.
    5015              :              */
    5016          197 :             if (!skip_tuple_lock &&
    5017          181 :                 !heap_acquire_tuplock(relation, tid, mode, wait_policy,
    5018              :                                       &have_tuple_lock))
    5019              :             {
    5020              :                 /*
    5021              :                  * This can only happen if wait_policy is Skip and the lock
    5022              :                  * couldn't be obtained.
    5023              :                  */
    5024            1 :                 result = TM_WouldBlock;
    5025              :                 /* recovery code expects to have buffer lock held */
    5026            1 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    5027            1 :                 goto failed;
    5028              :             }
    5029              : 
    5030          195 :             if (infomask & HEAP_XMAX_IS_MULTI)
    5031              :             {
    5032           40 :                 MultiXactStatus status = get_mxact_status_for_lock(mode, false);
    5033              : 
    5034              :                 /* We only ever lock tuples, never update them */
    5035           40 :                 if (status >= MultiXactStatusNoKeyUpdate)
    5036            0 :                     elog(ERROR, "invalid lock mode in heap_lock_tuple");
    5037              : 
    5038              :                 /* wait for multixact to end, or die trying  */
    5039           40 :                 switch (wait_policy)
    5040              :                 {
    5041           36 :                     case LockWaitBlock:
    5042           36 :                         MultiXactIdWait((MultiXactId) xwait, status, infomask,
    5043           36 :                                         relation, &tuple->t_self, XLTW_Lock, NULL);
    5044           36 :                         break;
    5045            2 :                     case LockWaitSkip:
    5046            2 :                         if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
    5047              :                                                         status, infomask, relation,
    5048              :                                                         NULL, false))
    5049              :                         {
    5050            2 :                             result = TM_WouldBlock;
    5051              :                             /* recovery code expects to have buffer lock held */
    5052            2 :                             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    5053            2 :                             goto failed;
    5054              :                         }
    5055            0 :                         break;
    5056            2 :                     case LockWaitError:
    5057            2 :                         if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
    5058              :                                                         status, infomask, relation,
    5059              :                                                         NULL, log_lock_failures))
    5060            2 :                             ereport(ERROR,
    5061              :                                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
    5062              :                                      errmsg("could not obtain lock on row in relation \"%s\"",
    5063              :                                             RelationGetRelationName(relation))));
    5064              : 
    5065            0 :                         break;
    5066              :                 }
    5067              : 
    5068              :                 /*
    5069              :                  * Of course, the multixact might not be done here: if we're
    5070              :                  * requesting a light lock mode, other transactions with light
    5071              :                  * locks could still be alive, as well as locks owned by our
    5072              :                  * own xact or other subxacts of this backend.  We need to
    5073              :                  * preserve the surviving MultiXact members.  Note that it
    5074              :                  * isn't absolutely necessary in the latter case, but doing so
    5075              :                  * is simpler.
    5076              :                  */
    5077              :             }
    5078              :             else
    5079              :             {
    5080              :                 /* wait for regular transaction to end, or die trying */
    5081          155 :                 switch (wait_policy)
    5082              :                 {
    5083          116 :                     case LockWaitBlock:
    5084          116 :                         XactLockTableWait(xwait, relation, &tuple->t_self,
    5085              :                                           XLTW_Lock);
    5086          116 :                         break;
    5087           33 :                     case LockWaitSkip:
    5088           33 :                         if (!ConditionalXactLockTableWait(xwait, false))
    5089              :                         {
    5090           33 :                             result = TM_WouldBlock;
    5091              :                             /* recovery code expects to have buffer lock held */
    5092           33 :                             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    5093           33 :                             goto failed;
    5094              :                         }
    5095            0 :                         break;
    5096            6 :                     case LockWaitError:
    5097            6 :                         if (!ConditionalXactLockTableWait(xwait, log_lock_failures))
    5098            6 :                             ereport(ERROR,
    5099              :                                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
    5100              :                                      errmsg("could not obtain lock on row in relation \"%s\"",
    5101              :                                             RelationGetRelationName(relation))));
    5102            0 :                         break;
    5103              :                 }
    5104              :             }
    5105              : 
    5106              :             /* if there are updates, follow the update chain */
    5107          152 :             if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
    5108           59 :                 !ItemPointerEquals(&tuple->t_self, &t_ctid))
    5109              :             {
    5110              :                 TM_Result   res;
    5111              : 
    5112           45 :                 res = heap_lock_updated_tuple(relation,
    5113              :                                               infomask, xwait, &t_ctid,
    5114              :                                               GetCurrentTransactionId(),
    5115              :                                               mode);
    5116           45 :                 if (res != TM_Ok)
    5117              :                 {
    5118            2 :                     result = res;
    5119              :                     /* recovery code expects to have buffer lock held */
    5120            2 :                     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    5121            2 :                     goto failed;
    5122              :                 }
    5123              :             }
    5124              : 
    5125          150 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    5126              : 
    5127              :             /*
    5128              :              * xwait is done, but if xwait had just locked the tuple then some
    5129              :              * other xact could update this tuple before we get to this point.
    5130              :              * Check for xmax change, and start over if so.
    5131              :              */
    5132          286 :             if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
    5133          136 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
    5134              :                                      xwait))
    5135           16 :                 goto l3;
    5136              : 
    5137          134 :             if (!(infomask & HEAP_XMAX_IS_MULTI))
    5138              :             {
    5139              :                 /*
    5140              :                  * Otherwise check if it committed or aborted.  Note we cannot
    5141              :                  * be here if the tuple was only locked by somebody who didn't
    5142              :                  * conflict with us; that would have been handled above.  So
    5143              :                  * that transaction must necessarily be gone by now.  But
    5144              :                  * don't check for this in the multixact case, because some
    5145              :                  * locker transactions might still be running.
    5146              :                  */
    5147          101 :                 UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
    5148              :             }
    5149              :         }
    5150              : 
    5151              :         /* By here, we're certain that we hold buffer exclusive lock again */
    5152              : 
    5153              :         /*
    5154              :          * We may lock if previous xmax aborted, or if it committed but only
    5155              :          * locked the tuple without updating it; or if we didn't have to wait
    5156              :          * at all for whatever reason.
    5157              :          */
    5158        79477 :         if (!require_sleep ||
    5159          232 :             (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
    5160          180 :             HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
    5161           82 :             HeapTupleHeaderIsOnlyLocked(tuple->t_data))
    5162        79401 :             result = TM_Ok;
    5163           76 :         else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
    5164           57 :             result = TM_Updated;
    5165              :         else
    5166           19 :             result = TM_Deleted;
    5167              :     }
    5168              : 
    5169        77257 : failed:
    5170       156932 :     if (result != TM_Ok)
    5171              :     {
    5172              :         Assert(result == TM_SelfModified || result == TM_Updated ||
    5173              :                result == TM_Deleted || result == TM_WouldBlock);
    5174              : 
    5175              :         /*
    5176              :          * When locking a tuple under LockWaitSkip semantics and we fail with
    5177              :          * TM_WouldBlock above, it's possible for concurrent transactions to
    5178              :          * release the lock and set HEAP_XMAX_INVALID in the meantime.  So
    5179              :          * this assert is slightly different from the equivalent one in
    5180              :          * heap_delete and heap_update.
    5181              :          */
    5182              :         Assert((result == TM_WouldBlock) ||
    5183              :                !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
    5184              :         Assert(result != TM_Updated ||
    5185              :                !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
    5186          280 :         tmfd->ctid = tuple->t_data->t_ctid;
    5187          280 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
    5188          280 :         if (result == TM_SelfModified)
    5189            6 :             tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
    5190              :         else
    5191          274 :             tmfd->cmax = InvalidCommandId;
    5192          280 :         goto out_locked;
    5193              :     }
    5194              : 
    5195              :     /*
    5196              :      * If we didn't pin the visibility map page and the page has become all
    5197              :      * visible while we were busy locking the buffer, or during some
    5198              :      * subsequent window during which we had it unlocked, we'll have to unlock
    5199              :      * and re-lock, to avoid holding the buffer lock across I/O.  That's a bit
    5200              :      * unfortunate, especially since we'll now have to recheck whether the
    5201              :      * tuple has been locked or updated under us, but hopefully it won't
    5202              :      * happen very often.
    5203              :      */
    5204       156652 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
    5205              :     {
    5206            0 :         LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
    5207            0 :         visibilitymap_pin(relation, block, &vmbuffer);
    5208            0 :         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
    5209            0 :         goto l3;
    5210              :     }
    5211              : 
    5212       156652 :     xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
    5213       156652 :     old_infomask = tuple->t_data->t_infomask;
    5214              : 
    5215              :     /*
    5216              :      * If this is the first possibly-multixact-able operation in the current
    5217              :      * transaction, set my per-backend OldestMemberMXactId setting. We can be
    5218              :      * certain that the transaction will never become a member of any older
    5219              :      * MultiXactIds than that.  (We have to do this even if we end up just
    5220              :      * using our own TransactionId below, since some other backend could
    5221              :      * incorporate our XID into a MultiXact immediately afterwards.)
    5222              :      */
    5223       156652 :     MultiXactIdSetOldestMember();
    5224              : 
    5225              :     /*
    5226              :      * Compute the new xmax and infomask to store into the tuple.  Note we do
    5227              :      * not modify the tuple just yet, because that would leave it in the wrong
    5228              :      * state if multixact.c elogs.
    5229              :      */
    5230       156652 :     compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
    5231              :                               GetCurrentTransactionId(), mode, false,
    5232              :                               &xid, &new_infomask, &new_infomask2);
    5233              : 
    5234       156652 :     START_CRIT_SECTION();
    5235              : 
    5236              :     /*
    5237              :      * Store transaction information of xact locking the tuple.
    5238              :      *
    5239              :      * Note: Cmax is meaningless in this context, so don't set it; this avoids
    5240              :      * possibly generating a useless combo CID.  Moreover, if we're locking a
    5241              :      * previously updated tuple, it's important to preserve the Cmax.
    5242              :      *
    5243              :      * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
    5244              :      * we would break the HOT chain.
    5245              :      */
    5246       156652 :     tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
    5247       156652 :     tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
    5248       156652 :     tuple->t_data->t_infomask |= new_infomask;
    5249       156652 :     tuple->t_data->t_infomask2 |= new_infomask2;
    5250       156652 :     if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
    5251       154505 :         HeapTupleHeaderClearHotUpdated(tuple->t_data);
    5252       156652 :     HeapTupleHeaderSetXmax(tuple->t_data, xid);
    5253              : 
    5254              :     /*
    5255              :      * Make sure there is no forward chain link in t_ctid.  Note that in the
    5256              :      * cases where the tuple has been updated, we must not overwrite t_ctid,
    5257              :      * because it was set by the updater.  Moreover, if the tuple has been
    5258              :      * updated, we need to follow the update chain to lock the new versions of
    5259              :      * the tuple as well.
    5260              :      */
    5261       156652 :     if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
    5262       154505 :         tuple->t_data->t_ctid = *tid;
    5263              : 
    5264              :     /* Clear only the all-frozen bit on visibility map if needed */
    5265       158318 :     if (PageIsAllVisible(page) &&
    5266         1666 :         visibilitymap_clear(relation, block, vmbuffer,
    5267              :                             VISIBILITYMAP_ALL_FROZEN))
    5268           14 :         cleared_all_frozen = true;
    5269              : 
    5270              : 
    5271       156652 :     MarkBufferDirty(*buffer);
    5272              : 
    5273              :     /*
    5274              :      * XLOG stuff.  You might think that we don't need an XLOG record because
    5275              :      * there is no state change worth restoring after a crash.  You would be
    5276              :      * wrong however: we have just written either a TransactionId or a
    5277              :      * MultiXactId that may never have been seen on disk before, and we need
    5278              :      * to make sure that there are XLOG entries covering those ID numbers.
    5279              :      * Else the same IDs might be re-used after a crash, which would be
    5280              :      * disastrous if this page made it to disk before the crash.  Essentially
    5281              :      * we have to enforce the WAL log-before-data rule even in this case.
    5282              :      * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
    5283              :      * entries for everything anyway.)
    5284              :      */
    5285       156652 :     if (RelationNeedsWAL(relation))
    5286              :     {
    5287              :         xl_heap_lock xlrec;
    5288              :         XLogRecPtr  recptr;
    5289              : 
    5290       156301 :         XLogBeginInsert();
    5291       156301 :         XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
    5292              : 
    5293       156301 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
    5294       156301 :         xlrec.xmax = xid;
    5295       312602 :         xlrec.infobits_set = compute_infobits(new_infomask,
    5296       156301 :                                               tuple->t_data->t_infomask2);
    5297       156301 :         xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
    5298       156301 :         XLogRegisterData(&xlrec, SizeOfHeapLock);
    5299              : 
    5300              :         /* we don't decode row locks atm, so no need to log the origin */
    5301              : 
    5302       156301 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
    5303              : 
    5304       156301 :         PageSetLSN(page, recptr);
    5305              :     }
    5306              : 
    5307       156652 :     END_CRIT_SECTION();
    5308              : 
    5309       156652 :     result = TM_Ok;
    5310              : 
    5311       156953 : out_locked:
    5312       156953 :     LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
    5313              : 
    5314       158465 : out_unlocked:
    5315       158465 :     if (BufferIsValid(vmbuffer))
    5316         1666 :         ReleaseBuffer(vmbuffer);
    5317              : 
    5318              :     /*
    5319              :      * Don't update the visibility map here. Locking a tuple doesn't change
    5320              :      * visibility info.
    5321              :      */
    5322              : 
    5323              :     /*
    5324              :      * Now that we have successfully marked the tuple as locked, we can
    5325              :      * release the lmgr tuple lock, if we had it.
    5326              :      */
    5327       158465 :     if (have_tuple_lock)
    5328          166 :         UnlockTupleTuplock(relation, tid, mode);
    5329              : 
    5330       158465 :     return result;
    5331              : }
    5332              : 
    5333              : /*
    5334              :  * Acquire heavyweight lock on the given tuple, in preparation for acquiring
    5335              :  * its normal, Xmax-based tuple lock.
    5336              :  *
    5337              :  * have_tuple_lock is an input and output parameter: on input, it indicates
    5338              :  * whether the lock has previously been acquired (and this function does
    5339              :  * nothing in that case).  If this function returns success, have_tuple_lock
    5340              :  * has been flipped to true.
    5341              :  *
    5342              :  * Returns false if it was unable to obtain the lock; this can only happen if
    5343              :  * wait_policy is Skip.
    5344              :  */
    5345              : static bool
    5346          319 : heap_acquire_tuplock(Relation relation, const ItemPointerData *tid, LockTupleMode mode,
    5347              :                      LockWaitPolicy wait_policy, bool *have_tuple_lock)
    5348              : {
    5349          319 :     if (*have_tuple_lock)
    5350            9 :         return true;
    5351              : 
    5352          310 :     switch (wait_policy)
    5353              :     {
    5354          269 :         case LockWaitBlock:
    5355          269 :             LockTupleTuplock(relation, tid, mode);
    5356          269 :             break;
    5357              : 
    5358           34 :         case LockWaitSkip:
    5359           34 :             if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
    5360            1 :                 return false;
    5361           33 :             break;
    5362              : 
    5363            7 :         case LockWaitError:
    5364            7 :             if (!ConditionalLockTupleTuplock(relation, tid, mode, log_lock_failures))
    5365            1 :                 ereport(ERROR,
    5366              :                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
    5367              :                          errmsg("could not obtain lock on row in relation \"%s\"",
    5368              :                                 RelationGetRelationName(relation))));
    5369            6 :             break;
    5370              :     }
    5371          308 :     *have_tuple_lock = true;
    5372              : 
    5373          308 :     return true;
    5374              : }
    5375              : 
    5376              : /*
    5377              :  * Given an original set of Xmax and infomask, and a transaction (identified by
    5378              :  * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
    5379              :  * corresponding infomasks to use on the tuple.
    5380              :  *
    5381              :  * Note that this might have side effects such as creating a new MultiXactId.
    5382              :  *
    5383              :  * Most callers will have called HeapTupleSatisfiesUpdate before this function;
    5384              :  * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
    5385              :  * but it was not running anymore. There is a race condition, which is that the
    5386              :  * MultiXactId may have finished since then, but that uncommon case is handled
    5387              :  * either here, or within MultiXactIdExpand.
    5388              :  *
    5389              :  * There is a similar race condition possible when the old xmax was a regular
    5390              :  * TransactionId.  We test TransactionIdIsInProgress again just to narrow the
    5391              :  * window, but it's still possible to end up creating an unnecessary
    5392              :  * MultiXactId.  Fortunately this is harmless.
    5393              :  */
    5394              : static void
    5395      2147724 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
    5396              :                           uint16 old_infomask2, TransactionId add_to_xmax,
    5397              :                           LockTupleMode mode, bool is_update,
    5398              :                           TransactionId *result_xmax, uint16 *result_infomask,
    5399              :                           uint16 *result_infomask2)
    5400              : {
    5401              :     TransactionId new_xmax;
    5402              :     uint16      new_infomask,
    5403              :                 new_infomask2;
    5404              : 
    5405              :     Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
    5406              : 
    5407       103986 : l5:
    5408      2251710 :     new_infomask = 0;
    5409      2251710 :     new_infomask2 = 0;
    5410      2251710 :     if (old_infomask & HEAP_XMAX_INVALID)
    5411              :     {
    5412              :         /*
    5413              :          * No previous locker; we just insert our own TransactionId.
    5414              :          *
    5415              :          * Note that it's critical that this case be the first one checked,
    5416              :          * because there are several blocks below that come back to this one
    5417              :          * to implement certain optimizations; old_infomask might contain
    5418              :          * other dirty bits in those cases, but we don't really care.
    5419              :          */
    5420      2071096 :         if (is_update)
    5421              :         {
    5422      1837895 :             new_xmax = add_to_xmax;
    5423      1837895 :             if (mode == LockTupleExclusive)
    5424      1563725 :                 new_infomask2 |= HEAP_KEYS_UPDATED;
    5425              :         }
    5426              :         else
    5427              :         {
    5428       233201 :             new_infomask |= HEAP_XMAX_LOCK_ONLY;
    5429       233201 :             switch (mode)
    5430              :             {
    5431         2639 :                 case LockTupleKeyShare:
    5432         2639 :                     new_xmax = add_to_xmax;
    5433         2639 :                     new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
    5434         2639 :                     break;
    5435          745 :                 case LockTupleShare:
    5436          745 :                     new_xmax = add_to_xmax;
    5437          745 :                     new_infomask |= HEAP_XMAX_SHR_LOCK;
    5438          745 :                     break;
    5439       134057 :                 case LockTupleNoKeyExclusive:
    5440       134057 :                     new_xmax = add_to_xmax;
    5441       134057 :                     new_infomask |= HEAP_XMAX_EXCL_LOCK;
    5442       134057 :                     break;
    5443        95760 :                 case LockTupleExclusive:
    5444        95760 :                     new_xmax = add_to_xmax;
    5445        95760 :                     new_infomask |= HEAP_XMAX_EXCL_LOCK;
    5446        95760 :                     new_infomask2 |= HEAP_KEYS_UPDATED;
    5447        95760 :                     break;
    5448            0 :                 default:
    5449            0 :                     new_xmax = InvalidTransactionId;    /* silence compiler */
    5450            0 :                     elog(ERROR, "invalid lock mode");
    5451              :             }
    5452              :         }
    5453              :     }
    5454       180614 :     else if (old_infomask & HEAP_XMAX_IS_MULTI)
    5455              :     {
    5456              :         MultiXactStatus new_status;
    5457              : 
    5458              :         /*
    5459              :          * Currently we don't allow XMAX_COMMITTED to be set for multis, so
    5460              :          * cross-check.
    5461              :          */
    5462              :         Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
    5463              : 
    5464              :         /*
    5465              :          * A multixact together with LOCK_ONLY set but neither lock bit set
    5466              :          * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
    5467              :          * anymore.  This check is critical for databases upgraded by
    5468              :          * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
    5469              :          * that such multis are never passed.
    5470              :          */
    5471        75566 :         if (HEAP_LOCKED_UPGRADED(old_infomask))
    5472              :         {
    5473            0 :             old_infomask &= ~HEAP_XMAX_IS_MULTI;
    5474            0 :             old_infomask |= HEAP_XMAX_INVALID;
    5475            0 :             goto l5;
    5476              :         }
    5477              : 
    5478              :         /*
    5479              :          * If the XMAX is already a MultiXactId, then we need to expand it to
    5480              :          * include add_to_xmax; but if all the members were lockers and are
    5481              :          * all gone, we can do away with the IS_MULTI bit and just set
    5482              :          * add_to_xmax as the only locker/updater.  If all lockers are gone
    5483              :          * and we have an updater that aborted, we can also do without a
    5484              :          * multi.
    5485              :          *
    5486              :          * The cost of doing GetMultiXactIdMembers would be paid by
    5487              :          * MultiXactIdExpand if we weren't to do this, so this check is not
    5488              :          * incurring extra work anyhow.
    5489              :          */
    5490        75566 :         if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
    5491              :         {
    5492           24 :             if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
    5493            8 :                 !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
    5494              :                                                                 old_infomask)))
    5495              :             {
    5496              :                 /*
    5497              :                  * Reset these bits and restart; otherwise fall through to
    5498              :                  * create a new multi below.
    5499              :                  */
    5500           24 :                 old_infomask &= ~HEAP_XMAX_IS_MULTI;
    5501           24 :                 old_infomask |= HEAP_XMAX_INVALID;
    5502           24 :                 goto l5;
    5503              :             }
    5504              :         }
    5505              : 
    5506        75542 :         new_status = get_mxact_status_for_lock(mode, is_update);
    5507              : 
    5508        75542 :         new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
    5509              :                                      new_status);
    5510        75542 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
    5511              :     }
    5512       105048 :     else if (old_infomask & HEAP_XMAX_COMMITTED)
    5513              :     {
    5514              :         /*
    5515              :          * It's a committed update, so we need to preserve him as updater of
    5516              :          * the tuple.
    5517              :          */
    5518              :         MultiXactStatus status;
    5519              :         MultiXactStatus new_status;
    5520              : 
    5521           13 :         if (old_infomask2 & HEAP_KEYS_UPDATED)
    5522            0 :             status = MultiXactStatusUpdate;
    5523              :         else
    5524           13 :             status = MultiXactStatusNoKeyUpdate;
    5525              : 
    5526           13 :         new_status = get_mxact_status_for_lock(mode, is_update);
    5527              : 
    5528              :         /*
    5529              :          * since it's not running, it's obviously impossible for the old
    5530              :          * updater to be identical to the current one, so we need not check
    5531              :          * for that case as we do in the block above.
    5532              :          */
    5533           13 :         new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
    5534           13 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
    5535              :     }
    5536       105035 :     else if (TransactionIdIsInProgress(xmax))
    5537              :     {
    5538              :         /*
    5539              :          * If the XMAX is a valid, in-progress TransactionId, then we need to
    5540              :          * create a new MultiXactId that includes both the old locker or
    5541              :          * updater and our own TransactionId.
    5542              :          */
    5543              :         MultiXactStatus new_status;
    5544              :         MultiXactStatus old_status;
    5545              :         LockTupleMode old_mode;
    5546              : 
    5547       105026 :         if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
    5548              :         {
    5549       105000 :             if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
    5550         5673 :                 old_status = MultiXactStatusForKeyShare;
    5551        99327 :             else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
    5552          433 :                 old_status = MultiXactStatusForShare;
    5553        98894 :             else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
    5554              :             {
    5555        98894 :                 if (old_infomask2 & HEAP_KEYS_UPDATED)
    5556        92766 :                     old_status = MultiXactStatusForUpdate;
    5557              :                 else
    5558         6128 :                     old_status = MultiXactStatusForNoKeyUpdate;
    5559              :             }
    5560              :             else
    5561              :             {
    5562              :                 /*
    5563              :                  * LOCK_ONLY can be present alone only when a page has been
    5564              :                  * upgraded by pg_upgrade.  But in that case,
    5565              :                  * TransactionIdIsInProgress() should have returned false.  We
    5566              :                  * assume it's no longer locked in this case.
    5567              :                  */
    5568            0 :                 elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
    5569            0 :                 old_infomask |= HEAP_XMAX_INVALID;
    5570            0 :                 old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
    5571            0 :                 goto l5;
    5572              :             }
    5573              :         }
    5574              :         else
    5575              :         {
    5576              :             /* it's an update, but which kind? */
    5577           26 :             if (old_infomask2 & HEAP_KEYS_UPDATED)
    5578            0 :                 old_status = MultiXactStatusUpdate;
    5579              :             else
    5580           26 :                 old_status = MultiXactStatusNoKeyUpdate;
    5581              :         }
    5582              : 
    5583       105026 :         old_mode = TUPLOCK_from_mxstatus(old_status);
    5584              : 
    5585              :         /*
    5586              :          * If the lock to be acquired is for the same TransactionId as the
    5587              :          * existing lock, there's an optimization possible: consider only the
    5588              :          * strongest of both locks as the only one present, and restart.
    5589              :          */
    5590       105026 :         if (xmax == add_to_xmax)
    5591              :         {
    5592              :             /*
    5593              :              * Note that it's not possible for the original tuple to be
    5594              :              * updated: we wouldn't be here because the tuple would have been
    5595              :              * invisible and we wouldn't try to update it.  As a subtlety,
    5596              :              * this code can also run when traversing an update chain to lock
    5597              :              * future versions of a tuple.  But we wouldn't be here either,
    5598              :              * because the add_to_xmax would be different from the original
    5599              :              * updater.
    5600              :              */
    5601              :             Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
    5602              : 
    5603              :             /* acquire the strongest of both */
    5604       103954 :             if (mode < old_mode)
    5605        52200 :                 mode = old_mode;
    5606              :             /* mustn't touch is_update */
    5607              : 
    5608       103954 :             old_infomask |= HEAP_XMAX_INVALID;
    5609       103954 :             goto l5;
    5610              :         }
    5611              : 
    5612              :         /* otherwise, just fall back to creating a new multixact */
    5613         1072 :         new_status = get_mxact_status_for_lock(mode, is_update);
    5614         1072 :         new_xmax = MultiXactIdCreate(xmax, old_status,
    5615              :                                      add_to_xmax, new_status);
    5616         1072 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
    5617              :     }
    5618           14 :     else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
    5619            5 :              TransactionIdDidCommit(xmax))
    5620            1 :     {
    5621              :         /*
    5622              :          * It's a committed update, so we gotta preserve him as updater of the
    5623              :          * tuple.
    5624              :          */
    5625              :         MultiXactStatus status;
    5626              :         MultiXactStatus new_status;
    5627              : 
    5628            1 :         if (old_infomask2 & HEAP_KEYS_UPDATED)
    5629            0 :             status = MultiXactStatusUpdate;
    5630              :         else
    5631            1 :             status = MultiXactStatusNoKeyUpdate;
    5632              : 
    5633            1 :         new_status = get_mxact_status_for_lock(mode, is_update);
    5634              : 
    5635              :         /*
    5636              :          * since it's not running, it's obviously impossible for the old
    5637              :          * updater to be identical to the current one, so we need not check
    5638              :          * for that case as we do in the block above.
    5639              :          */
    5640            1 :         new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
    5641            1 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
    5642              :     }
    5643              :     else
    5644              :     {
    5645              :         /*
    5646              :          * Can get here iff the locking/updating transaction was running when
    5647              :          * the infomask was extracted from the tuple, but finished before
    5648              :          * TransactionIdIsInProgress got to run.  Deal with it as if there was
    5649              :          * no locker at all in the first place.
    5650              :          */
    5651            8 :         old_infomask |= HEAP_XMAX_INVALID;
    5652            8 :         goto l5;
    5653              :     }
    5654              : 
    5655      2147724 :     *result_infomask = new_infomask;
    5656      2147724 :     *result_infomask2 = new_infomask2;
    5657      2147724 :     *result_xmax = new_xmax;
    5658      2147724 : }
    5659              : 
    5660              : /*
    5661              :  * Subroutine for heap_lock_updated_tuple_rec.
    5662              :  *
    5663              :  * Given a hypothetical multixact status held by the transaction identified
    5664              :  * with the given xid, does the current transaction need to wait, fail, or can
    5665              :  * it continue if it wanted to acquire a lock of the given mode?  "needwait"
    5666              :  * is set to true if waiting is necessary; if it can continue, then TM_Ok is
    5667              :  * returned.  If the lock is already held by the current transaction, return
    5668              :  * TM_SelfModified.  In case of a conflict with another transaction, a
    5669              :  * different HeapTupleSatisfiesUpdate return code is returned.
    5670              :  *
    5671              :  * The held status is said to be hypothetical because it might correspond to a
    5672              :  * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
    5673              :  * way for simplicity of API.
    5674              :  */
    5675              : static TM_Result
    5676        38774 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
    5677              :                            LockTupleMode mode, HeapTuple tup,
    5678              :                            bool *needwait)
    5679              : {
    5680              :     MultiXactStatus wantedstatus;
    5681              : 
    5682        38774 :     *needwait = false;
    5683        38774 :     wantedstatus = get_mxact_status_for_lock(mode, false);
    5684              : 
    5685              :     /*
    5686              :      * Note: we *must* check TransactionIdIsInProgress before
    5687              :      * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
    5688              :      * for an explanation.
    5689              :      */
    5690        38774 :     if (TransactionIdIsCurrentTransactionId(xid))
    5691              :     {
    5692              :         /*
    5693              :          * The tuple has already been locked by our own transaction.  This is
    5694              :          * very rare but can happen if multiple transactions are trying to
    5695              :          * lock an ancient version of the same tuple.
    5696              :          */
    5697            0 :         return TM_SelfModified;
    5698              :     }
    5699        38774 :     else if (TransactionIdIsInProgress(xid))
    5700              :     {
    5701              :         /*
    5702              :          * If the locking transaction is running, what we do depends on
    5703              :          * whether the lock modes conflict: if they do, then we must wait for
    5704              :          * it to finish; otherwise we can fall through to lock this tuple
    5705              :          * version without waiting.
    5706              :          */
    5707        36539 :         if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
    5708        36539 :                                 LOCKMODE_from_mxstatus(wantedstatus)))
    5709              :         {
    5710            8 :             *needwait = true;
    5711              :         }
    5712              : 
    5713              :         /*
    5714              :          * If we set needwait above, then this value doesn't matter;
    5715              :          * otherwise, this value signals to caller that it's okay to proceed.
    5716              :          */
    5717        36539 :         return TM_Ok;
    5718              :     }
    5719         2235 :     else if (TransactionIdDidAbort(xid))
    5720          206 :         return TM_Ok;
    5721         2029 :     else if (TransactionIdDidCommit(xid))
    5722              :     {
    5723              :         /*
    5724              :          * The other transaction committed.  If it was only a locker, then the
    5725              :          * lock is completely gone now and we can return success; but if it
    5726              :          * was an update, then what we do depends on whether the two lock
    5727              :          * modes conflict.  If they conflict, then we must report error to
    5728              :          * caller. But if they don't, we can fall through to allow the current
    5729              :          * transaction to lock the tuple.
    5730              :          *
    5731              :          * Note: the reason we worry about ISUPDATE here is because as soon as
    5732              :          * a transaction ends, all its locks are gone and meaningless, and
    5733              :          * thus we can ignore them; whereas its updates persist.  In the
    5734              :          * TransactionIdIsInProgress case, above, we don't need to check
    5735              :          * because we know the lock is still "alive" and thus a conflict needs
    5736              :          * always be checked.
    5737              :          */
    5738         2029 :         if (!ISUPDATE_from_mxstatus(status))
    5739         2020 :             return TM_Ok;
    5740              : 
    5741            9 :         if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
    5742            9 :                                 LOCKMODE_from_mxstatus(wantedstatus)))
    5743              :         {
    5744              :             /* bummer */
    5745            8 :             if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
    5746            6 :                 return TM_Updated;
    5747              :             else
    5748            2 :                 return TM_Deleted;
    5749              :         }
    5750              : 
    5751            1 :         return TM_Ok;
    5752              :     }
    5753              : 
    5754              :     /* Not in progress, not aborted, not committed -- must have crashed */
    5755            0 :     return TM_Ok;
    5756              : }
    5757              : 
    5758              : 
    5759              : /*
    5760              :  * Recursive part of heap_lock_updated_tuple
    5761              :  *
    5762              :  * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
    5763              :  * xid with the given mode; if this tuple is updated, recurse to lock the new
    5764              :  * version as well.
    5765              :  */
    5766              : static TM_Result
    5767         2212 : heap_lock_updated_tuple_rec(Relation rel, TransactionId priorXmax,
    5768              :                             const ItemPointerData *tid, TransactionId xid,
    5769              :                             LockTupleMode mode)
    5770              : {
    5771              :     TM_Result   result;
    5772              :     ItemPointerData tupid;
    5773              :     HeapTupleData mytup;
    5774              :     Buffer      buf;
    5775              :     uint16      new_infomask,
    5776              :                 new_infomask2,
    5777              :                 old_infomask,
    5778              :                 old_infomask2;
    5779              :     TransactionId xmax,
    5780              :                 new_xmax;
    5781         2212 :     bool        cleared_all_frozen = false;
    5782              :     bool        pinned_desired_page;
    5783         2212 :     Buffer      vmbuffer = InvalidBuffer;
    5784              :     BlockNumber block;
    5785              : 
    5786         2212 :     ItemPointerCopy(tid, &tupid);
    5787              : 
    5788              :     for (;;)
    5789              :     {
    5790         2215 :         new_infomask = 0;
    5791         2215 :         new_xmax = InvalidTransactionId;
    5792         2215 :         block = ItemPointerGetBlockNumber(&tupid);
    5793         2215 :         ItemPointerCopy(&tupid, &(mytup.t_self));
    5794              : 
    5795         2215 :         if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
    5796              :         {
    5797              :             /*
    5798              :              * if we fail to find the updated version of the tuple, it's
    5799              :              * because it was vacuumed/pruned away after its creator
    5800              :              * transaction aborted.  So behave as if we got to the end of the
    5801              :              * chain, and there's no further tuple to lock: return success to
    5802              :              * caller.
    5803              :              */
    5804            0 :             result = TM_Ok;
    5805            0 :             goto out_unlocked;
    5806              :         }
    5807              : 
    5808         2215 : l4:
    5809         2223 :         CHECK_FOR_INTERRUPTS();
    5810              : 
    5811              :         /*
    5812              :          * Before locking the buffer, pin the visibility map page if it
    5813              :          * appears to be necessary.  Since we haven't got the lock yet,
    5814              :          * someone else might be in the middle of changing this, so we'll need
    5815              :          * to recheck after we have the lock.
    5816              :          */
    5817         2223 :         if (PageIsAllVisible(BufferGetPage(buf)))
    5818              :         {
    5819            0 :             visibilitymap_pin(rel, block, &vmbuffer);
    5820            0 :             pinned_desired_page = true;
    5821              :         }
    5822              :         else
    5823         2223 :             pinned_desired_page = false;
    5824              : 
    5825         2223 :         LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
    5826              : 
    5827              :         /*
    5828              :          * If we didn't pin the visibility map page and the page has become
    5829              :          * all visible while we were busy locking the buffer, we'll have to
    5830              :          * unlock and re-lock, to avoid holding the buffer lock across I/O.
    5831              :          * That's a bit unfortunate, but hopefully shouldn't happen often.
    5832              :          *
    5833              :          * Note: in some paths through this function, we will reach here
    5834              :          * holding a pin on a vm page that may or may not be the one matching
    5835              :          * this page.  If this page isn't all-visible, we won't use the vm
    5836              :          * page, but we hold onto such a pin till the end of the function.
    5837              :          */
    5838         2223 :         if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
    5839              :         {
    5840            0 :             LockBuffer(buf, BUFFER_LOCK_UNLOCK);
    5841            0 :             visibilitymap_pin(rel, block, &vmbuffer);
    5842            0 :             LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
    5843              :         }
    5844              : 
    5845              :         /*
    5846              :          * Check the tuple XMIN against prior XMAX, if any.  If we reached the
    5847              :          * end of the chain, we're done, so return success.
    5848              :          */
    5849         4446 :         if (TransactionIdIsValid(priorXmax) &&
    5850         2223 :             !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
    5851              :                                  priorXmax))
    5852              :         {
    5853            2 :             result = TM_Ok;
    5854            2 :             goto out_locked;
    5855              :         }
    5856              : 
    5857              :         /*
    5858              :          * Also check Xmin: if this tuple was created by an aborted
    5859              :          * (sub)transaction, then we already locked the last live one in the
    5860              :          * chain, thus we're done, so return success.
    5861              :          */
    5862         2221 :         if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
    5863              :         {
    5864           24 :             result = TM_Ok;
    5865           24 :             goto out_locked;
    5866              :         }
    5867              : 
    5868         2197 :         old_infomask = mytup.t_data->t_infomask;
    5869         2197 :         old_infomask2 = mytup.t_data->t_infomask2;
    5870         2197 :         xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
    5871              : 
    5872              :         /*
    5873              :          * If this tuple version has been updated or locked by some concurrent
    5874              :          * transaction(s), what we do depends on whether our lock mode
    5875              :          * conflicts with what those other transactions hold, and also on the
    5876              :          * status of them.
    5877              :          */
    5878         2197 :         if (!(old_infomask & HEAP_XMAX_INVALID))
    5879              :         {
    5880              :             TransactionId rawxmax;
    5881              :             bool        needwait;
    5882              : 
    5883         2138 :             rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
    5884         2138 :             if (old_infomask & HEAP_XMAX_IS_MULTI)
    5885              :             {
    5886              :                 int         nmembers;
    5887              :                 int         i;
    5888              :                 MultiXactMember *members;
    5889              : 
    5890              :                 /*
    5891              :                  * We don't need a test for pg_upgrade'd tuples: this is only
    5892              :                  * applied to tuples after the first in an update chain.  Said
    5893              :                  * first tuple in the chain may well be locked-in-9.2-and-
    5894              :                  * pg_upgraded, but that one was already locked by our caller,
    5895              :                  * not us; and any subsequent ones cannot be because our
    5896              :                  * caller must necessarily have obtained a snapshot later than
    5897              :                  * the pg_upgrade itself.
    5898              :                  */
    5899              :                 Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
    5900              : 
    5901         2109 :                 nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
    5902         2109 :                                                  HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
    5903        40854 :                 for (i = 0; i < nmembers; i++)
    5904              :                 {
    5905        38745 :                     result = test_lockmode_for_conflict(members[i].status,
    5906        38745 :                                                         members[i].xid,
    5907              :                                                         mode,
    5908              :                                                         &mytup,
    5909              :                                                         &needwait);
    5910              : 
    5911              :                     /*
    5912              :                      * If the tuple was already locked by ourselves in a
    5913              :                      * previous iteration of this (say heap_lock_tuple was
    5914              :                      * forced to restart the locking loop because of a change
    5915              :                      * in xmax), then we hold the lock already on this tuple
    5916              :                      * version and we don't need to do anything; and this is
    5917              :                      * not an error condition either.  We just need to skip
    5918              :                      * this tuple and continue locking the next version in the
    5919              :                      * update chain.
    5920              :                      */
    5921        38745 :                     if (result == TM_SelfModified)
    5922              :                     {
    5923            0 :                         pfree(members);
    5924            0 :                         goto next;
    5925              :                     }
    5926              : 
    5927        38745 :                     if (needwait)
    5928              :                     {
    5929            0 :                         LockBuffer(buf, BUFFER_LOCK_UNLOCK);
    5930            0 :                         XactLockTableWait(members[i].xid, rel,
    5931              :                                           &mytup.t_self,
    5932              :                                           XLTW_LockUpdated);
    5933            0 :                         pfree(members);
    5934            0 :                         goto l4;
    5935              :                     }
    5936        38745 :                     if (result != TM_Ok)
    5937              :                     {
    5938            0 :                         pfree(members);
    5939            0 :                         goto out_locked;
    5940              :                     }
    5941              :                 }
    5942         2109 :                 if (members)
    5943         2109 :                     pfree(members);
    5944              :             }
    5945              :             else
    5946              :             {
    5947              :                 MultiXactStatus status;
    5948              : 
    5949              :                 /*
    5950              :                  * For a non-multi Xmax, we first need to compute the
    5951              :                  * corresponding MultiXactStatus by using the infomask bits.
    5952              :                  */
    5953           29 :                 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
    5954              :                 {
    5955           10 :                     if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
    5956           10 :                         status = MultiXactStatusForKeyShare;
    5957            0 :                     else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
    5958            0 :                         status = MultiXactStatusForShare;
    5959            0 :                     else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
    5960              :                     {
    5961            0 :                         if (old_infomask2 & HEAP_KEYS_UPDATED)
    5962            0 :                             status = MultiXactStatusForUpdate;
    5963              :                         else
    5964            0 :                             status = MultiXactStatusForNoKeyUpdate;
    5965              :                     }
    5966              :                     else
    5967              :                     {
    5968              :                         /*
    5969              :                          * LOCK_ONLY present alone (a pg_upgraded tuple marked
    5970              :                          * as share-locked in the old cluster) shouldn't be
    5971              :                          * seen in the middle of an update chain.
    5972              :                          */
    5973            0 :                         elog(ERROR, "invalid lock status in tuple");
    5974              :                     }
    5975              :                 }
    5976              :                 else
    5977              :                 {
    5978              :                     /* it's an update, but which kind? */
    5979           19 :                     if (old_infomask2 & HEAP_KEYS_UPDATED)
    5980           14 :                         status = MultiXactStatusUpdate;
    5981              :                     else
    5982            5 :                         status = MultiXactStatusNoKeyUpdate;
    5983              :                 }
    5984              : 
    5985           29 :                 result = test_lockmode_for_conflict(status, rawxmax, mode,
    5986              :                                                     &mytup, &needwait);
    5987              : 
    5988              :                 /*
    5989              :                  * If the tuple was already locked by ourselves in a previous
    5990              :                  * iteration of this (say heap_lock_tuple was forced to
    5991              :                  * restart the locking loop because of a change in xmax), then
    5992              :                  * we hold the lock already on this tuple version and we don't
    5993              :                  * need to do anything; and this is not an error condition
    5994              :                  * either.  We just need to skip this tuple and continue
    5995              :                  * locking the next version in the update chain.
    5996              :                  */
    5997           29 :                 if (result == TM_SelfModified)
    5998            0 :                     goto next;
    5999              : 
    6000           29 :                 if (needwait)
    6001              :                 {
    6002            8 :                     LockBuffer(buf, BUFFER_LOCK_UNLOCK);
    6003            8 :                     XactLockTableWait(rawxmax, rel, &mytup.t_self,
    6004              :                                       XLTW_LockUpdated);
    6005            8 :                     goto l4;
    6006              :                 }
    6007           21 :                 if (result != TM_Ok)
    6008              :                 {
    6009            8 :                     goto out_locked;
    6010              :                 }
    6011              :             }
    6012              :         }
    6013              : 
    6014              :         /* compute the new Xmax and infomask values for the tuple ... */
    6015         2181 :         compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
    6016              :                                   xid, mode, false,
    6017              :                                   &new_xmax, &new_infomask, &new_infomask2);
    6018              : 
    6019         2181 :         if (PageIsAllVisible(BufferGetPage(buf)) &&
    6020            0 :             visibilitymap_clear(rel, block, vmbuffer,
    6021              :                                 VISIBILITYMAP_ALL_FROZEN))
    6022            0 :             cleared_all_frozen = true;
    6023              : 
    6024         2181 :         START_CRIT_SECTION();
    6025              : 
    6026              :         /* ... and set them */
    6027         2181 :         HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
    6028         2181 :         mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
    6029         2181 :         mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
    6030         2181 :         mytup.t_data->t_infomask |= new_infomask;
    6031         2181 :         mytup.t_data->t_infomask2 |= new_infomask2;
    6032              : 
    6033         2181 :         MarkBufferDirty(buf);
    6034              : 
    6035              :         /* XLOG stuff */
    6036         2181 :         if (RelationNeedsWAL(rel))
    6037              :         {
    6038              :             xl_heap_lock_updated xlrec;
    6039              :             XLogRecPtr  recptr;
    6040         2181 :             Page        page = BufferGetPage(buf);
    6041              : 
    6042         2181 :             XLogBeginInsert();
    6043         2181 :             XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
    6044              : 
    6045         2181 :             xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
    6046         2181 :             xlrec.xmax = new_xmax;
    6047         2181 :             xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
    6048         2181 :             xlrec.flags =
    6049         2181 :                 cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
    6050              : 
    6051         2181 :             XLogRegisterData(&xlrec, SizeOfHeapLockUpdated);
    6052              : 
    6053         2181 :             recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
    6054              : 
    6055         2181 :             PageSetLSN(page, recptr);
    6056              :         }
    6057              : 
    6058         2181 :         END_CRIT_SECTION();
    6059              : 
    6060         2181 : next:
    6061              :         /* if we find the end of update chain, we're done. */
    6062         4362 :         if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
    6063         4362 :             HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
    6064         2185 :             ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
    6065            4 :             HeapTupleHeaderIsOnlyLocked(mytup.t_data))
    6066              :         {
    6067         2178 :             result = TM_Ok;
    6068         2178 :             goto out_locked;
    6069              :         }
    6070              : 
    6071              :         /* tail recursion */
    6072            3 :         priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
    6073            3 :         ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
    6074            3 :         UnlockReleaseBuffer(buf);
    6075              :     }
    6076              : 
    6077              :     result = TM_Ok;
    6078              : 
    6079         2212 : out_locked:
    6080         2212 :     UnlockReleaseBuffer(buf);
    6081              : 
    6082         2212 : out_unlocked:
    6083         2212 :     if (vmbuffer != InvalidBuffer)
    6084            0 :         ReleaseBuffer(vmbuffer);
    6085              : 
    6086         2212 :     return result;
    6087              : }
    6088              : 
    6089              : /*
    6090              :  * heap_lock_updated_tuple
    6091              :  *      Follow update chain when locking an updated tuple, acquiring locks (row
    6092              :  *      marks) on the updated versions.
    6093              :  *
    6094              :  * 'prior_infomask', 'prior_raw_xmax' and 'prior_ctid' are the corresponding
    6095              :  * fields from the initial tuple.  We will lock the tuples starting from the
    6096              :  * one that 'prior_ctid' points to.  Note: This function does not lock the
    6097              :  * initial tuple itself.
    6098              :  *
    6099              :  * This function doesn't check visibility, it just unconditionally marks the
    6100              :  * tuple(s) as locked.  If any tuple in the updated chain is being deleted
    6101              :  * concurrently (or updated with the key being modified), sleep until the
    6102              :  * transaction doing it is finished.
    6103              :  *
    6104              :  * Note that we don't acquire heavyweight tuple locks on the tuples we walk
    6105              :  * when we have to wait for other transactions to release them, as opposed to
    6106              :  * what heap_lock_tuple does.  The reason is that having more than one
    6107              :  * transaction walking the chain is probably uncommon enough that risk of
    6108              :  * starvation is not likely: one of the preconditions for being here is that
    6109              :  * the snapshot in use predates the update that created this tuple (because we
    6110              :  * started at an earlier version of the tuple), but at the same time such a
    6111              :  * transaction cannot be using repeatable read or serializable isolation
    6112              :  * levels, because that would lead to a serializability failure.
    6113              :  */
    6114              : static TM_Result
    6115         2214 : heap_lock_updated_tuple(Relation rel,
    6116              :                         uint16 prior_infomask,
    6117              :                         TransactionId prior_raw_xmax,
    6118              :                         const ItemPointerData *prior_ctid,
    6119              :                         TransactionId xid, LockTupleMode mode)
    6120              : {
    6121         2214 :     INJECTION_POINT("heap_lock_updated_tuple", NULL);
    6122              : 
    6123              :     /*
    6124              :      * If the tuple has moved into another partition (effectively a delete)
    6125              :      * stop here.
    6126              :      */
    6127         2214 :     if (!ItemPointerIndicatesMovedPartitions(prior_ctid))
    6128              :     {
    6129              :         TransactionId prior_xmax;
    6130              : 
    6131              :         /*
    6132              :          * If this is the first possibly-multixact-able operation in the
    6133              :          * current transaction, set my per-backend OldestMemberMXactId
    6134              :          * setting. We can be certain that the transaction will never become a
    6135              :          * member of any older MultiXactIds than that.  (We have to do this
    6136              :          * even if we end up just using our own TransactionId below, since
    6137              :          * some other backend could incorporate our XID into a MultiXact
    6138              :          * immediately afterwards.)
    6139              :          */
    6140         2212 :         MultiXactIdSetOldestMember();
    6141              : 
    6142         4424 :         prior_xmax = (prior_infomask & HEAP_XMAX_IS_MULTI) ?
    6143         2212 :             MultiXactIdGetUpdateXid(prior_raw_xmax, prior_infomask) : prior_raw_xmax;
    6144         2212 :         return heap_lock_updated_tuple_rec(rel, prior_xmax, prior_ctid, xid, mode);
    6145              :     }
    6146              : 
    6147              :     /* nothing to lock */
    6148            2 :     return TM_Ok;
    6149              : }
    6150              : 
    6151              : /*
    6152              :  *  heap_finish_speculative - mark speculative insertion as successful
    6153              :  *
    6154              :  * To successfully finish a speculative insertion we have to clear speculative
    6155              :  * token from tuple.  To do so the t_ctid field, which will contain a
    6156              :  * speculative token value, is modified in place to point to the tuple itself,
    6157              :  * which is characteristic of a newly inserted ordinary tuple.
    6158              :  *
    6159              :  * NB: It is not ok to commit without either finishing or aborting a
    6160              :  * speculative insertion.  We could treat speculative tuples of committed
    6161              :  * transactions implicitly as completed, but then we would have to be prepared
    6162              :  * to deal with speculative tokens on committed tuples.  That wouldn't be
    6163              :  * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
    6164              :  * but clearing the token at completion isn't very expensive either.
    6165              :  * An explicit confirmation WAL record also makes logical decoding simpler.
    6166              :  */
    6167              : void
    6168         2118 : heap_finish_speculative(Relation relation, const ItemPointerData *tid)
    6169              : {
    6170              :     Buffer      buffer;
    6171              :     Page        page;
    6172              :     OffsetNumber offnum;
    6173              :     ItemId      lp;
    6174              :     HeapTupleHeader htup;
    6175              : 
    6176         2118 :     buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
    6177         2118 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    6178         2118 :     page = BufferGetPage(buffer);
    6179              : 
    6180         2118 :     offnum = ItemPointerGetOffsetNumber(tid);
    6181         2118 :     if (offnum < 1 || offnum > PageGetMaxOffsetNumber(page))
    6182            0 :         elog(ERROR, "offnum out of range");
    6183         2118 :     lp = PageGetItemId(page, offnum);
    6184         2118 :     if (!ItemIdIsNormal(lp))
    6185            0 :         elog(ERROR, "invalid lp");
    6186              : 
    6187         2118 :     htup = (HeapTupleHeader) PageGetItem(page, lp);
    6188              : 
    6189              :     /* NO EREPORT(ERROR) from here till changes are logged */
    6190         2118 :     START_CRIT_SECTION();
    6191              : 
    6192              :     Assert(HeapTupleHeaderIsSpeculative(htup));
    6193              : 
    6194         2118 :     MarkBufferDirty(buffer);
    6195              : 
    6196              :     /*
    6197              :      * Replace the speculative insertion token with a real t_ctid, pointing to
    6198              :      * itself like it does on regular tuples.
    6199              :      */
    6200         2118 :     htup->t_ctid = *tid;
    6201              : 
    6202              :     /* XLOG stuff */
    6203         2118 :     if (RelationNeedsWAL(relation))
    6204              :     {
    6205              :         xl_heap_confirm xlrec;
    6206              :         XLogRecPtr  recptr;
    6207              : 
    6208         2102 :         xlrec.offnum = ItemPointerGetOffsetNumber(tid);
    6209              : 
    6210         2102 :         XLogBeginInsert();
    6211              : 
    6212              :         /* We want the same filtering on this as on a plain insert */
    6213         2102 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
    6214              : 
    6215         2102 :         XLogRegisterData(&xlrec, SizeOfHeapConfirm);
    6216         2102 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
    6217              : 
    6218         2102 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
    6219              : 
    6220         2102 :         PageSetLSN(page, recptr);
    6221              :     }
    6222              : 
    6223         2118 :     END_CRIT_SECTION();
    6224              : 
    6225         2118 :     UnlockReleaseBuffer(buffer);
    6226         2118 : }
    6227              : 
    6228              : /*
    6229              :  *  heap_abort_speculative - kill a speculatively inserted tuple
    6230              :  *
    6231              :  * Marks a tuple that was speculatively inserted in the same command as dead,
    6232              :  * by setting its xmin as invalid.  That makes it immediately appear as dead
    6233              :  * to all transactions, including our own.  In particular, it makes
    6234              :  * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
    6235              :  * inserting a duplicate key value won't unnecessarily wait for our whole
    6236              :  * transaction to finish (it'll just wait for our speculative insertion to
    6237              :  * finish).
    6238              :  *
    6239              :  * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
    6240              :  * that arise due to a mutual dependency that is not user visible.  By
    6241              :  * definition, unprincipled deadlocks cannot be prevented by the user
    6242              :  * reordering lock acquisition in client code, because the implementation level
    6243              :  * lock acquisitions are not under the user's direct control.  If speculative
    6244              :  * inserters did not take this precaution, then under high concurrency they
    6245              :  * could deadlock with each other, which would not be acceptable.
    6246              :  *
    6247              :  * This is somewhat redundant with heap_delete, but we prefer to have a
    6248              :  * dedicated routine with stripped down requirements.  Note that this is also
    6249              :  * used to delete the TOAST tuples created during speculative insertion.
    6250              :  *
    6251              :  * This routine does not affect logical decoding as it only looks at
    6252              :  * confirmation records.
    6253              :  */
    6254              : void
    6255           16 : heap_abort_speculative(Relation relation, const ItemPointerData *tid)
    6256              : {
    6257           16 :     TransactionId xid = GetCurrentTransactionId();
    6258              :     ItemId      lp;
    6259              :     HeapTupleData tp;
    6260              :     Page        page;
    6261              :     BlockNumber block;
    6262              :     Buffer      buffer;
    6263              : 
    6264              :     Assert(ItemPointerIsValid(tid));
    6265              : 
    6266           16 :     block = ItemPointerGetBlockNumber(tid);
    6267           16 :     buffer = ReadBuffer(relation, block);
    6268           16 :     page = BufferGetPage(buffer);
    6269              : 
    6270           16 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    6271              : 
    6272              :     /*
    6273              :      * Page can't be all visible, we just inserted into it, and are still
    6274              :      * running.
    6275              :      */
    6276              :     Assert(!PageIsAllVisible(page));
    6277              : 
    6278           16 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
    6279              :     Assert(ItemIdIsNormal(lp));
    6280              : 
    6281           16 :     tp.t_tableOid = RelationGetRelid(relation);
    6282           16 :     tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
    6283           16 :     tp.t_len = ItemIdGetLength(lp);
    6284           16 :     tp.t_self = *tid;
    6285              : 
    6286              :     /*
    6287              :      * Sanity check that the tuple really is a speculatively inserted tuple,
    6288              :      * inserted by us.
    6289              :      */
    6290           16 :     if (tp.t_data->t_choice.t_heap.t_xmin != xid)
    6291            0 :         elog(ERROR, "attempted to kill a tuple inserted by another transaction");
    6292           16 :     if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
    6293            0 :         elog(ERROR, "attempted to kill a non-speculative tuple");
    6294              :     Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
    6295              : 
    6296              :     /*
    6297              :      * No need to check for serializable conflicts here.  There is never a
    6298              :      * need for a combo CID, either.  No need to extract replica identity, or
    6299              :      * do anything special with infomask bits.
    6300              :      */
    6301              : 
    6302           16 :     START_CRIT_SECTION();
    6303              : 
    6304              :     /*
    6305              :      * The tuple will become DEAD immediately.  Flag that this page is a
    6306              :      * candidate for pruning by setting xmin to TransactionXmin. While not
    6307              :      * immediately prunable, it is the oldest xid we can cheaply determine
    6308              :      * that's safe against wraparound / being older than the table's
    6309              :      * relfrozenxid.  To defend against the unlikely case of a new relation
    6310              :      * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
    6311              :      * if so (vacuum can't subsequently move relfrozenxid to beyond
    6312              :      * TransactionXmin, so there's no race here).
    6313              :      */
    6314              :     Assert(TransactionIdIsValid(TransactionXmin));
    6315              :     {
    6316           16 :         TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
    6317              :         TransactionId prune_xid;
    6318              : 
    6319           16 :         if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
    6320            0 :             prune_xid = relfrozenxid;
    6321              :         else
    6322           16 :             prune_xid = TransactionXmin;
    6323           16 :         PageSetPrunable(page, prune_xid);
    6324              :     }
    6325              : 
    6326              :     /* store transaction information of xact deleting the tuple */
    6327           16 :     tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
    6328           16 :     tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
    6329              : 
    6330              :     /*
    6331              :      * Set the tuple header xmin to InvalidTransactionId.  This makes the
    6332              :      * tuple immediately invisible everyone.  (In particular, to any
    6333              :      * transactions waiting on the speculative token, woken up later.)
    6334              :      */
    6335           16 :     HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
    6336              : 
    6337              :     /* Clear the speculative insertion token too */
    6338           16 :     tp.t_data->t_ctid = tp.t_self;
    6339              : 
    6340           16 :     MarkBufferDirty(buffer);
    6341              : 
    6342              :     /*
    6343              :      * XLOG stuff
    6344              :      *
    6345              :      * The WAL records generated here match heap_delete().  The same recovery
    6346              :      * routines are used.
    6347              :      */
    6348           16 :     if (RelationNeedsWAL(relation))
    6349              :     {
    6350              :         xl_heap_delete xlrec;
    6351              :         XLogRecPtr  recptr;
    6352              : 
    6353           12 :         xlrec.flags = XLH_DELETE_IS_SUPER;
    6354           24 :         xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
    6355           12 :                                               tp.t_data->t_infomask2);
    6356           12 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
    6357           12 :         xlrec.xmax = xid;
    6358              : 
    6359           12 :         XLogBeginInsert();
    6360           12 :         XLogRegisterData(&xlrec, SizeOfHeapDelete);
    6361           12 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
    6362              : 
    6363              :         /* No replica identity & replication origin logged */
    6364              : 
    6365           12 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
    6366              : 
    6367           12 :         PageSetLSN(page, recptr);
    6368              :     }
    6369              : 
    6370           16 :     END_CRIT_SECTION();
    6371              : 
    6372           16 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    6373              : 
    6374           16 :     if (HeapTupleHasExternal(&tp))
    6375              :     {
    6376              :         Assert(!IsToastRelation(relation));
    6377            1 :         heap_toast_delete(relation, &tp, true);
    6378              :     }
    6379              : 
    6380              :     /*
    6381              :      * Never need to mark tuple for invalidation, since catalogs don't support
    6382              :      * speculative insertion
    6383              :      */
    6384              : 
    6385              :     /* Now we can release the buffer */
    6386           16 :     ReleaseBuffer(buffer);
    6387              : 
    6388              :     /* count deletion, as we counted the insertion too */
    6389           16 :     pgstat_count_heap_delete(relation);
    6390           16 : }
    6391              : 
    6392              : /*
    6393              :  * heap_inplace_lock - protect inplace update from concurrent heap_update()
    6394              :  *
    6395              :  * Evaluate whether the tuple's state is compatible with a no-key update.
    6396              :  * Current transaction rowmarks are fine, as is KEY SHARE from any
    6397              :  * transaction.  If compatible, return true with the buffer exclusive-locked,
    6398              :  * and the caller must release that by calling
    6399              :  * heap_inplace_update_and_unlock(), calling heap_inplace_unlock(), or raising
    6400              :  * an error.  Otherwise, call release_callback(arg), wait for blocking
    6401              :  * transactions to end, and return false.
    6402              :  *
    6403              :  * Since this is intended for system catalogs and SERIALIZABLE doesn't cover
    6404              :  * DDL, this doesn't guarantee any particular predicate locking.
    6405              :  *
    6406              :  * heap_delete() is a rarer source of blocking transactions (xwait).  We'll
    6407              :  * wait for such a transaction just like for the normal heap_update() case.
    6408              :  * Normal concurrent DROP commands won't cause that, because all inplace
    6409              :  * updaters take some lock that conflicts with DROP.  An explicit SQL "DELETE
    6410              :  * FROM pg_class" can cause it.  By waiting, if the concurrent transaction
    6411              :  * executed both "DELETE FROM pg_class" and "INSERT INTO pg_class", our caller
    6412              :  * can find the successor tuple.
    6413              :  *
    6414              :  * Readers of inplace-updated fields expect changes to those fields are
    6415              :  * durable.  For example, vac_truncate_clog() reads datfrozenxid from
    6416              :  * pg_database tuples via catalog snapshots.  A future snapshot must not
    6417              :  * return a lower datfrozenxid for the same database OID (lower in the
    6418              :  * FullTransactionIdPrecedes() sense).  We achieve that since no update of a
    6419              :  * tuple can start while we hold a lock on its buffer.  In cases like
    6420              :  * BEGIN;GRANT;CREATE INDEX;COMMIT we're inplace-updating a tuple visible only
    6421              :  * to this transaction.  ROLLBACK then is one case where it's okay to lose
    6422              :  * inplace updates.  (Restoring relhasindex=false on ROLLBACK is fine, since
    6423              :  * any concurrent CREATE INDEX would have blocked, then inplace-updated the
    6424              :  * committed tuple.)
    6425              :  *
    6426              :  * In principle, we could avoid waiting by overwriting every tuple in the
    6427              :  * updated tuple chain.  Reader expectations permit updating a tuple only if
    6428              :  * it's aborted, is the tail of the chain, or we already updated the tuple
    6429              :  * referenced in its t_ctid.  Hence, we would need to overwrite the tuples in
    6430              :  * order from tail to head.  That would imply either (a) mutating all tuples
    6431              :  * in one critical section or (b) accepting a chance of partial completion.
    6432              :  * Partial completion of a relfrozenxid update would have the weird
    6433              :  * consequence that the table's next VACUUM could see the table's relfrozenxid
    6434              :  * move forward between vacuum_get_cutoffs() and finishing.
    6435              :  */
    6436              : bool
    6437       201829 : heap_inplace_lock(Relation relation,
    6438              :                   HeapTuple oldtup_ptr, Buffer buffer,
    6439              :                   void (*release_callback) (void *), void *arg)
    6440              : {
    6441       201829 :     HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
    6442              :     TM_Result   result;
    6443              :     bool        ret;
    6444              : 
    6445              : #ifdef USE_ASSERT_CHECKING
    6446              :     if (RelationGetRelid(relation) == RelationRelationId)
    6447              :         check_inplace_rel_lock(oldtup_ptr);
    6448              : #endif
    6449              : 
    6450              :     Assert(BufferIsValid(buffer));
    6451              : 
    6452              :     /*
    6453              :      * Register shared cache invals if necessary.  Other sessions may finish
    6454              :      * inplace updates of this tuple between this step and LockTuple().  Since
    6455              :      * inplace updates don't change cache keys, that's harmless.
    6456              :      *
    6457              :      * While it's tempting to register invals only after confirming we can
    6458              :      * return true, the following obstacle precludes reordering steps that
    6459              :      * way.  Registering invals might reach a CatalogCacheInitializeCache()
    6460              :      * that locks "buffer".  That would hang indefinitely if running after our
    6461              :      * own LockBuffer().  Hence, we must register invals before LockBuffer().
    6462              :      */
    6463       201829 :     CacheInvalidateHeapTupleInplace(relation, oldtup_ptr);
    6464              : 
    6465       201829 :     LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
    6466       201829 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
    6467              : 
    6468              :     /*----------
    6469              :      * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
    6470              :      *
    6471              :      * - wait unconditionally
    6472              :      * - already locked tuple above, since inplace needs that unconditionally
    6473              :      * - don't recheck header after wait: simpler to defer to next iteration
    6474              :      * - don't try to continue even if the updater aborts: likewise
    6475              :      * - no crosscheck
    6476              :      */
    6477       201829 :     result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
    6478              :                                       buffer);
    6479              : 
    6480       201829 :     if (result == TM_Invisible)
    6481              :     {
    6482              :         /* no known way this can happen */
    6483            0 :         ereport(ERROR,
    6484              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    6485              :                  errmsg_internal("attempted to overwrite invisible tuple")));
    6486              :     }
    6487       201829 :     else if (result == TM_SelfModified)
    6488              :     {
    6489              :         /*
    6490              :          * CREATE INDEX might reach this if an expression is silly enough to
    6491              :          * call e.g. SELECT ... FROM pg_class FOR SHARE.  C code of other SQL
    6492              :          * statements might get here after a heap_update() of the same row, in
    6493              :          * the absence of an intervening CommandCounterIncrement().
    6494              :          */
    6495            0 :         ereport(ERROR,
    6496              :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    6497              :                  errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
    6498              :     }
    6499       201829 :     else if (result == TM_BeingModified)
    6500              :     {
    6501              :         TransactionId xwait;
    6502              :         uint16      infomask;
    6503              : 
    6504           31 :         xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
    6505           31 :         infomask = oldtup.t_data->t_infomask;
    6506              : 
    6507           31 :         if (infomask & HEAP_XMAX_IS_MULTI)
    6508              :         {
    6509            5 :             LockTupleMode lockmode = LockTupleNoKeyExclusive;
    6510            5 :             MultiXactStatus mxact_status = MultiXactStatusNoKeyUpdate;
    6511              :             int         remain;
    6512              : 
    6513            5 :             if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
    6514              :                                         lockmode, NULL))
    6515              :             {
    6516            2 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    6517            2 :                 release_callback(arg);
    6518            2 :                 ret = false;
    6519            2 :                 MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
    6520              :                                 relation, &oldtup.t_self, XLTW_Update,
    6521              :                                 &remain);
    6522              :             }
    6523              :             else
    6524            3 :                 ret = true;
    6525              :         }
    6526           26 :         else if (TransactionIdIsCurrentTransactionId(xwait))
    6527            1 :             ret = true;
    6528           25 :         else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
    6529            1 :             ret = true;
    6530              :         else
    6531              :         {
    6532           24 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    6533           24 :             release_callback(arg);
    6534           24 :             ret = false;
    6535           24 :             XactLockTableWait(xwait, relation, &oldtup.t_self,
    6536              :                               XLTW_Update);
    6537              :         }
    6538              :     }
    6539              :     else
    6540              :     {
    6541       201798 :         ret = (result == TM_Ok);
    6542       201798 :         if (!ret)
    6543              :         {
    6544            0 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    6545            0 :             release_callback(arg);
    6546              :         }
    6547              :     }
    6548              : 
    6549              :     /*
    6550              :      * GetCatalogSnapshot() relies on invalidation messages to know when to
    6551              :      * take a new snapshot.  COMMIT of xwait is responsible for sending the
    6552              :      * invalidation.  We're not acquiring heavyweight locks sufficient to
    6553              :      * block if not yet sent, so we must take a new snapshot to ensure a later
    6554              :      * attempt has a fair chance.  While we don't need this if xwait aborted,
    6555              :      * don't bother optimizing that.
    6556              :      */
    6557       201829 :     if (!ret)
    6558              :     {
    6559           26 :         UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
    6560           26 :         ForgetInplace_Inval();
    6561           26 :         InvalidateCatalogSnapshot();
    6562              :     }
    6563       201829 :     return ret;
    6564              : }
    6565              : 
    6566              : /*
    6567              :  * heap_inplace_update_and_unlock - core of systable_inplace_update_finish
    6568              :  *
    6569              :  * The tuple cannot change size, and therefore its header fields and null
    6570              :  * bitmap (if any) don't change either.
    6571              :  *
    6572              :  * Since we hold LOCKTAG_TUPLE, no updater has a local copy of this tuple.
    6573              :  */
    6574              : void
    6575        83943 : heap_inplace_update_and_unlock(Relation relation,
    6576              :                                HeapTuple oldtup, HeapTuple tuple,
    6577              :                                Buffer buffer)
    6578              : {
    6579        83943 :     HeapTupleHeader htup = oldtup->t_data;
    6580              :     uint32      oldlen;
    6581              :     uint32      newlen;
    6582              :     char       *dst;
    6583              :     char       *src;
    6584        83943 :     int         nmsgs = 0;
    6585        83943 :     SharedInvalidationMessage *invalMessages = NULL;
    6586        83943 :     bool        RelcacheInitFileInval = false;
    6587              : 
    6588              :     Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
    6589        83943 :     oldlen = oldtup->t_len - htup->t_hoff;
    6590        83943 :     newlen = tuple->t_len - tuple->t_data->t_hoff;
    6591        83943 :     if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
    6592            0 :         elog(ERROR, "wrong tuple length");
    6593              : 
    6594        83943 :     dst = (char *) htup + htup->t_hoff;
    6595        83943 :     src = (char *) tuple->t_data + tuple->t_data->t_hoff;
    6596              : 
    6597              :     /* Like RecordTransactionCommit(), log only if needed */
    6598        83943 :     if (XLogStandbyInfoActive())
    6599        58673 :         nmsgs = inplaceGetInvalidationMessages(&invalMessages,
    6600              :                                                &RelcacheInitFileInval);
    6601              : 
    6602              :     /*
    6603              :      * Unlink relcache init files as needed.  If unlinking, acquire
    6604              :      * RelCacheInitLock until after associated invalidations.  By doing this
    6605              :      * in advance, if we checkpoint and then crash between inplace
    6606              :      * XLogInsert() and inval, we don't rely on StartupXLOG() ->
    6607              :      * RelationCacheInitFileRemove().  That uses elevel==LOG, so replay would
    6608              :      * neglect to PANIC on EIO.
    6609              :      */
    6610        83943 :     PreInplace_Inval();
    6611              : 
    6612              :     /*----------
    6613              :      * NO EREPORT(ERROR) from here till changes are complete
    6614              :      *
    6615              :      * Our buffer lock won't stop a reader having already pinned and checked
    6616              :      * visibility for this tuple.  Hence, we write WAL first, then mutate the
    6617              :      * buffer.  Like in MarkBufferDirtyHint() or RecordTransactionCommit(),
    6618              :      * checkpoint delay makes that acceptable.  With the usual order of
    6619              :      * changes, a crash after memcpy() and before XLogInsert() could allow
    6620              :      * datfrozenxid to overtake relfrozenxid:
    6621              :      *
    6622              :      * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
    6623              :      * ["R" is a VACUUM tbl]
    6624              :      * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
    6625              :      * D: systable_getnext() returns pg_class tuple of tbl
    6626              :      * R: memcpy() into pg_class tuple of tbl
    6627              :      * D: raise pg_database.datfrozenxid, XLogInsert(), finish
    6628              :      * [crash]
    6629              :      * [recovery restores datfrozenxid w/o relfrozenxid]
    6630              :      *
    6631              :      * Mimic MarkBufferDirtyHint() subroutine XLogSaveBufferForHint().
    6632              :      * Specifically, use DELAY_CHKPT_START, and copy the buffer to the stack.
    6633              :      * The stack copy facilitates a FPI of the post-mutation block before we
    6634              :      * accept other sessions seeing it.  DELAY_CHKPT_START allows us to
    6635              :      * XLogInsert() before MarkBufferDirty().  Since XLogSaveBufferForHint()
    6636              :      * can operate under BUFFER_LOCK_SHARED, it can't avoid DELAY_CHKPT_START.
    6637              :      * This function, however, likely could avoid it with the following order
    6638              :      * of operations: MarkBufferDirty(), XLogInsert(), memcpy().  Opt to use
    6639              :      * DELAY_CHKPT_START here, too, as a way to have fewer distinct code
    6640              :      * patterns to analyze.  Inplace update isn't so frequent that it should
    6641              :      * pursue the small optimization of skipping DELAY_CHKPT_START.
    6642              :      */
    6643              :     Assert((MyProc->delayChkptFlags & DELAY_CHKPT_START) == 0);
    6644        83943 :     START_CRIT_SECTION();
    6645        83943 :     MyProc->delayChkptFlags |= DELAY_CHKPT_START;
    6646              : 
    6647              :     /* XLOG stuff */
    6648        83943 :     if (RelationNeedsWAL(relation))
    6649              :     {
    6650              :         xl_heap_inplace xlrec;
    6651              :         PGAlignedBlock copied_buffer;
    6652        83939 :         char       *origdata = (char *) BufferGetBlock(buffer);
    6653        83939 :         Page        page = BufferGetPage(buffer);
    6654        83939 :         uint16      lower = ((PageHeader) page)->pd_lower;
    6655        83939 :         uint16      upper = ((PageHeader) page)->pd_upper;
    6656              :         uintptr_t   dst_offset_in_block;
    6657              :         RelFileLocator rlocator;
    6658              :         ForkNumber  forkno;
    6659              :         BlockNumber blkno;
    6660              :         XLogRecPtr  recptr;
    6661              : 
    6662        83939 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
    6663        83939 :         xlrec.dbId = MyDatabaseId;
    6664        83939 :         xlrec.tsId = MyDatabaseTableSpace;
    6665        83939 :         xlrec.relcacheInitFileInval = RelcacheInitFileInval;
    6666        83939 :         xlrec.nmsgs = nmsgs;
    6667              : 
    6668        83939 :         XLogBeginInsert();
    6669        83939 :         XLogRegisterData(&xlrec, MinSizeOfHeapInplace);
    6670        83939 :         if (nmsgs != 0)
    6671        43730 :             XLogRegisterData(invalMessages,
    6672              :                              nmsgs * sizeof(SharedInvalidationMessage));
    6673              : 
    6674              :         /* register block matching what buffer will look like after changes */
    6675        83939 :         memcpy(copied_buffer.data, origdata, lower);
    6676        83939 :         memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
    6677        83939 :         dst_offset_in_block = dst - origdata;
    6678        83939 :         memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
    6679        83939 :         BufferGetTag(buffer, &rlocator, &forkno, &blkno);
    6680              :         Assert(forkno == MAIN_FORKNUM);
    6681        83939 :         XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
    6682              :                           REGBUF_STANDARD);
    6683        83939 :         XLogRegisterBufData(0, src, newlen);
    6684              : 
    6685              :         /* inplace updates aren't decoded atm, don't log the origin */
    6686              : 
    6687        83939 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
    6688              : 
    6689        83939 :         PageSetLSN(page, recptr);
    6690              :     }
    6691              : 
    6692        83943 :     memcpy(dst, src, newlen);
    6693              : 
    6694        83943 :     MarkBufferDirty(buffer);
    6695              : 
    6696        83943 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    6697              : 
    6698              :     /*
    6699              :      * Send invalidations to shared queue.  SearchSysCacheLocked1() assumes we
    6700              :      * do this before UnlockTuple().
    6701              :      */
    6702        83943 :     AtInplace_Inval();
    6703              : 
    6704        83943 :     MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
    6705        83943 :     END_CRIT_SECTION();
    6706        83943 :     UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
    6707              : 
    6708        83943 :     AcceptInvalidationMessages();   /* local processing of just-sent inval */
    6709              : 
    6710              :     /*
    6711              :      * Queue a transactional inval, for logical decoding and for third-party
    6712              :      * code that might have been relying on it since long before inplace
    6713              :      * update adopted immediate invalidation.  See README.tuplock section
    6714              :      * "Reading inplace-updated columns" for logical decoding details.
    6715              :      */
    6716        83943 :     if (!IsBootstrapProcessingMode())
    6717        69000 :         CacheInvalidateHeapTuple(relation, tuple, NULL);
    6718        83943 : }
    6719              : 
    6720              : /*
    6721              :  * heap_inplace_unlock - reverse of heap_inplace_lock
    6722              :  */
    6723              : void
    6724       117860 : heap_inplace_unlock(Relation relation,
    6725              :                     HeapTuple oldtup, Buffer buffer)
    6726              : {
    6727       117860 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
    6728       117860 :     UnlockTuple(relation, &oldtup->t_self, InplaceUpdateTupleLock);
    6729       117860 :     ForgetInplace_Inval();
    6730       117860 : }
    6731              : 
    6732              : #define     FRM_NOOP                0x0001
    6733              : #define     FRM_INVALIDATE_XMAX     0x0002
    6734              : #define     FRM_RETURN_IS_XID       0x0004
    6735              : #define     FRM_RETURN_IS_MULTI     0x0008
    6736              : #define     FRM_MARK_COMMITTED      0x0010
    6737              : 
    6738              : /*
    6739              :  * FreezeMultiXactId
    6740              :  *      Determine what to do during freezing when a tuple is marked by a
    6741              :  *      MultiXactId.
    6742              :  *
    6743              :  * "flags" is an output value; it's used to tell caller what to do on return.
    6744              :  * "pagefrz" is an input/output value, used to manage page level freezing.
    6745              :  *
    6746              :  * Possible values that we can set in "flags":
    6747              :  * FRM_NOOP
    6748              :  *      don't do anything -- keep existing Xmax
    6749              :  * FRM_INVALIDATE_XMAX
    6750              :  *      mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
    6751              :  * FRM_RETURN_IS_XID
    6752              :  *      The Xid return value is a single update Xid to set as xmax.
    6753              :  * FRM_MARK_COMMITTED
    6754              :  *      Xmax can be marked as HEAP_XMAX_COMMITTED
    6755              :  * FRM_RETURN_IS_MULTI
    6756              :  *      The return value is a new MultiXactId to set as new Xmax.
    6757              :  *      (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
    6758              :  *
    6759              :  * Caller delegates control of page freezing to us.  In practice we always
    6760              :  * force freezing of caller's page unless FRM_NOOP processing is indicated.
    6761              :  * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
    6762              :  * can never be left behind.  We freely choose when and how to process each
    6763              :  * Multi, without ever violating the cutoff postconditions for freezing.
    6764              :  *
    6765              :  * It's useful to remove Multis on a proactive timeline (relative to freezing
    6766              :  * XIDs) to keep MultiXact member SLRU buffer misses to a minimum.  It can also
    6767              :  * be cheaper in the short run, for us, since we too can avoid SLRU buffer
    6768              :  * misses through eager processing.
    6769              :  *
    6770              :  * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
    6771              :  * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
    6772              :  * This can usually be put off, which is usually enough to avoid it altogether.
    6773              :  * Allocating new multis during VACUUM should be avoided on general principle;
    6774              :  * only VACUUM can advance relminmxid, so allocating new Multis here comes with
    6775              :  * its own special risks.
    6776              :  *
    6777              :  * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
    6778              :  * using heap_tuple_should_freeze when we haven't forced page-level freezing.
    6779              :  *
    6780              :  * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
    6781              :  * have already forced page-level freezing, since that might incur the same
    6782              :  * SLRU buffer misses that we specifically intended to avoid by freezing.
    6783              :  */
    6784              : static TransactionId
    6785            6 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
    6786              :                   const struct VacuumCutoffs *cutoffs, uint16 *flags,
    6787              :                   HeapPageFreeze *pagefrz)
    6788              : {
    6789              :     TransactionId newxmax;
    6790              :     MultiXactMember *members;
    6791              :     int         nmembers;
    6792              :     bool        need_replace;
    6793              :     int         nnewmembers;
    6794              :     MultiXactMember *newmembers;
    6795              :     bool        has_lockers;
    6796              :     TransactionId update_xid;
    6797              :     bool        update_committed;
    6798              :     TransactionId FreezePageRelfrozenXid;
    6799              : 
    6800            6 :     *flags = 0;
    6801              : 
    6802              :     /* We should only be called in Multis */
    6803              :     Assert(t_infomask & HEAP_XMAX_IS_MULTI);
    6804              : 
    6805           12 :     if (!MultiXactIdIsValid(multi) ||
    6806            6 :         HEAP_LOCKED_UPGRADED(t_infomask))
    6807              :     {
    6808            0 :         *flags |= FRM_INVALIDATE_XMAX;
    6809            0 :         pagefrz->freeze_required = true;
    6810            0 :         return InvalidTransactionId;
    6811              :     }
    6812            6 :     else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
    6813            0 :         ereport(ERROR,
    6814              :                 (errcode(ERRCODE_DATA_CORRUPTED),
    6815              :                  errmsg_internal("found multixact %u from before relminmxid %u",
    6816              :                                  multi, cutoffs->relminmxid)));
    6817            6 :     else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
    6818              :     {
    6819              :         TransactionId update_xact;
    6820              : 
    6821              :         /*
    6822              :          * This old multi cannot possibly have members still running, but
    6823              :          * verify just in case.  If it was a locker only, it can be removed
    6824              :          * without any further consideration; but if it contained an update,
    6825              :          * we might need to preserve it.
    6826              :          */
    6827            4 :         if (MultiXactIdIsRunning(multi,
    6828            4 :                                  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
    6829            0 :             ereport(ERROR,
    6830              :                     (errcode(ERRCODE_DATA_CORRUPTED),
    6831              :                      errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
    6832              :                                      multi, cutoffs->OldestMxact)));
    6833              : 
    6834            4 :         if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
    6835              :         {
    6836            4 :             *flags |= FRM_INVALIDATE_XMAX;
    6837            4 :             pagefrz->freeze_required = true;
    6838            4 :             return InvalidTransactionId;
    6839              :         }
    6840              : 
    6841              :         /* replace multi with single XID for its updater? */
    6842            0 :         update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
    6843            0 :         if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
    6844            0 :             ereport(ERROR,
    6845              :                     (errcode(ERRCODE_DATA_CORRUPTED),
    6846              :                      errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
    6847              :                                      multi, update_xact,
    6848              :                                      cutoffs->relfrozenxid)));
    6849            0 :         else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
    6850              :         {
    6851              :             /*
    6852              :              * Updater XID has to have aborted (otherwise the tuple would have
    6853              :              * been pruned away instead, since updater XID is < OldestXmin).
    6854              :              * Just remove xmax.
    6855              :              */
    6856            0 :             if (TransactionIdDidCommit(update_xact))
    6857            0 :                 ereport(ERROR,
    6858              :                         (errcode(ERRCODE_DATA_CORRUPTED),
    6859              :                          errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
    6860              :                                          multi, update_xact,
    6861              :                                          cutoffs->OldestXmin)));
    6862            0 :             *flags |= FRM_INVALIDATE_XMAX;
    6863            0 :             pagefrz->freeze_required = true;
    6864            0 :             return InvalidTransactionId;
    6865              :         }
    6866              : 
    6867              :         /* Have to keep updater XID as new xmax */
    6868            0 :         *flags |= FRM_RETURN_IS_XID;
    6869            0 :         pagefrz->freeze_required = true;
    6870            0 :         return update_xact;
    6871              :     }
    6872              : 
    6873              :     /*
    6874              :      * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
    6875              :      * need to walk the whole members array to figure out what to do, if
    6876              :      * anything.
    6877              :      */
    6878              :     nmembers =
    6879            2 :         GetMultiXactIdMembers(multi, &members, false,
    6880            2 :                               HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
    6881            2 :     if (nmembers <= 0)
    6882              :     {
    6883              :         /* Nothing worth keeping */
    6884            0 :         *flags |= FRM_INVALIDATE_XMAX;
    6885            0 :         pagefrz->freeze_required = true;
    6886            0 :         return InvalidTransactionId;
    6887              :     }
    6888              : 
    6889              :     /*
    6890              :      * The FRM_NOOP case is the only case where we might need to ratchet back
    6891              :      * FreezePageRelfrozenXid or FreezePageRelminMxid.  It is also the only
    6892              :      * case where our caller might ratchet back its NoFreezePageRelfrozenXid
    6893              :      * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
    6894              :      * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
    6895              :      * trackers managed by VACUUM being ratcheting back by xmax to the degree
    6896              :      * required to make it safe to leave xmax undisturbed, independent of
    6897              :      * whether or not page freezing is triggered somewhere else.
    6898              :      *
    6899              :      * Our policy is to force freezing in every case other than FRM_NOOP,
    6900              :      * which obviates the need to maintain either set of trackers, anywhere.
    6901              :      * Every other case will reliably execute a freeze plan for xmax that
    6902              :      * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
    6903              :      * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
    6904              :      * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
    6905              :      * OldestXmin/OldestMxact, so later values never need to be tracked here.)
    6906              :      */
    6907            2 :     need_replace = false;
    6908            2 :     FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
    6909            4 :     for (int i = 0; i < nmembers; i++)
    6910              :     {
    6911            3 :         TransactionId xid = members[i].xid;
    6912              : 
    6913              :         Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
    6914              : 
    6915            3 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
    6916              :         {
    6917              :             /* Can't violate the FreezeLimit postcondition */
    6918            1 :             need_replace = true;
    6919            1 :             break;
    6920              :         }
    6921            2 :         if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
    6922            0 :             FreezePageRelfrozenXid = xid;
    6923              :     }
    6924              : 
    6925              :     /* Can't violate the MultiXactCutoff postcondition, either */
    6926            2 :     if (!need_replace)
    6927            1 :         need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
    6928              : 
    6929            2 :     if (!need_replace)
    6930              :     {
    6931              :         /*
    6932              :          * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
    6933              :          * both together to make it safe to retain this particular multi after
    6934              :          * freezing its page
    6935              :          */
    6936            1 :         *flags |= FRM_NOOP;
    6937            1 :         pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
    6938            1 :         if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
    6939            0 :             pagefrz->FreezePageRelminMxid = multi;
    6940            1 :         pfree(members);
    6941            1 :         return multi;
    6942              :     }
    6943              : 
    6944              :     /*
    6945              :      * Do a more thorough second pass over the multi to figure out which
    6946              :      * member XIDs actually need to be kept.  Checking the precise status of
    6947              :      * individual members might even show that we don't need to keep anything.
    6948              :      * That is quite possible even though the Multi must be >= OldestMxact,
    6949              :      * since our second pass only keeps member XIDs when it's truly necessary;
    6950              :      * even member XIDs >= OldestXmin often won't be kept by second pass.
    6951              :      */
    6952            1 :     nnewmembers = 0;
    6953            1 :     newmembers = palloc_array(MultiXactMember, nmembers);
    6954            1 :     has_lockers = false;
    6955            1 :     update_xid = InvalidTransactionId;
    6956            1 :     update_committed = false;
    6957              : 
    6958              :     /*
    6959              :      * Determine whether to keep each member xid, or to ignore it instead
    6960              :      */
    6961            3 :     for (int i = 0; i < nmembers; i++)
    6962              :     {
    6963            2 :         TransactionId xid = members[i].xid;
    6964            2 :         MultiXactStatus mstatus = members[i].status;
    6965              : 
    6966              :         Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
    6967              : 
    6968            2 :         if (!ISUPDATE_from_mxstatus(mstatus))
    6969              :         {
    6970              :             /*
    6971              :              * Locker XID (not updater XID).  We only keep lockers that are
    6972              :              * still running.
    6973              :              */
    6974            4 :             if (TransactionIdIsCurrentTransactionId(xid) ||
    6975            2 :                 TransactionIdIsInProgress(xid))
    6976              :             {
    6977            1 :                 if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
    6978            0 :                     ereport(ERROR,
    6979              :                             (errcode(ERRCODE_DATA_CORRUPTED),
    6980              :                              errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
    6981              :                                              multi, xid,
    6982              :                                              cutoffs->OldestXmin)));
    6983            1 :                 newmembers[nnewmembers++] = members[i];
    6984            1 :                 has_lockers = true;
    6985              :             }
    6986              : 
    6987            2 :             continue;
    6988              :         }
    6989              : 
    6990              :         /*
    6991              :          * Updater XID (not locker XID).  Should we keep it?
    6992              :          *
    6993              :          * Since the tuple wasn't totally removed when vacuum pruned, the
    6994              :          * update Xid cannot possibly be older than OldestXmin cutoff unless
    6995              :          * the updater XID aborted.  If the updater transaction is known
    6996              :          * aborted or crashed then it's okay to ignore it, otherwise not.
    6997              :          *
    6998              :          * In any case the Multi should never contain two updaters, whatever
    6999              :          * their individual commit status.  Check for that first, in passing.
    7000              :          */
    7001            0 :         if (TransactionIdIsValid(update_xid))
    7002            0 :             ereport(ERROR,
    7003              :                     (errcode(ERRCODE_DATA_CORRUPTED),
    7004              :                      errmsg_internal("multixact %u has two or more updating members",
    7005              :                                      multi),
    7006              :                      errdetail_internal("First updater XID=%u second updater XID=%u.",
    7007              :                                         update_xid, xid)));
    7008              : 
    7009              :         /*
    7010              :          * As with all tuple visibility routines, it's critical to test
    7011              :          * TransactionIdIsInProgress before TransactionIdDidCommit, because of
    7012              :          * race conditions explained in detail in heapam_visibility.c.
    7013              :          */
    7014            0 :         if (TransactionIdIsCurrentTransactionId(xid) ||
    7015            0 :             TransactionIdIsInProgress(xid))
    7016            0 :             update_xid = xid;
    7017            0 :         else if (TransactionIdDidCommit(xid))
    7018              :         {
    7019              :             /*
    7020              :              * The transaction committed, so we can tell caller to set
    7021              :              * HEAP_XMAX_COMMITTED.  (We can only do this because we know the
    7022              :              * transaction is not running.)
    7023              :              */
    7024            0 :             update_committed = true;
    7025            0 :             update_xid = xid;
    7026              :         }
    7027              :         else
    7028              :         {
    7029              :             /*
    7030              :              * Not in progress, not committed -- must be aborted or crashed;
    7031              :              * we can ignore it.
    7032              :              */
    7033            0 :             continue;
    7034              :         }
    7035              : 
    7036              :         /*
    7037              :          * We determined that updater must be kept -- add it to pending new
    7038              :          * members list
    7039              :          */
    7040            0 :         if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
    7041            0 :             ereport(ERROR,
    7042              :                     (errcode(ERRCODE_DATA_CORRUPTED),
    7043              :                      errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
    7044              :                                      multi, xid, cutoffs->OldestXmin)));
    7045            0 :         newmembers[nnewmembers++] = members[i];
    7046              :     }
    7047              : 
    7048            1 :     pfree(members);
    7049              : 
    7050              :     /*
    7051              :      * Determine what to do with caller's multi based on information gathered
    7052              :      * during our second pass
    7053              :      */
    7054            1 :     if (nnewmembers == 0)
    7055              :     {
    7056              :         /* Nothing worth keeping */
    7057            0 :         *flags |= FRM_INVALIDATE_XMAX;
    7058            0 :         newxmax = InvalidTransactionId;
    7059              :     }
    7060            1 :     else if (TransactionIdIsValid(update_xid) && !has_lockers)
    7061              :     {
    7062              :         /*
    7063              :          * If there's a single member and it's an update, pass it back alone
    7064              :          * without creating a new Multi.  (XXX we could do this when there's a
    7065              :          * single remaining locker, too, but that would complicate the API too
    7066              :          * much; moreover, the case with the single updater is more
    7067              :          * interesting, because those are longer-lived.)
    7068              :          */
    7069              :         Assert(nnewmembers == 1);
    7070            0 :         *flags |= FRM_RETURN_IS_XID;
    7071            0 :         if (update_committed)
    7072            0 :             *flags |= FRM_MARK_COMMITTED;
    7073            0 :         newxmax = update_xid;
    7074              :     }
    7075              :     else
    7076              :     {
    7077              :         /*
    7078              :          * Create a new multixact with the surviving members of the previous
    7079              :          * one, to set as new Xmax in the tuple
    7080              :          */
    7081            1 :         newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
    7082            1 :         *flags |= FRM_RETURN_IS_MULTI;
    7083              :     }
    7084              : 
    7085            1 :     pfree(newmembers);
    7086              : 
    7087            1 :     pagefrz->freeze_required = true;
    7088            1 :     return newxmax;
    7089              : }
    7090              : 
    7091              : /*
    7092              :  * heap_prepare_freeze_tuple
    7093              :  *
    7094              :  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
    7095              :  * are older than the OldestXmin and/or OldestMxact freeze cutoffs.  If so,
    7096              :  * setup enough state (in the *frz output argument) to enable caller to
    7097              :  * process this tuple as part of freezing its page, and return true.  Return
    7098              :  * false if nothing can be changed about the tuple right now.
    7099              :  *
    7100              :  * Also sets *totally_frozen to true if the tuple will be totally frozen once
    7101              :  * caller executes returned freeze plan (or if the tuple was already totally
    7102              :  * frozen by an earlier VACUUM).  This indicates that there are no remaining
    7103              :  * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
    7104              :  *
    7105              :  * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
    7106              :  * tuple that we returned true for, and then execute freezing.  Caller must
    7107              :  * initialize pagefrz fields for page as a whole before first call here for
    7108              :  * each heap page.
    7109              :  *
    7110              :  * VACUUM caller decides on whether or not to freeze the page as a whole.
    7111              :  * We'll often prepare freeze plans for a page that caller just discards.
    7112              :  * However, VACUUM doesn't always get to make a choice; it must freeze when
    7113              :  * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
    7114              :  * MXIDs < MultiXactCutoff) can never be left behind.  We help to make sure
    7115              :  * that VACUUM always follows that rule.
    7116              :  *
    7117              :  * We sometimes force freezing of xmax MultiXactId values long before it is
    7118              :  * strictly necessary to do so just to ensure the FreezeLimit postcondition.
    7119              :  * It's worth processing MultiXactIds proactively when it is cheap to do so,
    7120              :  * and it's convenient to make that happen by piggy-backing it on the "force
    7121              :  * freezing" mechanism.  Conversely, we sometimes delay freezing MultiXactIds
    7122              :  * because it is expensive right now (though only when it's still possible to
    7123              :  * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
    7124              :  *
    7125              :  * It is assumed that the caller has checked the tuple with
    7126              :  * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
    7127              :  * (else we should be removing the tuple, not freezing it).
    7128              :  *
    7129              :  * NB: This function has side effects: it might allocate a new MultiXactId.
    7130              :  * It will be set as tuple's new xmax when our *frz output is processed within
    7131              :  * heap_execute_freeze_tuple later on.  If the tuple is in a shared buffer
    7132              :  * then caller had better have an exclusive lock on it already.
    7133              :  */
    7134              : bool
    7135     23037084 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
    7136              :                           const struct VacuumCutoffs *cutoffs,
    7137              :                           HeapPageFreeze *pagefrz,
    7138              :                           HeapTupleFreeze *frz, bool *totally_frozen)
    7139              : {
    7140     23037084 :     bool        xmin_already_frozen = false,
    7141     23037084 :                 xmax_already_frozen = false;
    7142     23037084 :     bool        freeze_xmin = false,
    7143     23037084 :                 replace_xvac = false,
    7144     23037084 :                 replace_xmax = false,
    7145     23037084 :                 freeze_xmax = false;
    7146              :     TransactionId xid;
    7147              : 
    7148     23037084 :     frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
    7149     23037084 :     frz->t_infomask2 = tuple->t_infomask2;
    7150     23037084 :     frz->t_infomask = tuple->t_infomask;
    7151     23037084 :     frz->frzflags = 0;
    7152     23037084 :     frz->checkflags = 0;
    7153              : 
    7154              :     /*
    7155              :      * Process xmin, while keeping track of whether it's already frozen, or
    7156              :      * will become frozen iff our freeze plan is executed by caller (could be
    7157              :      * neither).
    7158              :      */
    7159     23037084 :     xid = HeapTupleHeaderGetXmin(tuple);
    7160     23037084 :     if (!TransactionIdIsNormal(xid))
    7161     19909024 :         xmin_already_frozen = true;
    7162              :     else
    7163              :     {
    7164      3128060 :         if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
    7165            0 :             ereport(ERROR,
    7166              :                     (errcode(ERRCODE_DATA_CORRUPTED),
    7167              :                      errmsg_internal("found xmin %u from before relfrozenxid %u",
    7168              :                                      xid, cutoffs->relfrozenxid)));
    7169              : 
    7170              :         /* Will set freeze_xmin flags in freeze plan below */
    7171      3128060 :         freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
    7172              : 
    7173              :         /* Verify that xmin committed if and when freeze plan is executed */
    7174      3128060 :         if (freeze_xmin)
    7175      2482137 :             frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
    7176              :     }
    7177              : 
    7178              :     /*
    7179              :      * Old-style VACUUM FULL is gone, but we have to process xvac for as long
    7180              :      * as we support having MOVED_OFF/MOVED_IN tuples in the database
    7181              :      */
    7182     23037084 :     xid = HeapTupleHeaderGetXvac(tuple);
    7183     23037084 :     if (TransactionIdIsNormal(xid))
    7184              :     {
    7185              :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
    7186              :         Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
    7187              : 
    7188              :         /*
    7189              :          * For Xvac, we always freeze proactively.  This allows totally_frozen
    7190              :          * tracking to ignore xvac.
    7191              :          */
    7192            0 :         replace_xvac = pagefrz->freeze_required = true;
    7193              : 
    7194              :         /* Will set replace_xvac flags in freeze plan below */
    7195              :     }
    7196              : 
    7197              :     /* Now process xmax */
    7198     23037084 :     xid = frz->xmax;
    7199     23037084 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
    7200              :     {
    7201              :         /* Raw xmax is a MultiXactId */
    7202              :         TransactionId newxmax;
    7203              :         uint16      flags;
    7204              : 
    7205              :         /*
    7206              :          * We will either remove xmax completely (in the "freeze_xmax" path),
    7207              :          * process xmax by replacing it (in the "replace_xmax" path), or
    7208              :          * perform no-op xmax processing.  The only constraint is that the
    7209              :          * FreezeLimit/MultiXactCutoff postcondition must never be violated.
    7210              :          */
    7211            6 :         newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
    7212              :                                     &flags, pagefrz);
    7213              : 
    7214            6 :         if (flags & FRM_NOOP)
    7215              :         {
    7216              :             /*
    7217              :              * xmax is a MultiXactId, and nothing about it changes for now.
    7218              :              * This is the only case where 'freeze_required' won't have been
    7219              :              * set for us by FreezeMultiXactId, as well as the only case where
    7220              :              * neither freeze_xmax nor replace_xmax are set (given a multi).
    7221              :              *
    7222              :              * This is a no-op, but the call to FreezeMultiXactId might have
    7223              :              * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
    7224              :              * for us (the "freeze page" variants, specifically).  That'll
    7225              :              * make it safe for our caller to freeze the page later on, while
    7226              :              * leaving this particular xmax undisturbed.
    7227              :              *
    7228              :              * FreezeMultiXactId is _not_ responsible for the "no freeze"
    7229              :              * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
    7230              :              * job.  A call to heap_tuple_should_freeze for this same tuple
    7231              :              * will take place below if 'freeze_required' isn't set already.
    7232              :              * (This repeats work from FreezeMultiXactId, but allows "no
    7233              :              * freeze" tracker maintenance to happen in only one place.)
    7234              :              */
    7235              :             Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
    7236              :             Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
    7237              :         }
    7238            5 :         else if (flags & FRM_RETURN_IS_XID)
    7239              :         {
    7240              :             /*
    7241              :              * xmax will become an updater Xid (original MultiXact's updater
    7242              :              * member Xid will be carried forward as a simple Xid in Xmax).
    7243              :              */
    7244              :             Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
    7245              : 
    7246              :             /*
    7247              :              * NB -- some of these transformations are only valid because we
    7248              :              * know the return Xid is a tuple updater (i.e. not merely a
    7249              :              * locker.) Also note that the only reason we don't explicitly
    7250              :              * worry about HEAP_KEYS_UPDATED is because it lives in
    7251              :              * t_infomask2 rather than t_infomask.
    7252              :              */
    7253            0 :             frz->t_infomask &= ~HEAP_XMAX_BITS;
    7254            0 :             frz->xmax = newxmax;
    7255            0 :             if (flags & FRM_MARK_COMMITTED)
    7256            0 :                 frz->t_infomask |= HEAP_XMAX_COMMITTED;
    7257            0 :             replace_xmax = true;
    7258              :         }
    7259            5 :         else if (flags & FRM_RETURN_IS_MULTI)
    7260              :         {
    7261              :             uint16      newbits;
    7262              :             uint16      newbits2;
    7263              : 
    7264              :             /*
    7265              :              * xmax is an old MultiXactId that we have to replace with a new
    7266              :              * MultiXactId, to carry forward two or more original member XIDs.
    7267              :              */
    7268              :             Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
    7269              : 
    7270              :             /*
    7271              :              * We can't use GetMultiXactIdHintBits directly on the new multi
    7272              :              * here; that routine initializes the masks to all zeroes, which
    7273              :              * would lose other bits we need.  Doing it this way ensures all
    7274              :              * unrelated bits remain untouched.
    7275              :              */
    7276            1 :             frz->t_infomask &= ~HEAP_XMAX_BITS;
    7277            1 :             frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
    7278            1 :             GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
    7279            1 :             frz->t_infomask |= newbits;
    7280            1 :             frz->t_infomask2 |= newbits2;
    7281            1 :             frz->xmax = newxmax;
    7282            1 :             replace_xmax = true;
    7283              :         }
    7284              :         else
    7285              :         {
    7286              :             /*
    7287              :              * Freeze plan for tuple "freezes xmax" in the strictest sense:
    7288              :              * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
    7289              :              */
    7290              :             Assert(flags & FRM_INVALIDATE_XMAX);
    7291              :             Assert(!TransactionIdIsValid(newxmax));
    7292              : 
    7293              :             /* Will set freeze_xmax flags in freeze plan below */
    7294            4 :             freeze_xmax = true;
    7295              :         }
    7296              : 
    7297              :         /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
    7298              :         Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
    7299              :     }
    7300     23037078 :     else if (TransactionIdIsNormal(xid))
    7301              :     {
    7302              :         /* Raw xmax is normal XID */
    7303      6692685 :         if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
    7304            0 :             ereport(ERROR,
    7305              :                     (errcode(ERRCODE_DATA_CORRUPTED),
    7306              :                      errmsg_internal("found xmax %u from before relfrozenxid %u",
    7307              :                                      xid, cutoffs->relfrozenxid)));
    7308              : 
    7309              :         /* Will set freeze_xmax flags in freeze plan below */
    7310      6692685 :         freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
    7311              : 
    7312              :         /*
    7313              :          * Verify that xmax aborted if and when freeze plan is executed,
    7314              :          * provided it's from an update. (A lock-only xmax can be removed
    7315              :          * independent of this, since the lock is released at xact end.)
    7316              :          */
    7317      6692685 :         if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
    7318         1379 :             frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
    7319              :     }
    7320     16344393 :     else if (!TransactionIdIsValid(xid))
    7321              :     {
    7322              :         /* Raw xmax is InvalidTransactionId XID */
    7323              :         Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
    7324     16344393 :         xmax_already_frozen = true;
    7325              :     }
    7326              :     else
    7327            0 :         ereport(ERROR,
    7328              :                 (errcode(ERRCODE_DATA_CORRUPTED),
    7329              :                  errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
    7330              :                                  xid, tuple->t_infomask)));
    7331              : 
    7332     23037084 :     if (freeze_xmin)
    7333              :     {
    7334              :         Assert(!xmin_already_frozen);
    7335              : 
    7336      2482137 :         frz->t_infomask |= HEAP_XMIN_FROZEN;
    7337              :     }
    7338     23037084 :     if (replace_xvac)
    7339              :     {
    7340              :         /*
    7341              :          * If a MOVED_OFF tuple is not dead, the xvac transaction must have
    7342              :          * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
    7343              :          * transaction succeeded.
    7344              :          */
    7345              :         Assert(pagefrz->freeze_required);
    7346            0 :         if (tuple->t_infomask & HEAP_MOVED_OFF)
    7347            0 :             frz->frzflags |= XLH_INVALID_XVAC;
    7348              :         else
    7349            0 :             frz->frzflags |= XLH_FREEZE_XVAC;
    7350              :     }
    7351              :     if (replace_xmax)
    7352              :     {
    7353              :         Assert(!xmax_already_frozen && !freeze_xmax);
    7354              :         Assert(pagefrz->freeze_required);
    7355              : 
    7356              :         /* Already set replace_xmax flags in freeze plan earlier */
    7357              :     }
    7358     23037084 :     if (freeze_xmax)
    7359              :     {
    7360              :         Assert(!xmax_already_frozen && !replace_xmax);
    7361              : 
    7362         2355 :         frz->xmax = InvalidTransactionId;
    7363              : 
    7364              :         /*
    7365              :          * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
    7366              :          * LOCKED.  Normalize to INVALID just to be sure no one gets confused.
    7367              :          * Also get rid of the HEAP_KEYS_UPDATED bit.
    7368              :          */
    7369         2355 :         frz->t_infomask &= ~HEAP_XMAX_BITS;
    7370         2355 :         frz->t_infomask |= HEAP_XMAX_INVALID;
    7371         2355 :         frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
    7372         2355 :         frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
    7373              :     }
    7374              : 
    7375              :     /*
    7376              :      * Determine if this tuple is already totally frozen, or will become
    7377              :      * totally frozen (provided caller executes freeze plans for the page)
    7378              :      */
    7379     45425890 :     *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
    7380     22388806 :                        (freeze_xmax || xmax_already_frozen));
    7381              : 
    7382     23037084 :     if (!pagefrz->freeze_required && !(xmin_already_frozen &&
    7383              :                                        xmax_already_frozen))
    7384              :     {
    7385              :         /*
    7386              :          * So far no previous tuple from the page made freezing mandatory.
    7387              :          * Does this tuple force caller to freeze the entire page?
    7388              :          */
    7389      8263077 :         pagefrz->freeze_required =
    7390      8263077 :             heap_tuple_should_freeze(tuple, cutoffs,
    7391              :                                      &pagefrz->NoFreezePageRelfrozenXid,
    7392              :                                      &pagefrz->NoFreezePageRelminMxid);
    7393              :     }
    7394              : 
    7395              :     /* Tell caller if this tuple has a usable freeze plan set in *frz */
    7396     23037084 :     return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
    7397              : }
    7398              : 
    7399              : /*
    7400              :  * Perform xmin/xmax XID status sanity checks before actually executing freeze
    7401              :  * plans.
    7402              :  *
    7403              :  * heap_prepare_freeze_tuple doesn't perform these checks directly because
    7404              :  * pg_xact lookups are relatively expensive.  They shouldn't be repeated by
    7405              :  * successive VACUUMs that each decide against freezing the same page.
    7406              :  */
    7407              : void
    7408        22270 : heap_pre_freeze_checks(Buffer buffer,
    7409              :                        HeapTupleFreeze *tuples, int ntuples)
    7410              : {
    7411        22270 :     Page        page = BufferGetPage(buffer);
    7412              : 
    7413       971660 :     for (int i = 0; i < ntuples; i++)
    7414              :     {
    7415       949390 :         HeapTupleFreeze *frz = tuples + i;
    7416       949390 :         ItemId      itemid = PageGetItemId(page, frz->offset);
    7417              :         HeapTupleHeader htup;
    7418              : 
    7419       949390 :         htup = (HeapTupleHeader) PageGetItem(page, itemid);
    7420              : 
    7421              :         /* Deliberately avoid relying on tuple hint bits here */
    7422       949390 :         if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
    7423              :         {
    7424       949389 :             TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
    7425              : 
    7426              :             Assert(!HeapTupleHeaderXminFrozen(htup));
    7427       949389 :             if (unlikely(!TransactionIdDidCommit(xmin)))
    7428            0 :                 ereport(ERROR,
    7429              :                         (errcode(ERRCODE_DATA_CORRUPTED),
    7430              :                          errmsg_internal("uncommitted xmin %u needs to be frozen",
    7431              :                                          xmin)));
    7432              :         }
    7433              : 
    7434              :         /*
    7435              :          * TransactionIdDidAbort won't work reliably in the presence of XIDs
    7436              :          * left behind by transactions that were in progress during a crash,
    7437              :          * so we can only check that xmax didn't commit
    7438              :          */
    7439       949390 :         if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
    7440              :         {
    7441          430 :             TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
    7442              : 
    7443              :             Assert(TransactionIdIsNormal(xmax));
    7444          430 :             if (unlikely(TransactionIdDidCommit(xmax)))
    7445            0 :                 ereport(ERROR,
    7446              :                         (errcode(ERRCODE_DATA_CORRUPTED),
    7447              :                          errmsg_internal("cannot freeze committed xmax %u",
    7448              :                                          xmax)));
    7449              :         }
    7450              :     }
    7451        22270 : }
    7452              : 
    7453              : /*
    7454              :  * Helper which executes freezing of one or more heap tuples on a page on
    7455              :  * behalf of caller.  Caller passes an array of tuple plans from
    7456              :  * heap_prepare_freeze_tuple.  Caller must set 'offset' in each plan for us.
    7457              :  * Must be called in a critical section that also marks the buffer dirty and,
    7458              :  * if needed, emits WAL.
    7459              :  */
    7460              : void
    7461        22270 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
    7462              : {
    7463        22270 :     Page        page = BufferGetPage(buffer);
    7464              : 
    7465       971660 :     for (int i = 0; i < ntuples; i++)
    7466              :     {
    7467       949390 :         HeapTupleFreeze *frz = tuples + i;
    7468       949390 :         ItemId      itemid = PageGetItemId(page, frz->offset);
    7469              :         HeapTupleHeader htup;
    7470              : 
    7471       949390 :         htup = (HeapTupleHeader) PageGetItem(page, itemid);
    7472       949390 :         heap_execute_freeze_tuple(htup, frz);
    7473              :     }
    7474        22270 : }
    7475              : 
    7476              : /*
    7477              :  * heap_freeze_tuple
    7478              :  *      Freeze tuple in place, without WAL logging.
    7479              :  *
    7480              :  * Useful for callers like CLUSTER that perform their own WAL logging.
    7481              :  */
    7482              : bool
    7483       362454 : heap_freeze_tuple(HeapTupleHeader tuple,
    7484              :                   TransactionId relfrozenxid, TransactionId relminmxid,
    7485              :                   TransactionId FreezeLimit, TransactionId MultiXactCutoff)
    7486              : {
    7487              :     HeapTupleFreeze frz;
    7488              :     bool        do_freeze;
    7489              :     bool        totally_frozen;
    7490              :     struct VacuumCutoffs cutoffs;
    7491              :     HeapPageFreeze pagefrz;
    7492              : 
    7493       362454 :     cutoffs.relfrozenxid = relfrozenxid;
    7494       362454 :     cutoffs.relminmxid = relminmxid;
    7495       362454 :     cutoffs.OldestXmin = FreezeLimit;
    7496       362454 :     cutoffs.OldestMxact = MultiXactCutoff;
    7497       362454 :     cutoffs.FreezeLimit = FreezeLimit;
    7498       362454 :     cutoffs.MultiXactCutoff = MultiXactCutoff;
    7499              : 
    7500       362454 :     pagefrz.freeze_required = true;
    7501       362454 :     pagefrz.FreezePageRelfrozenXid = FreezeLimit;
    7502       362454 :     pagefrz.FreezePageRelminMxid = MultiXactCutoff;
    7503       362454 :     pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
    7504       362454 :     pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
    7505              : 
    7506       362454 :     do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
    7507              :                                           &pagefrz, &frz, &totally_frozen);
    7508              : 
    7509              :     /*
    7510              :      * Note that because this is not a WAL-logged operation, we don't need to
    7511              :      * fill in the offset in the freeze record.
    7512              :      */
    7513              : 
    7514       362454 :     if (do_freeze)
    7515       251986 :         heap_execute_freeze_tuple(tuple, &frz);
    7516       362454 :     return do_freeze;
    7517              : }
    7518              : 
    7519              : /*
    7520              :  * For a given MultiXactId, return the hint bits that should be set in the
    7521              :  * tuple's infomask.
    7522              :  *
    7523              :  * Normally this should be called for a multixact that was just created, and
    7524              :  * so is on our local cache, so the GetMembers call is fast.
    7525              :  */
    7526              : static void
    7527        76801 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
    7528              :                        uint16 *new_infomask2)
    7529              : {
    7530              :     int         nmembers;
    7531              :     MultiXactMember *members;
    7532              :     int         i;
    7533        76801 :     uint16      bits = HEAP_XMAX_IS_MULTI;
    7534        76801 :     uint16      bits2 = 0;
    7535        76801 :     bool        has_update = false;
    7536        76801 :     LockTupleMode strongest = LockTupleKeyShare;
    7537              : 
    7538              :     /*
    7539              :      * We only use this in multis we just created, so they cannot be values
    7540              :      * pre-pg_upgrade.
    7541              :      */
    7542        76801 :     nmembers = GetMultiXactIdMembers(multi, &members, false, false);
    7543              : 
    7544      1472618 :     for (i = 0; i < nmembers; i++)
    7545              :     {
    7546              :         LockTupleMode mode;
    7547              : 
    7548              :         /*
    7549              :          * Remember the strongest lock mode held by any member of the
    7550              :          * multixact.
    7551              :          */
    7552      1395817 :         mode = TUPLOCK_from_mxstatus(members[i].status);
    7553      1395817 :         if (mode > strongest)
    7554         2888 :             strongest = mode;
    7555              : 
    7556              :         /* See what other bits we need */
    7557      1395817 :         switch (members[i].status)
    7558              :         {
    7559      1393399 :             case MultiXactStatusForKeyShare:
    7560              :             case MultiXactStatusForShare:
    7561              :             case MultiXactStatusForNoKeyUpdate:
    7562      1393399 :                 break;
    7563              : 
    7564           52 :             case MultiXactStatusForUpdate:
    7565           52 :                 bits2 |= HEAP_KEYS_UPDATED;
    7566           52 :                 break;
    7567              : 
    7568         2356 :             case MultiXactStatusNoKeyUpdate:
    7569         2356 :                 has_update = true;
    7570         2356 :                 break;
    7571              : 
    7572           10 :             case MultiXactStatusUpdate:
    7573           10 :                 bits2 |= HEAP_KEYS_UPDATED;
    7574           10 :                 has_update = true;
    7575           10 :                 break;
    7576              :         }
    7577              :     }
    7578              : 
    7579        76801 :     if (strongest == LockTupleExclusive ||
    7580              :         strongest == LockTupleNoKeyExclusive)
    7581         2446 :         bits |= HEAP_XMAX_EXCL_LOCK;
    7582        74355 :     else if (strongest == LockTupleShare)
    7583          439 :         bits |= HEAP_XMAX_SHR_LOCK;
    7584        73916 :     else if (strongest == LockTupleKeyShare)
    7585        73916 :         bits |= HEAP_XMAX_KEYSHR_LOCK;
    7586              : 
    7587        76801 :     if (!has_update)
    7588        74435 :         bits |= HEAP_XMAX_LOCK_ONLY;
    7589              : 
    7590        76801 :     if (nmembers > 0)
    7591        76801 :         pfree(members);
    7592              : 
    7593        76801 :     *new_infomask = bits;
    7594        76801 :     *new_infomask2 = bits2;
    7595        76801 : }
    7596              : 
    7597              : /*
    7598              :  * MultiXactIdGetUpdateXid
    7599              :  *
    7600              :  * Given a multixact Xmax and corresponding infomask, which does not have the
    7601              :  * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
    7602              :  * transaction.
    7603              :  *
    7604              :  * Caller is expected to check the status of the updating transaction, if
    7605              :  * necessary.
    7606              :  */
    7607              : static TransactionId
    7608       162019 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
    7609              : {
    7610       162019 :     TransactionId update_xact = InvalidTransactionId;
    7611              :     MultiXactMember *members;
    7612              :     int         nmembers;
    7613              : 
    7614              :     Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
    7615              :     Assert(t_infomask & HEAP_XMAX_IS_MULTI);
    7616              : 
    7617              :     /*
    7618              :      * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
    7619              :      * pre-pg_upgrade.
    7620              :      */
    7621       162019 :     nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
    7622              : 
    7623       162019 :     if (nmembers > 0)
    7624              :     {
    7625              :         int         i;
    7626              : 
    7627       245780 :         for (i = 0; i < nmembers; i++)
    7628              :         {
    7629              :             /* Ignore lockers */
    7630       245780 :             if (!ISUPDATE_from_mxstatus(members[i].status))
    7631        83761 :                 continue;
    7632              : 
    7633              :             /* there can be at most one updater */
    7634              :             Assert(update_xact == InvalidTransactionId);
    7635       162019 :             update_xact = members[i].xid;
    7636              : #ifndef USE_ASSERT_CHECKING
    7637              : 
    7638              :             /*
    7639              :              * in an assert-enabled build, walk the whole array to ensure
    7640              :              * there's no other updater.
    7641              :              */
    7642       162019 :             break;
    7643              : #endif
    7644              :         }
    7645              : 
    7646       162019 :         pfree(members);
    7647              :     }
    7648              : 
    7649       162019 :     return update_xact;
    7650              : }
    7651              : 
    7652              : /*
    7653              :  * HeapTupleGetUpdateXid
    7654              :  *      As above, but use a HeapTupleHeader
    7655              :  *
    7656              :  * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
    7657              :  * checking the hint bits.
    7658              :  */
    7659              : TransactionId
    7660       159881 : HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
    7661              : {
    7662       159881 :     return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tup),
    7663       159881 :                                    tup->t_infomask);
    7664              : }
    7665              : 
    7666              : /*
    7667              :  * Does the given multixact conflict with the current transaction grabbing a
    7668              :  * tuple lock of the given strength?
    7669              :  *
    7670              :  * The passed infomask pairs up with the given multixact in the tuple header.
    7671              :  *
    7672              :  * If current_is_member is not NULL, it is set to 'true' if the current
    7673              :  * transaction is a member of the given multixact.
    7674              :  */
    7675              : static bool
    7676          218 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
    7677              :                         LockTupleMode lockmode, bool *current_is_member)
    7678              : {
    7679              :     int         nmembers;
    7680              :     MultiXactMember *members;
    7681          218 :     bool        result = false;
    7682          218 :     LOCKMODE    wanted = tupleLockExtraInfo[lockmode].hwlock;
    7683              : 
    7684          218 :     if (HEAP_LOCKED_UPGRADED(infomask))
    7685            0 :         return false;
    7686              : 
    7687          218 :     nmembers = GetMultiXactIdMembers(multi, &members, false,
    7688          218 :                                      HEAP_XMAX_IS_LOCKED_ONLY(infomask));
    7689          218 :     if (nmembers >= 0)
    7690              :     {
    7691              :         int         i;
    7692              : 
    7693         2682 :         for (i = 0; i < nmembers; i++)
    7694              :         {
    7695              :             TransactionId memxid;
    7696              :             LOCKMODE    memlockmode;
    7697              : 
    7698         2471 :             if (result && (current_is_member == NULL || *current_is_member))
    7699              :                 break;
    7700              : 
    7701         2464 :             memlockmode = LOCKMODE_from_mxstatus(members[i].status);
    7702              : 
    7703              :             /* ignore members from current xact (but track their presence) */
    7704         2464 :             memxid = members[i].xid;
    7705         2464 :             if (TransactionIdIsCurrentTransactionId(memxid))
    7706              :             {
    7707           92 :                 if (current_is_member != NULL)
    7708           78 :                     *current_is_member = true;
    7709           92 :                 continue;
    7710              :             }
    7711         2372 :             else if (result)
    7712            8 :                 continue;
    7713              : 
    7714              :             /* ignore members that don't conflict with the lock we want */
    7715         2364 :             if (!DoLockModesConflict(memlockmode, wanted))
    7716         2325 :                 continue;
    7717              : 
    7718           39 :             if (ISUPDATE_from_mxstatus(members[i].status))
    7719              :             {
    7720              :                 /* ignore aborted updaters */
    7721           17 :                 if (TransactionIdDidAbort(memxid))
    7722            1 :                     continue;
    7723              :             }
    7724              :             else
    7725              :             {
    7726              :                 /* ignore lockers-only that are no longer in progress */
    7727           22 :                 if (!TransactionIdIsInProgress(memxid))
    7728            7 :                     continue;
    7729              :             }
    7730              : 
    7731              :             /*
    7732              :              * Whatever remains are either live lockers that conflict with our
    7733              :              * wanted lock, and updaters that are not aborted.  Those conflict
    7734              :              * with what we want.  Set up to return true, but keep going to
    7735              :              * look for the current transaction among the multixact members,
    7736              :              * if needed.
    7737              :              */
    7738           31 :             result = true;
    7739              :         }
    7740          218 :         pfree(members);
    7741              :     }
    7742              : 
    7743          218 :     return result;
    7744              : }
    7745              : 
    7746              : /*
    7747              :  * Do_MultiXactIdWait
    7748              :  *      Actual implementation for the two functions below.
    7749              :  *
    7750              :  * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
    7751              :  * needed to ensure we only sleep on conflicting members, and the infomask is
    7752              :  * used to optimize multixact access in case it's a lock-only multi); 'nowait'
    7753              :  * indicates whether to use conditional lock acquisition, to allow callers to
    7754              :  * fail if lock is unavailable.  'rel', 'ctid' and 'oper' are used to set up
    7755              :  * context information for error messages.  'remaining', if not NULL, receives
    7756              :  * the number of members that are still running, including any (non-aborted)
    7757              :  * subtransactions of our own transaction.  'logLockFailure' indicates whether
    7758              :  * to log details when a lock acquisition fails with 'nowait' enabled.
    7759              :  *
    7760              :  * We do this by sleeping on each member using XactLockTableWait.  Any
    7761              :  * members that belong to the current backend are *not* waited for, however;
    7762              :  * this would not merely be useless but would lead to Assert failure inside
    7763              :  * XactLockTableWait.  By the time this returns, it is certain that all
    7764              :  * transactions *of other backends* that were members of the MultiXactId
    7765              :  * that conflict with the requested status are dead (and no new ones can have
    7766              :  * been added, since it is not legal to add members to an existing
    7767              :  * MultiXactId).
    7768              :  *
    7769              :  * But by the time we finish sleeping, someone else may have changed the Xmax
    7770              :  * of the containing tuple, so the caller needs to iterate on us somehow.
    7771              :  *
    7772              :  * Note that in case we return false, the number of remaining members is
    7773              :  * not to be trusted.
    7774              :  */
    7775              : static bool
    7776           58 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
    7777              :                    uint16 infomask, bool nowait,
    7778              :                    Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
    7779              :                    int *remaining, bool logLockFailure)
    7780              : {
    7781           58 :     bool        result = true;
    7782              :     MultiXactMember *members;
    7783              :     int         nmembers;
    7784           58 :     int         remain = 0;
    7785              : 
    7786              :     /* for pre-pg_upgrade tuples, no need to sleep at all */
    7787           58 :     nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
    7788           58 :         GetMultiXactIdMembers(multi, &members, false,
    7789           58 :                               HEAP_XMAX_IS_LOCKED_ONLY(infomask));
    7790              : 
    7791           58 :     if (nmembers >= 0)
    7792              :     {
    7793              :         int         i;
    7794              : 
    7795          187 :         for (i = 0; i < nmembers; i++)
    7796              :         {
    7797          133 :             TransactionId memxid = members[i].xid;
    7798          133 :             MultiXactStatus memstatus = members[i].status;
    7799              : 
    7800          133 :             if (TransactionIdIsCurrentTransactionId(memxid))
    7801              :             {
    7802           24 :                 remain++;
    7803           24 :                 continue;
    7804              :             }
    7805              : 
    7806          109 :             if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
    7807          109 :                                      LOCKMODE_from_mxstatus(status)))
    7808              :             {
    7809           22 :                 if (remaining && TransactionIdIsInProgress(memxid))
    7810            8 :                     remain++;
    7811           22 :                 continue;
    7812              :             }
    7813              : 
    7814              :             /*
    7815              :              * This member conflicts with our multi, so we have to sleep (or
    7816              :              * return failure, if asked to avoid waiting.)
    7817              :              *
    7818              :              * Note that we don't set up an error context callback ourselves,
    7819              :              * but instead we pass the info down to XactLockTableWait.  This
    7820              :              * might seem a bit wasteful because the context is set up and
    7821              :              * tore down for each member of the multixact, but in reality it
    7822              :              * should be barely noticeable, and it avoids duplicate code.
    7823              :              */
    7824           87 :             if (nowait)
    7825              :             {
    7826            4 :                 result = ConditionalXactLockTableWait(memxid, logLockFailure);
    7827            4 :                 if (!result)
    7828            4 :                     break;
    7829              :             }
    7830              :             else
    7831           83 :                 XactLockTableWait(memxid, rel, ctid, oper);
    7832              :         }
    7833              : 
    7834           58 :         pfree(members);
    7835              :     }
    7836              : 
    7837           58 :     if (remaining)
    7838           10 :         *remaining = remain;
    7839              : 
    7840           58 :     return result;
    7841              : }
    7842              : 
    7843              : /*
    7844              :  * MultiXactIdWait
    7845              :  *      Sleep on a MultiXactId.
    7846              :  *
    7847              :  * By the time we finish sleeping, someone else may have changed the Xmax
    7848              :  * of the containing tuple, so the caller needs to iterate on us somehow.
    7849              :  *
    7850              :  * We return (in *remaining, if not NULL) the number of members that are still
    7851              :  * running, including any (non-aborted) subtransactions of our own transaction.
    7852              :  */
    7853              : static void
    7854           54 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
    7855              :                 Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
    7856              :                 int *remaining)
    7857              : {
    7858           54 :     (void) Do_MultiXactIdWait(multi, status, infomask, false,
    7859              :                               rel, ctid, oper, remaining, false);
    7860           54 : }
    7861              : 
    7862              : /*
    7863              :  * ConditionalMultiXactIdWait
    7864              :  *      As above, but only lock if we can get the lock without blocking.
    7865              :  *
    7866              :  * By the time we finish sleeping, someone else may have changed the Xmax
    7867              :  * of the containing tuple, so the caller needs to iterate on us somehow.
    7868              :  *
    7869              :  * If the multixact is now all gone, return true.  Returns false if some
    7870              :  * transactions might still be running.
    7871              :  *
    7872              :  * We return (in *remaining, if not NULL) the number of members that are still
    7873              :  * running, including any (non-aborted) subtransactions of our own transaction.
    7874              :  */
    7875              : static bool
    7876            4 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
    7877              :                            uint16 infomask, Relation rel, int *remaining,
    7878              :                            bool logLockFailure)
    7879              : {
    7880            4 :     return Do_MultiXactIdWait(multi, status, infomask, true,
    7881              :                               rel, NULL, XLTW_None, remaining, logLockFailure);
    7882              : }
    7883              : 
    7884              : /*
    7885              :  * heap_tuple_needs_eventual_freeze
    7886              :  *
    7887              :  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
    7888              :  * will eventually require freezing (if tuple isn't removed by pruning first).
    7889              :  */
    7890              : bool
    7891       129134 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
    7892              : {
    7893              :     TransactionId xid;
    7894              : 
    7895              :     /*
    7896              :      * If xmin is a normal transaction ID, this tuple is definitely not
    7897              :      * frozen.
    7898              :      */
    7899       129134 :     xid = HeapTupleHeaderGetXmin(tuple);
    7900       129134 :     if (TransactionIdIsNormal(xid))
    7901         3136 :         return true;
    7902              : 
    7903              :     /*
    7904              :      * If xmax is a valid xact or multixact, this tuple is also not frozen.
    7905              :      */
    7906       125998 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
    7907              :     {
    7908              :         MultiXactId multi;
    7909              : 
    7910            0 :         multi = HeapTupleHeaderGetRawXmax(tuple);
    7911            0 :         if (MultiXactIdIsValid(multi))
    7912            0 :             return true;
    7913              :     }
    7914              :     else
    7915              :     {
    7916       125998 :         xid = HeapTupleHeaderGetRawXmax(tuple);
    7917       125998 :         if (TransactionIdIsNormal(xid))
    7918            7 :             return true;
    7919              :     }
    7920              : 
    7921       125991 :     if (tuple->t_infomask & HEAP_MOVED)
    7922              :     {
    7923            0 :         xid = HeapTupleHeaderGetXvac(tuple);
    7924            0 :         if (TransactionIdIsNormal(xid))
    7925            0 :             return true;
    7926              :     }
    7927              : 
    7928       125991 :     return false;
    7929              : }
    7930              : 
    7931              : /*
    7932              :  * heap_tuple_should_freeze
    7933              :  *
    7934              :  * Return value indicates if heap_prepare_freeze_tuple sibling function would
    7935              :  * (or should) force freezing of the heap page that contains caller's tuple.
    7936              :  * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
    7937              :  * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
    7938              :  *
    7939              :  * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
    7940              :  * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
    7941              :  * Our working assumption is that caller won't decide to freeze this tuple.
    7942              :  * It's up to caller to only ratchet back its own top-level trackers after the
    7943              :  * point that it fully commits to not freezing the tuple/page in question.
    7944              :  */
    7945              : bool
    7946      8264770 : heap_tuple_should_freeze(HeapTupleHeader tuple,
    7947              :                          const struct VacuumCutoffs *cutoffs,
    7948              :                          TransactionId *NoFreezePageRelfrozenXid,
    7949              :                          MultiXactId *NoFreezePageRelminMxid)
    7950              : {
    7951              :     TransactionId xid;
    7952              :     MultiXactId multi;
    7953      8264770 :     bool        freeze = false;
    7954              : 
    7955              :     /* First deal with xmin */
    7956      8264770 :     xid = HeapTupleHeaderGetXmin(tuple);
    7957      8264770 :     if (TransactionIdIsNormal(xid))
    7958              :     {
    7959              :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
    7960      1935324 :         if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
    7961        22613 :             *NoFreezePageRelfrozenXid = xid;
    7962      1935324 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
    7963        21157 :             freeze = true;
    7964              :     }
    7965              : 
    7966              :     /* Now deal with xmax */
    7967      8264770 :     xid = InvalidTransactionId;
    7968      8264770 :     multi = InvalidMultiXactId;
    7969      8264770 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
    7970            2 :         multi = HeapTupleHeaderGetRawXmax(tuple);
    7971              :     else
    7972      8264768 :         xid = HeapTupleHeaderGetRawXmax(tuple);
    7973              : 
    7974      8264770 :     if (TransactionIdIsNormal(xid))
    7975              :     {
    7976              :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
    7977              :         /* xmax is a non-permanent XID */
    7978      6622738 :         if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
    7979            4 :             *NoFreezePageRelfrozenXid = xid;
    7980      6622738 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
    7981            5 :             freeze = true;
    7982              :     }
    7983      1642032 :     else if (!MultiXactIdIsValid(multi))
    7984              :     {
    7985              :         /* xmax is a permanent XID or invalid MultiXactId/XID */
    7986              :     }
    7987            2 :     else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
    7988              :     {
    7989              :         /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
    7990            0 :         if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
    7991            0 :             *NoFreezePageRelminMxid = multi;
    7992              :         /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
    7993            0 :         freeze = true;
    7994              :     }
    7995              :     else
    7996              :     {
    7997              :         /* xmax is a MultiXactId that may have an updater XID */
    7998              :         MultiXactMember *members;
    7999              :         int         nmembers;
    8000              : 
    8001              :         Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
    8002            2 :         if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
    8003            2 :             *NoFreezePageRelminMxid = multi;
    8004            2 :         if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
    8005            2 :             freeze = true;
    8006              : 
    8007              :         /* need to check whether any member of the mxact is old */
    8008            2 :         nmembers = GetMultiXactIdMembers(multi, &members, false,
    8009            2 :                                          HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
    8010              : 
    8011            5 :         for (int i = 0; i < nmembers; i++)
    8012              :         {
    8013            3 :             xid = members[i].xid;
    8014              :             Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
    8015            3 :             if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
    8016            0 :                 *NoFreezePageRelfrozenXid = xid;
    8017            3 :             if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
    8018            0 :                 freeze = true;
    8019              :         }
    8020            2 :         if (nmembers > 0)
    8021            1 :             pfree(members);
    8022              :     }
    8023              : 
    8024      8264770 :     if (tuple->t_infomask & HEAP_MOVED)
    8025              :     {
    8026            0 :         xid = HeapTupleHeaderGetXvac(tuple);
    8027            0 :         if (TransactionIdIsNormal(xid))
    8028              :         {
    8029              :             Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
    8030            0 :             if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
    8031            0 :                 *NoFreezePageRelfrozenXid = xid;
    8032              :             /* heap_prepare_freeze_tuple forces xvac freezing */
    8033            0 :             freeze = true;
    8034              :         }
    8035              :     }
    8036              : 
    8037      8264770 :     return freeze;
    8038              : }
    8039              : 
    8040              : /*
    8041              :  * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
    8042              :  * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
    8043              :  * that caller is in the process of physically removing, e.g. via HOT pruning
    8044              :  * or index deletion.
    8045              :  *
    8046              :  * Caller must initialize its value to InvalidTransactionId, which is
    8047              :  * generally interpreted as "definitely no need for a recovery conflict".
    8048              :  * Final value must reflect all heap tuples that caller will physically remove
    8049              :  * (or remove TID references to) via its ongoing pruning/deletion operation.
    8050              :  * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
    8051              :  * caller's WAL record) by REDO routine when it replays caller's operation.
    8052              :  */
    8053              : void
    8054      1572617 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
    8055              :                                       TransactionId *snapshotConflictHorizon)
    8056              : {
    8057      1572617 :     TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
    8058      1572617 :     TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
    8059      1572617 :     TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
    8060              : 
    8061      1572617 :     if (tuple->t_infomask & HEAP_MOVED)
    8062              :     {
    8063            0 :         if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
    8064            0 :             *snapshotConflictHorizon = xvac;
    8065              :     }
    8066              : 
    8067              :     /*
    8068              :      * Ignore tuples inserted by an aborted transaction or if the tuple was
    8069              :      * updated/deleted by the inserting transaction.
    8070              :      *
    8071              :      * Look for a committed hint bit, or if no xmin bit is set, check clog.
    8072              :      */
    8073      1572617 :     if (HeapTupleHeaderXminCommitted(tuple) ||
    8074       106822 :         (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
    8075              :     {
    8076      2847445 :         if (xmax != xmin &&
    8077      1353945 :             TransactionIdFollows(xmax, *snapshotConflictHorizon))
    8078       100440 :             *snapshotConflictHorizon = xmax;
    8079              :     }
    8080      1572617 : }
    8081              : 
    8082              : #ifdef USE_PREFETCH
    8083              : /*
    8084              :  * Helper function for heap_index_delete_tuples.  Issues prefetch requests for
    8085              :  * prefetch_count buffers.  The prefetch_state keeps track of all the buffers
    8086              :  * we can prefetch, and which have already been prefetched; each call to this
    8087              :  * function picks up where the previous call left off.
    8088              :  *
    8089              :  * Note: we expect the deltids array to be sorted in an order that groups TIDs
    8090              :  * by heap block, with all TIDs for each block appearing together in exactly
    8091              :  * one group.
    8092              :  */
    8093              : static void
    8094        19838 : index_delete_prefetch_buffer(Relation rel,
    8095              :                              IndexDeletePrefetchState *prefetch_state,
    8096              :                              int prefetch_count)
    8097              : {
    8098        19838 :     BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
    8099        19838 :     int         count = 0;
    8100              :     int         i;
    8101        19838 :     int         ndeltids = prefetch_state->ndeltids;
    8102        19838 :     TM_IndexDelete *deltids = prefetch_state->deltids;
    8103              : 
    8104        19838 :     for (i = prefetch_state->next_item;
    8105       685439 :          i < ndeltids && count < prefetch_count;
    8106       665601 :          i++)
    8107              :     {
    8108       665601 :         ItemPointer htid = &deltids[i].tid;
    8109              : 
    8110      1325335 :         if (cur_hblkno == InvalidBlockNumber ||
    8111       659734 :             ItemPointerGetBlockNumber(htid) != cur_hblkno)
    8112              :         {
    8113        18102 :             cur_hblkno = ItemPointerGetBlockNumber(htid);
    8114        18102 :             PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
    8115        18102 :             count++;
    8116              :         }
    8117              :     }
    8118              : 
    8119              :     /*
    8120              :      * Save the prefetch position so that next time we can continue from that
    8121              :      * position.
    8122              :      */
    8123        19838 :     prefetch_state->next_item = i;
    8124        19838 :     prefetch_state->cur_hblkno = cur_hblkno;
    8125        19838 : }
    8126              : #endif
    8127              : 
    8128              : /*
    8129              :  * Helper function for heap_index_delete_tuples.  Checks for index corruption
    8130              :  * involving an invalid TID in index AM caller's index page.
    8131              :  *
    8132              :  * This is an ideal place for these checks.  The index AM must hold a buffer
    8133              :  * lock on the index page containing the TIDs we examine here, so we don't
    8134              :  * have to worry about concurrent VACUUMs at all.  We can be sure that the
    8135              :  * index is corrupt when htid points directly to an LP_UNUSED item or
    8136              :  * heap-only tuple, which is not the case during standard index scans.
    8137              :  */
    8138              : static inline void
    8139       551090 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
    8140              :                         Page page, OffsetNumber maxoff,
    8141              :                         const ItemPointerData *htid, TM_IndexStatus *istatus)
    8142              : {
    8143       551090 :     OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
    8144              :     ItemId      iid;
    8145              : 
    8146              :     Assert(OffsetNumberIsValid(istatus->idxoffnum));
    8147              : 
    8148       551090 :     if (unlikely(indexpagehoffnum > maxoff))
    8149            0 :         ereport(ERROR,
    8150              :                 (errcode(ERRCODE_INDEX_CORRUPTED),
    8151              :                  errmsg_internal("heap tid from index tuple (%u,%u) points past end of heap page line pointer array at offset %u of block %u in index \"%s\"",
    8152              :                                  ItemPointerGetBlockNumber(htid),
    8153              :                                  indexpagehoffnum,
    8154              :                                  istatus->idxoffnum, delstate->iblknum,
    8155              :                                  RelationGetRelationName(delstate->irel))));
    8156              : 
    8157       551090 :     iid = PageGetItemId(page, indexpagehoffnum);
    8158       551090 :     if (unlikely(!ItemIdIsUsed(iid)))
    8159            0 :         ereport(ERROR,
    8160              :                 (errcode(ERRCODE_INDEX_CORRUPTED),
    8161              :                  errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
    8162              :                                  ItemPointerGetBlockNumber(htid),
    8163              :                                  indexpagehoffnum,
    8164              :                                  istatus->idxoffnum, delstate->iblknum,
    8165              :                                  RelationGetRelationName(delstate->irel))));
    8166              : 
    8167       551090 :     if (ItemIdHasStorage(iid))
    8168              :     {
    8169              :         HeapTupleHeader htup;
    8170              : 
    8171              :         Assert(ItemIdIsNormal(iid));
    8172       325690 :         htup = (HeapTupleHeader) PageGetItem(page, iid);
    8173              : 
    8174       325690 :         if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
    8175            0 :             ereport(ERROR,
    8176              :                     (errcode(ERRCODE_INDEX_CORRUPTED),
    8177              :                      errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
    8178              :                                      ItemPointerGetBlockNumber(htid),
    8179              :                                      indexpagehoffnum,
    8180              :                                      istatus->idxoffnum, delstate->iblknum,
    8181              :                                      RelationGetRelationName(delstate->irel))));
    8182              :     }
    8183       551090 : }
    8184              : 
    8185              : /*
    8186              :  * heapam implementation of tableam's index_delete_tuples interface.
    8187              :  *
    8188              :  * This helper function is called by index AMs during index tuple deletion.
    8189              :  * See tableam header comments for an explanation of the interface implemented
    8190              :  * here and a general theory of operation.  Note that each call here is either
    8191              :  * a simple index deletion call, or a bottom-up index deletion call.
    8192              :  *
    8193              :  * It's possible for this to generate a fair amount of I/O, since we may be
    8194              :  * deleting hundreds of tuples from a single index block.  To amortize that
    8195              :  * cost to some degree, this uses prefetching and combines repeat accesses to
    8196              :  * the same heap block.
    8197              :  */
    8198              : TransactionId
    8199         5867 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
    8200              : {
    8201              :     /* Initial assumption is that earlier pruning took care of conflict */
    8202         5867 :     TransactionId snapshotConflictHorizon = InvalidTransactionId;
    8203         5867 :     BlockNumber blkno = InvalidBlockNumber;
    8204         5867 :     Buffer      buf = InvalidBuffer;
    8205         5867 :     Page        page = NULL;
    8206         5867 :     OffsetNumber maxoff = InvalidOffsetNumber;
    8207              :     TransactionId priorXmax;
    8208              : #ifdef USE_PREFETCH
    8209              :     IndexDeletePrefetchState prefetch_state;
    8210              :     int         prefetch_distance;
    8211              : #endif
    8212              :     SnapshotData SnapshotNonVacuumable;
    8213         5867 :     int         finalndeltids = 0,
    8214         5867 :                 nblocksaccessed = 0;
    8215              : 
    8216              :     /* State that's only used in bottom-up index deletion case */
    8217         5867 :     int         nblocksfavorable = 0;
    8218         5867 :     int         curtargetfreespace = delstate->bottomupfreespace,
    8219         5867 :                 lastfreespace = 0,
    8220         5867 :                 actualfreespace = 0;
    8221         5867 :     bool        bottomup_final_block = false;
    8222              : 
    8223         5867 :     InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
    8224              : 
    8225              :     /* Sort caller's deltids array by TID for further processing */
    8226         5867 :     index_delete_sort(delstate);
    8227              : 
    8228              :     /*
    8229              :      * Bottom-up case: resort deltids array in an order attuned to where the
    8230              :      * greatest number of promising TIDs are to be found, and determine how
    8231              :      * many blocks from the start of sorted array should be considered
    8232              :      * favorable.  This will also shrink the deltids array in order to
    8233              :      * eliminate completely unfavorable blocks up front.
    8234              :      */
    8235         5867 :     if (delstate->bottomup)
    8236         1965 :         nblocksfavorable = bottomup_sort_and_shrink(delstate);
    8237              : 
    8238              : #ifdef USE_PREFETCH
    8239              :     /* Initialize prefetch state. */
    8240         5867 :     prefetch_state.cur_hblkno = InvalidBlockNumber;
    8241         5867 :     prefetch_state.next_item = 0;
    8242         5867 :     prefetch_state.ndeltids = delstate->ndeltids;
    8243         5867 :     prefetch_state.deltids = delstate->deltids;
    8244              : 
    8245              :     /*
    8246              :      * Determine the prefetch distance that we will attempt to maintain.
    8247              :      *
    8248              :      * Since the caller holds a buffer lock somewhere in rel, we'd better make
    8249              :      * sure that isn't a catalog relation before we call code that does
    8250              :      * syscache lookups, to avoid risk of deadlock.
    8251              :      */
    8252         5867 :     if (IsCatalogRelation(rel))
    8253         4276 :         prefetch_distance = maintenance_io_concurrency;
    8254              :     else
    8255              :         prefetch_distance =
    8256         1591 :             get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
    8257              : 
    8258              :     /* Cap initial prefetch distance for bottom-up deletion caller */
    8259         5867 :     if (delstate->bottomup)
    8260              :     {
    8261              :         Assert(nblocksfavorable >= 1);
    8262              :         Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
    8263         1965 :         prefetch_distance = Min(prefetch_distance, nblocksfavorable);
    8264              :     }
    8265              : 
    8266              :     /* Start prefetching. */
    8267         5867 :     index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
    8268              : #endif
    8269              : 
    8270              :     /* Iterate over deltids, determine which to delete, check their horizon */
    8271              :     Assert(delstate->ndeltids > 0);
    8272       556957 :     for (int i = 0; i < delstate->ndeltids; i++)
    8273              :     {
    8274       553055 :         TM_IndexDelete *ideltid = &delstate->deltids[i];
    8275       553055 :         TM_IndexStatus *istatus = delstate->status + ideltid->id;
    8276       553055 :         ItemPointer htid = &ideltid->tid;
    8277              :         OffsetNumber offnum;
    8278              : 
    8279              :         /*
    8280              :          * Read buffer, and perform required extra steps each time a new block
    8281              :          * is encountered.  Avoid refetching if it's the same block as the one
    8282              :          * from the last htid.
    8283              :          */
    8284      1100243 :         if (blkno == InvalidBlockNumber ||
    8285       547188 :             ItemPointerGetBlockNumber(htid) != blkno)
    8286              :         {
    8287              :             /*
    8288              :              * Consider giving up early for bottom-up index deletion caller
    8289              :              * first. (Only prefetch next-next block afterwards, when it
    8290              :              * becomes clear that we're at least going to access the next
    8291              :              * block in line.)
    8292              :              *
    8293              :              * Sometimes the first block frees so much space for bottom-up
    8294              :              * caller that the deletion process can end without accessing any
    8295              :              * more blocks.  It is usually necessary to access 2 or 3 blocks
    8296              :              * per bottom-up deletion operation, though.
    8297              :              */
    8298        15936 :             if (delstate->bottomup)
    8299              :             {
    8300              :                 /*
    8301              :                  * We often allow caller to delete a few additional items
    8302              :                  * whose entries we reached after the point that space target
    8303              :                  * from caller was satisfied.  The cost of accessing the page
    8304              :                  * was already paid at that point, so it made sense to finish
    8305              :                  * it off.  When that happened, we finalize everything here
    8306              :                  * (by finishing off the whole bottom-up deletion operation
    8307              :                  * without needlessly paying the cost of accessing any more
    8308              :                  * blocks).
    8309              :                  */
    8310         4423 :                 if (bottomup_final_block)
    8311          152 :                     break;
    8312              : 
    8313              :                 /*
    8314              :                  * Give up when we didn't enable our caller to free any
    8315              :                  * additional space as a result of processing the page that we
    8316              :                  * just finished up with.  This rule is the main way in which
    8317              :                  * we keep the cost of bottom-up deletion under control.
    8318              :                  */
    8319         4271 :                 if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
    8320         1813 :                     break;
    8321         2458 :                 lastfreespace = actualfreespace;    /* for next time */
    8322              : 
    8323              :                 /*
    8324              :                  * Deletion operation (which is bottom-up) will definitely
    8325              :                  * access the next block in line.  Prepare for that now.
    8326              :                  *
    8327              :                  * Decay target free space so that we don't hang on for too
    8328              :                  * long with a marginal case. (Space target is only truly
    8329              :                  * helpful when it allows us to recognize that we don't need
    8330              :                  * to access more than 1 or 2 blocks to satisfy caller due to
    8331              :                  * agreeable workload characteristics.)
    8332              :                  *
    8333              :                  * We are a bit more patient when we encounter contiguous
    8334              :                  * blocks, though: these are treated as favorable blocks.  The
    8335              :                  * decay process is only applied when the next block in line
    8336              :                  * is not a favorable/contiguous block.  This is not an
    8337              :                  * exception to the general rule; we still insist on finding
    8338              :                  * at least one deletable item per block accessed.  See
    8339              :                  * bottomup_nblocksfavorable() for full details of the theory
    8340              :                  * behind favorable blocks and heap block locality in general.
    8341              :                  *
    8342              :                  * Note: The first block in line is always treated as a
    8343              :                  * favorable block, so the earliest possible point that the
    8344              :                  * decay can be applied is just before we access the second
    8345              :                  * block in line.  The Assert() verifies this for us.
    8346              :                  */
    8347              :                 Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
    8348         2458 :                 if (nblocksfavorable > 0)
    8349         2209 :                     nblocksfavorable--;
    8350              :                 else
    8351          249 :                     curtargetfreespace /= 2;
    8352              :             }
    8353              : 
    8354              :             /* release old buffer */
    8355        13971 :             if (BufferIsValid(buf))
    8356         8104 :                 UnlockReleaseBuffer(buf);
    8357              : 
    8358        13971 :             blkno = ItemPointerGetBlockNumber(htid);
    8359        13971 :             buf = ReadBuffer(rel, blkno);
    8360        13971 :             nblocksaccessed++;
    8361              :             Assert(!delstate->bottomup ||
    8362              :                    nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
    8363              : 
    8364              : #ifdef USE_PREFETCH
    8365              : 
    8366              :             /*
    8367              :              * To maintain the prefetch distance, prefetch one more page for
    8368              :              * each page we read.
    8369              :              */
    8370        13971 :             index_delete_prefetch_buffer(rel, &prefetch_state, 1);
    8371              : #endif
    8372              : 
    8373        13971 :             LockBuffer(buf, BUFFER_LOCK_SHARE);
    8374              : 
    8375        13971 :             page = BufferGetPage(buf);
    8376        13971 :             maxoff = PageGetMaxOffsetNumber(page);
    8377              :         }
    8378              : 
    8379              :         /*
    8380              :          * In passing, detect index corruption involving an index page with a
    8381              :          * TID that points to a location in the heap that couldn't possibly be
    8382              :          * correct.  We only do this with actual TIDs from caller's index page
    8383              :          * (not items reached by traversing through a HOT chain).
    8384              :          */
    8385       551090 :         index_delete_check_htid(delstate, page, maxoff, htid, istatus);
    8386              : 
    8387       551090 :         if (istatus->knowndeletable)
    8388              :             Assert(!delstate->bottomup && !istatus->promising);
    8389              :         else
    8390              :         {
    8391       415152 :             ItemPointerData tmp = *htid;
    8392              :             HeapTupleData heapTuple;
    8393              : 
    8394              :             /* Are any tuples from this HOT chain non-vacuumable? */
    8395       415152 :             if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
    8396              :                                        &heapTuple, NULL, true))
    8397       246881 :                 continue;       /* can't delete entry */
    8398              : 
    8399              :             /* Caller will delete, since whole HOT chain is vacuumable */
    8400       168271 :             istatus->knowndeletable = true;
    8401              : 
    8402              :             /* Maintain index free space info for bottom-up deletion case */
    8403       168271 :             if (delstate->bottomup)
    8404              :             {
    8405              :                 Assert(istatus->freespace > 0);
    8406         9193 :                 actualfreespace += istatus->freespace;
    8407         9193 :                 if (actualfreespace >= curtargetfreespace)
    8408         2157 :                     bottomup_final_block = true;
    8409              :             }
    8410              :         }
    8411              : 
    8412              :         /*
    8413              :          * Maintain snapshotConflictHorizon value for deletion operation as a
    8414              :          * whole by advancing current value using heap tuple headers.  This is
    8415              :          * loosely based on the logic for pruning a HOT chain.
    8416              :          */
    8417       304209 :         offnum = ItemPointerGetOffsetNumber(htid);
    8418       304209 :         priorXmax = InvalidTransactionId;   /* cannot check first XMIN */
    8419              :         for (;;)
    8420        21435 :         {
    8421              :             ItemId      lp;
    8422              :             HeapTupleHeader htup;
    8423              : 
    8424              :             /* Sanity check (pure paranoia) */
    8425       325644 :             if (offnum < FirstOffsetNumber)
    8426            0 :                 break;
    8427              : 
    8428              :             /*
    8429              :              * An offset past the end of page's line pointer array is possible
    8430              :              * when the array was truncated
    8431              :              */
    8432       325644 :             if (offnum > maxoff)
    8433            0 :                 break;
    8434              : 
    8435       325644 :             lp = PageGetItemId(page, offnum);
    8436       325644 :             if (ItemIdIsRedirected(lp))
    8437              :             {
    8438         9385 :                 offnum = ItemIdGetRedirect(lp);
    8439         9385 :                 continue;
    8440              :             }
    8441              : 
    8442              :             /*
    8443              :              * We'll often encounter LP_DEAD line pointers (especially with an
    8444              :              * entry marked knowndeletable by our caller up front).  No heap
    8445              :              * tuple headers get examined for an htid that leads us to an
    8446              :              * LP_DEAD item.  This is okay because the earlier pruning
    8447              :              * operation that made the line pointer LP_DEAD in the first place
    8448              :              * must have considered the original tuple header as part of
    8449              :              * generating its own snapshotConflictHorizon value.
    8450              :              *
    8451              :              * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
    8452              :              * the same strategy that index vacuuming uses in all cases. Index
    8453              :              * VACUUM WAL records don't even have a snapshotConflictHorizon
    8454              :              * field of their own for this reason.
    8455              :              */
    8456       316259 :             if (!ItemIdIsNormal(lp))
    8457       200379 :                 break;
    8458              : 
    8459       115880 :             htup = (HeapTupleHeader) PageGetItem(page, lp);
    8460              : 
    8461              :             /*
    8462              :              * Check the tuple XMIN against prior XMAX, if any
    8463              :              */
    8464       127930 :             if (TransactionIdIsValid(priorXmax) &&
    8465        12050 :                 !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
    8466            0 :                 break;
    8467              : 
    8468       115880 :             HeapTupleHeaderAdvanceConflictHorizon(htup,
    8469              :                                                   &snapshotConflictHorizon);
    8470              : 
    8471              :             /*
    8472              :              * If the tuple is not HOT-updated, then we are at the end of this
    8473              :              * HOT-chain.  No need to visit later tuples from the same update
    8474              :              * chain (they get their own index entries) -- just move on to
    8475              :              * next htid from index AM caller.
    8476              :              */
    8477       115880 :             if (!HeapTupleHeaderIsHotUpdated(htup))
    8478       103830 :                 break;
    8479              : 
    8480              :             /* Advance to next HOT chain member */
    8481              :             Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
    8482        12050 :             offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
    8483        12050 :             priorXmax = HeapTupleHeaderGetUpdateXid(htup);
    8484              :         }
    8485              : 
    8486              :         /* Enable further/final shrinking of deltids for caller */
    8487       304209 :         finalndeltids = i + 1;
    8488              :     }
    8489              : 
    8490         5867 :     UnlockReleaseBuffer(buf);
    8491              : 
    8492              :     /*
    8493              :      * Shrink deltids array to exclude non-deletable entries at the end.  This
    8494              :      * is not just a minor optimization.  Final deltids array size might be
    8495              :      * zero for a bottom-up caller.  Index AM is explicitly allowed to rely on
    8496              :      * ndeltids being zero in all cases with zero total deletable entries.
    8497              :      */
    8498              :     Assert(finalndeltids > 0 || delstate->bottomup);
    8499         5867 :     delstate->ndeltids = finalndeltids;
    8500              : 
    8501         5867 :     return snapshotConflictHorizon;
    8502              : }
    8503              : 
    8504              : /*
    8505              :  * Specialized inlineable comparison function for index_delete_sort()
    8506              :  */
    8507              : static inline int
    8508     12893443 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
    8509              : {
    8510     12893443 :     ItemPointer tid1 = &deltid1->tid;
    8511     12893443 :     ItemPointer tid2 = &deltid2->tid;
    8512              : 
    8513              :     {
    8514     12893443 :         BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
    8515     12893443 :         BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
    8516              : 
    8517     12893443 :         if (blk1 != blk2)
    8518      5251798 :             return (blk1 < blk2) ? -1 : 1;
    8519              :     }
    8520              :     {
    8521      7641645 :         OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
    8522      7641645 :         OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
    8523              : 
    8524      7641645 :         if (pos1 != pos2)
    8525      7641645 :             return (pos1 < pos2) ? -1 : 1;
    8526              :     }
    8527              : 
    8528              :     Assert(false);
    8529              : 
    8530            0 :     return 0;
    8531              : }
    8532              : 
    8533              : /*
    8534              :  * Sort deltids array from delstate by TID.  This prepares it for further
    8535              :  * processing by heap_index_delete_tuples().
    8536              :  *
    8537              :  * This operation becomes a noticeable consumer of CPU cycles with some
    8538              :  * workloads, so we go to the trouble of specialization/micro optimization.
    8539              :  * We use shellsort for this because it's easy to specialize, compiles to
    8540              :  * relatively few instructions, and is adaptive to presorted inputs/subsets
    8541              :  * (which are typical here).
    8542              :  */
    8543              : static void
    8544         5867 : index_delete_sort(TM_IndexDeleteOp *delstate)
    8545              : {
    8546         5867 :     TM_IndexDelete *deltids = delstate->deltids;
    8547         5867 :     int         ndeltids = delstate->ndeltids;
    8548              : 
    8549              :     /*
    8550              :      * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
    8551              :      *
    8552              :      * This implementation is fast with array sizes up to ~4500.  This covers
    8553              :      * all supported BLCKSZ values.
    8554              :      */
    8555         5867 :     const int   gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
    8556              : 
    8557              :     /* Think carefully before changing anything here -- keep swaps cheap */
    8558              :     StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
    8559              :                      "element size exceeds 8 bytes");
    8560              : 
    8561        58670 :     for (int g = 0; g < lengthof(gaps); g++)
    8562              :     {
    8563      7681906 :         for (int hi = gaps[g], i = hi; i < ndeltids; i++)
    8564              :         {
    8565      7629103 :             TM_IndexDelete d = deltids[i];
    8566      7629103 :             int         j = i;
    8567              : 
    8568     13272407 :             while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
    8569              :             {
    8570      5643304 :                 deltids[j] = deltids[j - hi];
    8571      5643304 :                 j -= hi;
    8572              :             }
    8573      7629103 :             deltids[j] = d;
    8574              :         }
    8575              :     }
    8576         5867 : }
    8577              : 
    8578              : /*
    8579              :  * Returns how many blocks should be considered favorable/contiguous for a
    8580              :  * bottom-up index deletion pass.  This is a number of heap blocks that starts
    8581              :  * from and includes the first block in line.
    8582              :  *
    8583              :  * There is always at least one favorable block during bottom-up index
    8584              :  * deletion.  In the worst case (i.e. with totally random heap blocks) the
    8585              :  * first block in line (the only favorable block) can be thought of as a
    8586              :  * degenerate array of contiguous blocks that consists of a single block.
    8587              :  * heap_index_delete_tuples() will expect this.
    8588              :  *
    8589              :  * Caller passes blockgroups, a description of the final order that deltids
    8590              :  * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
    8591              :  * processing.  Note that deltids need not actually be sorted just yet (caller
    8592              :  * only passes deltids to us so that we can interpret blockgroups).
    8593              :  *
    8594              :  * You might guess that the existence of contiguous blocks cannot matter much,
    8595              :  * since in general the main factor that determines which blocks we visit is
    8596              :  * the number of promising TIDs, which is a fixed hint from the index AM.
    8597              :  * We're not really targeting the general case, though -- the actual goal is
    8598              :  * to adapt our behavior to a wide variety of naturally occurring conditions.
    8599              :  * The effects of most of the heuristics we apply are only noticeable in the
    8600              :  * aggregate, over time and across many _related_ bottom-up index deletion
    8601              :  * passes.
    8602              :  *
    8603              :  * Deeming certain blocks favorable allows heapam to recognize and adapt to
    8604              :  * workloads where heap blocks visited during bottom-up index deletion can be
    8605              :  * accessed contiguously, in the sense that each newly visited block is the
    8606              :  * neighbor of the block that bottom-up deletion just finished processing (or
    8607              :  * close enough to it).  It will likely be cheaper to access more favorable
    8608              :  * blocks sooner rather than later (e.g. in this pass, not across a series of
    8609              :  * related bottom-up passes).  Either way it is probably only a matter of time
    8610              :  * (or a matter of further correlated version churn) before all blocks that
    8611              :  * appear together as a single large batch of favorable blocks get accessed by
    8612              :  * _some_ bottom-up pass.  Large batches of favorable blocks tend to either
    8613              :  * appear almost constantly or not even once (it all depends on per-index
    8614              :  * workload characteristics).
    8615              :  *
    8616              :  * Note that the blockgroups sort order applies a power-of-two bucketing
    8617              :  * scheme that creates opportunities for contiguous groups of blocks to get
    8618              :  * batched together, at least with workloads that are naturally amenable to
    8619              :  * being driven by heap block locality.  This doesn't just enhance the spatial
    8620              :  * locality of bottom-up heap block processing in the obvious way.  It also
    8621              :  * enables temporal locality of access, since sorting by heap block number
    8622              :  * naturally tends to make the bottom-up processing order deterministic.
    8623              :  *
    8624              :  * Consider the following example to get a sense of how temporal locality
    8625              :  * might matter: There is a heap relation with several indexes, each of which
    8626              :  * is low to medium cardinality.  It is subject to constant non-HOT updates.
    8627              :  * The updates are skewed (in one part of the primary key, perhaps).  None of
    8628              :  * the indexes are logically modified by the UPDATE statements (if they were
    8629              :  * then bottom-up index deletion would not be triggered in the first place).
    8630              :  * Naturally, each new round of index tuples (for each heap tuple that gets a
    8631              :  * heap_update() call) will have the same heap TID in each and every index.
    8632              :  * Since these indexes are low cardinality and never get logically modified,
    8633              :  * heapam processing during bottom-up deletion passes will access heap blocks
    8634              :  * in approximately sequential order.  Temporal locality of access occurs due
    8635              :  * to bottom-up deletion passes behaving very similarly across each of the
    8636              :  * indexes at any given moment.  This keeps the number of buffer misses needed
    8637              :  * to visit heap blocks to a minimum.
    8638              :  */
    8639              : static int
    8640         1965 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
    8641              :                           TM_IndexDelete *deltids)
    8642              : {
    8643         1965 :     int64       lastblock = -1;
    8644         1965 :     int         nblocksfavorable = 0;
    8645              : 
    8646              :     Assert(nblockgroups >= 1);
    8647              :     Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
    8648              : 
    8649              :     /*
    8650              :      * We tolerate heap blocks that will be accessed only slightly out of
    8651              :      * physical order.  Small blips occur when a pair of almost-contiguous
    8652              :      * blocks happen to fall into different buckets (perhaps due only to a
    8653              :      * small difference in npromisingtids that the bucketing scheme didn't
    8654              :      * quite manage to ignore).  We effectively ignore these blips by applying
    8655              :      * a small tolerance.  The precise tolerance we use is a little arbitrary,
    8656              :      * but it works well enough in practice.
    8657              :      */
    8658         6471 :     for (int b = 0; b < nblockgroups; b++)
    8659              :     {
    8660         6151 :         IndexDeleteCounts *group = blockgroups + b;
    8661         6151 :         TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
    8662         6151 :         BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
    8663              : 
    8664         6151 :         if (lastblock != -1 &&
    8665         4186 :             ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
    8666         3718 :              (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
    8667              :             break;
    8668              : 
    8669         4506 :         nblocksfavorable++;
    8670         4506 :         lastblock = block;
    8671              :     }
    8672              : 
    8673              :     /* Always indicate that there is at least 1 favorable block */
    8674              :     Assert(nblocksfavorable >= 1);
    8675              : 
    8676         1965 :     return nblocksfavorable;
    8677              : }
    8678              : 
    8679              : /*
    8680              :  * qsort comparison function for bottomup_sort_and_shrink()
    8681              :  */
    8682              : static int
    8683       192552 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
    8684              : {
    8685       192552 :     const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
    8686       192552 :     const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
    8687              : 
    8688              :     /*
    8689              :      * Most significant field is npromisingtids (which we invert the order of
    8690              :      * so as to sort in desc order).
    8691              :      *
    8692              :      * Caller should have already normalized npromisingtids fields into
    8693              :      * power-of-two values (buckets).
    8694              :      */
    8695       192552 :     if (group1->npromisingtids > group2->npromisingtids)
    8696         9174 :         return -1;
    8697       183378 :     if (group1->npromisingtids < group2->npromisingtids)
    8698        10417 :         return 1;
    8699              : 
    8700              :     /*
    8701              :      * Tiebreak: desc ntids sort order.
    8702              :      *
    8703              :      * We cannot expect power-of-two values for ntids fields.  We should
    8704              :      * behave as if they were already rounded up for us instead.
    8705              :      */
    8706       172961 :     if (group1->ntids != group2->ntids)
    8707              :     {
    8708       123513 :         uint32      ntids1 = pg_nextpower2_32((uint32) group1->ntids);
    8709       123513 :         uint32      ntids2 = pg_nextpower2_32((uint32) group2->ntids);
    8710              : 
    8711       123513 :         if (ntids1 > ntids2)
    8712        17963 :             return -1;
    8713       105550 :         if (ntids1 < ntids2)
    8714        22425 :             return 1;
    8715              :     }
    8716              : 
    8717              :     /*
    8718              :      * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
    8719              :      * block in deltids array) order.
    8720              :      *
    8721              :      * This is equivalent to sorting in ascending heap block number order
    8722              :      * (among otherwise equal subsets of the array).  This approach allows us
    8723              :      * to avoid accessing the out-of-line TID.  (We rely on the assumption
    8724              :      * that the deltids array was sorted in ascending heap TID order when
    8725              :      * these offsets to the first TID from each heap block group were formed.)
    8726              :      */
    8727       132573 :     if (group1->ifirsttid > group2->ifirsttid)
    8728        64281 :         return 1;
    8729        68292 :     if (group1->ifirsttid < group2->ifirsttid)
    8730        68292 :         return -1;
    8731              : 
    8732            0 :     pg_unreachable();
    8733              : 
    8734              :     return 0;
    8735              : }
    8736              : 
    8737              : /*
    8738              :  * heap_index_delete_tuples() helper function for bottom-up deletion callers.
    8739              :  *
    8740              :  * Sorts deltids array in the order needed for useful processing by bottom-up
    8741              :  * deletion.  The array should already be sorted in TID order when we're
    8742              :  * called.  The sort process groups heap TIDs from deltids into heap block
    8743              :  * groupings.  Earlier/more-promising groups/blocks are usually those that are
    8744              :  * known to have the most "promising" TIDs.
    8745              :  *
    8746              :  * Sets new size of deltids array (ndeltids) in state.  deltids will only have
    8747              :  * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
    8748              :  * return.  This often means that deltids will be shrunk to a small fraction
    8749              :  * of its original size (we eliminate many heap blocks from consideration for
    8750              :  * caller up front).
    8751              :  *
    8752              :  * Returns the number of "favorable" blocks.  See bottomup_nblocksfavorable()
    8753              :  * for a definition and full details.
    8754              :  */
    8755              : static int
    8756         1965 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
    8757              : {
    8758              :     IndexDeleteCounts *blockgroups;
    8759              :     TM_IndexDelete *reordereddeltids;
    8760         1965 :     BlockNumber curblock = InvalidBlockNumber;
    8761         1965 :     int         nblockgroups = 0;
    8762         1965 :     int         ncopied = 0;
    8763         1965 :     int         nblocksfavorable = 0;
    8764              : 
    8765              :     Assert(delstate->bottomup);
    8766              :     Assert(delstate->ndeltids > 0);
    8767              : 
    8768              :     /* Calculate per-heap-block count of TIDs */
    8769         1965 :     blockgroups = palloc_array(IndexDeleteCounts, delstate->ndeltids);
    8770       951352 :     for (int i = 0; i < delstate->ndeltids; i++)
    8771              :     {
    8772       949387 :         TM_IndexDelete *ideltid = &delstate->deltids[i];
    8773       949387 :         TM_IndexStatus *istatus = delstate->status + ideltid->id;
    8774       949387 :         ItemPointer htid = &ideltid->tid;
    8775       949387 :         bool        promising = istatus->promising;
    8776              : 
    8777       949387 :         if (curblock != ItemPointerGetBlockNumber(htid))
    8778              :         {
    8779              :             /* New block group */
    8780        37693 :             nblockgroups++;
    8781              : 
    8782              :             Assert(curblock < ItemPointerGetBlockNumber(htid) ||
    8783              :                    !BlockNumberIsValid(curblock));
    8784              : 
    8785        37693 :             curblock = ItemPointerGetBlockNumber(htid);
    8786        37693 :             blockgroups[nblockgroups - 1].ifirsttid = i;
    8787        37693 :             blockgroups[nblockgroups - 1].ntids = 1;
    8788        37693 :             blockgroups[nblockgroups - 1].npromisingtids = 0;
    8789              :         }
    8790              :         else
    8791              :         {
    8792       911694 :             blockgroups[nblockgroups - 1].ntids++;
    8793              :         }
    8794              : 
    8795       949387 :         if (promising)
    8796       121665 :             blockgroups[nblockgroups - 1].npromisingtids++;
    8797              :     }
    8798              : 
    8799              :     /*
    8800              :      * We're about ready to sort block groups to determine the optimal order
    8801              :      * for visiting heap blocks.  But before we do, round the number of
    8802              :      * promising tuples for each block group up to the next power-of-two,
    8803              :      * unless it is very low (less than 4), in which case we round up to 4.
    8804              :      * npromisingtids is far too noisy to trust when choosing between a pair
    8805              :      * of block groups that both have very low values.
    8806              :      *
    8807              :      * This scheme divides heap blocks/block groups into buckets.  Each bucket
    8808              :      * contains blocks that have _approximately_ the same number of promising
    8809              :      * TIDs as each other.  The goal is to ignore relatively small differences
    8810              :      * in the total number of promising entries, so that the whole process can
    8811              :      * give a little weight to heapam factors (like heap block locality)
    8812              :      * instead.  This isn't a trade-off, really -- we have nothing to lose. It
    8813              :      * would be foolish to interpret small differences in npromisingtids
    8814              :      * values as anything more than noise.
    8815              :      *
    8816              :      * We tiebreak on nhtids when sorting block group subsets that have the
    8817              :      * same npromisingtids, but this has the same issues as npromisingtids,
    8818              :      * and so nhtids is subject to the same power-of-two bucketing scheme. The
    8819              :      * only reason that we don't fix nhtids in the same way here too is that
    8820              :      * we'll need accurate nhtids values after the sort.  We handle nhtids
    8821              :      * bucketization dynamically instead (in the sort comparator).
    8822              :      *
    8823              :      * See bottomup_nblocksfavorable() for a full explanation of when and how
    8824              :      * heap locality/favorable blocks can significantly influence when and how
    8825              :      * heap blocks are accessed.
    8826              :      */
    8827        39658 :     for (int b = 0; b < nblockgroups; b++)
    8828              :     {
    8829        37693 :         IndexDeleteCounts *group = blockgroups + b;
    8830              : 
    8831              :         /* Better off falling back on nhtids with low npromisingtids */
    8832        37693 :         if (group->npromisingtids <= 4)
    8833        32190 :             group->npromisingtids = 4;
    8834              :         else
    8835         5503 :             group->npromisingtids =
    8836         5503 :                 pg_nextpower2_32((uint32) group->npromisingtids);
    8837              :     }
    8838              : 
    8839              :     /* Sort groups and rearrange caller's deltids array */
    8840         1965 :     qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
    8841              :           bottomup_sort_and_shrink_cmp);
    8842         1965 :     reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
    8843              : 
    8844         1965 :     nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
    8845              :     /* Determine number of favorable blocks at the start of final deltids */
    8846         1965 :     nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
    8847              :                                                  delstate->deltids);
    8848              : 
    8849        13146 :     for (int b = 0; b < nblockgroups; b++)
    8850              :     {
    8851        11181 :         IndexDeleteCounts *group = blockgroups + b;
    8852        11181 :         TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
    8853              : 
    8854        11181 :         memcpy(reordereddeltids + ncopied, firstdtid,
    8855        11181 :                sizeof(TM_IndexDelete) * group->ntids);
    8856        11181 :         ncopied += group->ntids;
    8857              :     }
    8858              : 
    8859              :     /* Copy final grouped and sorted TIDs back into start of caller's array */
    8860         1965 :     memcpy(delstate->deltids, reordereddeltids,
    8861              :            sizeof(TM_IndexDelete) * ncopied);
    8862         1965 :     delstate->ndeltids = ncopied;
    8863              : 
    8864         1965 :     pfree(reordereddeltids);
    8865         1965 :     pfree(blockgroups);
    8866              : 
    8867         1965 :     return nblocksfavorable;
    8868              : }
    8869              : 
    8870              : /*
    8871              :  * Perform XLogInsert for a heap-visible operation.  'block' is the block
    8872              :  * being marked all-visible, and vm_buffer is the buffer containing the
    8873              :  * corresponding visibility map block.  Both should have already been modified
    8874              :  * and dirtied.
    8875              :  *
    8876              :  * snapshotConflictHorizon comes from the largest xmin on the page being
    8877              :  * marked all-visible.  REDO routine uses it to generate recovery conflicts.
    8878              :  *
    8879              :  * If checksums or wal_log_hints are enabled, we may also generate a full-page
    8880              :  * image of heap_buffer. Otherwise, we optimize away the FPI (by specifying
    8881              :  * REGBUF_NO_IMAGE for the heap buffer), in which case the caller should *not*
    8882              :  * update the heap page's LSN.
    8883              :  */
    8884              : XLogRecPtr
    8885        35535 : log_heap_visible(Relation rel, Buffer heap_buffer, Buffer vm_buffer,
    8886              :                  TransactionId snapshotConflictHorizon, uint8 vmflags)
    8887              : {
    8888              :     xl_heap_visible xlrec;
    8889              :     XLogRecPtr  recptr;
    8890              :     uint8       flags;
    8891              : 
    8892              :     Assert(BufferIsValid(heap_buffer));
    8893              :     Assert(BufferIsValid(vm_buffer));
    8894              : 
    8895        35535 :     xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
    8896        35535 :     xlrec.flags = vmflags;
    8897        35535 :     if (RelationIsAccessibleInLogicalDecoding(rel))
    8898           63 :         xlrec.flags |= VISIBILITYMAP_XLOG_CATALOG_REL;
    8899        35535 :     XLogBeginInsert();
    8900        35535 :     XLogRegisterData(&xlrec, SizeOfHeapVisible);
    8901              : 
    8902        35535 :     XLogRegisterBuffer(0, vm_buffer, 0);
    8903              : 
    8904        35535 :     flags = REGBUF_STANDARD;
    8905        35535 :     if (!XLogHintBitIsNeeded())
    8906         3135 :         flags |= REGBUF_NO_IMAGE;
    8907        35535 :     XLogRegisterBuffer(1, heap_buffer, flags);
    8908              : 
    8909        35535 :     recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);
    8910              : 
    8911        35535 :     return recptr;
    8912              : }
    8913              : 
    8914              : /*
    8915              :  * Perform XLogInsert for a heap-update operation.  Caller must already
    8916              :  * have modified the buffer(s) and marked them dirty.
    8917              :  */
    8918              : static XLogRecPtr
    8919       299371 : log_heap_update(Relation reln, Buffer oldbuf,
    8920              :                 Buffer newbuf, HeapTuple oldtup, HeapTuple newtup,
    8921              :                 HeapTuple old_key_tuple,
    8922              :                 bool all_visible_cleared, bool new_all_visible_cleared)
    8923              : {
    8924              :     xl_heap_update xlrec;
    8925              :     xl_heap_header xlhdr;
    8926              :     xl_heap_header xlhdr_idx;
    8927              :     uint8       info;
    8928              :     uint16      prefix_suffix[2];
    8929       299371 :     uint16      prefixlen = 0,
    8930       299371 :                 suffixlen = 0;
    8931              :     XLogRecPtr  recptr;
    8932       299371 :     Page        page = BufferGetPage(newbuf);
    8933       299371 :     bool        need_tuple_data = RelationIsLogicallyLogged(reln);
    8934              :     bool        init;
    8935              :     int         bufflags;
    8936              : 
    8937              :     /* Caller should not call me on a non-WAL-logged relation */
    8938              :     Assert(RelationNeedsWAL(reln));
    8939              : 
    8940       299371 :     XLogBeginInsert();
    8941              : 
    8942       299371 :     if (HeapTupleIsHeapOnly(newtup))
    8943       146939 :         info = XLOG_HEAP_HOT_UPDATE;
    8944              :     else
    8945       152432 :         info = XLOG_HEAP_UPDATE;
    8946              : 
    8947              :     /*
    8948              :      * If the old and new tuple are on the same page, we only need to log the
    8949              :      * parts of the new tuple that were changed.  That saves on the amount of
    8950              :      * WAL we need to write.  Currently, we just count any unchanged bytes in
    8951              :      * the beginning and end of the tuple.  That's quick to check, and
    8952              :      * perfectly covers the common case that only one field is updated.
    8953              :      *
    8954              :      * We could do this even if the old and new tuple are on different pages,
    8955              :      * but only if we don't make a full-page image of the old page, which is
    8956              :      * difficult to know in advance.  Also, if the old tuple is corrupt for
    8957              :      * some reason, it would allow the corruption to propagate the new page,
    8958              :      * so it seems best to avoid.  Under the general assumption that most
    8959              :      * updates tend to create the new tuple version on the same page, there
    8960              :      * isn't much to be gained by doing this across pages anyway.
    8961              :      *
    8962              :      * Skip this if we're taking a full-page image of the new page, as we
    8963              :      * don't include the new tuple in the WAL record in that case.  Also
    8964              :      * disable if effective_wal_level='logical', as logical decoding needs to
    8965              :      * be able to read the new tuple in whole from the WAL record alone.
    8966              :      */
    8967       299371 :     if (oldbuf == newbuf && !need_tuple_data &&
    8968       147335 :         !XLogCheckBufferNeedsBackup(newbuf))
    8969              :     {
    8970       146716 :         char       *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
    8971       146716 :         char       *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
    8972       146716 :         int         oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
    8973       146716 :         int         newlen = newtup->t_len - newtup->t_data->t_hoff;
    8974              : 
    8975              :         /* Check for common prefix between old and new tuple */
    8976     12331801 :         for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
    8977              :         {
    8978     12305637 :             if (newp[prefixlen] != oldp[prefixlen])
    8979       120552 :                 break;
    8980              :         }
    8981              : 
    8982              :         /*
    8983              :          * Storing the length of the prefix takes 2 bytes, so we need to save
    8984              :          * at least 3 bytes or there's no point.
    8985              :          */
    8986       146716 :         if (prefixlen < 3)
    8987        22105 :             prefixlen = 0;
    8988              : 
    8989              :         /* Same for suffix */
    8990      4828440 :         for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
    8991              :         {
    8992      4802017 :             if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
    8993       120293 :                 break;
    8994              :         }
    8995       146716 :         if (suffixlen < 3)
    8996        36955 :             suffixlen = 0;
    8997              :     }
    8998              : 
    8999              :     /* Prepare main WAL data chain */
    9000       299371 :     xlrec.flags = 0;
    9001       299371 :     if (all_visible_cleared)
    9002         1602 :         xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
    9003       299371 :     if (new_all_visible_cleared)
    9004          926 :         xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
    9005       299371 :     if (prefixlen > 0)
    9006       124611 :         xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
    9007       299371 :     if (suffixlen > 0)
    9008       109761 :         xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
    9009       299371 :     if (need_tuple_data)
    9010              :     {
    9011        47022 :         xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
    9012        47022 :         if (old_key_tuple)
    9013              :         {
    9014          146 :             if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
    9015           65 :                 xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
    9016              :             else
    9017           81 :                 xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
    9018              :         }
    9019              :     }
    9020              : 
    9021              :     /* If new tuple is the single and first tuple on page... */
    9022       302945 :     if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
    9023         3574 :         PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
    9024              :     {
    9025         3275 :         info |= XLOG_HEAP_INIT_PAGE;
    9026         3275 :         init = true;
    9027              :     }
    9028              :     else
    9029       296096 :         init = false;
    9030              : 
    9031              :     /* Prepare WAL data for the old page */
    9032       299371 :     xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
    9033       299371 :     xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
    9034       598742 :     xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
    9035       299371 :                                               oldtup->t_data->t_infomask2);
    9036              : 
    9037              :     /* Prepare WAL data for the new page */
    9038       299371 :     xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
    9039       299371 :     xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
    9040              : 
    9041       299371 :     bufflags = REGBUF_STANDARD;
    9042       299371 :     if (init)
    9043         3275 :         bufflags |= REGBUF_WILL_INIT;
    9044       299371 :     if (need_tuple_data)
    9045        47022 :         bufflags |= REGBUF_KEEP_DATA;
    9046              : 
    9047       299371 :     XLogRegisterBuffer(0, newbuf, bufflags);
    9048       299371 :     if (oldbuf != newbuf)
    9049       140094 :         XLogRegisterBuffer(1, oldbuf, REGBUF_STANDARD);
    9050              : 
    9051       299371 :     XLogRegisterData(&xlrec, SizeOfHeapUpdate);
    9052              : 
    9053              :     /*
    9054              :      * Prepare WAL data for the new tuple.
    9055              :      */
    9056       299371 :     if (prefixlen > 0 || suffixlen > 0)
    9057              :     {
    9058       146248 :         if (prefixlen > 0 && suffixlen > 0)
    9059              :         {
    9060        88124 :             prefix_suffix[0] = prefixlen;
    9061        88124 :             prefix_suffix[1] = suffixlen;
    9062        88124 :             XLogRegisterBufData(0, &prefix_suffix, sizeof(uint16) * 2);
    9063              :         }
    9064        58124 :         else if (prefixlen > 0)
    9065              :         {
    9066        36487 :             XLogRegisterBufData(0, &prefixlen, sizeof(uint16));
    9067              :         }
    9068              :         else
    9069              :         {
    9070        21637 :             XLogRegisterBufData(0, &suffixlen, sizeof(uint16));
    9071              :         }
    9072              :     }
    9073              : 
    9074       299371 :     xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
    9075       299371 :     xlhdr.t_infomask = newtup->t_data->t_infomask;
    9076       299371 :     xlhdr.t_hoff = newtup->t_data->t_hoff;
    9077              :     Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
    9078              : 
    9079              :     /*
    9080              :      * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
    9081              :      *
    9082              :      * The 'data' doesn't include the common prefix or suffix.
    9083              :      */
    9084       299371 :     XLogRegisterBufData(0, &xlhdr, SizeOfHeapHeader);
    9085       299371 :     if (prefixlen == 0)
    9086              :     {
    9087       174760 :         XLogRegisterBufData(0,
    9088       174760 :                             (char *) newtup->t_data + SizeofHeapTupleHeader,
    9089       174760 :                             newtup->t_len - SizeofHeapTupleHeader - suffixlen);
    9090              :     }
    9091              :     else
    9092              :     {
    9093              :         /*
    9094              :          * Have to write the null bitmap and data after the common prefix as
    9095              :          * two separate rdata entries.
    9096              :          */
    9097              :         /* bitmap [+ padding] [+ oid] */
    9098       124611 :         if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
    9099              :         {
    9100       124611 :             XLogRegisterBufData(0,
    9101       124611 :                                 (char *) newtup->t_data + SizeofHeapTupleHeader,
    9102       124611 :                                 newtup->t_data->t_hoff - SizeofHeapTupleHeader);
    9103              :         }
    9104              : 
    9105              :         /* data after common prefix */
    9106       124611 :         XLogRegisterBufData(0,
    9107       124611 :                             (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
    9108       124611 :                             newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
    9109              :     }
    9110              : 
    9111              :     /* We need to log a tuple identity */
    9112       299371 :     if (need_tuple_data && old_key_tuple)
    9113              :     {
    9114              :         /* don't really need this, but its more comfy to decode */
    9115          146 :         xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
    9116          146 :         xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
    9117          146 :         xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
    9118              : 
    9119          146 :         XLogRegisterData(&xlhdr_idx, SizeOfHeapHeader);
    9120              : 
    9121              :         /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
    9122          146 :         XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
    9123          146 :                          old_key_tuple->t_len - SizeofHeapTupleHeader);
    9124              :     }
    9125              : 
    9126              :     /* filtering by origin on a row level is much more efficient */
    9127       299371 :     XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
    9128              : 
    9129       299371 :     recptr = XLogInsert(RM_HEAP_ID, info);
    9130              : 
    9131       299371 :     return recptr;
    9132              : }
    9133              : 
    9134              : /*
    9135              :  * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
    9136              :  *
    9137              :  * This is only used when effective_wal_level is logical, and only for
    9138              :  * catalog tuples.
    9139              :  */
    9140              : static XLogRecPtr
    9141        24661 : log_heap_new_cid(Relation relation, HeapTuple tup)
    9142              : {
    9143              :     xl_heap_new_cid xlrec;
    9144              : 
    9145              :     XLogRecPtr  recptr;
    9146        24661 :     HeapTupleHeader hdr = tup->t_data;
    9147              : 
    9148              :     Assert(ItemPointerIsValid(&tup->t_self));
    9149              :     Assert(tup->t_tableOid != InvalidOid);
    9150              : 
    9151        24661 :     xlrec.top_xid = GetTopTransactionId();
    9152        24661 :     xlrec.target_locator = relation->rd_locator;
    9153        24661 :     xlrec.target_tid = tup->t_self;
    9154              : 
    9155              :     /*
    9156              :      * If the tuple got inserted & deleted in the same TX we definitely have a
    9157              :      * combo CID, set cmin and cmax.
    9158              :      */
    9159        24661 :     if (hdr->t_infomask & HEAP_COMBOCID)
    9160              :     {
    9161              :         Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
    9162              :         Assert(!HeapTupleHeaderXminInvalid(hdr));
    9163         2024 :         xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
    9164         2024 :         xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
    9165         2024 :         xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
    9166              :     }
    9167              :     /* No combo CID, so only cmin or cmax can be set by this TX */
    9168              :     else
    9169              :     {
    9170              :         /*
    9171              :          * Tuple inserted.
    9172              :          *
    9173              :          * We need to check for LOCK ONLY because multixacts might be
    9174              :          * transferred to the new tuple in case of FOR KEY SHARE updates in
    9175              :          * which case there will be an xmax, although the tuple just got
    9176              :          * inserted.
    9177              :          */
    9178        29473 :         if (hdr->t_infomask & HEAP_XMAX_INVALID ||
    9179         6836 :             HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
    9180              :         {
    9181        15802 :             xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
    9182        15802 :             xlrec.cmax = InvalidCommandId;
    9183              :         }
    9184              :         /* Tuple from a different tx updated or deleted. */
    9185              :         else
    9186              :         {
    9187         6835 :             xlrec.cmin = InvalidCommandId;
    9188         6835 :             xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
    9189              :         }
    9190        22637 :         xlrec.combocid = InvalidCommandId;
    9191              :     }
    9192              : 
    9193              :     /*
    9194              :      * Note that we don't need to register the buffer here, because this
    9195              :      * operation does not modify the page. The insert/update/delete that
    9196              :      * called us certainly did, but that's WAL-logged separately.
    9197              :      */
    9198        24661 :     XLogBeginInsert();
    9199        24661 :     XLogRegisterData(&xlrec, SizeOfHeapNewCid);
    9200              : 
    9201              :     /* will be looked at irrespective of origin */
    9202              : 
    9203        24661 :     recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
    9204              : 
    9205        24661 :     return recptr;
    9206              : }
    9207              : 
    9208              : /*
    9209              :  * Build a heap tuple representing the configured REPLICA IDENTITY to represent
    9210              :  * the old tuple in an UPDATE or DELETE.
    9211              :  *
    9212              :  * Returns NULL if there's no need to log an identity or if there's no suitable
    9213              :  * key defined.
    9214              :  *
    9215              :  * Pass key_required true if any replica identity columns changed value, or if
    9216              :  * any of them have any external data.  Delete must always pass true.
    9217              :  *
    9218              :  * *copy is set to true if the returned tuple is a modified copy rather than
    9219              :  * the same tuple that was passed in.
    9220              :  */
    9221              : static HeapTuple
    9222      1838098 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
    9223              :                        bool *copy)
    9224              : {
    9225      1838098 :     TupleDesc   desc = RelationGetDescr(relation);
    9226      1838098 :     char        replident = relation->rd_rel->relreplident;
    9227              :     Bitmapset  *idattrs;
    9228              :     HeapTuple   key_tuple;
    9229              :     bool        nulls[MaxHeapAttributeNumber];
    9230              :     Datum       values[MaxHeapAttributeNumber];
    9231              : 
    9232      1838098 :     *copy = false;
    9233              : 
    9234      1838098 :     if (!RelationIsLogicallyLogged(relation))
    9235      1737806 :         return NULL;
    9236              : 
    9237       100292 :     if (replident == REPLICA_IDENTITY_NOTHING)
    9238          231 :         return NULL;
    9239              : 
    9240       100061 :     if (replident == REPLICA_IDENTITY_FULL)
    9241              :     {
    9242              :         /*
    9243              :          * When logging the entire old tuple, it very well could contain
    9244              :          * toasted columns. If so, force them to be inlined.
    9245              :          */
    9246          197 :         if (HeapTupleHasExternal(tp))
    9247              :         {
    9248            4 :             *copy = true;
    9249            4 :             tp = toast_flatten_tuple(tp, desc);
    9250              :         }
    9251          197 :         return tp;
    9252              :     }
    9253              : 
    9254              :     /* if the key isn't required and we're only logging the key, we're done */
    9255        99864 :     if (!key_required)
    9256        46876 :         return NULL;
    9257              : 
    9258              :     /* find out the replica identity columns */
    9259        52988 :     idattrs = RelationGetIndexAttrBitmap(relation,
    9260              :                                          INDEX_ATTR_BITMAP_IDENTITY_KEY);
    9261              : 
    9262              :     /*
    9263              :      * If there's no defined replica identity columns, treat as !key_required.
    9264              :      * (This case should not be reachable from heap_update, since that should
    9265              :      * calculate key_required accurately.  But heap_delete just passes
    9266              :      * constant true for key_required, so we can hit this case in deletes.)
    9267              :      */
    9268        52988 :     if (bms_is_empty(idattrs))
    9269         6021 :         return NULL;
    9270              : 
    9271              :     /*
    9272              :      * Construct a new tuple containing only the replica identity columns,
    9273              :      * with nulls elsewhere.  While we're at it, assert that the replica
    9274              :      * identity columns aren't null.
    9275              :      */
    9276        46967 :     heap_deform_tuple(tp, desc, values, nulls);
    9277              : 
    9278       150895 :     for (int i = 0; i < desc->natts; i++)
    9279              :     {
    9280       103928 :         if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
    9281              :                           idattrs))
    9282              :             Assert(!nulls[i]);
    9283              :         else
    9284        56949 :             nulls[i] = true;
    9285              :     }
    9286              : 
    9287        46967 :     key_tuple = heap_form_tuple(desc, values, nulls);
    9288        46967 :     *copy = true;
    9289              : 
    9290        46967 :     bms_free(idattrs);
    9291              : 
    9292              :     /*
    9293              :      * If the tuple, which by here only contains indexed columns, still has
    9294              :      * toasted columns, force them to be inlined. This is somewhat unlikely
    9295              :      * since there's limits on the size of indexed columns, so we don't
    9296              :      * duplicate toast_flatten_tuple()s functionality in the above loop over
    9297              :      * the indexed columns, even if it would be more efficient.
    9298              :      */
    9299        46967 :     if (HeapTupleHasExternal(key_tuple))
    9300              :     {
    9301            4 :         HeapTuple   oldtup = key_tuple;
    9302              : 
    9303            4 :         key_tuple = toast_flatten_tuple(oldtup, desc);
    9304            4 :         heap_freetuple(oldtup);
    9305              :     }
    9306              : 
    9307        46967 :     return key_tuple;
    9308              : }
    9309              : 
    9310              : /*
    9311              :  * HeapCheckForSerializableConflictOut
    9312              :  *      We are reading a tuple.  If it's not visible, there may be a
    9313              :  *      rw-conflict out with the inserter.  Otherwise, if it is visible to us
    9314              :  *      but has been deleted, there may be a rw-conflict out with the deleter.
    9315              :  *
    9316              :  * We will determine the top level xid of the writing transaction with which
    9317              :  * we may be in conflict, and ask CheckForSerializableConflictOut() to check
    9318              :  * for overlap with our own transaction.
    9319              :  *
    9320              :  * This function should be called just about anywhere in heapam.c where a
    9321              :  * tuple has been read. The caller must hold at least a shared lock on the
    9322              :  * buffer, because this function might set hint bits on the tuple. There is
    9323              :  * currently no known reason to call this function from an index AM.
    9324              :  */
    9325              : void
    9326     32450189 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
    9327              :                                     HeapTuple tuple, Buffer buffer,
    9328              :                                     Snapshot snapshot)
    9329              : {
    9330              :     TransactionId xid;
    9331              :     HTSV_Result htsvResult;
    9332              : 
    9333     32450189 :     if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
    9334     32424815 :         return;
    9335              : 
    9336              :     /*
    9337              :      * Check to see whether the tuple has been written to by a concurrent
    9338              :      * transaction, either to create it not visible to us, or to delete it
    9339              :      * while it is visible to us.  The "visible" bool indicates whether the
    9340              :      * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
    9341              :      * is going on with it.
    9342              :      *
    9343              :      * In the event of a concurrently inserted tuple that also happens to have
    9344              :      * been concurrently updated (by a separate transaction), the xmin of the
    9345              :      * tuple will be used -- not the updater's xid.
    9346              :      */
    9347        25374 :     htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
    9348        25374 :     switch (htsvResult)
    9349              :     {
    9350        24561 :         case HEAPTUPLE_LIVE:
    9351        24561 :             if (visible)
    9352        24548 :                 return;
    9353           13 :             xid = HeapTupleHeaderGetXmin(tuple->t_data);
    9354           13 :             break;
    9355          361 :         case HEAPTUPLE_RECENTLY_DEAD:
    9356              :         case HEAPTUPLE_DELETE_IN_PROGRESS:
    9357          361 :             if (visible)
    9358          285 :                 xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
    9359              :             else
    9360           76 :                 xid = HeapTupleHeaderGetXmin(tuple->t_data);
    9361              : 
    9362          361 :             if (TransactionIdPrecedes(xid, TransactionXmin))
    9363              :             {
    9364              :                 /* This is like the HEAPTUPLE_DEAD case */
    9365              :                 Assert(!visible);
    9366           67 :                 return;
    9367              :             }
    9368          294 :             break;
    9369          328 :         case HEAPTUPLE_INSERT_IN_PROGRESS:
    9370          328 :             xid = HeapTupleHeaderGetXmin(tuple->t_data);
    9371          328 :             break;
    9372          124 :         case HEAPTUPLE_DEAD:
    9373              :             Assert(!visible);
    9374          124 :             return;
    9375            0 :         default:
    9376              : 
    9377              :             /*
    9378              :              * The only way to get to this default clause is if a new value is
    9379              :              * added to the enum type without adding it to this switch
    9380              :              * statement.  That's a bug, so elog.
    9381              :              */
    9382            0 :             elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
    9383              : 
    9384              :             /*
    9385              :              * In spite of having all enum values covered and calling elog on
    9386              :              * this default, some compilers think this is a code path which
    9387              :              * allows xid to be used below without initialization. Silence
    9388              :              * that warning.
    9389              :              */
    9390              :             xid = InvalidTransactionId;
    9391              :     }
    9392              : 
    9393              :     Assert(TransactionIdIsValid(xid));
    9394              :     Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
    9395              : 
    9396              :     /*
    9397              :      * Find top level xid.  Bail out if xid is too early to be a conflict, or
    9398              :      * if it's our own xid.
    9399              :      */
    9400          635 :     if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
    9401           64 :         return;
    9402          571 :     xid = SubTransGetTopmostTransaction(xid);
    9403          571 :     if (TransactionIdPrecedes(xid, TransactionXmin))
    9404            0 :         return;
    9405              : 
    9406          571 :     CheckForSerializableConflictOut(relation, xid, snapshot);
    9407              : }
        

Generated by: LCOV version 2.0-1