LCOV - differential code coverage report
Current view: top level - src/backend/access/heap - heapam.c (source / functions) Coverage Total Hit UNC UBC GBC GIC GNC CBC DCB
Current: 806555e3000d0b0e0c536c1dc65548128d457d86 vs 1d325ad99cb2dec0e8b45ba36909ee0a497d2a57 Lines: 91.2 % 2912 2656 2 254 1 43 2612 34
Current Date: 2025-12-17 08:58:58 +0900 Functions: 100.0 % 84 84 17 67 9
Baseline: lcov-20251217-005640-baseline Branches: 71.0 % 2325 1651 26 648 4 28 1619
Baseline Date: 2025-12-16 12:57:12 -0800 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 91.7 % 12 11 1 10 1
(7,30] days: 100.0 % 12 12 12
(30,360] days: 83.0 % 100 83 1 16 21 62
(360..) days: 91.5 % 2788 2550 238 1 2549
Function coverage date bins:
(30,360] days: 100.0 % 12 12 9 3
(360..) days: 100.0 % 72 72 8 64
Branch coverage date bins:
(1,7] days: 37.5 % 8 3 5 3
(7,30] days: 100.0 % 12 12 12
(30,360] days: 52.9 % 68 36 21 11 1 13 22
(360..) days: 71.5 % 2237 1600 637 3 1597

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * heapam.c
                                  4                 :                :  *    heap access method code
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
                                  7                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                  8                 :                :  *
                                  9                 :                :  *
                                 10                 :                :  * IDENTIFICATION
                                 11                 :                :  *    src/backend/access/heap/heapam.c
                                 12                 :                :  *
                                 13                 :                :  *
                                 14                 :                :  * INTERFACE ROUTINES
                                 15                 :                :  *      heap_beginscan  - begin relation scan
                                 16                 :                :  *      heap_rescan     - restart a relation scan
                                 17                 :                :  *      heap_endscan    - end relation scan
                                 18                 :                :  *      heap_getnext    - retrieve next tuple in scan
                                 19                 :                :  *      heap_fetch      - retrieve tuple with given tid
                                 20                 :                :  *      heap_insert     - insert tuple into a relation
                                 21                 :                :  *      heap_multi_insert - insert multiple tuples into a relation
                                 22                 :                :  *      heap_delete     - delete a tuple from a relation
                                 23                 :                :  *      heap_update     - replace a tuple in a relation with another tuple
                                 24                 :                :  *
                                 25                 :                :  * NOTES
                                 26                 :                :  *    This file contains the heap_ routines which implement
                                 27                 :                :  *    the POSTGRES heap access method used for all POSTGRES
                                 28                 :                :  *    relations.
                                 29                 :                :  *
                                 30                 :                :  *-------------------------------------------------------------------------
                                 31                 :                :  */
                                 32                 :                : #include "postgres.h"
                                 33                 :                : 
                                 34                 :                : #include "access/heapam.h"
                                 35                 :                : #include "access/heaptoast.h"
                                 36                 :                : #include "access/hio.h"
                                 37                 :                : #include "access/multixact.h"
                                 38                 :                : #include "access/subtrans.h"
                                 39                 :                : #include "access/syncscan.h"
                                 40                 :                : #include "access/valid.h"
                                 41                 :                : #include "access/visibilitymap.h"
                                 42                 :                : #include "access/xloginsert.h"
                                 43                 :                : #include "catalog/pg_database.h"
                                 44                 :                : #include "catalog/pg_database_d.h"
                                 45                 :                : #include "commands/vacuum.h"
                                 46                 :                : #include "pgstat.h"
                                 47                 :                : #include "port/pg_bitutils.h"
                                 48                 :                : #include "storage/lmgr.h"
                                 49                 :                : #include "storage/predicate.h"
                                 50                 :                : #include "storage/procarray.h"
                                 51                 :                : #include "utils/datum.h"
                                 52                 :                : #include "utils/injection_point.h"
                                 53                 :                : #include "utils/inval.h"
                                 54                 :                : #include "utils/spccache.h"
                                 55                 :                : #include "utils/syscache.h"
                                 56                 :                : 
                                 57                 :                : 
                                 58                 :                : static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
                                 59                 :                :                                      TransactionId xid, CommandId cid, int options);
                                 60                 :                : static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
                                 61                 :                :                                   Buffer newbuf, HeapTuple oldtup,
                                 62                 :                :                                   HeapTuple newtup, HeapTuple old_key_tuple,
                                 63                 :                :                                   bool all_visible_cleared, bool new_all_visible_cleared);
                                 64                 :                : #ifdef USE_ASSERT_CHECKING
                                 65                 :                : static void check_lock_if_inplace_updateable_rel(Relation relation,
                                 66                 :                :                                                  const ItemPointerData *otid,
                                 67                 :                :                                                  HeapTuple newtup);
                                 68                 :                : static void check_inplace_rel_lock(HeapTuple oldtup);
                                 69                 :                : #endif
                                 70                 :                : static Bitmapset *HeapDetermineColumnsInfo(Relation relation,
                                 71                 :                :                                            Bitmapset *interesting_cols,
                                 72                 :                :                                            Bitmapset *external_cols,
                                 73                 :                :                                            HeapTuple oldtup, HeapTuple newtup,
                                 74                 :                :                                            bool *has_external);
                                 75                 :                : static bool heap_acquire_tuplock(Relation relation, const ItemPointerData *tid,
                                 76                 :                :                                  LockTupleMode mode, LockWaitPolicy wait_policy,
                                 77                 :                :                                  bool *have_tuple_lock);
                                 78                 :                : static inline BlockNumber heapgettup_advance_block(HeapScanDesc scan,
                                 79                 :                :                                                    BlockNumber block,
                                 80                 :                :                                                    ScanDirection dir);
                                 81                 :                : static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan,
                                 82                 :                :                                                         ScanDirection dir);
                                 83                 :                : static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
                                 84                 :                :                                       uint16 old_infomask2, TransactionId add_to_xmax,
                                 85                 :                :                                       LockTupleMode mode, bool is_update,
                                 86                 :                :                                       TransactionId *result_xmax, uint16 *result_infomask,
                                 87                 :                :                                       uint16 *result_infomask2);
                                 88                 :                : static TM_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple,
                                 89                 :                :                                          const ItemPointerData *ctid, TransactionId xid,
                                 90                 :                :                                          LockTupleMode mode);
                                 91                 :                : static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
                                 92                 :                :                                    uint16 *new_infomask2);
                                 93                 :                : static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax,
                                 94                 :                :                                              uint16 t_infomask);
                                 95                 :                : static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
                                 96                 :                :                                     LockTupleMode lockmode, bool *current_is_member);
                                 97                 :                : static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
                                 98                 :                :                             Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
                                 99                 :                :                             int *remaining);
                                100                 :                : static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
                                101                 :                :                                        uint16 infomask, Relation rel, int *remaining,
                                102                 :                :                                        bool logLockFailure);
                                103                 :                : static void index_delete_sort(TM_IndexDeleteOp *delstate);
                                104                 :                : static int  bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate);
                                105                 :                : static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
                                106                 :                : static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
                                107                 :                :                                         bool *copy);
                                108                 :                : 
                                109                 :                : 
                                110                 :                : /*
                                111                 :                :  * Each tuple lock mode has a corresponding heavyweight lock, and one or two
                                112                 :                :  * corresponding MultiXactStatuses (one to merely lock tuples, another one to
                                113                 :                :  * update them).  This table (and the macros below) helps us determine the
                                114                 :                :  * heavyweight lock mode and MultiXactStatus values to use for any particular
                                115                 :                :  * tuple lock strength.
                                116                 :                :  *
                                117                 :                :  * These interact with InplaceUpdateTupleLock, an alias for ExclusiveLock.
                                118                 :                :  *
                                119                 :                :  * Don't look at lockstatus/updstatus directly!  Use get_mxact_status_for_lock
                                120                 :                :  * instead.
                                121                 :                :  */
                                122                 :                : static const struct
                                123                 :                : {
                                124                 :                :     LOCKMODE    hwlock;
                                125                 :                :     int         lockstatus;
                                126                 :                :     int         updstatus;
                                127                 :                : }
                                128                 :                : 
                                129                 :                :             tupleLockExtraInfo[MaxLockTupleMode + 1] =
                                130                 :                : {
                                131                 :                :     {                           /* LockTupleKeyShare */
                                132                 :                :         AccessShareLock,
                                133                 :                :         MultiXactStatusForKeyShare,
                                134                 :                :         -1                      /* KeyShare does not allow updating tuples */
                                135                 :                :     },
                                136                 :                :     {                           /* LockTupleShare */
                                137                 :                :         RowShareLock,
                                138                 :                :         MultiXactStatusForShare,
                                139                 :                :         -1                      /* Share does not allow updating tuples */
                                140                 :                :     },
                                141                 :                :     {                           /* LockTupleNoKeyExclusive */
                                142                 :                :         ExclusiveLock,
                                143                 :                :         MultiXactStatusForNoKeyUpdate,
                                144                 :                :         MultiXactStatusNoKeyUpdate
                                145                 :                :     },
                                146                 :                :     {                           /* LockTupleExclusive */
                                147                 :                :         AccessExclusiveLock,
                                148                 :                :         MultiXactStatusForUpdate,
                                149                 :                :         MultiXactStatusUpdate
                                150                 :                :     }
                                151                 :                : };
                                152                 :                : 
                                153                 :                : /* Get the LOCKMODE for a given MultiXactStatus */
                                154                 :                : #define LOCKMODE_from_mxstatus(status) \
                                155                 :                :             (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
                                156                 :                : 
                                157                 :                : /*
                                158                 :                :  * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
                                159                 :                :  * This is more readable than having every caller translate it to lock.h's
                                160                 :                :  * LOCKMODE.
                                161                 :                :  */
                                162                 :                : #define LockTupleTuplock(rel, tup, mode) \
                                163                 :                :     LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
                                164                 :                : #define UnlockTupleTuplock(rel, tup, mode) \
                                165                 :                :     UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
                                166                 :                : #define ConditionalLockTupleTuplock(rel, tup, mode, log) \
                                167                 :                :     ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock, (log))
                                168                 :                : 
                                169                 :                : #ifdef USE_PREFETCH
                                170                 :                : /*
                                171                 :                :  * heap_index_delete_tuples and index_delete_prefetch_buffer use this
                                172                 :                :  * structure to coordinate prefetching activity
                                173                 :                :  */
                                174                 :                : typedef struct
                                175                 :                : {
                                176                 :                :     BlockNumber cur_hblkno;
                                177                 :                :     int         next_item;
                                178                 :                :     int         ndeltids;
                                179                 :                :     TM_IndexDelete *deltids;
                                180                 :                : } IndexDeletePrefetchState;
                                181                 :                : #endif
                                182                 :                : 
                                183                 :                : /* heap_index_delete_tuples bottom-up index deletion costing constants */
                                184                 :                : #define BOTTOMUP_MAX_NBLOCKS            6
                                185                 :                : #define BOTTOMUP_TOLERANCE_NBLOCKS      3
                                186                 :                : 
                                187                 :                : /*
                                188                 :                :  * heap_index_delete_tuples uses this when determining which heap blocks it
                                189                 :                :  * must visit to help its bottom-up index deletion caller
                                190                 :                :  */
                                191                 :                : typedef struct IndexDeleteCounts
                                192                 :                : {
                                193                 :                :     int16       npromisingtids; /* Number of "promising" TIDs in group */
                                194                 :                :     int16       ntids;          /* Number of TIDs in group */
                                195                 :                :     int16       ifirsttid;      /* Offset to group's first deltid */
                                196                 :                : } IndexDeleteCounts;
                                197                 :                : 
                                198                 :                : /*
                                199                 :                :  * This table maps tuple lock strength values for each particular
                                200                 :                :  * MultiXactStatus value.
                                201                 :                :  */
                                202                 :                : static const int MultiXactStatusLock[MaxMultiXactStatus + 1] =
                                203                 :                : {
                                204                 :                :     LockTupleKeyShare,          /* ForKeyShare */
                                205                 :                :     LockTupleShare,             /* ForShare */
                                206                 :                :     LockTupleNoKeyExclusive,    /* ForNoKeyUpdate */
                                207                 :                :     LockTupleExclusive,         /* ForUpdate */
                                208                 :                :     LockTupleNoKeyExclusive,    /* NoKeyUpdate */
                                209                 :                :     LockTupleExclusive          /* Update */
                                210                 :                : };
                                211                 :                : 
                                212                 :                : /* Get the LockTupleMode for a given MultiXactStatus */
                                213                 :                : #define TUPLOCK_from_mxstatus(status) \
                                214                 :                :             (MultiXactStatusLock[(status)])
                                215                 :                : 
                                216                 :                : /*
                                217                 :                :  * Check that we have a valid snapshot if we might need TOAST access.
                                218                 :                :  */
                                219                 :                : static inline void
  201 nathan@postgresql.or      220                 :CBC    10583584 : AssertHasSnapshotForToast(Relation rel)
                                221                 :                : {
                                222                 :                : #ifdef USE_ASSERT_CHECKING
                                223                 :                : 
                                224                 :                :     /* bootstrap mode in particular breaks this rule */
                                225         [ +  + ]:       10583584 :     if (!IsNormalProcessingMode())
                                226                 :         597516 :         return;
                                227                 :                : 
                                228                 :                :     /* if the relation doesn't have a TOAST table, we are good */
                                229         [ +  + ]:        9986068 :     if (!OidIsValid(rel->rd_rel->reltoastrelid))
                                230                 :        5170316 :         return;
                                231                 :                : 
                                232         [ -  + ]:        4815752 :     Assert(HaveRegisteredOrActiveSnapshot());
                                233                 :                : 
                                234                 :                : #endif                          /* USE_ASSERT_CHECKING */
                                235                 :                : }
                                236                 :                : 
                                237                 :                : /* ----------------------------------------------------------------
                                238                 :                :  *                       heap support routines
                                239                 :                :  * ----------------------------------------------------------------
                                240                 :                :  */
                                241                 :                : 
                                242                 :                : /*
                                243                 :                :  * Streaming read API callback for parallel sequential scans. Returns the next
                                244                 :                :  * block the caller wants from the read stream or InvalidBlockNumber when done.
                                245                 :                :  */
                                246                 :                : static BlockNumber
  618 tmunro@postgresql.or      247                 :         101342 : heap_scan_stream_read_next_parallel(ReadStream *stream,
                                248                 :                :                                     void *callback_private_data,
                                249                 :                :                                     void *per_buffer_data)
                                250                 :                : {
                                251                 :         101342 :     HeapScanDesc scan = (HeapScanDesc) callback_private_data;
                                252                 :                : 
                                253         [ -  + ]:         101342 :     Assert(ScanDirectionIsForward(scan->rs_dir));
                                254         [ -  + ]:         101342 :     Assert(scan->rs_base.rs_parallel);
                                255                 :                : 
                                256         [ +  + ]:         101342 :     if (unlikely(!scan->rs_inited))
                                257                 :                :     {
                                258                 :                :         /* parallel scan */
                                259                 :           1645 :         table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
                                260                 :           1645 :                                                  scan->rs_parallelworkerdata,
   20 drowley@postgresql.o      261                 :GNC        1645 :                                                  (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel,
                                262                 :                :                                                  scan->rs_startblock,
                                263                 :                :                                                  scan->rs_numblocks);
                                264                 :                : 
                                265                 :                :         /* may return InvalidBlockNumber if there are no more blocks */
  618 tmunro@postgresql.or      266                 :CBC        3290 :         scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
                                267                 :           1645 :                                                                     scan->rs_parallelworkerdata,
                                268                 :           1645 :                                                                     (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
                                269                 :           1645 :         scan->rs_inited = true;
                                270                 :                :     }
                                271                 :                :     else
                                272                 :                :     {
                                273                 :          99697 :         scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
                                274                 :          99697 :                                                                     scan->rs_parallelworkerdata, (ParallelBlockTableScanDesc)
                                275                 :          99697 :                                                                     scan->rs_base.rs_parallel);
                                276                 :                :     }
                                277                 :                : 
                                278                 :         101342 :     return scan->rs_prefetch_block;
                                279                 :                : }
                                280                 :                : 
                                281                 :                : /*
                                282                 :                :  * Streaming read API callback for serial sequential and TID range scans.
                                283                 :                :  * Returns the next block the caller wants from the read stream or
                                284                 :                :  * InvalidBlockNumber when done.
                                285                 :                :  */
                                286                 :                : static BlockNumber
                                287                 :        3657485 : heap_scan_stream_read_next_serial(ReadStream *stream,
                                288                 :                :                                   void *callback_private_data,
                                289                 :                :                                   void *per_buffer_data)
                                290                 :                : {
                                291                 :        3657485 :     HeapScanDesc scan = (HeapScanDesc) callback_private_data;
                                292                 :                : 
                                293         [ +  + ]:        3657485 :     if (unlikely(!scan->rs_inited))
                                294                 :                :     {
                                295                 :         983976 :         scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
                                296                 :         983976 :         scan->rs_inited = true;
                                297                 :                :     }
                                298                 :                :     else
                                299                 :        2673509 :         scan->rs_prefetch_block = heapgettup_advance_block(scan,
                                300                 :                :                                                            scan->rs_prefetch_block,
                                301                 :                :                                                            scan->rs_dir);
                                302                 :                : 
                                303                 :        3657485 :     return scan->rs_prefetch_block;
                                304                 :                : }
                                305                 :                : 
                                306                 :                : /*
                                307                 :                :  * Read stream API callback for bitmap heap scans.
                                308                 :                :  * Returns the next block the caller wants from the read stream or
                                309                 :                :  * InvalidBlockNumber when done.
                                310                 :                :  */
                                311                 :                : static BlockNumber
  277 melanieplageman@gmai      312                 :         214378 : bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data,
                                313                 :                :                             void *per_buffer_data)
                                314                 :                : {
                                315                 :         214378 :     TBMIterateResult *tbmres = per_buffer_data;
                                316                 :         214378 :     BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) private_data;
                                317                 :         214378 :     HeapScanDesc hscan = (HeapScanDesc) bscan;
                                318                 :         214378 :     TableScanDesc sscan = &hscan->rs_base;
                                319                 :                : 
                                320                 :                :     for (;;)
                                321                 :                :     {
                                322         [ +  + ]:         214378 :         CHECK_FOR_INTERRUPTS();
                                323                 :                : 
                                324                 :                :         /* no more entries in the bitmap */
                                325         [ +  + ]:         214378 :         if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
                                326                 :          12593 :             return InvalidBlockNumber;
                                327                 :                : 
                                328                 :                :         /*
                                329                 :                :          * Ignore any claimed entries past what we think is the end of the
                                330                 :                :          * relation. It may have been extended after the start of our scan (we
                                331                 :                :          * only hold an AccessShareLock, and it could be inserts from this
                                332                 :                :          * backend).  We don't take this optimization in SERIALIZABLE
                                333                 :                :          * isolation though, as we need to examine all invisible tuples
                                334                 :                :          * reachable by the index.
                                335                 :                :          */
                                336         [ +  + ]:         201785 :         if (!IsolationIsSerializable() &&
                                337         [ -  + ]:         201676 :             tbmres->blockno >= hscan->rs_nblocks)
  277 melanieplageman@gmai      338                 :UBC           0 :             continue;
                                339                 :                : 
  277 melanieplageman@gmai      340                 :CBC      201785 :         return tbmres->blockno;
                                341                 :                :     }
                                342                 :                : 
                                343                 :                :     /* not reachable */
                                344                 :                :     Assert(false);
                                345                 :                : }
                                346                 :                : 
                                347                 :                : /* ----------------
                                348                 :                :  *      initscan - scan code common to heap_beginscan and heap_rescan
                                349                 :                :  * ----------------
                                350                 :                :  */
                                351                 :                : static void
 3798 tgl@sss.pgh.pa.us         352                 :        1008385 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
                                353                 :                : {
 2473 andres@anarazel.de        354                 :        1008385 :     ParallelBlockTableScanDesc bpscan = NULL;
                                355                 :                :     bool        allow_strat;
                                356                 :                :     bool        allow_sync;
                                357                 :                : 
                                358                 :                :     /*
                                359                 :                :      * Determine the number of blocks we have to scan.
                                360                 :                :      *
                                361                 :                :      * It is sufficient to do this once at scan start, since any tuples added
                                362                 :                :      * while the scan is in progress will be invisible to my snapshot anyway.
                                363                 :                :      * (That is not true when using a non-MVCC snapshot.  However, we couldn't
                                364                 :                :      * guarantee to return tuples added after scan start anyway, since they
                                365                 :                :      * might go into pages we already scanned.  To guarantee consistent
                                366                 :                :      * results for a non-MVCC snapshot, the caller must hold some higher-level
                                367                 :                :      * lock that ensures the interesting tuple(s) won't change.)
                                368                 :                :      */
                                369         [ +  + ]:        1008385 :     if (scan->rs_base.rs_parallel != NULL)
                                370                 :                :     {
                                371                 :           2172 :         bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
                                372                 :           2172 :         scan->rs_nblocks = bpscan->phs_nblocks;
                                373                 :                :     }
                                374                 :                :     else
                                375                 :        1006213 :         scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_base.rs_rd);
                                376                 :                : 
                                377                 :                :     /*
                                378                 :                :      * If the table is large relative to NBuffers, use a bulk-read access
                                379                 :                :      * strategy and enable synchronized scanning (see syncscan.c).  Although
                                380                 :                :      * the thresholds for these features could be different, we make them the
                                381                 :                :      * same so that there are only two behaviors to tune rather than four.
                                382                 :                :      * (However, some callers need to be able to disable one or both of these
                                383                 :                :      * behaviors, independently of the size of the table; also there is a GUC
                                384                 :                :      * variable that can disable synchronized scanning.)
                                385                 :                :      *
                                386                 :                :      * Note that table_block_parallelscan_initialize has a very similar test;
                                387                 :                :      * if you change this, consider changing that one, too.
                                388                 :                :      */
                                389         [ +  + ]:        1008383 :     if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
 6766 tgl@sss.pgh.pa.us         390         [ +  + ]:        1001057 :         scan->rs_nblocks > NBuffers / 4)
                                391                 :                :     {
 2404 andres@anarazel.de        392                 :          14313 :         allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
                                393                 :          14313 :         allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
                                394                 :                :     }
                                395                 :                :     else
 6547 tgl@sss.pgh.pa.us         396                 :         994070 :         allow_strat = allow_sync = false;
                                397                 :                : 
                                398         [ +  + ]:        1008383 :     if (allow_strat)
                                399                 :                :     {
                                400                 :                :         /* During a rescan, keep the previous strategy object. */
 6776                           401         [ +  + ]:          12977 :         if (scan->rs_strategy == NULL)
                                402                 :          12806 :             scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
                                403                 :                :     }
                                404                 :                :     else
                                405                 :                :     {
                                406         [ -  + ]:         995406 :         if (scan->rs_strategy != NULL)
 6776 tgl@sss.pgh.pa.us         407                 :UBC           0 :             FreeAccessStrategy(scan->rs_strategy);
 6776 tgl@sss.pgh.pa.us         408                 :CBC      995406 :         scan->rs_strategy = NULL;
                                409                 :                :     }
                                410                 :                : 
 2473 andres@anarazel.de        411         [ +  + ]:        1008383 :     if (scan->rs_base.rs_parallel != NULL)
                                412                 :                :     {
                                413                 :                :         /* For parallel scan, believe whatever ParallelTableScanDesc says. */
 2404                           414         [ +  + ]:           2172 :         if (scan->rs_base.rs_parallel->phs_syncscan)
                                415                 :              2 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                                416                 :                :         else
                                417                 :           2170 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                418                 :                : 
                                419                 :                :         /*
                                420                 :                :          * If not rescanning, initialize the startblock.  Finding the actual
                                421                 :                :          * start location is done in table_block_parallelscan_startblock_init,
                                422                 :                :          * based on whether an alternative start location has been set with
                                423                 :                :          * heap_setscanlimits, or using the syncscan location, when syncscan
                                424                 :                :          * is enabled.
                                425                 :                :          */
   19 drowley@postgresql.o      426         [ +  + ]:GNC        2172 :         if (!keep_startblock)
                                427                 :           2058 :             scan->rs_startblock = InvalidBlockNumber;
                                428                 :                :     }
                                429                 :                :     else
                                430                 :                :     {
                                431         [ +  + ]:        1006211 :         if (keep_startblock)
                                432                 :                :         {
                                433                 :                :             /*
                                434                 :                :              * When rescanning, we want to keep the previous startblock
                                435                 :                :              * setting, so that rewinding a cursor doesn't generate surprising
                                436                 :                :              * results.  Reset the active syncscan setting, though.
                                437                 :                :              */
                                438   [ +  +  +  + ]:         632441 :             if (allow_sync && synchronize_seqscans)
                                439                 :             50 :                 scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                                440                 :                :             else
                                441                 :         632391 :                 scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                442                 :                :         }
                                443   [ +  +  +  + ]:         373770 :         else if (allow_sync && synchronize_seqscans)
                                444                 :                :         {
                                445                 :             72 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                                446                 :             72 :             scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
                                447                 :                :         }
                                448                 :                :         else
                                449                 :                :         {
                                450                 :         373698 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                451                 :         373698 :             scan->rs_startblock = 0;
                                452                 :                :         }
                                453                 :                :     }
                                454                 :                : 
 4058 alvherre@alvh.no-ip.      455                 :CBC     1008383 :     scan->rs_numblocks = InvalidBlockNumber;
 7326 tgl@sss.pgh.pa.us         456                 :        1008383 :     scan->rs_inited = false;
 8957                           457                 :        1008383 :     scan->rs_ctup.t_data = NULL;
 7326                           458                 :        1008383 :     ItemPointerSetInvalid(&scan->rs_ctup.t_self);
 8957                           459                 :        1008383 :     scan->rs_cbuf = InvalidBuffer;
 7326                           460                 :        1008383 :     scan->rs_cblock = InvalidBlockNumber;
  364 melanieplageman@gmai      461                 :        1008383 :     scan->rs_ntuples = 0;
                                462                 :        1008383 :     scan->rs_cindex = 0;
                                463                 :                : 
                                464                 :                :     /*
                                465                 :                :      * Initialize to ForwardScanDirection because it is most common and
                                466                 :                :      * because heap scans go forward before going backward (e.g. CURSORs).
                                467                 :                :      */
  618 tmunro@postgresql.or      468                 :        1008383 :     scan->rs_dir = ForwardScanDirection;
                                469                 :        1008383 :     scan->rs_prefetch_block = InvalidBlockNumber;
                                470                 :                : 
                                471                 :                :     /* page-at-a-time fields are always invalid when not rs_inited */
                                472                 :                : 
                                473                 :                :     /*
                                474                 :                :      * copy the scan key, if appropriate
                                475                 :                :      */
 1385 tgl@sss.pgh.pa.us         476   [ +  +  +  + ]:        1008383 :     if (key != NULL && scan->rs_base.rs_nkeys > 0)
 2473 andres@anarazel.de        477                 :         214084 :         memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
                                478                 :                : 
                                479                 :                :     /*
                                480                 :                :      * Currently, we only have a stats counter for sequential heap scans (but
                                481                 :                :      * e.g for bitmap scans the underlying bitmap index scans will be counted,
                                482                 :                :      * and for sample scans we update stats for tuple fetches).
                                483                 :                :      */
 2404                           484         [ +  + ]:        1008383 :     if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
 2473                           485   [ +  +  +  +  :         985179 :         pgstat_count_heap_scan(scan->rs_base.rs_rd);
                                              +  + ]
10753 scrappy@hub.org           486                 :        1008383 : }
                                487                 :                : 
                                488                 :                : /*
                                489                 :                :  * heap_setscanlimits - restrict range of a heapscan
                                490                 :                :  *
                                491                 :                :  * startBlk is the page to start at
                                492                 :                :  * numBlks is number of pages to scan (InvalidBlockNumber means "all")
                                493                 :                :  */
                                494                 :                : void
 2473 andres@anarazel.de        495                 :           2878 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
                                496                 :                : {
                                497                 :           2878 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                                498                 :                : 
 3802 tgl@sss.pgh.pa.us         499         [ -  + ]:           2878 :     Assert(!scan->rs_inited);    /* else too late to change */
                                500                 :                :     /* else rs_startblock is significant */
 2404 andres@anarazel.de        501         [ -  + ]:           2878 :     Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
                                502                 :                : 
                                503                 :                :     /* Check startBlk is valid (but allow case of zero blocks...) */
 3802 tgl@sss.pgh.pa.us         504   [ +  +  -  + ]:           2878 :     Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
                                505                 :                : 
 4058 alvherre@alvh.no-ip.      506                 :           2878 :     scan->rs_startblock = startBlk;
                                507                 :           2878 :     scan->rs_numblocks = numBlks;
                                508                 :           2878 : }
                                509                 :                : 
                                510                 :                : /*
                                511                 :                :  * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
                                512                 :                :  * multiple times, with constant arguments for all_visible,
                                513                 :                :  * check_serializable.
                                514                 :                :  */
                                515                 :                : pg_attribute_always_inline
                                516                 :                : static int
  619 andres@anarazel.de        517                 :        2664157 : page_collect_tuples(HeapScanDesc scan, Snapshot snapshot,
                                518                 :                :                     Page page, Buffer buffer,
                                519                 :                :                     BlockNumber block, int lines,
                                520                 :                :                     bool all_visible, bool check_serializable)
                                521                 :                : {
  620                           522                 :        2664157 :     int         ntup = 0;
                                523                 :                :     OffsetNumber lineoff;
                                524                 :                : 
                                525         [ +  + ]:      134047296 :     for (lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
                                526                 :                :     {
                                527                 :      131383147 :         ItemId      lpp = PageGetItemId(page, lineoff);
                                528                 :                :         HeapTupleData loctup;
                                529                 :                :         bool        valid;
                                530                 :                : 
                                531         [ +  + ]:      131383147 :         if (!ItemIdIsNormal(lpp))
                                532                 :       25525295 :             continue;
                                533                 :                : 
                                534                 :      105857852 :         loctup.t_data = (HeapTupleHeader) PageGetItem(page, lpp);
                                535                 :      105857852 :         loctup.t_len = ItemIdGetLength(lpp);
                                536                 :      105857852 :         loctup.t_tableOid = RelationGetRelid(scan->rs_base.rs_rd);
                                537                 :      105857852 :         ItemPointerSet(&(loctup.t_self), block, lineoff);
                                538                 :                : 
                                539         [ +  + ]:      105857852 :         if (all_visible)
                                540                 :       40576159 :             valid = true;
                                541                 :                :         else
                                542                 :       65281693 :             valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
                                543                 :                : 
                                544         [ +  + ]:      105857852 :         if (check_serializable)
                                545                 :           1421 :             HeapCheckForSerializableConflictOut(valid, scan->rs_base.rs_rd,
                                546                 :                :                                                 &loctup, buffer, snapshot);
                                547                 :                : 
                                548         [ +  + ]:      105857844 :         if (valid)
                                549                 :                :         {
                                550                 :       98452210 :             scan->rs_vistuples[ntup] = lineoff;
                                551                 :       98452210 :             ntup++;
                                552                 :                :         }
                                553                 :                :     }
                                554                 :                : 
                                555         [ -  + ]:        2664149 :     Assert(ntup <= MaxHeapTuplesPerPage);
                                556                 :                : 
                                557                 :        2664149 :     return ntup;
                                558                 :                : }
                                559                 :                : 
                                560                 :                : /*
                                561                 :                :  * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
                                562                 :                :  *
                                563                 :                :  * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
                                564                 :                :  * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
                                565                 :                :  */
                                566                 :                : void
  622 drowley@postgresql.o      567                 :        2664157 : heap_prepare_pagescan(TableScanDesc sscan)
                                568                 :                : {
 2473 andres@anarazel.de        569                 :        2664157 :     HeapScanDesc scan = (HeapScanDesc) sscan;
  622 drowley@postgresql.o      570                 :        2664157 :     Buffer      buffer = scan->rs_cbuf;
                                571                 :        2664157 :     BlockNumber block = scan->rs_cblock;
                                572                 :                :     Snapshot    snapshot;
                                573                 :                :     Page        page;
                                574                 :                :     int         lines;
                                575                 :                :     bool        all_visible;
                                576                 :                :     bool        check_serializable;
                                577                 :                : 
                                578         [ -  + ]:        2664157 :     Assert(BufferGetBlockNumber(buffer) == block);
                                579                 :                : 
                                580                 :                :     /* ensure we're not accidentally being used when not in pagemode */
                                581         [ -  + ]:        2664157 :     Assert(scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE);
 2473 andres@anarazel.de        582                 :        2664157 :     snapshot = scan->rs_base.rs_snapshot;
                                583                 :                : 
                                584                 :                :     /*
                                585                 :                :      * Prune and repair fragmentation for the whole page, if possible.
                                586                 :                :      */
                                587                 :        2664157 :     heap_page_prune_opt(scan->rs_base.rs_rd, buffer);
                                588                 :                : 
                                589                 :                :     /*
                                590                 :                :      * We must hold share lock on the buffer content while examining tuple
                                591                 :                :      * visibility.  Afterwards, however, the tuples we have found to be
                                592                 :                :      * visible are guaranteed good as long as we hold the buffer pin.
                                593                 :                :      */
 7326 tgl@sss.pgh.pa.us         594                 :        2664157 :     LockBuffer(buffer, BUFFER_LOCK_SHARE);
                                595                 :                : 
 1127 peter@eisentraut.org      596                 :        2664157 :     page = BufferGetPage(buffer);
                                597                 :        2664157 :     lines = PageGetMaxOffsetNumber(page);
                                598                 :                : 
                                599                 :                :     /*
                                600                 :                :      * If the all-visible flag indicates that all tuples on the page are
                                601                 :                :      * visible to everyone, we can skip the per-tuple visibility tests.
                                602                 :                :      *
                                603                 :                :      * Note: In hot standby, a tuple that's already visible to all
                                604                 :                :      * transactions on the primary might still be invisible to a read-only
                                605                 :                :      * transaction in the standby. We partly handle this problem by tracking
                                606                 :                :      * the minimum xmin of visible tuples as the cut-off XID while marking a
                                607                 :                :      * page all-visible on the primary and WAL log that along with the
                                608                 :                :      * visibility map SET operation. In hot standby, we wait for (or abort)
                                609                 :                :      * all transactions that can potentially may not see one or more tuples on
                                610                 :                :      * the page. That's how index-only scans work fine in hot standby. A
                                611                 :                :      * crucial difference between index-only scans and heap scans is that the
                                612                 :                :      * index-only scan completely relies on the visibility map where as heap
                                613                 :                :      * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
                                614                 :                :      * the page-level flag can be trusted in the same way, because it might
                                615                 :                :      * get propagated somehow without being explicitly WAL-logged, e.g. via a
                                616                 :                :      * full page write. Until we can prove that beyond doubt, let's check each
                                617                 :                :      * tuple for visibility the hard way.
                                618                 :                :      */
                                619   [ +  +  +  + ]:        2664157 :     all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
                                620                 :                :     check_serializable =
  620 andres@anarazel.de        621                 :        2664157 :         CheckForSerializableConflictOutNeeded(scan->rs_base.rs_rd, snapshot);
                                622                 :                : 
                                623                 :                :     /*
                                624                 :                :      * We call page_collect_tuples() with constant arguments, to get the
                                625                 :                :      * compiler to constant fold the constant arguments. Separate calls with
                                626                 :                :      * constant arguments, rather than variables, are needed on several
                                627                 :                :      * compilers to actually perform constant folding.
                                628                 :                :      */
                                629         [ +  + ]:        2664157 :     if (likely(all_visible))
                                630                 :                :     {
                                631         [ +  - ]:         988129 :         if (likely(!check_serializable))
  619                           632                 :         988129 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                633                 :                :                                                    block, lines, true, false);
                                634                 :                :         else
  619 andres@anarazel.de        635                 :UBC           0 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                636                 :                :                                                    block, lines, true, true);
                                637                 :                :     }
                                638                 :                :     else
                                639                 :                :     {
  620 andres@anarazel.de        640         [ +  + ]:CBC     1676028 :         if (likely(!check_serializable))
  619                           641                 :        1675396 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                642                 :                :                                                    block, lines, false, false);
                                643                 :                :         else
                                644                 :            632 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                645                 :                :                                                    block, lines, false, true);
                                646                 :                :     }
                                647                 :                : 
 7326 tgl@sss.pgh.pa.us         648                 :        2664149 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                                649                 :        2664149 : }
                                650                 :                : 
                                651                 :                : /*
                                652                 :                :  * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
                                653                 :                :  *
                                654                 :                :  * Read the next block of the scan relation from the read stream and save it
                                655                 :                :  * in the scan descriptor.  It is already pinned.
                                656                 :                :  */
                                657                 :                : static inline void
  622 drowley@postgresql.o      658                 :        3579175 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
                                659                 :                : {
  618 tmunro@postgresql.or      660         [ -  + ]:        3579175 :     Assert(scan->rs_read_stream);
                                661                 :                : 
                                662                 :                :     /* release previous scan buffer, if any */
  622 drowley@postgresql.o      663         [ +  + ]:        3579175 :     if (BufferIsValid(scan->rs_cbuf))
                                664                 :                :     {
                                665                 :        2593553 :         ReleaseBuffer(scan->rs_cbuf);
                                666                 :        2593553 :         scan->rs_cbuf = InvalidBuffer;
                                667                 :                :     }
                                668                 :                : 
                                669                 :                :     /*
                                670                 :                :      * Be sure to check for interrupts at least once per page.  Checks at
                                671                 :                :      * higher code levels won't be able to stop a seqscan that encounters many
                                672                 :                :      * pages' worth of consecutive dead tuples.
                                673                 :                :      */
                                674         [ +  + ]:        3579175 :     CHECK_FOR_INTERRUPTS();
                                675                 :                : 
                                676                 :                :     /*
                                677                 :                :      * If the scan direction is changing, reset the prefetch block to the
                                678                 :                :      * current block. Otherwise, we will incorrectly prefetch the blocks
                                679                 :                :      * between the prefetch block and the current block again before
                                680                 :                :      * prefetching blocks in the new, correct scan direction.
                                681                 :                :      */
  618 tmunro@postgresql.or      682         [ +  + ]:        3579172 :     if (unlikely(scan->rs_dir != dir))
                                683                 :                :     {
                                684                 :             76 :         scan->rs_prefetch_block = scan->rs_cblock;
                                685                 :             76 :         read_stream_reset(scan->rs_read_stream);
                                686                 :                :     }
                                687                 :                : 
                                688                 :        3579172 :     scan->rs_dir = dir;
                                689                 :                : 
                                690                 :        3579172 :     scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
                                691         [ +  + ]:        3579150 :     if (BufferIsValid(scan->rs_cbuf))
                                692                 :        2751862 :         scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
  622 drowley@postgresql.o      693                 :        3579150 : }
                                694                 :                : 
                                695                 :                : /*
                                696                 :                :  * heapgettup_initial_block - return the first BlockNumber to scan
                                697                 :                :  *
                                698                 :                :  * Returns InvalidBlockNumber when there are no blocks to scan.  This can
                                699                 :                :  * occur with empty tables and in parallel scans when parallel workers get all
                                700                 :                :  * of the pages before we can get a chance to get our first page.
                                701                 :                :  */
                                702                 :                : static pg_noinline BlockNumber
 1049                           703                 :         983976 : heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
                                704                 :                : {
                                705         [ -  + ]:         983976 :     Assert(!scan->rs_inited);
  618 tmunro@postgresql.or      706         [ -  + ]:         983976 :     Assert(scan->rs_base.rs_parallel == NULL);
                                707                 :                : 
                                708                 :                :     /* When there are no pages to scan, return InvalidBlockNumber */
 1049 drowley@postgresql.o      709   [ +  +  +  + ]:         983976 :     if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
                                710                 :         512723 :         return InvalidBlockNumber;
                                711                 :                : 
                                712         [ +  + ]:         471253 :     if (ScanDirectionIsForward(dir))
                                713                 :                :     {
  618 tmunro@postgresql.or      714                 :         471222 :         return scan->rs_startblock;
                                715                 :                :     }
                                716                 :                :     else
                                717                 :                :     {
                                718                 :                :         /*
                                719                 :                :          * Disable reporting to syncscan logic in a backwards scan; it's not
                                720                 :                :          * very likely anyone else is doing the same thing at the same time,
                                721                 :                :          * and much more likely that we'll just bollix things for forward
                                722                 :                :          * scanners.
                                723                 :                :          */
 1049 drowley@postgresql.o      724                 :             31 :         scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                725                 :                : 
                                726                 :                :         /*
                                727                 :                :          * Start from last page of the scan.  Ensure we take into account
                                728                 :                :          * rs_numblocks if it's been adjusted by heap_setscanlimits().
                                729                 :                :          */
                                730         [ +  + ]:             31 :         if (scan->rs_numblocks != InvalidBlockNumber)
                                731                 :              3 :             return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
                                732                 :                : 
                                733         [ -  + ]:             28 :         if (scan->rs_startblock > 0)
 1049 drowley@postgresql.o      734                 :UBC           0 :             return scan->rs_startblock - 1;
                                735                 :                : 
 1049 drowley@postgresql.o      736                 :CBC          28 :         return scan->rs_nblocks - 1;
                                737                 :                :     }
                                738                 :                : }
                                739                 :                : 
                                740                 :                : 
                                741                 :                : /*
                                742                 :                :  * heapgettup_start_page - helper function for heapgettup()
                                743                 :                :  *
                                744                 :                :  * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
                                745                 :                :  * to the number of tuples on this page.  Also set *lineoff to the first
                                746                 :                :  * offset to scan with forward scans getting the first offset and backward
                                747                 :                :  * getting the final offset on the page.
                                748                 :                :  */
                                749                 :                : static Page
 1048                           750                 :          91982 : heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
                                751                 :                :                       OffsetNumber *lineoff)
                                752                 :                : {
                                753                 :                :     Page        page;
                                754                 :                : 
                                755         [ -  + ]:          91982 :     Assert(scan->rs_inited);
                                756         [ -  + ]:          91982 :     Assert(BufferIsValid(scan->rs_cbuf));
                                757                 :                : 
                                758                 :                :     /* Caller is responsible for ensuring buffer is locked if needed */
                                759                 :          91982 :     page = BufferGetPage(scan->rs_cbuf);
                                760                 :                : 
 1044                           761                 :          91982 :     *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
                                762                 :                : 
 1048                           763         [ +  - ]:          91982 :     if (ScanDirectionIsForward(dir))
                                764                 :          91982 :         *lineoff = FirstOffsetNumber;
                                765                 :                :     else
 1048 drowley@postgresql.o      766                 :UBC           0 :         *lineoff = (OffsetNumber) (*linesleft);
                                767                 :                : 
                                768                 :                :     /* lineoff now references the physically previous or next tid */
 1048 drowley@postgresql.o      769                 :CBC       91982 :     return page;
                                770                 :                : }
                                771                 :                : 
                                772                 :                : 
                                773                 :                : /*
                                774                 :                :  * heapgettup_continue_page - helper function for heapgettup()
                                775                 :                :  *
                                776                 :                :  * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
                                777                 :                :  * to the number of tuples left to scan on this page.  Also set *lineoff to
                                778                 :                :  * the next offset to scan according to the ScanDirection in 'dir'.
                                779                 :                :  */
                                780                 :                : static inline Page
                                781                 :        7465663 : heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
                                782                 :                :                          OffsetNumber *lineoff)
                                783                 :                : {
                                784                 :                :     Page        page;
                                785                 :                : 
                                786         [ -  + ]:        7465663 :     Assert(scan->rs_inited);
                                787         [ -  + ]:        7465663 :     Assert(BufferIsValid(scan->rs_cbuf));
                                788                 :                : 
                                789                 :                :     /* Caller is responsible for ensuring buffer is locked if needed */
                                790                 :        7465663 :     page = BufferGetPage(scan->rs_cbuf);
                                791                 :                : 
                                792         [ +  - ]:        7465663 :     if (ScanDirectionIsForward(dir))
                                793                 :                :     {
                                794                 :        7465663 :         *lineoff = OffsetNumberNext(scan->rs_coffset);
                                795                 :        7465663 :         *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
                                796                 :                :     }
                                797                 :                :     else
                                798                 :                :     {
                                799                 :                :         /*
                                800                 :                :          * The previous returned tuple may have been vacuumed since the
                                801                 :                :          * previous scan when we use a non-MVCC snapshot, so we must
                                802                 :                :          * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
                                803                 :                :          */
 1048 drowley@postgresql.o      804         [ #  # ]:UBC           0 :         *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
                                805                 :              0 :         *linesleft = *lineoff;
                                806                 :                :     }
                                807                 :                : 
                                808                 :                :     /* lineoff now references the physically previous or next tid */
 1048 drowley@postgresql.o      809                 :CBC     7465663 :     return page;
                                810                 :                : }
                                811                 :                : 
                                812                 :                : /*
                                813                 :                :  * heapgettup_advance_block - helper for heap_fetch_next_buffer()
                                814                 :                :  *
                                815                 :                :  * Given the current block number, the scan direction, and various information
                                816                 :                :  * contained in the scan descriptor, calculate the BlockNumber to scan next
                                817                 :                :  * and return it.  If there are no further blocks to scan, return
                                818                 :                :  * InvalidBlockNumber to indicate this fact to the caller.
                                819                 :                :  *
                                820                 :                :  * This should not be called to determine the initial block number -- only for
                                821                 :                :  * subsequent blocks.
                                822                 :                :  *
                                823                 :                :  * This also adjusts rs_numblocks when a limit has been imposed by
                                824                 :                :  * heap_setscanlimits().
                                825                 :                :  */
                                826                 :                : static inline BlockNumber
                                827                 :        2673509 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
                                828                 :                : {
  618 tmunro@postgresql.or      829         [ -  + ]:        2673509 :     Assert(scan->rs_base.rs_parallel == NULL);
                                830                 :                : 
                                831         [ +  + ]:        2673509 :     if (likely(ScanDirectionIsForward(dir)))
                                832                 :                :     {
                                833                 :        2673451 :         block++;
                                834                 :                : 
                                835                 :                :         /* wrap back to the start of the heap */
                                836         [ +  + ]:        2673451 :         if (block >= scan->rs_nblocks)
                                837                 :         372111 :             block = 0;
                                838                 :                : 
                                839                 :                :         /*
                                840                 :                :          * Report our new scan position for synchronization purposes. We don't
                                841                 :                :          * do that when moving backwards, however. That would just mess up any
                                842                 :                :          * other forward-moving scanners.
                                843                 :                :          *
                                844                 :                :          * Note: we do this before checking for end of scan so that the final
                                845                 :                :          * state of the position hint is back at the start of the rel.  That's
                                846                 :                :          * not strictly necessary, but otherwise when you run the same query
                                847                 :                :          * multiple times the starting position would shift a little bit
                                848                 :                :          * backwards on every invocation, which is confusing. We don't
                                849                 :                :          * guarantee any specific ordering in general, though.
                                850                 :                :          */
                                851         [ +  + ]:        2673451 :         if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
                                852                 :          11265 :             ss_report_location(scan->rs_base.rs_rd, block);
                                853                 :                : 
                                854                 :                :         /* we're done if we're back at where we started */
                                855         [ +  + ]:        2673451 :         if (block == scan->rs_startblock)
                                856                 :         372070 :             return InvalidBlockNumber;
                                857                 :                : 
                                858                 :                :         /* check if the limit imposed by heap_setscanlimits() is met */
                                859         [ +  + ]:        2301381 :         if (scan->rs_numblocks != InvalidBlockNumber)
                                860                 :                :         {
                                861         [ +  + ]:           2484 :             if (--scan->rs_numblocks == 0)
                                862                 :           1550 :                 return InvalidBlockNumber;
                                863                 :                :         }
                                864                 :                : 
                                865                 :        2299831 :         return block;
                                866                 :                :     }
                                867                 :                :     else
                                868                 :                :     {
                                869                 :                :         /* we're done if the last block is the start position */
 1048 drowley@postgresql.o      870         [ +  - ]:             58 :         if (block == scan->rs_startblock)
                                871                 :             58 :             return InvalidBlockNumber;
                                872                 :                : 
                                873                 :                :         /* check if the limit imposed by heap_setscanlimits() is met */
 1048 drowley@postgresql.o      874         [ #  # ]:UBC           0 :         if (scan->rs_numblocks != InvalidBlockNumber)
                                875                 :                :         {
                                876         [ #  # ]:              0 :             if (--scan->rs_numblocks == 0)
                                877                 :              0 :                 return InvalidBlockNumber;
                                878                 :                :         }
                                879                 :                : 
                                880                 :                :         /* wrap to the end of the heap when the last page was page 0 */
                                881         [ #  # ]:              0 :         if (block == 0)
                                882                 :              0 :             block = scan->rs_nblocks;
                                883                 :                : 
                                884                 :              0 :         block--;
                                885                 :                : 
                                886                 :              0 :         return block;
                                887                 :                :     }
                                888                 :                : }
                                889                 :                : 
                                890                 :                : /* ----------------
                                891                 :                :  *      heapgettup - fetch next heap tuple
                                892                 :                :  *
                                893                 :                :  *      Initialize the scan if not already done; then advance to the next
                                894                 :                :  *      tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
                                895                 :                :  *      or set scan->rs_ctup.t_data = NULL if no more tuples.
                                896                 :                :  *
                                897                 :                :  * Note: the reason nkeys/key are passed separately, even though they are
                                898                 :                :  * kept in the scan descriptor, is that the caller may not want us to check
                                899                 :                :  * the scankeys.
                                900                 :                :  *
                                901                 :                :  * Note: when we fall off the end of the scan in either direction, we
                                902                 :                :  * reset rs_inited.  This means that a further request with the same
                                903                 :                :  * scan direction will restart the scan, which is a bit odd, but a
                                904                 :                :  * request with the opposite scan direction will start a fresh scan
                                905                 :                :  * in the proper direction.  The latter is required behavior for cursors,
                                906                 :                :  * while the former case is generally undefined behavior in Postgres
                                907                 :                :  * so we don't care too much.
                                908                 :                :  * ----------------
                                909                 :                :  */
                                910                 :                : static void
 7326 tgl@sss.pgh.pa.us         911                 :CBC     7486495 : heapgettup(HeapScanDesc scan,
                                912                 :                :            ScanDirection dir,
                                913                 :                :            int nkeys,
                                914                 :                :            ScanKey key)
                                915                 :                : {
                                916                 :        7486495 :     HeapTuple   tuple = &(scan->rs_ctup);
                                917                 :                :     Page        page;
                                918                 :                :     OffsetNumber lineoff;
                                919                 :                :     int         linesleft;
                                920                 :                : 
  622 drowley@postgresql.o      921         [ +  + ]:        7486495 :     if (likely(scan->rs_inited))
                                922                 :                :     {
                                923                 :                :         /* continue from previously returned page/tuple */
 1048                           924                 :        7465663 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
                                925                 :        7465663 :         page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
 1044                           926                 :        7465663 :         goto continue_page;
                                927                 :                :     }
                                928                 :                : 
                                929                 :                :     /*
                                930                 :                :      * advance the scan until we find a qualifying tuple or run out of stuff
                                931                 :                :      * to scan
                                932                 :                :      */
                                933                 :                :     while (true)
                                934                 :                :     {
  622                           935                 :         112664 :         heap_fetch_next_buffer(scan, dir);
                                936                 :                : 
                                937                 :                :         /* did we run out of blocks to scan? */
                                938         [ +  + ]:         112664 :         if (!BufferIsValid(scan->rs_cbuf))
                                939                 :          20682 :             break;
                                940                 :                : 
                                941         [ -  + ]:          91982 :         Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
                                942                 :                : 
 1044                           943                 :          91982 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
                                944                 :          91982 :         page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
                                945                 :        7557645 : continue_page:
                                946                 :                : 
                                947                 :                :         /*
                                948                 :                :          * Only continue scanning the page while we have lines left.
                                949                 :                :          *
                                950                 :                :          * Note that this protects us from accessing line pointers past
                                951                 :                :          * PageGetMaxOffsetNumber(); both for forward scans when we resume the
                                952                 :                :          * table scan, and for when we start scanning a new page.
                                953                 :                :          */
                                954         [ +  + ]:        7594471 :         for (; linesleft > 0; linesleft--, lineoff += dir)
                                955                 :                :         {
                                956                 :                :             bool        visible;
                                957                 :        7502639 :             ItemId      lpp = PageGetItemId(page, lineoff);
                                958                 :                : 
                                959         [ +  + ]:        7502639 :             if (!ItemIdIsNormal(lpp))
                                960                 :          31596 :                 continue;
                                961                 :                : 
                                962                 :        7471043 :             tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
                                963                 :        7471043 :             tuple->t_len = ItemIdGetLength(lpp);
  622                           964                 :        7471043 :             ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
                                965                 :                : 
 1044                           966                 :        7471043 :             visible = HeapTupleSatisfiesVisibility(tuple,
                                967                 :                :                                                    scan->rs_base.rs_snapshot,
                                968                 :                :                                                    scan->rs_cbuf);
                                969                 :                : 
                                970                 :        7471043 :             HeapCheckForSerializableConflictOut(visible, scan->rs_base.rs_rd,
                                971                 :                :                                                 tuple, scan->rs_cbuf,
                                972                 :                :                                                 scan->rs_base.rs_snapshot);
                                973                 :                : 
                                974                 :                :             /* skip tuples not visible to this snapshot */
                                975         [ +  + ]:        7471043 :             if (!visible)
                                976                 :           5230 :                 continue;
                                977                 :                : 
                                978                 :                :             /* skip any tuples that don't match the scan key */
                                979         [ -  + ]:        7465813 :             if (key != NULL &&
 1044 drowley@postgresql.o      980         [ #  # ]:UBC           0 :                 !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
                                981                 :                :                              nkeys, key))
                                982                 :              0 :                 continue;
                                983                 :                : 
 1044 drowley@postgresql.o      984                 :CBC     7465813 :             LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                                985                 :        7465813 :             scan->rs_coffset = lineoff;
                                986                 :        7465813 :             return;
                                987                 :                :         }
                                988                 :                : 
                                989                 :                :         /*
                                990                 :                :          * if we get here, it means we've exhausted the items on this page and
                                991                 :                :          * it's time to move to the next.
                                992                 :                :          */
 7326 tgl@sss.pgh.pa.us         993                 :          91832 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                                994                 :                :     }
                                995                 :                : 
                                996                 :                :     /* end of scan */
 1044 drowley@postgresql.o      997         [ -  + ]:          20682 :     if (BufferIsValid(scan->rs_cbuf))
 1044 drowley@postgresql.o      998                 :UBC           0 :         ReleaseBuffer(scan->rs_cbuf);
                                999                 :                : 
 1044 drowley@postgresql.o     1000                 :CBC       20682 :     scan->rs_cbuf = InvalidBuffer;
                               1001                 :          20682 :     scan->rs_cblock = InvalidBlockNumber;
  618 tmunro@postgresql.or     1002                 :          20682 :     scan->rs_prefetch_block = InvalidBlockNumber;
 1044 drowley@postgresql.o     1003                 :          20682 :     tuple->t_data = NULL;
                               1004                 :          20682 :     scan->rs_inited = false;
                               1005                 :                : }
                               1006                 :                : 
                               1007                 :                : /* ----------------
                               1008                 :                :  *      heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
                               1009                 :                :  *
                               1010                 :                :  *      Same API as heapgettup, but used in page-at-a-time mode
                               1011                 :                :  *
                               1012                 :                :  * The internal logic is much the same as heapgettup's too, but there are some
                               1013                 :                :  * differences: we do not take the buffer content lock (that only needs to
                               1014                 :                :  * happen inside heap_prepare_pagescan), and we iterate through just the
                               1015                 :                :  * tuples listed in rs_vistuples[] rather than all tuples on the page.  Notice
                               1016                 :                :  * that lineindex is 0-based, where the corresponding loop variable lineoff in
                               1017                 :                :  * heapgettup is 1-based.
                               1018                 :                :  * ----------------
                               1019                 :                :  */
                               1020                 :                : static void
 7326 tgl@sss.pgh.pa.us        1021                 :       49036328 : heapgettup_pagemode(HeapScanDesc scan,
                               1022                 :                :                     ScanDirection dir,
                               1023                 :                :                     int nkeys,
                               1024                 :                :                     ScanKey key)
                               1025                 :                : {
                               1026                 :       49036328 :     HeapTuple   tuple = &(scan->rs_ctup);
                               1027                 :                :     Page        page;
                               1028                 :                :     uint32      lineindex;
                               1029                 :                :     uint32      linesleft;
                               1030                 :                : 
  622 drowley@postgresql.o     1031         [ +  + ]:       49036328 :     if (likely(scan->rs_inited))
                               1032                 :                :     {
                               1033                 :                :         /* continue from previously returned page/tuple */
 1048                          1034                 :       48071538 :         page = BufferGetPage(scan->rs_cbuf);
                               1035                 :                : 
                               1036                 :       48071538 :         lineindex = scan->rs_cindex + dir;
                               1037         [ +  + ]:       48071538 :         if (ScanDirectionIsForward(dir))
                               1038                 :       48071210 :             linesleft = scan->rs_ntuples - lineindex;
                               1039                 :                :         else
                               1040                 :            328 :             linesleft = scan->rs_cindex;
                               1041                 :                :         /* lineindex now references the next or previous visible tid */
                               1042                 :                : 
 1044                          1043                 :       48071538 :         goto continue_page;
                               1044                 :                :     }
                               1045                 :                : 
                               1046                 :                :     /*
                               1047                 :                :      * advance the scan until we find a qualifying tuple or run out of stuff
                               1048                 :                :      * to scan
                               1049                 :                :      */
                               1050                 :                :     while (true)
                               1051                 :                :     {
  622                          1052                 :        3466511 :         heap_fetch_next_buffer(scan, dir);
                               1053                 :                : 
                               1054                 :                :         /* did we run out of blocks to scan? */
                               1055         [ +  + ]:        3466486 :         if (!BufferIsValid(scan->rs_cbuf))
                               1056                 :         806606 :             break;
                               1057                 :                : 
                               1058         [ -  + ]:        2659880 :         Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
                               1059                 :                : 
                               1060                 :                :         /* prune the page and determine visible tuple offsets */
                               1061                 :        2659880 :         heap_prepare_pagescan((TableScanDesc) scan);
 1044                          1062                 :        2659872 :         page = BufferGetPage(scan->rs_cbuf);
                               1063                 :        2659872 :         linesleft = scan->rs_ntuples;
                               1064         [ +  + ]:        2659872 :         lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
                               1065                 :                : 
                               1066                 :                :         /* block is the same for all tuples, set it once outside the loop */
  260 heikki.linnakangas@i     1067                 :        2659872 :         ItemPointerSetBlockNumber(&tuple->t_self, scan->rs_cblock);
                               1068                 :                : 
                               1069                 :                :         /* lineindex now references the next or previous visible tid */
 1044 drowley@postgresql.o     1070                 :       50731410 : continue_page:
                               1071                 :                : 
                               1072         [ +  + ]:       97837315 :         for (; linesleft > 0; linesleft--, lineindex += dir)
                               1073                 :                :         {
                               1074                 :                :             ItemId      lpp;
                               1075                 :                :             OffsetNumber lineoff;
                               1076                 :                : 
  364 melanieplageman@gmai     1077         [ -  + ]:       95335594 :             Assert(lineindex <= scan->rs_ntuples);
 7326 tgl@sss.pgh.pa.us        1078                 :       95335594 :             lineoff = scan->rs_vistuples[lineindex];
 1127 peter@eisentraut.org     1079                 :       95335594 :             lpp = PageGetItemId(page, lineoff);
 6671 tgl@sss.pgh.pa.us        1080         [ -  + ]:       95335594 :             Assert(ItemIdIsNormal(lpp));
                               1081                 :                : 
 1127 peter@eisentraut.org     1082                 :       95335594 :             tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
 7326 tgl@sss.pgh.pa.us        1083                 :       95335594 :             tuple->t_len = ItemIdGetLength(lpp);
  260 heikki.linnakangas@i     1084                 :       95335594 :             ItemPointerSetOffsetNumber(&tuple->t_self, lineoff);
                               1085                 :                : 
                               1086                 :                :             /* skip any tuples that don't match the scan key */
 1044 drowley@postgresql.o     1087         [ +  + ]:       95335594 :             if (key != NULL &&
                               1088         [ +  + ]:       47428744 :                 !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
                               1089                 :                :                              nkeys, key))
                               1090                 :       47105905 :                 continue;
                               1091                 :                : 
                               1092                 :       48229689 :             scan->rs_cindex = lineindex;
                               1093                 :       48229689 :             return;
                               1094                 :                :         }
                               1095                 :                :     }
                               1096                 :                : 
                               1097                 :                :     /* end of scan */
                               1098         [ -  + ]:         806606 :     if (BufferIsValid(scan->rs_cbuf))
 1044 drowley@postgresql.o     1099                 :UBC           0 :         ReleaseBuffer(scan->rs_cbuf);
 1044 drowley@postgresql.o     1100                 :CBC      806606 :     scan->rs_cbuf = InvalidBuffer;
                               1101                 :         806606 :     scan->rs_cblock = InvalidBlockNumber;
  618 tmunro@postgresql.or     1102                 :         806606 :     scan->rs_prefetch_block = InvalidBlockNumber;
 1044 drowley@postgresql.o     1103                 :         806606 :     tuple->t_data = NULL;
                               1104                 :         806606 :     scan->rs_inited = false;
                               1105                 :                : }
                               1106                 :                : 
                               1107                 :                : 
                               1108                 :                : /* ----------------------------------------------------------------
                               1109                 :                :  *                   heap access method interface
                               1110                 :                :  * ----------------------------------------------------------------
                               1111                 :                :  */
                               1112                 :                : 
                               1113                 :                : 
                               1114                 :                : TableScanDesc
 8612 tgl@sss.pgh.pa.us        1115                 :         375830 : heap_beginscan(Relation relation, Snapshot snapshot,
                               1116                 :                :                int nkeys, ScanKey key,
                               1117                 :                :                ParallelTableScanDesc parallel_scan,
                               1118                 :                :                uint32 flags)
                               1119                 :                : {
                               1120                 :                :     HeapScanDesc scan;
                               1121                 :                : 
                               1122                 :                :     /*
                               1123                 :                :      * increment relation ref count while scanning relation
                               1124                 :                :      *
                               1125                 :                :      * This is just to make really sure the relcache entry won't go away while
                               1126                 :                :      * the scan has a pointer to it.  Caller should be holding the rel open
                               1127                 :                :      * anyway, so this is redundant in all normal scenarios...
                               1128                 :                :      */
 9170                          1129                 :         375830 :     RelationIncrementReferenceCount(relation);
                               1130                 :                : 
                               1131                 :                :     /*
                               1132                 :                :      * allocate and initialize scan descriptor
                               1133                 :                :      */
  335 melanieplageman@gmai     1134         [ +  + ]:         375830 :     if (flags & SO_TYPE_BITMAPSCAN)
                               1135                 :                :     {
    7 michael@paquier.xyz      1136                 :GNC       10507 :         BitmapHeapScanDesc bscan = palloc_object(BitmapHeapScanDescData);
                               1137                 :                : 
                               1138                 :                :         /*
                               1139                 :                :          * Bitmap Heap scans do not have any fields that a normal Heap Scan
                               1140                 :                :          * does not have, so no special initializations required here.
                               1141                 :                :          */
  335 melanieplageman@gmai     1142                 :CBC       10507 :         scan = (HeapScanDesc) bscan;
                               1143                 :                :     }
                               1144                 :                :     else
    7 michael@paquier.xyz      1145                 :GNC      365323 :         scan = (HeapScanDesc) palloc_object(HeapScanDescData);
                               1146                 :                : 
 2473 andres@anarazel.de       1147                 :CBC      375830 :     scan->rs_base.rs_rd = relation;
                               1148                 :         375830 :     scan->rs_base.rs_snapshot = snapshot;
                               1149                 :         375830 :     scan->rs_base.rs_nkeys = nkeys;
 2404                          1150                 :         375830 :     scan->rs_base.rs_flags = flags;
 2473                          1151                 :         375830 :     scan->rs_base.rs_parallel = parallel_scan;
 2404                          1152                 :         375830 :     scan->rs_strategy = NULL;    /* set in initscan */
  277 melanieplageman@gmai     1153                 :         375830 :     scan->rs_cbuf = InvalidBuffer;
                               1154                 :                : 
                               1155                 :                :     /*
                               1156                 :                :      * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
                               1157                 :                :      */
 2404 andres@anarazel.de       1158   [ +  +  +  +  :         375830 :     if (!(snapshot && IsMVCCSnapshot(snapshot)))
                                              +  + ]
                               1159                 :          29846 :         scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
                               1160                 :                : 
                               1161                 :                :     /* Check that a historic snapshot is not used for non-catalog tables */
  117 heikki.linnakangas@i     1162         [ +  + ]:GNC      375830 :     if (snapshot &&
                               1163         [ +  + ]:         366816 :         IsHistoricMVCCSnapshot(snapshot) &&
                               1164   [ +  -  +  -  :            644 :         !RelationIsAccessibleInLogicalDecoding(relation))
                                     -  +  -  -  -  
                                     -  -  +  -  -  
                                     -  -  -  -  -  
                                           -  -  - ]
                               1165                 :                :     {
  117 heikki.linnakangas@i     1166         [ #  # ]:UNC           0 :         ereport(ERROR,
                               1167                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               1168                 :                :                  errmsg("cannot query non-catalog table \"%s\" during logical decoding",
                               1169                 :                :                         RelationGetRelationName(relation))));
                               1170                 :                :     }
                               1171                 :                : 
                               1172                 :                :     /*
                               1173                 :                :      * For seqscan and sample scans in a serializable transaction, acquire a
                               1174                 :                :      * predicate lock on the entire relation. This is required not only to
                               1175                 :                :      * lock all the matching tuples, but also to conflict with new insertions
                               1176                 :                :      * into the table. In an indexscan, we take page locks on the index pages
                               1177                 :                :      * covering the range specified in the scan qual, but in a heap scan there
                               1178                 :                :      * is nothing more fine-grained to lock. A bitmap scan is a different
                               1179                 :                :      * story, there we have already scanned the index and locked the index
                               1180                 :                :      * pages covering the predicate. But in that case we still have to lock
                               1181                 :                :      * any matching heap tuples. For sample scan we could optimize the locking
                               1182                 :                :      * to be at least page-level granularity, but we'd need to add per-tuple
                               1183                 :                :      * locking for that.
                               1184                 :                :      */
 2404 andres@anarazel.de       1185         [ +  + ]:CBC      375830 :     if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN))
                               1186                 :                :     {
                               1187                 :                :         /*
                               1188                 :                :          * Ensure a missing snapshot is noticed reliably, even if the
                               1189                 :                :          * isolation mode means predicate locking isn't performed (and
                               1190                 :                :          * therefore the snapshot isn't used here).
                               1191                 :                :          */
                               1192         [ -  + ]:         354926 :         Assert(snapshot);
 5285 heikki.linnakangas@i     1193                 :         354926 :         PredicateLockRelation(relation, snapshot);
                               1194                 :                :     }
                               1195                 :                : 
                               1196                 :                :     /* we only need to set this up once */
 7326 tgl@sss.pgh.pa.us        1197                 :         375830 :     scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
                               1198                 :                : 
                               1199                 :                :     /*
                               1200                 :                :      * Allocate memory to keep track of page allocation for parallel workers
                               1201                 :                :      * when doing a parallel scan.
                               1202                 :                :      */
 1723 drowley@postgresql.o     1203         [ +  + ]:         375830 :     if (parallel_scan != NULL)
    7 michael@paquier.xyz      1204                 :GNC        2058 :         scan->rs_parallelworkerdata = palloc_object(ParallelBlockTableScanWorkerData);
                               1205                 :                :     else
 1723 drowley@postgresql.o     1206                 :CBC      373772 :         scan->rs_parallelworkerdata = NULL;
                               1207                 :                : 
                               1208                 :                :     /*
                               1209                 :                :      * we do this here instead of in initscan() because heap_rescan also calls
                               1210                 :                :      * initscan() and we don't want to allocate memory again
                               1211                 :                :      */
 8612 tgl@sss.pgh.pa.us        1212         [ +  + ]:         375830 :     if (nkeys > 0)
    7 michael@paquier.xyz      1213                 :GNC      214084 :         scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
                               1214                 :                :     else
 2473 andres@anarazel.de       1215                 :CBC      161746 :         scan->rs_base.rs_key = NULL;
                               1216                 :                : 
 6034 tgl@sss.pgh.pa.us        1217                 :         375830 :     initscan(scan, key, false);
                               1218                 :                : 
  618 tmunro@postgresql.or     1219                 :         375828 :     scan->rs_read_stream = NULL;
                               1220                 :                : 
                               1221                 :                :     /*
                               1222                 :                :      * Set up a read stream for sequential scans and TID range scans. This
                               1223                 :                :      * should be done after initscan() because initscan() allocates the
                               1224                 :                :      * BufferAccessStrategy object passed to the read stream API.
                               1225                 :                :      */
                               1226         [ +  + ]:         375828 :     if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
                               1227         [ +  + ]:          20977 :         scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
                               1228                 :         355839 :     {
                               1229                 :                :         ReadStreamBlockNumberCB cb;
                               1230                 :                : 
                               1231         [ +  + ]:         355839 :         if (scan->rs_base.rs_parallel)
                               1232                 :           2058 :             cb = heap_scan_stream_read_next_parallel;
                               1233                 :                :         else
                               1234                 :         353781 :             cb = heap_scan_stream_read_next_serial;
                               1235                 :                : 
                               1236                 :                :         /* ---
                               1237                 :                :          * It is safe to use batchmode as the only locks taken by `cb`
                               1238                 :                :          * are never taken while waiting for IO:
                               1239                 :                :          * - SyncScanLock is used in the non-parallel case
                               1240                 :                :          * - in the parallel case, only spinlocks and atomics are used
                               1241                 :                :          * ---
                               1242                 :                :          */
  262 andres@anarazel.de       1243                 :         355839 :         scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_SEQUENTIAL |
                               1244                 :                :                                                           READ_STREAM_USE_BATCHING,
                               1245                 :                :                                                           scan->rs_strategy,
                               1246                 :                :                                                           scan->rs_base.rs_rd,
                               1247                 :                :                                                           MAIN_FORKNUM,
                               1248                 :                :                                                           cb,
                               1249                 :                :                                                           scan,
                               1250                 :                :                                                           0);
                               1251                 :                :     }
  277 melanieplageman@gmai     1252         [ +  + ]:          19989 :     else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
                               1253                 :                :     {
  258                          1254                 :          10507 :         scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_DEFAULT |
                               1255                 :                :                                                           READ_STREAM_USE_BATCHING,
                               1256                 :                :                                                           scan->rs_strategy,
                               1257                 :                :                                                           scan->rs_base.rs_rd,
                               1258                 :                :                                                           MAIN_FORKNUM,
                               1259                 :                :                                                           bitmapheap_stream_read_next,
                               1260                 :                :                                                           scan,
                               1261                 :                :                                                           sizeof(TBMIterateResult));
                               1262                 :                :     }
                               1263                 :                : 
                               1264                 :                : 
 2473 andres@anarazel.de       1265                 :         375828 :     return (TableScanDesc) scan;
                               1266                 :                : }
                               1267                 :                : 
                               1268                 :                : void
                               1269                 :         632555 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
                               1270                 :                :             bool allow_strat, bool allow_sync, bool allow_pagemode)
                               1271                 :                : {
                               1272                 :         632555 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1273                 :                : 
                               1274         [ +  + ]:         632555 :     if (set_params)
                               1275                 :                :     {
 2404                          1276         [ +  - ]:             15 :         if (allow_strat)
                               1277                 :             15 :             scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
                               1278                 :                :         else
 2404 andres@anarazel.de       1279                 :UBC           0 :             scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
                               1280                 :                : 
 2404 andres@anarazel.de       1281         [ +  + ]:CBC          15 :         if (allow_sync)
                               1282                 :              6 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                               1283                 :                :         else
                               1284                 :              9 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                               1285                 :                : 
                               1286   [ +  -  +  - ]:             15 :         if (allow_pagemode && scan->rs_base.rs_snapshot &&
                               1287   [ -  +  -  - ]:             15 :             IsMVCCSnapshot(scan->rs_base.rs_snapshot))
                               1288                 :             15 :             scan->rs_base.rs_flags |= SO_ALLOW_PAGEMODE;
                               1289                 :                :         else
 2404 andres@anarazel.de       1290                 :UBC           0 :             scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
                               1291                 :                :     }
                               1292                 :                : 
                               1293                 :                :     /*
                               1294                 :                :      * unpin scan buffers
                               1295                 :                :      */
 8957 tgl@sss.pgh.pa.us        1296         [ +  + ]:CBC      632555 :     if (BufferIsValid(scan->rs_cbuf))
                               1297                 :                :     {
                               1298                 :           1754 :         ReleaseBuffer(scan->rs_cbuf);
  277 melanieplageman@gmai     1299                 :           1754 :         scan->rs_cbuf = InvalidBuffer;
                               1300                 :                :     }
                               1301                 :                : 
                               1302                 :                :     /*
                               1303                 :                :      * SO_TYPE_BITMAPSCAN would be cleaned up here, but it does not hold any
                               1304                 :                :      * additional data vs a normal HeapScan
                               1305                 :                :      */
                               1306                 :                : 
                               1307                 :                :     /*
                               1308                 :                :      * The read stream is reset on rescan. This must be done before
                               1309                 :                :      * initscan(), as some state referred to by read_stream_reset() is reset
                               1310                 :                :      * in initscan().
                               1311                 :                :      */
  618 tmunro@postgresql.or     1312         [ +  + ]:         632555 :     if (scan->rs_read_stream)
                               1313                 :         632537 :         read_stream_reset(scan->rs_read_stream);
                               1314                 :                : 
                               1315                 :                :     /*
                               1316                 :                :      * reinitialize scan descriptor
                               1317                 :                :      */
 6034 tgl@sss.pgh.pa.us        1318                 :         632555 :     initscan(scan, key, true);
10753 scrappy@hub.org          1319                 :         632555 : }
                               1320                 :                : 
                               1321                 :                : void
 2473 andres@anarazel.de       1322                 :         373459 : heap_endscan(TableScanDesc sscan)
                               1323                 :                : {
                               1324                 :         373459 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1325                 :                : 
                               1326                 :                :     /* Note: no locking manipulations needed */
                               1327                 :                : 
                               1328                 :                :     /*
                               1329                 :                :      * unpin scan buffers
                               1330                 :                :      */
 8957 tgl@sss.pgh.pa.us        1331         [ +  + ]:         373459 :     if (BufferIsValid(scan->rs_cbuf))
                               1332                 :         154922 :         ReleaseBuffer(scan->rs_cbuf);
                               1333                 :                : 
                               1334                 :                :     /*
                               1335                 :                :      * Must free the read stream before freeing the BufferAccessStrategy.
                               1336                 :                :      */
  618 tmunro@postgresql.or     1337         [ +  + ]:         373459 :     if (scan->rs_read_stream)
                               1338                 :         364031 :         read_stream_end(scan->rs_read_stream);
                               1339                 :                : 
                               1340                 :                :     /*
                               1341                 :                :      * decrement relation reference count and free scan descriptor storage
                               1342                 :                :      */
 2473 andres@anarazel.de       1343                 :         373459 :     RelationDecrementReferenceCount(scan->rs_base.rs_rd);
                               1344                 :                : 
                               1345         [ +  + ]:         373459 :     if (scan->rs_base.rs_key)
                               1346                 :         214053 :         pfree(scan->rs_base.rs_key);
                               1347                 :                : 
 6776 tgl@sss.pgh.pa.us        1348         [ +  + ]:         373459 :     if (scan->rs_strategy != NULL)
                               1349                 :          12796 :         FreeAccessStrategy(scan->rs_strategy);
                               1350                 :                : 
 1723 drowley@postgresql.o     1351         [ +  + ]:         373459 :     if (scan->rs_parallelworkerdata != NULL)
                               1352                 :           2058 :         pfree(scan->rs_parallelworkerdata);
                               1353                 :                : 
 2404 andres@anarazel.de       1354         [ +  + ]:         373459 :     if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
 2473                          1355                 :          32341 :         UnregisterSnapshot(scan->rs_base.rs_snapshot);
                               1356                 :                : 
 9587 tgl@sss.pgh.pa.us        1357                 :         373459 :     pfree(scan);
10753 scrappy@hub.org          1358                 :         373459 : }
                               1359                 :                : 
                               1360                 :                : HeapTuple
 2473 andres@anarazel.de       1361                 :        9132506 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
                               1362                 :                : {
                               1363                 :        9132506 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1364                 :                : 
                               1365                 :                :     /*
                               1366                 :                :      * This is still widely used directly, without going through table AM, so
                               1367                 :                :      * add a safety check.  It's possible we should, at a later point,
                               1368                 :                :      * downgrade this to an assert. The reason for checking the AM routine,
                               1369                 :                :      * rather than the AM oid, is that this allows to write regression tests
                               1370                 :                :      * that create another AM reusing the heap handler.
                               1371                 :                :      */
                               1372         [ -  + ]:        9132506 :     if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
 2473 andres@anarazel.de       1373         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1374                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1375                 :                :                  errmsg_internal("only heap AM is supported")));
                               1376                 :                : 
                               1377                 :                :     /*
                               1378                 :                :      * We don't expect direct calls to heap_getnext with valid CheckXidAlive
                               1379                 :                :      * for catalog or regular tables.  See detailed comments in xact.c where
                               1380                 :                :      * these variables are declared.  Normally we have such a check at tableam
                               1381                 :                :      * level API but this is called from many places so we need to ensure it
                               1382                 :                :      * here.
                               1383                 :                :      */
 1957 akapila@postgresql.o     1384   [ -  +  -  -  :CBC     9132506 :     if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
                                              -  + ]
 1957 akapila@postgresql.o     1385         [ #  # ]:UBC           0 :         elog(ERROR, "unexpected heap_getnext call during logical decoding");
                               1386                 :                : 
                               1387                 :                :     /* Note: no locking manipulations needed */
                               1388                 :                : 
 2404 andres@anarazel.de       1389         [ +  + ]:CBC     9132506 :     if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
 7239 neilc@samurai.com        1390                 :        2124510 :         heapgettup_pagemode(scan, direction,
 2473 andres@anarazel.de       1391                 :        2124510 :                             scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
                               1392                 :                :     else
                               1393                 :        7007996 :         heapgettup(scan, direction,
                               1394                 :        7007996 :                    scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
                               1395                 :                : 
 7326 tgl@sss.pgh.pa.us        1396         [ +  + ]:        9132506 :     if (scan->rs_ctup.t_data == NULL)
 8612                          1397                 :          59003 :         return NULL;
                               1398                 :                : 
                               1399                 :                :     /*
                               1400                 :                :      * if we get here it means we have a new current scan tuple, so point to
                               1401                 :                :      * the proper return buffer and return the tuple.
                               1402                 :                :      */
                               1403                 :                : 
 2473 andres@anarazel.de       1404   [ -  +  -  -  :        9073503 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
                                              +  - ]
                               1405                 :                : 
                               1406                 :        9073503 :     return &scan->rs_ctup;
                               1407                 :                : }
                               1408                 :                : 
                               1409                 :                : bool
                               1410                 :       47385042 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
                               1411                 :                : {
                               1412                 :       47385042 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1413                 :                : 
                               1414                 :                :     /* Note: no locking manipulations needed */
                               1415                 :                : 
 2404                          1416         [ +  + ]:       47385042 :     if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
                               1417                 :       46906543 :         heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1418                 :                :     else
                               1419                 :         478499 :         heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1420                 :                : 
 2473                          1421         [ +  + ]:       47385015 :     if (scan->rs_ctup.t_data == NULL)
                               1422                 :                :     {
                               1423                 :         768181 :         ExecClearTuple(slot);
                               1424                 :         768181 :         return false;
                               1425                 :                :     }
                               1426                 :                : 
                               1427                 :                :     /*
                               1428                 :                :      * if we get here it means we have a new current scan tuple, so point to
                               1429                 :                :      * the proper return buffer and return the tuple.
                               1430                 :                :      */
                               1431                 :                : 
                               1432   [ +  +  -  +  :       46616834 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
                                              +  + ]
                               1433                 :                : 
                               1434                 :       46616834 :     ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
                               1435                 :                :                              scan->rs_cbuf);
                               1436                 :       46616834 :     return true;
                               1437                 :                : }
                               1438                 :                : 
                               1439                 :                : void
 1754 drowley@postgresql.o     1440                 :           1033 : heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
                               1441                 :                :                   ItemPointer maxtid)
                               1442                 :                : {
                               1443                 :           1033 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1444                 :                :     BlockNumber startBlk;
                               1445                 :                :     BlockNumber numBlks;
                               1446                 :                :     ItemPointerData highestItem;
                               1447                 :                :     ItemPointerData lowestItem;
                               1448                 :                : 
                               1449                 :                :     /*
                               1450                 :                :      * For relations without any pages, we can simply leave the TID range
                               1451                 :                :      * unset.  There will be no tuples to scan, therefore no tuples outside
                               1452                 :                :      * the given TID range.
                               1453                 :                :      */
                               1454         [ +  + ]:           1033 :     if (scan->rs_nblocks == 0)
                               1455                 :             24 :         return;
                               1456                 :                : 
                               1457                 :                :     /*
                               1458                 :                :      * Set up some ItemPointers which point to the first and last possible
                               1459                 :                :      * tuples in the heap.
                               1460                 :                :      */
                               1461                 :           1027 :     ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
                               1462                 :           1027 :     ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
                               1463                 :                : 
                               1464                 :                :     /*
                               1465                 :                :      * If the given maximum TID is below the highest possible TID in the
                               1466                 :                :      * relation, then restrict the range to that, otherwise we scan to the end
                               1467                 :                :      * of the relation.
                               1468                 :                :      */
                               1469         [ +  + ]:           1027 :     if (ItemPointerCompare(maxtid, &highestItem) < 0)
                               1470                 :            128 :         ItemPointerCopy(maxtid, &highestItem);
                               1471                 :                : 
                               1472                 :                :     /*
                               1473                 :                :      * If the given minimum TID is above the lowest possible TID in the
                               1474                 :                :      * relation, then restrict the range to only scan for TIDs above that.
                               1475                 :                :      */
                               1476         [ +  + ]:           1027 :     if (ItemPointerCompare(mintid, &lowestItem) > 0)
                               1477                 :            911 :         ItemPointerCopy(mintid, &lowestItem);
                               1478                 :                : 
                               1479                 :                :     /*
                               1480                 :                :      * Check for an empty range and protect from would be negative results
                               1481                 :                :      * from the numBlks calculation below.
                               1482                 :                :      */
                               1483         [ +  + ]:           1027 :     if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
                               1484                 :                :     {
                               1485                 :                :         /* Set an empty range of blocks to scan */
                               1486                 :             18 :         heap_setscanlimits(sscan, 0, 0);
                               1487                 :             18 :         return;
                               1488                 :                :     }
                               1489                 :                : 
                               1490                 :                :     /*
                               1491                 :                :      * Calculate the first block and the number of blocks we must scan. We
                               1492                 :                :      * could be more aggressive here and perform some more validation to try
                               1493                 :                :      * and further narrow the scope of blocks to scan by checking if the
                               1494                 :                :      * lowestItem has an offset above MaxOffsetNumber.  In this case, we could
                               1495                 :                :      * advance startBlk by one.  Likewise, if highestItem has an offset of 0
                               1496                 :                :      * we could scan one fewer blocks.  However, such an optimization does not
                               1497                 :                :      * seem worth troubling over, currently.
                               1498                 :                :      */
                               1499                 :           1009 :     startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
                               1500                 :                : 
                               1501                 :           1009 :     numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
                               1502                 :           1009 :         ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
                               1503                 :                : 
                               1504                 :                :     /* Set the start block and number of blocks to scan */
                               1505                 :           1009 :     heap_setscanlimits(sscan, startBlk, numBlks);
                               1506                 :                : 
                               1507                 :                :     /* Finally, set the TID range in sscan */
  418 melanieplageman@gmai     1508                 :           1009 :     ItemPointerCopy(&lowestItem, &sscan->st.tidrange.rs_mintid);
                               1509                 :           1009 :     ItemPointerCopy(&highestItem, &sscan->st.tidrange.rs_maxtid);
                               1510                 :                : }
                               1511                 :                : 
                               1512                 :                : bool
 1754 drowley@postgresql.o     1513                 :           5182 : heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
                               1514                 :                :                           TupleTableSlot *slot)
                               1515                 :                : {
                               1516                 :           5182 :     HeapScanDesc scan = (HeapScanDesc) sscan;
  418 melanieplageman@gmai     1517                 :           5182 :     ItemPointer mintid = &sscan->st.tidrange.rs_mintid;
                               1518                 :           5182 :     ItemPointer maxtid = &sscan->st.tidrange.rs_maxtid;
                               1519                 :                : 
                               1520                 :                :     /* Note: no locking manipulations needed */
                               1521                 :                :     for (;;)
                               1522                 :                :     {
 1754 drowley@postgresql.o     1523         [ +  - ]:           5275 :         if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
                               1524                 :           5275 :             heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1525                 :                :         else
 1754 drowley@postgresql.o     1526                 :UBC           0 :             heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1527                 :                : 
 1754 drowley@postgresql.o     1528         [ +  + ]:CBC        5269 :         if (scan->rs_ctup.t_data == NULL)
                               1529                 :                :         {
                               1530                 :            104 :             ExecClearTuple(slot);
                               1531                 :            104 :             return false;
                               1532                 :                :         }
                               1533                 :                : 
                               1534                 :                :         /*
                               1535                 :                :          * heap_set_tidrange will have used heap_setscanlimits to limit the
                               1536                 :                :          * range of pages we scan to only ones that can contain the TID range
                               1537                 :                :          * we're scanning for.  Here we must filter out any tuples from these
                               1538                 :                :          * pages that are outside of that range.
                               1539                 :                :          */
                               1540         [ +  + ]:           5165 :         if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
                               1541                 :                :         {
                               1542                 :             93 :             ExecClearTuple(slot);
                               1543                 :                : 
                               1544                 :                :             /*
                               1545                 :                :              * When scanning backwards, the TIDs will be in descending order.
                               1546                 :                :              * Future tuples in this direction will be lower still, so we can
                               1547                 :                :              * just return false to indicate there will be no more tuples.
                               1548                 :                :              */
                               1549         [ -  + ]:             93 :             if (ScanDirectionIsBackward(direction))
 1754 drowley@postgresql.o     1550                 :UBC           0 :                 return false;
                               1551                 :                : 
 1754 drowley@postgresql.o     1552                 :CBC          93 :             continue;
                               1553                 :                :         }
                               1554                 :                : 
                               1555                 :                :         /*
                               1556                 :                :          * Likewise for the final page, we must filter out TIDs greater than
                               1557                 :                :          * maxtid.
                               1558                 :                :          */
                               1559         [ +  + ]:           5072 :         if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
                               1560                 :                :         {
                               1561                 :             56 :             ExecClearTuple(slot);
                               1562                 :                : 
                               1563                 :                :             /*
                               1564                 :                :              * When scanning forward, the TIDs will be in ascending order.
                               1565                 :                :              * Future tuples in this direction will be higher still, so we can
                               1566                 :                :              * just return false to indicate there will be no more tuples.
                               1567                 :                :              */
                               1568         [ +  - ]:             56 :             if (ScanDirectionIsForward(direction))
                               1569                 :             56 :                 return false;
 1754 drowley@postgresql.o     1570                 :UBC           0 :             continue;
                               1571                 :                :         }
                               1572                 :                : 
 1754 drowley@postgresql.o     1573                 :CBC        5016 :         break;
                               1574                 :                :     }
                               1575                 :                : 
                               1576                 :                :     /*
                               1577                 :                :      * if we get here it means we have a new current scan tuple, so point to
                               1578                 :                :      * the proper return buffer and return the tuple.
                               1579                 :                :      */
                               1580   [ -  +  -  -  :           5016 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
                                              +  - ]
                               1581                 :                : 
                               1582                 :           5016 :     ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
                               1583                 :           5016 :     return true;
                               1584                 :                : }
                               1585                 :                : 
                               1586                 :                : /*
                               1587                 :                :  *  heap_fetch      - retrieve tuple with given tid
                               1588                 :                :  *
                               1589                 :                :  * On entry, tuple->t_self is the TID to fetch.  We pin the buffer holding
                               1590                 :                :  * the tuple, fill in the remaining fields of *tuple, and check the tuple
                               1591                 :                :  * against the specified snapshot.
                               1592                 :                :  *
                               1593                 :                :  * If successful (tuple found and passes snapshot time qual), then *userbuf
                               1594                 :                :  * is set to the buffer holding the tuple and true is returned.  The caller
                               1595                 :                :  * must unpin the buffer when done with the tuple.
                               1596                 :                :  *
                               1597                 :                :  * If the tuple is not found (ie, item number references a deleted slot),
                               1598                 :                :  * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
                               1599                 :                :  * and false is returned.
                               1600                 :                :  *
                               1601                 :                :  * If the tuple is found but fails the time qual check, then the behavior
                               1602                 :                :  * depends on the keep_buf parameter.  If keep_buf is false, the results
                               1603                 :                :  * are the same as for the tuple-not-found case.  If keep_buf is true,
                               1604                 :                :  * then tuple->t_data and *userbuf are returned as for the success case,
                               1605                 :                :  * and again the caller must unpin the buffer; but false is returned.
                               1606                 :                :  *
                               1607                 :                :  * heap_fetch does not follow HOT chains: only the exact TID requested will
                               1608                 :                :  * be fetched.
                               1609                 :                :  *
                               1610                 :                :  * It is somewhat inconsistent that we ereport() on invalid block number but
                               1611                 :                :  * return false on invalid item number.  There are a couple of reasons though.
                               1612                 :                :  * One is that the caller can relatively easily check the block number for
                               1613                 :                :  * validity, but cannot check the item number without reading the page
                               1614                 :                :  * himself.  Another is that when we are following a t_ctid link, we can be
                               1615                 :                :  * reasonably confident that the page number is valid (since VACUUM shouldn't
                               1616                 :                :  * truncate off the destination page without having killed the referencing
                               1617                 :                :  * tuple first), but the item number might well not be good.
                               1618                 :                :  */
                               1619                 :                : bool
10753 scrappy@hub.org          1620                 :         181478 : heap_fetch(Relation relation,
                               1621                 :                :            Snapshot snapshot,
                               1622                 :                :            HeapTuple tuple,
                               1623                 :                :            Buffer *userbuf,
                               1624                 :                :            bool keep_buf)
                               1625                 :                : {
 8608 tgl@sss.pgh.pa.us        1626                 :         181478 :     ItemPointer tid = &(tuple->t_self);
                               1627                 :                :     ItemId      lp;
                               1628                 :                :     Buffer      buffer;
                               1629                 :                :     Page        page;
                               1630                 :                :     OffsetNumber offnum;
                               1631                 :                :     bool        valid;
                               1632                 :                : 
                               1633                 :                :     /*
                               1634                 :                :      * Fetch and pin the appropriate page of the relation.
                               1635                 :                :      */
 6467                          1636                 :         181478 :     buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
                               1637                 :                : 
                               1638                 :                :     /*
                               1639                 :                :      * Need share lock on buffer to examine tuple commit status.
                               1640                 :                :      */
 9864 vadim4o@yahoo.com        1641                 :         181469 :     LockBuffer(buffer, BUFFER_LOCK_SHARE);
 3528 kgrittn@postgresql.o     1642                 :         181469 :     page = BufferGetPage(buffer);
                               1643                 :                : 
                               1644                 :                :     /*
                               1645                 :                :      * We'd better check for out-of-range offnum in case of VACUUM since the
                               1646                 :                :      * TID was obtained.
                               1647                 :                :      */
10328 bruce@momjian.us         1648                 :         181469 :     offnum = ItemPointerGetOffsetNumber(tid);
 6366 tgl@sss.pgh.pa.us        1649   [ +  -  +  + ]:         181469 :     if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
                               1650                 :                :     {
 7570                          1651                 :              3 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
 2461 andres@anarazel.de       1652                 :              3 :         ReleaseBuffer(buffer);
                               1653                 :              3 :         *userbuf = InvalidBuffer;
 7570 tgl@sss.pgh.pa.us        1654                 :              3 :         tuple->t_data = NULL;
                               1655                 :              3 :         return false;
                               1656                 :                :     }
                               1657                 :                : 
                               1658                 :                :     /*
                               1659                 :                :      * get the item line pointer corresponding to the requested tid
                               1660                 :                :      */
 6366                          1661                 :         181466 :     lp = PageGetItemId(page, offnum);
                               1662                 :                : 
                               1663                 :                :     /*
                               1664                 :                :      * Must check for deleted tuple.
                               1665                 :                :      */
 6671                          1666         [ +  + ]:         181466 :     if (!ItemIdIsNormal(lp))
                               1667                 :                :     {
 9297 vadim4o@yahoo.com        1668                 :            354 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
 2461 andres@anarazel.de       1669                 :            354 :         ReleaseBuffer(buffer);
                               1670                 :            354 :         *userbuf = InvalidBuffer;
 8608 tgl@sss.pgh.pa.us        1671                 :            354 :         tuple->t_data = NULL;
                               1672                 :            354 :         return false;
                               1673                 :                :     }
                               1674                 :                : 
                               1675                 :                :     /*
                               1676                 :                :      * fill in *tuple fields
                               1677                 :                :      */
 6366                          1678                 :         181112 :     tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
 9882 vadim4o@yahoo.com        1679                 :         181112 :     tuple->t_len = ItemIdGetLength(lp);
 7424 tgl@sss.pgh.pa.us        1680                 :         181112 :     tuple->t_tableOid = RelationGetRelid(relation);
                               1681                 :                : 
                               1682                 :                :     /*
                               1683                 :                :      * check tuple visibility, then release lock
                               1684                 :                :      */
 7326                          1685                 :         181112 :     valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
                               1686                 :                : 
 5427 heikki.linnakangas@i     1687         [ +  + ]:         181112 :     if (valid)
 2150 tmunro@postgresql.or     1688                 :         181057 :         PredicateLockTID(relation, &(tuple->t_self), snapshot,
                               1689                 :         181057 :                          HeapTupleHeaderGetXmin(tuple->t_data));
                               1690                 :                : 
                               1691                 :         181112 :     HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
                               1692                 :                : 
 5402 heikki.linnakangas@i     1693                 :         181112 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               1694                 :                : 
 8608 tgl@sss.pgh.pa.us        1695         [ +  + ]:         181112 :     if (valid)
                               1696                 :                :     {
                               1697                 :                :         /*
                               1698                 :                :          * All checks passed, so return the tuple as valid. Caller is now
                               1699                 :                :          * responsible for releasing the buffer.
                               1700                 :                :          */
 9581                          1701                 :         181057 :         *userbuf = buffer;
                               1702                 :                : 
 8608                          1703                 :         181057 :         return true;
                               1704                 :                :     }
                               1705                 :                : 
                               1706                 :                :     /* Tuple failed time qual, but maybe caller wants to see it anyway. */
 1344                          1707         [ +  + ]:             55 :     if (keep_buf)
                               1708                 :             34 :         *userbuf = buffer;
                               1709                 :                :     else
                               1710                 :                :     {
                               1711                 :             21 :         ReleaseBuffer(buffer);
                               1712                 :             21 :         *userbuf = InvalidBuffer;
                               1713                 :             21 :         tuple->t_data = NULL;
                               1714                 :                :     }
                               1715                 :                : 
 8608                          1716                 :             55 :     return false;
                               1717                 :                : }
                               1718                 :                : 
                               1719                 :                : /*
                               1720                 :                :  *  heap_hot_search_buffer  - search HOT chain for tuple satisfying snapshot
                               1721                 :                :  *
                               1722                 :                :  * On entry, *tid is the TID of a tuple (either a simple tuple, or the root
                               1723                 :                :  * of a HOT chain), and buffer is the buffer holding this tuple.  We search
                               1724                 :                :  * for the first chain member satisfying the given snapshot.  If one is
                               1725                 :                :  * found, we update *tid to reference that tuple's offset number, and
                               1726                 :                :  * return true.  If no match, return false without modifying *tid.
                               1727                 :                :  *
                               1728                 :                :  * heapTuple is a caller-supplied buffer.  When a match is found, we return
                               1729                 :                :  * the tuple here, in addition to updating *tid.  If no match is found, the
                               1730                 :                :  * contents of this buffer on return are undefined.
                               1731                 :                :  *
                               1732                 :                :  * If all_dead is not NULL, we check non-visible tuples to see if they are
                               1733                 :                :  * globally dead; *all_dead is set true if all members of the HOT chain
                               1734                 :                :  * are vacuumable, false if not.
                               1735                 :                :  *
                               1736                 :                :  * Unlike heap_fetch, the caller must already have pin and (at least) share
                               1737                 :                :  * lock on the buffer; it is still pinned/locked at exit.
                               1738                 :                :  */
                               1739                 :                : bool
 5427 heikki.linnakangas@i     1740                 :       21490585 : heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer,
                               1741                 :                :                        Snapshot snapshot, HeapTuple heapTuple,
                               1742                 :                :                        bool *all_dead, bool first_call)
                               1743                 :                : {
 1127 peter@eisentraut.org     1744                 :       21490585 :     Page        page = BufferGetPage(buffer);
 6663 tgl@sss.pgh.pa.us        1745                 :       21490585 :     TransactionId prev_xmax = InvalidTransactionId;
                               1746                 :                :     BlockNumber blkno;
                               1747                 :                :     OffsetNumber offnum;
                               1748                 :                :     bool        at_chain_start;
                               1749                 :                :     bool        valid;
                               1750                 :                :     bool        skip;
 1953 andres@anarazel.de       1751                 :       21490585 :     GlobalVisState *vistest = NULL;
                               1752                 :                : 
                               1753                 :                :     /* If this is not the first call, previous call returned a (live!) tuple */
 6663 tgl@sss.pgh.pa.us        1754         [ +  + ]:       21490585 :     if (all_dead)
 5287 rhaas@postgresql.org     1755                 :       18197827 :         *all_dead = first_call;
                               1756                 :                : 
 2324 heikki.linnakangas@i     1757                 :       21490585 :     blkno = ItemPointerGetBlockNumber(tid);
 6663 tgl@sss.pgh.pa.us        1758                 :       21490585 :     offnum = ItemPointerGetOffsetNumber(tid);
 5287 rhaas@postgresql.org     1759                 :       21490585 :     at_chain_start = first_call;
                               1760                 :       21490585 :     skip = !first_call;
                               1761                 :                : 
                               1762                 :                :     /* XXX: we should assert that a snapshot is pushed or registered */
 1953 andres@anarazel.de       1763         [ -  + ]:       21490585 :     Assert(TransactionIdIsValid(RecentXmin));
 2324 heikki.linnakangas@i     1764         [ +  - ]:       21490585 :     Assert(BufferGetBlockNumber(buffer) == blkno);
                               1765                 :                : 
                               1766                 :                :     /* Scan through possible multiple members of HOT-chain */
                               1767                 :                :     for (;;)
 6663 tgl@sss.pgh.pa.us        1768                 :        1621481 :     {
                               1769                 :                :         ItemId      lp;
                               1770                 :                : 
                               1771                 :                :         /* check for bogus TID */
 1127 peter@eisentraut.org     1772   [ +  -  +  - ]:       23112066 :         if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
                               1773                 :                :             break;
                               1774                 :                : 
                               1775                 :       23112066 :         lp = PageGetItemId(page, offnum);
                               1776                 :                : 
                               1777                 :                :         /* check for unused, dead, or redirected items */
 6663 tgl@sss.pgh.pa.us        1778         [ +  + ]:       23112066 :         if (!ItemIdIsNormal(lp))
                               1779                 :                :         {
                               1780                 :                :             /* We should only see a redirect at start of chain */
                               1781   [ +  +  +  - ]:         779363 :             if (ItemIdIsRedirected(lp) && at_chain_start)
                               1782                 :                :             {
                               1783                 :                :                 /* Follow the redirect */
                               1784                 :         422418 :                 offnum = ItemIdGetRedirect(lp);
                               1785                 :         422418 :                 at_chain_start = false;
                               1786                 :         422418 :                 continue;
                               1787                 :                :             }
                               1788                 :                :             /* else must be end of chain */
                               1789                 :         356945 :             break;
                               1790                 :                :         }
                               1791                 :                : 
                               1792                 :                :         /*
                               1793                 :                :          * Update heapTuple to point to the element of the HOT chain we're
                               1794                 :                :          * currently investigating. Having t_self set correctly is important
                               1795                 :                :          * because the SSI checks and the *Satisfies routine for historical
                               1796                 :                :          * MVCC snapshots need the correct tid to decide about the visibility.
                               1797                 :                :          */
 1127 peter@eisentraut.org     1798                 :       22332703 :         heapTuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
 5287 rhaas@postgresql.org     1799                 :       22332703 :         heapTuple->t_len = ItemIdGetLength(lp);
 4531                          1800                 :       22332703 :         heapTuple->t_tableOid = RelationGetRelid(relation);
 2324 heikki.linnakangas@i     1801                 :       22332703 :         ItemPointerSet(&heapTuple->t_self, blkno, offnum);
                               1802                 :                : 
                               1803                 :                :         /*
                               1804                 :                :          * Shouldn't see a HEAP_ONLY tuple at chain start.
                               1805                 :                :          */
 5287 rhaas@postgresql.org     1806   [ +  +  -  + ]:       22332703 :         if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
 6663 tgl@sss.pgh.pa.us        1807                 :UBC           0 :             break;
                               1808                 :                : 
                               1809                 :                :         /*
                               1810                 :                :          * The xmin should match the previous xmax value, else chain is
                               1811                 :                :          * broken.
                               1812                 :                :          */
 6663 tgl@sss.pgh.pa.us        1813   [ +  +  -  + ]:CBC    23531766 :         if (TransactionIdIsValid(prev_xmax) &&
 2967 alvherre@alvh.no-ip.     1814                 :        1199063 :             !TransactionIdEquals(prev_xmax,
                               1815                 :                :                                  HeapTupleHeaderGetXmin(heapTuple->t_data)))
 6663 tgl@sss.pgh.pa.us        1816                 :UBC           0 :             break;
                               1817                 :                : 
                               1818                 :                :         /*
                               1819                 :                :          * When first_call is true (and thus, skip is initially false) we'll
                               1820                 :                :          * return the first tuple we find.  But on later passes, heapTuple
                               1821                 :                :          * will initially be pointing to the tuple we returned last time.
                               1822                 :                :          * Returning it again would be incorrect (and would loop forever), so
                               1823                 :                :          * we skip it and return the next match we find.
                               1824                 :                :          */
 5287 rhaas@postgresql.org     1825         [ +  + ]:CBC    22332703 :         if (!skip)
                               1826                 :                :         {
                               1827                 :                :             /* If it's visible per the snapshot, we must return it */
                               1828                 :       22246258 :             valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
 2150 tmunro@postgresql.or     1829                 :       22246258 :             HeapCheckForSerializableConflictOut(valid, relation, heapTuple,
                               1830                 :                :                                                 buffer, snapshot);
                               1831                 :                : 
 5287 rhaas@postgresql.org     1832         [ +  + ]:       22246253 :             if (valid)
                               1833                 :                :             {
                               1834                 :       14899736 :                 ItemPointerSetOffsetNumber(tid, offnum);
 2150 tmunro@postgresql.or     1835                 :       14899736 :                 PredicateLockTID(relation, &heapTuple->t_self, snapshot,
                               1836                 :       14899736 :                                  HeapTupleHeaderGetXmin(heapTuple->t_data));
 5287 rhaas@postgresql.org     1837         [ +  + ]:       14899736 :                 if (all_dead)
                               1838                 :       11887521 :                     *all_dead = false;
                               1839                 :       14899736 :                 return true;
                               1840                 :                :             }
                               1841                 :                :         }
                               1842                 :        7432962 :         skip = false;
                               1843                 :                : 
                               1844                 :                :         /*
                               1845                 :                :          * If we can't see it, maybe no one else can either.  At caller
                               1846                 :                :          * request, check whether all chain members are dead to all
                               1847                 :                :          * transactions.
                               1848                 :                :          *
                               1849                 :                :          * Note: if you change the criterion here for what is "dead", fix the
                               1850                 :                :          * planner's get_actual_variable_range() function to match.
                               1851                 :                :          */
 1953 andres@anarazel.de       1852   [ +  +  +  + ]:        7432962 :         if (all_dead && *all_dead)
                               1853                 :                :         {
                               1854         [ +  + ]:        6477122 :             if (!vistest)
                               1855                 :        6358394 :                 vistest = GlobalVisTestFor(relation);
                               1856                 :                : 
                               1857         [ +  + ]:        6477122 :             if (!HeapTupleIsSurelyDead(heapTuple, vistest))
                               1858                 :        6121855 :                 *all_dead = false;
                               1859                 :                :         }
                               1860                 :                : 
                               1861                 :                :         /*
                               1862                 :                :          * Check to see if HOT chain continues past this tuple; if so fetch
                               1863                 :                :          * the next offnum and loop around.
                               1864                 :                :          */
 5287 rhaas@postgresql.org     1865         [ +  + ]:        7432962 :         if (HeapTupleIsHotUpdated(heapTuple))
                               1866                 :                :         {
                               1867         [ -  + ]:        1199063 :             Assert(ItemPointerGetBlockNumber(&heapTuple->t_data->t_ctid) ==
                               1868                 :                :                    blkno);
                               1869                 :        1199063 :             offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
 6663 tgl@sss.pgh.pa.us        1870                 :        1199063 :             at_chain_start = false;
 4711 alvherre@alvh.no-ip.     1871                 :        1199063 :             prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
                               1872                 :                :         }
                               1873                 :                :         else
 6607 bruce@momjian.us         1874                 :        6233899 :             break;              /* end of chain */
                               1875                 :                :     }
                               1876                 :                : 
 5315 heikki.linnakangas@i     1877                 :        6590844 :     return false;
                               1878                 :                : }
                               1879                 :                : 
                               1880                 :                : /*
                               1881                 :                :  *  heap_get_latest_tid -  get the latest tid of a specified tuple
                               1882                 :                :  *
                               1883                 :                :  * Actually, this gets the latest version that is visible according to the
                               1884                 :                :  * scan's snapshot.  Create a scan using SnapshotDirty to get the very latest,
                               1885                 :                :  * possibly uncommitted version.
                               1886                 :                :  *
                               1887                 :                :  * *tid is both an input and an output parameter: it is updated to
                               1888                 :                :  * show the latest version of the row.  Note that it will not be changed
                               1889                 :                :  * if no version of the row passes the snapshot test.
                               1890                 :                :  */
                               1891                 :                : void
 2406 andres@anarazel.de       1892                 :            150 : heap_get_latest_tid(TableScanDesc sscan,
                               1893                 :                :                     ItemPointer tid)
                               1894                 :                : {
 2401 tgl@sss.pgh.pa.us        1895                 :            150 :     Relation    relation = sscan->rs_rd;
                               1896                 :            150 :     Snapshot    snapshot = sscan->rs_snapshot;
                               1897                 :                :     ItemPointerData ctid;
                               1898                 :                :     TransactionId priorXmax;
                               1899                 :                : 
                               1900                 :                :     /*
                               1901                 :                :      * table_tuple_get_latest_tid() verified that the passed in tid is valid.
                               1902                 :                :      * Assume that t_ctid links are valid however - there shouldn't be invalid
                               1903                 :                :      * ones in the table.
                               1904                 :                :      */
 2406 andres@anarazel.de       1905         [ -  + ]:            150 :     Assert(ItemPointerIsValid(tid));
                               1906                 :                : 
                               1907                 :                :     /*
                               1908                 :                :      * Loop to chase down t_ctid links.  At top of loop, ctid is the tuple we
                               1909                 :                :      * need to examine, and *tid is the TID we will return if ctid turns out
                               1910                 :                :      * to be bogus.
                               1911                 :                :      *
                               1912                 :                :      * Note that we will loop until we reach the end of the t_ctid chain.
                               1913                 :                :      * Depending on the snapshot passed, there might be at most one visible
                               1914                 :                :      * version of the row, but we don't try to optimize for that.
                               1915                 :                :      */
 7424 tgl@sss.pgh.pa.us        1916                 :            150 :     ctid = *tid;
                               1917                 :            150 :     priorXmax = InvalidTransactionId;   /* cannot check first XMIN */
                               1918                 :                :     for (;;)
                               1919                 :             45 :     {
                               1920                 :                :         Buffer      buffer;
                               1921                 :                :         Page        page;
                               1922                 :                :         OffsetNumber offnum;
                               1923                 :                :         ItemId      lp;
                               1924                 :                :         HeapTupleData tp;
                               1925                 :                :         bool        valid;
                               1926                 :                : 
                               1927                 :                :         /*
                               1928                 :                :          * Read, pin, and lock the page.
                               1929                 :                :          */
                               1930                 :            195 :         buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
                               1931                 :            195 :         LockBuffer(buffer, BUFFER_LOCK_SHARE);
 3528 kgrittn@postgresql.o     1932                 :            195 :         page = BufferGetPage(buffer);
                               1933                 :                : 
                               1934                 :                :         /*
                               1935                 :                :          * Check for bogus item number.  This is not treated as an error
                               1936                 :                :          * condition because it can happen while following a t_ctid link. We
                               1937                 :                :          * just assume that the prior tid is OK and return it unchanged.
                               1938                 :                :          */
 7424 tgl@sss.pgh.pa.us        1939                 :            195 :         offnum = ItemPointerGetOffsetNumber(&ctid);
 6366                          1940   [ +  -  -  + ]:            195 :         if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
                               1941                 :                :         {
 7201 tgl@sss.pgh.pa.us        1942                 :UBC           0 :             UnlockReleaseBuffer(buffer);
 7424                          1943                 :              0 :             break;
                               1944                 :                :         }
 6366 tgl@sss.pgh.pa.us        1945                 :CBC         195 :         lp = PageGetItemId(page, offnum);
 6671                          1946         [ -  + ]:            195 :         if (!ItemIdIsNormal(lp))
                               1947                 :                :         {
 7201 tgl@sss.pgh.pa.us        1948                 :UBC           0 :             UnlockReleaseBuffer(buffer);
 7424                          1949                 :              0 :             break;
                               1950                 :                :         }
                               1951                 :                : 
                               1952                 :                :         /* OK to access the tuple */
 7424 tgl@sss.pgh.pa.us        1953                 :CBC         195 :         tp.t_self = ctid;
 6366                          1954                 :            195 :         tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
 7424                          1955                 :            195 :         tp.t_len = ItemIdGetLength(lp);
 4531 rhaas@postgresql.org     1956                 :            195 :         tp.t_tableOid = RelationGetRelid(relation);
                               1957                 :                : 
                               1958                 :                :         /*
                               1959                 :                :          * After following a t_ctid link, we might arrive at an unrelated
                               1960                 :                :          * tuple.  Check for XMIN match.
                               1961                 :                :          */
 7424 tgl@sss.pgh.pa.us        1962   [ +  +  -  + ]:            240 :         if (TransactionIdIsValid(priorXmax) &&
 2967 alvherre@alvh.no-ip.     1963                 :             45 :             !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
                               1964                 :                :         {
 7201 tgl@sss.pgh.pa.us        1965                 :UBC           0 :             UnlockReleaseBuffer(buffer);
 7424                          1966                 :              0 :             break;
                               1967                 :                :         }
                               1968                 :                : 
                               1969                 :                :         /*
                               1970                 :                :          * Check tuple visibility; if visible, set it as the new result
                               1971                 :                :          * candidate.
                               1972                 :                :          */
 7326 tgl@sss.pgh.pa.us        1973                 :CBC         195 :         valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
 2150 tmunro@postgresql.or     1974                 :            195 :         HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
 7424 tgl@sss.pgh.pa.us        1975         [ +  + ]:            195 :         if (valid)
                               1976                 :            138 :             *tid = ctid;
                               1977                 :                : 
                               1978                 :                :         /*
                               1979                 :                :          * If there's a valid t_ctid link, follow it, else we're done.
                               1980                 :                :          */
 4711 alvherre@alvh.no-ip.     1981   [ +  +  +  + ]:            276 :         if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
                               1982         [ +  - ]:            138 :             HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
 2811 andres@anarazel.de       1983         [ +  + ]:            114 :             HeapTupleHeaderIndicatesMovedPartitions(tp.t_data) ||
 7424 tgl@sss.pgh.pa.us        1984                 :             57 :             ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
                               1985                 :                :         {
 7201                          1986                 :            150 :             UnlockReleaseBuffer(buffer);
 7424                          1987                 :            150 :             break;
                               1988                 :                :         }
                               1989                 :                : 
                               1990                 :             45 :         ctid = tp.t_data->t_ctid;
 4711 alvherre@alvh.no-ip.     1991                 :             45 :         priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
 7201 tgl@sss.pgh.pa.us        1992                 :             45 :         UnlockReleaseBuffer(buffer);
                               1993                 :                :     }                           /* end of loop */
 9564 inoue@tpf.co.jp          1994                 :            150 : }
                               1995                 :                : 
                               1996                 :                : 
                               1997                 :                : /*
                               1998                 :                :  * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
                               1999                 :                :  *
                               2000                 :                :  * This is called after we have waited for the XMAX transaction to terminate.
                               2001                 :                :  * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
                               2002                 :                :  * be set on exit.  If the transaction committed, we set the XMAX_COMMITTED
                               2003                 :                :  * hint bit if possible --- but beware that that may not yet be possible,
                               2004                 :                :  * if the transaction committed asynchronously.
                               2005                 :                :  *
                               2006                 :                :  * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
                               2007                 :                :  * even if it commits.
                               2008                 :                :  *
                               2009                 :                :  * Hence callers should look only at XMAX_INVALID.
                               2010                 :                :  *
                               2011                 :                :  * Note this is not allowed for tuples whose xmax is a multixact.
                               2012                 :                :  */
                               2013                 :                : static void
 6700 tgl@sss.pgh.pa.us        2014                 :            221 : UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
                               2015                 :                : {
 4711 alvherre@alvh.no-ip.     2016         [ -  + ]:            221 :     Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
                               2017         [ -  + ]:            221 :     Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
                               2018                 :                : 
 6700 tgl@sss.pgh.pa.us        2019         [ +  - ]:            221 :     if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
                               2020                 :                :     {
 4711 alvherre@alvh.no-ip.     2021   [ +  +  +  + ]:            397 :         if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
                               2022                 :            176 :             TransactionIdDidCommit(xid))
 6700 tgl@sss.pgh.pa.us        2023                 :            149 :             HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
                               2024                 :                :                                  xid);
                               2025                 :                :         else
                               2026                 :             72 :             HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
                               2027                 :                :                                  InvalidTransactionId);
                               2028                 :                :     }
                               2029                 :            221 : }
                               2030                 :                : 
                               2031                 :                : 
                               2032                 :                : /*
                               2033                 :                :  * GetBulkInsertState - prepare status object for a bulk insert
                               2034                 :                :  */
                               2035                 :                : BulkInsertState
 6250                          2036                 :           2723 : GetBulkInsertState(void)
                               2037                 :                : {
                               2038                 :                :     BulkInsertState bistate;
                               2039                 :                : 
    7 michael@paquier.xyz      2040                 :GNC        2723 :     bistate = (BulkInsertState) palloc_object(BulkInsertStateData);
 6250 tgl@sss.pgh.pa.us        2041                 :CBC        2723 :     bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
                               2042                 :           2723 :     bistate->current_buf = InvalidBuffer;
  986 andres@anarazel.de       2043                 :           2723 :     bistate->next_free = InvalidBlockNumber;
                               2044                 :           2723 :     bistate->last_free = InvalidBlockNumber;
  856                          2045                 :           2723 :     bistate->already_extended_by = 0;
 6250 tgl@sss.pgh.pa.us        2046                 :           2723 :     return bistate;
                               2047                 :                : }
                               2048                 :                : 
                               2049                 :                : /*
                               2050                 :                :  * FreeBulkInsertState - clean up after finishing a bulk insert
                               2051                 :                :  */
                               2052                 :                : void
                               2053                 :           2578 : FreeBulkInsertState(BulkInsertState bistate)
                               2054                 :                : {
                               2055         [ +  + ]:           2578 :     if (bistate->current_buf != InvalidBuffer)
 6033 bruce@momjian.us         2056                 :           1999 :         ReleaseBuffer(bistate->current_buf);
 6250 tgl@sss.pgh.pa.us        2057                 :           2578 :     FreeAccessStrategy(bistate->strategy);
                               2058                 :           2578 :     pfree(bistate);
                               2059                 :           2578 : }
                               2060                 :                : 
                               2061                 :                : /*
                               2062                 :                :  * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
                               2063                 :                :  */
                               2064                 :                : void
 3249 rhaas@postgresql.org     2065                 :          80758 : ReleaseBulkInsertStatePin(BulkInsertState bistate)
                               2066                 :                : {
                               2067         [ +  + ]:          80758 :     if (bistate->current_buf != InvalidBuffer)
                               2068                 :          30021 :         ReleaseBuffer(bistate->current_buf);
                               2069                 :          80758 :     bistate->current_buf = InvalidBuffer;
                               2070                 :                : 
                               2071                 :                :     /*
                               2072                 :                :      * Despite the name, we also reset bulk relation extension state.
                               2073                 :                :      * Otherwise we can end up erroring out due to looking for free space in
                               2074                 :                :      * ->next_free of one partition, even though ->next_free was set when
                               2075                 :                :      * extending another partition. It could obviously also be bad for
                               2076                 :                :      * efficiency to look at existing blocks at offsets from another
                               2077                 :                :      * partition, even if we don't error out.
                               2078                 :                :      */
  796 andres@anarazel.de       2079                 :          80758 :     bistate->next_free = InvalidBlockNumber;
                               2080                 :          80758 :     bistate->last_free = InvalidBlockNumber;
 3249 rhaas@postgresql.org     2081                 :          80758 : }
                               2082                 :                : 
                               2083                 :                : 
                               2084                 :                : /*
                               2085                 :                :  *  heap_insert     - insert tuple into a heap
                               2086                 :                :  *
                               2087                 :                :  * The new tuple is stamped with current transaction ID and the specified
                               2088                 :                :  * command ID.
                               2089                 :                :  *
                               2090                 :                :  * See table_tuple_insert for comments about most of the input flags, except
                               2091                 :                :  * that this routine directly takes a tuple rather than a slot.
                               2092                 :                :  *
                               2093                 :                :  * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
                               2094                 :                :  * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
                               2095                 :                :  * implement table_tuple_insert_speculative().
                               2096                 :                :  *
                               2097                 :                :  * On return the header fields of *tup are updated to match the stored tuple;
                               2098                 :                :  * in particular tup->t_self receives the actual TID where the tuple was
                               2099                 :                :  * stored.  But note that any toasting of fields within the tuple data is NOT
                               2100                 :                :  * reflected into *tup.
                               2101                 :                :  */
                               2102                 :                : void
 7485 tgl@sss.pgh.pa.us        2103                 :        8451135 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
                               2104                 :                :             int options, BulkInsertState bistate)
                               2105                 :                : {
 7762                          2106                 :        8451135 :     TransactionId xid = GetCurrentTransactionId();
                               2107                 :                :     HeapTuple   heaptup;
                               2108                 :                :     Buffer      buffer;
 5293 rhaas@postgresql.org     2109                 :        8451135 :     Buffer      vmbuffer = InvalidBuffer;
 6223 heikki.linnakangas@i     2110                 :        8451135 :     bool        all_visible_cleared = false;
                               2111                 :                : 
                               2112                 :                :     /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
 1682 tgl@sss.pgh.pa.us        2113         [ -  + ]:        8451135 :     Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
                               2114                 :                :            RelationGetNumberOfAttributes(relation));
                               2115                 :                : 
  201 nathan@postgresql.or     2116                 :        8451135 :     AssertHasSnapshotForToast(relation);
                               2117                 :                : 
                               2118                 :                :     /*
                               2119                 :                :      * Fill in tuple header fields and toast the tuple if necessary.
                               2120                 :                :      *
                               2121                 :                :      * Note: below this point, heaptup is the data we actually intend to store
                               2122                 :                :      * into the relation; tup is the caller's original untoasted data.
                               2123                 :                :      */
 5152 heikki.linnakangas@i     2124                 :        8451135 :     heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
                               2125                 :                : 
                               2126                 :                :     /*
                               2127                 :                :      * Find buffer to insert this tuple into.  If the page is all visible,
                               2128                 :                :      * this will also pin the requisite visibility map page.
                               2129                 :                :      */
 3700 kgrittn@postgresql.o     2130                 :        8451135 :     buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
                               2131                 :                :                                        InvalidBuffer, options, bistate,
                               2132                 :                :                                        &vmbuffer, NULL,
                               2133                 :                :                                        0);
                               2134                 :                : 
                               2135                 :                :     /*
                               2136                 :                :      * We're about to do the actual insert -- but check for conflict first, to
                               2137                 :                :      * avoid possibly having to roll back work we've just done.
                               2138                 :                :      *
                               2139                 :                :      * This is safe without a recheck as long as there is no possibility of
                               2140                 :                :      * another process scanning the page between this check and the insert
                               2141                 :                :      * being visible to the scan (i.e., an exclusive buffer content lock is
                               2142                 :                :      * continuously held from this point until the tuple insert is visible).
                               2143                 :                :      *
                               2144                 :                :      * For a heap insert, we only need to check for table-level SSI locks. Our
                               2145                 :                :      * new tuple can't possibly conflict with existing tuple locks, and heap
                               2146                 :                :      * page locks are only consolidated versions of tuple locks; they do not
                               2147                 :                :      * lock "gaps" as index page locks do.  So we don't need to specify a
                               2148                 :                :      * buffer when making the call, which makes for a faster check.
                               2149                 :                :      */
 2150 tmunro@postgresql.or     2150                 :        8451135 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
                               2151                 :                : 
                               2152                 :                :     /* NO EREPORT(ERROR) from here till changes are logged */
 9105 tgl@sss.pgh.pa.us        2153                 :        8451123 :     START_CRIT_SECTION();
                               2154                 :                : 
 3876 andres@anarazel.de       2155                 :        8451123 :     RelationPutHeapTuple(relation, buffer, heaptup,
                               2156                 :        8451123 :                          (options & HEAP_INSERT_SPECULATIVE) != 0);
                               2157                 :                : 
 1658 tomas.vondra@postgre     2158         [ +  + ]:        8451123 :     if (PageIsAllVisible(BufferGetPage(buffer)))
                               2159                 :                :     {
 6223 heikki.linnakangas@i     2160                 :           7616 :         all_visible_cleared = true;
 3528 kgrittn@postgresql.o     2161                 :           7616 :         PageClearAllVisible(BufferGetPage(buffer));
 5293 rhaas@postgresql.org     2162                 :           7616 :         visibilitymap_clear(relation,
                               2163                 :           7616 :                             ItemPointerGetBlockNumber(&(heaptup->t_self)),
                               2164                 :                :                             vmbuffer, VISIBILITYMAP_VALID_BITS);
                               2165                 :                :     }
                               2166                 :                : 
                               2167                 :                :     /*
                               2168                 :                :      * XXX Should we set PageSetPrunable on this page ?
                               2169                 :                :      *
                               2170                 :                :      * The inserting transaction may eventually abort thus making this tuple
                               2171                 :                :      * DEAD and hence available for pruning. Though we don't want to optimize
                               2172                 :                :      * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
                               2173                 :                :      * aborted tuple will never be pruned until next vacuum is triggered.
                               2174                 :                :      *
                               2175                 :                :      * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
                               2176                 :                :      */
                               2177                 :                : 
 7201 tgl@sss.pgh.pa.us        2178                 :        8451123 :     MarkBufferDirty(buffer);
                               2179                 :                : 
                               2180                 :                :     /* XLOG stuff */
 2083 noah@leadboat.com        2181   [ +  +  +  +  :        8451123 :     if (RelationNeedsWAL(relation))
                                        +  +  +  + ]
                               2182                 :                :     {
                               2183                 :                :         xl_heap_insert xlrec;
                               2184                 :                :         xl_heap_header xlhdr;
                               2185                 :                :         XLogRecPtr  recptr;
 3528 kgrittn@postgresql.o     2186                 :        7099680 :         Page        page = BufferGetPage(buffer);
 9036 bruce@momjian.us         2187                 :        7099680 :         uint8       info = XLOG_HEAP_INSERT;
 4045 heikki.linnakangas@i     2188                 :        7099680 :         int         bufflags = 0;
                               2189                 :                : 
                               2190                 :                :         /*
                               2191                 :                :          * If this is a catalog, we need to transmit combo CIDs to properly
                               2192                 :                :          * decode, so log that as well.
                               2193                 :                :          */
 4390 rhaas@postgresql.org     2194   [ +  +  +  -  :        7099680 :         if (RelationIsAccessibleInLogicalDecoding(relation))
                                     -  +  -  -  -  
                                     -  +  +  +  +  
                                     -  +  -  -  +  
                                                 + ]
                               2195                 :           3305 :             log_heap_new_cid(relation, heaptup);
                               2196                 :                : 
                               2197                 :                :         /*
                               2198                 :                :          * If this is the single and first tuple on page, we can reinit the
                               2199                 :                :          * page instead of restoring the whole thing.  Set flag, and hide
                               2200                 :                :          * buffer references from XLogInsert.
                               2201                 :                :          */
 4045 heikki.linnakangas@i     2202   [ +  +  +  + ]:        7190286 :         if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
                               2203                 :          90606 :             PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
                               2204                 :                :         {
                               2205                 :          89484 :             info |= XLOG_HEAP_INIT_PAGE;
                               2206                 :          89484 :             bufflags |= REGBUF_WILL_INIT;
                               2207                 :                :         }
                               2208                 :                : 
                               2209                 :        7099680 :         xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
 3876 andres@anarazel.de       2210                 :        7099680 :         xlrec.flags = 0;
                               2211         [ +  + ]:        7099680 :         if (all_visible_cleared)
                               2212                 :           7613 :             xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
                               2213         [ +  + ]:        7099680 :         if (options & HEAP_INSERT_SPECULATIVE)
                               2214                 :           2073 :             xlrec.flags |= XLH_INSERT_IS_SPECULATIVE;
 4045 heikki.linnakangas@i     2215         [ -  + ]:        7099680 :         Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
                               2216                 :                : 
                               2217                 :                :         /*
                               2218                 :                :          * For logical decoding, we need the tuple even if we're doing a full
                               2219                 :                :          * page write, so make sure it's included even if we take a full-page
                               2220                 :                :          * image. (XXX We could alternatively store a pointer into the FPW).
                               2221                 :                :          */
 2625 andres@anarazel.de       2222   [ +  +  +  -  :        7099680 :         if (RelationIsLogicallyLogged(relation) &&
                                     -  +  -  -  -  
                                        -  +  -  +  
                                                 + ]
                               2223         [ +  + ]:         250423 :             !(options & HEAP_INSERT_NO_LOGICAL))
                               2224                 :                :         {
 3876                          2225                 :         250396 :             xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
 4045 heikki.linnakangas@i     2226                 :         250396 :             bufflags |= REGBUF_KEEP_DATA;
                               2227                 :                : 
 1957 akapila@postgresql.o     2228         [ +  + ]:         250396 :             if (IsToastRelation(relation))
                               2229                 :           1786 :                 xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
                               2230                 :                :         }
                               2231                 :                : 
 4045 heikki.linnakangas@i     2232                 :        7099680 :         XLogBeginInsert();
  309 peter@eisentraut.org     2233                 :        7099680 :         XLogRegisterData(&xlrec, SizeOfHeapInsert);
                               2234                 :                : 
 4045 heikki.linnakangas@i     2235                 :        7099680 :         xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
                               2236                 :        7099680 :         xlhdr.t_infomask = heaptup->t_data->t_infomask;
                               2237                 :        7099680 :         xlhdr.t_hoff = heaptup->t_data->t_hoff;
                               2238                 :                : 
                               2239                 :                :         /*
                               2240                 :                :          * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
                               2241                 :                :          * write the whole page to the xlog, we don't need to store
                               2242                 :                :          * xl_heap_header in the xlog.
                               2243                 :                :          */
                               2244                 :        7099680 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
  309 peter@eisentraut.org     2245                 :        7099680 :         XLogRegisterBufData(0, &xlhdr, SizeOfHeapHeader);
                               2246                 :                :         /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
 4045 heikki.linnakangas@i     2247                 :        7099680 :         XLogRegisterBufData(0,
 3952 tgl@sss.pgh.pa.us        2248                 :        7099680 :                             (char *) heaptup->t_data + SizeofHeapTupleHeader,
                               2249                 :        7099680 :                             heaptup->t_len - SizeofHeapTupleHeader);
                               2250                 :                : 
                               2251                 :                :         /* filtering by origin on a row level is much more efficient */
 3282 andres@anarazel.de       2252                 :        7099680 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               2253                 :                : 
 4045 heikki.linnakangas@i     2254                 :        7099680 :         recptr = XLogInsert(RM_HEAP_ID, info);
                               2255                 :                : 
 9120 vadim4o@yahoo.com        2256                 :        7099680 :         PageSetLSN(page, recptr);
                               2257                 :                :     }
                               2258                 :                : 
 9105 tgl@sss.pgh.pa.us        2259         [ -  + ]:        8451123 :     END_CRIT_SECTION();
                               2260                 :                : 
 7201                          2261                 :        8451123 :     UnlockReleaseBuffer(buffer);
 5293 rhaas@postgresql.org     2262         [ +  + ]:        8451123 :     if (vmbuffer != InvalidBuffer)
                               2263                 :           7898 :         ReleaseBuffer(vmbuffer);
                               2264                 :                : 
                               2265                 :                :     /*
                               2266                 :                :      * If tuple is cacheable, mark it for invalidation from the caches in case
                               2267                 :                :      * we abort.  Note it is OK to do this after releasing the buffer, because
                               2268                 :                :      * the heaptup data structure is all in local memory, not in the shared
                               2269                 :                :      * buffer.
                               2270                 :                :      */
 5237 tgl@sss.pgh.pa.us        2271                 :        8451123 :     CacheInvalidateHeapTuple(relation, heaptup, NULL);
                               2272                 :                : 
                               2273                 :                :     /* Note: speculative insertions are counted too, even if aborted later */
 5152 heikki.linnakangas@i     2274                 :        8451123 :     pgstat_count_heap_insert(relation, 1);
                               2275                 :                : 
                               2276                 :                :     /*
                               2277                 :                :      * If heaptup is a private copy, release it.  Don't forget to copy t_self
                               2278                 :                :      * back to the caller's image, too.
                               2279                 :                :      */
 7332 tgl@sss.pgh.pa.us        2280         [ +  + ]:        8451123 :     if (heaptup != tup)
                               2281                 :                :     {
                               2282                 :          18566 :         tup->t_self = heaptup->t_self;
                               2283                 :          18566 :         heap_freetuple(heaptup);
                               2284                 :                :     }
10753 scrappy@hub.org          2285                 :        8451123 : }
                               2286                 :                : 
                               2287                 :                : /*
                               2288                 :                :  * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
                               2289                 :                :  * tuple header fields and toasts the tuple if necessary.  Returns a toasted
                               2290                 :                :  * version of the tuple if it was toasted, or the original tuple if not. Note
                               2291                 :                :  * that in any case, the header fields are also set in the original tuple.
                               2292                 :                :  */
                               2293                 :                : static HeapTuple
 5152 heikki.linnakangas@i     2294                 :       10045674 : heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
                               2295                 :                :                     CommandId cid, int options)
                               2296                 :                : {
                               2297                 :                :     /*
                               2298                 :                :      * To allow parallel inserts, we need to ensure that they are safe to be
                               2299                 :                :      * performed in workers. We have the infrastructure to allow parallel
                               2300                 :                :      * inserts in general except for the cases where inserts generate a new
                               2301                 :                :      * CommandId (eg. inserts into a table having a foreign key column).
                               2302                 :                :      */
 2995 rhaas@postgresql.org     2303         [ -  + ]:       10045674 :     if (IsParallelWorker())
 3884 rhaas@postgresql.org     2304         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2305                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               2306                 :                :                  errmsg("cannot insert tuples in a parallel worker")));
                               2307                 :                : 
 5152 heikki.linnakangas@i     2308                 :CBC    10045674 :     tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
                               2309                 :       10045674 :     tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
                               2310                 :       10045674 :     tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
 4378 rhaas@postgresql.org     2311                 :       10045674 :     HeapTupleHeaderSetXmin(tup->t_data, xid);
 4763 simon@2ndQuadrant.co     2312         [ +  + ]:       10045674 :     if (options & HEAP_INSERT_FROZEN)
 4378 rhaas@postgresql.org     2313                 :         102088 :         HeapTupleHeaderSetXminFrozen(tup->t_data);
                               2314                 :                : 
 5152 heikki.linnakangas@i     2315                 :       10045674 :     HeapTupleHeaderSetCmin(tup->t_data, cid);
 3101 tgl@sss.pgh.pa.us        2316                 :       10045674 :     HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
 5152 heikki.linnakangas@i     2317                 :       10045674 :     tup->t_tableOid = RelationGetRelid(relation);
                               2318                 :                : 
                               2319                 :                :     /*
                               2320                 :                :      * If the new tuple is too big for storage or contains already toasted
                               2321                 :                :      * out-of-line attributes from some other relation, invoke the toaster.
                               2322                 :                :      */
 4672 kgrittn@postgresql.o     2323         [ +  + ]:       10045674 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
                               2324         [ +  + ]:          31443 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
                               2325                 :                :     {
                               2326                 :                :         /* toast table entries should never be recursively toasted */
 5152 heikki.linnakangas@i     2327         [ -  + ]:          31395 :         Assert(!HeapTupleHasExternal(tup));
                               2328                 :          31395 :         return tup;
                               2329                 :                :     }
                               2330   [ +  +  +  + ]:       10014279 :     else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
 2266 rhaas@postgresql.org     2331                 :          18610 :         return heap_toast_insert_or_update(relation, tup, NULL, options);
                               2332                 :                :     else
 5152 heikki.linnakangas@i     2333                 :        9995669 :         return tup;
                               2334                 :                : }
                               2335                 :                : 
                               2336                 :                : /*
                               2337                 :                :  * Helper for heap_multi_insert() that computes the number of entire pages
                               2338                 :                :  * that inserting the remaining heaptuples requires. Used to determine how
                               2339                 :                :  * much the relation needs to be extended by.
                               2340                 :                :  */
                               2341                 :                : static int
  986 andres@anarazel.de       2342                 :         372537 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
                               2343                 :                : {
                               2344                 :         372537 :     size_t      page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
                               2345                 :         372537 :     int         npages = 1;
                               2346                 :                : 
                               2347         [ +  + ]:        2646910 :     for (int i = done; i < ntuples; i++)
                               2348                 :                :     {
                               2349                 :        2274373 :         size_t      tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
                               2350                 :                : 
                               2351         [ +  + ]:        2274373 :         if (page_avail < tup_sz)
                               2352                 :                :         {
                               2353                 :          16322 :             npages++;
                               2354                 :          16322 :             page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
                               2355                 :                :         }
                               2356                 :        2274373 :         page_avail -= tup_sz;
                               2357                 :                :     }
                               2358                 :                : 
                               2359                 :         372537 :     return npages;
                               2360                 :                : }
                               2361                 :                : 
                               2362                 :                : /*
                               2363                 :                :  *  heap_multi_insert   - insert multiple tuples into a heap
                               2364                 :                :  *
                               2365                 :                :  * This is like heap_insert(), but inserts multiple tuples in one operation.
                               2366                 :                :  * That's faster than calling heap_insert() in a loop, because when multiple
                               2367                 :                :  * tuples can be inserted on a single page, we can write just a single WAL
                               2368                 :                :  * record covering all of them, and only need to lock/unlock the page once.
                               2369                 :                :  *
                               2370                 :                :  * Note: this leaks memory into the current memory context. You can create a
                               2371                 :                :  * temporary context before calling this, if that's a problem.
                               2372                 :                :  */
                               2373                 :                : void
 2449                          2374                 :         365819 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
                               2375                 :                :                   CommandId cid, int options, BulkInsertState bistate)
                               2376                 :                : {
 5152 heikki.linnakangas@i     2377                 :         365819 :     TransactionId xid = GetCurrentTransactionId();
                               2378                 :                :     HeapTuple  *heaptuples;
                               2379                 :                :     int         i;
                               2380                 :                :     int         ndone;
                               2381                 :                :     PGAlignedBlock scratch;
                               2382                 :                :     Page        page;
 1795 tomas.vondra@postgre     2383                 :         365819 :     Buffer      vmbuffer = InvalidBuffer;
                               2384                 :                :     bool        needwal;
                               2385                 :                :     Size        saveFreeSpace;
 4390 rhaas@postgresql.org     2386   [ +  +  +  -  :         365819 :     bool        need_tuple_data = RelationIsLogicallyLogged(relation);
                                     -  +  -  -  -  
                                        -  +  -  +  
                                                 + ]
                               2387   [ +  +  +  -  :         365819 :     bool        need_cids = RelationIsAccessibleInLogicalDecoding(relation);
                                     -  +  -  -  -  
                                     -  +  +  -  +  
                                     -  -  -  -  -  
                                                 - ]
  986 andres@anarazel.de       2388                 :         365819 :     bool        starting_with_empty_page = false;
                               2389                 :         365819 :     int         npages = 0;
                               2390                 :         365819 :     int         npages_used = 0;
                               2391                 :                : 
                               2392                 :                :     /* currently not needed (thus unsupported) for heap_multi_insert() */
 1146 peter@eisentraut.org     2393         [ -  + ]:         365819 :     Assert(!(options & HEAP_INSERT_NO_LOGICAL));
                               2394                 :                : 
  201 nathan@postgresql.or     2395                 :         365819 :     AssertHasSnapshotForToast(relation);
                               2396                 :                : 
 2083 noah@leadboat.com        2397   [ +  +  +  +  :         365819 :     needwal = RelationNeedsWAL(relation);
                                        +  +  +  + ]
  615 akorotkov@postgresql     2398         [ +  + ]:         365819 :     saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
                               2399                 :                :                                                    HEAP_DEFAULT_FILLFACTOR);
                               2400                 :                : 
                               2401                 :                :     /* Toast and set header data in all the slots */
 5152 heikki.linnakangas@i     2402                 :         365819 :     heaptuples = palloc(ntuples * sizeof(HeapTuple));
                               2403         [ +  + ]:        1960358 :     for (i = 0; i < ntuples; i++)
                               2404                 :                :     {
                               2405                 :                :         HeapTuple   tuple;
                               2406                 :                : 
 2449 andres@anarazel.de       2407                 :        1594539 :         tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
                               2408                 :        1594539 :         slots[i]->tts_tableOid = RelationGetRelid(relation);
                               2409                 :        1594539 :         tuple->t_tableOid = slots[i]->tts_tableOid;
                               2410                 :        1594539 :         heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
                               2411                 :                :                                             options);
                               2412                 :                :     }
                               2413                 :                : 
                               2414                 :                :     /*
                               2415                 :                :      * We're about to do the actual inserts -- but check for conflict first,
                               2416                 :                :      * to minimize the possibility of having to roll back work we've just
                               2417                 :                :      * done.
                               2418                 :                :      *
                               2419                 :                :      * A check here does not definitively prevent a serialization anomaly;
                               2420                 :                :      * that check MUST be done at least past the point of acquiring an
                               2421                 :                :      * exclusive buffer content lock on every buffer that will be affected,
                               2422                 :                :      * and MAY be done after all inserts are reflected in the buffers and
                               2423                 :                :      * those locks are released; otherwise there is a race condition.  Since
                               2424                 :                :      * multiple buffers can be locked and unlocked in the loop below, and it
                               2425                 :                :      * would not be feasible to identify and lock all of those buffers before
                               2426                 :                :      * the loop, we must do a final check at the end.
                               2427                 :                :      *
                               2428                 :                :      * The check here could be omitted with no loss of correctness; it is
                               2429                 :                :      * present strictly as an optimization.
                               2430                 :                :      *
                               2431                 :                :      * For heap inserts, we only need to check for table-level SSI locks. Our
                               2432                 :                :      * new tuples can't possibly conflict with existing tuple locks, and heap
                               2433                 :                :      * page locks are only consolidated versions of tuple locks; they do not
                               2434                 :                :      * lock "gaps" as index page locks do.  So we don't need to specify a
                               2435                 :                :      * buffer when making the call, which makes for a faster check.
                               2436                 :                :      */
 2150 tmunro@postgresql.or     2437                 :         365819 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
                               2438                 :                : 
 5152 heikki.linnakangas@i     2439                 :         365819 :     ndone = 0;
                               2440         [ +  + ]:         746906 :     while (ndone < ntuples)
                               2441                 :                :     {
                               2442                 :                :         Buffer      buffer;
                               2443                 :         381087 :         bool        all_visible_cleared = false;
 1795 tomas.vondra@postgre     2444                 :         381087 :         bool        all_frozen_set = false;
                               2445                 :                :         int         nthispage;
                               2446                 :                : 
 4195 rhaas@postgresql.org     2447         [ -  + ]:         381087 :         CHECK_FOR_INTERRUPTS();
                               2448                 :                : 
                               2449                 :                :         /*
                               2450                 :                :          * Compute number of pages needed to fit the to-be-inserted tuples in
                               2451                 :                :          * the worst case.  This will be used to determine how much to extend
                               2452                 :                :          * the relation by in RelationGetBufferForTuple(), if needed.  If we
                               2453                 :                :          * filled a prior page from scratch, we can just update our last
                               2454                 :                :          * computation, but if we started with a partially filled page,
                               2455                 :                :          * recompute from scratch, the number of potentially required pages
                               2456                 :                :          * can vary due to tuples needing to fit onto the page, page headers
                               2457                 :                :          * etc.
                               2458                 :                :          */
  986 andres@anarazel.de       2459   [ +  +  +  + ]:         381087 :         if (ndone == 0 || !starting_with_empty_page)
                               2460                 :                :         {
                               2461                 :         372537 :             npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
                               2462                 :                :                                              saveFreeSpace);
                               2463                 :         372537 :             npages_used = 0;
                               2464                 :                :         }
                               2465                 :                :         else
                               2466                 :           8550 :             npages_used++;
                               2467                 :                : 
                               2468                 :                :         /*
                               2469                 :                :          * Find buffer where at least the next tuple will fit.  If the page is
                               2470                 :                :          * all-visible, this will also pin the requisite visibility map page.
                               2471                 :                :          *
                               2472                 :                :          * Also pin visibility map page if COPY FREEZE inserts tuples into an
                               2473                 :                :          * empty page. See all_frozen_set below.
                               2474                 :                :          */
 5152 heikki.linnakangas@i     2475                 :         381087 :         buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
                               2476                 :                :                                            InvalidBuffer, options, bistate,
                               2477                 :                :                                            &vmbuffer, NULL,
                               2478                 :                :                                            npages - npages_used);
 3528 kgrittn@postgresql.o     2479                 :         381087 :         page = BufferGetPage(buffer);
                               2480                 :                : 
 1795 tomas.vondra@postgre     2481                 :         381087 :         starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
                               2482                 :                : 
                               2483   [ +  +  +  + ]:         381087 :         if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
                               2484                 :                :         {
                               2485                 :           1661 :             all_frozen_set = true;
                               2486                 :                :             /* Lock the vmbuffer before entering the critical section */
   69 melanieplageman@gmai     2487                 :GNC        1661 :             LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
                               2488                 :                :         }
                               2489                 :                : 
                               2490                 :                :         /* NO EREPORT(ERROR) from here till changes are logged */
 5152 heikki.linnakangas@i     2491                 :CBC      381087 :         START_CRIT_SECTION();
                               2492                 :                : 
                               2493                 :                :         /*
                               2494                 :                :          * RelationGetBufferForTuple has ensured that the first tuple fits.
                               2495                 :                :          * Put that on the page, and then as many other tuples as fit.
                               2496                 :                :          */
 3876 andres@anarazel.de       2497                 :         381087 :         RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
                               2498                 :                : 
                               2499                 :                :         /*
                               2500                 :                :          * For logical decoding we need combo CIDs to properly decode the
                               2501                 :                :          * catalog.
                               2502                 :                :          */
 2122 michael@paquier.xyz      2503   [ +  +  +  + ]:         381087 :         if (needwal && need_cids)
                               2504                 :           4852 :             log_heap_new_cid(relation, heaptuples[ndone]);
                               2505                 :                : 
 4753 heikki.linnakangas@i     2506         [ +  + ]:        1594539 :         for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
                               2507                 :                :         {
 5152                          2508                 :        1228720 :             HeapTuple   heaptup = heaptuples[ndone + nthispage];
                               2509                 :                : 
 4963                          2510         [ +  + ]:        1228720 :             if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
 5152                          2511                 :          15268 :                 break;
                               2512                 :                : 
 3876 andres@anarazel.de       2513                 :        1213452 :             RelationPutHeapTuple(relation, buffer, heaptup, false);
                               2514                 :                : 
                               2515                 :                :             /*
                               2516                 :                :              * For logical decoding we need combo CIDs to properly decode the
                               2517                 :                :              * catalog.
                               2518                 :                :              */
 4045 heikki.linnakangas@i     2519   [ +  +  +  + ]:        1213452 :             if (needwal && need_cids)
                               2520                 :           4592 :                 log_heap_new_cid(relation, heaptup);
                               2521                 :                :         }
                               2522                 :                : 
                               2523                 :                :         /*
                               2524                 :                :          * If the page is all visible, need to clear that, unless we're only
                               2525                 :                :          * going to add further frozen rows to it.
                               2526                 :                :          *
                               2527                 :                :          * If we're only adding already frozen rows to a previously empty
                               2528                 :                :          * page, mark it as all-frozen and update the visibility map. We're
                               2529                 :                :          * already holding a pin on the vmbuffer.
                               2530                 :                :          */
 1795 tomas.vondra@postgre     2531   [ +  +  +  + ]:         381087 :         if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
                               2532                 :                :         {
 4941 rhaas@postgresql.org     2533                 :           3448 :             all_visible_cleared = true;
                               2534                 :           3448 :             PageClearAllVisible(page);
                               2535                 :           3448 :             visibilitymap_clear(relation,
                               2536                 :                :                                 BufferGetBlockNumber(buffer),
                               2537                 :                :                                 vmbuffer, VISIBILITYMAP_VALID_BITS);
                               2538                 :                :         }
 1795 tomas.vondra@postgre     2539         [ +  + ]:         377639 :         else if (all_frozen_set)
                               2540                 :                :         {
                               2541                 :           1661 :             PageSetAllVisible(page);
   69 melanieplageman@gmai     2542                 :GNC        1661 :             visibilitymap_set_vmbits(BufferGetBlockNumber(buffer),
                               2543                 :                :                                      vmbuffer,
                               2544                 :                :                                      VISIBILITYMAP_ALL_VISIBLE |
                               2545                 :                :                                      VISIBILITYMAP_ALL_FROZEN,
                               2546                 :                :                                      relation->rd_locator);
                               2547                 :                :         }
                               2548                 :                : 
                               2549                 :                :         /*
                               2550                 :                :          * XXX Should we set PageSetPrunable on this page ? See heap_insert()
                               2551                 :                :          */
                               2552                 :                : 
 5152 heikki.linnakangas@i     2553                 :CBC      381087 :         MarkBufferDirty(buffer);
                               2554                 :                : 
                               2555                 :                :         /* XLOG stuff */
                               2556         [ +  + ]:         381087 :         if (needwal)
                               2557                 :                :         {
                               2558                 :                :             XLogRecPtr  recptr;
                               2559                 :                :             xl_heap_multi_insert *xlrec;
                               2560                 :         376717 :             uint8       info = XLOG_HEAP2_MULTI_INSERT;
                               2561                 :                :             char       *tupledata;
                               2562                 :                :             int         totaldatalen;
 2664 tgl@sss.pgh.pa.us        2563                 :         376717 :             char       *scratchptr = scratch.data;
                               2564                 :                :             bool        init;
 4045 heikki.linnakangas@i     2565                 :         376717 :             int         bufflags = 0;
                               2566                 :                : 
                               2567                 :                :             /*
                               2568                 :                :              * If the page was previously empty, we can reinit the page
                               2569                 :                :              * instead of restoring the whole thing.
                               2570                 :                :              */
 1795 tomas.vondra@postgre     2571                 :         376717 :             init = starting_with_empty_page;
                               2572                 :                : 
                               2573                 :                :             /* allocate xl_heap_multi_insert struct from the scratch area */
 5152 heikki.linnakangas@i     2574                 :         376717 :             xlrec = (xl_heap_multi_insert *) scratchptr;
                               2575                 :         376717 :             scratchptr += SizeOfHeapMultiInsert;
                               2576                 :                : 
                               2577                 :                :             /*
                               2578                 :                :              * Allocate offsets array. Unless we're reinitializing the page,
                               2579                 :                :              * in that case the tuples are stored in order starting at
                               2580                 :                :              * FirstOffsetNumber and we don't need to store the offsets
                               2581                 :                :              * explicitly.
                               2582                 :                :              */
                               2583         [ +  + ]:         376717 :             if (!init)
                               2584                 :         363796 :                 scratchptr += nthispage * sizeof(OffsetNumber);
                               2585                 :                : 
                               2586                 :                :             /* the rest of the scratch space is used for tuple data */
                               2587                 :         376717 :             tupledata = scratchptr;
                               2588                 :                : 
                               2589                 :                :             /* check that the mutually exclusive flags are not both set */
 1680 tgl@sss.pgh.pa.us        2590   [ +  +  -  + ]:         376717 :             Assert(!(all_visible_cleared && all_frozen_set));
                               2591                 :                : 
 1795 tomas.vondra@postgre     2592                 :         376717 :             xlrec->flags = 0;
                               2593         [ +  + ]:         376717 :             if (all_visible_cleared)
                               2594                 :           3448 :                 xlrec->flags = XLH_INSERT_ALL_VISIBLE_CLEARED;
                               2595                 :                : 
                               2596                 :                :             /*
                               2597                 :                :              * We don't have to worry about including a conflict xid in the
                               2598                 :                :              * WAL record, as HEAP_INSERT_FROZEN intentionally violates
                               2599                 :                :              * visibility rules.
                               2600                 :                :              */
                               2601         [ +  + ]:         376717 :             if (all_frozen_set)
                               2602                 :             13 :                 xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
                               2603                 :                : 
 5152 heikki.linnakangas@i     2604                 :         376717 :             xlrec->ntuples = nthispage;
                               2605                 :                : 
                               2606                 :                :             /*
                               2607                 :                :              * Write out an xl_multi_insert_tuple and the tuple data itself
                               2608                 :                :              * for each tuple.
                               2609                 :                :              */
                               2610         [ +  + ]:        1665841 :             for (i = 0; i < nthispage; i++)
                               2611                 :                :             {
                               2612                 :        1289124 :                 HeapTuple   heaptup = heaptuples[ndone + i];
                               2613                 :                :                 xl_multi_insert_tuple *tuphdr;
                               2614                 :                :                 int         datalen;
                               2615                 :                : 
                               2616         [ +  + ]:        1289124 :                 if (!init)
                               2617                 :         763816 :                     xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
                               2618                 :                :                 /* xl_multi_insert_tuple needs two-byte alignment. */
                               2619                 :        1289124 :                 tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
                               2620                 :        1289124 :                 scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
                               2621                 :                : 
                               2622                 :        1289124 :                 tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
                               2623                 :        1289124 :                 tuphdr->t_infomask = heaptup->t_data->t_infomask;
                               2624                 :        1289124 :                 tuphdr->t_hoff = heaptup->t_data->t_hoff;
                               2625                 :                : 
                               2626                 :                :                 /* write bitmap [+ padding] [+ oid] + data */
 3952 tgl@sss.pgh.pa.us        2627                 :        1289124 :                 datalen = heaptup->t_len - SizeofHeapTupleHeader;
 5152 heikki.linnakangas@i     2628                 :        1289124 :                 memcpy(scratchptr,
 3952 tgl@sss.pgh.pa.us        2629                 :        1289124 :                        (char *) heaptup->t_data + SizeofHeapTupleHeader,
                               2630                 :                :                        datalen);
 5152 heikki.linnakangas@i     2631                 :        1289124 :                 tuphdr->datalen = datalen;
                               2632                 :        1289124 :                 scratchptr += datalen;
                               2633                 :                :             }
                               2634                 :         376717 :             totaldatalen = scratchptr - tupledata;
 2664 tgl@sss.pgh.pa.us        2635         [ -  + ]:         376717 :             Assert((scratchptr - scratch.data) < BLCKSZ);
                               2636                 :                : 
 4390 rhaas@postgresql.org     2637         [ +  + ]:         376717 :             if (need_tuple_data)
 3876 andres@anarazel.de       2638                 :             72 :                 xlrec->flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
                               2639                 :                : 
                               2640                 :                :             /*
                               2641                 :                :              * Signal that this is the last xl_heap_multi_insert record
                               2642                 :                :              * emitted by this call to heap_multi_insert(). Needed for logical
                               2643                 :                :              * decoding so it knows when to cleanup temporary data.
                               2644                 :                :              */
 4045 heikki.linnakangas@i     2645         [ +  + ]:         376717 :             if (ndone + nthispage == ntuples)
 3876 andres@anarazel.de       2646                 :         365300 :                 xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
                               2647                 :                : 
 5152 heikki.linnakangas@i     2648         [ +  + ]:         376717 :             if (init)
                               2649                 :                :             {
                               2650                 :          12921 :                 info |= XLOG_HEAP_INIT_PAGE;
 4045                          2651                 :          12921 :                 bufflags |= REGBUF_WILL_INIT;
                               2652                 :                :             }
                               2653                 :                : 
                               2654                 :                :             /*
                               2655                 :                :              * If we're doing logical decoding, include the new tuple data
                               2656                 :                :              * even if we take a full-page image of the page.
                               2657                 :                :              */
                               2658         [ +  + ]:         376717 :             if (need_tuple_data)
                               2659                 :             72 :                 bufflags |= REGBUF_KEEP_DATA;
                               2660                 :                : 
                               2661                 :         376717 :             XLogBeginInsert();
  309 peter@eisentraut.org     2662                 :         376717 :             XLogRegisterData(xlrec, tupledata - scratch.data);
 4045 heikki.linnakangas@i     2663                 :         376717 :             XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
   69 melanieplageman@gmai     2664         [ +  + ]:GNC      376717 :             if (all_frozen_set)
                               2665                 :             13 :                 XLogRegisterBuffer(1, vmbuffer, 0);
                               2666                 :                : 
 4045 heikki.linnakangas@i     2667                 :CBC      376717 :             XLogRegisterBufData(0, tupledata, totaldatalen);
                               2668                 :                : 
                               2669                 :                :             /* filtering by origin on a row level is much more efficient */
 3282 andres@anarazel.de       2670                 :         376717 :             XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               2671                 :                : 
 4045 heikki.linnakangas@i     2672                 :         376717 :             recptr = XLogInsert(RM_HEAP2_ID, info);
                               2673                 :                : 
 5152                          2674                 :         376717 :             PageSetLSN(page, recptr);
   69 melanieplageman@gmai     2675         [ +  + ]:GNC      376717 :             if (all_frozen_set)
                               2676                 :                :             {
                               2677         [ -  + ]:             13 :                 Assert(BufferIsDirty(vmbuffer));
                               2678                 :             13 :                 PageSetLSN(BufferGetPage(vmbuffer), recptr);
                               2679                 :                :             }
                               2680                 :                :         }
                               2681                 :                : 
 5152 heikki.linnakangas@i     2682         [ -  + ]:CBC      381087 :         END_CRIT_SECTION();
                               2683                 :                : 
 1795 tomas.vondra@postgre     2684         [ +  + ]:         381087 :         if (all_frozen_set)
   69 melanieplageman@gmai     2685                 :GNC        1661 :             LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
                               2686                 :                : 
 1795 tomas.vondra@postgre     2687                 :CBC      381087 :         UnlockReleaseBuffer(buffer);
 5152 heikki.linnakangas@i     2688                 :         381087 :         ndone += nthispage;
                               2689                 :                : 
                               2690                 :                :         /*
                               2691                 :                :          * NB: Only release vmbuffer after inserting all tuples - it's fairly
                               2692                 :                :          * likely that we'll insert into subsequent heap pages that are likely
                               2693                 :                :          * to use the same vm page.
                               2694                 :                :          */
                               2695                 :                :     }
                               2696                 :                : 
                               2697                 :                :     /* We're done with inserting all tuples, so release the last vmbuffer. */
 1795 tomas.vondra@postgre     2698         [ +  + ]:         365819 :     if (vmbuffer != InvalidBuffer)
                               2699                 :           3533 :         ReleaseBuffer(vmbuffer);
                               2700                 :                : 
                               2701                 :                :     /*
                               2702                 :                :      * We're done with the actual inserts.  Check for conflicts again, to
                               2703                 :                :      * ensure that all rw-conflicts in to these inserts are detected.  Without
                               2704                 :                :      * this final check, a sequential scan of the heap may have locked the
                               2705                 :                :      * table after the "before" check, missing one opportunity to detect the
                               2706                 :                :      * conflict, and then scanned the table before the new tuples were there,
                               2707                 :                :      * missing the other chance to detect the conflict.
                               2708                 :                :      *
                               2709                 :                :      * For heap inserts, we only need to check for table-level SSI locks. Our
                               2710                 :                :      * new tuples can't possibly conflict with existing tuple locks, and heap
                               2711                 :                :      * page locks are only consolidated versions of tuple locks; they do not
                               2712                 :                :      * lock "gaps" as index page locks do.  So we don't need to specify a
                               2713                 :                :      * buffer when making the call.
                               2714                 :                :      */
 2150 tmunro@postgresql.or     2715                 :         365819 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
                               2716                 :                : 
                               2717                 :                :     /*
                               2718                 :                :      * If tuples are cacheable, mark them for invalidation from the caches in
                               2719                 :                :      * case we abort.  Note it is OK to do this after releasing the buffer,
                               2720                 :                :      * because the heaptuples data structure is all in local memory, not in
                               2721                 :                :      * the shared buffer.
                               2722                 :                :      */
 4402 rhaas@postgresql.org     2723         [ +  + ]:         365819 :     if (IsCatalogRelation(relation))
                               2724                 :                :     {
 5152 heikki.linnakangas@i     2725         [ +  + ]:        1256718 :         for (i = 0; i < ntuples; i++)
                               2726                 :         892215 :             CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
                               2727                 :                :     }
                               2728                 :                : 
                               2729                 :                :     /* copy t_self fields back to the caller's slots */
 5056                          2730         [ +  + ]:        1960358 :     for (i = 0; i < ntuples; i++)
 2449 andres@anarazel.de       2731                 :        1594539 :         slots[i]->tts_tid = heaptuples[i]->t_self;
                               2732                 :                : 
 5152 heikki.linnakangas@i     2733                 :         365819 :     pgstat_count_heap_insert(relation, ntuples);
                               2734                 :         365819 : }
                               2735                 :                : 
                               2736                 :                : /*
                               2737                 :                :  *  simple_heap_insert - insert a tuple
                               2738                 :                :  *
                               2739                 :                :  * Currently, this routine differs from heap_insert only in supplying
                               2740                 :                :  * a default command ID and not allowing access to the speedup options.
                               2741                 :                :  *
                               2742                 :                :  * This should be used rather than using heap_insert directly in most places
                               2743                 :                :  * where we are modifying system catalogs.
                               2744                 :                :  */
                               2745                 :                : void
 8611 tgl@sss.pgh.pa.us        2746                 :         953133 : simple_heap_insert(Relation relation, HeapTuple tup)
                               2747                 :                : {
 2584 andres@anarazel.de       2748                 :         953133 :     heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
 8611 tgl@sss.pgh.pa.us        2749                 :         953133 : }
                               2750                 :                : 
                               2751                 :                : /*
                               2752                 :                :  * Given infomask/infomask2, compute the bits that must be saved in the
                               2753                 :                :  * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
                               2754                 :                :  * xl_heap_lock_updated WAL records.
                               2755                 :                :  *
                               2756                 :                :  * See fix_infomask_from_infobits.
                               2757                 :                :  */
                               2758                 :                : static uint8
 4711 alvherre@alvh.no-ip.     2759                 :        1992823 : compute_infobits(uint16 infomask, uint16 infomask2)
                               2760                 :                : {
                               2761                 :                :     return
                               2762                 :        1992823 :         ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
                               2763                 :        1992823 :         ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
                               2764                 :        1992823 :         ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
                               2765                 :                :     /* note we ignore HEAP_XMAX_SHR_LOCK here */
                               2766                 :        3985646 :         ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
                               2767                 :                :         ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
                               2768                 :        1992823 :          XLHL_KEYS_UPDATED : 0);
                               2769                 :                : }
                               2770                 :                : 
                               2771                 :                : /*
                               2772                 :                :  * Given two versions of the same t_infomask for a tuple, compare them and
                               2773                 :                :  * return whether the relevant status for a tuple Xmax has changed.  This is
                               2774                 :                :  * used after a buffer lock has been released and reacquired: we want to ensure
                               2775                 :                :  * that the tuple state continues to be the same it was when we previously
                               2776                 :                :  * examined it.
                               2777                 :                :  *
                               2778                 :                :  * Note the Xmax field itself must be compared separately.
                               2779                 :                :  */
                               2780                 :                : static inline bool
 4255                          2781                 :           5376 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
                               2782                 :                : {
 4243 bruce@momjian.us         2783                 :           5376 :     const uint16 interesting =
                               2784                 :                :         HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
                               2785                 :                : 
 4255 alvherre@alvh.no-ip.     2786         [ +  + ]:           5376 :     if ((new_infomask & interesting) != (old_infomask & interesting))
                               2787                 :             12 :         return true;
                               2788                 :                : 
                               2789                 :           5364 :     return false;
                               2790                 :                : }
                               2791                 :                : 
                               2792                 :                : /*
                               2793                 :                :  *  heap_delete - delete a tuple
                               2794                 :                :  *
                               2795                 :                :  * See table_tuple_delete() for an explanation of the parameters, except that
                               2796                 :                :  * this routine directly takes a tuple rather than a slot.
                               2797                 :                :  *
                               2798                 :                :  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
                               2799                 :                :  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
                               2800                 :                :  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
                               2801                 :                :  * generated by another transaction).
                               2802                 :                :  */
                               2803                 :                : TM_Result
   48 peter@eisentraut.org     2804                 :GNC     1454502 : heap_delete(Relation relation, const ItemPointerData *tid,
                               2805                 :                :             CommandId cid, Snapshot crosscheck, bool wait,
                               2806                 :                :             TM_FailureData *tmfd, bool changingPart)
                               2807                 :                : {
                               2808                 :                :     TM_Result   result;
 7762 tgl@sss.pgh.pa.us        2809                 :CBC     1454502 :     TransactionId xid = GetCurrentTransactionId();
                               2810                 :                :     ItemId      lp;
                               2811                 :                :     HeapTupleData tp;
                               2812                 :                :     Page        page;
                               2813                 :                :     BlockNumber block;
                               2814                 :                :     Buffer      buffer;
 5293 rhaas@postgresql.org     2815                 :        1454502 :     Buffer      vmbuffer = InvalidBuffer;
                               2816                 :                :     TransactionId new_xmax;
                               2817                 :                :     uint16      new_infomask,
                               2818                 :                :                 new_infomask2;
 7536 tgl@sss.pgh.pa.us        2819                 :        1454502 :     bool        have_tuple_lock = false;
                               2820                 :                :     bool        iscombo;
 6223 heikki.linnakangas@i     2821                 :        1454502 :     bool        all_visible_cleared = false;
 4243 bruce@momjian.us         2822                 :        1454502 :     HeapTuple   old_key_tuple = NULL;   /* replica identity of the tuple */
 4390 rhaas@postgresql.org     2823                 :        1454502 :     bool        old_key_copied = false;
                               2824                 :                : 
10328 bruce@momjian.us         2825         [ -  + ]:        1454502 :     Assert(ItemPointerIsValid(tid));
                               2826                 :                : 
  201 nathan@postgresql.or     2827                 :        1454502 :     AssertHasSnapshotForToast(relation);
                               2828                 :                : 
                               2829                 :                :     /*
                               2830                 :                :      * Forbid this during a parallel operation, lest it allocate a combo CID.
                               2831                 :                :      * Other workers might need that combo CID for visibility checks, and we
                               2832                 :                :      * have no provision for broadcasting it to them.
                               2833                 :                :      */
 3884 rhaas@postgresql.org     2834         [ -  + ]:        1454502 :     if (IsInParallelMode())
 3884 rhaas@postgresql.org     2835         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2836                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               2837                 :                :                  errmsg("cannot delete tuples during a parallel operation")));
                               2838                 :                : 
 5293 rhaas@postgresql.org     2839                 :CBC     1454502 :     block = ItemPointerGetBlockNumber(tid);
                               2840                 :        1454502 :     buffer = ReadBuffer(relation, block);
 3528 kgrittn@postgresql.o     2841                 :        1454502 :     page = BufferGetPage(buffer);
                               2842                 :                : 
                               2843                 :                :     /*
                               2844                 :                :      * Before locking the buffer, pin the visibility map page if it appears to
                               2845                 :                :      * be necessary.  Since we haven't got the lock yet, someone else might be
                               2846                 :                :      * in the middle of changing this, so we'll need to recheck after we have
                               2847                 :                :      * the lock.
                               2848                 :                :      */
 5293 rhaas@postgresql.org     2849         [ +  + ]:        1454502 :     if (PageIsAllVisible(page))
                               2850                 :            355 :         visibilitymap_pin(relation, block, &vmbuffer);
                               2851                 :                : 
 9864 vadim4o@yahoo.com        2852                 :        1454502 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2853                 :                : 
 1182 jdavis@postgresql.or     2854                 :        1454502 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
                               2855         [ -  + ]:        1454502 :     Assert(ItemIdIsNormal(lp));
                               2856                 :                : 
                               2857                 :        1454502 :     tp.t_tableOid = RelationGetRelid(relation);
                               2858                 :        1454502 :     tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
                               2859                 :        1454502 :     tp.t_len = ItemIdGetLength(lp);
                               2860                 :        1454502 :     tp.t_self = *tid;
                               2861                 :                : 
                               2862                 :              1 : l1:
                               2863                 :                : 
                               2864                 :                :     /*
                               2865                 :                :      * If we didn't pin the visibility map page and the page has become all
                               2866                 :                :      * visible while we were busy locking the buffer, we'll have to unlock and
                               2867                 :                :      * re-lock, to avoid holding the buffer lock across an I/O.  That's a bit
                               2868                 :                :      * unfortunate, but hopefully shouldn't happen often.
                               2869                 :                :      */
 5293 rhaas@postgresql.org     2870   [ +  +  -  + ]:        1454503 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
                               2871                 :                :     {
 5293 rhaas@postgresql.org     2872                 :UBC           0 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               2873                 :              0 :         visibilitymap_pin(relation, block, &vmbuffer);
                               2874                 :              0 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2875                 :                :     }
                               2876                 :                : 
 4531 rhaas@postgresql.org     2877                 :CBC     1454503 :     result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
                               2878                 :                : 
 2461 andres@anarazel.de       2879         [ -  + ]:        1454503 :     if (result == TM_Invisible)
                               2880                 :                :     {
 7201 tgl@sss.pgh.pa.us        2881                 :UBC           0 :         UnlockReleaseBuffer(buffer);
 3790                          2882         [ #  # ]:              0 :         ereport(ERROR,
                               2883                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               2884                 :                :                  errmsg("attempted to delete invisible tuple")));
                               2885                 :                :     }
  615 akorotkov@postgresql     2886   [ +  +  +  - ]:CBC     1454503 :     else if (result == TM_BeingModified && wait)
                               2887                 :                :     {
                               2888                 :                :         TransactionId xwait;
                               2889                 :                :         uint16      infomask;
                               2890                 :                : 
                               2891                 :                :         /* must copy state data before unlocking buffer */
 4711 alvherre@alvh.no-ip.     2892                 :          40559 :         xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
 7536 tgl@sss.pgh.pa.us        2893                 :          40559 :         infomask = tp.t_data->t_infomask;
                               2894                 :                : 
                               2895                 :                :         /*
                               2896                 :                :          * Sleep until concurrent transaction ends -- except when there's a
                               2897                 :                :          * single locker and it's our own transaction.  Note we don't care
                               2898                 :                :          * which lock mode the locker has, because we need the strongest one.
                               2899                 :                :          *
                               2900                 :                :          * Before sleeping, we need to acquire tuple lock to establish our
                               2901                 :                :          * priority for the tuple (see heap_lock_tuple).  LockTuple will
                               2902                 :                :          * release us when we are next-in-line for the tuple.
                               2903                 :                :          *
                               2904                 :                :          * If we are forced to "start over" below, we keep the tuple lock;
                               2905                 :                :          * this arranges that we stay at the head of the line while rechecking
                               2906                 :                :          * tuple state.
                               2907                 :                :          */
 7538                          2908         [ +  + ]:          40559 :         if (infomask & HEAP_XMAX_IS_MULTI)
                               2909                 :                :         {
 2374 alvherre@alvh.no-ip.     2910                 :              8 :             bool        current_is_member = false;
                               2911                 :                : 
 3904                          2912         [ +  - ]:              8 :             if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
                               2913                 :                :                                         LockTupleExclusive, &current_is_member))
                               2914                 :                :             {
                               2915                 :              8 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               2916                 :                : 
                               2917                 :                :                 /*
                               2918                 :                :                  * Acquire the lock, if necessary (but skip it when we're
                               2919                 :                :                  * requesting a lock and already have one; avoids deadlock).
                               2920                 :                :                  */
 2374                          2921         [ +  + ]:              8 :                 if (!current_is_member)
                               2922                 :              6 :                     heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
                               2923                 :                :                                          LockWaitBlock, &have_tuple_lock);
                               2924                 :                : 
                               2925                 :                :                 /* wait for multixact */
 3904                          2926                 :              8 :                 MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
                               2927                 :                :                                 relation, &(tp.t_self), XLTW_Delete,
                               2928                 :                :                                 NULL);
                               2929                 :              8 :                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2930                 :                : 
                               2931                 :                :                 /*
                               2932                 :                :                  * If xwait had just locked the tuple then some other xact
                               2933                 :                :                  * could update this tuple before we get to this point.  Check
                               2934                 :                :                  * for xmax change, and start over if so.
                               2935                 :                :                  *
                               2936                 :                :                  * We also must start over if we didn't pin the VM page, and
                               2937                 :                :                  * the page has become all visible.
                               2938                 :                :                  */
 1182 jdavis@postgresql.or     2939   [ +  -  +  -  :             16 :                 if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
                                              +  - ]
                               2940         [ -  + ]:             16 :                     xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
 3904 alvherre@alvh.no-ip.     2941                 :              8 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
                               2942                 :                :                                          xwait))
 3904 alvherre@alvh.no-ip.     2943                 :UBC           0 :                     goto l1;
                               2944                 :                :             }
                               2945                 :                : 
                               2946                 :                :             /*
                               2947                 :                :              * You might think the multixact is necessarily done here, but not
                               2948                 :                :              * so: it could have surviving members, namely our own xact or
                               2949                 :                :              * other subxacts of this backend.  It is legal for us to delete
                               2950                 :                :              * the tuple in either case, however (the latter case is
                               2951                 :                :              * essentially a situation of upgrading our former shared lock to
                               2952                 :                :              * exclusive).  We don't bother changing the on-disk hint bits
                               2953                 :                :              * since we are about to overwrite the xmax altogether.
                               2954                 :                :              */
                               2955                 :                :         }
 3904 alvherre@alvh.no-ip.     2956         [ +  + ]:CBC       40551 :         else if (!TransactionIdIsCurrentTransactionId(xwait))
                               2957                 :                :         {
                               2958                 :                :             /*
                               2959                 :                :              * Wait for regular transaction to end; but first, acquire tuple
                               2960                 :                :              * lock.
                               2961                 :                :              */
                               2962                 :             52 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               2963                 :             52 :             heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
                               2964                 :                :                                  LockWaitBlock, &have_tuple_lock);
 3969 heikki.linnakangas@i     2965                 :             52 :             XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
 7538 tgl@sss.pgh.pa.us        2966                 :             48 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2967                 :                : 
                               2968                 :                :             /*
                               2969                 :                :              * xwait is done, but if xwait had just locked the tuple then some
                               2970                 :                :              * other xact could update this tuple before we get to this point.
                               2971                 :                :              * Check for xmax change, and start over if so.
                               2972                 :                :              *
                               2973                 :                :              * We also must start over if we didn't pin the VM page, and the
                               2974                 :                :              * page has become all visible.
                               2975                 :                :              */
 1182 jdavis@postgresql.or     2976   [ +  -  +  -  :             96 :             if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
                                              +  + ]
                               2977         [ -  + ]:             95 :                 xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
 4711 alvherre@alvh.no-ip.     2978                 :             47 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
                               2979                 :                :                                      xwait))
 7538 tgl@sss.pgh.pa.us        2980                 :              1 :                 goto l1;
                               2981                 :                : 
                               2982                 :                :             /* Otherwise check if it committed or aborted */
 6700                          2983                 :             47 :             UpdateXmaxHintBits(tp.t_data, buffer, xwait);
                               2984                 :                :         }
                               2985                 :                : 
                               2986                 :                :         /*
                               2987                 :                :          * We may overwrite if previous xmax aborted, or if it committed but
                               2988                 :                :          * only locked the tuple without updating it.
                               2989                 :                :          */
 4711 alvherre@alvh.no-ip.     2990   [ +  +  +  + ]:          81088 :         if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
                               2991         [ +  + ]:          40565 :             HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
                               2992                 :             31 :             HeapTupleHeaderIsOnlyLocked(tp.t_data))
 2461 andres@anarazel.de       2993                 :          40527 :             result = TM_Ok;
 1759 alvherre@alvh.no-ip.     2994         [ +  + ]:             27 :         else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
 2461 andres@anarazel.de       2995                 :             23 :             result = TM_Updated;
                               2996                 :                :         else
                               2997                 :              4 :             result = TM_Deleted;
                               2998                 :                :     }
                               2999                 :                : 
                               3000                 :                :     /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
                               3001         [ +  + ]:        1454498 :     if (result != TM_Ok)
                               3002                 :                :     {
                               3003   [ +  +  +  +  :             61 :         Assert(result == TM_SelfModified ||
                                        -  +  -  - ]
                               3004                 :                :                result == TM_Updated ||
                               3005                 :                :                result == TM_Deleted ||
                               3006                 :                :                result == TM_BeingModified);
 7424 tgl@sss.pgh.pa.us        3007         [ -  + ]:             61 :         Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
 2461 andres@anarazel.de       3008   [ +  +  -  + ]:             61 :         Assert(result != TM_Updated ||
                               3009                 :                :                !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
                               3010                 :                :     }
                               3011                 :                : 
  750 heikki.linnakangas@i     3012   [ +  +  +  - ]:        1454498 :     if (crosscheck != InvalidSnapshot && result == TM_Ok)
                               3013                 :                :     {
                               3014                 :                :         /* Perform additional check for transaction-snapshot mode RI updates */
                               3015         [ +  - ]:              1 :         if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
                               3016                 :              1 :             result = TM_Updated;
                               3017                 :                :     }
                               3018                 :                : 
                               3019         [ +  + ]:        1454498 :     if (result != TM_Ok)
                               3020                 :                :     {
 2461 andres@anarazel.de       3021                 :             62 :         tmfd->ctid = tp.t_data->t_ctid;
                               3022                 :             62 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
                               3023         [ +  + ]:             62 :         if (result == TM_SelfModified)
                               3024                 :             21 :             tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
                               3025                 :                :         else
                               3026                 :             41 :             tmfd->cmax = InvalidCommandId;
  615 akorotkov@postgresql     3027                 :             62 :         UnlockReleaseBuffer(buffer);
 7536 tgl@sss.pgh.pa.us        3028         [ +  + ]:             62 :         if (have_tuple_lock)
 4711 alvherre@alvh.no-ip.     3029                 :             27 :             UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
 5293 rhaas@postgresql.org     3030         [ -  + ]:             62 :         if (vmbuffer != InvalidBuffer)
 5293 rhaas@postgresql.org     3031                 :UBC           0 :             ReleaseBuffer(vmbuffer);
 9864 vadim4o@yahoo.com        3032                 :CBC          62 :         return result;
                               3033                 :                :     }
                               3034                 :                : 
                               3035                 :                :     /*
                               3036                 :                :      * We're about to do the actual delete -- check for conflict first, to
                               3037                 :                :      * avoid possibly having to roll back work we've just done.
                               3038                 :                :      *
                               3039                 :                :      * This is safe without a recheck as long as there is no possibility of
                               3040                 :                :      * another process scanning the page between this check and the delete
                               3041                 :                :      * being visible to the scan (i.e., an exclusive buffer content lock is
                               3042                 :                :      * continuously held from this point until the tuple delete is visible).
                               3043                 :                :      */
 2150 tmunro@postgresql.or     3044                 :        1454436 :     CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
                               3045                 :                : 
                               3046                 :                :     /* replace cid with a combo CID if necessary */
 6886 tgl@sss.pgh.pa.us        3047                 :        1454422 :     HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
                               3048                 :                : 
                               3049                 :                :     /*
                               3050                 :                :      * Compute replica identity tuple before entering the critical section so
                               3051                 :                :      * we don't PANIC upon a memory allocation failure.
                               3052                 :                :      */
 4390 rhaas@postgresql.org     3053                 :        1454422 :     old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
                               3054                 :                : 
                               3055                 :                :     /*
                               3056                 :                :      * If this is the first possibly-multixact-able operation in the current
                               3057                 :                :      * transaction, set my per-backend OldestMemberMXactId setting. We can be
                               3058                 :                :      * certain that the transaction will never become a member of any older
                               3059                 :                :      * MultiXactIds than that.  (We have to do this even if we end up just
                               3060                 :                :      * using our own TransactionId below, since some other backend could
                               3061                 :                :      * incorporate our XID into a MultiXact immediately afterwards.)
                               3062                 :                :      */
 4275 heikki.linnakangas@i     3063                 :        1454422 :     MultiXactIdSetOldestMember();
                               3064                 :                : 
                               3065                 :        1454422 :     compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
                               3066                 :        1454422 :                               tp.t_data->t_infomask, tp.t_data->t_infomask2,
                               3067                 :                :                               xid, LockTupleExclusive, true,
                               3068                 :                :                               &new_xmax, &new_infomask, &new_infomask2);
                               3069                 :                : 
 9105 tgl@sss.pgh.pa.us        3070                 :        1454422 :     START_CRIT_SECTION();
                               3071                 :                : 
                               3072                 :                :     /*
                               3073                 :                :      * If this transaction commits, the tuple will become DEAD sooner or
                               3074                 :                :      * later.  Set flag that this page is a candidate for pruning once our xid
                               3075                 :                :      * falls below the OldestXmin horizon.  If the transaction finally aborts,
                               3076                 :                :      * the subsequent page pruning will be a no-op and the hint will be
                               3077                 :                :      * cleared.
                               3078                 :                :      */
 6366                          3079   [ -  +  +  +  :        1454422 :     PageSetPrunable(page, xid);
                                              +  + ]
                               3080                 :                : 
 6223 heikki.linnakangas@i     3081         [ +  + ]:        1454422 :     if (PageIsAllVisible(page))
                               3082                 :                :     {
                               3083                 :            355 :         all_visible_cleared = true;
                               3084                 :            355 :         PageClearAllVisible(page);
 5293 rhaas@postgresql.org     3085                 :            355 :         visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
                               3086                 :                :                             vmbuffer, VISIBILITYMAP_VALID_BITS);
                               3087                 :                :     }
                               3088                 :                : 
                               3089                 :                :     /* store transaction information of xact deleting the tuple */
 4711 alvherre@alvh.no-ip.     3090                 :        1454422 :     tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               3091                 :        1454422 :     tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               3092                 :        1454422 :     tp.t_data->t_infomask |= new_infomask;
                               3093                 :        1454422 :     tp.t_data->t_infomask2 |= new_infomask2;
 6663 tgl@sss.pgh.pa.us        3094                 :        1454422 :     HeapTupleHeaderClearHotUpdated(tp.t_data);
 4711 alvherre@alvh.no-ip.     3095                 :        1454422 :     HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
 6886 tgl@sss.pgh.pa.us        3096                 :        1454422 :     HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
                               3097                 :                :     /* Make sure there is no forward chain link in t_ctid */
 8527                          3098                 :        1454422 :     tp.t_data->t_ctid = tp.t_self;
                               3099                 :                : 
                               3100                 :                :     /* Signal that this is actually a move into another partition */
 2811 andres@anarazel.de       3101         [ +  + ]:        1454422 :     if (changingPart)
                               3102                 :            492 :         HeapTupleHeaderSetMovedPartitions(tp.t_data);
                               3103                 :                : 
 7201 tgl@sss.pgh.pa.us        3104                 :        1454422 :     MarkBufferDirty(buffer);
                               3105                 :                : 
                               3106                 :                :     /*
                               3107                 :                :      * XLOG stuff
                               3108                 :                :      *
                               3109                 :                :      * NB: heap_abort_speculative() uses the same xlog record and replay
                               3110                 :                :      * routines.
                               3111                 :                :      */
 5483 rhaas@postgresql.org     3112   [ +  +  +  +  :        1454422 :     if (RelationNeedsWAL(relation))
                                        +  +  +  + ]
                               3113                 :                :     {
                               3114                 :                :         xl_heap_delete xlrec;
                               3115                 :                :         xl_heap_header xlhdr;
                               3116                 :                :         XLogRecPtr  recptr;
                               3117                 :                : 
                               3118                 :                :         /*
                               3119                 :                :          * For logical decode we need combo CIDs to properly decode the
                               3120                 :                :          * catalog
                               3121                 :                :          */
 4390                          3122   [ +  +  +  -  :        1391803 :         if (RelationIsAccessibleInLogicalDecoding(relation))
                                     -  +  -  -  -  
                                     -  +  +  -  +  
                                     -  -  -  -  -  
                                                 - ]
                               3123                 :           6161 :             log_heap_new_cid(relation, &tp);
                               3124                 :                : 
 2811 andres@anarazel.de       3125                 :        1391803 :         xlrec.flags = 0;
                               3126         [ +  + ]:        1391803 :         if (all_visible_cleared)
                               3127                 :            355 :             xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
                               3128         [ +  + ]:        1391803 :         if (changingPart)
                               3129                 :            492 :             xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
 4711 alvherre@alvh.no-ip.     3130                 :        2783606 :         xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
                               3131                 :        1391803 :                                               tp.t_data->t_infomask2);
 4045 heikki.linnakangas@i     3132                 :        1391803 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
 4711 alvherre@alvh.no-ip.     3133                 :        1391803 :         xlrec.xmax = new_xmax;
                               3134                 :                : 
 4045 heikki.linnakangas@i     3135         [ +  + ]:        1391803 :         if (old_key_tuple != NULL)
                               3136                 :                :         {
                               3137         [ +  + ]:          47017 :             if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
 3876 andres@anarazel.de       3138                 :            130 :                 xlrec.flags |= XLH_DELETE_CONTAINS_OLD_TUPLE;
                               3139                 :                :             else
                               3140                 :          46887 :                 xlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;
                               3141                 :                :         }
                               3142                 :                : 
 4045 heikki.linnakangas@i     3143                 :        1391803 :         XLogBeginInsert();
  309 peter@eisentraut.org     3144                 :        1391803 :         XLogRegisterData(&xlrec, SizeOfHeapDelete);
                               3145                 :                : 
 4045 heikki.linnakangas@i     3146                 :        1391803 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               3147                 :                : 
                               3148                 :                :         /*
                               3149                 :                :          * Log replica identity of the deleted tuple if there is one
                               3150                 :                :          */
 4390 rhaas@postgresql.org     3151         [ +  + ]:        1391803 :         if (old_key_tuple != NULL)
                               3152                 :                :         {
                               3153                 :          47017 :             xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
                               3154                 :          47017 :             xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
                               3155                 :          47017 :             xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
                               3156                 :                : 
  309 peter@eisentraut.org     3157                 :          47017 :             XLogRegisterData(&xlhdr, SizeOfHeapHeader);
 4045 heikki.linnakangas@i     3158                 :          47017 :             XLogRegisterData((char *) old_key_tuple->t_data
                               3159                 :                :                              + SizeofHeapTupleHeader,
                               3160                 :          47017 :                              old_key_tuple->t_len
                               3161                 :                :                              - SizeofHeapTupleHeader);
                               3162                 :                :         }
                               3163                 :                : 
                               3164                 :                :         /* filtering by origin on a row level is much more efficient */
 3282 andres@anarazel.de       3165                 :        1391803 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               3166                 :                : 
 4045 heikki.linnakangas@i     3167                 :        1391803 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
                               3168                 :                : 
 6366 tgl@sss.pgh.pa.us        3169                 :        1391803 :         PageSetLSN(page, recptr);
                               3170                 :                :     }
                               3171                 :                : 
 9105                          3172         [ -  + ]:        1454422 :     END_CRIT_SECTION();
                               3173                 :                : 
 9102                          3174                 :        1454422 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               3175                 :                : 
 5293 rhaas@postgresql.org     3176         [ +  + ]:        1454422 :     if (vmbuffer != InvalidBuffer)
                               3177                 :            355 :         ReleaseBuffer(vmbuffer);
                               3178                 :                : 
                               3179                 :                :     /*
                               3180                 :                :      * If the tuple has toasted out-of-line attributes, we need to delete
                               3181                 :                :      * those items too.  We have to do this before releasing the buffer
                               3182                 :                :      * because we need to look at the contents of the tuple, but it's OK to
                               3183                 :                :      * release the content lock on the buffer first.
                               3184                 :                :      */
 4672 kgrittn@postgresql.o     3185         [ +  + ]:        1454422 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
                               3186         [ +  + ]:           2602 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
                               3187                 :                :     {
                               3188                 :                :         /* toast table entries should never be recursively toasted */
 6833 tgl@sss.pgh.pa.us        3189         [ -  + ]:           2592 :         Assert(!HeapTupleHasExternal(&tp));
                               3190                 :                :     }
                               3191         [ +  + ]:        1451830 :     else if (HeapTupleHasExternal(&tp))
 2266 rhaas@postgresql.org     3192                 :            299 :         heap_toast_delete(relation, &tp, false);
                               3193                 :                : 
                               3194                 :                :     /*
                               3195                 :                :      * Mark tuple for invalidation from system caches at next command
                               3196                 :                :      * boundary. We have to do this before releasing the buffer because we
                               3197                 :                :      * need to look at the contents of the tuple.
                               3198                 :                :      */
 5237 tgl@sss.pgh.pa.us        3199                 :        1454422 :     CacheInvalidateHeapTuple(relation, &tp, NULL);
                               3200                 :                : 
                               3201                 :                :     /* Now we can release the buffer */
  615 akorotkov@postgresql     3202                 :        1454422 :     ReleaseBuffer(buffer);
                               3203                 :                : 
                               3204                 :                :     /*
                               3205                 :                :      * Release the lmgr tuple lock, if we had it.
                               3206                 :                :      */
 7536 tgl@sss.pgh.pa.us        3207         [ +  + ]:        1454422 :     if (have_tuple_lock)
 4711 alvherre@alvh.no-ip.     3208                 :             26 :         UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
                               3209                 :                : 
 6779 tgl@sss.pgh.pa.us        3210                 :        1454422 :     pgstat_count_heap_delete(relation);
                               3211                 :                : 
 4390 rhaas@postgresql.org     3212   [ +  +  +  + ]:        1454422 :     if (old_key_tuple != NULL && old_key_copied)
                               3213                 :          46888 :         heap_freetuple(old_key_tuple);
                               3214                 :                : 
 2461 andres@anarazel.de       3215                 :        1454422 :     return TM_Ok;
                               3216                 :                : }
                               3217                 :                : 
                               3218                 :                : /*
                               3219                 :                :  *  simple_heap_delete - delete a tuple
                               3220                 :                :  *
                               3221                 :                :  * This routine may be used to delete a tuple when concurrent updates of
                               3222                 :                :  * the target tuple are not expected (for example, because we have a lock
                               3223                 :                :  * on the relation associated with the tuple).  Any failure is reported
                               3224                 :                :  * via ereport().
                               3225                 :                :  */
                               3226                 :                : void
   48 peter@eisentraut.org     3227                 :GNC      645029 : simple_heap_delete(Relation relation, const ItemPointerData *tid)
                               3228                 :                : {
                               3229                 :                :     TM_Result   result;
                               3230                 :                :     TM_FailureData tmfd;
                               3231                 :                : 
 8129 tgl@sss.pgh.pa.us        3232                 :CBC      645029 :     result = heap_delete(relation, tid,
                               3233                 :                :                          GetCurrentCommandId(true), InvalidSnapshot,
                               3234                 :                :                          true /* wait for commit */ ,
                               3235                 :                :                          &tmfd, false /* changingPart */ );
 9094                          3236   [ -  +  -  -  :         645029 :     switch (result)
                                                 - ]
                               3237                 :                :     {
 2461 andres@anarazel.de       3238                 :UBC           0 :         case TM_SelfModified:
                               3239                 :                :             /* Tuple was already updated in current command? */
 8185 tgl@sss.pgh.pa.us        3240         [ #  # ]:              0 :             elog(ERROR, "tuple already updated by self");
                               3241                 :                :             break;
                               3242                 :                : 
 2461 andres@anarazel.de       3243                 :CBC      645029 :         case TM_Ok:
                               3244                 :                :             /* done successfully */
 9094 tgl@sss.pgh.pa.us        3245                 :         645029 :             break;
                               3246                 :                : 
 2461 andres@anarazel.de       3247                 :UBC           0 :         case TM_Updated:
 8185 tgl@sss.pgh.pa.us        3248         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently updated");
                               3249                 :                :             break;
                               3250                 :                : 
 2461 andres@anarazel.de       3251                 :              0 :         case TM_Deleted:
                               3252         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently deleted");
                               3253                 :                :             break;
                               3254                 :                : 
 9094 tgl@sss.pgh.pa.us        3255                 :              0 :         default:
 8185                          3256         [ #  # ]:              0 :             elog(ERROR, "unrecognized heap_delete status: %u", result);
                               3257                 :                :             break;
                               3258                 :                :     }
 9094 tgl@sss.pgh.pa.us        3259                 :CBC      645029 : }
                               3260                 :                : 
                               3261                 :                : /*
                               3262                 :                :  *  heap_update - replace a tuple
                               3263                 :                :  *
                               3264                 :                :  * See table_tuple_update() for an explanation of the parameters, except that
                               3265                 :                :  * this routine directly takes a tuple rather than a slot.
                               3266                 :                :  *
                               3267                 :                :  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
                               3268                 :                :  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
                               3269                 :                :  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
                               3270                 :                :  * generated by another transaction).
                               3271                 :                :  */
                               3272                 :                : TM_Result
   48 peter@eisentraut.org     3273                 :GNC      312128 : heap_update(Relation relation, const ItemPointerData *otid, HeapTuple newtup,
                               3274                 :                :             CommandId cid, Snapshot crosscheck, bool wait,
                               3275                 :                :             TM_FailureData *tmfd, LockTupleMode *lockmode,
                               3276                 :                :             TU_UpdateIndexes *update_indexes)
                               3277                 :                : {
                               3278                 :                :     TM_Result   result;
 7762 tgl@sss.pgh.pa.us        3279                 :CBC      312128 :     TransactionId xid = GetCurrentTransactionId();
                               3280                 :                :     Bitmapset  *hot_attrs;
                               3281                 :                :     Bitmapset  *sum_attrs;
                               3282                 :                :     Bitmapset  *key_attrs;
                               3283                 :                :     Bitmapset  *id_attrs;
                               3284                 :                :     Bitmapset  *interesting_attrs;
                               3285                 :                :     Bitmapset  *modified_attrs;
                               3286                 :                :     ItemId      lp;
                               3287                 :                :     HeapTupleData oldtup;
                               3288                 :                :     HeapTuple   heaptup;
 4390 rhaas@postgresql.org     3289                 :         312128 :     HeapTuple   old_key_tuple = NULL;
                               3290                 :         312128 :     bool        old_key_copied = false;
                               3291                 :                :     Page        page;
                               3292                 :                :     BlockNumber block;
                               3293                 :                :     MultiXactStatus mxact_status;
                               3294                 :                :     Buffer      buffer,
                               3295                 :                :                 newbuf,
 5293                          3296                 :         312128 :                 vmbuffer = InvalidBuffer,
                               3297                 :         312128 :                 vmbuffer_new = InvalidBuffer;
                               3298                 :                :     bool        need_toast;
                               3299                 :                :     Size        newtupsize,
                               3300                 :                :                 pagefree;
 7536 tgl@sss.pgh.pa.us        3301                 :         312128 :     bool        have_tuple_lock = false;
                               3302                 :                :     bool        iscombo;
 6663                          3303                 :         312128 :     bool        use_hot_update = false;
 1003 tomas.vondra@postgre     3304                 :         312128 :     bool        summarized_update = false;
                               3305                 :                :     bool        key_intact;
 6223 heikki.linnakangas@i     3306                 :         312128 :     bool        all_visible_cleared = false;
                               3307                 :         312128 :     bool        all_visible_cleared_new = false;
                               3308                 :                :     bool        checked_lockers;
                               3309                 :                :     bool        locker_remains;
 1402 akapila@postgresql.o     3310                 :         312128 :     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                 :                : 
10328 bruce@momjian.us         3318         [ -  + ]:         312128 :     Assert(ItemPointerIsValid(otid));
                               3319                 :                : 
                               3320                 :                :     /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
 1682 tgl@sss.pgh.pa.us        3321         [ -  + ]:         312128 :     Assert(HeapTupleHeaderGetNatts(newtup->t_data) <=
                               3322                 :                :            RelationGetNumberOfAttributes(relation));
                               3323                 :                : 
  201 nathan@postgresql.or     3324                 :         312128 :     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                 :                :      */
 3884 rhaas@postgresql.org     3331         [ -  + ]:         312128 :     if (IsInParallelMode())
 3884 rhaas@postgresql.org     3332         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3333                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               3334                 :                :                  errmsg("cannot update tuples during a parallel operation")));
                               3335                 :                : 
                               3336                 :                : #ifdef USE_ASSERT_CHECKING
  449 noah@leadboat.com        3337                 :CBC      312128 :     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                 :                :      */
 1003 tomas.vondra@postgre     3356                 :         312128 :     hot_attrs = RelationGetIndexAttrBitmap(relation,
                               3357                 :                :                                            INDEX_ATTR_BITMAP_HOT_BLOCKING);
                               3358                 :         312128 :     sum_attrs = RelationGetIndexAttrBitmap(relation,
                               3359                 :                :                                            INDEX_ATTR_BITMAP_SUMMARIZED);
 4390 rhaas@postgresql.org     3360                 :         312128 :     key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
                               3361                 :         312128 :     id_attrs = RelationGetIndexAttrBitmap(relation,
                               3362                 :                :                                           INDEX_ATTR_BITMAP_IDENTITY_KEY);
 1482 pg@bowt.ie               3363                 :         312128 :     interesting_attrs = NULL;
                               3364                 :         312128 :     interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
 1003 tomas.vondra@postgre     3365                 :         312128 :     interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
 1482 pg@bowt.ie               3366                 :         312128 :     interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
                               3367                 :         312128 :     interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
                               3368                 :                : 
 5293 rhaas@postgresql.org     3369                 :         312128 :     block = ItemPointerGetBlockNumber(otid);
                               3370                 :                :     INJECTION_POINT("heap_update-before-pin", NULL);
                               3371                 :         312128 :     buffer = ReadBuffer(relation, block);
 3528 kgrittn@postgresql.o     3372                 :         312128 :     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                 :                :      */
 5293 rhaas@postgresql.org     3380         [ +  + ]:         312128 :     if (PageIsAllVisible(page))
                               3381                 :           1636 :         visibilitymap_pin(relation, block, &vmbuffer);
                               3382                 :                : 
 9864 vadim4o@yahoo.com        3383                 :         312128 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               3384                 :                : 
 6366 tgl@sss.pgh.pa.us        3385                 :         312128 :     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                 :                :      */
  326 noah@leadboat.com        3410         [ -  + ]:         312128 :     if (!ItemIdIsNormal(lp))
                               3411                 :                :     {
  326 noah@leadboat.com        3412         [ #  # ]:UBC           0 :         Assert(RelationSupportsSysCache(RelationGetRelid(relation)));
                               3413                 :                : 
                               3414                 :              0 :         UnlockReleaseBuffer(buffer);
                               3415         [ #  # ]:              0 :         Assert(!have_tuple_lock);
                               3416         [ #  # ]:              0 :         if (vmbuffer != InvalidBuffer)
                               3417                 :              0 :             ReleaseBuffer(vmbuffer);
                               3418                 :              0 :         tmfd->ctid = *otid;
                               3419                 :              0 :         tmfd->xmax = InvalidTransactionId;
                               3420                 :              0 :         tmfd->cmax = InvalidCommandId;
                               3421                 :              0 :         *update_indexes = TU_None;
                               3422                 :                : 
                               3423                 :              0 :         bms_free(hot_attrs);
                               3424                 :              0 :         bms_free(sum_attrs);
                               3425                 :              0 :         bms_free(key_attrs);
                               3426                 :              0 :         bms_free(id_attrs);
                               3427                 :                :         /* modified_attrs not yet initialized */
                               3428                 :              0 :         bms_free(interesting_attrs);
                               3429                 :              0 :         return TM_Deleted;
                               3430                 :                :     }
                               3431                 :                : 
                               3432                 :                :     /*
                               3433                 :                :      * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
                               3434                 :                :      * properly.
                               3435                 :                :      */
 4702 alvherre@alvh.no-ip.     3436                 :CBC      312128 :     oldtup.t_tableOid = RelationGetRelid(relation);
 6366 tgl@sss.pgh.pa.us        3437                 :         312128 :     oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
 9882 vadim4o@yahoo.com        3438                 :         312128 :     oldtup.t_len = ItemIdGetLength(lp);
                               3439                 :         312128 :     oldtup.t_self = *otid;
                               3440                 :                : 
                               3441                 :                :     /* the new tuple is ready, except for this: */
 4702 alvherre@alvh.no-ip.     3442                 :         312128 :     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                 :                :      */
 1402 akapila@postgresql.o     3452                 :         312128 :     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                 :                :      */
 3185 alvherre@alvh.no-ip.     3467         [ +  + ]:         312128 :     if (!bms_overlap(modified_attrs, key_attrs))
                               3468                 :                :     {
 2806 simon@2ndQuadrant.co     3469                 :         307862 :         *lockmode = LockTupleNoKeyExclusive;
 4711 alvherre@alvh.no-ip.     3470                 :         307862 :         mxact_status = MultiXactStatusNoKeyUpdate;
                               3471                 :         307862 :         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                 :         307862 :         MultiXactIdSetOldestMember();
                               3483                 :                :     }
                               3484                 :                :     else
                               3485                 :                :     {
 2806 simon@2ndQuadrant.co     3486                 :           4266 :         *lockmode = LockTupleExclusive;
 4711 alvherre@alvh.no-ip.     3487                 :           4266 :         mxact_status = MultiXactStatusUpdate;
                               3488                 :           4266 :         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                 :                : 
 9864 vadim4o@yahoo.com        3498                 :              1 : l2:
 4711 alvherre@alvh.no-ip.     3499                 :         312129 :     checked_lockers = false;
                               3500                 :         312129 :     locker_remains = false;
 4531 rhaas@postgresql.org     3501                 :         312129 :     result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
                               3502                 :                : 
                               3503                 :                :     /* see below about the "no wait" case */
  615 akorotkov@postgresql     3504   [ +  +  -  + ]:         312129 :     Assert(result != TM_BeingModified || wait);
                               3505                 :                : 
 2461 andres@anarazel.de       3506         [ -  + ]:         312129 :     if (result == TM_Invisible)
                               3507                 :                :     {
 7201 tgl@sss.pgh.pa.us        3508                 :UBC           0 :         UnlockReleaseBuffer(buffer);
 3790                          3509         [ #  # ]:              0 :         ereport(ERROR,
                               3510                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               3511                 :                :                  errmsg("attempted to update invisible tuple")));
                               3512                 :                :     }
  615 akorotkov@postgresql     3513   [ +  +  +  - ]:CBC      312129 :     else if (result == TM_BeingModified && wait)
                               3514                 :                :     {
                               3515                 :                :         TransactionId xwait;
                               3516                 :                :         uint16      infomask;
 4711 alvherre@alvh.no-ip.     3517                 :          36098 :         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                 :          36098 :         xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
 7536 tgl@sss.pgh.pa.us        3534                 :          36098 :         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                 :                :          */
 7538                          3558         [ +  + ]:          36098 :         if (infomask & HEAP_XMAX_IS_MULTI)
                               3559                 :                :         {
                               3560                 :                :             TransactionId update_xact;
                               3561                 :                :             int         remain;
 2374 alvherre@alvh.no-ip.     3562                 :            179 :             bool        current_is_member = false;
                               3563                 :                : 
 3904                          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                 :                :                  */
 2374                          3573         [ -  + ]:              8 :                 if (!current_is_member)
 2374 alvherre@alvh.no-ip.     3574                 :UBC           0 :                     heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
                               3575                 :                :                                          LockWaitBlock, &have_tuple_lock);
                               3576                 :                : 
                               3577                 :                :                 /* wait for multixact */
 3904 alvherre@alvh.no-ip.     3578                 :CBC           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) ||
 3101 tgl@sss.pgh.pa.us        3592                 :              8 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
                               3593                 :                :                                          xwait))
 3904 alvherre@alvh.no-ip.     3594                 :UBC           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                 :                :              */
 4711 alvherre@alvh.no-ip.     3617         [ +  + ]:CBC         179 :             if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
                               3618                 :              8 :                 update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
                               3619                 :                :             else
 3904                          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                 :                :              */
 4711                          3627   [ +  +  +  + ]:            187 :             if (!TransactionIdIsValid(update_xact) ||
                               3628                 :              8 :                 TransactionIdDidAbort(update_xact))
                               3629                 :            172 :                 can_continue = true;
                               3630                 :                :         }
 3904                          3631         [ +  + ]:          35919 :         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                 :          35810 :             checked_lockers = true;
                               3638                 :          35810 :             locker_remains = true;
                               3639                 :          35810 :             can_continue = true;
                               3640                 :                :         }
                               3641   [ +  +  +  + ]:            109 :         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                 :             80 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
 2806 simon@2ndQuadrant.co     3659                 :             80 :             heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
                               3660                 :                :                                  LockWaitBlock, &have_tuple_lock);
 3904 alvherre@alvh.no-ip.     3661                 :             80 :             XactLockTableWait(xwait, relation, &oldtup.t_self,
                               3662                 :                :                               XLTW_Update);
                               3663                 :             80 :             checked_lockers = true;
                               3664                 :             80 :             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   [ +  +  -  + ]:            159 :             if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
                               3672                 :             79 :                 !TransactionIdEquals(xwait,
                               3673                 :                :                                      HeapTupleHeaderGetRawXmax(oldtup.t_data)))
                               3674                 :              1 :                 goto l2;
                               3675                 :                : 
                               3676                 :                :             /* Otherwise check if it committed or aborted */
                               3677                 :             79 :             UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
                               3678         [ +  + ]:             79 :             if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
 4711                          3679                 :             22 :                 can_continue = true;
                               3680                 :                :         }
                               3681                 :                : 
 2461 andres@anarazel.de       3682         [ +  + ]:          36097 :         if (can_continue)
                               3683                 :          36033 :             result = TM_Ok;
 1759 alvherre@alvh.no-ip.     3684         [ +  + ]:             64 :         else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
 2461 andres@anarazel.de       3685                 :             59 :             result = TM_Updated;
                               3686                 :                :         else
                               3687                 :              5 :             result = TM_Deleted;
                               3688                 :                :     }
                               3689                 :                : 
                               3690                 :                :     /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
                               3691         [ +  + ]:         312128 :     if (result != TM_Ok)
                               3692                 :                :     {
                               3693   [ +  +  +  +  :            161 :         Assert(result == TM_SelfModified ||
                                        -  +  -  - ]
                               3694                 :                :                result == TM_Updated ||
                               3695                 :                :                result == TM_Deleted ||
                               3696                 :                :                result == TM_BeingModified);
 7424 tgl@sss.pgh.pa.us        3697         [ -  + ]:            161 :         Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
 2461 andres@anarazel.de       3698   [ +  +  -  + ]:            161 :         Assert(result != TM_Updated ||
                               3699                 :                :                !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
                               3700                 :                :     }
                               3701                 :                : 
  750 heikki.linnakangas@i     3702   [ +  +  +  - ]:         312128 :     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         [ +  + ]:         312128 :     if (result != TM_Ok)
                               3710                 :                :     {
 2461 andres@anarazel.de       3711                 :            162 :         tmfd->ctid = oldtup.t_data->t_ctid;
                               3712                 :            162 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
                               3713         [ +  + ]:            162 :         if (result == TM_SelfModified)
                               3714                 :             52 :             tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
                               3715                 :                :         else
                               3716                 :            110 :             tmfd->cmax = InvalidCommandId;
  615 akorotkov@postgresql     3717                 :            162 :         UnlockReleaseBuffer(buffer);
 7536 tgl@sss.pgh.pa.us        3718         [ +  + ]:            162 :         if (have_tuple_lock)
 2806 simon@2ndQuadrant.co     3719                 :             57 :             UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
 5293 rhaas@postgresql.org     3720         [ -  + ]:            162 :         if (vmbuffer != InvalidBuffer)
 5293 rhaas@postgresql.org     3721                 :UBC           0 :             ReleaseBuffer(vmbuffer);
 1003 tomas.vondra@postgre     3722                 :CBC         162 :         *update_indexes = TU_None;
                               3723                 :                : 
 6663 tgl@sss.pgh.pa.us        3724                 :            162 :         bms_free(hot_attrs);
 1003 tomas.vondra@postgre     3725                 :            162 :         bms_free(sum_attrs);
 4711 alvherre@alvh.no-ip.     3726                 :            162 :         bms_free(key_attrs);
 3402 tgl@sss.pgh.pa.us        3727                 :            162 :         bms_free(id_attrs);
 3185 alvherre@alvh.no-ip.     3728                 :            162 :         bms_free(modified_attrs);
                               3729                 :            162 :         bms_free(interesting_attrs);
 9864 vadim4o@yahoo.com        3730                 :            162 :         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                 :                :      */
 5287 rhaas@postgresql.org     3742   [ +  +  -  + ]:         311966 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
                               3743                 :                :     {
 5287 rhaas@postgresql.org     3744                 :UBC           0 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               3745                 :              0 :         visibilitymap_pin(relation, block, &vmbuffer);
                               3746                 :              0 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
 5195                          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                 :                :      */
 4711 alvherre@alvh.no-ip.     3756                 :CBC      311966 :     compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
                               3757                 :         311966 :                               oldtup.t_data->t_infomask,
                               3758                 :         311966 :                               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   [ +  +  +  - ]:         347977 :     if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
 3463                          3771         [ +  + ]:          72022 :         HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
 4711                          3772         [ -  + ]:          35840 :         (checked_lockers && !locker_remains))
                               3773                 :         275955 :         xmax_new_tuple = InvalidTransactionId;
                               3774                 :                :     else
                               3775                 :          36011 :         xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
                               3776                 :                : 
                               3777         [ +  + ]:         311966 :     if (!TransactionIdIsValid(xmax_new_tuple))
                               3778                 :                :     {
                               3779                 :         275955 :         infomask_new_tuple = HEAP_XMAX_INVALID;
                               3780                 :         275955 :         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         [ +  + ]:          36011 :         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                 :          35839 :             infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
                               3798                 :          35839 :             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                 :                :      */
 9882 vadim4o@yahoo.com        3806                 :         311966 :     newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
 6663 tgl@sss.pgh.pa.us        3807                 :         311966 :     newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
 7762                          3808                 :         311966 :     HeapTupleHeaderSetXmin(newtup->t_data, xid);
 8586 bruce@momjian.us         3809                 :         311966 :     HeapTupleHeaderSetCmin(newtup->t_data, cid);
 4711 alvherre@alvh.no-ip.     3810                 :         311966 :     newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
                               3811                 :         311966 :     newtup->t_data->t_infomask2 |= infomask2_new_tuple;
                               3812                 :         311966 :     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                 :                :      */
 6886 tgl@sss.pgh.pa.us        3818                 :         311966 :     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                 :                :      */
 4672 kgrittn@postgresql.o     3831         [ -  + ]:         311966 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
 4672 kgrittn@postgresql.o     3832         [ #  # ]:UBC           0 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
                               3833                 :                :     {
                               3834                 :                :         /* toast table entries should never be recursively toasted */
 6833 tgl@sss.pgh.pa.us        3835         [ #  # ]:              0 :         Assert(!HeapTupleHasExternal(&oldtup));
                               3836         [ #  # ]:              0 :         Assert(!HeapTupleHasExternal(newtup));
                               3837                 :              0 :         need_toast = false;
                               3838                 :                :     }
                               3839                 :                :     else
 6833 tgl@sss.pgh.pa.us        3840         [ +  + ]:CBC      935512 :         need_toast = (HeapTupleHasExternal(&oldtup) ||
                               3841         [ +  + ]:         623546 :                       HeapTupleHasExternal(newtup) ||
                               3842         [ +  + ]:         311556 :                       newtup->t_len > TOAST_TUPLE_THRESHOLD);
                               3843                 :                : 
 6366                          3844                 :         311966 :     pagefree = PageGetHeapFreeSpace(page);
                               3845                 :                : 
 6891                          3846                 :         311966 :     newtupsize = MAXALIGN(newtup->t_len);
                               3847                 :                : 
 8981                          3848   [ +  +  +  + ]:         311966 :     if (need_toast || newtupsize > pagefree)
 9232 vadim4o@yahoo.com        3849                 :         152128 :     {
                               3850                 :                :         TransactionId xmax_lock_old_tuple;
                               3851                 :                :         uint16      infomask_lock_old_tuple,
                               3852                 :                :                     infomask2_lock_old_tuple;
 3439 andres@anarazel.de       3853                 :         152128 :         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                 :                :          */
 3442                          3873                 :         152128 :         compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
                               3874                 :         152128 :                                   oldtup.t_data->t_infomask,
                               3875                 :         152128 :                                   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         [ -  + ]:         152128 :         Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
                               3881                 :                : 
                               3882                 :         152128 :         START_CRIT_SECTION();
                               3883                 :                : 
                               3884                 :                :         /* Clear obsolete visibility flags ... */
 4711 alvherre@alvh.no-ip.     3885                 :         152128 :         oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               3886                 :         152128 :         oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
 6663 tgl@sss.pgh.pa.us        3887                 :         152128 :         HeapTupleClearHotUpdated(&oldtup);
                               3888                 :                :         /* ... and store info about transaction updating this tuple */
 3442 andres@anarazel.de       3889         [ -  + ]:         152128 :         Assert(TransactionIdIsValid(xmax_lock_old_tuple));
                               3890                 :         152128 :         HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
                               3891                 :         152128 :         oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
                               3892                 :         152128 :         oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
 6886 tgl@sss.pgh.pa.us        3893                 :         152128 :         HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
                               3894                 :                : 
                               3895                 :                :         /* temporarily make it look not-updated, but locked */
 7332                          3896                 :         152128 :         oldtup.t_data->t_ctid = oldtup.t_self;
                               3897                 :                : 
                               3898                 :                :         /*
                               3899                 :                :          * Clear all-frozen bit on visibility map if needed. We could
                               3900                 :                :          * immediately reset ALL_VISIBLE, but given that the WAL logging
                               3901                 :                :          * overhead would be unchanged, that doesn't seem necessarily
                               3902                 :                :          * worthwhile.
                               3903                 :                :          */
 1709                          3904   [ +  +  +  + ]:         153054 :         if (PageIsAllVisible(page) &&
 3439 andres@anarazel.de       3905                 :            926 :             visibilitymap_clear(relation, block, vmbuffer,
                               3906                 :                :                                 VISIBILITYMAP_ALL_FROZEN))
                               3907                 :            719 :             cleared_all_frozen = true;
                               3908                 :                : 
 3442                          3909                 :         152128 :         MarkBufferDirty(buffer);
                               3910                 :                : 
                               3911   [ +  +  +  +  :         152128 :         if (RelationNeedsWAL(relation))
                                        +  -  +  + ]
                               3912                 :                :         {
                               3913                 :                :             xl_heap_lock xlrec;
                               3914                 :                :             XLogRecPtr  recptr;
                               3915                 :                : 
                               3916                 :         141998 :             XLogBeginInsert();
                               3917                 :         141998 :             XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               3918                 :                : 
                               3919                 :         141998 :             xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
  981 pg@bowt.ie               3920                 :         141998 :             xlrec.xmax = xmax_lock_old_tuple;
 3442 andres@anarazel.de       3921                 :         283996 :             xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
                               3922                 :         141998 :                                                   oldtup.t_data->t_infomask2);
 3439                          3923                 :         141998 :             xlrec.flags =
                               3924                 :         141998 :                 cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
  309 peter@eisentraut.org     3925                 :         141998 :             XLogRegisterData(&xlrec, SizeOfHeapLock);
 3442 andres@anarazel.de       3926                 :         141998 :             recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
                               3927                 :         141998 :             PageSetLSN(page, recptr);
                               3928                 :                :         }
                               3929                 :                : 
                               3930         [ -  + ]:         152128 :         END_CRIT_SECTION();
                               3931                 :                : 
 9232 vadim4o@yahoo.com        3932                 :         152128 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               3933                 :                : 
                               3934                 :                :         /*
                               3935                 :                :          * Let the toaster do its thing, if needed.
                               3936                 :                :          *
                               3937                 :                :          * Note: below this point, heaptup is the data we actually intend to
                               3938                 :                :          * store into the relation; newtup is the caller's original untoasted
                               3939                 :                :          * data.
                               3940                 :                :          */
 9102 tgl@sss.pgh.pa.us        3941         [ +  + ]:         152128 :         if (need_toast)
                               3942                 :                :         {
                               3943                 :                :             /* Note we always use WAL and FSM during updates */
 2266 rhaas@postgresql.org     3944                 :           1773 :             heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
 7332 tgl@sss.pgh.pa.us        3945                 :           1773 :             newtupsize = MAXALIGN(heaptup->t_len);
                               3946                 :                :         }
                               3947                 :                :         else
                               3948                 :         150355 :             heaptup = newtup;
                               3949                 :                : 
                               3950                 :                :         /*
                               3951                 :                :          * Now, do we need a new page for the tuple, or not?  This is a bit
                               3952                 :                :          * tricky since someone else could have added tuples to the page while
                               3953                 :                :          * we weren't looking.  We have to recheck the available space after
                               3954                 :                :          * reacquiring the buffer lock.  But don't bother to do that if the
                               3955                 :                :          * former amount of free space is still not enough; it's unlikely
                               3956                 :                :          * there's more free now than before.
                               3957                 :                :          *
                               3958                 :                :          * What's more, if we need to get a new page, we will need to acquire
                               3959                 :                :          * buffer locks on both old and new pages.  To avoid deadlock against
                               3960                 :                :          * some other backend trying to get the same two locks in the other
                               3961                 :                :          * order, we must be consistent about the order we get the locks in.
                               3962                 :                :          * We use the rule "lock the lower-numbered page of the relation
                               3963                 :                :          * first".  To implement this, we must do RelationGetBufferForTuple
                               3964                 :                :          * while not holding the lock on the old page, and we must rely on it
                               3965                 :                :          * to get the locks on both pages in the correct order.
                               3966                 :                :          *
                               3967                 :                :          * Another consideration is that we need visibility map page pin(s) if
                               3968                 :                :          * we will have to clear the all-visible flag on either page.  If we
                               3969                 :                :          * call RelationGetBufferForTuple, we rely on it to acquire any such
                               3970                 :                :          * pins; but if we don't, we have to handle that here.  Hence we need
                               3971                 :                :          * a loop.
                               3972                 :                :          */
                               3973                 :                :         for (;;)
                               3974                 :                :         {
 1709                          3975         [ +  + ]:         152128 :             if (newtupsize > pagefree)
                               3976                 :                :             {
                               3977                 :                :                 /* It doesn't fit, must use RelationGetBufferForTuple. */
                               3978                 :         151586 :                 newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
                               3979                 :                :                                                    buffer, 0, NULL,
                               3980                 :                :                                                    &vmbuffer_new, &vmbuffer,
                               3981                 :                :                                                    0);
                               3982                 :                :                 /* We're all done. */
                               3983                 :         151586 :                 break;
                               3984                 :                :             }
                               3985                 :                :             /* Acquire VM page pin if needed and we don't have it. */
                               3986   [ +  +  -  + ]:            542 :             if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
 1709 tgl@sss.pgh.pa.us        3987                 :UBC           0 :                 visibilitymap_pin(relation, block, &vmbuffer);
                               3988                 :                :             /* Re-acquire the lock on the old tuple's page. */
 8981 tgl@sss.pgh.pa.us        3989                 :CBC         542 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               3990                 :                :             /* Re-check using the up-to-date free space */
 6366                          3991                 :            542 :             pagefree = PageGetHeapFreeSpace(page);
 1709                          3992         [ +  - ]:            542 :             if (newtupsize > pagefree ||
                               3993   [ +  +  -  + ]:            542 :                 (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
                               3994                 :                :             {
                               3995                 :                :                 /*
                               3996                 :                :                  * Rats, it doesn't fit anymore, or somebody just now set the
                               3997                 :                :                  * all-visible flag.  We must now unlock and loop to avoid
                               3998                 :                :                  * deadlock.  Fortunately, this path should seldom be taken.
                               3999                 :                :                  */
 8981 tgl@sss.pgh.pa.us        4000                 :UBC           0 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               4001                 :                :             }
                               4002                 :                :             else
                               4003                 :                :             {
                               4004                 :                :                 /* We're all done. */
 8981 tgl@sss.pgh.pa.us        4005                 :CBC         542 :                 newbuf = buffer;
 1709                          4006                 :            542 :                 break;
                               4007                 :                :             }
                               4008                 :                :         }
                               4009                 :                :     }
                               4010                 :                :     else
                               4011                 :                :     {
                               4012                 :                :         /* No TOAST work needed, and it'll fit on same page */
 9102                          4013                 :         159838 :         newbuf = buffer;
 7332                          4014                 :         159838 :         heaptup = newtup;
                               4015                 :                :     }
                               4016                 :                : 
                               4017                 :                :     /*
                               4018                 :                :      * We're about to do the actual update -- check for conflict first, to
                               4019                 :                :      * avoid possibly having to roll back work we've just done.
                               4020                 :                :      *
                               4021                 :                :      * This is safe without a recheck as long as there is no possibility of
                               4022                 :                :      * another process scanning the pages between this check and the update
                               4023                 :                :      * being visible to the scan (i.e., exclusive buffer content lock(s) are
                               4024                 :                :      * continuously held from this point until the tuple update is visible).
                               4025                 :                :      *
                               4026                 :                :      * For the new tuple the only check needed is at the relation level, but
                               4027                 :                :      * since both tuples are in the same relation and the check for oldtup
                               4028                 :                :      * will include checking the relation level, there is no benefit to a
                               4029                 :                :      * separate check for the new tuple.
                               4030                 :                :      */
 1709 tmunro@postgresql.or     4031                 :         311966 :     CheckForSerializableConflictIn(relation, &oldtup.t_self,
                               4032                 :                :                                    BufferGetBlockNumber(buffer));
                               4033                 :                : 
                               4034                 :                :     /*
                               4035                 :                :      * At this point newbuf and buffer are both pinned and locked, and newbuf
                               4036                 :                :      * has enough space for the new tuple.  If they are the same buffer, only
                               4037                 :                :      * one pin is held.
                               4038                 :                :      */
                               4039                 :                : 
 6663 tgl@sss.pgh.pa.us        4040         [ +  + ]:         311954 :     if (newbuf == buffer)
                               4041                 :                :     {
                               4042                 :                :         /*
                               4043                 :                :          * Since the new tuple is going into the same page, we might be able
                               4044                 :                :          * to do a HOT update.  Check if any of the index columns have been
                               4045                 :                :          * changed.
                               4046                 :                :          */
 1482 pg@bowt.ie               4047         [ +  + ]:         160368 :         if (!bms_overlap(modified_attrs, hot_attrs))
                               4048                 :                :         {
 6663 tgl@sss.pgh.pa.us        4049                 :         148133 :             use_hot_update = true;
                               4050                 :                : 
                               4051                 :                :             /*
                               4052                 :                :              * If none of the columns that are used in hot-blocking indexes
                               4053                 :                :              * were updated, we can apply HOT, but we do still need to check
                               4054                 :                :              * if we need to update the summarizing indexes, and update those
                               4055                 :                :              * indexes if the columns were updated, or we may fail to detect
                               4056                 :                :              * e.g. value bound changes in BRIN minmax indexes.
                               4057                 :                :              */
 1003 tomas.vondra@postgre     4058         [ +  + ]:         148133 :             if (bms_overlap(modified_attrs, sum_attrs))
                               4059                 :           1641 :                 summarized_update = true;
                               4060                 :                :         }
                               4061                 :                :     }
                               4062                 :                :     else
                               4063                 :                :     {
                               4064                 :                :         /* Set a hint that the old page could use prune/defrag */
 6366 tgl@sss.pgh.pa.us        4065                 :         151586 :         PageSetFull(page);
                               4066                 :                :     }
                               4067                 :                : 
                               4068                 :                :     /*
                               4069                 :                :      * Compute replica identity tuple before entering the critical section so
                               4070                 :                :      * we don't PANIC upon a memory allocation failure.
                               4071                 :                :      * ExtractReplicaIdentity() will return NULL if nothing needs to be
                               4072                 :                :      * logged.  Pass old key required as true only if the replica identity key
                               4073                 :                :      * columns are modified or it has external data.
                               4074                 :                :      */
 3185 alvherre@alvh.no-ip.     4075                 :         311954 :     old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
 1402 akapila@postgresql.o     4076   [ +  +  +  + ]:         311954 :                                            bms_overlap(modified_attrs, id_attrs) ||
                               4077                 :                :                                            id_has_external,
                               4078                 :                :                                            &old_key_copied);
                               4079                 :                : 
                               4080                 :                :     /* NO EREPORT(ERROR) from here till changes are logged */
 9105 tgl@sss.pgh.pa.us        4081                 :         311954 :     START_CRIT_SECTION();
                               4082                 :                : 
                               4083                 :                :     /*
                               4084                 :                :      * If this transaction commits, the old tuple will become DEAD sooner or
                               4085                 :                :      * later.  Set flag that this page is a candidate for pruning once our xid
                               4086                 :                :      * falls below the OldestXmin horizon.  If the transaction finally aborts,
                               4087                 :                :      * the subsequent page pruning will be a no-op and the hint will be
                               4088                 :                :      * cleared.
                               4089                 :                :      *
                               4090                 :                :      * XXX Should we set hint on newbuf as well?  If the transaction aborts,
                               4091                 :                :      * there would be a prunable tuple in the newbuf; but for now we choose
                               4092                 :                :      * not to optimize for aborts.  Note that heap_xlog_update must be kept in
                               4093                 :                :      * sync if this decision changes.
                               4094                 :                :      */
 6366                          4095   [ -  +  +  +  :         311954 :     PageSetPrunable(page, xid);
                                              +  + ]
                               4096                 :                : 
 6663                          4097         [ +  + ]:         311954 :     if (use_hot_update)
                               4098                 :                :     {
                               4099                 :                :         /* Mark the old tuple as HOT-updated */
                               4100                 :         148133 :         HeapTupleSetHotUpdated(&oldtup);
                               4101                 :                :         /* And mark the new tuple as heap-only */
                               4102                 :         148133 :         HeapTupleSetHeapOnly(heaptup);
                               4103                 :                :         /* Mark the caller's copy too, in case different from heaptup */
                               4104                 :         148133 :         HeapTupleSetHeapOnly(newtup);
                               4105                 :                :     }
                               4106                 :                :     else
                               4107                 :                :     {
                               4108                 :                :         /* Make sure tuples are correctly marked as not-HOT */
                               4109                 :         163821 :         HeapTupleClearHotUpdated(&oldtup);
                               4110                 :         163821 :         HeapTupleClearHeapOnly(heaptup);
                               4111                 :         163821 :         HeapTupleClearHeapOnly(newtup);
                               4112                 :                :     }
                               4113                 :                : 
 3101                          4114                 :         311954 :     RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
                               4115                 :                : 
                               4116                 :                : 
                               4117                 :                :     /* Clear obsolete visibility flags, possibly set by ourselves above... */
 3442 andres@anarazel.de       4118                 :         311954 :     oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               4119                 :         311954 :     oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               4120                 :                :     /* ... and store info about transaction updating this tuple */
                               4121         [ -  + ]:         311954 :     Assert(TransactionIdIsValid(xmax_old_tuple));
                               4122                 :         311954 :     HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
                               4123                 :         311954 :     oldtup.t_data->t_infomask |= infomask_old_tuple;
                               4124                 :         311954 :     oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
                               4125                 :         311954 :     HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
                               4126                 :                : 
                               4127                 :                :     /* record address of new tuple in t_ctid of old one */
 7332 tgl@sss.pgh.pa.us        4128                 :         311954 :     oldtup.t_data->t_ctid = heaptup->t_self;
                               4129                 :                : 
                               4130                 :                :     /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
 3528 kgrittn@postgresql.o     4131         [ +  + ]:         311954 :     if (PageIsAllVisible(BufferGetPage(buffer)))
                               4132                 :                :     {
 5959 tgl@sss.pgh.pa.us        4133                 :           1635 :         all_visible_cleared = true;
 3528 kgrittn@postgresql.o     4134                 :           1635 :         PageClearAllVisible(BufferGetPage(buffer));
 5287 rhaas@postgresql.org     4135                 :           1635 :         visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
                               4136                 :                :                             vmbuffer, VISIBILITYMAP_VALID_BITS);
                               4137                 :                :     }
 3528 kgrittn@postgresql.o     4138   [ +  +  +  + ]:         311954 :     if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
                               4139                 :                :     {
 5959 tgl@sss.pgh.pa.us        4140                 :           1016 :         all_visible_cleared_new = true;
 3528 kgrittn@postgresql.o     4141                 :           1016 :         PageClearAllVisible(BufferGetPage(newbuf));
 5287 rhaas@postgresql.org     4142                 :           1016 :         visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
                               4143                 :                :                             vmbuffer_new, VISIBILITYMAP_VALID_BITS);
                               4144                 :                :     }
                               4145                 :                : 
 7201 tgl@sss.pgh.pa.us        4146         [ +  + ]:         311954 :     if (newbuf != buffer)
                               4147                 :         151586 :         MarkBufferDirty(newbuf);
                               4148                 :         311954 :     MarkBufferDirty(buffer);
                               4149                 :                : 
                               4150                 :                :     /* XLOG stuff */
 5483 rhaas@postgresql.org     4151   [ +  +  +  +  :         311954 :     if (RelationNeedsWAL(relation))
                                        +  +  +  + ]
                               4152                 :                :     {
                               4153                 :                :         XLogRecPtr  recptr;
                               4154                 :                : 
                               4155                 :                :         /*
                               4156                 :                :          * For logical decoding we need combo CIDs to properly decode the
                               4157                 :                :          * catalog.
                               4158                 :                :          */
 4390                          4159   [ +  +  +  -  :         300589 :         if (RelationIsAccessibleInLogicalDecoding(relation))
                                     -  +  -  -  -  
                                     -  +  +  -  +  
                                     -  -  -  -  -  
                                                 - ]
                               4160                 :                :         {
                               4161                 :           2540 :             log_heap_new_cid(relation, &oldtup);
                               4162                 :           2540 :             log_heap_new_cid(relation, heaptup);
                               4163                 :                :         }
                               4164                 :                : 
                               4165                 :         300589 :         recptr = log_heap_update(relation, buffer,
                               4166                 :                :                                  newbuf, &oldtup, heaptup,
                               4167                 :                :                                  old_key_tuple,
                               4168                 :                :                                  all_visible_cleared,
                               4169                 :                :                                  all_visible_cleared_new);
 9298 vadim4o@yahoo.com        4170         [ +  + ]:         300589 :         if (newbuf != buffer)
                               4171                 :                :         {
 3528 kgrittn@postgresql.o     4172                 :         141462 :             PageSetLSN(BufferGetPage(newbuf), recptr);
                               4173                 :                :         }
                               4174                 :         300589 :         PageSetLSN(BufferGetPage(buffer), recptr);
                               4175                 :                :     }
                               4176                 :                : 
 9105 tgl@sss.pgh.pa.us        4177         [ -  + ]:         311954 :     END_CRIT_SECTION();
                               4178                 :                : 
 9298 vadim4o@yahoo.com        4179         [ +  + ]:         311954 :     if (newbuf != buffer)
                               4180                 :         151586 :         LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
 9864                          4181                 :         311954 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               4182                 :                : 
                               4183                 :                :     /*
                               4184                 :                :      * Mark old tuple for invalidation from system caches at next command
                               4185                 :                :      * boundary, and mark the new tuple for invalidation in case we abort. We
                               4186                 :                :      * have to do this before releasing the buffer because oldtup is in the
                               4187                 :                :      * buffer.  (heaptup is all in local memory, but it's necessary to process
                               4188                 :                :      * both tuple versions in one call to inval.c so we can avoid redundant
                               4189                 :                :      * sinval messages.)
                               4190                 :                :      */
 5237 tgl@sss.pgh.pa.us        4191                 :         311954 :     CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
                               4192                 :                : 
                               4193                 :                :     /* Now we can release the buffer(s) */
 9110                          4194         [ +  + ]:         311954 :     if (newbuf != buffer)
 7201                          4195                 :         151586 :         ReleaseBuffer(newbuf);
  615 akorotkov@postgresql     4196                 :         311954 :     ReleaseBuffer(buffer);
 5293 rhaas@postgresql.org     4197         [ +  + ]:         311954 :     if (BufferIsValid(vmbuffer_new))
                               4198                 :           1019 :         ReleaseBuffer(vmbuffer_new);
                               4199         [ +  + ]:         311954 :     if (BufferIsValid(vmbuffer))
                               4200                 :           1636 :         ReleaseBuffer(vmbuffer);
                               4201                 :                : 
                               4202                 :                :     /*
                               4203                 :                :      * Release the lmgr tuple lock, if we had it.
                               4204                 :                :      */
 7536 tgl@sss.pgh.pa.us        4205         [ +  + ]:         311954 :     if (have_tuple_lock)
 2806 simon@2ndQuadrant.co     4206                 :             22 :         UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
                               4207                 :                : 
 1000 pg@bowt.ie               4208                 :         311954 :     pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
                               4209                 :                : 
                               4210                 :                :     /*
                               4211                 :                :      * If heaptup is a private copy, release it.  Don't forget to copy t_self
                               4212                 :                :      * back to the caller's image, too.
                               4213                 :                :      */
 7332 tgl@sss.pgh.pa.us        4214         [ +  + ]:         311954 :     if (heaptup != newtup)
                               4215                 :                :     {
                               4216                 :           1725 :         newtup->t_self = heaptup->t_self;
                               4217                 :           1725 :         heap_freetuple(heaptup);
                               4218                 :                :     }
                               4219                 :                : 
                               4220                 :                :     /*
                               4221                 :                :      * If it is a HOT update, the update may still need to update summarized
                               4222                 :                :      * indexes, lest we fail to update those summaries and get incorrect
                               4223                 :                :      * results (for example, minmax bounds of the block may change with this
                               4224                 :                :      * update).
                               4225                 :                :      */
 1003 tomas.vondra@postgre     4226         [ +  + ]:         311954 :     if (use_hot_update)
                               4227                 :                :     {
                               4228         [ +  + ]:         148133 :         if (summarized_update)
                               4229                 :           1641 :             *update_indexes = TU_Summarizing;
                               4230                 :                :         else
                               4231                 :         146492 :             *update_indexes = TU_None;
                               4232                 :                :     }
                               4233                 :                :     else
                               4234                 :         163821 :         *update_indexes = TU_All;
                               4235                 :                : 
 4390 rhaas@postgresql.org     4236   [ +  +  +  + ]:         311954 :     if (old_key_tuple != NULL && old_key_copied)
                               4237                 :             84 :         heap_freetuple(old_key_tuple);
                               4238                 :                : 
 6663 tgl@sss.pgh.pa.us        4239                 :         311954 :     bms_free(hot_attrs);
 1003 tomas.vondra@postgre     4240                 :         311954 :     bms_free(sum_attrs);
 4711 alvherre@alvh.no-ip.     4241                 :         311954 :     bms_free(key_attrs);
 3402 tgl@sss.pgh.pa.us        4242                 :         311954 :     bms_free(id_attrs);
 3185 alvherre@alvh.no-ip.     4243                 :         311954 :     bms_free(modified_attrs);
                               4244                 :         311954 :     bms_free(interesting_attrs);
                               4245                 :                : 
 2461 andres@anarazel.de       4246                 :         311954 :     return TM_Ok;
                               4247                 :                : }
                               4248                 :                : 
                               4249                 :                : #ifdef USE_ASSERT_CHECKING
                               4250                 :                : /*
                               4251                 :                :  * Confirm adequate lock held during heap_update(), per rules from
                               4252                 :                :  * README.tuplock section "Locking to write inplace-updated tables".
                               4253                 :                :  */
                               4254                 :                : static void
  449 noah@leadboat.com        4255                 :         312128 : check_lock_if_inplace_updateable_rel(Relation relation,
                               4256                 :                :                                      const ItemPointerData *otid,
                               4257                 :                :                                      HeapTuple newtup)
                               4258                 :                : {
                               4259                 :                :     /* LOCKTAG_TUPLE acceptable for any catalog */
                               4260         [ +  + ]:         312128 :     switch (RelationGetRelid(relation))
                               4261                 :                :     {
                               4262                 :          70105 :         case RelationRelationId:
                               4263                 :                :         case DatabaseRelationId:
                               4264                 :                :             {
                               4265                 :                :                 LOCKTAG     tuptag;
                               4266                 :                : 
                               4267                 :          70105 :                 SET_LOCKTAG_TUPLE(tuptag,
                               4268                 :                :                                   relation->rd_lockInfo.lockRelId.dbId,
                               4269                 :                :                                   relation->rd_lockInfo.lockRelId.relId,
                               4270                 :                :                                   ItemPointerGetBlockNumber(otid),
                               4271                 :                :                                   ItemPointerGetOffsetNumber(otid));
                               4272         [ +  + ]:          70105 :                 if (LockHeldByMe(&tuptag, InplaceUpdateTupleLock, false))
                               4273                 :          31135 :                     return;
                               4274                 :                :             }
                               4275                 :          38970 :             break;
                               4276                 :         242023 :         default:
                               4277         [ -  + ]:         242023 :             Assert(!IsInplaceUpdateRelation(relation));
                               4278                 :         242023 :             return;
                               4279                 :                :     }
                               4280                 :                : 
                               4281      [ +  -  - ]:          38970 :     switch (RelationGetRelid(relation))
                               4282                 :                :     {
                               4283                 :          38970 :         case RelationRelationId:
                               4284                 :                :             {
                               4285                 :                :                 /* LOCKTAG_TUPLE or LOCKTAG_RELATION ok */
                               4286                 :          38970 :                 Form_pg_class classForm = (Form_pg_class) GETSTRUCT(newtup);
                               4287                 :          38970 :                 Oid         relid = classForm->oid;
                               4288                 :                :                 Oid         dbid;
                               4289                 :                :                 LOCKTAG     tag;
                               4290                 :                : 
                               4291         [ +  + ]:          38970 :                 if (IsSharedRelation(relid))
                               4292                 :             44 :                     dbid = InvalidOid;
                               4293                 :                :                 else
                               4294                 :          38926 :                     dbid = MyDatabaseId;
                               4295                 :                : 
                               4296         [ +  + ]:          38970 :                 if (classForm->relkind == RELKIND_INDEX)
                               4297                 :                :                 {
                               4298                 :            996 :                     Relation    irel = index_open(relid, AccessShareLock);
                               4299                 :                : 
                               4300                 :            996 :                     SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
                               4301                 :            996 :                     index_close(irel, AccessShareLock);
                               4302                 :                :                 }
                               4303                 :                :                 else
                               4304                 :          37974 :                     SET_LOCKTAG_RELATION(tag, dbid, relid);
                               4305                 :                : 
                               4306         [ +  + ]:          38970 :                 if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, false) &&
                               4307         [ -  + ]:          35433 :                     !LockHeldByMe(&tag, ShareRowExclusiveLock, true))
  449 noah@leadboat.com        4308         [ #  # ]:UBC           0 :                     elog(WARNING,
                               4309                 :                :                          "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
                               4310                 :                :                          NameStr(classForm->relname),
                               4311                 :                :                          relid,
                               4312                 :                :                          classForm->relkind,
                               4313                 :                :                          ItemPointerGetBlockNumber(otid),
                               4314                 :                :                          ItemPointerGetOffsetNumber(otid));
                               4315                 :                :             }
  449 noah@leadboat.com        4316                 :CBC       38970 :             break;
  449 noah@leadboat.com        4317                 :UBC           0 :         case DatabaseRelationId:
                               4318                 :                :             {
                               4319                 :                :                 /* LOCKTAG_TUPLE required */
                               4320                 :              0 :                 Form_pg_database dbForm = (Form_pg_database) GETSTRUCT(newtup);
                               4321                 :                : 
                               4322         [ #  # ]:              0 :                 elog(WARNING,
                               4323                 :                :                      "missing lock on database \"%s\" (OID %u) @ TID (%u,%u)",
                               4324                 :                :                      NameStr(dbForm->datname),
                               4325                 :                :                      dbForm->oid,
                               4326                 :                :                      ItemPointerGetBlockNumber(otid),
                               4327                 :                :                      ItemPointerGetOffsetNumber(otid));
                               4328                 :                :             }
                               4329                 :              0 :             break;
                               4330                 :                :     }
                               4331                 :                : }
                               4332                 :                : 
                               4333                 :                : /*
                               4334                 :                :  * Confirm adequate relation lock held, per rules from README.tuplock section
                               4335                 :                :  * "Locking to write inplace-updated tables".
                               4336                 :                :  */
                               4337                 :                : static void
  449 noah@leadboat.com        4338                 :CBC       93207 : check_inplace_rel_lock(HeapTuple oldtup)
                               4339                 :                : {
                               4340                 :          93207 :     Form_pg_class classForm = (Form_pg_class) GETSTRUCT(oldtup);
                               4341                 :          93207 :     Oid         relid = classForm->oid;
                               4342                 :                :     Oid         dbid;
                               4343                 :                :     LOCKTAG     tag;
                               4344                 :                : 
                               4345         [ +  + ]:          93207 :     if (IsSharedRelation(relid))
                               4346                 :           8859 :         dbid = InvalidOid;
                               4347                 :                :     else
                               4348                 :          84348 :         dbid = MyDatabaseId;
                               4349                 :                : 
                               4350         [ +  + ]:          93207 :     if (classForm->relkind == RELKIND_INDEX)
                               4351                 :                :     {
                               4352                 :          40499 :         Relation    irel = index_open(relid, AccessShareLock);
                               4353                 :                : 
                               4354                 :          40499 :         SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
                               4355                 :          40499 :         index_close(irel, AccessShareLock);
                               4356                 :                :     }
                               4357                 :                :     else
                               4358                 :          52708 :         SET_LOCKTAG_RELATION(tag, dbid, relid);
                               4359                 :                : 
                               4360         [ -  + ]:          93207 :     if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, true))
  449 noah@leadboat.com        4361         [ #  # ]:UBC           0 :         elog(WARNING,
                               4362                 :                :              "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
                               4363                 :                :              NameStr(classForm->relname),
                               4364                 :                :              relid,
                               4365                 :                :              classForm->relkind,
                               4366                 :                :              ItemPointerGetBlockNumber(&oldtup->t_self),
                               4367                 :                :              ItemPointerGetOffsetNumber(&oldtup->t_self));
  449 noah@leadboat.com        4368                 :CBC       93207 : }
                               4369                 :                : #endif
                               4370                 :                : 
                               4371                 :                : /*
                               4372                 :                :  * Check if the specified attribute's values are the same.  Subroutine for
                               4373                 :                :  * HeapDetermineColumnsInfo.
                               4374                 :                :  */
                               4375                 :                : static bool
 1402 akapila@postgresql.o     4376                 :         765911 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
                               4377                 :                :                  bool isnull1, bool isnull2)
                               4378                 :                : {
                               4379                 :                :     /*
                               4380                 :                :      * If one value is NULL and other is not, then they are certainly not
                               4381                 :                :      * equal
                               4382                 :                :      */
 6663 tgl@sss.pgh.pa.us        4383         [ +  + ]:         765911 :     if (isnull1 != isnull2)
                               4384                 :             45 :         return false;
                               4385                 :                : 
                               4386                 :                :     /*
                               4387                 :                :      * If both are NULL, they can be considered equal.
                               4388                 :                :      */
                               4389         [ +  + ]:         765866 :     if (isnull1)
                               4390                 :           4991 :         return true;
                               4391                 :                : 
                               4392                 :                :     /*
                               4393                 :                :      * We do simple binary comparison of the two datums.  This may be overly
                               4394                 :                :      * strict because there can be multiple binary representations for the
                               4395                 :                :      * same logical value.  But we should be OK as long as there are no false
                               4396                 :                :      * positives.  Using a type-specific equality operator is messy because
                               4397                 :                :      * there could be multiple notions of equality in different operator
                               4398                 :                :      * classes; furthermore, we cannot safely invoke user-defined functions
                               4399                 :                :      * while holding exclusive buffer lock.
                               4400                 :                :      */
                               4401         [ -  + ]:         760875 :     if (attrnum <= 0)
                               4402                 :                :     {
                               4403                 :                :         /* The only allowed system columns are OIDs, so do this */
 6663 tgl@sss.pgh.pa.us        4404                 :UBC           0 :         return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
                               4405                 :                :     }
                               4406                 :                :     else
                               4407                 :                :     {
                               4408                 :                :         CompactAttribute *att;
                               4409                 :                : 
 6663 tgl@sss.pgh.pa.us        4410         [ -  + ]:CBC      760875 :         Assert(attrnum <= tupdesc->natts);
  362 drowley@postgresql.o     4411                 :         760875 :         att = TupleDescCompactAttr(tupdesc, attrnum - 1);
 6663 tgl@sss.pgh.pa.us        4412                 :         760875 :         return datumIsEqual(value1, value2, att->attbyval, att->attlen);
                               4413                 :                :     }
                               4414                 :                : }
                               4415                 :                : 
                               4416                 :                : /*
                               4417                 :                :  * Check which columns are being updated.
                               4418                 :                :  *
                               4419                 :                :  * Given an updated tuple, determine (and return into the output bitmapset),
                               4420                 :                :  * from those listed as interesting, the set of columns that changed.
                               4421                 :                :  *
                               4422                 :                :  * has_external indicates if any of the unmodified attributes (from those
                               4423                 :                :  * listed as interesting) of the old tuple is a member of external_cols and is
                               4424                 :                :  * stored externally.
                               4425                 :                :  */
                               4426                 :                : static Bitmapset *
 1402 akapila@postgresql.o     4427                 :         312128 : HeapDetermineColumnsInfo(Relation relation,
                               4428                 :                :                          Bitmapset *interesting_cols,
                               4429                 :                :                          Bitmapset *external_cols,
                               4430                 :                :                          HeapTuple oldtup, HeapTuple newtup,
                               4431                 :                :                          bool *has_external)
                               4432                 :                : {
                               4433                 :                :     int         attidx;
 3136 bruce@momjian.us         4434                 :         312128 :     Bitmapset  *modified = NULL;
 1402 akapila@postgresql.o     4435                 :         312128 :     TupleDesc   tupdesc = RelationGetDescr(relation);
                               4436                 :                : 
 1021 tgl@sss.pgh.pa.us        4437                 :         312128 :     attidx = -1;
                               4438         [ +  + ]:        1078039 :     while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
                               4439                 :                :     {
                               4440                 :                :         /* attidx is zero-based, attrnum is the normal attribute number */
                               4441                 :         765911 :         AttrNumber  attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
                               4442                 :                :         Datum       value1,
                               4443                 :                :                     value2;
                               4444                 :                :         bool        isnull1,
                               4445                 :                :                     isnull2;
                               4446                 :                : 
                               4447                 :                :         /*
                               4448                 :                :          * If it's a whole-tuple reference, say "not equal".  It's not really
                               4449                 :                :          * worth supporting this case, since it could only succeed after a
                               4450                 :                :          * no-op update, which is hardly a case worth optimizing for.
                               4451                 :                :          */
 1402 akapila@postgresql.o     4452         [ -  + ]:         765911 :         if (attrnum == 0)
                               4453                 :                :         {
 1021 tgl@sss.pgh.pa.us        4454                 :UBC           0 :             modified = bms_add_member(modified, attidx);
 1402 akapila@postgresql.o     4455                 :CBC      733573 :             continue;
                               4456                 :                :         }
                               4457                 :                : 
                               4458                 :                :         /*
                               4459                 :                :          * Likewise, automatically say "not equal" for any system attribute
                               4460                 :                :          * other than tableOID; we cannot expect these to be consistent in a
                               4461                 :                :          * HOT chain, or even to be set correctly yet in the new tuple.
                               4462                 :                :          */
                               4463         [ -  + ]:         765911 :         if (attrnum < 0)
                               4464                 :                :         {
 1402 akapila@postgresql.o     4465         [ #  # ]:UBC           0 :             if (attrnum != TableOidAttributeNumber)
                               4466                 :                :             {
 1021 tgl@sss.pgh.pa.us        4467                 :              0 :                 modified = bms_add_member(modified, attidx);
 1402 akapila@postgresql.o     4468                 :              0 :                 continue;
                               4469                 :                :             }
                               4470                 :                :         }
                               4471                 :                : 
                               4472                 :                :         /*
                               4473                 :                :          * Extract the corresponding values.  XXX this is pretty inefficient
                               4474                 :                :          * if there are many indexed columns.  Should we do a single
                               4475                 :                :          * heap_deform_tuple call on each tuple, instead?   But that doesn't
                               4476                 :                :          * work for system columns ...
                               4477                 :                :          */
 1402 akapila@postgresql.o     4478                 :CBC      765911 :         value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
                               4479                 :         765911 :         value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
                               4480                 :                : 
                               4481         [ +  + ]:         765911 :         if (!heap_attr_equals(tupdesc, attrnum, value1,
                               4482                 :                :                               value2, isnull1, isnull2))
                               4483                 :                :         {
 1021 tgl@sss.pgh.pa.us        4484                 :          27106 :             modified = bms_add_member(modified, attidx);
 1402 akapila@postgresql.o     4485                 :          27106 :             continue;
                               4486                 :                :         }
                               4487                 :                : 
                               4488                 :                :         /*
                               4489                 :                :          * No need to check attributes that can't be stored externally. Note
                               4490                 :                :          * that system attributes can't be stored externally.
                               4491                 :                :          */
                               4492   [ +  -  +  + ]:         738805 :         if (attrnum < 0 || isnull1 ||
  362 drowley@postgresql.o     4493         [ +  + ]:         733814 :             TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
 1402 akapila@postgresql.o     4494                 :         706467 :             continue;
                               4495                 :                : 
                               4496                 :                :         /*
                               4497                 :                :          * Check if the old tuple's attribute is stored externally and is a
                               4498                 :                :          * member of external_cols.
                               4499                 :                :          */
                               4500   [ +  +  +  + ]:          32343 :         if (VARATT_IS_EXTERNAL((struct varlena *) DatumGetPointer(value1)) &&
 1021 tgl@sss.pgh.pa.us        4501                 :              5 :             bms_is_member(attidx, external_cols))
 1402 akapila@postgresql.o     4502                 :              2 :             *has_external = true;
                               4503                 :                :     }
                               4504                 :                : 
 3185 alvherre@alvh.no-ip.     4505                 :         312128 :     return modified;
                               4506                 :                : }
                               4507                 :                : 
                               4508                 :                : /*
                               4509                 :                :  *  simple_heap_update - replace a tuple
                               4510                 :                :  *
                               4511                 :                :  * This routine may be used to update a tuple when concurrent updates of
                               4512                 :                :  * the target tuple are not expected (for example, because we have a lock
                               4513                 :                :  * on the relation associated with the tuple).  Any failure is reported
                               4514                 :                :  * via ereport().
                               4515                 :                :  */
                               4516                 :                : void
   48 peter@eisentraut.org     4517                 :GNC      117419 : simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup,
                               4518                 :                :                    TU_UpdateIndexes *update_indexes)
                               4519                 :                : {
                               4520                 :                :     TM_Result   result;
                               4521                 :                :     TM_FailureData tmfd;
                               4522                 :                :     LockTupleMode lockmode;
                               4523                 :                : 
 8129 tgl@sss.pgh.pa.us        4524                 :CBC      117419 :     result = heap_update(relation, otid, tup,
                               4525                 :                :                          GetCurrentCommandId(true), InvalidSnapshot,
                               4526                 :                :                          true /* wait for commit */ ,
                               4527                 :                :                          &tmfd, &lockmode, update_indexes);
 9094                          4528   [ -  +  -  -  :         117419 :     switch (result)
                                                 - ]
                               4529                 :                :     {
 2461 andres@anarazel.de       4530                 :UBC           0 :         case TM_SelfModified:
                               4531                 :                :             /* Tuple was already updated in current command? */
 8185 tgl@sss.pgh.pa.us        4532         [ #  # ]:              0 :             elog(ERROR, "tuple already updated by self");
                               4533                 :                :             break;
                               4534                 :                : 
 2461 andres@anarazel.de       4535                 :CBC      117419 :         case TM_Ok:
                               4536                 :                :             /* done successfully */
 9094 tgl@sss.pgh.pa.us        4537                 :         117419 :             break;
                               4538                 :                : 
 2461 andres@anarazel.de       4539                 :UBC           0 :         case TM_Updated:
 8185 tgl@sss.pgh.pa.us        4540         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently updated");
                               4541                 :                :             break;
                               4542                 :                : 
 2461 andres@anarazel.de       4543                 :              0 :         case TM_Deleted:
                               4544         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently deleted");
                               4545                 :                :             break;
                               4546                 :                : 
 9094 tgl@sss.pgh.pa.us        4547                 :              0 :         default:
 8185                          4548         [ #  # ]:              0 :             elog(ERROR, "unrecognized heap_update status: %u", result);
                               4549                 :                :             break;
                               4550                 :                :     }
 9094 tgl@sss.pgh.pa.us        4551                 :CBC      117419 : }
                               4552                 :                : 
                               4553                 :                : 
                               4554                 :                : /*
                               4555                 :                :  * Return the MultiXactStatus corresponding to the given tuple lock mode.
                               4556                 :                :  */
                               4557                 :                : static MultiXactStatus
 4711 alvherre@alvh.no-ip.     4558                 :         115444 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
                               4559                 :                : {
                               4560                 :                :     int         retval;
                               4561                 :                : 
                               4562         [ +  + ]:         115444 :     if (is_update)
                               4563                 :            215 :         retval = tupleLockExtraInfo[mode].updstatus;
                               4564                 :                :     else
                               4565                 :         115229 :         retval = tupleLockExtraInfo[mode].lockstatus;
                               4566                 :                : 
                               4567         [ -  + ]:         115444 :     if (retval == -1)
 4711 alvherre@alvh.no-ip.     4568   [ #  #  #  # ]:UBC           0 :         elog(ERROR, "invalid lock tuple mode %d/%s", mode,
                               4569                 :                :              is_update ? "true" : "false");
                               4570                 :                : 
 4558 alvherre@alvh.no-ip.     4571                 :CBC      115444 :     return (MultiXactStatus) retval;
                               4572                 :                : }
                               4573                 :                : 
                               4574                 :                : /*
                               4575                 :                :  *  heap_lock_tuple - lock a tuple in shared or exclusive mode
                               4576                 :                :  *
                               4577                 :                :  * Note that this acquires a buffer pin, which the caller must release.
                               4578                 :                :  *
                               4579                 :                :  * Input parameters:
                               4580                 :                :  *  relation: relation containing tuple (caller must hold suitable lock)
                               4581                 :                :  *  cid: current command ID (used for visibility test, and stored into
                               4582                 :                :  *      tuple's cmax if lock is successful)
                               4583                 :                :  *  mode: indicates if shared or exclusive tuple lock is desired
                               4584                 :                :  *  wait_policy: what to do if tuple lock is not available
                               4585                 :                :  *  follow_updates: if true, follow the update chain to also lock descendant
                               4586                 :                :  *      tuples.
                               4587                 :                :  *
                               4588                 :                :  * Output parameters:
                               4589                 :                :  *  *tuple: all fields filled in
                               4590                 :                :  *  *buffer: set to buffer holding tuple (pinned but not locked at exit)
                               4591                 :                :  *  *tmfd: filled in failure cases (see below)
                               4592                 :                :  *
                               4593                 :                :  * Function results are the same as the ones for table_tuple_lock().
                               4594                 :                :  *
                               4595                 :                :  * In the failure cases other than TM_Invisible, the routine fills
                               4596                 :                :  * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
                               4597                 :                :  * if necessary), and t_cmax (the last only for TM_SelfModified,
                               4598                 :                :  * since we cannot obtain cmax from a combo CID generated by another
                               4599                 :                :  * transaction).
                               4600                 :                :  * See comments for struct TM_FailureData for additional info.
                               4601                 :                :  *
                               4602                 :                :  * See README.tuplock for a thorough explanation of this mechanism.
                               4603                 :                :  */
                               4604                 :                : TM_Result
  615 akorotkov@postgresql     4605                 :         158395 : heap_lock_tuple(Relation relation, HeapTuple tuple,
                               4606                 :                :                 CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
                               4607                 :                :                 bool follow_updates,
                               4608                 :                :                 Buffer *buffer, TM_FailureData *tmfd)
                               4609                 :                : {
                               4610                 :                :     TM_Result   result;
                               4611                 :         158395 :     ItemPointer tid = &(tuple->t_self);
                               4612                 :                :     ItemId      lp;
                               4613                 :                :     Page        page;
 3439 andres@anarazel.de       4614                 :         158395 :     Buffer      vmbuffer = InvalidBuffer;
                               4615                 :                :     BlockNumber block;
                               4616                 :                :     TransactionId xid,
                               4617                 :                :                 xmax;
                               4618                 :                :     uint16      old_infomask,
                               4619                 :                :                 new_infomask,
                               4620                 :                :                 new_infomask2;
 3904 alvherre@alvh.no-ip.     4621                 :         158395 :     bool        first_time = true;
 2374                          4622                 :         158395 :     bool        skip_tuple_lock = false;
 7536 tgl@sss.pgh.pa.us        4623                 :         158395 :     bool        have_tuple_lock = false;
 3439 andres@anarazel.de       4624                 :         158395 :     bool        cleared_all_frozen = false;
                               4625                 :                : 
  615 akorotkov@postgresql     4626                 :         158395 :     *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
 3439 andres@anarazel.de       4627                 :         158395 :     block = ItemPointerGetBlockNumber(tid);
                               4628                 :                : 
                               4629                 :                :     /*
                               4630                 :                :      * Before locking the buffer, pin the visibility map page if it appears to
                               4631                 :                :      * be necessary.  Since we haven't got the lock yet, someone else might be
                               4632                 :                :      * in the middle of changing this, so we'll need to recheck after we have
                               4633                 :                :      * the lock.
                               4634                 :                :      */
  615 akorotkov@postgresql     4635         [ +  + ]:         158395 :     if (PageIsAllVisible(BufferGetPage(*buffer)))
 3439 andres@anarazel.de       4636                 :           1666 :         visibilitymap_pin(relation, block, &vmbuffer);
                               4637                 :                : 
  615 akorotkov@postgresql     4638                 :         158395 :     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4639                 :                : 
                               4640                 :         158395 :     page = BufferGetPage(*buffer);
 6366 tgl@sss.pgh.pa.us        4641                 :         158395 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
 6671                          4642         [ -  + ]:         158395 :     Assert(ItemIdIsNormal(lp));
                               4643                 :                : 
 6366                          4644                 :         158395 :     tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
 9864 vadim4o@yahoo.com        4645                 :         158395 :     tuple->t_len = ItemIdGetLength(lp);
 7424 tgl@sss.pgh.pa.us        4646                 :         158395 :     tuple->t_tableOid = RelationGetRelid(relation);
                               4647                 :                : 
 9864 vadim4o@yahoo.com        4648                 :             12 : l3:
  615 akorotkov@postgresql     4649                 :         158407 :     result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
                               4650                 :                : 
 2461 andres@anarazel.de       4651         [ +  + ]:         158407 :     if (result == TM_Invisible)
                               4652                 :                :     {
                               4653                 :                :         /*
                               4654                 :                :          * This is possible, but only when locking a tuple for ON CONFLICT
                               4655                 :                :          * UPDATE.  We return this value here rather than throwing an error in
                               4656                 :                :          * order to give that case the opportunity to throw a more specific
                               4657                 :                :          * error.
                               4658                 :                :          */
                               4659                 :             12 :         result = TM_Invisible;
 3439                          4660                 :             12 :         goto out_locked;
                               4661                 :                :     }
 2461                          4662   [ +  +  +  + ]:         158395 :     else if (result == TM_BeingModified ||
                               4663         [ -  + ]:          77195 :              result == TM_Updated ||
                               4664                 :                :              result == TM_Deleted)
                               4665                 :                :     {
                               4666                 :                :         TransactionId xwait;
                               4667                 :                :         uint16      infomask;
                               4668                 :                :         uint16      infomask2;
                               4669                 :                :         bool        require_sleep;
                               4670                 :                :         ItemPointerData t_ctid;
                               4671                 :                : 
                               4672                 :                :         /* must copy state data before unlocking buffer */
 4711 alvherre@alvh.no-ip.     4673                 :          81200 :         xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
 7536 tgl@sss.pgh.pa.us        4674                 :          81200 :         infomask = tuple->t_data->t_infomask;
 4711 alvherre@alvh.no-ip.     4675                 :          81200 :         infomask2 = tuple->t_data->t_infomask2;
                               4676                 :          81200 :         ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
                               4677                 :                : 
  615 akorotkov@postgresql     4678                 :          81200 :         LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
                               4679                 :                : 
                               4680                 :                :         /*
                               4681                 :                :          * If any subtransaction of the current top transaction already holds
                               4682                 :                :          * a lock as strong as or stronger than what we're requesting, we
                               4683                 :                :          * effectively hold the desired lock already.  We *must* succeed
                               4684                 :                :          * without trying to take the tuple lock, else we will deadlock
                               4685                 :                :          * against anyone wanting to acquire a stronger lock.
                               4686                 :                :          *
                               4687                 :                :          * Note we only do this the first time we loop on the HTSU result;
                               4688                 :                :          * there is no point in testing in subsequent passes, because
                               4689                 :                :          * evidently our own transaction cannot have acquired a new lock after
                               4690                 :                :          * the first time we checked.
                               4691                 :                :          */
 3904 alvherre@alvh.no-ip.     4692         [ +  + ]:          81200 :         if (first_time)
                               4693                 :                :         {
                               4694                 :          81192 :             first_time = false;
                               4695                 :                : 
                               4696         [ +  + ]:          81192 :             if (infomask & HEAP_XMAX_IS_MULTI)
                               4697                 :                :             {
                               4698                 :                :                 int         i;
                               4699                 :                :                 int         nmembers;
                               4700                 :                :                 MultiXactMember *members;
                               4701                 :                : 
                               4702                 :                :                 /*
                               4703                 :                :                  * We don't need to allow old multixacts here; if that had
                               4704                 :                :                  * been the case, HeapTupleSatisfiesUpdate would have returned
                               4705                 :                :                  * MayBeUpdated and we wouldn't be here.
                               4706                 :                :                  */
                               4707                 :                :                 nmembers =
                               4708                 :          73306 :                     GetMultiXactIdMembers(xwait, &members, false,
                               4709                 :          73306 :                                           HEAP_XMAX_IS_LOCKED_ONLY(infomask));
                               4710                 :                : 
                               4711         [ +  + ]:        1422692 :                 for (i = 0; i < nmembers; i++)
                               4712                 :                :                 {
                               4713                 :                :                     /* only consider members of our own transaction */
                               4714         [ +  + ]:        1349400 :                     if (!TransactionIdIsCurrentTransactionId(members[i].xid))
                               4715                 :        1349351 :                         continue;
                               4716                 :                : 
                               4717         [ +  + ]:             49 :                     if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
                               4718                 :                :                     {
 4711                          4719                 :             14 :                         pfree(members);
 2461 andres@anarazel.de       4720                 :             14 :                         result = TM_Ok;
 3439                          4721                 :             14 :                         goto out_unlocked;
                               4722                 :                :                     }
                               4723                 :                :                     else
                               4724                 :                :                     {
                               4725                 :                :                         /*
                               4726                 :                :                          * Disable acquisition of the heavyweight tuple lock.
                               4727                 :                :                          * Otherwise, when promoting a weaker lock, we might
                               4728                 :                :                          * deadlock with another locker that has acquired the
                               4729                 :                :                          * heavyweight tuple lock and is waiting for our
                               4730                 :                :                          * transaction to finish.
                               4731                 :                :                          *
                               4732                 :                :                          * Note that in this case we still need to wait for
                               4733                 :                :                          * the multixact if required, to avoid acquiring
                               4734                 :                :                          * conflicting locks.
                               4735                 :                :                          */
 2374 alvherre@alvh.no-ip.     4736                 :             35 :                         skip_tuple_lock = true;
                               4737                 :                :                     }
                               4738                 :                :                 }
                               4739                 :                : 
 3904                          4740         [ +  - ]:          73292 :                 if (members)
                               4741                 :          73292 :                     pfree(members);
                               4742                 :                :             }
                               4743         [ +  + ]:           7886 :             else if (TransactionIdIsCurrentTransactionId(xwait))
                               4744                 :                :             {
                               4745   [ +  +  +  +  :           6576 :                 switch (mode)
                                                 - ]
                               4746                 :                :                 {
                               4747                 :            177 :                     case LockTupleKeyShare:
                               4748   [ -  +  -  -  :            177 :                         Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
                                              -  - ]
                               4749                 :                :                                HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
                               4750                 :                :                                HEAP_XMAX_IS_EXCL_LOCKED(infomask));
 2461 andres@anarazel.de       4751                 :            177 :                         result = TM_Ok;
 3439                          4752                 :            177 :                         goto out_unlocked;
 3904 alvherre@alvh.no-ip.     4753                 :             22 :                     case LockTupleShare:
                               4754   [ +  +  -  + ]:             28 :                         if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
                               4755                 :              6 :                             HEAP_XMAX_IS_EXCL_LOCKED(infomask))
                               4756                 :                :                         {
 2461 andres@anarazel.de       4757                 :             16 :                             result = TM_Ok;
 3439                          4758                 :             16 :                             goto out_unlocked;
                               4759                 :                :                         }
 3904 alvherre@alvh.no-ip.     4760                 :              6 :                         break;
                               4761                 :             72 :                     case LockTupleNoKeyExclusive:
                               4762         [ +  + ]:             72 :                         if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
                               4763                 :                :                         {
 2461 andres@anarazel.de       4764                 :             60 :                             result = TM_Ok;
 3439                          4765                 :             60 :                             goto out_unlocked;
                               4766                 :                :                         }
 3904 alvherre@alvh.no-ip.     4767                 :             12 :                         break;
                               4768                 :           6305 :                     case LockTupleExclusive:
                               4769         [ +  + ]:           6305 :                         if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
                               4770         [ +  + ]:           1265 :                             infomask2 & HEAP_KEYS_UPDATED)
                               4771                 :                :                         {
 2461 andres@anarazel.de       4772                 :           1244 :                             result = TM_Ok;
 3439                          4773                 :           1244 :                             goto out_unlocked;
                               4774                 :                :                         }
 3904 alvherre@alvh.no-ip.     4775                 :           5061 :                         break;
                               4776                 :                :                 }
                               4777                 :                :             }
                               4778                 :                :         }
                               4779                 :                : 
                               4780                 :                :         /*
                               4781                 :                :          * Initially assume that we will have to wait for the locking
                               4782                 :                :          * transaction(s) to finish.  We check various cases below in which
                               4783                 :                :          * this can be turned off.
                               4784                 :                :          */
 4711                          4785                 :          79689 :         require_sleep = true;
                               4786         [ +  + ]:          79689 :         if (mode == LockTupleKeyShare)
                               4787                 :                :         {
                               4788                 :                :             /*
                               4789                 :                :              * If we're requesting KeyShare, and there's no update present, we
                               4790                 :                :              * don't need to wait.  Even if there is an update, we can still
                               4791                 :                :              * continue if the key hasn't been modified.
                               4792                 :                :              *
                               4793                 :                :              * However, if there are updates, we need to walk the update chain
                               4794                 :                :              * to mark future versions of the row as locked, too.  That way,
                               4795                 :                :              * if somebody deletes that future version, we're protected
                               4796                 :                :              * against the key going away.  This locking of future versions
                               4797                 :                :              * could block momentarily, if a concurrent transaction is
                               4798                 :                :              * deleting a key; or it could return a value to the effect that
                               4799                 :                :              * the transaction deleting the key has already committed.  So we
                               4800                 :                :              * do this before re-locking the buffer; otherwise this would be
                               4801                 :                :              * prone to deadlocks.
                               4802                 :                :              *
                               4803                 :                :              * Note that the TID we're locking was grabbed before we unlocked
                               4804                 :                :              * the buffer.  For it to change while we're not looking, the
                               4805                 :                :              * other properties we're testing for below after re-locking the
                               4806                 :                :              * buffer would also change, in which case we would restart this
                               4807                 :                :              * loop above.
                               4808                 :                :              */
                               4809         [ +  + ]:          73865 :             if (!(infomask2 & HEAP_KEYS_UPDATED))
                               4810                 :                :             {
                               4811                 :                :                 bool        updated;
                               4812                 :                : 
                               4813                 :          73822 :                 updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
                               4814                 :                : 
                               4815                 :                :                 /*
                               4816                 :                :                  * If there are updates, follow the update chain; bail out if
                               4817                 :                :                  * that cannot be done.
                               4818                 :                :                  */
                               4819   [ +  -  +  + ]:          73822 :                 if (follow_updates && updated)
                               4820                 :                :                 {
                               4821                 :                :                     TM_Result   res;
                               4822                 :                : 
                               4823                 :           2169 :                     res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
                               4824                 :                :                                                   GetCurrentTransactionId(),
                               4825                 :                :                                                   mode);
 2461 andres@anarazel.de       4826         [ +  + ]:           2169 :                     if (res != TM_Ok)
                               4827                 :                :                     {
 4711 alvherre@alvh.no-ip.     4828                 :              6 :                         result = res;
                               4829                 :                :                         /* recovery code expects to have buffer lock held */
  615 akorotkov@postgresql     4830                 :              6 :                         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4711 alvherre@alvh.no-ip.     4831                 :            195 :                         goto failed;
                               4832                 :                :                     }
                               4833                 :                :                 }
                               4834                 :                : 
  615 akorotkov@postgresql     4835                 :          73816 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4836                 :                : 
                               4837                 :                :                 /*
                               4838                 :                :                  * Make sure it's still an appropriate lock, else start over.
                               4839                 :                :                  * Also, if it wasn't updated before we released the lock, but
                               4840                 :                :                  * is updated now, we start over too; the reason is that we
                               4841                 :                :                  * now need to follow the update chain to lock the new
                               4842                 :                :                  * versions.
                               4843                 :                :                  */
 4711 alvherre@alvh.no-ip.     4844         [ +  + ]:          73816 :                 if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
                               4845         [ +  - ]:           2151 :                     ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
                               4846         [ -  + ]:           2151 :                      !updated))
                               4847                 :             12 :                     goto l3;
                               4848                 :                : 
                               4849                 :                :                 /* Things look okay, so we can skip sleeping */
                               4850                 :          73816 :                 require_sleep = false;
                               4851                 :                : 
                               4852                 :                :                 /*
                               4853                 :                :                  * Note we allow Xmax to change here; other updaters/lockers
                               4854                 :                :                  * could have modified it before we grabbed the buffer lock.
                               4855                 :                :                  * However, this is not a problem, because with the recheck we
                               4856                 :                :                  * just did we ensure that they still don't conflict with the
                               4857                 :                :                  * lock we want.
                               4858                 :                :                  */
                               4859                 :                :             }
                               4860                 :                :         }
                               4861         [ +  + ]:           5824 :         else if (mode == LockTupleShare)
                               4862                 :                :         {
                               4863                 :                :             /*
                               4864                 :                :              * If we're requesting Share, we can similarly avoid sleeping if
                               4865                 :                :              * there's no update and no exclusive lock present.
                               4866                 :                :              */
                               4867         [ +  - ]:            443 :             if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
                               4868         [ +  + ]:            443 :                 !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
                               4869                 :                :             {
  615 akorotkov@postgresql     4870                 :            437 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4871                 :                : 
                               4872                 :                :                 /*
                               4873                 :                :                  * Make sure it's still an appropriate lock, else start over.
                               4874                 :                :                  * See above about allowing xmax to change.
                               4875                 :                :                  */
 4711 alvherre@alvh.no-ip.     4876   [ +  -  -  + ]:            874 :                 if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
                               4877                 :            437 :                     HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
 4711 alvherre@alvh.no-ip.     4878                 :UBC           0 :                     goto l3;
 4711 alvherre@alvh.no-ip.     4879                 :CBC         437 :                 require_sleep = false;
                               4880                 :                :             }
                               4881                 :                :         }
                               4882         [ +  + ]:           5381 :         else if (mode == LockTupleNoKeyExclusive)
                               4883                 :                :         {
                               4884                 :                :             /*
                               4885                 :                :              * If we're requesting NoKeyExclusive, we might also be able to
                               4886                 :                :              * avoid sleeping; just ensure that there no conflicting lock
                               4887                 :                :              * already acquired.
                               4888                 :                :              */
                               4889         [ +  + ]:            166 :             if (infomask & HEAP_XMAX_IS_MULTI)
                               4890                 :                :             {
 4009                          4891         [ +  + ]:             26 :                 if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
                               4892                 :                :                                              mode, NULL))
                               4893                 :                :                 {
                               4894                 :                :                     /*
                               4895                 :                :                      * No conflict, but if the xmax changed under us in the
                               4896                 :                :                      * meantime, start over.
                               4897                 :                :                      */
  615 akorotkov@postgresql     4898                 :             13 :                     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4009 alvherre@alvh.no-ip.     4899   [ +  -  -  + ]:             26 :                     if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
                               4900                 :             13 :                         !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               4901                 :                :                                              xwait))
 4009 alvherre@alvh.no-ip.     4902                 :UBC           0 :                         goto l3;
                               4903                 :                : 
                               4904                 :                :                     /* otherwise, we're good */
 4009 alvherre@alvh.no-ip.     4905                 :CBC          13 :                     require_sleep = false;
                               4906                 :                :                 }
                               4907                 :                :             }
 4711                          4908         [ +  + ]:            140 :             else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
                               4909                 :                :             {
  615 akorotkov@postgresql     4910                 :             18 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4911                 :                : 
                               4912                 :                :                 /* if the xmax changed in the meantime, start over */
 4255 alvherre@alvh.no-ip.     4913   [ +  -  -  + ]:             36 :                 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
 2148                          4914                 :             18 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               4915                 :                :                                          xwait))
 4711 alvherre@alvh.no-ip.     4916                 :UBC           0 :                     goto l3;
                               4917                 :                :                 /* otherwise, we're good */
 4711 alvherre@alvh.no-ip.     4918                 :CBC          18 :                 require_sleep = false;
                               4919                 :                :             }
                               4920                 :                :         }
                               4921                 :                : 
                               4922                 :                :         /*
                               4923                 :                :          * As a check independent from those above, we can also avoid sleeping
                               4924                 :                :          * if the current transaction is the sole locker of the tuple.  Note
                               4925                 :                :          * that the strength of the lock already held is irrelevant; this is
                               4926                 :                :          * not about recording the lock in Xmax (which will be done regardless
                               4927                 :                :          * of this optimization, below).  Also, note that the cases where we
                               4928                 :                :          * hold a lock stronger than we are requesting are already handled
                               4929                 :                :          * above by not doing anything.
                               4930                 :                :          *
                               4931                 :                :          * Note we only deal with the non-multixact case here; MultiXactIdWait
                               4932                 :                :          * is well equipped to deal with this situation on its own.
                               4933                 :                :          */
 3904                          4934   [ +  +  +  +  :          85042 :         if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
                                              +  + ]
                               4935                 :           5359 :             TransactionIdIsCurrentTransactionId(xwait))
                               4936                 :                :         {
                               4937                 :                :             /* ... but if the xmax changed in the meantime, start over */
  615 akorotkov@postgresql     4938                 :           5061 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3904 alvherre@alvh.no-ip.     4939   [ +  -  -  + ]:          10122 :             if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
                               4940                 :           5061 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               4941                 :                :                                      xwait))
 3904 alvherre@alvh.no-ip.     4942                 :UBC           0 :                 goto l3;
 3904 alvherre@alvh.no-ip.     4943         [ -  + ]:CBC        5061 :             Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
                               4944                 :           5061 :             require_sleep = false;
                               4945                 :                :         }
                               4946                 :                : 
                               4947                 :                :         /*
                               4948                 :                :          * Time to sleep on the other transaction/multixact, if necessary.
                               4949                 :                :          *
                               4950                 :                :          * If the other transaction is an update/delete that's already
                               4951                 :                :          * committed, then sleeping cannot possibly do any good: if we're
                               4952                 :                :          * required to sleep, get out to raise an error instead.
                               4953                 :                :          *
                               4954                 :                :          * By here, we either have already acquired the buffer exclusive lock,
                               4955                 :                :          * or we must wait for the locking transaction or multixact; so below
                               4956                 :                :          * we ensure that we grab buffer lock after the sleep.
                               4957                 :                :          */
 2461 andres@anarazel.de       4958   [ +  +  +  +  :          79683 :         if (require_sleep && (result == TM_Updated || result == TM_Deleted))
                                              -  + ]
                               4959                 :                :         {
  615 akorotkov@postgresql     4960                 :            151 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3442 alvherre@alvh.no-ip.     4961                 :            151 :             goto failed;
                               4962                 :                :         }
                               4963         [ +  + ]:          79532 :         else if (require_sleep)
                               4964                 :                :         {
                               4965                 :                :             /*
                               4966                 :                :              * Acquire tuple lock to establish our priority for the tuple, or
                               4967                 :                :              * die trying.  LockTuple will release us when we are next-in-line
                               4968                 :                :              * for the tuple.  We must do this even if we are share-locking,
                               4969                 :                :              * but not if we already have a weaker lock on the tuple.
                               4970                 :                :              *
                               4971                 :                :              * If we are forced to "start over" below, we keep the tuple lock;
                               4972                 :                :              * this arranges that we stay at the head of the line while
                               4973                 :                :              * rechecking tuple state.
                               4974                 :                :              */
 2374                          4975         [ +  + ]:            187 :             if (!skip_tuple_lock &&
                               4976         [ +  + ]:            171 :                 !heap_acquire_tuplock(relation, tid, mode, wait_policy,
                               4977                 :                :                                       &have_tuple_lock))
                               4978                 :                :             {
                               4979                 :                :                 /*
                               4980                 :                :                  * This can only happen if wait_policy is Skip and the lock
                               4981                 :                :                  * couldn't be obtained.
                               4982                 :                :                  */
 2461 andres@anarazel.de       4983                 :              1 :                 result = TM_WouldBlock;
                               4984                 :                :                 /* recovery code expects to have buffer lock held */
  615 akorotkov@postgresql     4985                 :              1 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4009 alvherre@alvh.no-ip.     4986                 :              1 :                 goto failed;
                               4987                 :                :             }
                               4988                 :                : 
 4711                          4989         [ +  + ]:            185 :             if (infomask & HEAP_XMAX_IS_MULTI)
                               4990                 :                :             {
                               4991                 :             40 :                 MultiXactStatus status = get_mxact_status_for_lock(mode, false);
                               4992                 :                : 
                               4993                 :                :                 /* We only ever lock tuples, never update them */
                               4994         [ -  + ]:             40 :                 if (status >= MultiXactStatusNoKeyUpdate)
 4711 alvherre@alvh.no-ip.     4995         [ #  # ]:UBC           0 :                     elog(ERROR, "invalid lock mode in heap_lock_tuple");
                               4996                 :                : 
                               4997                 :                :                 /* wait for multixact to end, or die trying  */
 4089 alvherre@alvh.no-ip.     4998   [ +  +  +  - ]:CBC          40 :                 switch (wait_policy)
                               4999                 :                :                 {
                               5000                 :             36 :                     case LockWaitBlock:
                               5001                 :             36 :                         MultiXactIdWait((MultiXactId) xwait, status, infomask,
 3101 tgl@sss.pgh.pa.us        5002                 :GIC          36 :                                         relation, &tuple->t_self, XLTW_Lock, NULL);
 4089 alvherre@alvh.no-ip.     5003                 :CBC          36 :                         break;
                               5004                 :              2 :                     case LockWaitSkip:
                               5005         [ +  - ]:              2 :                         if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
                               5006                 :                :                                                         status, infomask, relation,
                               5007                 :                :                                                         NULL, false))
                               5008                 :                :                         {
 2461 andres@anarazel.de       5009                 :              2 :                             result = TM_WouldBlock;
                               5010                 :                :                             /* recovery code expects to have buffer lock held */
  615 akorotkov@postgresql     5011                 :              2 :                             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4089 alvherre@alvh.no-ip.     5012                 :              2 :                             goto failed;
                               5013                 :                :                         }
 4089 alvherre@alvh.no-ip.     5014                 :UBC           0 :                         break;
 4089 alvherre@alvh.no-ip.     5015                 :CBC           2 :                     case LockWaitError:
                               5016         [ +  - ]:              2 :                         if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
                               5017                 :                :                                                         status, infomask, relation,
                               5018                 :                :                                                         NULL, log_lock_failures))
                               5019         [ +  - ]:              2 :                             ereport(ERROR,
                               5020                 :                :                                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                               5021                 :                :                                      errmsg("could not obtain lock on row in relation \"%s\"",
                               5022                 :                :                                             RelationGetRelationName(relation))));
                               5023                 :                : 
 4089 alvherre@alvh.no-ip.     5024                 :UBC           0 :                         break;
                               5025                 :                :                 }
                               5026                 :                : 
                               5027                 :                :                 /*
                               5028                 :                :                  * Of course, the multixact might not be done here: if we're
                               5029                 :                :                  * requesting a light lock mode, other transactions with light
                               5030                 :                :                  * locks could still be alive, as well as locks owned by our
                               5031                 :                :                  * own xact or other subxacts of this backend.  We need to
                               5032                 :                :                  * preserve the surviving MultiXact members.  Note that it
                               5033                 :                :                  * isn't absolutely necessary in the latter case, but doing so
                               5034                 :                :                  * is simpler.
                               5035                 :                :                  */
                               5036                 :                :             }
                               5037                 :                :             else
                               5038                 :                :             {
                               5039                 :                :                 /* wait for regular transaction to end, or die trying */
 4089 alvherre@alvh.no-ip.     5040   [ +  +  +  - ]:CBC         145 :                 switch (wait_policy)
                               5041                 :                :                 {
                               5042                 :            106 :                     case LockWaitBlock:
 3969 heikki.linnakangas@i     5043                 :            106 :                         XactLockTableWait(xwait, relation, &tuple->t_self,
                               5044                 :                :                                           XLTW_Lock);
 4089 alvherre@alvh.no-ip.     5045                 :            106 :                         break;
                               5046                 :             33 :                     case LockWaitSkip:
  278 fujii@postgresql.org     5047         [ +  - ]:             33 :                         if (!ConditionalXactLockTableWait(xwait, false))
                               5048                 :                :                         {
 2461 andres@anarazel.de       5049                 :             33 :                             result = TM_WouldBlock;
                               5050                 :                :                             /* recovery code expects to have buffer lock held */
  615 akorotkov@postgresql     5051                 :             33 :                             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4089 alvherre@alvh.no-ip.     5052                 :             33 :                             goto failed;
                               5053                 :                :                         }
 4089 alvherre@alvh.no-ip.     5054                 :UBC           0 :                         break;
 4089 alvherre@alvh.no-ip.     5055                 :CBC           6 :                     case LockWaitError:
  197 fujii@postgresql.org     5056         [ +  - ]:              6 :                         if (!ConditionalXactLockTableWait(xwait, log_lock_failures))
 4089 alvherre@alvh.no-ip.     5057         [ +  - ]:              6 :                             ereport(ERROR,
                               5058                 :                :                                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                               5059                 :                :                                      errmsg("could not obtain lock on row in relation \"%s\"",
                               5060                 :                :                                             RelationGetRelationName(relation))));
 4089 alvherre@alvh.no-ip.     5061                 :UBC           0 :                         break;
                               5062                 :                :                 }
                               5063                 :                :             }
                               5064                 :                : 
                               5065                 :                :             /* if there are updates, follow the update chain */
 3904 alvherre@alvh.no-ip.     5066   [ +  +  +  + ]:CBC         142 :             if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
                               5067                 :                :             {
                               5068                 :                :                 TM_Result   res;
                               5069                 :                : 
                               5070                 :             57 :                 res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
                               5071                 :                :                                               GetCurrentTransactionId(),
                               5072                 :                :                                               mode);
 2461 andres@anarazel.de       5073         [ +  + ]:             57 :                 if (res != TM_Ok)
                               5074                 :                :                 {
 3904 alvherre@alvh.no-ip.     5075                 :              2 :                     result = res;
                               5076                 :                :                     /* recovery code expects to have buffer lock held */
  615 akorotkov@postgresql     5077                 :              2 :                     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3904 alvherre@alvh.no-ip.     5078                 :              2 :                     goto failed;
                               5079                 :                :                 }
                               5080                 :                :             }
                               5081                 :                : 
  615 akorotkov@postgresql     5082                 :            140 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               5083                 :                : 
                               5084                 :                :             /*
                               5085                 :                :              * xwait is done, but if xwait had just locked the tuple then some
                               5086                 :                :              * other xact could update this tuple before we get to this point.
                               5087                 :                :              * Check for xmax change, and start over if so.
                               5088                 :                :              */
 3904 alvherre@alvh.no-ip.     5089   [ +  +  +  + ]:            270 :             if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
                               5090                 :            130 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               5091                 :                :                                      xwait))
                               5092                 :             12 :                 goto l3;
                               5093                 :                : 
                               5094         [ +  + ]:            128 :             if (!(infomask & HEAP_XMAX_IS_MULTI))
                               5095                 :                :             {
                               5096                 :                :                 /*
                               5097                 :                :                  * Otherwise check if it committed or aborted.  Note we cannot
                               5098                 :                :                  * be here if the tuple was only locked by somebody who didn't
                               5099                 :                :                  * conflict with us; that would have been handled above.  So
                               5100                 :                :                  * that transaction must necessarily be gone by now.  But
                               5101                 :                :                  * don't check for this in the multixact case, because some
                               5102                 :                :                  * locker transactions might still be running.
                               5103                 :                :                  */
  615 akorotkov@postgresql     5104                 :             95 :                 UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
                               5105                 :                :             }
                               5106                 :                :         }
                               5107                 :                : 
                               5108                 :                :         /* By here, we're certain that we hold buffer exclusive lock again */
                               5109                 :                : 
                               5110                 :                :         /*
                               5111                 :                :          * We may lock if previous xmax aborted, or if it committed but only
                               5112                 :                :          * locked the tuple without updating it; or if we didn't have to wait
                               5113                 :                :          * at all for whatever reason.
                               5114                 :                :          */
 4711 alvherre@alvh.no-ip.     5115         [ +  + ]:          79473 :         if (!require_sleep ||
                               5116   [ +  +  +  + ]:            226 :             (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
                               5117         [ +  + ]:            180 :             HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
                               5118                 :             82 :             HeapTupleHeaderIsOnlyLocked(tuple->t_data))
 2461 andres@anarazel.de       5119                 :          79397 :             result = TM_Ok;
 1759 alvherre@alvh.no-ip.     5120         [ +  + ]:             76 :         else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
 2461 andres@anarazel.de       5121                 :             57 :             result = TM_Updated;
                               5122                 :                :         else
                               5123                 :             19 :             result = TM_Deleted;
                               5124                 :                :     }
                               5125                 :                : 
 4711 alvherre@alvh.no-ip.     5126                 :          77195 : failed:
 2461 andres@anarazel.de       5127         [ +  + ]:         156863 :     if (result != TM_Ok)
                               5128                 :                :     {
                               5129   [ +  +  +  +  :            277 :         Assert(result == TM_SelfModified || result == TM_Updated ||
                                        +  +  -  + ]
                               5130                 :                :                result == TM_Deleted || result == TM_WouldBlock);
                               5131                 :                : 
                               5132                 :                :         /*
                               5133                 :                :          * When locking a tuple under LockWaitSkip semantics and we fail with
                               5134                 :                :          * TM_WouldBlock above, it's possible for concurrent transactions to
                               5135                 :                :          * release the lock and set HEAP_XMAX_INVALID in the meantime.  So
                               5136                 :                :          * this assert is slightly different from the equivalent one in
                               5137                 :                :          * heap_delete and heap_update.
                               5138                 :                :          */
 1443 alvherre@alvh.no-ip.     5139   [ +  +  -  + ]:            277 :         Assert((result == TM_WouldBlock) ||
                               5140                 :                :                !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
 2461 andres@anarazel.de       5141   [ +  +  -  + ]:            277 :         Assert(result != TM_Updated ||
                               5142                 :                :                !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
                               5143                 :            277 :         tmfd->ctid = tuple->t_data->t_ctid;
                               5144                 :            277 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
                               5145         [ +  + ]:            277 :         if (result == TM_SelfModified)
                               5146                 :              6 :             tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
                               5147                 :                :         else
                               5148                 :            271 :             tmfd->cmax = InvalidCommandId;
 3439                          5149                 :            277 :         goto out_locked;
                               5150                 :                :     }
                               5151                 :                : 
                               5152                 :                :     /*
                               5153                 :                :      * If we didn't pin the visibility map page and the page has become all
                               5154                 :                :      * visible while we were busy locking the buffer, or during some
                               5155                 :                :      * subsequent window during which we had it unlocked, we'll have to unlock
                               5156                 :                :      * and re-lock, to avoid holding the buffer lock across I/O.  That's a bit
                               5157                 :                :      * unfortunate, especially since we'll now have to recheck whether the
                               5158                 :                :      * tuple has been locked or updated under us, but hopefully it won't
                               5159                 :                :      * happen very often.
                               5160                 :                :      */
 3422                          5161   [ +  +  -  + ]:         156586 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
                               5162                 :                :     {
  615 akorotkov@postgresql     5163                 :UBC           0 :         LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
 3422 andres@anarazel.de       5164                 :              0 :         visibilitymap_pin(relation, block, &vmbuffer);
  615 akorotkov@postgresql     5165                 :              0 :         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3422 andres@anarazel.de       5166                 :              0 :         goto l3;
                               5167                 :                :     }
                               5168                 :                : 
 4711 alvherre@alvh.no-ip.     5169                 :CBC      156586 :     xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
                               5170                 :         156586 :     old_infomask = tuple->t_data->t_infomask;
                               5171                 :                : 
                               5172                 :                :     /*
                               5173                 :                :      * If this is the first possibly-multixact-able operation in the current
                               5174                 :                :      * transaction, set my per-backend OldestMemberMXactId setting. We can be
                               5175                 :                :      * certain that the transaction will never become a member of any older
                               5176                 :                :      * MultiXactIds than that.  (We have to do this even if we end up just
                               5177                 :                :      * using our own TransactionId below, since some other backend could
                               5178                 :                :      * incorporate our XID into a MultiXact immediately afterwards.)
                               5179                 :                :      */
                               5180                 :         156586 :     MultiXactIdSetOldestMember();
                               5181                 :                : 
                               5182                 :                :     /*
                               5183                 :                :      * Compute the new xmax and infomask to store into the tuple.  Note we do
                               5184                 :                :      * not modify the tuple just yet, because that would leave it in the wrong
                               5185                 :                :      * state if multixact.c elogs.
                               5186                 :                :      */
                               5187                 :         156586 :     compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
                               5188                 :                :                               GetCurrentTransactionId(), mode, false,
                               5189                 :                :                               &xid, &new_infomask, &new_infomask2);
                               5190                 :                : 
 7538 tgl@sss.pgh.pa.us        5191                 :         156586 :     START_CRIT_SECTION();
                               5192                 :                : 
                               5193                 :                :     /*
                               5194                 :                :      * Store transaction information of xact locking the tuple.
                               5195                 :                :      *
                               5196                 :                :      * Note: Cmax is meaningless in this context, so don't set it; this avoids
                               5197                 :                :      * possibly generating a useless combo CID.  Moreover, if we're locking a
                               5198                 :                :      * previously updated tuple, it's important to preserve the Cmax.
                               5199                 :                :      *
                               5200                 :                :      * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
                               5201                 :                :      * we would break the HOT chain.
                               5202                 :                :      */
 4711 alvherre@alvh.no-ip.     5203                 :         156586 :     tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
                               5204                 :         156586 :     tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               5205                 :         156586 :     tuple->t_data->t_infomask |= new_infomask;
                               5206                 :         156586 :     tuple->t_data->t_infomask2 |= new_infomask2;
                               5207         [ +  + ]:         156586 :     if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
                               5208                 :         154439 :         HeapTupleHeaderClearHotUpdated(tuple->t_data);
 7762 tgl@sss.pgh.pa.us        5209                 :         156586 :     HeapTupleHeaderSetXmax(tuple->t_data, xid);
                               5210                 :                : 
                               5211                 :                :     /*
                               5212                 :                :      * Make sure there is no forward chain link in t_ctid.  Note that in the
                               5213                 :                :      * cases where the tuple has been updated, we must not overwrite t_ctid,
                               5214                 :                :      * because it was set by the updater.  Moreover, if the tuple has been
                               5215                 :                :      * updated, we need to follow the update chain to lock the new versions of
                               5216                 :                :      * the tuple as well.
                               5217                 :                :      */
 4711 alvherre@alvh.no-ip.     5218         [ +  + ]:         156586 :     if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
                               5219                 :         154439 :         tuple->t_data->t_ctid = *tid;
                               5220                 :                : 
                               5221                 :                :     /* Clear only the all-frozen bit on visibility map if needed */
 3439 andres@anarazel.de       5222   [ +  +  +  + ]:         158252 :     if (PageIsAllVisible(page) &&
                               5223                 :           1666 :         visibilitymap_clear(relation, block, vmbuffer,
                               5224                 :                :                             VISIBILITYMAP_ALL_FROZEN))
                               5225                 :             14 :         cleared_all_frozen = true;
                               5226                 :                : 
                               5227                 :                : 
  615 akorotkov@postgresql     5228                 :         156586 :     MarkBufferDirty(*buffer);
                               5229                 :                : 
                               5230                 :                :     /*
                               5231                 :                :      * XLOG stuff.  You might think that we don't need an XLOG record because
                               5232                 :                :      * there is no state change worth restoring after a crash.  You would be
                               5233                 :                :      * wrong however: we have just written either a TransactionId or a
                               5234                 :                :      * MultiXactId that may never have been seen on disk before, and we need
                               5235                 :                :      * to make sure that there are XLOG entries covering those ID numbers.
                               5236                 :                :      * Else the same IDs might be re-used after a crash, which would be
                               5237                 :                :      * disastrous if this page made it to disk before the crash.  Essentially
                               5238                 :                :      * we have to enforce the WAL log-before-data rule even in this case.
                               5239                 :                :      * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
                               5240                 :                :      * entries for everything anyway.)
                               5241                 :                :      */
 5483 rhaas@postgresql.org     5242   [ +  +  +  +  :         156586 :     if (RelationNeedsWAL(relation))
                                        +  -  +  - ]
                               5243                 :                :     {
                               5244                 :                :         xl_heap_lock xlrec;
                               5245                 :                :         XLogRecPtr  recptr;
                               5246                 :                : 
 4045 heikki.linnakangas@i     5247                 :         156242 :         XLogBeginInsert();
  615 akorotkov@postgresql     5248                 :         156242 :         XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
                               5249                 :                : 
 4045 heikki.linnakangas@i     5250                 :         156242 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
  981 pg@bowt.ie               5251                 :         156242 :         xlrec.xmax = xid;
 4711 alvherre@alvh.no-ip.     5252                 :         312484 :         xlrec.infobits_set = compute_infobits(new_infomask,
                               5253                 :         156242 :                                               tuple->t_data->t_infomask2);
 3439 andres@anarazel.de       5254                 :         156242 :         xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
  309 peter@eisentraut.org     5255                 :         156242 :         XLogRegisterData(&xlrec, SizeOfHeapLock);
                               5256                 :                : 
                               5257                 :                :         /* we don't decode row locks atm, so no need to log the origin */
                               5258                 :                : 
 4045 heikki.linnakangas@i     5259                 :         156242 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
                               5260                 :                : 
 6366 tgl@sss.pgh.pa.us        5261                 :         156242 :         PageSetLSN(page, recptr);
                               5262                 :                :     }
                               5263                 :                : 
 7538                          5264         [ -  + ]:         156586 :     END_CRIT_SECTION();
                               5265                 :                : 
 2461 andres@anarazel.de       5266                 :         156586 :     result = TM_Ok;
                               5267                 :                : 
 3439                          5268                 :         156875 : out_locked:
  615 akorotkov@postgresql     5269                 :         156875 :     LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
                               5270                 :                : 
 3439 andres@anarazel.de       5271                 :         158386 : out_unlocked:
                               5272         [ +  + ]:         158386 :     if (BufferIsValid(vmbuffer))
                               5273                 :           1666 :         ReleaseBuffer(vmbuffer);
                               5274                 :                : 
                               5275                 :                :     /*
                               5276                 :                :      * Don't update the visibility map here. Locking a tuple doesn't change
                               5277                 :                :      * visibility info.
                               5278                 :                :      */
                               5279                 :                : 
                               5280                 :                :     /*
                               5281                 :                :      * Now that we have successfully marked the tuple as locked, we can
                               5282                 :                :      * release the lmgr tuple lock, if we had it.
                               5283                 :                :      */
 7536 tgl@sss.pgh.pa.us        5284         [ +  + ]:         158386 :     if (have_tuple_lock)
 4711 alvherre@alvh.no-ip.     5285                 :            156 :         UnlockTupleTuplock(relation, tid, mode);
                               5286                 :                : 
 3439 andres@anarazel.de       5287                 :         158386 :     return result;
                               5288                 :                : }
                               5289                 :                : 
                               5290                 :                : /*
                               5291                 :                :  * Acquire heavyweight lock on the given tuple, in preparation for acquiring
                               5292                 :                :  * its normal, Xmax-based tuple lock.
                               5293                 :                :  *
                               5294                 :                :  * have_tuple_lock is an input and output parameter: on input, it indicates
                               5295                 :                :  * whether the lock has previously been acquired (and this function does
                               5296                 :                :  * nothing in that case).  If this function returns success, have_tuple_lock
                               5297                 :                :  * has been flipped to true.
                               5298                 :                :  *
                               5299                 :                :  * Returns false if it was unable to obtain the lock; this can only happen if
                               5300                 :                :  * wait_policy is Skip.
                               5301                 :                :  */
                               5302                 :                : static bool
   48 peter@eisentraut.org     5303                 :GNC         309 : heap_acquire_tuplock(Relation relation, const ItemPointerData *tid, LockTupleMode mode,
                               5304                 :                :                      LockWaitPolicy wait_policy, bool *have_tuple_lock)
                               5305                 :                : {
 4009 alvherre@alvh.no-ip.     5306         [ +  + ]:CBC         309 :     if (*have_tuple_lock)
                               5307                 :              9 :         return true;
                               5308                 :                : 
                               5309   [ +  +  +  - ]:            300 :     switch (wait_policy)
                               5310                 :                :     {
                               5311                 :            259 :         case LockWaitBlock:
                               5312                 :            259 :             LockTupleTuplock(relation, tid, mode);
                               5313                 :            259 :             break;
                               5314                 :                : 
                               5315                 :             34 :         case LockWaitSkip:
  278 fujii@postgresql.org     5316         [ +  + ]:             34 :             if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
 4009 alvherre@alvh.no-ip.     5317                 :              1 :                 return false;
                               5318                 :             33 :             break;
                               5319                 :                : 
                               5320                 :              7 :         case LockWaitError:
  197 fujii@postgresql.org     5321         [ +  + ]:              7 :             if (!ConditionalLockTupleTuplock(relation, tid, mode, log_lock_failures))
 4009 alvherre@alvh.no-ip.     5322         [ +  - ]:              1 :                 ereport(ERROR,
                               5323                 :                :                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                               5324                 :                :                          errmsg("could not obtain lock on row in relation \"%s\"",
                               5325                 :                :                                 RelationGetRelationName(relation))));
                               5326                 :              6 :             break;
                               5327                 :                :     }
                               5328                 :            298 :     *have_tuple_lock = true;
                               5329                 :                : 
                               5330                 :            298 :     return true;
                               5331                 :                : }
                               5332                 :                : 
                               5333                 :                : /*
                               5334                 :                :  * Given an original set of Xmax and infomask, and a transaction (identified by
                               5335                 :                :  * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
                               5336                 :                :  * corresponding infomasks to use on the tuple.
                               5337                 :                :  *
                               5338                 :                :  * Note that this might have side effects such as creating a new MultiXactId.
                               5339                 :                :  *
                               5340                 :                :  * Most callers will have called HeapTupleSatisfiesUpdate before this function;
                               5341                 :                :  * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
                               5342                 :                :  * but it was not running anymore. There is a race condition, which is that the
                               5343                 :                :  * MultiXactId may have finished since then, but that uncommon case is handled
                               5344                 :                :  * either here, or within MultiXactIdExpand.
                               5345                 :                :  *
                               5346                 :                :  * There is a similar race condition possible when the old xmax was a regular
                               5347                 :                :  * TransactionId.  We test TransactionIdIsInProgress again just to narrow the
                               5348                 :                :  * window, but it's still possible to end up creating an unnecessary
                               5349                 :                :  * MultiXactId.  Fortunately this is harmless.
                               5350                 :                :  */
                               5351                 :                : static void
 4711                          5352                 :        2077283 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
                               5353                 :                :                           uint16 old_infomask2, TransactionId add_to_xmax,
                               5354                 :                :                           LockTupleMode mode, bool is_update,
                               5355                 :                :                           TransactionId *result_xmax, uint16 *result_infomask,
                               5356                 :                :                           uint16 *result_infomask2)
                               5357                 :                : {
                               5358                 :                :     TransactionId new_xmax;
                               5359                 :                :     uint16      new_infomask,
                               5360                 :                :                 new_infomask2;
                               5361                 :                : 
 4381                          5362         [ +  - ]:        2077283 :     Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
                               5363                 :                : 
 4711                          5364                 :        2181252 : l5:
                               5365                 :        2181252 :     new_infomask = 0;
                               5366                 :        2181252 :     new_infomask2 = 0;
                               5367         [ +  + ]:        2181252 :     if (old_infomask & HEAP_XMAX_INVALID)
                               5368                 :                :     {
                               5369                 :                :         /*
                               5370                 :                :          * No previous locker; we just insert our own TransactionId.
                               5371                 :                :          *
                               5372                 :                :          * Note that it's critical that this case be the first one checked,
                               5373                 :                :          * because there are several blocks below that come back to this one
                               5374                 :                :          * to implement certain optimizations; old_infomask might contain
                               5375                 :                :          * other dirty bits in those cases, but we don't really care.
                               5376                 :                :          */
                               5377         [ +  + ]:        2000653 :         if (is_update)
                               5378                 :                :         {
                               5379                 :        1766173 :             new_xmax = add_to_xmax;
                               5380         [ +  + ]:        1766173 :             if (mode == LockTupleExclusive)
                               5381                 :        1490725 :                 new_infomask2 |= HEAP_KEYS_UPDATED;
                               5382                 :                :         }
                               5383                 :                :         else
                               5384                 :                :         {
                               5385                 :         234480 :             new_infomask |= HEAP_XMAX_LOCK_ONLY;
                               5386   [ +  +  +  +  :         234480 :             switch (mode)
                                                 - ]
                               5387                 :                :             {
                               5388                 :           2633 :                 case LockTupleKeyShare:
                               5389                 :           2633 :                     new_xmax = add_to_xmax;
                               5390                 :           2633 :                     new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
                               5391                 :           2633 :                     break;
                               5392                 :            745 :                 case LockTupleShare:
                               5393                 :            745 :                     new_xmax = add_to_xmax;
                               5394                 :            745 :                     new_infomask |= HEAP_XMAX_SHR_LOCK;
                               5395                 :            745 :                     break;
                               5396                 :         135433 :                 case LockTupleNoKeyExclusive:
                               5397                 :         135433 :                     new_xmax = add_to_xmax;
                               5398                 :         135433 :                     new_infomask |= HEAP_XMAX_EXCL_LOCK;
                               5399                 :         135433 :                     break;
                               5400                 :          95669 :                 case LockTupleExclusive:
                               5401                 :          95669 :                     new_xmax = add_to_xmax;
                               5402                 :          95669 :                     new_infomask |= HEAP_XMAX_EXCL_LOCK;
                               5403                 :          95669 :                     new_infomask2 |= HEAP_KEYS_UPDATED;
                               5404                 :          95669 :                     break;
 4711 alvherre@alvh.no-ip.     5405                 :UBC           0 :                 default:
                               5406                 :              0 :                     new_xmax = InvalidTransactionId;    /* silence compiler */
                               5407         [ #  # ]:              0 :                     elog(ERROR, "invalid lock mode");
                               5408                 :                :             }
                               5409                 :                :         }
                               5410                 :                :     }
 4711 alvherre@alvh.no-ip.     5411         [ +  + ]:CBC      180599 :     else if (old_infomask & HEAP_XMAX_IS_MULTI)
                               5412                 :                :     {
                               5413                 :                :         MultiXactStatus new_status;
                               5414                 :                : 
                               5415                 :                :         /*
                               5416                 :                :          * Currently we don't allow XMAX_COMMITTED to be set for multis, so
                               5417                 :                :          * cross-check.
                               5418                 :                :          */
                               5419         [ -  + ]:          75570 :         Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
                               5420                 :                : 
                               5421                 :                :         /*
                               5422                 :                :          * A multixact together with LOCK_ONLY set but neither lock bit set
                               5423                 :                :          * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
                               5424                 :                :          * anymore.  This check is critical for databases upgraded by
                               5425                 :                :          * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
                               5426                 :                :          * that such multis are never passed.
                               5427                 :                :          */
 3463                          5428         [ -  + ]:          75570 :         if (HEAP_LOCKED_UPGRADED(old_infomask))
                               5429                 :                :         {
 4711 alvherre@alvh.no-ip.     5430                 :UBC           0 :             old_infomask &= ~HEAP_XMAX_IS_MULTI;
                               5431                 :              0 :             old_infomask |= HEAP_XMAX_INVALID;
                               5432                 :              0 :             goto l5;
                               5433                 :                :         }
                               5434                 :                : 
                               5435                 :                :         /*
                               5436                 :                :          * If the XMAX is already a MultiXactId, then we need to expand it to
                               5437                 :                :          * include add_to_xmax; but if all the members were lockers and are
                               5438                 :                :          * all gone, we can do away with the IS_MULTI bit and just set
                               5439                 :                :          * add_to_xmax as the only locker/updater.  If all lockers are gone
                               5440                 :                :          * and we have an updater that aborted, we can also do without a
                               5441                 :                :          * multi.
                               5442                 :                :          *
                               5443                 :                :          * The cost of doing GetMultiXactIdMembers would be paid by
                               5444                 :                :          * MultiXactIdExpand if we weren't to do this, so this check is not
                               5445                 :                :          * incurring extra work anyhow.
                               5446                 :                :          */
 4159 alvherre@alvh.no-ip.     5447         [ +  + ]:CBC       75570 :         if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
                               5448                 :                :         {
 4711                          5449         [ +  + ]:             24 :             if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
 3904                          5450         [ +  - ]:              8 :                 !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
                               5451                 :                :                                                                 old_infomask)))
                               5452                 :                :             {
                               5453                 :                :                 /*
                               5454                 :                :                  * Reset these bits and restart; otherwise fall through to
                               5455                 :                :                  * create a new multi below.
                               5456                 :                :                  */
 4711                          5457                 :             24 :                 old_infomask &= ~HEAP_XMAX_IS_MULTI;
                               5458                 :             24 :                 old_infomask |= HEAP_XMAX_INVALID;
                               5459                 :             24 :                 goto l5;
                               5460                 :                :             }
                               5461                 :                :         }
                               5462                 :                : 
                               5463                 :          75546 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5464                 :                : 
                               5465                 :          75546 :         new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
                               5466                 :                :                                      new_status);
                               5467                 :          75546 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5468                 :                :     }
                               5469         [ +  + ]:         105029 :     else if (old_infomask & HEAP_XMAX_COMMITTED)
                               5470                 :                :     {
                               5471                 :                :         /*
                               5472                 :                :          * It's a committed update, so we need to preserve him as updater of
                               5473                 :                :          * the tuple.
                               5474                 :                :          */
                               5475                 :                :         MultiXactStatus status;
                               5476                 :                :         MultiXactStatus new_status;
                               5477                 :                : 
                               5478         [ -  + ]:             13 :         if (old_infomask2 & HEAP_KEYS_UPDATED)
 4711 alvherre@alvh.no-ip.     5479                 :UBC           0 :             status = MultiXactStatusUpdate;
                               5480                 :                :         else
 4711 alvherre@alvh.no-ip.     5481                 :CBC          13 :             status = MultiXactStatusNoKeyUpdate;
                               5482                 :                : 
                               5483                 :             13 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5484                 :                : 
                               5485                 :                :         /*
                               5486                 :                :          * since it's not running, it's obviously impossible for the old
                               5487                 :                :          * updater to be identical to the current one, so we need not check
                               5488                 :                :          * for that case as we do in the block above.
                               5489                 :                :          */
                               5490                 :             13 :         new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
                               5491                 :             13 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5492                 :                :     }
                               5493         [ +  + ]:         105016 :     else if (TransactionIdIsInProgress(xmax))
                               5494                 :                :     {
                               5495                 :                :         /*
                               5496                 :                :          * If the XMAX is a valid, in-progress TransactionId, then we need to
                               5497                 :                :          * create a new MultiXactId that includes both the old locker or
                               5498                 :                :          * updater and our own TransactionId.
                               5499                 :                :          */
                               5500                 :                :         MultiXactStatus new_status;
                               5501                 :                :         MultiXactStatus old_status;
                               5502                 :                :         LockTupleMode old_mode;
                               5503                 :                : 
                               5504         [ +  + ]:         105007 :         if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
                               5505                 :                :         {
                               5506         [ +  + ]:         104981 :             if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
 4381                          5507                 :           5671 :                 old_status = MultiXactStatusForKeyShare;
 4711                          5508         [ +  + ]:          99310 :             else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
 4381                          5509                 :            433 :                 old_status = MultiXactStatusForShare;
 4711                          5510         [ +  - ]:          98877 :             else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
                               5511                 :                :             {
                               5512         [ +  + ]:          98877 :                 if (old_infomask2 & HEAP_KEYS_UPDATED)
 4381                          5513                 :          92739 :                     old_status = MultiXactStatusForUpdate;
                               5514                 :                :                 else
                               5515                 :           6138 :                     old_status = MultiXactStatusForNoKeyUpdate;
                               5516                 :                :             }
                               5517                 :                :             else
                               5518                 :                :             {
                               5519                 :                :                 /*
                               5520                 :                :                  * LOCK_ONLY can be present alone only when a page has been
                               5521                 :                :                  * upgraded by pg_upgrade.  But in that case,
                               5522                 :                :                  * TransactionIdIsInProgress() should have returned false.  We
                               5523                 :                :                  * assume it's no longer locked in this case.
                               5524                 :                :                  */
 4711 alvherre@alvh.no-ip.     5525         [ #  # ]:UBC           0 :                 elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
                               5526                 :              0 :                 old_infomask |= HEAP_XMAX_INVALID;
                               5527                 :              0 :                 old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
                               5528                 :              0 :                 goto l5;
                               5529                 :                :             }
                               5530                 :                :         }
                               5531                 :                :         else
                               5532                 :                :         {
                               5533                 :                :             /* it's an update, but which kind? */
 4711 alvherre@alvh.no-ip.     5534         [ -  + ]:CBC          26 :             if (old_infomask2 & HEAP_KEYS_UPDATED)
 4381 alvherre@alvh.no-ip.     5535                 :UBC           0 :                 old_status = MultiXactStatusUpdate;
                               5536                 :                :             else
 4381 alvherre@alvh.no-ip.     5537                 :CBC          26 :                 old_status = MultiXactStatusNoKeyUpdate;
                               5538                 :                :         }
                               5539                 :                : 
                               5540                 :         105007 :         old_mode = TUPLOCK_from_mxstatus(old_status);
                               5541                 :                : 
                               5542                 :                :         /*
                               5543                 :                :          * If the lock to be acquired is for the same TransactionId as the
                               5544                 :                :          * existing lock, there's an optimization possible: consider only the
                               5545                 :                :          * strongest of both locks as the only one present, and restart.
                               5546                 :                :          */
 4711                          5547         [ +  + ]:         105007 :         if (xmax == add_to_xmax)
                               5548                 :                :         {
                               5549                 :                :             /*
                               5550                 :                :              * Note that it's not possible for the original tuple to be
                               5551                 :                :              * updated: we wouldn't be here because the tuple would have been
                               5552                 :                :              * invisible and we wouldn't try to update it.  As a subtlety,
                               5553                 :                :              * this code can also run when traversing an update chain to lock
                               5554                 :                :              * future versions of a tuple.  But we wouldn't be here either,
                               5555                 :                :              * because the add_to_xmax would be different from the original
                               5556                 :                :              * updater.
                               5557                 :                :              */
 4381                          5558         [ -  + ]:         103937 :             Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
                               5559                 :                : 
                               5560                 :                :             /* acquire the strongest of both */
                               5561         [ +  + ]:         103937 :             if (mode < old_mode)
                               5562                 :          52176 :                 mode = old_mode;
                               5563                 :                :             /* mustn't touch is_update */
                               5564                 :                : 
                               5565                 :         103937 :             old_infomask |= HEAP_XMAX_INVALID;
                               5566                 :         103937 :             goto l5;
                               5567                 :                :         }
                               5568                 :                : 
                               5569                 :                :         /* otherwise, just fall back to creating a new multixact */
                               5570                 :           1070 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5571                 :           1070 :         new_xmax = MultiXactIdCreate(xmax, old_status,
                               5572                 :                :                                      add_to_xmax, new_status);
 4711                          5573                 :           1070 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5574                 :                :     }
                               5575   [ +  +  +  + ]:             14 :     else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
                               5576                 :              5 :              TransactionIdDidCommit(xmax))
                               5577                 :              1 :     {
                               5578                 :                :         /*
                               5579                 :                :          * It's a committed update, so we gotta preserve him as updater of the
                               5580                 :                :          * tuple.
                               5581                 :                :          */
                               5582                 :                :         MultiXactStatus status;
                               5583                 :                :         MultiXactStatus new_status;
                               5584                 :                : 
                               5585         [ -  + ]:              1 :         if (old_infomask2 & HEAP_KEYS_UPDATED)
 4711 alvherre@alvh.no-ip.     5586                 :UBC           0 :             status = MultiXactStatusUpdate;
                               5587                 :                :         else
 4711 alvherre@alvh.no-ip.     5588                 :CBC           1 :             status = MultiXactStatusNoKeyUpdate;
                               5589                 :                : 
                               5590                 :              1 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5591                 :                : 
                               5592                 :                :         /*
                               5593                 :                :          * since it's not running, it's obviously impossible for the old
                               5594                 :                :          * updater to be identical to the current one, so we need not check
                               5595                 :                :          * for that case as we do in the block above.
                               5596                 :                :          */
                               5597                 :              1 :         new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
                               5598                 :              1 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5599                 :                :     }
                               5600                 :                :     else
                               5601                 :                :     {
                               5602                 :                :         /*
                               5603                 :                :          * Can get here iff the locking/updating transaction was running when
                               5604                 :                :          * the infomask was extracted from the tuple, but finished before
                               5605                 :                :          * TransactionIdIsInProgress got to run.  Deal with it as if there was
                               5606                 :                :          * no locker at all in the first place.
                               5607                 :                :          */
                               5608                 :              8 :         old_infomask |= HEAP_XMAX_INVALID;
                               5609                 :              8 :         goto l5;
                               5610                 :                :     }
                               5611                 :                : 
                               5612                 :        2077283 :     *result_infomask = new_infomask;
                               5613                 :        2077283 :     *result_infomask2 = new_infomask2;
                               5614                 :        2077283 :     *result_xmax = new_xmax;
                               5615                 :        2077283 : }
                               5616                 :                : 
                               5617                 :                : /*
                               5618                 :                :  * Subroutine for heap_lock_updated_tuple_rec.
                               5619                 :                :  *
                               5620                 :                :  * Given a hypothetical multixact status held by the transaction identified
                               5621                 :                :  * with the given xid, does the current transaction need to wait, fail, or can
                               5622                 :                :  * it continue if it wanted to acquire a lock of the given mode?  "needwait"
                               5623                 :                :  * is set to true if waiting is necessary; if it can continue, then TM_Ok is
                               5624                 :                :  * returned.  If the lock is already held by the current transaction, return
                               5625                 :                :  * TM_SelfModified.  In case of a conflict with another transaction, a
                               5626                 :                :  * different HeapTupleSatisfiesUpdate return code is returned.
                               5627                 :                :  *
                               5628                 :                :  * The held status is said to be hypothetical because it might correspond to a
                               5629                 :                :  * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
                               5630                 :                :  * way for simplicity of API.
                               5631                 :                :  */
                               5632                 :                : static TM_Result
 4403                          5633                 :          38774 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
                               5634                 :                :                            LockTupleMode mode, HeapTuple tup,
                               5635                 :                :                            bool *needwait)
                               5636                 :                : {
                               5637                 :                :     MultiXactStatus wantedstatus;
                               5638                 :                : 
                               5639                 :          38774 :     *needwait = false;
                               5640                 :          38774 :     wantedstatus = get_mxact_status_for_lock(mode, false);
                               5641                 :                : 
                               5642                 :                :     /*
                               5643                 :                :      * Note: we *must* check TransactionIdIsInProgress before
                               5644                 :                :      * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
                               5645                 :                :      * for an explanation.
                               5646                 :                :      */
                               5647         [ -  + ]:          38774 :     if (TransactionIdIsCurrentTransactionId(xid))
                               5648                 :                :     {
                               5649                 :                :         /*
                               5650                 :                :          * The tuple has already been locked by our own transaction.  This is
                               5651                 :                :          * very rare but can happen if multiple transactions are trying to
                               5652                 :                :          * lock an ancient version of the same tuple.
                               5653                 :                :          */
 2461 andres@anarazel.de       5654                 :UBC           0 :         return TM_SelfModified;
                               5655                 :                :     }
 4403 alvherre@alvh.no-ip.     5656         [ +  + ]:CBC       38774 :     else if (TransactionIdIsInProgress(xid))
                               5657                 :                :     {
                               5658                 :                :         /*
                               5659                 :                :          * If the locking transaction is running, what we do depends on
                               5660                 :                :          * whether the lock modes conflict: if they do, then we must wait for
                               5661                 :                :          * it to finish; otherwise we can fall through to lock this tuple
                               5662                 :                :          * version without waiting.
                               5663                 :                :          */
                               5664         [ +  + ]:          36539 :         if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
                               5665                 :          36539 :                                 LOCKMODE_from_mxstatus(wantedstatus)))
                               5666                 :                :         {
                               5667                 :              8 :             *needwait = true;
                               5668                 :                :         }
                               5669                 :                : 
                               5670                 :                :         /*
                               5671                 :                :          * If we set needwait above, then this value doesn't matter;
                               5672                 :                :          * otherwise, this value signals to caller that it's okay to proceed.
                               5673                 :                :          */
 2461 andres@anarazel.de       5674                 :          36539 :         return TM_Ok;
                               5675                 :                :     }
 4403 alvherre@alvh.no-ip.     5676         [ +  + ]:           2235 :     else if (TransactionIdDidAbort(xid))
 2461 andres@anarazel.de       5677                 :            206 :         return TM_Ok;
 4403 alvherre@alvh.no-ip.     5678         [ +  - ]:           2029 :     else if (TransactionIdDidCommit(xid))
                               5679                 :                :     {
                               5680                 :                :         /*
                               5681                 :                :          * The other transaction committed.  If it was only a locker, then the
                               5682                 :                :          * lock is completely gone now and we can return success; but if it
                               5683                 :                :          * was an update, then what we do depends on whether the two lock
                               5684                 :                :          * modes conflict.  If they conflict, then we must report error to
                               5685                 :                :          * caller. But if they don't, we can fall through to allow the current
                               5686                 :                :          * transaction to lock the tuple.
                               5687                 :                :          *
                               5688                 :                :          * Note: the reason we worry about ISUPDATE here is because as soon as
                               5689                 :                :          * a transaction ends, all its locks are gone and meaningless, and
                               5690                 :                :          * thus we can ignore them; whereas its updates persist.  In the
                               5691                 :                :          * TransactionIdIsInProgress case, above, we don't need to check
                               5692                 :                :          * because we know the lock is still "alive" and thus a conflict needs
                               5693                 :                :          * always be checked.
                               5694                 :                :          */
 4395                          5695         [ +  + ]:           2029 :         if (!ISUPDATE_from_mxstatus(status))
 2461 andres@anarazel.de       5696                 :           2020 :             return TM_Ok;
                               5697                 :                : 
 4403 alvherre@alvh.no-ip.     5698         [ +  + ]:              9 :         if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
                               5699                 :              9 :                                 LOCKMODE_from_mxstatus(wantedstatus)))
                               5700                 :                :         {
                               5701                 :                :             /* bummer */
 1759                          5702         [ +  + ]:              8 :             if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
 2461 andres@anarazel.de       5703                 :              6 :                 return TM_Updated;
                               5704                 :                :             else
                               5705                 :              2 :                 return TM_Deleted;
                               5706                 :                :         }
                               5707                 :                : 
                               5708                 :              1 :         return TM_Ok;
                               5709                 :                :     }
                               5710                 :                : 
                               5711                 :                :     /* Not in progress, not aborted, not committed -- must have crashed */
 2461 andres@anarazel.de       5712                 :UBC           0 :     return TM_Ok;
                               5713                 :                : }
                               5714                 :                : 
                               5715                 :                : 
                               5716                 :                : /*
                               5717                 :                :  * Recursive part of heap_lock_updated_tuple
                               5718                 :                :  *
                               5719                 :                :  * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
                               5720                 :                :  * xid with the given mode; if this tuple is updated, recurse to lock the new
                               5721                 :                :  * version as well.
                               5722                 :                :  */
                               5723                 :                : static TM_Result
   48 peter@eisentraut.org     5724                 :GNC        2210 : heap_lock_updated_tuple_rec(Relation rel, const ItemPointerData *tid, TransactionId xid,
                               5725                 :                :                             LockTupleMode mode)
                               5726                 :                : {
                               5727                 :                :     TM_Result   result;
                               5728                 :                :     ItemPointerData tupid;
                               5729                 :                :     HeapTupleData mytup;
                               5730                 :                :     Buffer      buf;
                               5731                 :                :     uint16      new_infomask,
                               5732                 :                :                 new_infomask2,
                               5733                 :                :                 old_infomask,
                               5734                 :                :                 old_infomask2;
                               5735                 :                :     TransactionId xmax,
                               5736                 :                :                 new_xmax;
 4403 alvherre@alvh.no-ip.     5737                 :CBC        2210 :     TransactionId priorXmax = InvalidTransactionId;
 3439 andres@anarazel.de       5738                 :           2210 :     bool        cleared_all_frozen = false;
                               5739                 :                :     bool        pinned_desired_page;
                               5740                 :           2210 :     Buffer      vmbuffer = InvalidBuffer;
                               5741                 :                :     BlockNumber block;
                               5742                 :                : 
 4711 alvherre@alvh.no-ip.     5743                 :           2210 :     ItemPointerCopy(tid, &tupid);
                               5744                 :                : 
                               5745                 :                :     for (;;)
                               5746                 :                :     {
                               5747                 :           2213 :         new_infomask = 0;
                               5748                 :           2213 :         new_xmax = InvalidTransactionId;
 3439 andres@anarazel.de       5749                 :           2213 :         block = ItemPointerGetBlockNumber(&tupid);
 4711 alvherre@alvh.no-ip.     5750                 :           2213 :         ItemPointerCopy(&tupid, &(mytup.t_self));
                               5751                 :                : 
 1344 tgl@sss.pgh.pa.us        5752         [ +  - ]:           2213 :         if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
                               5753                 :                :         {
                               5754                 :                :             /*
                               5755                 :                :              * if we fail to find the updated version of the tuple, it's
                               5756                 :                :              * because it was vacuumed/pruned away after its creator
                               5757                 :                :              * transaction aborted.  So behave as if we got to the end of the
                               5758                 :                :              * chain, and there's no further tuple to lock: return success to
                               5759                 :                :              * caller.
                               5760                 :                :              */
 2461 andres@anarazel.de       5761                 :UBC           0 :             result = TM_Ok;
 2847 tgl@sss.pgh.pa.us        5762                 :              0 :             goto out_unlocked;
                               5763                 :                :         }
                               5764                 :                : 
 4711 alvherre@alvh.no-ip.     5765                 :CBC        2213 : l4:
                               5766         [ -  + ]:           2221 :         CHECK_FOR_INTERRUPTS();
                               5767                 :                : 
                               5768                 :                :         /*
                               5769                 :                :          * Before locking the buffer, pin the visibility map page if it
                               5770                 :                :          * appears to be necessary.  Since we haven't got the lock yet,
                               5771                 :                :          * someone else might be in the middle of changing this, so we'll need
                               5772                 :                :          * to recheck after we have the lock.
                               5773                 :                :          */
 3439 andres@anarazel.de       5774         [ -  + ]:           2221 :         if (PageIsAllVisible(BufferGetPage(buf)))
                               5775                 :                :         {
 3439 andres@anarazel.de       5776                 :UBC           0 :             visibilitymap_pin(rel, block, &vmbuffer);
 2847 tgl@sss.pgh.pa.us        5777                 :              0 :             pinned_desired_page = true;
                               5778                 :                :         }
                               5779                 :                :         else
 2847 tgl@sss.pgh.pa.us        5780                 :CBC        2221 :             pinned_desired_page = false;
                               5781                 :                : 
 4711 alvherre@alvh.no-ip.     5782                 :           2221 :         LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
                               5783                 :                : 
                               5784                 :                :         /*
                               5785                 :                :          * If we didn't pin the visibility map page and the page has become
                               5786                 :                :          * all visible while we were busy locking the buffer, we'll have to
                               5787                 :                :          * unlock and re-lock, to avoid holding the buffer lock across I/O.
                               5788                 :                :          * That's a bit unfortunate, but hopefully shouldn't happen often.
                               5789                 :                :          *
                               5790                 :                :          * Note: in some paths through this function, we will reach here
                               5791                 :                :          * holding a pin on a vm page that may or may not be the one matching
                               5792                 :                :          * this page.  If this page isn't all-visible, we won't use the vm
                               5793                 :                :          * page, but we hold onto such a pin till the end of the function.
                               5794                 :                :          */
 2847 tgl@sss.pgh.pa.us        5795   [ +  -  -  + ]:           2221 :         if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
                               5796                 :                :         {
 3422 andres@anarazel.de       5797                 :UBC           0 :             LockBuffer(buf, BUFFER_LOCK_UNLOCK);
                               5798                 :              0 :             visibilitymap_pin(rel, block, &vmbuffer);
                               5799                 :              0 :             LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
                               5800                 :                :         }
                               5801                 :                : 
                               5802                 :                :         /*
                               5803                 :                :          * Check the tuple XMIN against prior XMAX, if any.  If we reached the
                               5804                 :                :          * end of the chain, we're done, so return success.
                               5805                 :                :          */
 4403 alvherre@alvh.no-ip.     5806   [ +  +  -  + ]:CBC        2224 :         if (TransactionIdIsValid(priorXmax) &&
 2967                          5807                 :              3 :             !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
                               5808                 :                :                                  priorXmax))
                               5809                 :                :         {
 2461 andres@anarazel.de       5810                 :UBC           0 :             result = TM_Ok;
 3439                          5811                 :              0 :             goto out_locked;
                               5812                 :                :         }
                               5813                 :                : 
                               5814                 :                :         /*
                               5815                 :                :          * Also check Xmin: if this tuple was created by an aborted
                               5816                 :                :          * (sub)transaction, then we already locked the last live one in the
                               5817                 :                :          * chain, thus we're done, so return success.
                               5818                 :                :          */
 3386 alvherre@alvh.no-ip.     5819         [ +  + ]:CBC        2221 :         if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
                               5820                 :                :         {
 2461 andres@anarazel.de       5821                 :             24 :             result = TM_Ok;
 2847 tgl@sss.pgh.pa.us        5822                 :             24 :             goto out_locked;
                               5823                 :                :         }
                               5824                 :                : 
 4711 alvherre@alvh.no-ip.     5825                 :           2197 :         old_infomask = mytup.t_data->t_infomask;
 4403                          5826                 :           2197 :         old_infomask2 = mytup.t_data->t_infomask2;
 4711                          5827                 :           2197 :         xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
                               5828                 :                : 
                               5829                 :                :         /*
                               5830                 :                :          * If this tuple version has been updated or locked by some concurrent
                               5831                 :                :          * transaction(s), what we do depends on whether our lock mode
                               5832                 :                :          * conflicts with what those other transactions hold, and also on the
                               5833                 :                :          * status of them.
                               5834                 :                :          */
 4403                          5835         [ +  + ]:           2197 :         if (!(old_infomask & HEAP_XMAX_INVALID))
                               5836                 :                :         {
                               5837                 :                :             TransactionId rawxmax;
                               5838                 :                :             bool        needwait;
                               5839                 :                : 
                               5840                 :           2138 :             rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
                               5841         [ +  + ]:           2138 :             if (old_infomask & HEAP_XMAX_IS_MULTI)
                               5842                 :                :             {
                               5843                 :                :                 int         nmembers;
                               5844                 :                :                 int         i;
                               5845                 :                :                 MultiXactMember *members;
                               5846                 :                : 
                               5847                 :                :                 /*
                               5848                 :                :                  * We don't need a test for pg_upgrade'd tuples: this is only
                               5849                 :                :                  * applied to tuples after the first in an update chain.  Said
                               5850                 :                :                  * first tuple in the chain may well be locked-in-9.2-and-
                               5851                 :                :                  * pg_upgraded, but that one was already locked by our caller,
                               5852                 :                :                  * not us; and any subsequent ones cannot be because our
                               5853                 :                :                  * caller must necessarily have obtained a snapshot later than
                               5854                 :                :                  * the pg_upgrade itself.
                               5855                 :                :                  */
 3463                          5856         [ -  + ]:           2109 :                 Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
                               5857                 :                : 
 4159                          5858                 :           2109 :                 nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
 3101 tgl@sss.pgh.pa.us        5859                 :           2109 :                                                  HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
 4403 alvherre@alvh.no-ip.     5860         [ +  + ]:          40854 :                 for (i = 0; i < nmembers; i++)
                               5861                 :                :                 {
 3439 andres@anarazel.de       5862                 :          38745 :                     result = test_lockmode_for_conflict(members[i].status,
                               5863                 :          38745 :                                                         members[i].xid,
                               5864                 :                :                                                         mode,
                               5865                 :                :                                                         &mytup,
                               5866                 :                :                                                         &needwait);
                               5867                 :                : 
                               5868                 :                :                     /*
                               5869                 :                :                      * If the tuple was already locked by ourselves in a
                               5870                 :                :                      * previous iteration of this (say heap_lock_tuple was
                               5871                 :                :                      * forced to restart the locking loop because of a change
                               5872                 :                :                      * in xmax), then we hold the lock already on this tuple
                               5873                 :                :                      * version and we don't need to do anything; and this is
                               5874                 :                :                      * not an error condition either.  We just need to skip
                               5875                 :                :                      * this tuple and continue locking the next version in the
                               5876                 :                :                      * update chain.
                               5877                 :                :                      */
 2461                          5878         [ -  + ]:          38745 :                     if (result == TM_SelfModified)
                               5879                 :                :                     {
 3066 alvherre@alvh.no-ip.     5880                 :UBC           0 :                         pfree(members);
                               5881                 :              0 :                         goto next;
                               5882                 :                :                     }
                               5883                 :                : 
 4403 alvherre@alvh.no-ip.     5884         [ -  + ]:CBC       38745 :                     if (needwait)
                               5885                 :                :                     {
 4403 alvherre@alvh.no-ip.     5886                 :UBC           0 :                         LockBuffer(buf, BUFFER_LOCK_UNLOCK);
 4291                          5887                 :              0 :                         XactLockTableWait(members[i].xid, rel,
                               5888                 :                :                                           &mytup.t_self,
                               5889                 :                :                                           XLTW_LockUpdated);
 4403                          5890                 :              0 :                         pfree(members);
                               5891                 :              0 :                         goto l4;
                               5892                 :                :                     }
 2461 andres@anarazel.de       5893         [ -  + ]:CBC       38745 :                     if (result != TM_Ok)
                               5894                 :                :                     {
 4403 alvherre@alvh.no-ip.     5895                 :UBC           0 :                         pfree(members);
 3439 andres@anarazel.de       5896                 :              0 :                         goto out_locked;
                               5897                 :                :                     }
                               5898                 :                :                 }
 4403 alvherre@alvh.no-ip.     5899         [ +  - ]:CBC        2109 :                 if (members)
                               5900                 :           2109 :                     pfree(members);
                               5901                 :                :             }
                               5902                 :                :             else
                               5903                 :                :             {
                               5904                 :                :                 MultiXactStatus status;
                               5905                 :                : 
                               5906                 :                :                 /*
                               5907                 :                :                  * For a non-multi Xmax, we first need to compute the
                               5908                 :                :                  * corresponding MultiXactStatus by using the infomask bits.
                               5909                 :                :                  */
                               5910         [ +  + ]:             29 :                 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
                               5911                 :                :                 {
                               5912         [ +  - ]:             10 :                     if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
                               5913                 :             10 :                         status = MultiXactStatusForKeyShare;
 4403 alvherre@alvh.no-ip.     5914         [ #  # ]:UBC           0 :                     else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
                               5915                 :              0 :                         status = MultiXactStatusForShare;
                               5916         [ #  # ]:              0 :                     else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
                               5917                 :                :                     {
                               5918         [ #  # ]:              0 :                         if (old_infomask2 & HEAP_KEYS_UPDATED)
                               5919                 :              0 :                             status = MultiXactStatusForUpdate;
                               5920                 :                :                         else
                               5921                 :              0 :                             status = MultiXactStatusForNoKeyUpdate;
                               5922                 :                :                     }
                               5923                 :                :                     else
                               5924                 :                :                     {
                               5925                 :                :                         /*
                               5926                 :                :                          * LOCK_ONLY present alone (a pg_upgraded tuple marked
                               5927                 :                :                          * as share-locked in the old cluster) shouldn't be
                               5928                 :                :                          * seen in the middle of an update chain.
                               5929                 :                :                          */
                               5930         [ #  # ]:              0 :                         elog(ERROR, "invalid lock status in tuple");
                               5931                 :                :                     }
                               5932                 :                :                 }
                               5933                 :                :                 else
                               5934                 :                :                 {
                               5935                 :                :                     /* it's an update, but which kind? */
 4403 alvherre@alvh.no-ip.     5936         [ +  + ]:CBC          19 :                     if (old_infomask2 & HEAP_KEYS_UPDATED)
                               5937                 :             14 :                         status = MultiXactStatusUpdate;
                               5938                 :                :                     else
                               5939                 :              5 :                         status = MultiXactStatusNoKeyUpdate;
                               5940                 :                :                 }
                               5941                 :                : 
 3439 andres@anarazel.de       5942                 :             29 :                 result = test_lockmode_for_conflict(status, rawxmax, mode,
                               5943                 :                :                                                     &mytup, &needwait);
                               5944                 :                : 
                               5945                 :                :                 /*
                               5946                 :                :                  * If the tuple was already locked by ourselves in a previous
                               5947                 :                :                  * iteration of this (say heap_lock_tuple was forced to
                               5948                 :                :                  * restart the locking loop because of a change in xmax), then
                               5949                 :                :                  * we hold the lock already on this tuple version and we don't
                               5950                 :                :                  * need to do anything; and this is not an error condition
                               5951                 :                :                  * either.  We just need to skip this tuple and continue
                               5952                 :                :                  * locking the next version in the update chain.
                               5953                 :                :                  */
 2461                          5954         [ -  + ]:             29 :                 if (result == TM_SelfModified)
 3066 alvherre@alvh.no-ip.     5955                 :UBC           0 :                     goto next;
                               5956                 :                : 
 4403 alvherre@alvh.no-ip.     5957         [ +  + ]:CBC          29 :                 if (needwait)
                               5958                 :                :                 {
                               5959                 :              8 :                     LockBuffer(buf, BUFFER_LOCK_UNLOCK);
 3969 heikki.linnakangas@i     5960                 :              8 :                     XactLockTableWait(rawxmax, rel, &mytup.t_self,
                               5961                 :                :                                       XLTW_LockUpdated);
 4403 alvherre@alvh.no-ip.     5962                 :              8 :                     goto l4;
                               5963                 :                :                 }
 2461 andres@anarazel.de       5964         [ +  + ]:             21 :                 if (result != TM_Ok)
                               5965                 :                :                 {
 3439                          5966                 :              8 :                     goto out_locked;
                               5967                 :                :                 }
                               5968                 :                :             }
                               5969                 :                :         }
                               5970                 :                : 
                               5971                 :                :         /* compute the new Xmax and infomask values for the tuple ... */
 4711 alvherre@alvh.no-ip.     5972                 :           2181 :         compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
                               5973                 :                :                                   xid, mode, false,
                               5974                 :                :                                   &new_xmax, &new_infomask, &new_infomask2);
                               5975                 :                : 
 3439 andres@anarazel.de       5976   [ -  +  -  - ]:           2181 :         if (PageIsAllVisible(BufferGetPage(buf)) &&
 3439 andres@anarazel.de       5977                 :UBC           0 :             visibilitymap_clear(rel, block, vmbuffer,
                               5978                 :                :                                 VISIBILITYMAP_ALL_FROZEN))
                               5979                 :              0 :             cleared_all_frozen = true;
                               5980                 :                : 
 4711 alvherre@alvh.no-ip.     5981                 :CBC        2181 :         START_CRIT_SECTION();
                               5982                 :                : 
                               5983                 :                :         /* ... and set them */
                               5984                 :           2181 :         HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
                               5985                 :           2181 :         mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
                               5986                 :           2181 :         mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               5987                 :           2181 :         mytup.t_data->t_infomask |= new_infomask;
                               5988                 :           2181 :         mytup.t_data->t_infomask2 |= new_infomask2;
                               5989                 :                : 
                               5990                 :           2181 :         MarkBufferDirty(buf);
                               5991                 :                : 
                               5992                 :                :         /* XLOG stuff */
                               5993   [ +  -  +  +  :           2181 :         if (RelationNeedsWAL(rel))
                                        +  -  +  - ]
                               5994                 :                :         {
                               5995                 :                :             xl_heap_lock_updated xlrec;
                               5996                 :                :             XLogRecPtr  recptr;
 3528 kgrittn@postgresql.o     5997                 :           2181 :             Page        page = BufferGetPage(buf);
                               5998                 :                : 
 4045 heikki.linnakangas@i     5999                 :           2181 :             XLogBeginInsert();
                               6000                 :           2181 :             XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
                               6001                 :                : 
                               6002                 :           2181 :             xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
 4711 alvherre@alvh.no-ip.     6003                 :           2181 :             xlrec.xmax = new_xmax;
                               6004                 :           2181 :             xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
 3439 andres@anarazel.de       6005                 :           2181 :             xlrec.flags =
                               6006                 :           2181 :                 cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
                               6007                 :                : 
  309 peter@eisentraut.org     6008                 :           2181 :             XLogRegisterData(&xlrec, SizeOfHeapLockUpdated);
                               6009                 :                : 
 4045 heikki.linnakangas@i     6010                 :           2181 :             recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
                               6011                 :                : 
 4711 alvherre@alvh.no-ip.     6012                 :           2181 :             PageSetLSN(page, recptr);
                               6013                 :                :         }
                               6014                 :                : 
                               6015         [ -  + ]:           2181 :         END_CRIT_SECTION();
                               6016                 :                : 
 3066                          6017                 :           2181 : next:
                               6018                 :                :         /* if we find the end of update chain, we're done. */
 4711                          6019   [ +  -  +  - ]:           4362 :         if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
 2811 andres@anarazel.de       6020         [ +  + ]:           4362 :             HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
 4585 bruce@momjian.us         6021         [ +  + ]:           2185 :             ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
 4711 alvherre@alvh.no-ip.     6022                 :              4 :             HeapTupleHeaderIsOnlyLocked(mytup.t_data))
                               6023                 :                :         {
 2461 andres@anarazel.de       6024                 :           2178 :             result = TM_Ok;
 3439                          6025                 :           2178 :             goto out_locked;
                               6026                 :                :         }
                               6027                 :                : 
                               6028                 :                :         /* tail recursion */
 4403 alvherre@alvh.no-ip.     6029                 :              3 :         priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
 4711                          6030                 :              3 :         ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
                               6031                 :              3 :         UnlockReleaseBuffer(buf);
                               6032                 :                :     }
                               6033                 :                : 
                               6034                 :                :     result = TM_Ok;
                               6035                 :                : 
 3439 andres@anarazel.de       6036                 :           2210 : out_locked:
                               6037                 :           2210 :     UnlockReleaseBuffer(buf);
                               6038                 :                : 
 2847 tgl@sss.pgh.pa.us        6039                 :           2210 : out_unlocked:
 3439 andres@anarazel.de       6040         [ -  + ]:           2210 :     if (vmbuffer != InvalidBuffer)
 3439 andres@anarazel.de       6041                 :UBC           0 :         ReleaseBuffer(vmbuffer);
                               6042                 :                : 
 3439 andres@anarazel.de       6043                 :CBC        2210 :     return result;
                               6044                 :                : }
                               6045                 :                : 
                               6046                 :                : /*
                               6047                 :                :  * heap_lock_updated_tuple
                               6048                 :                :  *      Follow update chain when locking an updated tuple, acquiring locks (row
                               6049                 :                :  *      marks) on the updated versions.
                               6050                 :                :  *
                               6051                 :                :  * The initial tuple is assumed to be already locked.
                               6052                 :                :  *
                               6053                 :                :  * This function doesn't check visibility, it just unconditionally marks the
                               6054                 :                :  * tuple(s) as locked.  If any tuple in the updated chain is being deleted
                               6055                 :                :  * concurrently (or updated with the key being modified), sleep until the
                               6056                 :                :  * transaction doing it is finished.
                               6057                 :                :  *
                               6058                 :                :  * Note that we don't acquire heavyweight tuple locks on the tuples we walk
                               6059                 :                :  * when we have to wait for other transactions to release them, as opposed to
                               6060                 :                :  * what heap_lock_tuple does.  The reason is that having more than one
                               6061                 :                :  * transaction walking the chain is probably uncommon enough that risk of
                               6062                 :                :  * starvation is not likely: one of the preconditions for being here is that
                               6063                 :                :  * the snapshot in use predates the update that created this tuple (because we
                               6064                 :                :  * started at an earlier version of the tuple), but at the same time such a
                               6065                 :                :  * transaction cannot be using repeatable read or serializable isolation
                               6066                 :                :  * levels, because that would lead to a serializability failure.
                               6067                 :                :  */
                               6068                 :                : static TM_Result
   48 peter@eisentraut.org     6069                 :GNC        2226 : heap_lock_updated_tuple(Relation rel, HeapTuple tuple, const ItemPointerData *ctid,
                               6070                 :                :                         TransactionId xid, LockTupleMode mode)
                               6071                 :                : {
                               6072                 :                :     /*
                               6073                 :                :      * If the tuple has not been updated, or has moved into another partition
                               6074                 :                :      * (effectively a delete) stop here.
                               6075                 :                :      */
 2811 andres@anarazel.de       6076         [ +  + ]:CBC        2226 :     if (!HeapTupleHeaderIndicatesMovedPartitions(tuple->t_data) &&
                               6077         [ +  + ]:           2224 :         !ItemPointerEquals(&tuple->t_self, ctid))
                               6078                 :                :     {
                               6079                 :                :         /*
                               6080                 :                :          * If this is the first possibly-multixact-able operation in the
                               6081                 :                :          * current transaction, set my per-backend OldestMemberMXactId
                               6082                 :                :          * setting. We can be certain that the transaction will never become a
                               6083                 :                :          * member of any older MultiXactIds than that.  (We have to do this
                               6084                 :                :          * even if we end up just using our own TransactionId below, since
                               6085                 :                :          * some other backend could incorporate our XID into a MultiXact
                               6086                 :                :          * immediately afterwards.)
                               6087                 :                :          */
 4711 alvherre@alvh.no-ip.     6088                 :           2210 :         MultiXactIdSetOldestMember();
                               6089                 :                : 
                               6090                 :           2210 :         return heap_lock_updated_tuple_rec(rel, ctid, xid, mode);
                               6091                 :                :     }
                               6092                 :                : 
                               6093                 :                :     /* nothing to lock */
 2461 andres@anarazel.de       6094                 :             16 :     return TM_Ok;
                               6095                 :                : }
                               6096                 :                : 
                               6097                 :                : /*
                               6098                 :                :  *  heap_finish_speculative - mark speculative insertion as successful
                               6099                 :                :  *
                               6100                 :                :  * To successfully finish a speculative insertion we have to clear speculative
                               6101                 :                :  * token from tuple.  To do so the t_ctid field, which will contain a
                               6102                 :                :  * speculative token value, is modified in place to point to the tuple itself,
                               6103                 :                :  * which is characteristic of a newly inserted ordinary tuple.
                               6104                 :                :  *
                               6105                 :                :  * NB: It is not ok to commit without either finishing or aborting a
                               6106                 :                :  * speculative insertion.  We could treat speculative tuples of committed
                               6107                 :                :  * transactions implicitly as completed, but then we would have to be prepared
                               6108                 :                :  * to deal with speculative tokens on committed tuples.  That wouldn't be
                               6109                 :                :  * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
                               6110                 :                :  * but clearing the token at completion isn't very expensive either.
                               6111                 :                :  * An explicit confirmation WAL record also makes logical decoding simpler.
                               6112                 :                :  */
                               6113                 :                : void
   48 peter@eisentraut.org     6114                 :GNC        2074 : heap_finish_speculative(Relation relation, const ItemPointerData *tid)
                               6115                 :                : {
                               6116                 :                :     Buffer      buffer;
                               6117                 :                :     Page        page;
                               6118                 :                :     OffsetNumber offnum;
                               6119                 :                :     ItemId      lp;
                               6120                 :                :     HeapTupleHeader htup;
                               6121                 :                : 
 2461 andres@anarazel.de       6122                 :CBC        2074 :     buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
 3876                          6123                 :           2074 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
  110 peter@eisentraut.org     6124                 :GNC        2074 :     page = BufferGetPage(buffer);
                               6125                 :                : 
 2461 andres@anarazel.de       6126                 :CBC        2074 :     offnum = ItemPointerGetOffsetNumber(tid);
    2 tgl@sss.pgh.pa.us        6127   [ +  -  -  + ]:GNC        2074 :     if (offnum < 1 || offnum > PageGetMaxOffsetNumber(page))
    2 tgl@sss.pgh.pa.us        6128         [ #  # ]:UNC           0 :         elog(ERROR, "offnum out of range");
    2 tgl@sss.pgh.pa.us        6129                 :GNC        2074 :     lp = PageGetItemId(page, offnum);
                               6130         [ -  + ]:           2074 :     if (!ItemIdIsNormal(lp))
 3681 andres@anarazel.de       6131         [ #  # ]:UBC           0 :         elog(ERROR, "invalid lp");
                               6132                 :                : 
 3876 andres@anarazel.de       6133                 :CBC        2074 :     htup = (HeapTupleHeader) PageGetItem(page, lp);
                               6134                 :                : 
                               6135                 :                :     /* NO EREPORT(ERROR) from here till changes are logged */
                               6136                 :           2074 :     START_CRIT_SECTION();
                               6137                 :                : 
 2461                          6138         [ -  + ]:           2074 :     Assert(HeapTupleHeaderIsSpeculative(htup));
                               6139                 :                : 
 3876                          6140                 :           2074 :     MarkBufferDirty(buffer);
                               6141                 :                : 
                               6142                 :                :     /*
                               6143                 :                :      * Replace the speculative insertion token with a real t_ctid, pointing to
                               6144                 :                :      * itself like it does on regular tuples.
                               6145                 :                :      */
 2461                          6146                 :           2074 :     htup->t_ctid = *tid;
                               6147                 :                : 
                               6148                 :                :     /* XLOG stuff */
 3876                          6149   [ +  +  +  +  :           2074 :     if (RelationNeedsWAL(relation))
                                        +  -  +  - ]
                               6150                 :                :     {
                               6151                 :                :         xl_heap_confirm xlrec;
                               6152                 :                :         XLogRecPtr  recptr;
                               6153                 :                : 
 2461                          6154                 :           2065 :         xlrec.offnum = ItemPointerGetOffsetNumber(tid);
                               6155                 :                : 
 3876                          6156                 :           2065 :         XLogBeginInsert();
                               6157                 :                : 
                               6158                 :                :         /* We want the same filtering on this as on a plain insert */
 3282                          6159                 :           2065 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               6160                 :                : 
  309 peter@eisentraut.org     6161                 :           2065 :         XLogRegisterData(&xlrec, SizeOfHeapConfirm);
 3876 andres@anarazel.de       6162                 :           2065 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               6163                 :                : 
                               6164                 :           2065 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
                               6165                 :                : 
                               6166                 :           2065 :         PageSetLSN(page, recptr);
                               6167                 :                :     }
                               6168                 :                : 
                               6169         [ -  + ]:           2074 :     END_CRIT_SECTION();
                               6170                 :                : 
                               6171                 :           2074 :     UnlockReleaseBuffer(buffer);
                               6172                 :           2074 : }
                               6173                 :                : 
                               6174                 :                : /*
                               6175                 :                :  *  heap_abort_speculative - kill a speculatively inserted tuple
                               6176                 :                :  *
                               6177                 :                :  * Marks a tuple that was speculatively inserted in the same command as dead,
                               6178                 :                :  * by setting its xmin as invalid.  That makes it immediately appear as dead
                               6179                 :                :  * to all transactions, including our own.  In particular, it makes
                               6180                 :                :  * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
                               6181                 :                :  * inserting a duplicate key value won't unnecessarily wait for our whole
                               6182                 :                :  * transaction to finish (it'll just wait for our speculative insertion to
                               6183                 :                :  * finish).
                               6184                 :                :  *
                               6185                 :                :  * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
                               6186                 :                :  * that arise due to a mutual dependency that is not user visible.  By
                               6187                 :                :  * definition, unprincipled deadlocks cannot be prevented by the user
                               6188                 :                :  * reordering lock acquisition in client code, because the implementation level
                               6189                 :                :  * lock acquisitions are not under the user's direct control.  If speculative
                               6190                 :                :  * inserters did not take this precaution, then under high concurrency they
                               6191                 :                :  * could deadlock with each other, which would not be acceptable.
                               6192                 :                :  *
                               6193                 :                :  * This is somewhat redundant with heap_delete, but we prefer to have a
                               6194                 :                :  * dedicated routine with stripped down requirements.  Note that this is also
                               6195                 :                :  * used to delete the TOAST tuples created during speculative insertion.
                               6196                 :                :  *
                               6197                 :                :  * This routine does not affect logical decoding as it only looks at
                               6198                 :                :  * confirmation records.
                               6199                 :                :  */
                               6200                 :                : void
   48 peter@eisentraut.org     6201                 :GNC          10 : heap_abort_speculative(Relation relation, const ItemPointerData *tid)
                               6202                 :                : {
 3876 andres@anarazel.de       6203                 :CBC          10 :     TransactionId xid = GetCurrentTransactionId();
                               6204                 :                :     ItemId      lp;
                               6205                 :                :     HeapTupleData tp;
                               6206                 :                :     Page        page;
                               6207                 :                :     BlockNumber block;
                               6208                 :                :     Buffer      buffer;
                               6209                 :                : 
                               6210         [ -  + ]:             10 :     Assert(ItemPointerIsValid(tid));
                               6211                 :                : 
                               6212                 :             10 :     block = ItemPointerGetBlockNumber(tid);
                               6213                 :             10 :     buffer = ReadBuffer(relation, block);
 3528 kgrittn@postgresql.o     6214                 :             10 :     page = BufferGetPage(buffer);
                               6215                 :                : 
 3876 andres@anarazel.de       6216                 :             10 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               6217                 :                : 
                               6218                 :                :     /*
                               6219                 :                :      * Page can't be all visible, we just inserted into it, and are still
                               6220                 :                :      * running.
                               6221                 :                :      */
                               6222         [ -  + ]:             10 :     Assert(!PageIsAllVisible(page));
                               6223                 :                : 
                               6224                 :             10 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
                               6225         [ -  + ]:             10 :     Assert(ItemIdIsNormal(lp));
                               6226                 :                : 
                               6227                 :             10 :     tp.t_tableOid = RelationGetRelid(relation);
                               6228                 :             10 :     tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
                               6229                 :             10 :     tp.t_len = ItemIdGetLength(lp);
                               6230                 :             10 :     tp.t_self = *tid;
                               6231                 :                : 
                               6232                 :                :     /*
                               6233                 :                :      * Sanity check that the tuple really is a speculatively inserted tuple,
                               6234                 :                :      * inserted by us.
                               6235                 :                :      */
                               6236         [ -  + ]:             10 :     if (tp.t_data->t_choice.t_heap.t_xmin != xid)
 3876 andres@anarazel.de       6237         [ #  # ]:UBC           0 :         elog(ERROR, "attempted to kill a tuple inserted by another transaction");
 3409 andres@anarazel.de       6238   [ +  +  -  + ]:CBC          10 :     if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
 3876 andres@anarazel.de       6239         [ #  # ]:UBC           0 :         elog(ERROR, "attempted to kill a non-speculative tuple");
 3876 andres@anarazel.de       6240         [ -  + ]:CBC          10 :     Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
                               6241                 :                : 
                               6242                 :                :     /*
                               6243                 :                :      * No need to check for serializable conflicts here.  There is never a
                               6244                 :                :      * need for a combo CID, either.  No need to extract replica identity, or
                               6245                 :                :      * do anything special with infomask bits.
                               6246                 :                :      */
                               6247                 :                : 
                               6248                 :             10 :     START_CRIT_SECTION();
                               6249                 :                : 
                               6250                 :                :     /*
                               6251                 :                :      * The tuple will become DEAD immediately.  Flag that this page is a
                               6252                 :                :      * candidate for pruning by setting xmin to TransactionXmin. While not
                               6253                 :                :      * immediately prunable, it is the oldest xid we can cheaply determine
                               6254                 :                :      * that's safe against wraparound / being older than the table's
                               6255                 :                :      * relfrozenxid.  To defend against the unlikely case of a new relation
                               6256                 :                :      * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
                               6257                 :                :      * if so (vacuum can't subsequently move relfrozenxid to beyond
                               6258                 :                :      * TransactionXmin, so there's no race here).
                               6259                 :                :      */
 2082                          6260         [ -  + ]:             10 :     Assert(TransactionIdIsValid(TransactionXmin));
                               6261                 :                :     {
  597 noah@leadboat.com        6262                 :             10 :         TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
                               6263                 :                :         TransactionId prune_xid;
                               6264                 :                : 
                               6265         [ -  + ]:             10 :         if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
  597 noah@leadboat.com        6266                 :UBC           0 :             prune_xid = relfrozenxid;
                               6267                 :                :         else
  597 noah@leadboat.com        6268                 :CBC          10 :             prune_xid = TransactionXmin;
                               6269   [ -  +  +  +  :             10 :         PageSetPrunable(page, prune_xid);
                                              -  + ]
                               6270                 :                :     }
                               6271                 :                : 
                               6272                 :                :     /* store transaction information of xact deleting the tuple */
 3876 andres@anarazel.de       6273                 :             10 :     tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               6274                 :             10 :     tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               6275                 :                : 
                               6276                 :                :     /*
                               6277                 :                :      * Set the tuple header xmin to InvalidTransactionId.  This makes the
                               6278                 :                :      * tuple immediately invisible everyone.  (In particular, to any
                               6279                 :                :      * transactions waiting on the speculative token, woken up later.)
                               6280                 :                :      */
                               6281                 :             10 :     HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
                               6282                 :                : 
                               6283                 :                :     /* Clear the speculative insertion token too */
                               6284                 :             10 :     tp.t_data->t_ctid = tp.t_self;
                               6285                 :                : 
                               6286                 :             10 :     MarkBufferDirty(buffer);
                               6287                 :                : 
                               6288                 :                :     /*
                               6289                 :                :      * XLOG stuff
                               6290                 :                :      *
                               6291                 :                :      * The WAL records generated here match heap_delete().  The same recovery
                               6292                 :                :      * routines are used.
                               6293                 :                :      */
                               6294   [ +  -  -  +  :             10 :     if (RelationNeedsWAL(relation))
                                        -  -  -  - ]
                               6295                 :                :     {
                               6296                 :                :         xl_heap_delete xlrec;
                               6297                 :                :         XLogRecPtr  recptr;
                               6298                 :                : 
                               6299                 :             10 :         xlrec.flags = XLH_DELETE_IS_SUPER;
                               6300                 :             20 :         xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
                               6301                 :             10 :                                               tp.t_data->t_infomask2);
                               6302                 :             10 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
                               6303                 :             10 :         xlrec.xmax = xid;
                               6304                 :                : 
                               6305                 :             10 :         XLogBeginInsert();
  309 peter@eisentraut.org     6306                 :             10 :         XLogRegisterData(&xlrec, SizeOfHeapDelete);
 3876 andres@anarazel.de       6307                 :             10 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               6308                 :                : 
                               6309                 :                :         /* No replica identity & replication origin logged */
                               6310                 :                : 
                               6311                 :             10 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
                               6312                 :                : 
                               6313                 :             10 :         PageSetLSN(page, recptr);
                               6314                 :                :     }
                               6315                 :                : 
                               6316         [ -  + ]:             10 :     END_CRIT_SECTION();
                               6317                 :                : 
                               6318                 :             10 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               6319                 :                : 
                               6320         [ +  + ]:             10 :     if (HeapTupleHasExternal(&tp))
                               6321                 :                :     {
 3409                          6322         [ -  + ]:              1 :         Assert(!IsToastRelation(relation));
 2266 rhaas@postgresql.org     6323                 :              1 :         heap_toast_delete(relation, &tp, true);
                               6324                 :                :     }
                               6325                 :                : 
                               6326                 :                :     /*
                               6327                 :                :      * Never need to mark tuple for invalidation, since catalogs don't support
                               6328                 :                :      * speculative insertion
                               6329                 :                :      */
                               6330                 :                : 
                               6331                 :                :     /* Now we can release the buffer */
 3876 andres@anarazel.de       6332                 :             10 :     ReleaseBuffer(buffer);
                               6333                 :                : 
                               6334                 :                :     /* count deletion, as we counted the insertion too */
                               6335                 :             10 :     pgstat_count_heap_delete(relation);
                               6336                 :             10 : }
                               6337                 :                : 
                               6338                 :                : /*
                               6339                 :                :  * heap_inplace_lock - protect inplace update from concurrent heap_update()
                               6340                 :                :  *
                               6341                 :                :  * Evaluate whether the tuple's state is compatible with a no-key update.
                               6342                 :                :  * Current transaction rowmarks are fine, as is KEY SHARE from any
                               6343                 :                :  * transaction.  If compatible, return true with the buffer exclusive-locked,
                               6344                 :                :  * and the caller must release that by calling
                               6345                 :                :  * heap_inplace_update_and_unlock(), calling heap_inplace_unlock(), or raising
                               6346                 :                :  * an error.  Otherwise, call release_callback(arg), wait for blocking
                               6347                 :                :  * transactions to end, and return false.
                               6348                 :                :  *
                               6349                 :                :  * Since this is intended for system catalogs and SERIALIZABLE doesn't cover
                               6350                 :                :  * DDL, this doesn't guarantee any particular predicate locking.
                               6351                 :                :  *
                               6352                 :                :  * heap_delete() is a rarer source of blocking transactions (xwait).  We'll
                               6353                 :                :  * wait for such a transaction just like for the normal heap_update() case.
                               6354                 :                :  * Normal concurrent DROP commands won't cause that, because all inplace
                               6355                 :                :  * updaters take some lock that conflicts with DROP.  An explicit SQL "DELETE
                               6356                 :                :  * FROM pg_class" can cause it.  By waiting, if the concurrent transaction
                               6357                 :                :  * executed both "DELETE FROM pg_class" and "INSERT INTO pg_class", our caller
                               6358                 :                :  * can find the successor tuple.
                               6359                 :                :  *
                               6360                 :                :  * Readers of inplace-updated fields expect changes to those fields are
                               6361                 :                :  * durable.  For example, vac_truncate_clog() reads datfrozenxid from
                               6362                 :                :  * pg_database tuples via catalog snapshots.  A future snapshot must not
                               6363                 :                :  * return a lower datfrozenxid for the same database OID (lower in the
                               6364                 :                :  * FullTransactionIdPrecedes() sense).  We achieve that since no update of a
                               6365                 :                :  * tuple can start while we hold a lock on its buffer.  In cases like
                               6366                 :                :  * BEGIN;GRANT;CREATE INDEX;COMMIT we're inplace-updating a tuple visible only
                               6367                 :                :  * to this transaction.  ROLLBACK then is one case where it's okay to lose
                               6368                 :                :  * inplace updates.  (Restoring relhasindex=false on ROLLBACK is fine, since
                               6369                 :                :  * any concurrent CREATE INDEX would have blocked, then inplace-updated the
                               6370                 :                :  * committed tuple.)
                               6371                 :                :  *
                               6372                 :                :  * In principle, we could avoid waiting by overwriting every tuple in the
                               6373                 :                :  * updated tuple chain.  Reader expectations permit updating a tuple only if
                               6374                 :                :  * it's aborted, is the tail of the chain, or we already updated the tuple
                               6375                 :                :  * referenced in its t_ctid.  Hence, we would need to overwrite the tuples in
                               6376                 :                :  * order from tail to head.  That would imply either (a) mutating all tuples
                               6377                 :                :  * in one critical section or (b) accepting a chance of partial completion.
                               6378                 :                :  * Partial completion of a relfrozenxid update would have the weird
                               6379                 :                :  * consequence that the table's next VACUUM could see the table's relfrozenxid
                               6380                 :                :  * move forward between vacuum_get_cutoffs() and finishing.
                               6381                 :                :  */
                               6382                 :                : bool
  449 noah@leadboat.com        6383                 :          94161 : heap_inplace_lock(Relation relation,
                               6384                 :                :                   HeapTuple oldtup_ptr, Buffer buffer,
                               6385                 :                :                   void (*release_callback) (void *), void *arg)
                               6386                 :                : {
                               6387                 :          94161 :     HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
                               6388                 :                :     TM_Result   result;
                               6389                 :                :     bool        ret;
                               6390                 :                : 
                               6391                 :                : #ifdef USE_ASSERT_CHECKING
                               6392         [ +  + ]:          94161 :     if (RelationGetRelid(relation) == RelationRelationId)
                               6393                 :          93207 :         check_inplace_rel_lock(oldtup_ptr);
                               6394                 :                : #endif
                               6395                 :                : 
                               6396         [ -  + ]:          94161 :     Assert(BufferIsValid(buffer));
                               6397                 :                : 
                               6398                 :                :     /*
                               6399                 :                :      * Register shared cache invals if necessary.  Other sessions may finish
                               6400                 :                :      * inplace updates of this tuple between this step and LockTuple().  Since
                               6401                 :                :      * inplace updates don't change cache keys, that's harmless.
                               6402                 :                :      *
                               6403                 :                :      * While it's tempting to register invals only after confirming we can
                               6404                 :                :      * return true, the following obstacle precludes reordering steps that
                               6405                 :                :      * way.  Registering invals might reach a CatalogCacheInitializeCache()
                               6406                 :                :      * that locks "buffer".  That would hang indefinitely if running after our
                               6407                 :                :      * own LockBuffer().  Hence, we must register invals before LockBuffer().
                               6408                 :                :      */
    2                          6409                 :          94161 :     CacheInvalidateHeapTupleInplace(relation, oldtup_ptr);
                               6410                 :                : 
  449                          6411                 :          94161 :     LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
                               6412                 :          94161 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               6413                 :                : 
                               6414                 :                :     /*----------
                               6415                 :                :      * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
                               6416                 :                :      *
                               6417                 :                :      * - wait unconditionally
                               6418                 :                :      * - already locked tuple above, since inplace needs that unconditionally
                               6419                 :                :      * - don't recheck header after wait: simpler to defer to next iteration
                               6420                 :                :      * - don't try to continue even if the updater aborts: likewise
                               6421                 :                :      * - no crosscheck
                               6422                 :                :      */
                               6423                 :          94161 :     result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
                               6424                 :                :                                       buffer);
                               6425                 :                : 
                               6426         [ -  + ]:          94161 :     if (result == TM_Invisible)
                               6427                 :                :     {
                               6428                 :                :         /* no known way this can happen */
 3884 rhaas@postgresql.org     6429         [ #  # ]:UBC           0 :         ereport(ERROR,
                               6430                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               6431                 :                :                  errmsg_internal("attempted to overwrite invisible tuple")));
                               6432                 :                :     }
  449 noah@leadboat.com        6433         [ -  + ]:CBC       94161 :     else if (result == TM_SelfModified)
                               6434                 :                :     {
                               6435                 :                :         /*
                               6436                 :                :          * CREATE INDEX might reach this if an expression is silly enough to
                               6437                 :                :          * call e.g. SELECT ... FROM pg_class FOR SHARE.  C code of other SQL
                               6438                 :                :          * statements might get here after a heap_update() of the same row, in
                               6439                 :                :          * the absence of an intervening CommandCounterIncrement().
                               6440                 :                :          */
  449 noah@leadboat.com        6441         [ #  # ]:UBC           0 :         ereport(ERROR,
                               6442                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               6443                 :                :                  errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
                               6444                 :                :     }
  449 noah@leadboat.com        6445         [ +  + ]:CBC       94161 :     else if (result == TM_BeingModified)
                               6446                 :                :     {
                               6447                 :                :         TransactionId xwait;
                               6448                 :                :         uint16      infomask;
                               6449                 :                : 
                               6450                 :             56 :         xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
                               6451                 :             56 :         infomask = oldtup.t_data->t_infomask;
                               6452                 :                : 
                               6453         [ +  + ]:             56 :         if (infomask & HEAP_XMAX_IS_MULTI)
                               6454                 :                :         {
                               6455                 :              5 :             LockTupleMode lockmode = LockTupleNoKeyExclusive;
                               6456                 :              5 :             MultiXactStatus mxact_status = MultiXactStatusNoKeyUpdate;
                               6457                 :                :             int         remain;
                               6458                 :                : 
                               6459         [ +  + ]:              5 :             if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
                               6460                 :                :                                         lockmode, NULL))
                               6461                 :                :             {
                               6462                 :              2 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
  414                          6463                 :              2 :                 release_callback(arg);
  449                          6464                 :              2 :                 ret = false;
                               6465                 :              2 :                 MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
                               6466                 :                :                                 relation, &oldtup.t_self, XLTW_Update,
                               6467                 :                :                                 &remain);
                               6468                 :                :             }
                               6469                 :                :             else
                               6470                 :              3 :                 ret = true;
                               6471                 :                :         }
                               6472         [ +  + ]:             51 :         else if (TransactionIdIsCurrentTransactionId(xwait))
                               6473                 :              1 :             ret = true;
                               6474         [ +  + ]:             50 :         else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
                               6475                 :              1 :             ret = true;
                               6476                 :                :         else
                               6477                 :                :         {
                               6478                 :             49 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
  414                          6479                 :             49 :             release_callback(arg);
  449                          6480                 :             49 :             ret = false;
                               6481                 :             49 :             XactLockTableWait(xwait, relation, &oldtup.t_self,
                               6482                 :                :                               XLTW_Update);
                               6483                 :                :         }
                               6484                 :                :     }
                               6485                 :                :     else
                               6486                 :                :     {
                               6487                 :          94105 :         ret = (result == TM_Ok);
                               6488         [ -  + ]:          94105 :         if (!ret)
                               6489                 :                :         {
  449 noah@leadboat.com        6490                 :UBC           0 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
  414                          6491                 :              0 :             release_callback(arg);
                               6492                 :                :         }
                               6493                 :                :     }
                               6494                 :                : 
                               6495                 :                :     /*
                               6496                 :                :      * GetCatalogSnapshot() relies on invalidation messages to know when to
                               6497                 :                :      * take a new snapshot.  COMMIT of xwait is responsible for sending the
                               6498                 :                :      * invalidation.  We're not acquiring heavyweight locks sufficient to
                               6499                 :                :      * block if not yet sent, so we must take a new snapshot to ensure a later
                               6500                 :                :      * attempt has a fair chance.  While we don't need this if xwait aborted,
                               6501                 :                :      * don't bother optimizing that.
                               6502                 :                :      */
  449 noah@leadboat.com        6503         [ +  + ]:CBC       94161 :     if (!ret)
                               6504                 :                :     {
                               6505                 :             51 :         UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
  410                          6506                 :             51 :         ForgetInplace_Inval();
  449                          6507                 :             51 :         InvalidateCatalogSnapshot();
                               6508                 :                :     }
                               6509                 :          94161 :     return ret;
                               6510                 :                : }
                               6511                 :                : 
                               6512                 :                : /*
                               6513                 :                :  * heap_inplace_update_and_unlock - core of systable_inplace_update_finish
                               6514                 :                :  *
                               6515                 :                :  * The tuple cannot change size, and therefore its header fields and null
                               6516                 :                :  * bitmap (if any) don't change either.
                               6517                 :                :  *
                               6518                 :                :  * Since we hold LOCKTAG_TUPLE, no updater has a local copy of this tuple.
                               6519                 :                :  */
                               6520                 :                : void
                               6521                 :          65225 : heap_inplace_update_and_unlock(Relation relation,
                               6522                 :                :                                HeapTuple oldtup, HeapTuple tuple,
                               6523                 :                :                                Buffer buffer)
                               6524                 :                : {
                               6525                 :          65225 :     HeapTupleHeader htup = oldtup->t_data;
                               6526                 :                :     uint32      oldlen;
                               6527                 :                :     uint32      newlen;
                               6528                 :                :     char       *dst;
                               6529                 :                :     char       *src;
  418                          6530                 :          65225 :     int         nmsgs = 0;
                               6531                 :          65225 :     SharedInvalidationMessage *invalMessages = NULL;
                               6532                 :          65225 :     bool        RelcacheInitFileInval = false;
                               6533                 :                : 
  449                          6534         [ -  + ]:          65225 :     Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
                               6535                 :          65225 :     oldlen = oldtup->t_len - htup->t_hoff;
 7161 tgl@sss.pgh.pa.us        6536                 :          65225 :     newlen = tuple->t_len - tuple->t_data->t_hoff;
                               6537   [ +  -  -  + ]:          65225 :     if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
 3681 andres@anarazel.de       6538         [ #  # ]:UBC           0 :         elog(ERROR, "wrong tuple length");
                               6539                 :                : 
  418 noah@leadboat.com        6540                 :CBC       65225 :     dst = (char *) htup + htup->t_hoff;
                               6541                 :          65225 :     src = (char *) tuple->t_data + tuple->t_data->t_hoff;
                               6542                 :                : 
                               6543                 :                :     /* Like RecordTransactionCommit(), log only if needed */
                               6544         [ +  + ]:          65225 :     if (XLogStandbyInfoActive())
                               6545                 :          50990 :         nmsgs = inplaceGetInvalidationMessages(&invalMessages,
                               6546                 :                :                                                &RelcacheInitFileInval);
                               6547                 :                : 
                               6548                 :                :     /*
                               6549                 :                :      * Unlink relcache init files as needed.  If unlinking, acquire
                               6550                 :                :      * RelCacheInitLock until after associated invalidations.  By doing this
                               6551                 :                :      * in advance, if we checkpoint and then crash between inplace
                               6552                 :                :      * XLogInsert() and inval, we don't rely on StartupXLOG() ->
                               6553                 :                :      * RelationCacheInitFileRemove().  That uses elevel==LOG, so replay would
                               6554                 :                :      * neglect to PANIC on EIO.
                               6555                 :                :      */
                               6556                 :          65225 :     PreInplace_Inval();
                               6557                 :                : 
                               6558                 :                :     /*----------
                               6559                 :                :      * NO EREPORT(ERROR) from here till changes are complete
                               6560                 :                :      *
                               6561                 :                :      * Our buffer lock won't stop a reader having already pinned and checked
                               6562                 :                :      * visibility for this tuple.  Hence, we write WAL first, then mutate the
                               6563                 :                :      * buffer.  Like in MarkBufferDirtyHint() or RecordTransactionCommit(),
                               6564                 :                :      * checkpoint delay makes that acceptable.  With the usual order of
                               6565                 :                :      * changes, a crash after memcpy() and before XLogInsert() could allow
                               6566                 :                :      * datfrozenxid to overtake relfrozenxid:
                               6567                 :                :      *
                               6568                 :                :      * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
                               6569                 :                :      * ["R" is a VACUUM tbl]
                               6570                 :                :      * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
                               6571                 :                :      * D: systable_getnext() returns pg_class tuple of tbl
                               6572                 :                :      * R: memcpy() into pg_class tuple of tbl
                               6573                 :                :      * D: raise pg_database.datfrozenxid, XLogInsert(), finish
                               6574                 :                :      * [crash]
                               6575                 :                :      * [recovery restores datfrozenxid w/o relfrozenxid]
                               6576                 :                :      *
                               6577                 :                :      * Mimic MarkBufferDirtyHint() subroutine XLogSaveBufferForHint().
                               6578                 :                :      * Specifically, use DELAY_CHKPT_START, and copy the buffer to the stack.
                               6579                 :                :      * The stack copy facilitates a FPI of the post-mutation block before we
                               6580                 :                :      * accept other sessions seeing it.  DELAY_CHKPT_START allows us to
                               6581                 :                :      * XLogInsert() before MarkBufferDirty().  Since XLogSaveBufferForHint()
                               6582                 :                :      * can operate under BUFFER_LOCK_SHARED, it can't avoid DELAY_CHKPT_START.
                               6583                 :                :      * This function, however, likely could avoid it with the following order
                               6584                 :                :      * of operations: MarkBufferDirty(), XLogInsert(), memcpy().  Opt to use
                               6585                 :                :      * DELAY_CHKPT_START here, too, as a way to have fewer distinct code
                               6586                 :                :      * patterns to analyze.  Inplace update isn't so frequent that it should
                               6587                 :                :      * pursue the small optimization of skipping DELAY_CHKPT_START.
                               6588                 :                :      */
                               6589         [ -  + ]:          65225 :     Assert((MyProc->delayChkptFlags & DELAY_CHKPT_START) == 0);
                               6590                 :          65225 :     START_CRIT_SECTION();
                               6591                 :          65225 :     MyProc->delayChkptFlags |= DELAY_CHKPT_START;
                               6592                 :                : 
                               6593                 :                :     /* XLOG stuff */
 5483 rhaas@postgresql.org     6594   [ +  -  +  +  :          65225 :     if (RelationNeedsWAL(relation))
                                        +  -  +  + ]
                               6595                 :                :     {
                               6596                 :                :         xl_heap_inplace xlrec;
                               6597                 :                :         PGAlignedBlock copied_buffer;
  418 noah@leadboat.com        6598                 :          65217 :         char       *origdata = (char *) BufferGetBlock(buffer);
                               6599                 :          65217 :         Page        page = BufferGetPage(buffer);
                               6600                 :          65217 :         uint16      lower = ((PageHeader) page)->pd_lower;
                               6601                 :          65217 :         uint16      upper = ((PageHeader) page)->pd_upper;
                               6602                 :                :         uintptr_t   dst_offset_in_block;
                               6603                 :                :         RelFileLocator rlocator;
                               6604                 :                :         ForkNumber  forkno;
                               6605                 :                :         BlockNumber blkno;
                               6606                 :                :         XLogRecPtr  recptr;
                               6607                 :                : 
 4045 heikki.linnakangas@i     6608                 :          65217 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
  418 noah@leadboat.com        6609                 :          65217 :         xlrec.dbId = MyDatabaseId;
                               6610                 :          65217 :         xlrec.tsId = MyDatabaseTableSpace;
                               6611                 :          65217 :         xlrec.relcacheInitFileInval = RelcacheInitFileInval;
                               6612                 :          65217 :         xlrec.nmsgs = nmsgs;
                               6613                 :                : 
 4045 heikki.linnakangas@i     6614                 :          65217 :         XLogBeginInsert();
  309 peter@eisentraut.org     6615                 :          65217 :         XLogRegisterData(&xlrec, MinSizeOfHeapInplace);
  418 noah@leadboat.com        6616         [ +  + ]:          65217 :         if (nmsgs != 0)
  309 peter@eisentraut.org     6617                 :          36047 :             XLogRegisterData(invalMessages,
                               6618                 :                :                              nmsgs * sizeof(SharedInvalidationMessage));
                               6619                 :                : 
                               6620                 :                :         /* register block matching what buffer will look like after changes */
  418 noah@leadboat.com        6621                 :          65217 :         memcpy(copied_buffer.data, origdata, lower);
                               6622                 :          65217 :         memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
                               6623                 :          65217 :         dst_offset_in_block = dst - origdata;
                               6624                 :          65217 :         memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
                               6625                 :          65217 :         BufferGetTag(buffer, &rlocator, &forkno, &blkno);
                               6626         [ -  + ]:          65217 :         Assert(forkno == MAIN_FORKNUM);
                               6627                 :          65217 :         XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
                               6628                 :                :                           REGBUF_STANDARD);
                               6629                 :          65217 :         XLogRegisterBufData(0, src, newlen);
                               6630                 :                : 
                               6631                 :                :         /* inplace updates aren't decoded atm, don't log the origin */
                               6632                 :                : 
 4045 heikki.linnakangas@i     6633                 :          65217 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
                               6634                 :                : 
  418 noah@leadboat.com        6635                 :          65217 :         PageSetLSN(page, recptr);
                               6636                 :                :     }
                               6637                 :                : 
                               6638                 :          65225 :     memcpy(dst, src, newlen);
                               6639                 :                : 
                               6640                 :          65225 :     MarkBufferDirty(buffer);
                               6641                 :                : 
                               6642                 :          65225 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               6643                 :                : 
                               6644                 :                :     /*
                               6645                 :                :      * Send invalidations to shared queue.  SearchSysCacheLocked1() assumes we
                               6646                 :                :      * do this before UnlockTuple().
                               6647                 :                :      */
                               6648                 :          65225 :     AtInplace_Inval();
                               6649                 :                : 
                               6650                 :          65225 :     MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
 7161 tgl@sss.pgh.pa.us        6651         [ -  + ]:          65225 :     END_CRIT_SECTION();
  418 noah@leadboat.com        6652                 :          65225 :     UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
                               6653                 :                : 
                               6654                 :          65225 :     AcceptInvalidationMessages();   /* local processing of just-sent inval */
                               6655                 :                : 
                               6656                 :                :     /*
                               6657                 :                :      * Queue a transactional inval, for logical decoding and for third-party
                               6658                 :                :      * code that might have been relying on it since long before inplace
                               6659                 :                :      * update adopted immediate invalidation.  See README.tuplock section
                               6660                 :                :      * "Reading inplace-updated columns" for logical decoding details.
                               6661                 :                :      */
 7161 tgl@sss.pgh.pa.us        6662         [ +  + ]:          65225 :     if (!IsBootstrapProcessingMode())
 5237                          6663                 :          50282 :         CacheInvalidateHeapTuple(relation, tuple, NULL);
 7161                          6664                 :          65225 : }
                               6665                 :                : 
                               6666                 :                : /*
                               6667                 :                :  * heap_inplace_unlock - reverse of heap_inplace_lock
                               6668                 :                :  */
                               6669                 :                : void
  449 noah@leadboat.com        6670                 :          28885 : heap_inplace_unlock(Relation relation,
                               6671                 :                :                     HeapTuple oldtup, Buffer buffer)
                               6672                 :                : {
                               6673                 :          28885 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               6674                 :          28885 :     UnlockTuple(relation, &oldtup->t_self, InplaceUpdateTupleLock);
  410                          6675                 :          28885 :     ForgetInplace_Inval();
  449                          6676                 :          28885 : }
                               6677                 :                : 
                               6678                 :                : #define     FRM_NOOP                0x0001
                               6679                 :                : #define     FRM_INVALIDATE_XMAX     0x0002
                               6680                 :                : #define     FRM_RETURN_IS_XID       0x0004
                               6681                 :                : #define     FRM_RETURN_IS_MULTI     0x0008
                               6682                 :                : #define     FRM_MARK_COMMITTED      0x0010
                               6683                 :                : 
                               6684                 :                : /*
                               6685                 :                :  * FreezeMultiXactId
                               6686                 :                :  *      Determine what to do during freezing when a tuple is marked by a
                               6687                 :                :  *      MultiXactId.
                               6688                 :                :  *
                               6689                 :                :  * "flags" is an output value; it's used to tell caller what to do on return.
                               6690                 :                :  * "pagefrz" is an input/output value, used to manage page level freezing.
                               6691                 :                :  *
                               6692                 :                :  * Possible values that we can set in "flags":
                               6693                 :                :  * FRM_NOOP
                               6694                 :                :  *      don't do anything -- keep existing Xmax
                               6695                 :                :  * FRM_INVALIDATE_XMAX
                               6696                 :                :  *      mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
                               6697                 :                :  * FRM_RETURN_IS_XID
                               6698                 :                :  *      The Xid return value is a single update Xid to set as xmax.
                               6699                 :                :  * FRM_MARK_COMMITTED
                               6700                 :                :  *      Xmax can be marked as HEAP_XMAX_COMMITTED
                               6701                 :                :  * FRM_RETURN_IS_MULTI
                               6702                 :                :  *      The return value is a new MultiXactId to set as new Xmax.
                               6703                 :                :  *      (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
                               6704                 :                :  *
                               6705                 :                :  * Caller delegates control of page freezing to us.  In practice we always
                               6706                 :                :  * force freezing of caller's page unless FRM_NOOP processing is indicated.
                               6707                 :                :  * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
                               6708                 :                :  * can never be left behind.  We freely choose when and how to process each
                               6709                 :                :  * Multi, without ever violating the cutoff postconditions for freezing.
                               6710                 :                :  *
                               6711                 :                :  * It's useful to remove Multis on a proactive timeline (relative to freezing
                               6712                 :                :  * XIDs) to keep MultiXact member SLRU buffer misses to a minimum.  It can also
                               6713                 :                :  * be cheaper in the short run, for us, since we too can avoid SLRU buffer
                               6714                 :                :  * misses through eager processing.
                               6715                 :                :  *
                               6716                 :                :  * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
                               6717                 :                :  * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
                               6718                 :                :  * This can usually be put off, which is usually enough to avoid it altogether.
                               6719                 :                :  * Allocating new multis during VACUUM should be avoided on general principle;
                               6720                 :                :  * only VACUUM can advance relminmxid, so allocating new Multis here comes with
                               6721                 :                :  * its own special risks.
                               6722                 :                :  *
                               6723                 :                :  * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
                               6724                 :                :  * using heap_tuple_should_freeze when we haven't forced page-level freezing.
                               6725                 :                :  *
                               6726                 :                :  * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
                               6727                 :                :  * have already forced page-level freezing, since that might incur the same
                               6728                 :                :  * SLRU buffer misses that we specifically intended to avoid by freezing.
                               6729                 :                :  */
                               6730                 :                : static TransactionId
 4384 alvherre@alvh.no-ip.     6731                 :              6 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
                               6732                 :                :                   const struct VacuumCutoffs *cutoffs, uint16 *flags,
                               6733                 :                :                   HeapPageFreeze *pagefrz)
                               6734                 :                : {
                               6735                 :                :     TransactionId newxmax;
                               6736                 :                :     MultiXactMember *members;
                               6737                 :                :     int         nmembers;
                               6738                 :                :     bool        need_replace;
                               6739                 :                :     int         nnewmembers;
                               6740                 :                :     MultiXactMember *newmembers;
                               6741                 :                :     bool        has_lockers;
                               6742                 :                :     TransactionId update_xid;
                               6743                 :                :     bool        update_committed;
                               6744                 :                :     TransactionId FreezePageRelfrozenXid;
                               6745                 :                : 
                               6746                 :              6 :     *flags = 0;
                               6747                 :                : 
                               6748                 :                :     /* We should only be called in Multis */
                               6749         [ -  + ]:              6 :     Assert(t_infomask & HEAP_XMAX_IS_MULTI);
                               6750                 :                : 
 3463                          6751   [ +  -  -  + ]:             12 :     if (!MultiXactIdIsValid(multi) ||
                               6752                 :              6 :         HEAP_LOCKED_UPGRADED(t_infomask))
                               6753                 :                :     {
 4384 alvherre@alvh.no-ip.     6754                 :UBC           0 :         *flags |= FRM_INVALIDATE_XMAX;
 1085 pg@bowt.ie               6755                 :              0 :         pagefrz->freeze_required = true;
 4384 alvherre@alvh.no-ip.     6756                 :              0 :         return InvalidTransactionId;
                               6757                 :                :     }
 1091 pg@bowt.ie               6758         [ -  + ]:CBC           6 :     else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
 2956 andres@anarazel.de       6759         [ #  # ]:UBC           0 :         ereport(ERROR,
                               6760                 :                :                 (errcode(ERRCODE_DATA_CORRUPTED),
                               6761                 :                :                  errmsg_internal("found multixact %u from before relminmxid %u",
                               6762                 :                :                                  multi, cutoffs->relminmxid)));
 1085 pg@bowt.ie               6763         [ +  + ]:CBC           6 :     else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
                               6764                 :                :     {
                               6765                 :                :         TransactionId update_xact;
                               6766                 :                : 
                               6767                 :                :         /*
                               6768                 :                :          * This old multi cannot possibly have members still running, but
                               6769                 :                :          * verify just in case.  If it was a locker only, it can be removed
                               6770                 :                :          * without any further consideration; but if it contained an update,
                               6771                 :                :          * we might need to preserve it.
                               6772                 :                :          */
 2956 andres@anarazel.de       6773         [ -  + ]:              4 :         if (MultiXactIdIsRunning(multi,
                               6774                 :              4 :                                  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
 2956 andres@anarazel.de       6775         [ #  # ]:UBC           0 :             ereport(ERROR,
                               6776                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6777                 :                :                      errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
                               6778                 :                :                                      multi, cutoffs->OldestMxact)));
                               6779                 :                : 
 4384 alvherre@alvh.no-ip.     6780         [ +  - ]:CBC           4 :         if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
                               6781                 :                :         {
                               6782                 :              4 :             *flags |= FRM_INVALIDATE_XMAX;
 1085 pg@bowt.ie               6783                 :              4 :             pagefrz->freeze_required = true;
                               6784                 :              4 :             return InvalidTransactionId;
                               6785                 :                :         }
                               6786                 :                : 
                               6787                 :                :         /* replace multi with single XID for its updater? */
 1085 pg@bowt.ie               6788                 :UBC           0 :         update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
                               6789         [ #  # ]:              0 :         if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
                               6790         [ #  # ]:              0 :             ereport(ERROR,
                               6791                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6792                 :                :                      errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
                               6793                 :                :                                      multi, update_xact,
                               6794                 :                :                                      cutoffs->relfrozenxid)));
                               6795         [ #  # ]:              0 :         else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
                               6796                 :                :         {
                               6797                 :                :             /*
                               6798                 :                :              * Updater XID has to have aborted (otherwise the tuple would have
                               6799                 :                :              * been pruned away instead, since updater XID is < OldestXmin).
                               6800                 :                :              * Just remove xmax.
                               6801                 :                :              */
 1079                          6802         [ #  # ]:              0 :             if (TransactionIdDidCommit(update_xact))
 1085                          6803         [ #  # ]:              0 :                 ereport(ERROR,
                               6804                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               6805                 :                :                          errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
                               6806                 :                :                                          multi, update_xact,
                               6807                 :                :                                          cutoffs->OldestXmin)));
                               6808                 :              0 :             *flags |= FRM_INVALIDATE_XMAX;
                               6809                 :              0 :             pagefrz->freeze_required = true;
                               6810                 :              0 :             return InvalidTransactionId;
                               6811                 :                :         }
                               6812                 :                : 
                               6813                 :                :         /* Have to keep updater XID as new xmax */
                               6814                 :              0 :         *flags |= FRM_RETURN_IS_XID;
                               6815                 :              0 :         pagefrz->freeze_required = true;
                               6816                 :              0 :         return update_xact;
                               6817                 :                :     }
                               6818                 :                : 
                               6819                 :                :     /*
                               6820                 :                :      * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
                               6821                 :                :      * need to walk the whole members array to figure out what to do, if
                               6822                 :                :      * anything.
                               6823                 :                :      */
                               6824                 :                :     nmembers =
 3463 alvherre@alvh.no-ip.     6825                 :CBC           2 :         GetMultiXactIdMembers(multi, &members, false,
 4159                          6826                 :              2 :                               HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
 4384                          6827         [ -  + ]:              2 :     if (nmembers <= 0)
                               6828                 :                :     {
                               6829                 :                :         /* Nothing worth keeping */
 4384 alvherre@alvh.no-ip.     6830                 :UBC           0 :         *flags |= FRM_INVALIDATE_XMAX;
 1085 pg@bowt.ie               6831                 :              0 :         pagefrz->freeze_required = true;
 4384 alvherre@alvh.no-ip.     6832                 :              0 :         return InvalidTransactionId;
                               6833                 :                :     }
                               6834                 :                : 
                               6835                 :                :     /*
                               6836                 :                :      * The FRM_NOOP case is the only case where we might need to ratchet back
                               6837                 :                :      * FreezePageRelfrozenXid or FreezePageRelminMxid.  It is also the only
                               6838                 :                :      * case where our caller might ratchet back its NoFreezePageRelfrozenXid
                               6839                 :                :      * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
                               6840                 :                :      * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
                               6841                 :                :      * trackers managed by VACUUM being ratcheting back by xmax to the degree
                               6842                 :                :      * required to make it safe to leave xmax undisturbed, independent of
                               6843                 :                :      * whether or not page freezing is triggered somewhere else.
                               6844                 :                :      *
                               6845                 :                :      * Our policy is to force freezing in every case other than FRM_NOOP,
                               6846                 :                :      * which obviates the need to maintain either set of trackers, anywhere.
                               6847                 :                :      * Every other case will reliably execute a freeze plan for xmax that
                               6848                 :                :      * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
                               6849                 :                :      * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
                               6850                 :                :      * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
                               6851                 :                :      * OldestXmin/OldestMxact, so later values never need to be tracked here.)
                               6852                 :                :      */
 4384 alvherre@alvh.no-ip.     6853                 :CBC           2 :     need_replace = false;
 1085 pg@bowt.ie               6854                 :              2 :     FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
 1091                          6855         [ +  + ]:              4 :     for (int i = 0; i < nmembers; i++)
                               6856                 :                :     {
                               6857                 :              3 :         TransactionId xid = members[i].xid;
                               6858                 :                : 
                               6859         [ -  + ]:              3 :         Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
                               6860                 :                : 
                               6861         [ +  + ]:              3 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
                               6862                 :                :         {
                               6863                 :                :             /* Can't violate the FreezeLimit postcondition */
 4384 alvherre@alvh.no-ip.     6864                 :              1 :             need_replace = true;
                               6865                 :              1 :             break;
                               6866                 :                :         }
 1085 pg@bowt.ie               6867         [ -  + ]:              2 :         if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
 1085 pg@bowt.ie               6868                 :UBC           0 :             FreezePageRelfrozenXid = xid;
                               6869                 :                :     }
                               6870                 :                : 
                               6871                 :                :     /* Can't violate the MultiXactCutoff postcondition, either */
 1085 pg@bowt.ie               6872         [ +  + ]:CBC           2 :     if (!need_replace)
                               6873                 :              1 :         need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
                               6874                 :                : 
 4384 alvherre@alvh.no-ip.     6875         [ +  + ]:              2 :     if (!need_replace)
                               6876                 :                :     {
                               6877                 :                :         /*
                               6878                 :                :          * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
                               6879                 :                :          * both together to make it safe to retain this particular multi after
                               6880                 :                :          * freezing its page
                               6881                 :                :          */
                               6882                 :              1 :         *flags |= FRM_NOOP;
 1085 pg@bowt.ie               6883                 :              1 :         pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
                               6884         [ -  + ]:              1 :         if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
 1085 pg@bowt.ie               6885                 :UBC           0 :             pagefrz->FreezePageRelminMxid = multi;
 4384 alvherre@alvh.no-ip.     6886                 :CBC           1 :         pfree(members);
 1354 pg@bowt.ie               6887                 :              1 :         return multi;
                               6888                 :                :     }
                               6889                 :                : 
                               6890                 :                :     /*
                               6891                 :                :      * Do a more thorough second pass over the multi to figure out which
                               6892                 :                :      * member XIDs actually need to be kept.  Checking the precise status of
                               6893                 :                :      * individual members might even show that we don't need to keep anything.
                               6894                 :                :      * That is quite possible even though the Multi must be >= OldestMxact,
                               6895                 :                :      * since our second pass only keeps member XIDs when it's truly necessary;
                               6896                 :                :      * even member XIDs >= OldestXmin often won't be kept by second pass.
                               6897                 :                :      */
 4384 alvherre@alvh.no-ip.     6898                 :              1 :     nnewmembers = 0;
    7 michael@paquier.xyz      6899                 :GNC           1 :     newmembers = palloc_array(MultiXactMember, nmembers);
 4384 alvherre@alvh.no-ip.     6900                 :CBC           1 :     has_lockers = false;
                               6901                 :              1 :     update_xid = InvalidTransactionId;
                               6902                 :              1 :     update_committed = false;
                               6903                 :                : 
                               6904                 :                :     /*
                               6905                 :                :      * Determine whether to keep each member xid, or to ignore it instead
                               6906                 :                :      */
 1091 pg@bowt.ie               6907         [ +  + ]:              3 :     for (int i = 0; i < nmembers; i++)
                               6908                 :                :     {
                               6909                 :              2 :         TransactionId xid = members[i].xid;
                               6910                 :              2 :         MultiXactStatus mstatus = members[i].status;
                               6911                 :                : 
                               6912         [ -  + ]:              2 :         Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
                               6913                 :                : 
                               6914         [ +  - ]:              2 :         if (!ISUPDATE_from_mxstatus(mstatus))
                               6915                 :                :         {
                               6916                 :                :             /*
                               6917                 :                :              * Locker XID (not updater XID).  We only keep lockers that are
                               6918                 :                :              * still running.
                               6919                 :                :              */
                               6920   [ +  -  +  + ]:              4 :             if (TransactionIdIsCurrentTransactionId(xid) ||
                               6921                 :              2 :                 TransactionIdIsInProgress(xid))
                               6922                 :                :             {
 1085                          6923         [ -  + ]:              1 :                 if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
 1085 pg@bowt.ie               6924         [ #  # ]:UBC           0 :                     ereport(ERROR,
                               6925                 :                :                             (errcode(ERRCODE_DATA_CORRUPTED),
                               6926                 :                :                              errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
                               6927                 :                :                                              multi, xid,
                               6928                 :                :                                              cutoffs->OldestXmin)));
 1091 pg@bowt.ie               6929                 :CBC           1 :                 newmembers[nnewmembers++] = members[i];
                               6930                 :              1 :                 has_lockers = true;
                               6931                 :                :             }
                               6932                 :                : 
                               6933                 :              2 :             continue;
                               6934                 :                :         }
                               6935                 :                : 
                               6936                 :                :         /*
                               6937                 :                :          * Updater XID (not locker XID).  Should we keep it?
                               6938                 :                :          *
                               6939                 :                :          * Since the tuple wasn't totally removed when vacuum pruned, the
                               6940                 :                :          * update Xid cannot possibly be older than OldestXmin cutoff unless
                               6941                 :                :          * the updater XID aborted.  If the updater transaction is known
                               6942                 :                :          * aborted or crashed then it's okay to ignore it, otherwise not.
                               6943                 :                :          *
                               6944                 :                :          * In any case the Multi should never contain two updaters, whatever
                               6945                 :                :          * their individual commit status.  Check for that first, in passing.
                               6946                 :                :          */
 1091 pg@bowt.ie               6947         [ #  # ]:UBC           0 :         if (TransactionIdIsValid(update_xid))
                               6948         [ #  # ]:              0 :             ereport(ERROR,
                               6949                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6950                 :                :                      errmsg_internal("multixact %u has two or more updating members",
                               6951                 :                :                                      multi),
                               6952                 :                :                      errdetail_internal("First updater XID=%u second updater XID=%u.",
                               6953                 :                :                                         update_xid, xid)));
                               6954                 :                : 
                               6955                 :                :         /*
                               6956                 :                :          * As with all tuple visibility routines, it's critical to test
                               6957                 :                :          * TransactionIdIsInProgress before TransactionIdDidCommit, because of
                               6958                 :                :          * race conditions explained in detail in heapam_visibility.c.
                               6959                 :                :          */
                               6960   [ #  #  #  # ]:              0 :         if (TransactionIdIsCurrentTransactionId(xid) ||
                               6961                 :              0 :             TransactionIdIsInProgress(xid))
                               6962                 :              0 :             update_xid = xid;
                               6963         [ #  # ]:              0 :         else if (TransactionIdDidCommit(xid))
                               6964                 :                :         {
                               6965                 :                :             /*
                               6966                 :                :              * The transaction committed, so we can tell caller to set
                               6967                 :                :              * HEAP_XMAX_COMMITTED.  (We can only do this because we know the
                               6968                 :                :              * transaction is not running.)
                               6969                 :                :              */
                               6970                 :              0 :             update_committed = true;
                               6971                 :              0 :             update_xid = xid;
                               6972                 :                :         }
                               6973                 :                :         else
                               6974                 :                :         {
                               6975                 :                :             /*
                               6976                 :                :              * Not in progress, not committed -- must be aborted or crashed;
                               6977                 :                :              * we can ignore it.
                               6978                 :                :              */
                               6979                 :              0 :             continue;
                               6980                 :                :         }
                               6981                 :                : 
                               6982                 :                :         /*
                               6983                 :                :          * We determined that updater must be kept -- add it to pending new
                               6984                 :                :          * members list
                               6985                 :                :          */
 1085                          6986         [ #  # ]:              0 :         if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
                               6987         [ #  # ]:              0 :             ereport(ERROR,
                               6988                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6989                 :                :                      errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
                               6990                 :                :                                      multi, xid, cutoffs->OldestXmin)));
 1091                          6991                 :              0 :         newmembers[nnewmembers++] = members[i];
                               6992                 :                :     }
                               6993                 :                : 
 4384 alvherre@alvh.no-ip.     6994                 :CBC           1 :     pfree(members);
                               6995                 :                : 
                               6996                 :                :     /*
                               6997                 :                :      * Determine what to do with caller's multi based on information gathered
                               6998                 :                :      * during our second pass
                               6999                 :                :      */
                               7000         [ -  + ]:              1 :     if (nnewmembers == 0)
                               7001                 :                :     {
                               7002                 :                :         /* Nothing worth keeping */
 4384 alvherre@alvh.no-ip.     7003                 :UBC           0 :         *flags |= FRM_INVALIDATE_XMAX;
 1091 pg@bowt.ie               7004                 :              0 :         newxmax = InvalidTransactionId;
                               7005                 :                :     }
 4384 alvherre@alvh.no-ip.     7006   [ -  +  -  - ]:CBC           1 :     else if (TransactionIdIsValid(update_xid) && !has_lockers)
                               7007                 :                :     {
                               7008                 :                :         /*
                               7009                 :                :          * If there's a single member and it's an update, pass it back alone
                               7010                 :                :          * without creating a new Multi.  (XXX we could do this when there's a
                               7011                 :                :          * single remaining locker, too, but that would complicate the API too
                               7012                 :                :          * much; moreover, the case with the single updater is more
                               7013                 :                :          * interesting, because those are longer-lived.)
                               7014                 :                :          */
 4384 alvherre@alvh.no-ip.     7015         [ #  # ]:UBC           0 :         Assert(nnewmembers == 1);
                               7016                 :              0 :         *flags |= FRM_RETURN_IS_XID;
                               7017         [ #  # ]:              0 :         if (update_committed)
                               7018                 :              0 :             *flags |= FRM_MARK_COMMITTED;
 1091 pg@bowt.ie               7019                 :              0 :         newxmax = update_xid;
                               7020                 :                :     }
                               7021                 :                :     else
                               7022                 :                :     {
                               7023                 :                :         /*
                               7024                 :                :          * Create a new multixact with the surviving members of the previous
                               7025                 :                :          * one, to set as new Xmax in the tuple
                               7026                 :                :          */
 1091 pg@bowt.ie               7027                 :CBC           1 :         newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
 4384 alvherre@alvh.no-ip.     7028                 :              1 :         *flags |= FRM_RETURN_IS_MULTI;
                               7029                 :                :     }
                               7030                 :                : 
                               7031                 :              1 :     pfree(newmembers);
                               7032                 :                : 
 1085 pg@bowt.ie               7033                 :              1 :     pagefrz->freeze_required = true;
 1091                          7034                 :              1 :     return newxmax;
                               7035                 :                : }
                               7036                 :                : 
                               7037                 :                : /*
                               7038                 :                :  * heap_prepare_freeze_tuple
                               7039                 :                :  *
                               7040                 :                :  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
                               7041                 :                :  * are older than the OldestXmin and/or OldestMxact freeze cutoffs.  If so,
                               7042                 :                :  * setup enough state (in the *frz output argument) to enable caller to
                               7043                 :                :  * process this tuple as part of freezing its page, and return true.  Return
                               7044                 :                :  * false if nothing can be changed about the tuple right now.
                               7045                 :                :  *
                               7046                 :                :  * Also sets *totally_frozen to true if the tuple will be totally frozen once
                               7047                 :                :  * caller executes returned freeze plan (or if the tuple was already totally
                               7048                 :                :  * frozen by an earlier VACUUM).  This indicates that there are no remaining
                               7049                 :                :  * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
                               7050                 :                :  *
                               7051                 :                :  * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
                               7052                 :                :  * tuple that we returned true for, and then execute freezing.  Caller must
                               7053                 :                :  * initialize pagefrz fields for page as a whole before first call here for
                               7054                 :                :  * each heap page.
                               7055                 :                :  *
                               7056                 :                :  * VACUUM caller decides on whether or not to freeze the page as a whole.
                               7057                 :                :  * We'll often prepare freeze plans for a page that caller just discards.
                               7058                 :                :  * However, VACUUM doesn't always get to make a choice; it must freeze when
                               7059                 :                :  * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
                               7060                 :                :  * MXIDs < MultiXactCutoff) can never be left behind.  We help to make sure
                               7061                 :                :  * that VACUUM always follows that rule.
                               7062                 :                :  *
                               7063                 :                :  * We sometimes force freezing of xmax MultiXactId values long before it is
                               7064                 :                :  * strictly necessary to do so just to ensure the FreezeLimit postcondition.
                               7065                 :                :  * It's worth processing MultiXactIds proactively when it is cheap to do so,
                               7066                 :                :  * and it's convenient to make that happen by piggy-backing it on the "force
                               7067                 :                :  * freezing" mechanism.  Conversely, we sometimes delay freezing MultiXactIds
                               7068                 :                :  * because it is expensive right now (though only when it's still possible to
                               7069                 :                :  * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
                               7070                 :                :  *
                               7071                 :                :  * It is assumed that the caller has checked the tuple with
                               7072                 :                :  * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
                               7073                 :                :  * (else we should be removing the tuple, not freezing it).
                               7074                 :                :  *
                               7075                 :                :  * NB: This function has side effects: it might allocate a new MultiXactId.
                               7076                 :                :  * It will be set as tuple's new xmax when our *frz output is processed within
                               7077                 :                :  * heap_execute_freeze_tuple later on.  If the tuple is in a shared buffer
                               7078                 :                :  * then caller had better have an exclusive lock on it already.
                               7079                 :                :  */
                               7080                 :                : bool
 2956 andres@anarazel.de       7081                 :        4665109 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
                               7082                 :                :                           const struct VacuumCutoffs *cutoffs,
                               7083                 :                :                           HeapPageFreeze *pagefrz,
                               7084                 :                :                           HeapTupleFreeze *frz, bool *totally_frozen)
                               7085                 :                : {
 1091 pg@bowt.ie               7086                 :        4665109 :     bool        xmin_already_frozen = false,
                               7087                 :        4665109 :                 xmax_already_frozen = false;
                               7088                 :        4665109 :     bool        freeze_xmin = false,
                               7089                 :        4665109 :                 replace_xvac = false,
                               7090                 :        4665109 :                 replace_xmax = false,
                               7091                 :        4665109 :                 freeze_xmax = false;
                               7092                 :                :     TransactionId xid;
                               7093                 :                : 
 1079                          7094                 :        4665109 :     frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
 4384 alvherre@alvh.no-ip.     7095                 :        4665109 :     frz->t_infomask2 = tuple->t_infomask2;
                               7096                 :        4665109 :     frz->t_infomask = tuple->t_infomask;
 1079 pg@bowt.ie               7097                 :        4665109 :     frz->frzflags = 0;
                               7098                 :        4665109 :     frz->checkflags = 0;
                               7099                 :                : 
                               7100                 :                :     /*
                               7101                 :                :      * Process xmin, while keeping track of whether it's already frozen, or
                               7102                 :                :      * will become frozen iff our freeze plan is executed by caller (could be
                               7103                 :                :      * neither).
                               7104                 :                :      */
 6982 tgl@sss.pgh.pa.us        7105                 :        4665109 :     xid = HeapTupleHeaderGetXmin(tuple);
 2421 alvherre@alvh.no-ip.     7106         [ +  + ]:        4665109 :     if (!TransactionIdIsNormal(xid))
 1091 pg@bowt.ie               7107                 :        1429161 :         xmin_already_frozen = true;
                               7108                 :                :     else
                               7109                 :                :     {
                               7110         [ -  + ]:        3235948 :         if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
 2956 andres@anarazel.de       7111         [ #  # ]:UBC           0 :             ereport(ERROR,
                               7112                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               7113                 :                :                      errmsg_internal("found xmin %u from before relfrozenxid %u",
                               7114                 :                :                                      xid, cutoffs->relfrozenxid)));
                               7115                 :                : 
                               7116                 :                :         /* Will set freeze_xmin flags in freeze plan below */
 1085 pg@bowt.ie               7117                 :CBC     3235948 :         freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
                               7118                 :                : 
                               7119                 :                :         /* Verify that xmin committed if and when freeze plan is executed */
 1079                          7120         [ +  + ]:        3235948 :         if (freeze_xmin)
                               7121                 :        2713781 :             frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
                               7122                 :                :     }
                               7123                 :                : 
                               7124                 :                :     /*
                               7125                 :                :      * Old-style VACUUM FULL is gone, but we have to process xvac for as long
                               7126                 :                :      * as we support having MOVED_OFF/MOVED_IN tuples in the database
                               7127                 :                :      */
 1091                          7128                 :        4665109 :     xid = HeapTupleHeaderGetXvac(tuple);
                               7129         [ -  + ]:        4665109 :     if (TransactionIdIsNormal(xid))
                               7130                 :                :     {
 1091 pg@bowt.ie               7131         [ #  # ]:UBC           0 :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
                               7132         [ #  # ]:              0 :         Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
                               7133                 :                : 
                               7134                 :                :         /*
                               7135                 :                :          * For Xvac, we always freeze proactively.  This allows totally_frozen
                               7136                 :                :          * tracking to ignore xvac.
                               7137                 :                :          */
 1085                          7138                 :              0 :         replace_xvac = pagefrz->freeze_required = true;
                               7139                 :                : 
                               7140                 :                :         /* Will set replace_xvac flags in freeze plan below */
                               7141                 :                :     }
                               7142                 :                : 
                               7143                 :                :     /* Now process xmax */
 1079 pg@bowt.ie               7144                 :CBC     4665109 :     xid = frz->xmax;
 4402 alvherre@alvh.no-ip.     7145         [ +  + ]:        4665109 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
                               7146                 :                :     {
                               7147                 :                :         /* Raw xmax is a MultiXactId */
                               7148                 :                :         TransactionId newxmax;
                               7149                 :                :         uint16      flags;
                               7150                 :                : 
                               7151                 :                :         /*
                               7152                 :                :          * We will either remove xmax completely (in the "freeze_xmax" path),
                               7153                 :                :          * process xmax by replacing it (in the "replace_xmax" path), or
                               7154                 :                :          * perform no-op xmax processing.  The only constraint is that the
                               7155                 :                :          * FreezeLimit/MultiXactCutoff postcondition must never be violated.
                               7156                 :                :          */
 1091 pg@bowt.ie               7157                 :              6 :         newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
                               7158                 :                :                                     &flags, pagefrz);
                               7159                 :                : 
 1085                          7160         [ +  + ]:              6 :         if (flags & FRM_NOOP)
                               7161                 :                :         {
                               7162                 :                :             /*
                               7163                 :                :              * xmax is a MultiXactId, and nothing about it changes for now.
                               7164                 :                :              * This is the only case where 'freeze_required' won't have been
                               7165                 :                :              * set for us by FreezeMultiXactId, as well as the only case where
                               7166                 :                :              * neither freeze_xmax nor replace_xmax are set (given a multi).
                               7167                 :                :              *
                               7168                 :                :              * This is a no-op, but the call to FreezeMultiXactId might have
                               7169                 :                :              * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
                               7170                 :                :              * for us (the "freeze page" variants, specifically).  That'll
                               7171                 :                :              * make it safe for our caller to freeze the page later on, while
                               7172                 :                :              * leaving this particular xmax undisturbed.
                               7173                 :                :              *
                               7174                 :                :              * FreezeMultiXactId is _not_ responsible for the "no freeze"
                               7175                 :                :              * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
                               7176                 :                :              * job.  A call to heap_tuple_should_freeze for this same tuple
                               7177                 :                :              * will take place below if 'freeze_required' isn't set already.
                               7178                 :                :              * (This repeats work from FreezeMultiXactId, but allows "no
                               7179                 :                :              * freeze" tracker maintenance to happen in only one place.)
                               7180                 :                :              */
                               7181         [ -  + ]:              1 :             Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
                               7182   [ +  -  -  + ]:              1 :             Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
                               7183                 :                :         }
                               7184         [ -  + ]:              5 :         else if (flags & FRM_RETURN_IS_XID)
                               7185                 :                :         {
                               7186                 :                :             /*
                               7187                 :                :              * xmax will become an updater Xid (original MultiXact's updater
                               7188                 :                :              * member Xid will be carried forward as a simple Xid in Xmax).
                               7189                 :                :              */
 1091 pg@bowt.ie               7190         [ #  # ]:UBC           0 :             Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
                               7191                 :                : 
                               7192                 :                :             /*
                               7193                 :                :              * NB -- some of these transformations are only valid because we
                               7194                 :                :              * know the return Xid is a tuple updater (i.e. not merely a
                               7195                 :                :              * locker.) Also note that the only reason we don't explicitly
                               7196                 :                :              * worry about HEAP_KEYS_UPDATED is because it lives in
                               7197                 :                :              * t_infomask2 rather than t_infomask.
                               7198                 :                :              */
 4384 alvherre@alvh.no-ip.     7199                 :              0 :             frz->t_infomask &= ~HEAP_XMAX_BITS;
                               7200                 :              0 :             frz->xmax = newxmax;
                               7201         [ #  # ]:              0 :             if (flags & FRM_MARK_COMMITTED)
 3086 teodor@sigaev.ru         7202                 :              0 :                 frz->t_infomask |= HEAP_XMAX_COMMITTED;
 1091 pg@bowt.ie               7203                 :              0 :             replace_xmax = true;
                               7204                 :                :         }
 4384 alvherre@alvh.no-ip.     7205         [ +  + ]:CBC           5 :         else if (flags & FRM_RETURN_IS_MULTI)
                               7206                 :                :         {
                               7207                 :                :             uint16      newbits;
                               7208                 :                :             uint16      newbits2;
                               7209                 :                : 
                               7210                 :                :             /*
                               7211                 :                :              * xmax is an old MultiXactId that we have to replace with a new
                               7212                 :                :              * MultiXactId, to carry forward two or more original member XIDs.
                               7213                 :                :              */
 1091 pg@bowt.ie               7214         [ -  + ]:              1 :             Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
                               7215                 :                : 
                               7216                 :                :             /*
                               7217                 :                :              * We can't use GetMultiXactIdHintBits directly on the new multi
                               7218                 :                :              * here; that routine initializes the masks to all zeroes, which
                               7219                 :                :              * would lose other bits we need.  Doing it this way ensures all
                               7220                 :                :              * unrelated bits remain untouched.
                               7221                 :                :              */
 4384 alvherre@alvh.no-ip.     7222                 :              1 :             frz->t_infomask &= ~HEAP_XMAX_BITS;
                               7223                 :              1 :             frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               7224                 :              1 :             GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
                               7225                 :              1 :             frz->t_infomask |= newbits;
                               7226                 :              1 :             frz->t_infomask2 |= newbits2;
                               7227                 :              1 :             frz->xmax = newxmax;
 1091 pg@bowt.ie               7228                 :              1 :             replace_xmax = true;
                               7229                 :                :         }
                               7230                 :                :         else
                               7231                 :                :         {
                               7232                 :                :             /*
                               7233                 :                :              * Freeze plan for tuple "freezes xmax" in the strictest sense:
                               7234                 :                :              * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
                               7235                 :                :              */
                               7236         [ -  + ]:              4 :             Assert(flags & FRM_INVALIDATE_XMAX);
 1354                          7237         [ -  + ]:              4 :             Assert(!TransactionIdIsValid(newxmax));
                               7238                 :                : 
                               7239                 :                :             /* Will set freeze_xmax flags in freeze plan below */
 1091                          7240                 :              4 :             freeze_xmax = true;
                               7241                 :                :         }
                               7242                 :                : 
                               7243                 :                :         /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
 1085                          7244   [ -  +  -  -  :              6 :         Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
                                              -  - ]
                               7245                 :                :     }
 3472 rhaas@postgresql.org     7246         [ +  + ]:        4665103 :     else if (TransactionIdIsNormal(xid))
                               7247                 :                :     {
                               7248                 :                :         /* Raw xmax is normal XID */
 1091 pg@bowt.ie               7249         [ -  + ]:         277957 :         if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
 2956 andres@anarazel.de       7250         [ #  # ]:UBC           0 :             ereport(ERROR,
                               7251                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               7252                 :                :                      errmsg_internal("found xmax %u from before relfrozenxid %u",
                               7253                 :                :                                      xid, cutoffs->relfrozenxid)));
                               7254                 :                : 
                               7255                 :                :         /* Will set freeze_xmax flags in freeze plan below */
 1079 pg@bowt.ie               7256                 :CBC      277957 :         freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
                               7257                 :                : 
                               7258                 :                :         /*
                               7259                 :                :          * Verify that xmax aborted if and when freeze plan is executed,
                               7260                 :                :          * provided it's from an update. (A lock-only xmax can be removed
                               7261                 :                :          * independent of this, since the lock is released at xact end.)
                               7262                 :                :          */
                               7263   [ +  +  +  + ]:         277957 :         if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
                               7264                 :           1953 :             frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
                               7265                 :                :     }
 1120                          7266         [ +  - ]:        4387146 :     else if (!TransactionIdIsValid(xid))
                               7267                 :                :     {
                               7268                 :                :         /* Raw xmax is InvalidTransactionId XID */
                               7269         [ -  + ]:        4387146 :         Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
 2784 alvherre@alvh.no-ip.     7270                 :        4387146 :         xmax_already_frozen = true;
                               7271                 :                :     }
                               7272                 :                :     else
 2784 alvherre@alvh.no-ip.     7273         [ #  # ]:UBC           0 :         ereport(ERROR,
                               7274                 :                :                 (errcode(ERRCODE_DATA_CORRUPTED),
                               7275                 :                :                  errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
                               7276                 :                :                                  xid, tuple->t_infomask)));
                               7277                 :                : 
 1091 pg@bowt.ie               7278         [ +  + ]:CBC     4665109 :     if (freeze_xmin)
                               7279                 :                :     {
                               7280         [ -  + ]:        2713781 :         Assert(!xmin_already_frozen);
                               7281                 :                : 
                               7282                 :        2713781 :         frz->t_infomask |= HEAP_XMIN_FROZEN;
                               7283                 :                :     }
                               7284         [ -  + ]:        4665109 :     if (replace_xvac)
                               7285                 :                :     {
                               7286                 :                :         /*
                               7287                 :                :          * If a MOVED_OFF tuple is not dead, the xvac transaction must have
                               7288                 :                :          * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
                               7289                 :                :          * transaction succeeded.
                               7290                 :                :          */
 1085 pg@bowt.ie               7291         [ #  # ]:UBC           0 :         Assert(pagefrz->freeze_required);
 1091                          7292         [ #  # ]:              0 :         if (tuple->t_infomask & HEAP_MOVED_OFF)
                               7293                 :              0 :             frz->frzflags |= XLH_INVALID_XVAC;
                               7294                 :                :         else
                               7295                 :              0 :             frz->frzflags |= XLH_FREEZE_XVAC;
                               7296                 :                :     }
 1091 pg@bowt.ie               7297         [ +  + ]:CBC     4665109 :     if (replace_xmax)
                               7298                 :                :     {
                               7299   [ +  -  -  + ]:              1 :         Assert(!xmax_already_frozen && !freeze_xmax);
 1085                          7300         [ -  + ]:              1 :         Assert(pagefrz->freeze_required);
                               7301                 :                : 
                               7302                 :                :         /* Already set replace_xmax flags in freeze plan earlier */
                               7303                 :                :     }
 4402 alvherre@alvh.no-ip.     7304         [ +  + ]:        4665109 :     if (freeze_xmax)
                               7305                 :                :     {
 1091 pg@bowt.ie               7306   [ +  -  -  + ]:           2925 :         Assert(!xmax_already_frozen && !replace_xmax);
                               7307                 :                : 
 4384 alvherre@alvh.no-ip.     7308                 :           2925 :         frz->xmax = InvalidTransactionId;
                               7309                 :                : 
                               7310                 :                :         /*
                               7311                 :                :          * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
                               7312                 :                :          * LOCKED.  Normalize to INVALID just to be sure no one gets confused.
                               7313                 :                :          * Also get rid of the HEAP_KEYS_UPDATED bit.
                               7314                 :                :          */
                               7315                 :           2925 :         frz->t_infomask &= ~HEAP_XMAX_BITS;
                               7316                 :           2925 :         frz->t_infomask |= HEAP_XMAX_INVALID;
                               7317                 :           2925 :         frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
                               7318                 :           2925 :         frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               7319                 :                :     }
                               7320                 :                : 
                               7321                 :                :     /*
                               7322                 :                :      * Determine if this tuple is already totally frozen, or will become
                               7323                 :                :      * totally frozen (provided caller executes freeze plans for the page)
                               7324                 :                :      */
 1091 pg@bowt.ie               7325   [ +  +  +  +  :        8805126 :     *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
                                              +  + ]
                               7326         [ +  + ]:        4140017 :                        (freeze_xmax || xmax_already_frozen));
                               7327                 :                : 
 1085                          7328   [ +  +  +  +  :        4665109 :     if (!pagefrz->freeze_required && !(xmin_already_frozen &&
                                              +  + ]
                               7329                 :                :                                        xmax_already_frozen))
                               7330                 :                :     {
                               7331                 :                :         /*
                               7332                 :                :          * So far no previous tuple from the page made freezing mandatory.
                               7333                 :                :          * Does this tuple force caller to freeze the entire page?
                               7334                 :                :          */
                               7335                 :        2143870 :         pagefrz->freeze_required =
                               7336                 :        2143870 :             heap_tuple_should_freeze(tuple, cutoffs,
                               7337                 :                :                                      &pagefrz->NoFreezePageRelfrozenXid,
                               7338                 :                :                                      &pagefrz->NoFreezePageRelminMxid);
                               7339                 :                :     }
                               7340                 :                : 
                               7341                 :                :     /* Tell caller if this tuple has a usable freeze plan set in *frz */
 1091                          7342   [ +  +  +  -  :        4665109 :     return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
                                        +  -  +  + ]
                               7343                 :                : }
                               7344                 :                : 
                               7345                 :                : /*
                               7346                 :                :  * Perform xmin/xmax XID status sanity checks before actually executing freeze
                               7347                 :                :  * plans.
                               7348                 :                :  *
                               7349                 :                :  * heap_prepare_freeze_tuple doesn't perform these checks directly because
                               7350                 :                :  * pg_xact lookups are relatively expensive.  They shouldn't be repeated by
                               7351                 :                :  * successive VACUUMs that each decide against freezing the same page.
                               7352                 :                :  */
                               7353                 :                : void
  623 heikki.linnakangas@i     7354                 :          21586 : heap_pre_freeze_checks(Buffer buffer,
                               7355                 :                :                        HeapTupleFreeze *tuples, int ntuples)
                               7356                 :                : {
 1128 pg@bowt.ie               7357                 :          21586 :     Page        page = BufferGetPage(buffer);
                               7358                 :                : 
 1079                          7359         [ +  + ]:         977025 :     for (int i = 0; i < ntuples; i++)
                               7360                 :                :     {
                               7361                 :         955439 :         HeapTupleFreeze *frz = tuples + i;
                               7362                 :         955439 :         ItemId      itemid = PageGetItemId(page, frz->offset);
                               7363                 :                :         HeapTupleHeader htup;
                               7364                 :                : 
                               7365                 :         955439 :         htup = (HeapTupleHeader) PageGetItem(page, itemid);
                               7366                 :                : 
                               7367                 :                :         /* Deliberately avoid relying on tuple hint bits here */
                               7368         [ +  + ]:         955439 :         if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
                               7369                 :                :         {
                               7370                 :         955438 :             TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
                               7371                 :                : 
                               7372         [ -  + ]:         955438 :             Assert(!HeapTupleHeaderXminFrozen(htup));
                               7373         [ -  + ]:         955438 :             if (unlikely(!TransactionIdDidCommit(xmin)))
 1079 pg@bowt.ie               7374         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               7375                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               7376                 :                :                          errmsg_internal("uncommitted xmin %u needs to be frozen",
                               7377                 :                :                                          xmin)));
                               7378                 :                :         }
                               7379                 :                : 
                               7380                 :                :         /*
                               7381                 :                :          * TransactionIdDidAbort won't work reliably in the presence of XIDs
                               7382                 :                :          * left behind by transactions that were in progress during a crash,
                               7383                 :                :          * so we can only check that xmax didn't commit
                               7384                 :                :          */
 1079 pg@bowt.ie               7385         [ +  + ]:CBC      955439 :         if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
                               7386                 :                :         {
                               7387                 :            589 :             TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
                               7388                 :                : 
                               7389         [ -  + ]:            589 :             Assert(TransactionIdIsNormal(xmax));
                               7390         [ -  + ]:            589 :             if (unlikely(TransactionIdDidCommit(xmax)))
 1079 pg@bowt.ie               7391         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               7392                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               7393                 :                :                          errmsg_internal("cannot freeze committed xmax %u",
                               7394                 :                :                                          xmax)));
                               7395                 :                :         }
                               7396                 :                :     }
  623 heikki.linnakangas@i     7397                 :CBC       21586 : }
                               7398                 :                : 
                               7399                 :                : /*
                               7400                 :                :  * Helper which executes freezing of one or more heap tuples on a page on
                               7401                 :                :  * behalf of caller.  Caller passes an array of tuple plans from
                               7402                 :                :  * heap_prepare_freeze_tuple.  Caller must set 'offset' in each plan for us.
                               7403                 :                :  * Must be called in a critical section that also marks the buffer dirty and,
                               7404                 :                :  * if needed, emits WAL.
                               7405                 :                :  */
                               7406                 :                : void
                               7407                 :          21586 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
                               7408                 :                : {
                               7409                 :          21586 :     Page        page = BufferGetPage(buffer);
                               7410                 :                : 
 1128 pg@bowt.ie               7411         [ +  + ]:         977025 :     for (int i = 0; i < ntuples; i++)
                               7412                 :                :     {
 1079                          7413                 :         955439 :         HeapTupleFreeze *frz = tuples + i;
                               7414                 :         955439 :         ItemId      itemid = PageGetItemId(page, frz->offset);
                               7415                 :                :         HeapTupleHeader htup;
                               7416                 :                : 
 1128                          7417                 :         955439 :         htup = (HeapTupleHeader) PageGetItem(page, itemid);
 1079                          7418                 :         955439 :         heap_execute_freeze_tuple(htup, frz);
                               7419                 :                :     }
 1128                          7420                 :          21586 : }
                               7421                 :                : 
                               7422                 :                : /*
                               7423                 :                :  * heap_freeze_tuple
                               7424                 :                :  *      Freeze tuple in place, without WAL logging.
                               7425                 :                :  *
                               7426                 :                :  * Useful for callers like CLUSTER that perform their own WAL logging.
                               7427                 :                :  */
                               7428                 :                : bool
 2956 andres@anarazel.de       7429                 :         358489 : heap_freeze_tuple(HeapTupleHeader tuple,
                               7430                 :                :                   TransactionId relfrozenxid, TransactionId relminmxid,
                               7431                 :                :                   TransactionId FreezeLimit, TransactionId MultiXactCutoff)
                               7432                 :                : {
                               7433                 :                :     HeapTupleFreeze frz;
                               7434                 :                :     bool        do_freeze;
                               7435                 :                :     bool        totally_frozen;
                               7436                 :                :     struct VacuumCutoffs cutoffs;
                               7437                 :                :     HeapPageFreeze pagefrz;
                               7438                 :                : 
 1091 pg@bowt.ie               7439                 :         358489 :     cutoffs.relfrozenxid = relfrozenxid;
                               7440                 :         358489 :     cutoffs.relminmxid = relminmxid;
                               7441                 :         358489 :     cutoffs.OldestXmin = FreezeLimit;
                               7442                 :         358489 :     cutoffs.OldestMxact = MultiXactCutoff;
                               7443                 :         358489 :     cutoffs.FreezeLimit = FreezeLimit;
                               7444                 :         358489 :     cutoffs.MultiXactCutoff = MultiXactCutoff;
                               7445                 :                : 
 1085                          7446                 :         358489 :     pagefrz.freeze_required = true;
                               7447                 :         358489 :     pagefrz.FreezePageRelfrozenXid = FreezeLimit;
                               7448                 :         358489 :     pagefrz.FreezePageRelminMxid = MultiXactCutoff;
                               7449                 :         358489 :     pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
                               7450                 :         358489 :     pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
                               7451                 :                : 
 1091                          7452                 :         358489 :     do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
                               7453                 :                :                                           &pagefrz, &frz, &totally_frozen);
                               7454                 :                : 
                               7455                 :                :     /*
                               7456                 :                :      * Note that because this is not a WAL-logged operation, we don't need to
                               7457                 :                :      * fill in the offset in the freeze record.
                               7458                 :                :      */
                               7459                 :                : 
 4384 alvherre@alvh.no-ip.     7460         [ +  + ]:         358489 :     if (do_freeze)
                               7461                 :         276955 :         heap_execute_freeze_tuple(tuple, &frz);
                               7462                 :         358489 :     return do_freeze;
                               7463                 :                : }
                               7464                 :                : 
                               7465                 :                : /*
                               7466                 :                :  * For a given MultiXactId, return the hint bits that should be set in the
                               7467                 :                :  * tuple's infomask.
                               7468                 :                :  *
                               7469                 :                :  * Normally this should be called for a multixact that was just created, and
                               7470                 :                :  * so is on our local cache, so the GetMembers call is fast.
                               7471                 :                :  */
                               7472                 :                : static void
 4711                          7473                 :          76803 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
                               7474                 :                :                        uint16 *new_infomask2)
                               7475                 :                : {
                               7476                 :                :     int         nmembers;
                               7477                 :                :     MultiXactMember *members;
                               7478                 :                :     int         i;
 4585 bruce@momjian.us         7479                 :          76803 :     uint16      bits = HEAP_XMAX_IS_MULTI;
                               7480                 :          76803 :     uint16      bits2 = 0;
                               7481                 :          76803 :     bool        has_update = false;
                               7482                 :          76803 :     LockTupleMode strongest = LockTupleKeyShare;
                               7483                 :                : 
                               7484                 :                :     /*
                               7485                 :                :      * We only use this in multis we just created, so they cannot be values
                               7486                 :                :      * pre-pg_upgrade.
                               7487                 :                :      */
 4159 alvherre@alvh.no-ip.     7488                 :          76803 :     nmembers = GetMultiXactIdMembers(multi, &members, false, false);
                               7489                 :                : 
 4711                          7490         [ +  + ]:        1472621 :     for (i = 0; i < nmembers; i++)
                               7491                 :                :     {
                               7492                 :                :         LockTupleMode mode;
                               7493                 :                : 
                               7494                 :                :         /*
                               7495                 :                :          * Remember the strongest lock mode held by any member of the
                               7496                 :                :          * multixact.
                               7497                 :                :          */
 4703                          7498                 :        1395818 :         mode = TUPLOCK_from_mxstatus(members[i].status);
                               7499         [ +  + ]:        1395818 :         if (mode > strongest)
                               7500                 :           2888 :             strongest = mode;
                               7501                 :                : 
                               7502                 :                :         /* See what other bits we need */
 4711                          7503   [ +  +  +  +  :        1395818 :         switch (members[i].status)
                                                 - ]
                               7504                 :                :         {
                               7505                 :        1393400 :             case MultiXactStatusForKeyShare:
                               7506                 :                :             case MultiXactStatusForShare:
                               7507                 :                :             case MultiXactStatusForNoKeyUpdate:
                               7508                 :        1393400 :                 break;
                               7509                 :                : 
                               7510                 :             52 :             case MultiXactStatusForUpdate:
                               7511                 :             52 :                 bits2 |= HEAP_KEYS_UPDATED;
                               7512                 :             52 :                 break;
                               7513                 :                : 
                               7514                 :           2356 :             case MultiXactStatusNoKeyUpdate:
                               7515                 :           2356 :                 has_update = true;
                               7516                 :           2356 :                 break;
                               7517                 :                : 
                               7518                 :             10 :             case MultiXactStatusUpdate:
                               7519                 :             10 :                 bits2 |= HEAP_KEYS_UPDATED;
                               7520                 :             10 :                 has_update = true;
                               7521                 :             10 :                 break;
                               7522                 :                :         }
                               7523                 :                :     }
                               7524                 :                : 
 4703                          7525   [ +  +  +  + ]:          76803 :     if (strongest == LockTupleExclusive ||
                               7526                 :                :         strongest == LockTupleNoKeyExclusive)
                               7527                 :           2446 :         bits |= HEAP_XMAX_EXCL_LOCK;
                               7528         [ +  + ]:          74357 :     else if (strongest == LockTupleShare)
                               7529                 :            439 :         bits |= HEAP_XMAX_SHR_LOCK;
                               7530         [ +  - ]:          73918 :     else if (strongest == LockTupleKeyShare)
                               7531                 :          73918 :         bits |= HEAP_XMAX_KEYSHR_LOCK;
                               7532                 :                : 
 4711                          7533         [ +  + ]:          76803 :     if (!has_update)
                               7534                 :          74437 :         bits |= HEAP_XMAX_LOCK_ONLY;
                               7535                 :                : 
                               7536         [ +  - ]:          76803 :     if (nmembers > 0)
                               7537                 :          76803 :         pfree(members);
                               7538                 :                : 
                               7539                 :          76803 :     *new_infomask = bits;
                               7540                 :          76803 :     *new_infomask2 = bits2;
                               7541                 :          76803 : }
                               7542                 :                : 
                               7543                 :                : /*
                               7544                 :                :  * MultiXactIdGetUpdateXid
                               7545                 :                :  *
                               7546                 :                :  * Given a multixact Xmax and corresponding infomask, which does not have the
                               7547                 :                :  * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
                               7548                 :                :  * transaction.
                               7549                 :                :  *
                               7550                 :                :  * Caller is expected to check the status of the updating transaction, if
                               7551                 :                :  * necessary.
                               7552                 :                :  */
                               7553                 :                : static TransactionId
                               7554                 :         159929 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
                               7555                 :                : {
 4585 bruce@momjian.us         7556                 :         159929 :     TransactionId update_xact = InvalidTransactionId;
                               7557                 :                :     MultiXactMember *members;
                               7558                 :                :     int         nmembers;
                               7559                 :                : 
 4711 alvherre@alvh.no-ip.     7560         [ -  + ]:         159929 :     Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
                               7561         [ -  + ]:         159929 :     Assert(t_infomask & HEAP_XMAX_IS_MULTI);
                               7562                 :                : 
                               7563                 :                :     /*
                               7564                 :                :      * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
                               7565                 :                :      * pre-pg_upgrade.
                               7566                 :                :      */
 4159                          7567                 :         159929 :     nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
                               7568                 :                : 
 4711                          7569         [ +  - ]:         159929 :     if (nmembers > 0)
                               7570                 :                :     {
                               7571                 :                :         int         i;
                               7572                 :                : 
                               7573         [ +  + ]:        3191942 :         for (i = 0; i < nmembers; i++)
                               7574                 :                :         {
                               7575                 :                :             /* Ignore lockers */
 4401                          7576         [ +  + ]:        3032013 :             if (!ISUPDATE_from_mxstatus(members[i].status))
 4711                          7577                 :        2872084 :                 continue;
                               7578                 :                : 
                               7579                 :                :             /* there can be at most one updater */
                               7580         [ -  + ]:         159929 :             Assert(update_xact == InvalidTransactionId);
                               7581                 :         159929 :             update_xact = members[i].xid;
                               7582                 :                : #ifndef USE_ASSERT_CHECKING
                               7583                 :                : 
                               7584                 :                :             /*
                               7585                 :                :              * in an assert-enabled build, walk the whole array to ensure
                               7586                 :                :              * there's no other updater.
                               7587                 :                :              */
                               7588                 :                :             break;
                               7589                 :                : #endif
                               7590                 :                :         }
                               7591                 :                : 
                               7592                 :         159929 :         pfree(members);
                               7593                 :                :     }
                               7594                 :                : 
                               7595                 :         159929 :     return update_xact;
                               7596                 :                : }
                               7597                 :                : 
                               7598                 :                : /*
                               7599                 :                :  * HeapTupleGetUpdateXid
                               7600                 :                :  *      As above, but use a HeapTupleHeader
                               7601                 :                :  *
                               7602                 :                :  * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
                               7603                 :                :  * checking the hint bits.
                               7604                 :                :  */
                               7605                 :                : TransactionId
  328 peter@eisentraut.org     7606                 :         159921 : HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
                               7607                 :                : {
                               7608                 :         159921 :     return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tup),
                               7609                 :         159921 :                                    tup->t_infomask);
                               7610                 :                : }
                               7611                 :                : 
                               7612                 :                : /*
                               7613                 :                :  * Does the given multixact conflict with the current transaction grabbing a
                               7614                 :                :  * tuple lock of the given strength?
                               7615                 :                :  *
                               7616                 :                :  * The passed infomask pairs up with the given multixact in the tuple header.
                               7617                 :                :  *
                               7618                 :                :  * If current_is_member is not NULL, it is set to 'true' if the current
                               7619                 :                :  * transaction is a member of the given multixact.
                               7620                 :                :  */
                               7621                 :                : static bool
 4009 alvherre@alvh.no-ip.     7622                 :            218 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
                               7623                 :                :                         LockTupleMode lockmode, bool *current_is_member)
                               7624                 :                : {
                               7625                 :                :     int         nmembers;
                               7626                 :                :     MultiXactMember *members;
 3861 bruce@momjian.us         7627                 :            218 :     bool        result = false;
                               7628                 :            218 :     LOCKMODE    wanted = tupleLockExtraInfo[lockmode].hwlock;
                               7629                 :                : 
 3463 alvherre@alvh.no-ip.     7630         [ -  + ]:            218 :     if (HEAP_LOCKED_UPGRADED(infomask))
 3463 alvherre@alvh.no-ip.     7631                 :UBC           0 :         return false;
                               7632                 :                : 
 3463 alvherre@alvh.no-ip.     7633                 :CBC         218 :     nmembers = GetMultiXactIdMembers(multi, &members, false,
 4009                          7634                 :            218 :                                      HEAP_XMAX_IS_LOCKED_ONLY(infomask));
                               7635         [ +  - ]:            218 :     if (nmembers >= 0)
                               7636                 :                :     {
                               7637                 :                :         int         i;
                               7638                 :                : 
                               7639         [ +  + ]:           2682 :         for (i = 0; i < nmembers; i++)
                               7640                 :                :         {
                               7641                 :                :             TransactionId memxid;
                               7642                 :                :             LOCKMODE    memlockmode;
                               7643                 :                : 
 2374                          7644   [ +  +  +  +  :           2471 :             if (result && (current_is_member == NULL || *current_is_member))
                                              +  - ]
                               7645                 :                :                 break;
                               7646                 :                : 
                               7647                 :           2464 :             memlockmode = LOCKMODE_from_mxstatus(members[i].status);
                               7648                 :                : 
                               7649                 :                :             /* ignore members from current xact (but track their presence) */
 2376                          7650                 :           2464 :             memxid = members[i].xid;
                               7651         [ +  + ]:           2464 :             if (TransactionIdIsCurrentTransactionId(memxid))
                               7652                 :                :             {
 2374                          7653         [ +  + ]:             92 :                 if (current_is_member != NULL)
                               7654                 :             78 :                     *current_is_member = true;
                               7655                 :             92 :                 continue;
                               7656                 :                :             }
                               7657         [ +  + ]:           2372 :             else if (result)
                               7658                 :              8 :                 continue;
                               7659                 :                : 
                               7660                 :                :             /* ignore members that don't conflict with the lock we want */
                               7661         [ +  + ]:           2364 :             if (!DoLockModesConflict(memlockmode, wanted))
 2376                          7662                 :           2325 :                 continue;
                               7663                 :                : 
 4009                          7664         [ +  + ]:             39 :             if (ISUPDATE_from_mxstatus(members[i].status))
                               7665                 :                :             {
                               7666                 :                :                 /* ignore aborted updaters */
                               7667         [ +  + ]:             17 :                 if (TransactionIdDidAbort(memxid))
                               7668                 :              1 :                     continue;
                               7669                 :                :             }
                               7670                 :                :             else
                               7671                 :                :             {
                               7672                 :                :                 /* ignore lockers-only that are no longer in progress */
                               7673         [ +  + ]:             22 :                 if (!TransactionIdIsInProgress(memxid))
                               7674                 :              7 :                     continue;
                               7675                 :                :             }
                               7676                 :                : 
                               7677                 :                :             /*
                               7678                 :                :              * Whatever remains are either live lockers that conflict with our
                               7679                 :                :              * wanted lock, and updaters that are not aborted.  Those conflict
                               7680                 :                :              * with what we want.  Set up to return true, but keep going to
                               7681                 :                :              * look for the current transaction among the multixact members,
                               7682                 :                :              * if needed.
                               7683                 :                :              */
                               7684                 :             31 :             result = true;
                               7685                 :                :         }
                               7686                 :            218 :         pfree(members);
                               7687                 :                :     }
                               7688                 :                : 
                               7689                 :            218 :     return result;
                               7690                 :                : }
                               7691                 :                : 
                               7692                 :                : /*
                               7693                 :                :  * Do_MultiXactIdWait
                               7694                 :                :  *      Actual implementation for the two functions below.
                               7695                 :                :  *
                               7696                 :                :  * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
                               7697                 :                :  * needed to ensure we only sleep on conflicting members, and the infomask is
                               7698                 :                :  * used to optimize multixact access in case it's a lock-only multi); 'nowait'
                               7699                 :                :  * indicates whether to use conditional lock acquisition, to allow callers to
                               7700                 :                :  * fail if lock is unavailable.  'rel', 'ctid' and 'oper' are used to set up
                               7701                 :                :  * context information for error messages.  'remaining', if not NULL, receives
                               7702                 :                :  * the number of members that are still running, including any (non-aborted)
                               7703                 :                :  * subtransactions of our own transaction.  'logLockFailure' indicates whether
                               7704                 :                :  * to log details when a lock acquisition fails with 'nowait' enabled.
                               7705                 :                :  *
                               7706                 :                :  * We do this by sleeping on each member using XactLockTableWait.  Any
                               7707                 :                :  * members that belong to the current backend are *not* waited for, however;
                               7708                 :                :  * this would not merely be useless but would lead to Assert failure inside
                               7709                 :                :  * XactLockTableWait.  By the time this returns, it is certain that all
                               7710                 :                :  * transactions *of other backends* that were members of the MultiXactId
                               7711                 :                :  * that conflict with the requested status are dead (and no new ones can have
                               7712                 :                :  * been added, since it is not legal to add members to an existing
                               7713                 :                :  * MultiXactId).
                               7714                 :                :  *
                               7715                 :                :  * But by the time we finish sleeping, someone else may have changed the Xmax
                               7716                 :                :  * of the containing tuple, so the caller needs to iterate on us somehow.
                               7717                 :                :  *
                               7718                 :                :  * Note that in case we return false, the number of remaining members is
                               7719                 :                :  * not to be trusted.
                               7720                 :                :  */
                               7721                 :                : static bool
 4711                          7722                 :             58 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
                               7723                 :                :                    uint16 infomask, bool nowait,
                               7724                 :                :                    Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
                               7725                 :                :                    int *remaining, bool logLockFailure)
                               7726                 :                : {
                               7727                 :             58 :     bool        result = true;
                               7728                 :                :     MultiXactMember *members;
                               7729                 :                :     int         nmembers;
                               7730                 :             58 :     int         remain = 0;
                               7731                 :                : 
                               7732                 :                :     /* for pre-pg_upgrade tuples, no need to sleep at all */
 3463                          7733         [ +  - ]:             58 :     nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
                               7734                 :             58 :         GetMultiXactIdMembers(multi, &members, false,
                               7735                 :             58 :                               HEAP_XMAX_IS_LOCKED_ONLY(infomask));
                               7736                 :                : 
 4711                          7737         [ +  - ]:             58 :     if (nmembers >= 0)
                               7738                 :                :     {
                               7739                 :                :         int         i;
                               7740                 :                : 
                               7741         [ +  + ]:            187 :         for (i = 0; i < nmembers; i++)
                               7742                 :                :         {
                               7743                 :            133 :             TransactionId memxid = members[i].xid;
                               7744                 :            133 :             MultiXactStatus memstatus = members[i].status;
                               7745                 :                : 
                               7746         [ +  + ]:            133 :             if (TransactionIdIsCurrentTransactionId(memxid))
                               7747                 :                :             {
                               7748                 :             24 :                 remain++;
                               7749                 :             24 :                 continue;
                               7750                 :                :             }
                               7751                 :                : 
                               7752         [ +  + ]:            109 :             if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
                               7753                 :            109 :                                      LOCKMODE_from_mxstatus(status)))
                               7754                 :                :             {
                               7755   [ +  +  +  - ]:             22 :                 if (remaining && TransactionIdIsInProgress(memxid))
                               7756                 :              8 :                     remain++;
                               7757                 :             22 :                 continue;
                               7758                 :                :             }
                               7759                 :                : 
                               7760                 :                :             /*
                               7761                 :                :              * This member conflicts with our multi, so we have to sleep (or
                               7762                 :                :              * return failure, if asked to avoid waiting.)
                               7763                 :                :              *
                               7764                 :                :              * Note that we don't set up an error context callback ourselves,
                               7765                 :                :              * but instead we pass the info down to XactLockTableWait.  This
                               7766                 :                :              * might seem a bit wasteful because the context is set up and
                               7767                 :                :              * tore down for each member of the multixact, but in reality it
                               7768                 :                :              * should be barely noticeable, and it avoids duplicate code.
                               7769                 :                :              */
                               7770         [ +  + ]:             87 :             if (nowait)
                               7771                 :                :             {
  278 fujii@postgresql.org     7772                 :              4 :                 result = ConditionalXactLockTableWait(memxid, logLockFailure);
 4711 alvherre@alvh.no-ip.     7773         [ +  - ]:              4 :                 if (!result)
                               7774                 :              4 :                     break;
                               7775                 :                :             }
                               7776                 :                :             else
 4291                          7777                 :             83 :                 XactLockTableWait(memxid, rel, ctid, oper);
                               7778                 :                :         }
                               7779                 :                : 
 4711                          7780                 :             58 :         pfree(members);
                               7781                 :                :     }
                               7782                 :                : 
                               7783         [ +  + ]:             58 :     if (remaining)
                               7784                 :             10 :         *remaining = remain;
                               7785                 :                : 
                               7786                 :             58 :     return result;
                               7787                 :                : }
                               7788                 :                : 
                               7789                 :                : /*
                               7790                 :                :  * MultiXactIdWait
                               7791                 :                :  *      Sleep on a MultiXactId.
                               7792                 :                :  *
                               7793                 :                :  * By the time we finish sleeping, someone else may have changed the Xmax
                               7794                 :                :  * of the containing tuple, so the caller needs to iterate on us somehow.
                               7795                 :                :  *
                               7796                 :                :  * We return (in *remaining, if not NULL) the number of members that are still
                               7797                 :                :  * running, including any (non-aborted) subtransactions of our own transaction.
                               7798                 :                :  */
                               7799                 :                : static void
 4291                          7800                 :             54 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
                               7801                 :                :                 Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
                               7802                 :                :                 int *remaining)
                               7803                 :                : {
                               7804                 :             54 :     (void) Do_MultiXactIdWait(multi, status, infomask, false,
                               7805                 :                :                               rel, ctid, oper, remaining, false);
 4711                          7806                 :             54 : }
                               7807                 :                : 
                               7808                 :                : /*
                               7809                 :                :  * ConditionalMultiXactIdWait
                               7810                 :                :  *      As above, but only lock if we can get the lock without blocking.
                               7811                 :                :  *
                               7812                 :                :  * By the time we finish sleeping, someone else may have changed the Xmax
                               7813                 :                :  * of the containing tuple, so the caller needs to iterate on us somehow.
                               7814                 :                :  *
                               7815                 :                :  * If the multixact is now all gone, return true.  Returns false if some
                               7816                 :                :  * transactions might still be running.
                               7817                 :                :  *
                               7818                 :                :  * We return (in *remaining, if not NULL) the number of members that are still
                               7819                 :                :  * running, including any (non-aborted) subtransactions of our own transaction.
                               7820                 :                :  */
                               7821                 :                : static bool
                               7822                 :              4 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
                               7823                 :                :                            uint16 infomask, Relation rel, int *remaining,
                               7824                 :                :                            bool logLockFailure)
                               7825                 :                : {
 4291                          7826                 :              4 :     return Do_MultiXactIdWait(multi, status, infomask, true,
                               7827                 :                :                               rel, NULL, XLTW_None, remaining, logLockFailure);
                               7828                 :                : }
                               7829                 :                : 
                               7830                 :                : /*
                               7831                 :                :  * heap_tuple_needs_eventual_freeze
                               7832                 :                :  *
                               7833                 :                :  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
                               7834                 :                :  * will eventually require freezing (if tuple isn't removed by pruning first).
                               7835                 :                :  */
                               7836                 :                : bool
 3578 rhaas@postgresql.org     7837                 :        2309317 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
                               7838                 :                : {
                               7839                 :                :     TransactionId xid;
                               7840                 :                : 
                               7841                 :                :     /*
                               7842                 :                :      * If xmin is a normal transaction ID, this tuple is definitely not
                               7843                 :                :      * frozen.
                               7844                 :                :      */
                               7845                 :        2309317 :     xid = HeapTupleHeaderGetXmin(tuple);
                               7846         [ +  + ]:        2309317 :     if (TransactionIdIsNormal(xid))
                               7847                 :          15552 :         return true;
                               7848                 :                : 
                               7849                 :                :     /*
                               7850                 :                :      * If xmax is a valid xact or multixact, this tuple is also not frozen.
                               7851                 :                :      */
                               7852         [ +  + ]:        2293765 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
                               7853                 :                :     {
                               7854                 :                :         MultiXactId multi;
                               7855                 :                : 
                               7856                 :              2 :         multi = HeapTupleHeaderGetRawXmax(tuple);
                               7857         [ +  - ]:              2 :         if (MultiXactIdIsValid(multi))
                               7858                 :              2 :             return true;
                               7859                 :                :     }
                               7860                 :                :     else
                               7861                 :                :     {
                               7862                 :        2293763 :         xid = HeapTupleHeaderGetRawXmax(tuple);
                               7863         [ +  + ]:        2293763 :         if (TransactionIdIsNormal(xid))
                               7864                 :             13 :             return true;
                               7865                 :                :     }
                               7866                 :                : 
                               7867         [ -  + ]:        2293750 :     if (tuple->t_infomask & HEAP_MOVED)
                               7868                 :                :     {
 3578 rhaas@postgresql.org     7869                 :UBC           0 :         xid = HeapTupleHeaderGetXvac(tuple);
                               7870         [ #  # ]:              0 :         if (TransactionIdIsNormal(xid))
                               7871                 :              0 :             return true;
                               7872                 :                :     }
                               7873                 :                : 
 3578 rhaas@postgresql.org     7874                 :CBC     2293750 :     return false;
                               7875                 :                : }
                               7876                 :                : 
                               7877                 :                : /*
                               7878                 :                :  * heap_tuple_should_freeze
                               7879                 :                :  *
                               7880                 :                :  * Return value indicates if heap_prepare_freeze_tuple sibling function would
                               7881                 :                :  * (or should) force freezing of the heap page that contains caller's tuple.
                               7882                 :                :  * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
                               7883                 :                :  * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
                               7884                 :                :  *
                               7885                 :                :  * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
                               7886                 :                :  * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
                               7887                 :                :  * Our working assumption is that caller won't decide to freeze this tuple.
                               7888                 :                :  * It's up to caller to only ratchet back its own top-level trackers after the
                               7889                 :                :  * point that it fully commits to not freezing the tuple/page in question.
                               7890                 :                :  */
                               7891                 :                : bool
 1085 pg@bowt.ie               7892                 :        2144137 : heap_tuple_should_freeze(HeapTupleHeader tuple,
                               7893                 :                :                          const struct VacuumCutoffs *cutoffs,
                               7894                 :                :                          TransactionId *NoFreezePageRelfrozenXid,
                               7895                 :                :                          MultiXactId *NoFreezePageRelminMxid)
                               7896                 :                : {
                               7897                 :                :     TransactionId xid;
                               7898                 :                :     MultiXactId multi;
 1091                          7899                 :        2144137 :     bool        freeze = false;
                               7900                 :                : 
                               7901                 :                :     /* First deal with xmin */
 5154 rhaas@postgresql.org     7902                 :        2144137 :     xid = HeapTupleHeaderGetXmin(tuple);
 1354 pg@bowt.ie               7903         [ +  + ]:        2144137 :     if (TransactionIdIsNormal(xid))
                               7904                 :                :     {
 1091                          7905         [ -  + ]:        2103980 :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
 1085                          7906         [ +  + ]:        2103980 :         if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
                               7907                 :          21677 :             *NoFreezePageRelfrozenXid = xid;
 1091                          7908         [ +  + ]:        2103980 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
                               7909                 :          19040 :             freeze = true;
                               7910                 :                :     }
                               7911                 :                : 
                               7912                 :                :     /* Now deal with xmax */
 1354                          7913                 :        2144137 :     xid = InvalidTransactionId;
                               7914                 :        2144137 :     multi = InvalidMultiXactId;
                               7915         [ +  + ]:        2144137 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
 4402 alvherre@alvh.no-ip.     7916                 :              2 :         multi = HeapTupleHeaderGetRawXmax(tuple);
                               7917                 :                :     else
 1354 pg@bowt.ie               7918                 :        2144135 :         xid = HeapTupleHeaderGetRawXmax(tuple);
                               7919                 :                : 
                               7920         [ +  + ]:        2144137 :     if (TransactionIdIsNormal(xid))
                               7921                 :                :     {
 1091                          7922         [ -  + ]:         262430 :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
                               7923                 :                :         /* xmax is a non-permanent XID */
 1085                          7924         [ +  + ]:         262430 :         if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
                               7925                 :              4 :             *NoFreezePageRelfrozenXid = xid;
 1091                          7926         [ +  + ]:         262430 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
                               7927                 :              3 :             freeze = true;
                               7928                 :                :     }
 1354                          7929         [ +  + ]:        1881707 :     else if (!MultiXactIdIsValid(multi))
                               7930                 :                :     {
                               7931                 :                :         /* xmax is a permanent XID or invalid MultiXactId/XID */
                               7932                 :                :     }
                               7933         [ -  + ]:              2 :     else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
                               7934                 :                :     {
                               7935                 :                :         /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
 1085 pg@bowt.ie               7936         [ #  # ]:UBC           0 :         if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
                               7937                 :              0 :             *NoFreezePageRelminMxid = multi;
                               7938                 :                :         /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
 1091                          7939                 :              0 :         freeze = true;
                               7940                 :                :     }
                               7941                 :                :     else
                               7942                 :                :     {
                               7943                 :                :         /* xmax is a MultiXactId that may have an updater XID */
                               7944                 :                :         MultiXactMember *members;
                               7945                 :                :         int         nmembers;
                               7946                 :                : 
 1091 pg@bowt.ie               7947         [ -  + ]:CBC           2 :         Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
 1085                          7948         [ +  - ]:              2 :         if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
                               7949                 :              2 :             *NoFreezePageRelminMxid = multi;
 1091                          7950         [ +  - ]:              2 :         if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
                               7951                 :              2 :             freeze = true;
                               7952                 :                : 
                               7953                 :                :         /* need to check whether any member of the mxact is old */
 1354                          7954                 :              2 :         nmembers = GetMultiXactIdMembers(multi, &members, false,
                               7955                 :              2 :                                          HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
                               7956                 :                : 
                               7957         [ +  + ]:              5 :         for (int i = 0; i < nmembers; i++)
                               7958                 :                :         {
                               7959                 :              3 :             xid = members[i].xid;
 1091                          7960         [ -  + ]:              3 :             Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
 1085                          7961         [ -  + ]:              3 :             if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
 1085 pg@bowt.ie               7962                 :UBC           0 :                 *NoFreezePageRelfrozenXid = xid;
 1091 pg@bowt.ie               7963         [ -  + ]:CBC           3 :             if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
 1091 pg@bowt.ie               7964                 :UBC           0 :                 freeze = true;
                               7965                 :                :         }
 1354 pg@bowt.ie               7966         [ +  + ]:CBC           2 :         if (nmembers > 0)
                               7967                 :              1 :             pfree(members);
                               7968                 :                :     }
                               7969                 :                : 
 5154 rhaas@postgresql.org     7970         [ -  + ]:        2144137 :     if (tuple->t_infomask & HEAP_MOVED)
                               7971                 :                :     {
 5154 rhaas@postgresql.org     7972                 :UBC           0 :         xid = HeapTupleHeaderGetXvac(tuple);
 1354 pg@bowt.ie               7973         [ #  # ]:              0 :         if (TransactionIdIsNormal(xid))
                               7974                 :                :         {
 1091                          7975         [ #  # ]:              0 :             Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
 1085                          7976         [ #  # ]:              0 :             if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
                               7977                 :              0 :                 *NoFreezePageRelfrozenXid = xid;
                               7978                 :                :             /* heap_prepare_freeze_tuple forces xvac freezing */
 1091                          7979                 :              0 :             freeze = true;
                               7980                 :                :         }
                               7981                 :                :     }
                               7982                 :                : 
 1091 pg@bowt.ie               7983                 :CBC     2144137 :     return freeze;
                               7984                 :                : }
                               7985                 :                : 
                               7986                 :                : /*
                               7987                 :                :  * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
                               7988                 :                :  * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
                               7989                 :                :  * that caller is in the process of physically removing, e.g. via HOT pruning
                               7990                 :                :  * or index deletion.
                               7991                 :                :  *
                               7992                 :                :  * Caller must initialize its value to InvalidTransactionId, which is
                               7993                 :                :  * generally interpreted as "definitely no need for a recovery conflict".
                               7994                 :                :  * Final value must reflect all heap tuples that caller will physically remove
                               7995                 :                :  * (or remove TID references to) via its ongoing pruning/deletion operation.
                               7996                 :                :  * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
                               7997                 :                :  * caller's WAL record) by REDO routine when it replays caller's operation.
                               7998                 :                :  */
                               7999                 :                : void
 1126                          8000                 :        1566612 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
                               8001                 :                :                                       TransactionId *snapshotConflictHorizon)
                               8002                 :                : {
 5842 simon@2ndQuadrant.co     8003                 :        1566612 :     TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
 4711 alvherre@alvh.no-ip.     8004                 :        1566612 :     TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
 5842 simon@2ndQuadrant.co     8005                 :        1566612 :     TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
                               8006                 :                : 
 5791 tgl@sss.pgh.pa.us        8007         [ -  + ]:        1566612 :     if (tuple->t_infomask & HEAP_MOVED)
                               8008                 :                :     {
 1126 pg@bowt.ie               8009         [ #  # ]:UBC           0 :         if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
                               8010                 :              0 :             *snapshotConflictHorizon = xvac;
                               8011                 :                :     }
                               8012                 :                : 
                               8013                 :                :     /*
                               8014                 :                :      * Ignore tuples inserted by an aborted transaction or if the tuple was
                               8015                 :                :      * updated/deleted by the inserting transaction.
                               8016                 :                :      *
                               8017                 :                :      * Look for a committed hint bit, or if no xmin bit is set, check clog.
                               8018                 :                :      */
 4378 rhaas@postgresql.org     8019         [ +  + ]:CBC     1566612 :     if (HeapTupleHeaderXminCommitted(tuple) ||
                               8020   [ +  +  +  - ]:         106711 :         (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
                               8021                 :                :     {
 5487 simon@2ndQuadrant.co     8022   [ +  +  +  + ]:        2813310 :         if (xmax != xmin &&
 1126 pg@bowt.ie               8023                 :        1326464 :             TransactionIdFollows(xmax, *snapshotConflictHorizon))
                               8024                 :         101146 :             *snapshotConflictHorizon = xmax;
                               8025                 :                :     }
 5842 simon@2ndQuadrant.co     8026                 :        1566612 : }
                               8027                 :                : 
                               8028                 :                : #ifdef USE_PREFETCH
                               8029                 :                : /*
                               8030                 :                :  * Helper function for heap_index_delete_tuples.  Issues prefetch requests for
                               8031                 :                :  * prefetch_count buffers.  The prefetch_state keeps track of all the buffers
                               8032                 :                :  * we can prefetch, and which have already been prefetched; each call to this
                               8033                 :                :  * function picks up where the previous call left off.
                               8034                 :                :  *
                               8035                 :                :  * Note: we expect the deltids array to be sorted in an order that groups TIDs
                               8036                 :                :  * by heap block, with all TIDs for each block appearing together in exactly
                               8037                 :                :  * one group.
                               8038                 :                :  */
                               8039                 :                : static void
 1799 pg@bowt.ie               8040                 :          20048 : index_delete_prefetch_buffer(Relation rel,
                               8041                 :                :                              IndexDeletePrefetchState *prefetch_state,
                               8042                 :                :                              int prefetch_count)
                               8043                 :                : {
 2458 andres@anarazel.de       8044                 :          20048 :     BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
                               8045                 :          20048 :     int         count = 0;
                               8046                 :                :     int         i;
 1799 pg@bowt.ie               8047                 :          20048 :     int         ndeltids = prefetch_state->ndeltids;
                               8048                 :          20048 :     TM_IndexDelete *deltids = prefetch_state->deltids;
                               8049                 :                : 
 2458 andres@anarazel.de       8050                 :          20048 :     for (i = prefetch_state->next_item;
 1799 pg@bowt.ie               8051   [ +  +  +  + ]:         689653 :          i < ndeltids && count < prefetch_count;
 2458 andres@anarazel.de       8052                 :         669605 :          i++)
                               8053                 :                :     {
 1799 pg@bowt.ie               8054                 :         669605 :         ItemPointer htid = &deltids[i].tid;
                               8055                 :                : 
 2458 andres@anarazel.de       8056   [ +  +  +  + ]:        1333329 :         if (cur_hblkno == InvalidBlockNumber ||
                               8057                 :         663724 :             ItemPointerGetBlockNumber(htid) != cur_hblkno)
                               8058                 :                :         {
                               8059                 :          18299 :             cur_hblkno = ItemPointerGetBlockNumber(htid);
                               8060                 :          18299 :             PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
                               8061                 :          18299 :             count++;
                               8062                 :                :         }
                               8063                 :                :     }
                               8064                 :                : 
                               8065                 :                :     /*
                               8066                 :                :      * Save the prefetch position so that next time we can continue from that
                               8067                 :                :      * position.
                               8068                 :                :      */
                               8069                 :          20048 :     prefetch_state->next_item = i;
                               8070                 :          20048 :     prefetch_state->cur_hblkno = cur_hblkno;
                               8071                 :          20048 : }
                               8072                 :                : #endif
                               8073                 :                : 
                               8074                 :                : /*
                               8075                 :                :  * Helper function for heap_index_delete_tuples.  Checks for index corruption
                               8076                 :                :  * involving an invalid TID in index AM caller's index page.
                               8077                 :                :  *
                               8078                 :                :  * This is an ideal place for these checks.  The index AM must hold a buffer
                               8079                 :                :  * lock on the index page containing the TIDs we examine here, so we don't
                               8080                 :                :  * have to worry about concurrent VACUUMs at all.  We can be sure that the
                               8081                 :                :  * index is corrupt when htid points directly to an LP_UNUSED item or
                               8082                 :                :  * heap-only tuple, which is not the case during standard index scans.
                               8083                 :                :  */
                               8084                 :                : static inline void
 1504 pg@bowt.ie               8085                 :         555378 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
                               8086                 :                :                         Page page, OffsetNumber maxoff,
                               8087                 :                :                         const ItemPointerData *htid, TM_IndexStatus *istatus)
                               8088                 :                : {
                               8089                 :         555378 :     OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
                               8090                 :                :     ItemId      iid;
                               8091                 :                : 
                               8092   [ +  -  +  -  :         555378 :     Assert(OffsetNumberIsValid(istatus->idxoffnum));
                                              -  + ]
                               8093                 :                : 
                               8094         [ -  + ]:         555378 :     if (unlikely(indexpagehoffnum > maxoff))
 1504 pg@bowt.ie               8095         [ #  # ]:UBC           0 :         ereport(ERROR,
                               8096                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               8097                 :                :                  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\"",
                               8098                 :                :                                  ItemPointerGetBlockNumber(htid),
                               8099                 :                :                                  indexpagehoffnum,
                               8100                 :                :                                  istatus->idxoffnum, delstate->iblknum,
                               8101                 :                :                                  RelationGetRelationName(delstate->irel))));
                               8102                 :                : 
 1504 pg@bowt.ie               8103                 :CBC      555378 :     iid = PageGetItemId(page, indexpagehoffnum);
                               8104         [ -  + ]:         555378 :     if (unlikely(!ItemIdIsUsed(iid)))
 1504 pg@bowt.ie               8105         [ #  # ]:UBC           0 :         ereport(ERROR,
                               8106                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               8107                 :                :                  errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
                               8108                 :                :                                  ItemPointerGetBlockNumber(htid),
                               8109                 :                :                                  indexpagehoffnum,
                               8110                 :                :                                  istatus->idxoffnum, delstate->iblknum,
                               8111                 :                :                                  RelationGetRelationName(delstate->irel))));
                               8112                 :                : 
 1504 pg@bowt.ie               8113         [ +  + ]:CBC      555378 :     if (ItemIdHasStorage(iid))
                               8114                 :                :     {
                               8115                 :                :         HeapTupleHeader htup;
                               8116                 :                : 
                               8117         [ -  + ]:         328532 :         Assert(ItemIdIsNormal(iid));
                               8118                 :         328532 :         htup = (HeapTupleHeader) PageGetItem(page, iid);
                               8119                 :                : 
                               8120         [ -  + ]:         328532 :         if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
 1504 pg@bowt.ie               8121         [ #  # ]:UBC           0 :             ereport(ERROR,
                               8122                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               8123                 :                :                      errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
                               8124                 :                :                                      ItemPointerGetBlockNumber(htid),
                               8125                 :                :                                      indexpagehoffnum,
                               8126                 :                :                                      istatus->idxoffnum, delstate->iblknum,
                               8127                 :                :                                      RelationGetRelationName(delstate->irel))));
                               8128                 :                :     }
 1504 pg@bowt.ie               8129                 :CBC      555378 : }
                               8130                 :                : 
                               8131                 :                : /*
                               8132                 :                :  * heapam implementation of tableam's index_delete_tuples interface.
                               8133                 :                :  *
                               8134                 :                :  * This helper function is called by index AMs during index tuple deletion.
                               8135                 :                :  * See tableam header comments for an explanation of the interface implemented
                               8136                 :                :  * here and a general theory of operation.  Note that each call here is either
                               8137                 :                :  * a simple index deletion call, or a bottom-up index deletion call.
                               8138                 :                :  *
                               8139                 :                :  * It's possible for this to generate a fair amount of I/O, since we may be
                               8140                 :                :  * deleting hundreds of tuples from a single index block.  To amortize that
                               8141                 :                :  * cost to some degree, this uses prefetching and combines repeat accesses to
                               8142                 :                :  * the same heap block.
                               8143                 :                :  */
                               8144                 :                : TransactionId
 1799                          8145                 :           5881 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
                               8146                 :                : {
                               8147                 :                :     /* Initial assumption is that earlier pruning took care of conflict */
 1126                          8148                 :           5881 :     TransactionId snapshotConflictHorizon = InvalidTransactionId;
 1813                          8149                 :           5881 :     BlockNumber blkno = InvalidBlockNumber;
 2458 andres@anarazel.de       8150                 :           5881 :     Buffer      buf = InvalidBuffer;
 1813 pg@bowt.ie               8151                 :           5881 :     Page        page = NULL;
                               8152                 :           5881 :     OffsetNumber maxoff = InvalidOffsetNumber;
                               8153                 :                :     TransactionId priorXmax;
                               8154                 :                : #ifdef USE_PREFETCH
                               8155                 :                :     IndexDeletePrefetchState prefetch_state;
                               8156                 :                :     int         prefetch_distance;
                               8157                 :                : #endif
                               8158                 :                :     SnapshotData SnapshotNonVacuumable;
 1799                          8159                 :           5881 :     int         finalndeltids = 0,
                               8160                 :           5881 :                 nblocksaccessed = 0;
                               8161                 :                : 
                               8162                 :                :     /* State that's only used in bottom-up index deletion case */
                               8163                 :           5881 :     int         nblocksfavorable = 0;
                               8164                 :           5881 :     int         curtargetfreespace = delstate->bottomupfreespace,
                               8165                 :           5881 :                 lastfreespace = 0,
                               8166                 :           5881 :                 actualfreespace = 0;
                               8167                 :           5881 :     bool        bottomup_final_block = false;
                               8168                 :                : 
                               8169                 :           5881 :     InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
                               8170                 :                : 
                               8171                 :                :     /* Sort caller's deltids array by TID for further processing */
                               8172                 :           5881 :     index_delete_sort(delstate);
                               8173                 :                : 
                               8174                 :                :     /*
                               8175                 :                :      * Bottom-up case: resort deltids array in an order attuned to where the
                               8176                 :                :      * greatest number of promising TIDs are to be found, and determine how
                               8177                 :                :      * many blocks from the start of sorted array should be considered
                               8178                 :                :      * favorable.  This will also shrink the deltids array in order to
                               8179                 :                :      * eliminate completely unfavorable blocks up front.
                               8180                 :                :      */
                               8181         [ +  + ]:           5881 :     if (delstate->bottomup)
                               8182                 :           1981 :         nblocksfavorable = bottomup_sort_and_shrink(delstate);
                               8183                 :                : 
                               8184                 :                : #ifdef USE_PREFETCH
                               8185                 :                :     /* Initialize prefetch state. */
 2458 andres@anarazel.de       8186                 :           5881 :     prefetch_state.cur_hblkno = InvalidBlockNumber;
                               8187                 :           5881 :     prefetch_state.next_item = 0;
 1799 pg@bowt.ie               8188                 :           5881 :     prefetch_state.ndeltids = delstate->ndeltids;
                               8189                 :           5881 :     prefetch_state.deltids = delstate->deltids;
                               8190                 :                : 
                               8191                 :                :     /*
                               8192                 :                :      * Determine the prefetch distance that we will attempt to maintain.
                               8193                 :                :      *
                               8194                 :                :      * Since the caller holds a buffer lock somewhere in rel, we'd better make
                               8195                 :                :      * sure that isn't a catalog relation before we call code that does
                               8196                 :                :      * syscache lookups, to avoid risk of deadlock.
                               8197                 :                :      */
 2451 tmunro@postgresql.or     8198         [ +  + ]:           5881 :     if (IsCatalogRelation(rel))
 2102                          8199                 :           4284 :         prefetch_distance = maintenance_io_concurrency;
                               8200                 :                :     else
                               8201                 :                :         prefetch_distance =
                               8202                 :           1597 :             get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
                               8203                 :                : 
                               8204                 :                :     /* Cap initial prefetch distance for bottom-up deletion caller */
 1799 pg@bowt.ie               8205         [ +  + ]:           5881 :     if (delstate->bottomup)
                               8206                 :                :     {
                               8207         [ -  + ]:           1981 :         Assert(nblocksfavorable >= 1);
                               8208         [ -  + ]:           1981 :         Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
                               8209                 :           1981 :         prefetch_distance = Min(prefetch_distance, nblocksfavorable);
                               8210                 :                :     }
                               8211                 :                : 
                               8212                 :                :     /* Start prefetching. */
                               8213                 :           5881 :     index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
                               8214                 :                : #endif
                               8215                 :                : 
                               8216                 :                :     /* Iterate over deltids, determine which to delete, check their horizon */
                               8217         [ -  + ]:           5881 :     Assert(delstate->ndeltids > 0);
                               8218         [ +  + ]:         561259 :     for (int i = 0; i < delstate->ndeltids; i++)
                               8219                 :                :     {
                               8220                 :         557359 :         TM_IndexDelete *ideltid = &delstate->deltids[i];
                               8221                 :         557359 :         TM_IndexStatus *istatus = delstate->status + ideltid->id;
                               8222                 :         557359 :         ItemPointer htid = &ideltid->tid;
                               8223                 :                :         OffsetNumber offnum;
                               8224                 :                : 
                               8225                 :                :         /*
                               8226                 :                :          * Read buffer, and perform required extra steps each time a new block
                               8227                 :                :          * is encountered.  Avoid refetching if it's the same block as the one
                               8228                 :                :          * from the last htid.
                               8229                 :                :          */
 1813                          8230   [ +  +  +  + ]:        1108837 :         if (blkno == InvalidBlockNumber ||
                               8231                 :         551478 :             ItemPointerGetBlockNumber(htid) != blkno)
                               8232                 :                :         {
                               8233                 :                :             /*
                               8234                 :                :              * Consider giving up early for bottom-up index deletion caller
                               8235                 :                :              * first. (Only prefetch next-next block afterwards, when it
                               8236                 :                :              * becomes clear that we're at least going to access the next
                               8237                 :                :              * block in line.)
                               8238                 :                :              *
                               8239                 :                :              * Sometimes the first block frees so much space for bottom-up
                               8240                 :                :              * caller that the deletion process can end without accessing any
                               8241                 :                :              * more blocks.  It is usually necessary to access 2 or 3 blocks
                               8242                 :                :              * per bottom-up deletion operation, though.
                               8243                 :                :              */
 1799                          8244         [ +  + ]:          16148 :             if (delstate->bottomup)
                               8245                 :                :             {
                               8246                 :                :                 /*
                               8247                 :                :                  * We often allow caller to delete a few additional items
                               8248                 :                :                  * whose entries we reached after the point that space target
                               8249                 :                :                  * from caller was satisfied.  The cost of accessing the page
                               8250                 :                :                  * was already paid at that point, so it made sense to finish
                               8251                 :                :                  * it off.  When that happened, we finalize everything here
                               8252                 :                :                  * (by finishing off the whole bottom-up deletion operation
                               8253                 :                :                  * without needlessly paying the cost of accessing any more
                               8254                 :                :                  * blocks).
                               8255                 :                :                  */
                               8256         [ +  + ]:           4360 :                 if (bottomup_final_block)
                               8257                 :            133 :                     break;
                               8258                 :                : 
                               8259                 :                :                 /*
                               8260                 :                :                  * Give up when we didn't enable our caller to free any
                               8261                 :                :                  * additional space as a result of processing the page that we
                               8262                 :                :                  * just finished up with.  This rule is the main way in which
                               8263                 :                :                  * we keep the cost of bottom-up deletion under control.
                               8264                 :                :                  */
                               8265   [ +  +  +  + ]:           4227 :                 if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
                               8266                 :           1848 :                     break;
                               8267                 :           2379 :                 lastfreespace = actualfreespace;    /* for next time */
                               8268                 :                : 
                               8269                 :                :                 /*
                               8270                 :                :                  * Deletion operation (which is bottom-up) will definitely
                               8271                 :                :                  * access the next block in line.  Prepare for that now.
                               8272                 :                :                  *
                               8273                 :                :                  * Decay target free space so that we don't hang on for too
                               8274                 :                :                  * long with a marginal case. (Space target is only truly
                               8275                 :                :                  * helpful when it allows us to recognize that we don't need
                               8276                 :                :                  * to access more than 1 or 2 blocks to satisfy caller due to
                               8277                 :                :                  * agreeable workload characteristics.)
                               8278                 :                :                  *
                               8279                 :                :                  * We are a bit more patient when we encounter contiguous
                               8280                 :                :                  * blocks, though: these are treated as favorable blocks.  The
                               8281                 :                :                  * decay process is only applied when the next block in line
                               8282                 :                :                  * is not a favorable/contiguous block.  This is not an
                               8283                 :                :                  * exception to the general rule; we still insist on finding
                               8284                 :                :                  * at least one deletable item per block accessed.  See
                               8285                 :                :                  * bottomup_nblocksfavorable() for full details of the theory
                               8286                 :                :                  * behind favorable blocks and heap block locality in general.
                               8287                 :                :                  *
                               8288                 :                :                  * Note: The first block in line is always treated as a
                               8289                 :                :                  * favorable block, so the earliest possible point that the
                               8290                 :                :                  * decay can be applied is just before we access the second
                               8291                 :                :                  * block in line.  The Assert() verifies this for us.
                               8292                 :                :                  */
                               8293   [ +  +  -  + ]:           2379 :                 Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
                               8294         [ +  + ]:           2379 :                 if (nblocksfavorable > 0)
                               8295                 :           2153 :                     nblocksfavorable--;
                               8296                 :                :                 else
                               8297                 :            226 :                     curtargetfreespace /= 2;
                               8298                 :                :             }
                               8299                 :                : 
                               8300                 :                :             /* release old buffer */
                               8301         [ +  + ]:          14167 :             if (BufferIsValid(buf))
                               8302                 :           8286 :                 UnlockReleaseBuffer(buf);
                               8303                 :                : 
                               8304                 :          14167 :             blkno = ItemPointerGetBlockNumber(htid);
 1813                          8305                 :          14167 :             buf = ReadBuffer(rel, blkno);
 1799                          8306                 :          14167 :             nblocksaccessed++;
                               8307   [ +  +  -  + ]:          14167 :             Assert(!delstate->bottomup ||
                               8308                 :                :                    nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
                               8309                 :                : 
                               8310                 :                : #ifdef USE_PREFETCH
                               8311                 :                : 
                               8312                 :                :             /*
                               8313                 :                :              * To maintain the prefetch distance, prefetch one more page for
                               8314                 :                :              * each page we read.
                               8315                 :                :              */
                               8316                 :          14167 :             index_delete_prefetch_buffer(rel, &prefetch_state, 1);
                               8317                 :                : #endif
                               8318                 :                : 
 1813                          8319                 :          14167 :             LockBuffer(buf, BUFFER_LOCK_SHARE);
                               8320                 :                : 
                               8321                 :          14167 :             page = BufferGetPage(buf);
                               8322                 :          14167 :             maxoff = PageGetMaxOffsetNumber(page);
                               8323                 :                :         }
                               8324                 :                : 
                               8325                 :                :         /*
                               8326                 :                :          * In passing, detect index corruption involving an index page with a
                               8327                 :                :          * TID that points to a location in the heap that couldn't possibly be
                               8328                 :                :          * correct.  We only do this with actual TIDs from caller's index page
                               8329                 :                :          * (not items reached by traversing through a HOT chain).
                               8330                 :                :          */
 1504                          8331                 :         555378 :         index_delete_check_htid(delstate, page, maxoff, htid, istatus);
                               8332                 :                : 
 1799                          8333         [ +  + ]:         555378 :         if (istatus->knowndeletable)
                               8334   [ +  -  -  + ]:         138272 :             Assert(!delstate->bottomup && !istatus->promising);
                               8335                 :                :         else
                               8336                 :                :         {
                               8337                 :         417106 :             ItemPointerData tmp = *htid;
                               8338                 :                :             HeapTupleData heapTuple;
                               8339                 :                : 
                               8340                 :                :             /* Are any tuples from this HOT chain non-vacuumable? */
                               8341         [ +  + ]:         417106 :             if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
                               8342                 :                :                                        &heapTuple, NULL, true))
                               8343                 :         250167 :                 continue;       /* can't delete entry */
                               8344                 :                : 
                               8345                 :                :             /* Caller will delete, since whole HOT chain is vacuumable */
                               8346                 :         166939 :             istatus->knowndeletable = true;
                               8347                 :                : 
                               8348                 :                :             /* Maintain index free space info for bottom-up deletion case */
                               8349         [ +  + ]:         166939 :             if (delstate->bottomup)
                               8350                 :                :             {
                               8351         [ -  + ]:           8229 :                 Assert(istatus->freespace > 0);
                               8352                 :           8229 :                 actualfreespace += istatus->freespace;
                               8353         [ +  + ]:           8229 :                 if (actualfreespace >= curtargetfreespace)
                               8354                 :           2137 :                     bottomup_final_block = true;
                               8355                 :                :             }
                               8356                 :                :         }
                               8357                 :                : 
                               8358                 :                :         /*
                               8359                 :                :          * Maintain snapshotConflictHorizon value for deletion operation as a
                               8360                 :                :          * whole by advancing current value using heap tuple headers.  This is
                               8361                 :                :          * loosely based on the logic for pruning a HOT chain.
                               8362                 :                :          */
 1813                          8363                 :         305211 :         offnum = ItemPointerGetOffsetNumber(htid);
                               8364                 :         305211 :         priorXmax = InvalidTransactionId;   /* cannot check first XMIN */
                               8365                 :                :         for (;;)
 2458 andres@anarazel.de       8366                 :          20964 :         {
                               8367                 :                :             ItemId      lp;
                               8368                 :                :             HeapTupleHeader htup;
                               8369                 :                : 
                               8370                 :                :             /* Sanity check (pure paranoia) */
 1547 pg@bowt.ie               8371         [ -  + ]:         326175 :             if (offnum < FirstOffsetNumber)
 1547 pg@bowt.ie               8372                 :UBC           0 :                 break;
                               8373                 :                : 
                               8374                 :                :             /*
                               8375                 :                :              * An offset past the end of page's line pointer array is possible
                               8376                 :                :              * when the array was truncated
                               8377                 :                :              */
 1547 pg@bowt.ie               8378         [ -  + ]:CBC      326175 :             if (offnum > maxoff)
 1813 pg@bowt.ie               8379                 :UBC           0 :                 break;
                               8380                 :                : 
 1813 pg@bowt.ie               8381                 :CBC      326175 :             lp = PageGetItemId(page, offnum);
                               8382         [ +  + ]:         326175 :             if (ItemIdIsRedirected(lp))
                               8383                 :                :             {
                               8384                 :           9398 :                 offnum = ItemIdGetRedirect(lp);
                               8385                 :           9398 :                 continue;
                               8386                 :                :             }
                               8387                 :                : 
                               8388                 :                :             /*
                               8389                 :                :              * We'll often encounter LP_DEAD line pointers (especially with an
                               8390                 :                :              * entry marked knowndeletable by our caller up front).  No heap
                               8391                 :                :              * tuple headers get examined for an htid that leads us to an
                               8392                 :                :              * LP_DEAD item.  This is okay because the earlier pruning
                               8393                 :                :              * operation that made the line pointer LP_DEAD in the first place
                               8394                 :                :              * must have considered the original tuple header as part of
                               8395                 :                :              * generating its own snapshotConflictHorizon value.
                               8396                 :                :              *
                               8397                 :                :              * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
                               8398                 :                :              * the same strategy that index vacuuming uses in all cases. Index
                               8399                 :                :              * VACUUM WAL records don't even have a snapshotConflictHorizon
                               8400                 :                :              * field of their own for this reason.
                               8401                 :                :              */
                               8402         [ +  + ]:         316777 :             if (!ItemIdIsNormal(lp))
                               8403                 :         201051 :                 break;
                               8404                 :                : 
                               8405                 :         115726 :             htup = (HeapTupleHeader) PageGetItem(page, lp);
                               8406                 :                : 
                               8407                 :                :             /*
                               8408                 :                :              * Check the tuple XMIN against prior XMAX, if any
                               8409                 :                :              */
                               8410   [ +  +  -  + ]:         127292 :             if (TransactionIdIsValid(priorXmax) &&
                               8411                 :          11566 :                 !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
 1813 pg@bowt.ie               8412                 :UBC           0 :                 break;
                               8413                 :                : 
 1126 pg@bowt.ie               8414                 :CBC      115726 :             HeapTupleHeaderAdvanceConflictHorizon(htup,
                               8415                 :                :                                                   &snapshotConflictHorizon);
                               8416                 :                : 
                               8417                 :                :             /*
                               8418                 :                :              * If the tuple is not HOT-updated, then we are at the end of this
                               8419                 :                :              * HOT-chain.  No need to visit later tuples from the same update
                               8420                 :                :              * chain (they get their own index entries) -- just move on to
                               8421                 :                :              * next htid from index AM caller.
                               8422                 :                :              */
 1813                          8423         [ +  + ]:         115726 :             if (!HeapTupleHeaderIsHotUpdated(htup))
                               8424                 :         104160 :                 break;
                               8425                 :                : 
                               8426                 :                :             /* Advance to next HOT chain member */
                               8427         [ -  + ]:          11566 :             Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
                               8428                 :          11566 :             offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
                               8429                 :          11566 :             priorXmax = HeapTupleHeaderGetUpdateXid(htup);
                               8430                 :                :         }
                               8431                 :                : 
                               8432                 :                :         /* Enable further/final shrinking of deltids for caller */
 1799                          8433                 :         305211 :         finalndeltids = i + 1;
                               8434                 :                :     }
                               8435                 :                : 
                               8436                 :           5881 :     UnlockReleaseBuffer(buf);
                               8437                 :                : 
                               8438                 :                :     /*
                               8439                 :                :      * Shrink deltids array to exclude non-deletable entries at the end.  This
                               8440                 :                :      * is not just a minor optimization.  Final deltids array size might be
                               8441                 :                :      * zero for a bottom-up caller.  Index AM is explicitly allowed to rely on
                               8442                 :                :      * ndeltids being zero in all cases with zero total deletable entries.
                               8443                 :                :      */
                               8444   [ +  +  -  + ]:           5881 :     Assert(finalndeltids > 0 || delstate->bottomup);
                               8445                 :           5881 :     delstate->ndeltids = finalndeltids;
                               8446                 :                : 
 1126                          8447                 :           5881 :     return snapshotConflictHorizon;
                               8448                 :                : }
                               8449                 :                : 
                               8450                 :                : /*
                               8451                 :                :  * Specialized inlineable comparison function for index_delete_sort()
                               8452                 :                :  */
                               8453                 :                : static inline int
 1799                          8454                 :       12893858 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
                               8455                 :                : {
                               8456                 :       12893858 :     ItemPointer tid1 = &deltid1->tid;
                               8457                 :       12893858 :     ItemPointer tid2 = &deltid2->tid;
                               8458                 :                : 
                               8459                 :                :     {
                               8460                 :       12893858 :         BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
                               8461                 :       12893858 :         BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
                               8462                 :                : 
                               8463         [ +  + ]:       12893858 :         if (blk1 != blk2)
                               8464         [ +  + ]:        5249917 :             return (blk1 < blk2) ? -1 : 1;
                               8465                 :                :     }
                               8466                 :                :     {
                               8467                 :        7643941 :         OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
                               8468                 :        7643941 :         OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
                               8469                 :                : 
                               8470         [ +  - ]:        7643941 :         if (pos1 != pos2)
                               8471         [ +  + ]:        7643941 :             return (pos1 < pos2) ? -1 : 1;
                               8472                 :                :     }
                               8473                 :                : 
 1510 pg@bowt.ie               8474                 :UBC           0 :     Assert(false);
                               8475                 :                : 
                               8476                 :                :     return 0;
                               8477                 :                : }
                               8478                 :                : 
                               8479                 :                : /*
                               8480                 :                :  * Sort deltids array from delstate by TID.  This prepares it for further
                               8481                 :                :  * processing by heap_index_delete_tuples().
                               8482                 :                :  *
                               8483                 :                :  * This operation becomes a noticeable consumer of CPU cycles with some
                               8484                 :                :  * workloads, so we go to the trouble of specialization/micro optimization.
                               8485                 :                :  * We use shellsort for this because it's easy to specialize, compiles to
                               8486                 :                :  * relatively few instructions, and is adaptive to presorted inputs/subsets
                               8487                 :                :  * (which are typical here).
                               8488                 :                :  */
                               8489                 :                : static void
 1799 pg@bowt.ie               8490                 :CBC        5881 : index_delete_sort(TM_IndexDeleteOp *delstate)
                               8491                 :                : {
                               8492                 :           5881 :     TM_IndexDelete *deltids = delstate->deltids;
                               8493                 :           5881 :     int         ndeltids = delstate->ndeltids;
                               8494                 :                : 
                               8495                 :                :     /*
                               8496                 :                :      * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
                               8497                 :                :      *
                               8498                 :                :      * This implementation is fast with array sizes up to ~4500.  This covers
                               8499                 :                :      * all supported BLCKSZ values.
                               8500                 :                :      */
                               8501                 :           5881 :     const int   gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
                               8502                 :                : 
                               8503                 :                :     /* Think carefully before changing anything here -- keep swaps cheap */
                               8504                 :                :     StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
                               8505                 :                :                      "element size exceeds 8 bytes");
                               8506                 :                : 
                               8507         [ +  + ]:          58810 :     for (int g = 0; g < lengthof(gaps); g++)
                               8508                 :                :     {
  406 dgustafsson@postgres     8509         [ +  + ]:        7685016 :         for (int hi = gaps[g], i = hi; i < ndeltids; i++)
                               8510                 :                :         {
 1799 pg@bowt.ie               8511                 :        7632087 :             TM_IndexDelete d = deltids[i];
                               8512                 :        7632087 :             int         j = i;
                               8513                 :                : 
                               8514   [ +  +  +  + ]:       13267658 :             while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
                               8515                 :                :             {
                               8516                 :        5635571 :                 deltids[j] = deltids[j - hi];
                               8517                 :        5635571 :                 j -= hi;
                               8518                 :                :             }
                               8519                 :        7632087 :             deltids[j] = d;
                               8520                 :                :         }
                               8521                 :                :     }
                               8522                 :           5881 : }
                               8523                 :                : 
                               8524                 :                : /*
                               8525                 :                :  * Returns how many blocks should be considered favorable/contiguous for a
                               8526                 :                :  * bottom-up index deletion pass.  This is a number of heap blocks that starts
                               8527                 :                :  * from and includes the first block in line.
                               8528                 :                :  *
                               8529                 :                :  * There is always at least one favorable block during bottom-up index
                               8530                 :                :  * deletion.  In the worst case (i.e. with totally random heap blocks) the
                               8531                 :                :  * first block in line (the only favorable block) can be thought of as a
                               8532                 :                :  * degenerate array of contiguous blocks that consists of a single block.
                               8533                 :                :  * heap_index_delete_tuples() will expect this.
                               8534                 :                :  *
                               8535                 :                :  * Caller passes blockgroups, a description of the final order that deltids
                               8536                 :                :  * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
                               8537                 :                :  * processing.  Note that deltids need not actually be sorted just yet (caller
                               8538                 :                :  * only passes deltids to us so that we can interpret blockgroups).
                               8539                 :                :  *
                               8540                 :                :  * You might guess that the existence of contiguous blocks cannot matter much,
                               8541                 :                :  * since in general the main factor that determines which blocks we visit is
                               8542                 :                :  * the number of promising TIDs, which is a fixed hint from the index AM.
                               8543                 :                :  * We're not really targeting the general case, though -- the actual goal is
                               8544                 :                :  * to adapt our behavior to a wide variety of naturally occurring conditions.
                               8545                 :                :  * The effects of most of the heuristics we apply are only noticeable in the
                               8546                 :                :  * aggregate, over time and across many _related_ bottom-up index deletion
                               8547                 :                :  * passes.
                               8548                 :                :  *
                               8549                 :                :  * Deeming certain blocks favorable allows heapam to recognize and adapt to
                               8550                 :                :  * workloads where heap blocks visited during bottom-up index deletion can be
                               8551                 :                :  * accessed contiguously, in the sense that each newly visited block is the
                               8552                 :                :  * neighbor of the block that bottom-up deletion just finished processing (or
                               8553                 :                :  * close enough to it).  It will likely be cheaper to access more favorable
                               8554                 :                :  * blocks sooner rather than later (e.g. in this pass, not across a series of
                               8555                 :                :  * related bottom-up passes).  Either way it is probably only a matter of time
                               8556                 :                :  * (or a matter of further correlated version churn) before all blocks that
                               8557                 :                :  * appear together as a single large batch of favorable blocks get accessed by
                               8558                 :                :  * _some_ bottom-up pass.  Large batches of favorable blocks tend to either
                               8559                 :                :  * appear almost constantly or not even once (it all depends on per-index
                               8560                 :                :  * workload characteristics).
                               8561                 :                :  *
                               8562                 :                :  * Note that the blockgroups sort order applies a power-of-two bucketing
                               8563                 :                :  * scheme that creates opportunities for contiguous groups of blocks to get
                               8564                 :                :  * batched together, at least with workloads that are naturally amenable to
                               8565                 :                :  * being driven by heap block locality.  This doesn't just enhance the spatial
                               8566                 :                :  * locality of bottom-up heap block processing in the obvious way.  It also
                               8567                 :                :  * enables temporal locality of access, since sorting by heap block number
                               8568                 :                :  * naturally tends to make the bottom-up processing order deterministic.
                               8569                 :                :  *
                               8570                 :                :  * Consider the following example to get a sense of how temporal locality
                               8571                 :                :  * might matter: There is a heap relation with several indexes, each of which
                               8572                 :                :  * is low to medium cardinality.  It is subject to constant non-HOT updates.
                               8573                 :                :  * The updates are skewed (in one part of the primary key, perhaps).  None of
                               8574                 :                :  * the indexes are logically modified by the UPDATE statements (if they were
                               8575                 :                :  * then bottom-up index deletion would not be triggered in the first place).
                               8576                 :                :  * Naturally, each new round of index tuples (for each heap tuple that gets a
                               8577                 :                :  * heap_update() call) will have the same heap TID in each and every index.
                               8578                 :                :  * Since these indexes are low cardinality and never get logically modified,
                               8579                 :                :  * heapam processing during bottom-up deletion passes will access heap blocks
                               8580                 :                :  * in approximately sequential order.  Temporal locality of access occurs due
                               8581                 :                :  * to bottom-up deletion passes behaving very similarly across each of the
                               8582                 :                :  * indexes at any given moment.  This keeps the number of buffer misses needed
                               8583                 :                :  * to visit heap blocks to a minimum.
                               8584                 :                :  */
                               8585                 :                : static int
                               8586                 :           1981 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
                               8587                 :                :                           TM_IndexDelete *deltids)
                               8588                 :                : {
                               8589                 :           1981 :     int64       lastblock = -1;
                               8590                 :           1981 :     int         nblocksfavorable = 0;
                               8591                 :                : 
                               8592         [ -  + ]:           1981 :     Assert(nblockgroups >= 1);
                               8593         [ -  + ]:           1981 :     Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
                               8594                 :                : 
                               8595                 :                :     /*
                               8596                 :                :      * We tolerate heap blocks that will be accessed only slightly out of
                               8597                 :                :      * physical order.  Small blips occur when a pair of almost-contiguous
                               8598                 :                :      * blocks happen to fall into different buckets (perhaps due only to a
                               8599                 :                :      * small difference in npromisingtids that the bucketing scheme didn't
                               8600                 :                :      * quite manage to ignore).  We effectively ignore these blips by applying
                               8601                 :                :      * a small tolerance.  The precise tolerance we use is a little arbitrary,
                               8602                 :                :      * but it works well enough in practice.
                               8603                 :                :      */
                               8604         [ +  + ]:           6410 :     for (int b = 0; b < nblockgroups; b++)
                               8605                 :                :     {
                               8606                 :           6128 :         IndexDeleteCounts *group = blockgroups + b;
                               8607                 :           6128 :         TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
                               8608                 :           6128 :         BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
                               8609                 :                : 
                               8610         [ +  + ]:           6128 :         if (lastblock != -1 &&
                               8611         [ +  + ]:           4147 :             ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
                               8612         [ +  + ]:           3591 :              (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
                               8613                 :                :             break;
                               8614                 :                : 
                               8615                 :           4429 :         nblocksfavorable++;
                               8616                 :           4429 :         lastblock = block;
                               8617                 :                :     }
                               8618                 :                : 
                               8619                 :                :     /* Always indicate that there is at least 1 favorable block */
                               8620         [ -  + ]:           1981 :     Assert(nblocksfavorable >= 1);
                               8621                 :                : 
                               8622                 :           1981 :     return nblocksfavorable;
                               8623                 :                : }
                               8624                 :                : 
                               8625                 :                : /*
                               8626                 :                :  * qsort comparison function for bottomup_sort_and_shrink()
                               8627                 :                :  */
                               8628                 :                : static int
                               8629                 :         201804 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
                               8630                 :                : {
                               8631                 :         201804 :     const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
                               8632                 :         201804 :     const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
                               8633                 :                : 
                               8634                 :                :     /*
                               8635                 :                :      * Most significant field is npromisingtids (which we invert the order of
                               8636                 :                :      * so as to sort in desc order).
                               8637                 :                :      *
                               8638                 :                :      * Caller should have already normalized npromisingtids fields into
                               8639                 :                :      * power-of-two values (buckets).
                               8640                 :                :      */
                               8641         [ +  + ]:         201804 :     if (group1->npromisingtids > group2->npromisingtids)
                               8642                 :           8847 :         return -1;
                               8643         [ +  + ]:         192957 :     if (group1->npromisingtids < group2->npromisingtids)
                               8644                 :          10921 :         return 1;
                               8645                 :                : 
                               8646                 :                :     /*
                               8647                 :                :      * Tiebreak: desc ntids sort order.
                               8648                 :                :      *
                               8649                 :                :      * We cannot expect power-of-two values for ntids fields.  We should
                               8650                 :                :      * behave as if they were already rounded up for us instead.
                               8651                 :                :      */
                               8652         [ +  + ]:         182036 :     if (group1->ntids != group2->ntids)
                               8653                 :                :     {
                               8654                 :         127414 :         uint32      ntids1 = pg_nextpower2_32((uint32) group1->ntids);
                               8655                 :         127414 :         uint32      ntids2 = pg_nextpower2_32((uint32) group2->ntids);
                               8656                 :                : 
                               8657         [ +  + ]:         127414 :         if (ntids1 > ntids2)
                               8658                 :          20882 :             return -1;
                               8659         [ +  + ]:         106532 :         if (ntids1 < ntids2)
                               8660                 :          24843 :             return 1;
                               8661                 :                :     }
                               8662                 :                : 
                               8663                 :                :     /*
                               8664                 :                :      * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
                               8665                 :                :      * block in deltids array) order.
                               8666                 :                :      *
                               8667                 :                :      * This is equivalent to sorting in ascending heap block number order
                               8668                 :                :      * (among otherwise equal subsets of the array).  This approach allows us
                               8669                 :                :      * to avoid accessing the out-of-line TID.  (We rely on the assumption
                               8670                 :                :      * that the deltids array was sorted in ascending heap TID order when
                               8671                 :                :      * these offsets to the first TID from each heap block group were formed.)
                               8672                 :                :      */
                               8673         [ +  + ]:         136311 :     if (group1->ifirsttid > group2->ifirsttid)
                               8674                 :          67261 :         return 1;
                               8675         [ +  - ]:          69050 :     if (group1->ifirsttid < group2->ifirsttid)
                               8676                 :          69050 :         return -1;
                               8677                 :                : 
 1799 pg@bowt.ie               8678                 :UBC           0 :     pg_unreachable();
                               8679                 :                : 
                               8680                 :                :     return 0;
                               8681                 :                : }
                               8682                 :                : 
                               8683                 :                : /*
                               8684                 :                :  * heap_index_delete_tuples() helper function for bottom-up deletion callers.
                               8685                 :                :  *
                               8686                 :                :  * Sorts deltids array in the order needed for useful processing by bottom-up
                               8687                 :                :  * deletion.  The array should already be sorted in TID order when we're
                               8688                 :                :  * called.  The sort process groups heap TIDs from deltids into heap block
                               8689                 :                :  * groupings.  Earlier/more-promising groups/blocks are usually those that are
                               8690                 :                :  * known to have the most "promising" TIDs.
                               8691                 :                :  *
                               8692                 :                :  * Sets new size of deltids array (ndeltids) in state.  deltids will only have
                               8693                 :                :  * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
                               8694                 :                :  * return.  This often means that deltids will be shrunk to a small fraction
                               8695                 :                :  * of its original size (we eliminate many heap blocks from consideration for
                               8696                 :                :  * caller up front).
                               8697                 :                :  *
                               8698                 :                :  * Returns the number of "favorable" blocks.  See bottomup_nblocksfavorable()
                               8699                 :                :  * for a definition and full details.
                               8700                 :                :  */
                               8701                 :                : static int
 1799 pg@bowt.ie               8702                 :CBC        1981 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
                               8703                 :                : {
                               8704                 :                :     IndexDeleteCounts *blockgroups;
                               8705                 :                :     TM_IndexDelete *reordereddeltids;
                               8706                 :           1981 :     BlockNumber curblock = InvalidBlockNumber;
                               8707                 :           1981 :     int         nblockgroups = 0;
                               8708                 :           1981 :     int         ncopied = 0;
                               8709                 :           1981 :     int         nblocksfavorable = 0;
                               8710                 :                : 
                               8711         [ -  + ]:           1981 :     Assert(delstate->bottomup);
                               8712         [ -  + ]:           1981 :     Assert(delstate->ndeltids > 0);
                               8713                 :                : 
                               8714                 :                :     /* Calculate per-heap-block count of TIDs */
    7 michael@paquier.xyz      8715                 :GNC        1981 :     blockgroups = palloc_array(IndexDeleteCounts, delstate->ndeltids);
 1799 pg@bowt.ie               8716         [ +  + ]:CBC      947172 :     for (int i = 0; i < delstate->ndeltids; i++)
                               8717                 :                :     {
                               8718                 :         945191 :         TM_IndexDelete *ideltid = &delstate->deltids[i];
                               8719                 :         945191 :         TM_IndexStatus *istatus = delstate->status + ideltid->id;
                               8720                 :         945191 :         ItemPointer htid = &ideltid->tid;
                               8721                 :         945191 :         bool        promising = istatus->promising;
                               8722                 :                : 
                               8723         [ +  + ]:         945191 :         if (curblock != ItemPointerGetBlockNumber(htid))
                               8724                 :                :         {
                               8725                 :                :             /* New block group */
                               8726                 :          39287 :             nblockgroups++;
                               8727                 :                : 
                               8728   [ +  +  -  + ]:          39287 :             Assert(curblock < ItemPointerGetBlockNumber(htid) ||
                               8729                 :                :                    !BlockNumberIsValid(curblock));
                               8730                 :                : 
                               8731                 :          39287 :             curblock = ItemPointerGetBlockNumber(htid);
                               8732                 :          39287 :             blockgroups[nblockgroups - 1].ifirsttid = i;
                               8733                 :          39287 :             blockgroups[nblockgroups - 1].ntids = 1;
                               8734                 :          39287 :             blockgroups[nblockgroups - 1].npromisingtids = 0;
                               8735                 :                :         }
                               8736                 :                :         else
                               8737                 :                :         {
                               8738                 :         905904 :             blockgroups[nblockgroups - 1].ntids++;
                               8739                 :                :         }
                               8740                 :                : 
                               8741         [ +  + ]:         945191 :         if (promising)
                               8742                 :         122049 :             blockgroups[nblockgroups - 1].npromisingtids++;
                               8743                 :                :     }
                               8744                 :                : 
                               8745                 :                :     /*
                               8746                 :                :      * We're about ready to sort block groups to determine the optimal order
                               8747                 :                :      * for visiting heap blocks.  But before we do, round the number of
                               8748                 :                :      * promising tuples for each block group up to the next power-of-two,
                               8749                 :                :      * unless it is very low (less than 4), in which case we round up to 4.
                               8750                 :                :      * npromisingtids is far too noisy to trust when choosing between a pair
                               8751                 :                :      * of block groups that both have very low values.
                               8752                 :                :      *
                               8753                 :                :      * This scheme divides heap blocks/block groups into buckets.  Each bucket
                               8754                 :                :      * contains blocks that have _approximately_ the same number of promising
                               8755                 :                :      * TIDs as each other.  The goal is to ignore relatively small differences
                               8756                 :                :      * in the total number of promising entries, so that the whole process can
                               8757                 :                :      * give a little weight to heapam factors (like heap block locality)
                               8758                 :                :      * instead.  This isn't a trade-off, really -- we have nothing to lose. It
                               8759                 :                :      * would be foolish to interpret small differences in npromisingtids
                               8760                 :                :      * values as anything more than noise.
                               8761                 :                :      *
                               8762                 :                :      * We tiebreak on nhtids when sorting block group subsets that have the
                               8763                 :                :      * same npromisingtids, but this has the same issues as npromisingtids,
                               8764                 :                :      * and so nhtids is subject to the same power-of-two bucketing scheme. The
                               8765                 :                :      * only reason that we don't fix nhtids in the same way here too is that
                               8766                 :                :      * we'll need accurate nhtids values after the sort.  We handle nhtids
                               8767                 :                :      * bucketization dynamically instead (in the sort comparator).
                               8768                 :                :      *
                               8769                 :                :      * See bottomup_nblocksfavorable() for a full explanation of when and how
                               8770                 :                :      * heap locality/favorable blocks can significantly influence when and how
                               8771                 :                :      * heap blocks are accessed.
                               8772                 :                :      */
                               8773         [ +  + ]:          41268 :     for (int b = 0; b < nblockgroups; b++)
                               8774                 :                :     {
                               8775                 :          39287 :         IndexDeleteCounts *group = blockgroups + b;
                               8776                 :                : 
                               8777                 :                :         /* Better off falling back on nhtids with low npromisingtids */
                               8778         [ +  + ]:          39287 :         if (group->npromisingtids <= 4)
                               8779                 :          33801 :             group->npromisingtids = 4;
                               8780                 :                :         else
                               8781                 :           5486 :             group->npromisingtids =
                               8782                 :           5486 :                 pg_nextpower2_32((uint32) group->npromisingtids);
                               8783                 :                :     }
                               8784                 :                : 
                               8785                 :                :     /* Sort groups and rearrange caller's deltids array */
                               8786                 :           1981 :     qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
                               8787                 :                :           bottomup_sort_and_shrink_cmp);
                               8788                 :           1981 :     reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
                               8789                 :                : 
                               8790                 :           1981 :     nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
                               8791                 :                :     /* Determine number of favorable blocks at the start of final deltids */
                               8792                 :           1981 :     nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
                               8793                 :                :                                                  delstate->deltids);
                               8794                 :                : 
                               8795         [ +  + ]:          13257 :     for (int b = 0; b < nblockgroups; b++)
                               8796                 :                :     {
                               8797                 :          11276 :         IndexDeleteCounts *group = blockgroups + b;
                               8798                 :          11276 :         TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
                               8799                 :                : 
                               8800                 :          11276 :         memcpy(reordereddeltids + ncopied, firstdtid,
                               8801                 :          11276 :                sizeof(TM_IndexDelete) * group->ntids);
                               8802                 :          11276 :         ncopied += group->ntids;
                               8803                 :                :     }
                               8804                 :                : 
                               8805                 :                :     /* Copy final grouped and sorted TIDs back into start of caller's array */
                               8806                 :           1981 :     memcpy(delstate->deltids, reordereddeltids,
                               8807                 :                :            sizeof(TM_IndexDelete) * ncopied);
                               8808                 :           1981 :     delstate->ndeltids = ncopied;
                               8809                 :                : 
                               8810                 :           1981 :     pfree(reordereddeltids);
                               8811                 :           1981 :     pfree(blockgroups);
                               8812                 :                : 
                               8813                 :           1981 :     return nblocksfavorable;
                               8814                 :                : }
                               8815                 :                : 
                               8816                 :                : /*
                               8817                 :                :  * Perform XLogInsert for a heap-visible operation.  'block' is the block
                               8818                 :                :  * being marked all-visible, and vm_buffer is the buffer containing the
                               8819                 :                :  * corresponding visibility map block.  Both should have already been modified
                               8820                 :                :  * and dirtied.
                               8821                 :                :  *
                               8822                 :                :  * snapshotConflictHorizon comes from the largest xmin on the page being
                               8823                 :                :  * marked all-visible.  REDO routine uses it to generate recovery conflicts.
                               8824                 :                :  *
                               8825                 :                :  * If checksums or wal_log_hints are enabled, we may also generate a full-page
                               8826                 :                :  * image of heap_buffer. Otherwise, we optimize away the FPI (by specifying
                               8827                 :                :  * REGBUF_NO_IMAGE for the heap buffer), in which case the caller should *not*
                               8828                 :                :  * update the heap page's LSN.
                               8829                 :                :  */
                               8830                 :                : XLogRecPtr
  991 andres@anarazel.de       8831                 :          36990 : log_heap_visible(Relation rel, Buffer heap_buffer, Buffer vm_buffer,
                               8832                 :                :                  TransactionId snapshotConflictHorizon, uint8 vmflags)
                               8833                 :                : {
                               8834                 :                :     xl_heap_visible xlrec;
                               8835                 :                :     XLogRecPtr  recptr;
                               8836                 :                :     uint8       flags;
                               8837                 :                : 
 4653 simon@2ndQuadrant.co     8838         [ -  + ]:          36990 :     Assert(BufferIsValid(heap_buffer));
                               8839         [ -  + ]:          36990 :     Assert(BufferIsValid(vm_buffer));
                               8840                 :                : 
 1126 pg@bowt.ie               8841                 :          36990 :     xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
 3578 rhaas@postgresql.org     8842                 :          36990 :     xlrec.flags = vmflags;
  990 andres@anarazel.de       8843   [ +  +  +  -  :          36990 :     if (RelationIsAccessibleInLogicalDecoding(rel))
                                     -  +  -  -  -  
                                     -  +  +  -  +  
                                     -  -  -  -  -  
                                                 - ]
                               8844                 :             49 :         xlrec.flags |= VISIBILITYMAP_XLOG_CATALOG_REL;
 4045 heikki.linnakangas@i     8845                 :          36990 :     XLogBeginInsert();
  309 peter@eisentraut.org     8846                 :          36990 :     XLogRegisterData(&xlrec, SizeOfHeapVisible);
                               8847                 :                : 
 4045 heikki.linnakangas@i     8848                 :          36990 :     XLogRegisterBuffer(0, vm_buffer, 0);
                               8849                 :                : 
                               8850                 :          36990 :     flags = REGBUF_STANDARD;
                               8851   [ +  +  +  - ]:          36990 :     if (!XLogHintBitIsNeeded())
                               8852                 :           3138 :         flags |= REGBUF_NO_IMAGE;
                               8853                 :          36990 :     XLogRegisterBuffer(1, heap_buffer, flags);
                               8854                 :                : 
                               8855                 :          36990 :     recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);
                               8856                 :                : 
 5293 rhaas@postgresql.org     8857                 :          36990 :     return recptr;
                               8858                 :                : }
                               8859                 :                : 
                               8860                 :                : /*
                               8861                 :                :  * Perform XLogInsert for a heap-update operation.  Caller must already
                               8862                 :                :  * have modified the buffer(s) and marked them dirty.
                               8863                 :                :  */
                               8864                 :                : static XLogRecPtr
 4711 alvherre@alvh.no-ip.     8865                 :         300589 : log_heap_update(Relation reln, Buffer oldbuf,
                               8866                 :                :                 Buffer newbuf, HeapTuple oldtup, HeapTuple newtup,
                               8867                 :                :                 HeapTuple old_key_tuple,
                               8868                 :                :                 bool all_visible_cleared, bool new_all_visible_cleared)
                               8869                 :                : {
                               8870                 :                :     xl_heap_update xlrec;
                               8871                 :                :     xl_heap_header xlhdr;
                               8872                 :                :     xl_heap_header xlhdr_idx;
                               8873                 :                :     uint8       info;
                               8874                 :                :     uint16      prefix_suffix[2];
 4298 heikki.linnakangas@i     8875                 :         300589 :     uint16      prefixlen = 0,
                               8876                 :         300589 :                 suffixlen = 0;
                               8877                 :                :     XLogRecPtr  recptr;
 3528 kgrittn@postgresql.o     8878                 :         300589 :     Page        page = BufferGetPage(newbuf);
 4390 rhaas@postgresql.org     8879   [ +  +  +  -  :         300589 :     bool        need_tuple_data = RelationIsLogicallyLogged(reln);
                                     -  +  -  -  -  
                                        -  +  -  +  
                                                 + ]
                               8880                 :                :     bool        init;
                               8881                 :                :     int         bufflags;
                               8882                 :                : 
                               8883                 :                :     /* Caller should not call me on a non-WAL-logged relation */
 5483                          8884   [ +  -  +  +  :         300589 :     Assert(RelationNeedsWAL(reln));
                                        +  -  -  + ]
                               8885                 :                : 
 4045 heikki.linnakangas@i     8886                 :         300589 :     XLogBeginInsert();
                               8887                 :                : 
 5791 tgl@sss.pgh.pa.us        8888         [ +  + ]:         300589 :     if (HeapTupleIsHeapOnly(newtup))
 6663                          8889                 :         146950 :         info = XLOG_HEAP_HOT_UPDATE;
                               8890                 :                :     else
                               8891                 :         153639 :         info = XLOG_HEAP_UPDATE;
                               8892                 :                : 
                               8893                 :                :     /*
                               8894                 :                :      * If the old and new tuple are on the same page, we only need to log the
                               8895                 :                :      * parts of the new tuple that were changed.  That saves on the amount of
                               8896                 :                :      * WAL we need to write.  Currently, we just count any unchanged bytes in
                               8897                 :                :      * the beginning and end of the tuple.  That's quick to check, and
                               8898                 :                :      * perfectly covers the common case that only one field is updated.
                               8899                 :                :      *
                               8900                 :                :      * We could do this even if the old and new tuple are on different pages,
                               8901                 :                :      * but only if we don't make a full-page image of the old page, which is
                               8902                 :                :      * difficult to know in advance.  Also, if the old tuple is corrupt for
                               8903                 :                :      * some reason, it would allow the corruption to propagate the new page,
                               8904                 :                :      * so it seems best to avoid.  Under the general assumption that most
                               8905                 :                :      * updates tend to create the new tuple version on the same page, there
                               8906                 :                :      * isn't much to be gained by doing this across pages anyway.
                               8907                 :                :      *
                               8908                 :                :      * Skip this if we're taking a full-page image of the new page, as we
                               8909                 :                :      * don't include the new tuple in the WAL record in that case.  Also
                               8910                 :                :      * disable if wal_level='logical', as logical decoding needs to be able to
                               8911                 :                :      * read the new tuple in whole from the WAL record alone.
                               8912                 :                :      */
 4298 heikki.linnakangas@i     8913   [ +  +  +  + ]:         300589 :     if (oldbuf == newbuf && !need_tuple_data &&
                               8914         [ +  + ]:         147192 :         !XLogCheckBufferNeedsBackup(newbuf))
                               8915                 :                :     {
                               8916                 :         146565 :         char       *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
                               8917                 :         146565 :         char       *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
                               8918                 :         146565 :         int         oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
                               8919                 :         146565 :         int         newlen = newtup->t_len - newtup->t_data->t_hoff;
                               8920                 :                : 
                               8921                 :                :         /* Check for common prefix between old and new tuple */
                               8922         [ +  + ]:       12348803 :         for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
                               8923                 :                :         {
                               8924         [ +  + ]:       12322646 :             if (newp[prefixlen] != oldp[prefixlen])
                               8925                 :         120408 :                 break;
                               8926                 :                :         }
                               8927                 :                : 
                               8928                 :                :         /*
                               8929                 :                :          * Storing the length of the prefix takes 2 bytes, so we need to save
                               8930                 :                :          * at least 3 bytes or there's no point.
                               8931                 :                :          */
                               8932         [ +  + ]:         146565 :         if (prefixlen < 3)
                               8933                 :          22100 :             prefixlen = 0;
                               8934                 :                : 
                               8935                 :                :         /* Same for suffix */
                               8936         [ +  + ]:        4771251 :         for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
                               8937                 :                :         {
                               8938         [ +  + ]:        4744838 :             if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
                               8939                 :         120152 :                 break;
                               8940                 :                :         }
                               8941         [ +  + ]:         146565 :         if (suffixlen < 3)
                               8942                 :          36927 :             suffixlen = 0;
                               8943                 :                :     }
                               8944                 :                : 
                               8945                 :                :     /* Prepare main WAL data chain */
 4390 rhaas@postgresql.org     8946                 :         300589 :     xlrec.flags = 0;
                               8947         [ +  + ]:         300589 :     if (all_visible_cleared)
 3876 andres@anarazel.de       8948                 :           1634 :         xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
 4390 rhaas@postgresql.org     8949         [ +  + ]:         300589 :     if (new_all_visible_cleared)
 3876 andres@anarazel.de       8950                 :           1016 :         xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
 4298 heikki.linnakangas@i     8951         [ +  + ]:         300589 :     if (prefixlen > 0)
 3876 andres@anarazel.de       8952                 :         124465 :         xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
 4298 heikki.linnakangas@i     8953         [ +  + ]:         300589 :     if (suffixlen > 0)
 3876 andres@anarazel.de       8954                 :         109638 :         xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
 4045 heikki.linnakangas@i     8955         [ +  + ]:         300589 :     if (need_tuple_data)
                               8956                 :                :     {
 3876 andres@anarazel.de       8957                 :          47015 :         xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
 4045 heikki.linnakangas@i     8958         [ +  + ]:          47015 :         if (old_key_tuple)
                               8959                 :                :         {
                               8960         [ +  + ]:            145 :             if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
 3876 andres@anarazel.de       8961                 :             64 :                 xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
                               8962                 :                :             else
                               8963                 :             81 :                 xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
                               8964                 :                :         }
                               8965                 :                :     }
                               8966                 :                : 
                               8967                 :                :     /* If new tuple is the single and first tuple on page... */
 4298 heikki.linnakangas@i     8968   [ +  +  +  + ]:         304117 :     if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
                               8969                 :           3528 :         PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
                               8970                 :                :     {
                               8971                 :           3233 :         info |= XLOG_HEAP_INIT_PAGE;
 4045                          8972                 :           3233 :         init = true;
                               8973                 :                :     }
                               8974                 :                :     else
                               8975                 :         297356 :         init = false;
                               8976                 :                : 
                               8977                 :                :     /* Prepare WAL data for the old page */
                               8978                 :         300589 :     xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
                               8979                 :         300589 :     xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
                               8980                 :         601178 :     xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
                               8981                 :         300589 :                                               oldtup->t_data->t_infomask2);
                               8982                 :                : 
                               8983                 :                :     /* Prepare WAL data for the new page */
                               8984                 :         300589 :     xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
                               8985                 :         300589 :     xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
                               8986                 :                : 
                               8987                 :         300589 :     bufflags = REGBUF_STANDARD;
                               8988         [ +  + ]:         300589 :     if (init)
                               8989                 :           3233 :         bufflags |= REGBUF_WILL_INIT;
                               8990         [ +  + ]:         300589 :     if (need_tuple_data)
                               8991                 :          47015 :         bufflags |= REGBUF_KEEP_DATA;
                               8992                 :                : 
                               8993                 :         300589 :     XLogRegisterBuffer(0, newbuf, bufflags);
                               8994         [ +  + ]:         300589 :     if (oldbuf != newbuf)
                               8995                 :         141462 :         XLogRegisterBuffer(1, oldbuf, REGBUF_STANDARD);
                               8996                 :                : 
  309 peter@eisentraut.org     8997                 :         300589 :     XLogRegisterData(&xlrec, SizeOfHeapUpdate);
                               8998                 :                : 
                               8999                 :                :     /*
                               9000                 :                :      * Prepare WAL data for the new tuple.
                               9001                 :                :      */
 4298 heikki.linnakangas@i     9002   [ +  +  +  + ]:         300589 :     if (prefixlen > 0 || suffixlen > 0)
                               9003                 :                :     {
                               9004   [ +  +  +  + ]:         146104 :         if (prefixlen > 0 && suffixlen > 0)
                               9005                 :                :         {
                               9006                 :          87999 :             prefix_suffix[0] = prefixlen;
                               9007                 :          87999 :             prefix_suffix[1] = suffixlen;
  309 peter@eisentraut.org     9008                 :          87999 :             XLogRegisterBufData(0, &prefix_suffix, sizeof(uint16) * 2);
                               9009                 :                :         }
 4298 heikki.linnakangas@i     9010         [ +  + ]:          58105 :         else if (prefixlen > 0)
                               9011                 :                :         {
  309 peter@eisentraut.org     9012                 :          36466 :             XLogRegisterBufData(0, &prefixlen, sizeof(uint16));
                               9013                 :                :         }
                               9014                 :                :         else
                               9015                 :                :         {
                               9016                 :          21639 :             XLogRegisterBufData(0, &suffixlen, sizeof(uint16));
                               9017                 :                :         }
                               9018                 :                :     }
                               9019                 :                : 
 4045 heikki.linnakangas@i     9020                 :         300589 :     xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
                               9021                 :         300589 :     xlhdr.t_infomask = newtup->t_data->t_infomask;
                               9022                 :         300589 :     xlhdr.t_hoff = newtup->t_data->t_hoff;
 3952 tgl@sss.pgh.pa.us        9023         [ -  + ]:         300589 :     Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
                               9024                 :                : 
                               9025                 :                :     /*
                               9026                 :                :      * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
                               9027                 :                :      *
                               9028                 :                :      * The 'data' doesn't include the common prefix or suffix.
                               9029                 :                :      */
  309 peter@eisentraut.org     9030                 :         300589 :     XLogRegisterBufData(0, &xlhdr, SizeOfHeapHeader);
 4298 heikki.linnakangas@i     9031         [ +  + ]:         300589 :     if (prefixlen == 0)
                               9032                 :                :     {
 4045                          9033                 :         176124 :         XLogRegisterBufData(0,
  309 peter@eisentraut.org     9034                 :         176124 :                             (char *) newtup->t_data + SizeofHeapTupleHeader,
 3101 tgl@sss.pgh.pa.us        9035                 :         176124 :                             newtup->t_len - SizeofHeapTupleHeader - suffixlen);
                               9036                 :                :     }
                               9037                 :                :     else
                               9038                 :                :     {
                               9039                 :                :         /*
                               9040                 :                :          * Have to write the null bitmap and data after the common prefix as
                               9041                 :                :          * two separate rdata entries.
                               9042                 :                :          */
                               9043                 :                :         /* bitmap [+ padding] [+ oid] */
 3952                          9044         [ +  - ]:         124465 :         if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
                               9045                 :                :         {
 4045 heikki.linnakangas@i     9046                 :         124465 :             XLogRegisterBufData(0,
  309 peter@eisentraut.org     9047                 :         124465 :                                 (char *) newtup->t_data + SizeofHeapTupleHeader,
 3101 tgl@sss.pgh.pa.us        9048                 :         124465 :                                 newtup->t_data->t_hoff - SizeofHeapTupleHeader);
                               9049                 :                :         }
                               9050                 :                : 
                               9051                 :                :         /* data after common prefix */
 4045 heikki.linnakangas@i     9052                 :         124465 :         XLogRegisterBufData(0,
  309 peter@eisentraut.org     9053                 :         124465 :                             (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
 3101 tgl@sss.pgh.pa.us        9054                 :         124465 :                             newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
                               9055                 :                :     }
                               9056                 :                : 
                               9057                 :                :     /* We need to log a tuple identity */
 4045 heikki.linnakangas@i     9058   [ +  +  +  + ]:         300589 :     if (need_tuple_data && old_key_tuple)
                               9059                 :                :     {
                               9060                 :                :         /* don't really need this, but its more comfy to decode */
                               9061                 :            145 :         xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
                               9062                 :            145 :         xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
                               9063                 :            145 :         xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
                               9064                 :                : 
  309 peter@eisentraut.org     9065                 :            145 :         XLogRegisterData(&xlhdr_idx, SizeOfHeapHeader);
                               9066                 :                : 
                               9067                 :                :         /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
 3952 tgl@sss.pgh.pa.us        9068                 :            145 :         XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
                               9069                 :            145 :                          old_key_tuple->t_len - SizeofHeapTupleHeader);
                               9070                 :                :     }
                               9071                 :                : 
                               9072                 :                :     /* filtering by origin on a row level is much more efficient */
 3282 andres@anarazel.de       9073                 :         300589 :     XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               9074                 :                : 
 4045 heikki.linnakangas@i     9075                 :         300589 :     recptr = XLogInsert(RM_HEAP_ID, info);
                               9076                 :                : 
 7280 neilc@samurai.com        9077                 :         300589 :     return recptr;
                               9078                 :                : }
                               9079                 :                : 
                               9080                 :                : /*
                               9081                 :                :  * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
                               9082                 :                :  *
                               9083                 :                :  * This is only used in wal_level >= WAL_LEVEL_LOGICAL, and only for catalog
                               9084                 :                :  * tuples.
                               9085                 :                :  */
                               9086                 :                : static XLogRecPtr
 4390 rhaas@postgresql.org     9087                 :          23990 : log_heap_new_cid(Relation relation, HeapTuple tup)
                               9088                 :                : {
                               9089                 :                :     xl_heap_new_cid xlrec;
                               9090                 :                : 
                               9091                 :                :     XLogRecPtr  recptr;
                               9092                 :          23990 :     HeapTupleHeader hdr = tup->t_data;
                               9093                 :                : 
                               9094         [ -  + ]:          23990 :     Assert(ItemPointerIsValid(&tup->t_self));
                               9095         [ -  + ]:          23990 :     Assert(tup->t_tableOid != InvalidOid);
                               9096                 :                : 
                               9097                 :          23990 :     xlrec.top_xid = GetTopTransactionId();
 1260                          9098                 :          23990 :     xlrec.target_locator = relation->rd_locator;
 4045 heikki.linnakangas@i     9099                 :          23990 :     xlrec.target_tid = tup->t_self;
                               9100                 :                : 
                               9101                 :                :     /*
                               9102                 :                :      * If the tuple got inserted & deleted in the same TX we definitely have a
                               9103                 :                :      * combo CID, set cmin and cmax.
                               9104                 :                :      */
 4390 rhaas@postgresql.org     9105         [ +  + ]:          23990 :     if (hdr->t_infomask & HEAP_COMBOCID)
                               9106                 :                :     {
                               9107         [ -  + ]:           1973 :         Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
 4378                          9108         [ -  + ]:           1973 :         Assert(!HeapTupleHeaderXminInvalid(hdr));
 4390                          9109                 :           1973 :         xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
                               9110                 :           1973 :         xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
                               9111                 :           1973 :         xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
                               9112                 :                :     }
                               9113                 :                :     /* No combo CID, so only cmin or cmax can be set by this TX */
                               9114                 :                :     else
                               9115                 :                :     {
                               9116                 :                :         /*
                               9117                 :                :          * Tuple inserted.
                               9118                 :                :          *
                               9119                 :                :          * We need to check for LOCK ONLY because multixacts might be
                               9120                 :                :          * transferred to the new tuple in case of FOR KEY SHARE updates in
                               9121                 :                :          * which case there will be an xmax, although the tuple just got
                               9122                 :                :          * inserted.
                               9123                 :                :          */
                               9124   [ +  +  +  + ]:          28746 :         if (hdr->t_infomask & HEAP_XMAX_INVALID ||
                               9125                 :           6729 :             HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
                               9126                 :                :         {
                               9127                 :          15289 :             xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
                               9128                 :          15289 :             xlrec.cmax = InvalidCommandId;
                               9129                 :                :         }
                               9130                 :                :         /* Tuple from a different tx updated or deleted. */
                               9131                 :                :         else
                               9132                 :                :         {
                               9133                 :           6728 :             xlrec.cmin = InvalidCommandId;
                               9134                 :           6728 :             xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
                               9135                 :                :         }
                               9136                 :          22017 :         xlrec.combocid = InvalidCommandId;
                               9137                 :                :     }
                               9138                 :                : 
                               9139                 :                :     /*
                               9140                 :                :      * Note that we don't need to register the buffer here, because this
                               9141                 :                :      * operation does not modify the page. The insert/update/delete that
                               9142                 :                :      * called us certainly did, but that's WAL-logged separately.
                               9143                 :                :      */
 4045 heikki.linnakangas@i     9144                 :          23990 :     XLogBeginInsert();
  309 peter@eisentraut.org     9145                 :          23990 :     XLogRegisterData(&xlrec, SizeOfHeapNewCid);
                               9146                 :                : 
                               9147                 :                :     /* will be looked at irrespective of origin */
                               9148                 :                : 
 4045 heikki.linnakangas@i     9149                 :          23990 :     recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
                               9150                 :                : 
 4390 rhaas@postgresql.org     9151                 :          23990 :     return recptr;
                               9152                 :                : }
                               9153                 :                : 
                               9154                 :                : /*
                               9155                 :                :  * Build a heap tuple representing the configured REPLICA IDENTITY to represent
                               9156                 :                :  * the old tuple in an UPDATE or DELETE.
                               9157                 :                :  *
                               9158                 :                :  * Returns NULL if there's no need to log an identity or if there's no suitable
                               9159                 :                :  * key defined.
                               9160                 :                :  *
                               9161                 :                :  * Pass key_required true if any replica identity columns changed value, or if
                               9162                 :                :  * any of them have any external data.  Delete must always pass true.
                               9163                 :                :  *
                               9164                 :                :  * *copy is set to true if the returned tuple is a modified copy rather than
                               9165                 :                :  * the same tuple that was passed in.
                               9166                 :                :  */
                               9167                 :                : static HeapTuple
 1402 akapila@postgresql.o     9168                 :        1766376 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
                               9169                 :                :                        bool *copy)
                               9170                 :                : {
 4390 rhaas@postgresql.org     9171                 :        1766376 :     TupleDesc   desc = RelationGetDescr(relation);
                               9172                 :        1766376 :     char        replident = relation->rd_rel->relreplident;
                               9173                 :                :     Bitmapset  *idattrs;
                               9174                 :                :     HeapTuple   key_tuple;
                               9175                 :                :     bool        nulls[MaxHeapAttributeNumber];
                               9176                 :                :     Datum       values[MaxHeapAttributeNumber];
                               9177                 :                : 
                               9178                 :        1766376 :     *copy = false;
                               9179                 :                : 
                               9180   [ +  +  +  +  :        1766376 :     if (!RelationIsLogicallyLogged(relation))
                                     -  +  -  -  -  
                                        -  +  -  +  
                                                 + ]
                               9181                 :        1666092 :         return NULL;
                               9182                 :                : 
                               9183         [ +  + ]:         100284 :     if (replident == REPLICA_IDENTITY_NOTHING)
                               9184                 :            231 :         return NULL;
                               9185                 :                : 
                               9186         [ +  + ]:         100053 :     if (replident == REPLICA_IDENTITY_FULL)
                               9187                 :                :     {
                               9188                 :                :         /*
                               9189                 :                :          * When logging the entire old tuple, it very well could contain
                               9190                 :                :          * toasted columns. If so, force them to be inlined.
                               9191                 :                :          */
                               9192         [ +  + ]:            194 :         if (HeapTupleHasExternal(tp))
                               9193                 :                :         {
                               9194                 :              4 :             *copy = true;
 2298 tgl@sss.pgh.pa.us        9195                 :              4 :             tp = toast_flatten_tuple(tp, desc);
                               9196                 :                :         }
 4390 rhaas@postgresql.org     9197                 :            194 :         return tp;
                               9198                 :                :     }
                               9199                 :                : 
                               9200                 :                :     /* if the key isn't required and we're only logging the key, we're done */
 1402 akapila@postgresql.o     9201         [ +  + ]:          99859 :     if (!key_required)
 4390 rhaas@postgresql.org     9202                 :          46870 :         return NULL;
                               9203                 :                : 
                               9204                 :                :     /* find out the replica identity columns */
 2298 tgl@sss.pgh.pa.us        9205                 :          52989 :     idattrs = RelationGetIndexAttrBitmap(relation,
                               9206                 :                :                                          INDEX_ATTR_BITMAP_IDENTITY_KEY);
                               9207                 :                : 
                               9208                 :                :     /*
                               9209                 :                :      * If there's no defined replica identity columns, treat as !key_required.
                               9210                 :                :      * (This case should not be reachable from heap_update, since that should
                               9211                 :                :      * calculate key_required accurately.  But heap_delete just passes
                               9212                 :                :      * constant true for key_required, so we can hit this case in deletes.)
                               9213                 :                :      */
                               9214         [ +  + ]:          52989 :     if (bms_is_empty(idattrs))
                               9215                 :           6021 :         return NULL;
                               9216                 :                : 
                               9217                 :                :     /*
                               9218                 :                :      * Construct a new tuple containing only the replica identity columns,
                               9219                 :                :      * with nulls elsewhere.  While we're at it, assert that the replica
                               9220                 :                :      * identity columns aren't null.
                               9221                 :                :      */
                               9222                 :          46968 :     heap_deform_tuple(tp, desc, values, nulls);
                               9223                 :                : 
                               9224         [ +  + ]:         150898 :     for (int i = 0; i < desc->natts; i++)
                               9225                 :                :     {
                               9226         [ +  + ]:         103930 :         if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
                               9227                 :                :                           idattrs))
                               9228         [ -  + ]:          46980 :             Assert(!nulls[i]);
                               9229                 :                :         else
                               9230                 :          56950 :             nulls[i] = true;
                               9231                 :                :     }
                               9232                 :                : 
 4390 rhaas@postgresql.org     9233                 :          46968 :     key_tuple = heap_form_tuple(desc, values, nulls);
                               9234                 :          46968 :     *copy = true;
                               9235                 :                : 
 2298 tgl@sss.pgh.pa.us        9236                 :          46968 :     bms_free(idattrs);
                               9237                 :                : 
                               9238                 :                :     /*
                               9239                 :                :      * If the tuple, which by here only contains indexed columns, still has
                               9240                 :                :      * toasted columns, force them to be inlined. This is somewhat unlikely
                               9241                 :                :      * since there's limits on the size of indexed columns, so we don't
                               9242                 :                :      * duplicate toast_flatten_tuple()s functionality in the above loop over
                               9243                 :                :      * the indexed columns, even if it would be more efficient.
                               9244                 :                :      */
 4390 rhaas@postgresql.org     9245         [ +  + ]:          46968 :     if (HeapTupleHasExternal(key_tuple))
                               9246                 :                :     {
 4243 bruce@momjian.us         9247                 :              4 :         HeapTuple   oldtup = key_tuple;
                               9248                 :                : 
 2298 tgl@sss.pgh.pa.us        9249                 :              4 :         key_tuple = toast_flatten_tuple(oldtup, desc);
 4390 rhaas@postgresql.org     9250                 :              4 :         heap_freetuple(oldtup);
                               9251                 :                :     }
                               9252                 :                : 
                               9253                 :          46968 :     return key_tuple;
                               9254                 :                : }
                               9255                 :                : 
                               9256                 :                : /*
                               9257                 :                :  * HeapCheckForSerializableConflictOut
                               9258                 :                :  *      We are reading a tuple.  If it's not visible, there may be a
                               9259                 :                :  *      rw-conflict out with the inserter.  Otherwise, if it is visible to us
                               9260                 :                :  *      but has been deleted, there may be a rw-conflict out with the deleter.
                               9261                 :                :  *
                               9262                 :                :  * We will determine the top level xid of the writing transaction with which
                               9263                 :                :  * we may be in conflict, and ask CheckForSerializableConflictOut() to check
                               9264                 :                :  * for overlap with our own transaction.
                               9265                 :                :  *
                               9266                 :                :  * This function should be called just about anywhere in heapam.c where a
                               9267                 :                :  * tuple has been read. The caller must hold at least a shared lock on the
                               9268                 :                :  * buffer, because this function might set hint bits on the tuple. There is
                               9269                 :                :  * currently no known reason to call this function from an index AM.
                               9270                 :                :  */
                               9271                 :                : void
 2150 tmunro@postgresql.or     9272                 :       30512187 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
                               9273                 :                :                                     HeapTuple tuple, Buffer buffer,
                               9274                 :                :                                     Snapshot snapshot)
                               9275                 :                : {
                               9276                 :                :     TransactionId xid;
                               9277                 :                :     HTSV_Result htsvResult;
                               9278                 :                : 
                               9279         [ +  + ]:       30512187 :     if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
                               9280                 :       30486813 :         return;
                               9281                 :                : 
                               9282                 :                :     /*
                               9283                 :                :      * Check to see whether the tuple has been written to by a concurrent
                               9284                 :                :      * transaction, either to create it not visible to us, or to delete it
                               9285                 :                :      * while it is visible to us.  The "visible" bool indicates whether the
                               9286                 :                :      * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
                               9287                 :                :      * is going on with it.
                               9288                 :                :      *
                               9289                 :                :      * In the event of a concurrently inserted tuple that also happens to have
                               9290                 :                :      * been concurrently updated (by a separate transaction), the xmin of the
                               9291                 :                :      * tuple will be used -- not the updater's xid.
                               9292                 :                :      */
                               9293                 :          25374 :     htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
                               9294   [ +  +  +  +  :          25374 :     switch (htsvResult)
                                                 - ]
                               9295                 :                :     {
                               9296                 :          24561 :         case HEAPTUPLE_LIVE:
                               9297         [ +  + ]:          24561 :             if (visible)
                               9298                 :          24548 :                 return;
                               9299                 :             13 :             xid = HeapTupleHeaderGetXmin(tuple->t_data);
                               9300                 :             13 :             break;
                               9301                 :            361 :         case HEAPTUPLE_RECENTLY_DEAD:
                               9302                 :                :         case HEAPTUPLE_DELETE_IN_PROGRESS:
 2015 pg@bowt.ie               9303         [ +  + ]:            361 :             if (visible)
                               9304                 :            285 :                 xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
                               9305                 :                :             else
                               9306                 :             76 :                 xid = HeapTupleHeaderGetXmin(tuple->t_data);
                               9307                 :                : 
                               9308         [ +  + ]:            361 :             if (TransactionIdPrecedes(xid, TransactionXmin))
                               9309                 :                :             {
                               9310                 :                :                 /* This is like the HEAPTUPLE_DEAD case */
                               9311         [ -  + ]:             67 :                 Assert(!visible);
                               9312                 :             67 :                 return;
                               9313                 :                :             }
 2150 tmunro@postgresql.or     9314                 :            294 :             break;
                               9315                 :            328 :         case HEAPTUPLE_INSERT_IN_PROGRESS:
                               9316                 :            328 :             xid = HeapTupleHeaderGetXmin(tuple->t_data);
                               9317                 :            328 :             break;
                               9318                 :            124 :         case HEAPTUPLE_DEAD:
 2015 pg@bowt.ie               9319         [ -  + ]:            124 :             Assert(!visible);
 2150 tmunro@postgresql.or     9320                 :            124 :             return;
 2150 tmunro@postgresql.or     9321                 :UBC           0 :         default:
                               9322                 :                : 
                               9323                 :                :             /*
                               9324                 :                :              * The only way to get to this default clause is if a new value is
                               9325                 :                :              * added to the enum type without adding it to this switch
                               9326                 :                :              * statement.  That's a bug, so elog.
                               9327                 :                :              */
                               9328         [ #  # ]:              0 :             elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
                               9329                 :                : 
                               9330                 :                :             /*
                               9331                 :                :              * In spite of having all enum values covered and calling elog on
                               9332                 :                :              * this default, some compilers think this is a code path which
                               9333                 :                :              * allows xid to be used below without initialization. Silence
                               9334                 :                :              * that warning.
                               9335                 :                :              */
                               9336                 :                :             xid = InvalidTransactionId;
                               9337                 :                :     }
                               9338                 :                : 
 2150 tmunro@postgresql.or     9339         [ -  + ]:CBC         635 :     Assert(TransactionIdIsValid(xid));
                               9340         [ -  + ]:            635 :     Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
                               9341                 :                : 
                               9342                 :                :     /*
                               9343                 :                :      * Find top level xid.  Bail out if xid is too early to be a conflict, or
                               9344                 :                :      * if it's our own xid.
                               9345                 :                :      */
                               9346         [ +  + ]:            635 :     if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
                               9347                 :             64 :         return;
                               9348                 :            571 :     xid = SubTransGetTopmostTransaction(xid);
                               9349         [ -  + ]:            571 :     if (TransactionIdPrecedes(xid, TransactionXmin))
 2150 tmunro@postgresql.or     9350                 :UBC           0 :         return;
                               9351                 :                : 
 2150 tmunro@postgresql.or     9352                 :CBC         571 :     CheckForSerializableConflictOut(relation, xid, snapshot);
                               9353                 :                : }
        

Generated by: LCOV version 2.4-beta