LCOV - code coverage report
Current view: top level - src/backend/access/heap - heapam.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 91.7 % 2800 2568
Test Date: 2026-07-26 05:16:53 Functions: 100.0 % 80 80
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 77.2 % 2026 1565

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

Generated by: LCOV version 2.0-1