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

Generated by: LCOV version 2.0-1