LCOV - differential code coverage report
Current view: top level - src/backend/access/heap - heapam.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC DUB DCB
Current: 603a3335f2b60b2c798da5c627b3bb288b92a7bd vs e395fbd32a07557de4ac98088928c1749d4845d8 Lines: 91.9 % 2987 2744 1 242 2 8 2734 1 8
Current Date: 2026-07-25 17:13:00 -0400 Functions: 100.0 % 82 82 7 75
Baseline: lcov-20260726-baseline Branches: 73.4 % 2443 1794 5 1 643 2 13 1779
Baseline Date: 2026-07-25 19:16:42 +0200 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 92.9 % 168 156 1 11 8 148
(30,360] days: 96.0 % 124 119 5 119
(360..) days: 91.6 % 2695 2469 226 2 2467
Function coverage date bins:
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 9 9 3 6
(360..) days: 100.0 % 72 72 4 68
Branch coverage date bins:
(7,30] days: 86.0 % 172 148 5 19 13 135
(30,360] days: 70.3 % 158 111 47 111
(360..) days: 72.6 % 2113 1535 1 577 2 1533

 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-2026, PostgreSQL Global Development Group
                                  7                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                  8                 :                :  *
                                  9                 :                :  *
                                 10                 :                :  * IDENTIFICATION
                                 11                 :                :  *    src/backend/access/heap/heapam.c
                                 12                 :                :  *
                                 13                 :                :  *
                                 14                 :                :  * INTERFACE ROUTINES
                                 15                 :                :  *      heap_beginscan  - begin relation scan
                                 16                 :                :  *      heap_rescan     - restart a relation scan
                                 17                 :                :  *      heap_endscan    - end relation scan
                                 18                 :                :  *      heap_getnext    - retrieve next tuple in scan
                                 19                 :                :  *      heap_fetch      - retrieve tuple with given tid
                                 20                 :                :  *      heap_insert     - insert tuple into a relation
                                 21                 :                :  *      heap_multi_insert - insert multiple tuples into a relation
                                 22                 :                :  *      heap_delete     - delete a tuple from a relation
                                 23                 :                :  *      heap_update     - replace a tuple in a relation with another tuple
                                 24                 :                :  *
                                 25                 :                :  * NOTES
                                 26                 :                :  *    This file contains the heap_ routines which implement
                                 27                 :                :  *    the POSTGRES heap access method used for all POSTGRES
                                 28                 :                :  *    relations.
                                 29                 :                :  *
                                 30                 :                :  *-------------------------------------------------------------------------
                                 31                 :                :  */
                                 32                 :                : #include "postgres.h"
                                 33                 :                : 
                                 34                 :                : #include "access/heapam.h"
                                 35                 :                : #include "access/heaptoast.h"
                                 36                 :                : #include "access/hio.h"
                                 37                 :                : #include "access/multixact.h"
                                 38                 :                : #include "access/subtrans.h"
                                 39                 :                : #include "access/syncscan.h"
                                 40                 :                : #include "access/valid.h"
                                 41                 :                : #include "access/visibilitymap.h"
                                 42                 :                : #include "access/xloginsert.h"
                                 43                 :                : #include "catalog/pg_database.h"
                                 44                 :                : #include "catalog/pg_database_d.h"
                                 45                 :                : #include "commands/vacuum.h"
                                 46                 :                : #include "executor/instrument_node.h"
                                 47                 :                : #include "pgstat.h"
                                 48                 :                : #include "port/pg_bitutils.h"
                                 49                 :                : #include "storage/lmgr.h"
                                 50                 :                : #include "storage/predicate.h"
                                 51                 :                : #include "storage/proc.h"
                                 52                 :                : #include "storage/procarray.h"
                                 53                 :                : #include "utils/datum.h"
                                 54                 :                : #include "utils/injection_point.h"
                                 55                 :                : #include "utils/inval.h"
                                 56                 :                : #include "utils/spccache.h"
                                 57                 :                : #include "utils/syscache.h"
                                 58                 :                : 
                                 59                 :                : 
                                 60                 :                : static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
                                 61                 :                :                                      TransactionId xid, CommandId cid, uint32 options);
                                 62                 :                : static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
                                 63                 :                :                                   Buffer vmbuffer_old, Buffer newbuf,
                                 64                 :                :                                   Buffer vmbuffer_new, HeapTuple oldtup,
                                 65                 :                :                                   HeapTuple newtup, HeapTuple old_key_tuple,
                                 66                 :                :                                   bool all_visible_cleared, bool new_all_visible_cleared,
                                 67                 :                :                                   bool walLogical);
                                 68                 :                : #ifdef USE_ASSERT_CHECKING
                                 69                 :                : static void check_lock_if_inplace_updateable_rel(Relation relation,
                                 70                 :                :                                                  const ItemPointerData *otid,
                                 71                 :                :                                                  HeapTuple newtup);
                                 72                 :                : static void check_inplace_rel_lock(HeapTuple oldtup);
                                 73                 :                : #endif
                                 74                 :                : static Bitmapset *HeapDetermineColumnsInfo(Relation relation,
                                 75                 :                :                                            Bitmapset *interesting_cols,
                                 76                 :                :                                            Bitmapset *external_cols,
                                 77                 :                :                                            HeapTuple oldtup, HeapTuple newtup,
                                 78                 :                :                                            bool *has_external);
                                 79                 :                : static bool heap_acquire_tuplock(Relation relation, const ItemPointerData *tid,
                                 80                 :                :                                  LockTupleMode mode, LockWaitPolicy wait_policy,
                                 81                 :                :                                  bool *have_tuple_lock);
                                 82                 :                : static inline BlockNumber heapgettup_advance_block(HeapScanDesc scan,
                                 83                 :                :                                                    BlockNumber block,
                                 84                 :                :                                                    ScanDirection dir);
                                 85                 :                : static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan,
                                 86                 :                :                                                         ScanDirection dir);
                                 87                 :                : static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
                                 88                 :                :                                       uint16 old_infomask2, TransactionId add_to_xmax,
                                 89                 :                :                                       LockTupleMode mode, bool is_update,
                                 90                 :                :                                       TransactionId *result_xmax, uint16 *result_infomask,
                                 91                 :                :                                       uint16 *result_infomask2);
                                 92                 :                : static TM_Result heap_lock_updated_tuple(Relation rel,
                                 93                 :                :                                          uint16 prior_infomask,
                                 94                 :                :                                          TransactionId prior_raw_xmax,
                                 95                 :                :                                          const ItemPointerData *prior_ctid,
                                 96                 :                :                                          TransactionId xid,
                                 97                 :                :                                          LockTupleMode mode);
                                 98                 :                : static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
                                 99                 :                :                                    uint16 *new_infomask2);
                                100                 :                : static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax,
                                101                 :                :                                              uint16 t_infomask);
                                102                 :                : static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
                                103                 :                :                                     LockTupleMode lockmode, bool *current_is_member);
                                104                 :                : static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
                                105                 :                :                             Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
                                106                 :                :                             int *remaining);
                                107                 :                : static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
                                108                 :                :                                        uint16 infomask, Relation rel, int *remaining,
                                109                 :                :                                        bool logLockFailure);
                                110                 :                : static void index_delete_sort(TM_IndexDeleteOp *delstate);
                                111                 :                : static int  bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate);
                                112                 :                : static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup);
                                113                 :                : static HeapTuple ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
                                114                 :                :                                         bool *copy);
                                115                 :                : 
                                116                 :                : 
                                117                 :                : /*
                                118                 :                :  * This table lists the heavyweight lock mode that corresponds to each tuple
                                119                 :                :  * lock mode, as well as one or two corresponding MultiXactStatus values:
                                120                 :                :  * .lockstatus to merely lock tuples, and .updstatus to update them.  The
                                121                 :                :  * latter is set to -1 if the corresponding tuple lock mode does not allow
                                122                 :                :  * updating tuples -- see get_mxact_status_for_lock().
                                123                 :                :  *
                                124                 :                :  * These interact with InplaceUpdateTupleLock, an alias for ExclusiveLock.
                                125                 :                :  *
                                126                 :                :  * Don't look at lockstatus/updstatus directly!  Use get_mxact_status_for_lock
                                127                 :                :  * instead.
                                128                 :                :  */
                                129                 :                : static const struct
                                130                 :                : {
                                131                 :                :     LOCKMODE    hwlock;
                                132                 :                :     int         lockstatus;
                                133                 :                :     int         updstatus;
                                134                 :                : }           tupleLockExtraInfo[] =
                                135                 :                : 
                                136                 :                : {
                                137                 :                :     [LockTupleKeyShare] = {
                                138                 :                :         .hwlock = AccessShareLock,
                                139                 :                :         .lockstatus = MultiXactStatusForKeyShare,
                                140                 :                :         /* KeyShare does not allow updating tuples */
                                141                 :                :         .updstatus = -1
                                142                 :                :     },
                                143                 :                :     [LockTupleShare] = {
                                144                 :                :         .hwlock = RowShareLock,
                                145                 :                :         .lockstatus = MultiXactStatusForShare,
                                146                 :                :         /* Share does not allow updating tuples */
                                147                 :                :         .updstatus = -1
                                148                 :                :     },
                                149                 :                :     [LockTupleNoKeyExclusive] = {
                                150                 :                :         .hwlock = ExclusiveLock,
                                151                 :                :         .lockstatus = MultiXactStatusForNoKeyUpdate,
                                152                 :                :         .updstatus = MultiXactStatusNoKeyUpdate
                                153                 :                :     },
                                154                 :                :     [LockTupleExclusive] = {
                                155                 :                :         .hwlock = AccessExclusiveLock,
                                156                 :                :         .lockstatus = MultiXactStatusForUpdate,
                                157                 :                :         .updstatus = MultiXactStatusUpdate
                                158                 :                :     }
                                159                 :                : };
                                160                 :                : 
                                161                 :                : /* Get the LOCKMODE for a given MultiXactStatus */
                                162                 :                : #define LOCKMODE_from_mxstatus(status) \
                                163                 :                :             (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
                                164                 :                : 
                                165                 :                : /*
                                166                 :                :  * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
                                167                 :                :  * This is more readable than having every caller translate it to lock.h's
                                168                 :                :  * LOCKMODE.
                                169                 :                :  */
                                170                 :                : #define LockTupleTuplock(rel, tup, mode) \
                                171                 :                :     LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
                                172                 :                : #define UnlockTupleTuplock(rel, tup, mode) \
                                173                 :                :     UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
                                174                 :                : #define ConditionalLockTupleTuplock(rel, tup, mode, log) \
                                175                 :                :     ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock, (log))
                                176                 :                : 
                                177                 :                : #ifdef USE_PREFETCH
                                178                 :                : /*
                                179                 :                :  * heap_index_delete_tuples and index_delete_prefetch_buffer use this
                                180                 :                :  * structure to coordinate prefetching activity
                                181                 :                :  */
                                182                 :                : typedef struct
                                183                 :                : {
                                184                 :                :     BlockNumber cur_hblkno;
                                185                 :                :     int         next_item;
                                186                 :                :     int         ndeltids;
                                187                 :                :     TM_IndexDelete *deltids;
                                188                 :                : } IndexDeletePrefetchState;
                                189                 :                : #endif
                                190                 :                : 
                                191                 :                : /* heap_index_delete_tuples bottom-up index deletion costing constants */
                                192                 :                : #define BOTTOMUP_MAX_NBLOCKS            6
                                193                 :                : #define BOTTOMUP_TOLERANCE_NBLOCKS      3
                                194                 :                : 
                                195                 :                : /*
                                196                 :                :  * heap_index_delete_tuples uses this when determining which heap blocks it
                                197                 :                :  * must visit to help its bottom-up index deletion caller
                                198                 :                :  */
                                199                 :                : typedef struct IndexDeleteCounts
                                200                 :                : {
                                201                 :                :     int16       npromisingtids; /* Number of "promising" TIDs in group */
                                202                 :                :     int16       ntids;          /* Number of TIDs in group */
                                203                 :                :     int16       ifirsttid;      /* Offset to group's first deltid */
                                204                 :                : } IndexDeleteCounts;
                                205                 :                : 
                                206                 :                : /*
                                207                 :                :  * This table maps tuple lock strength values for each particular
                                208                 :                :  * MultiXactStatus value.
                                209                 :                :  */
                                210                 :                : static const int MultiXactStatusLock[MaxMultiXactStatus + 1] =
                                211                 :                : {
                                212                 :                :     LockTupleKeyShare,          /* ForKeyShare */
                                213                 :                :     LockTupleShare,             /* ForShare */
                                214                 :                :     LockTupleNoKeyExclusive,    /* ForNoKeyUpdate */
                                215                 :                :     LockTupleExclusive,         /* ForUpdate */
                                216                 :                :     LockTupleNoKeyExclusive,    /* NoKeyUpdate */
                                217                 :                :     LockTupleExclusive          /* Update */
                                218                 :                : };
                                219                 :                : 
                                220                 :                : /* Get the LockTupleMode for a given MultiXactStatus */
                                221                 :                : #define TUPLOCK_from_mxstatus(status) \
                                222                 :                :             (MultiXactStatusLock[(status)])
                                223                 :                : 
                                224                 :                : /*
                                225                 :                :  * Check that we have a valid snapshot if we might need TOAST access.
                                226                 :                :  */
                                227                 :                : static inline void
  422 nathan@postgresql.or      228                 :CBC    16484266 : AssertHasSnapshotForToast(Relation rel)
                                229                 :                : {
                                230                 :                : #ifdef USE_ASSERT_CHECKING
                                231                 :                : 
                                232                 :                :     /* bootstrap mode in particular breaks this rule */
                                233         [ +  + ]:       16484266 :     if (!IsNormalProcessingMode())
                                234                 :         660408 :         return;
                                235                 :                : 
                                236                 :                :     /* if the relation doesn't have a TOAST table, we are good */
                                237         [ +  + ]:       15823858 :     if (!OidIsValid(rel->rd_rel->reltoastrelid))
                                238                 :       10260395 :         return;
                                239                 :                : 
                                240         [ -  + ]:        5563463 :     Assert(HaveRegisteredOrActiveSnapshot());
                                241                 :                : 
                                242                 :                : #endif                          /* USE_ASSERT_CHECKING */
                                243                 :                : }
                                244                 :                : 
                                245                 :                : /* ----------------------------------------------------------------
                                246                 :                :  *                       heap support routines
                                247                 :                :  * ----------------------------------------------------------------
                                248                 :                :  */
                                249                 :                : 
                                250                 :                : /*
                                251                 :                :  * Streaming read API callback for parallel sequential scans. Returns the next
                                252                 :                :  * block the caller wants from the read stream or InvalidBlockNumber when done.
                                253                 :                :  */
                                254                 :                : static BlockNumber
  839 tmunro@postgresql.or      255                 :         146064 : heap_scan_stream_read_next_parallel(ReadStream *stream,
                                256                 :                :                                     void *callback_private_data,
                                257                 :                :                                     void *per_buffer_data)
                                258                 :                : {
                                259                 :         146064 :     HeapScanDesc scan = (HeapScanDesc) callback_private_data;
                                260                 :                : 
                                261         [ -  + ]:         146064 :     Assert(ScanDirectionIsForward(scan->rs_dir));
                                262         [ -  + ]:         146064 :     Assert(scan->rs_base.rs_parallel);
                                263                 :                : 
                                264         [ +  + ]:         146064 :     if (unlikely(!scan->rs_inited))
                                265                 :                :     {
                                266                 :                :         /* parallel scan */
                                267                 :           2853 :         table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
                                268                 :           2853 :                                                  scan->rs_parallelworkerdata,
  241 drowley@postgresql.o      269                 :           2853 :                                                  (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel,
                                270                 :                :                                                  scan->rs_startblock,
                                271                 :                :                                                  scan->rs_numblocks);
                                272                 :                : 
                                273                 :                :         /* may return InvalidBlockNumber if there are no more blocks */
  839 tmunro@postgresql.or      274                 :           5706 :         scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
                                275                 :           2853 :                                                                     scan->rs_parallelworkerdata,
                                276                 :           2853 :                                                                     (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
                                277                 :           2853 :         scan->rs_inited = true;
                                278                 :                :     }
                                279                 :                :     else
                                280                 :                :     {
                                281                 :         143211 :         scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
                                282                 :         143211 :                                                                     scan->rs_parallelworkerdata, (ParallelBlockTableScanDesc)
                                283                 :         143211 :                                                                     scan->rs_base.rs_parallel);
                                284                 :                :     }
                                285                 :                : 
                                286                 :         146064 :     return scan->rs_prefetch_block;
                                287                 :                : }
                                288                 :                : 
                                289                 :                : /*
                                290                 :                :  * Streaming read API callback for serial sequential and TID range scans.
                                291                 :                :  * Returns the next block the caller wants from the read stream or
                                292                 :                :  * InvalidBlockNumber when done.
                                293                 :                :  */
                                294                 :                : static BlockNumber
                                295                 :        4153614 : heap_scan_stream_read_next_serial(ReadStream *stream,
                                296                 :                :                                   void *callback_private_data,
                                297                 :                :                                   void *per_buffer_data)
                                298                 :                : {
                                299                 :        4153614 :     HeapScanDesc scan = (HeapScanDesc) callback_private_data;
                                300                 :                : 
                                301         [ +  + ]:        4153614 :     if (unlikely(!scan->rs_inited))
                                302                 :                :     {
                                303                 :        1077637 :         scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
                                304                 :        1077637 :         scan->rs_inited = true;
                                305                 :                :     }
                                306                 :                :     else
                                307                 :        3075977 :         scan->rs_prefetch_block = heapgettup_advance_block(scan,
                                308                 :                :                                                            scan->rs_prefetch_block,
                                309                 :                :                                                            scan->rs_dir);
                                310                 :                : 
                                311                 :        4153614 :     return scan->rs_prefetch_block;
                                312                 :                : }
                                313                 :                : 
                                314                 :                : /*
                                315                 :                :  * Read stream API callback for bitmap heap scans.
                                316                 :                :  * Returns the next block the caller wants from the read stream or
                                317                 :                :  * InvalidBlockNumber when done.
                                318                 :                :  */
                                319                 :                : static BlockNumber
  498 melanieplageman@gmai      320                 :         258209 : bitmapheap_stream_read_next(ReadStream *pgsr, void *private_data,
                                321                 :                :                             void *per_buffer_data)
                                322                 :                : {
                                323                 :         258209 :     TBMIterateResult *tbmres = per_buffer_data;
                                324                 :         258209 :     BitmapHeapScanDesc bscan = (BitmapHeapScanDesc) private_data;
                                325                 :         258209 :     HeapScanDesc hscan = (HeapScanDesc) bscan;
                                326                 :         258209 :     TableScanDesc sscan = &hscan->rs_base;
                                327                 :                : 
                                328                 :                :     for (;;)
                                329                 :                :     {
                                330         [ +  + ]:         258209 :         CHECK_FOR_INTERRUPTS();
                                331                 :                : 
                                332                 :                :         /* no more entries in the bitmap */
                                333         [ +  + ]:         258209 :         if (!tbm_iterate(&sscan->st.rs_tbmiterator, tbmres))
                                334                 :          14797 :             return InvalidBlockNumber;
                                335                 :                : 
                                336                 :                :         /*
                                337                 :                :          * Ignore any claimed entries past what we think is the end of the
                                338                 :                :          * relation. It may have been extended after the start of our scan (we
                                339                 :                :          * only hold an AccessShareLock, and it could be inserts from this
                                340                 :                :          * backend).  We don't take this optimization in SERIALIZABLE
                                341                 :                :          * isolation though, as we need to examine all invisible tuples
                                342                 :                :          * reachable by the index.
                                343                 :                :          */
                                344         [ +  + ]:         243412 :         if (!IsolationIsSerializable() &&
                                345         [ -  + ]:         243303 :             tbmres->blockno >= hscan->rs_nblocks)
  498 melanieplageman@gmai      346                 :UBC           0 :             continue;
                                347                 :                : 
  498 melanieplageman@gmai      348                 :CBC      243412 :         return tbmres->blockno;
                                349                 :                :     }
                                350                 :                : 
                                351                 :                :     /* not reachable */
                                352                 :                :     Assert(false);
                                353                 :                : }
                                354                 :                : 
                                355                 :                : /* ----------------
                                356                 :                :  *      initscan - scan code common to heap_beginscan and heap_rescan
                                357                 :                :  * ----------------
                                358                 :                :  */
                                359                 :                : static void
 4019 tgl@sss.pgh.pa.us         360                 :        1109399 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
                                361                 :                : {
 2694 andres@anarazel.de        362                 :        1109399 :     ParallelBlockTableScanDesc bpscan = NULL;
                                363                 :                :     bool        allow_strat;
                                364                 :                :     bool        allow_sync;
                                365                 :                : 
                                366                 :                :     /*
                                367                 :                :      * Determine the number of blocks we have to scan.
                                368                 :                :      *
                                369                 :                :      * It is sufficient to do this once at scan start, since any tuples added
                                370                 :                :      * while the scan is in progress will be invisible to my snapshot anyway.
                                371                 :                :      * (That is not true when using a non-MVCC snapshot.  However, we couldn't
                                372                 :                :      * guarantee to return tuples added after scan start anyway, since they
                                373                 :                :      * might go into pages we already scanned.  To guarantee consistent
                                374                 :                :      * results for a non-MVCC snapshot, the caller must hold some higher-level
                                375                 :                :      * lock that ensures the interesting tuple(s) won't change.)
                                376                 :                :      */
                                377         [ +  + ]:        1109399 :     if (scan->rs_base.rs_parallel != NULL)
                                378                 :                :     {
                                379                 :           4678 :         bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
                                380                 :           4678 :         scan->rs_nblocks = bpscan->phs_nblocks;
                                381                 :                :     }
                                382                 :                :     else
                                383                 :        1104721 :         scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_base.rs_rd);
                                384                 :                : 
                                385                 :                :     /*
                                386                 :                :      * If the table is large relative to NBuffers, use a bulk-read access
                                387                 :                :      * strategy and enable synchronized scanning (see syncscan.c).  Although
                                388                 :                :      * the thresholds for these features could be different, we make them the
                                389                 :                :      * same so that there are only two behaviors to tune rather than four.
                                390                 :                :      * (However, some callers need to be able to disable one or both of these
                                391                 :                :      * behaviors, independently of the size of the table; also there is a GUC
                                392                 :                :      * variable that can disable synchronized scanning.)
                                393                 :                :      *
                                394                 :                :      * Note that table_block_parallelscan_initialize has a very similar test;
                                395                 :                :      * if you change this, consider changing that one, too.
                                396                 :                :      */
                                397         [ +  + ]:        1109397 :     if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
 6987 tgl@sss.pgh.pa.us         398         [ +  + ]:        1099401 :         scan->rs_nblocks > NBuffers / 4)
                                399                 :                :     {
 2625 andres@anarazel.de        400                 :          15791 :         allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
                                401                 :          15791 :         allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
                                402                 :                :     }
                                403                 :                :     else
 6768 tgl@sss.pgh.pa.us         404                 :        1093606 :         allow_strat = allow_sync = false;
                                405                 :                : 
                                406         [ +  + ]:        1109397 :     if (allow_strat)
                                407                 :                :     {
                                408                 :                :         /* During a rescan, keep the previous strategy object. */
 6997                           409         [ +  + ]:          14418 :         if (scan->rs_strategy == NULL)
                                410                 :          14235 :             scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
                                411                 :                :     }
                                412                 :                :     else
                                413                 :                :     {
                                414         [ -  + ]:        1094979 :         if (scan->rs_strategy != NULL)
 6997 tgl@sss.pgh.pa.us         415                 :UBC           0 :             FreeAccessStrategy(scan->rs_strategy);
 6997 tgl@sss.pgh.pa.us         416                 :CBC     1094979 :         scan->rs_strategy = NULL;
                                417                 :                :     }
                                418                 :                : 
 2694 andres@anarazel.de        419         [ +  + ]:        1109397 :     if (scan->rs_base.rs_parallel != NULL)
                                420                 :                :     {
                                421                 :                :         /* For parallel scan, believe whatever ParallelTableScanDesc says. */
 2625                           422         [ +  + ]:           4678 :         if (scan->rs_base.rs_parallel->phs_syncscan)
                                423                 :              5 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                                424                 :                :         else
                                425                 :           4673 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                426                 :                : 
                                427                 :                :         /*
                                428                 :                :          * If not rescanning, initialize the startblock.  Finding the actual
                                429                 :                :          * start location is done in table_block_parallelscan_startblock_init,
                                430                 :                :          * based on whether an alternative start location has been set with
                                431                 :                :          * heap_setscanlimits, or using the syncscan location, when syncscan
                                432                 :                :          * is enabled.
                                433                 :                :          */
  240 drowley@postgresql.o      434         [ +  + ]:           4678 :         if (!keep_startblock)
                                435                 :           4526 :             scan->rs_startblock = InvalidBlockNumber;
                                436                 :                :     }
                                437                 :                :     else
                                438                 :                :     {
                                439         [ +  + ]:        1104719 :         if (keep_startblock)
                                440                 :                :         {
                                441                 :                :             /*
                                442                 :                :              * When rescanning, we want to keep the previous startblock
                                443                 :                :              * setting, so that rewinding a cursor doesn't generate surprising
                                444                 :                :              * results.  Reset the active syncscan setting, though.
                                445                 :                :              */
                                446   [ +  +  +  + ]:         638112 :             if (allow_sync && synchronize_seqscans)
                                447                 :             50 :                 scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                                448                 :                :             else
                                449                 :         638062 :                 scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                450                 :                :         }
                                451   [ +  +  +  + ]:         466607 :         else if (allow_sync && synchronize_seqscans)
                                452                 :                :         {
                                453                 :             98 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                                454                 :             98 :             scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
                                455                 :                :         }
                                456                 :                :         else
                                457                 :                :         {
                                458                 :         466509 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                459                 :         466509 :             scan->rs_startblock = 0;
                                460                 :                :         }
                                461                 :                :     }
                                462                 :                : 
 4279 alvherre@alvh.no-ip.      463                 :        1109397 :     scan->rs_numblocks = InvalidBlockNumber;
 7547 tgl@sss.pgh.pa.us         464                 :        1109397 :     scan->rs_inited = false;
 9178                           465                 :        1109397 :     scan->rs_ctup.t_data = NULL;
 7547                           466                 :        1109397 :     ItemPointerSetInvalid(&scan->rs_ctup.t_self);
 9178                           467                 :        1109397 :     scan->rs_cbuf = InvalidBuffer;
 7547                           468                 :        1109397 :     scan->rs_cblock = InvalidBlockNumber;
  585 melanieplageman@gmai      469                 :        1109397 :     scan->rs_ntuples = 0;
                                470                 :        1109397 :     scan->rs_cindex = 0;
                                471                 :                : 
                                472                 :                :     /*
                                473                 :                :      * Initialize to ForwardScanDirection because it is most common and
                                474                 :                :      * because heap scans go forward before going backward (e.g. CURSORs).
                                475                 :                :      */
  839 tmunro@postgresql.or      476                 :        1109397 :     scan->rs_dir = ForwardScanDirection;
                                477                 :        1109397 :     scan->rs_prefetch_block = InvalidBlockNumber;
                                478                 :                : 
                                479                 :                :     /* page-at-a-time fields are always invalid when not rs_inited */
                                480                 :                : 
                                481                 :                :     /*
                                482                 :                :      * copy the scan key, if appropriate
                                483                 :                :      */
 1606 tgl@sss.pgh.pa.us         484   [ +  +  +  + ]:        1109397 :     if (key != NULL && scan->rs_base.rs_nkeys > 0)
 2694 andres@anarazel.de        485                 :         264155 :         memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
                                486                 :                : 
                                487                 :                :     /*
                                488                 :                :      * Currently, we only have a stats counter for sequential heap scans (but
                                489                 :                :      * e.g for bitmap scans the underlying bitmap index scans will be counted,
                                490                 :                :      * and for sample scans we update stats for tuple fetches).
                                491                 :                :      */
 2625                           492         [ +  + ]:        1109397 :     if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
 2694                           493   [ +  +  +  +  :        1080983 :         pgstat_count_heap_scan(scan->rs_base.rs_rd);
                                              +  + ]
10974 scrappy@hub.org           494                 :        1109397 : }
                                495                 :                : 
                                496                 :                : /*
                                497                 :                :  * heap_setscanlimits - restrict range of a heapscan
                                498                 :                :  *
                                499                 :                :  * startBlk is the page to start at
                                500                 :                :  * numBlks is number of pages to scan (InvalidBlockNumber means "all")
                                501                 :                :  */
                                502                 :                : void
 2694 andres@anarazel.de        503                 :           3280 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
                                504                 :                : {
                                505                 :           3280 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                                506                 :                : 
 4023 tgl@sss.pgh.pa.us         507         [ -  + ]:           3280 :     Assert(!scan->rs_inited);    /* else too late to change */
                                508                 :                :     /* else rs_startblock is significant */
 2625 andres@anarazel.de        509         [ -  + ]:           3280 :     Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
                                510                 :                : 
                                511                 :                :     /* Check startBlk is valid (but allow case of zero blocks...) */
 4023 tgl@sss.pgh.pa.us         512   [ +  +  -  + ]:           3280 :     Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
                                513                 :                : 
 4279 alvherre@alvh.no-ip.      514                 :           3280 :     scan->rs_startblock = startBlk;
                                515                 :           3280 :     scan->rs_numblocks = numBlks;
                                516                 :           3280 : }
                                517                 :                : 
                                518                 :                : /*
                                519                 :                :  * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
                                520                 :                :  * multiple times, with constant arguments for all_visible,
                                521                 :                :  * check_serializable.
                                522                 :                :  */
                                523                 :                : pg_always_inline
                                524                 :                : static int
  840 andres@anarazel.de        525                 :        3090271 : page_collect_tuples(HeapScanDesc scan, Snapshot snapshot,
                                526                 :                :                     Page page, Buffer buffer,
                                527                 :                :                     BlockNumber block, int lines,
                                528                 :                :                     bool all_visible, bool check_serializable)
                                529                 :                : {
  195                           530                 :        3090271 :     Oid         relid = RelationGetRelid(scan->rs_base.rs_rd);
  841                           531                 :        3090271 :     int         ntup = 0;
  195                           532                 :        3090271 :     int         nvis = 0;
                                533                 :                :     BatchMVCCState batchmvcc;
                                534                 :                : 
                                535                 :                :     /* page at a time should have been disabled otherwise */
                                536         [ -  + ]:        3090271 :     Assert(IsMVCCSnapshot(snapshot));
                                537                 :                : 
                                538                 :                :     /* first find all tuples on the page */
                                539         [ +  + ]:      163806854 :     for (OffsetNumber lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
                                540                 :                :     {
  841                           541                 :      160716583 :         ItemId      lpp = PageGetItemId(page, lineoff);
                                542                 :                :         HeapTuple   tup;
                                543                 :                : 
  195                           544         [ +  + ]:      160716583 :         if (unlikely(!ItemIdIsNormal(lpp)))
  841                           545                 :       25298920 :             continue;
                                546                 :                : 
                                547                 :                :         /*
                                548                 :                :          * If the page is not all-visible or we need to check serializability,
                                549                 :                :          * maintain enough state to be able to refind the tuple efficiently,
                                550                 :                :          * without again first needing to fetch the item and then via that the
                                551                 :                :          * tuple.
                                552                 :                :          */
  195                           553   [ +  +  -  + ]:      135417663 :         if (!all_visible || check_serializable)
                                554                 :                :         {
                                555                 :       75064882 :             tup = &batchmvcc.tuples[ntup];
                                556                 :                : 
                                557                 :       75064882 :             tup->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
                                558                 :       75064882 :             tup->t_len = ItemIdGetLength(lpp);
                                559                 :       75064882 :             tup->t_tableOid = relid;
                                560                 :       75064882 :             ItemPointerSet(&(tup->t_self), block, lineoff);
                                561                 :                :         }
                                562                 :                : 
                                563                 :                :         /*
                                564                 :                :          * If the page is all visible, these fields otherwise won't be
                                565                 :                :          * populated in loop below.
                                566                 :                :          */
                                567         [ +  + ]:      135417663 :         if (all_visible)
                                568                 :                :         {
                                569         [ -  + ]:       60352781 :             if (check_serializable)
                                570                 :                :             {
  195 andres@anarazel.de        571                 :UBC           0 :                 batchmvcc.visible[ntup] = true;
                                572                 :                :             }
  841 andres@anarazel.de        573                 :CBC    60352781 :             scan->rs_vistuples[ntup] = lineoff;
                                574                 :                :         }
                                575                 :                : 
  195                           576                 :      135417663 :         ntup++;
                                577                 :                :     }
                                578                 :                : 
  841                           579         [ -  + ]:        3090271 :     Assert(ntup <= MaxHeapTuplesPerPage);
                                580                 :                : 
                                581                 :                :     /*
                                582                 :                :      * Unless the page is all visible, test visibility for all tuples one go.
                                583                 :                :      * That is considerably more efficient than calling
                                584                 :                :      * HeapTupleSatisfiesMVCC() one-by-one.
                                585                 :                :      */
  195                           586         [ +  + ]:        3090271 :     if (all_visible)
                                587                 :        1282211 :         nvis = ntup;
                                588                 :                :     else
                                589                 :        1808060 :         nvis = HeapTupleSatisfiesMVCCBatch(snapshot, buffer,
                                590                 :                :                                            ntup,
                                591                 :                :                                            &batchmvcc,
                                592                 :        1808060 :                                            scan->rs_vistuples);
                                593                 :                : 
                                594                 :                :     /*
                                595                 :                :      * So far we don't have batch API for testing serializabilty, so do so
                                596                 :                :      * one-by-one.
                                597                 :                :      */
                                598         [ +  + ]:        3090271 :     if (check_serializable)
                                599                 :                :     {
                                600         [ +  + ]:           2087 :         for (int i = 0; i < ntup; i++)
                                601                 :                :         {
                                602                 :           1464 :             HeapCheckForSerializableConflictOut(batchmvcc.visible[i],
                                603                 :                :                                                 scan->rs_base.rs_rd,
                                604                 :                :                                                 &batchmvcc.tuples[i],
                                605                 :                :                                                 buffer, snapshot);
                                606                 :                :         }
                                607                 :                :     }
                                608                 :                : 
                                609                 :        3090263 :     return nvis;
                                610                 :                : }
                                611                 :                : 
                                612                 :                : /*
                                613                 :                :  * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
                                614                 :                :  *
                                615                 :                :  * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
                                616                 :                :  * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
                                617                 :                :  */
                                618                 :                : void
  843 drowley@postgresql.o      619                 :        3090271 : heap_prepare_pagescan(TableScanDesc sscan)
                                620                 :                : {
 2694 andres@anarazel.de        621                 :        3090271 :     HeapScanDesc scan = (HeapScanDesc) sscan;
  843 drowley@postgresql.o      622                 :        3090271 :     Buffer      buffer = scan->rs_cbuf;
                                623                 :        3090271 :     BlockNumber block = scan->rs_cblock;
                                624                 :                :     Snapshot    snapshot;
                                625                 :                :     Page        page;
                                626                 :                :     int         lines;
                                627                 :                :     bool        all_visible;
                                628                 :                :     bool        check_serializable;
                                629                 :                : 
                                630         [ -  + ]:        3090271 :     Assert(BufferGetBlockNumber(buffer) == block);
                                631                 :                : 
                                632                 :                :     /* ensure we're not accidentally being used when not in pagemode */
                                633         [ -  + ]:        3090271 :     Assert(scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE);
 2694 andres@anarazel.de        634                 :        3090271 :     snapshot = scan->rs_base.rs_snapshot;
                                635                 :                : 
                                636                 :                :     /*
                                637                 :                :      * Prune and repair fragmentation for the whole page, if possible.
                                638                 :                :      */
  118 melanieplageman@gmai      639                 :        3090271 :     heap_page_prune_opt(scan->rs_base.rs_rd, buffer, &scan->rs_vmbuffer,
                                640                 :        3090271 :                         sscan->rs_flags & SO_HINT_REL_READ_ONLY);
                                641                 :                : 
                                642                 :                :     /*
                                643                 :                :      * We must hold share lock on the buffer content while examining tuple
                                644                 :                :      * visibility.  Afterwards, however, the tuples we have found to be
                                645                 :                :      * visible are guaranteed good as long as we hold the buffer pin.
                                646                 :                :      */
 7547 tgl@sss.pgh.pa.us         647                 :        3090271 :     LockBuffer(buffer, BUFFER_LOCK_SHARE);
                                648                 :                : 
 1348 peter@eisentraut.org      649                 :        3090271 :     page = BufferGetPage(buffer);
                                650                 :        3090271 :     lines = PageGetMaxOffsetNumber(page);
                                651                 :                : 
                                652                 :                :     /*
                                653                 :                :      * If the all-visible flag indicates that all tuples on the page are
                                654                 :                :      * visible to everyone, we can skip the per-tuple visibility tests.
                                655                 :                :      *
                                656                 :                :      * Note: In hot standby, a tuple that's already visible to all
                                657                 :                :      * transactions on the primary might still be invisible to a read-only
                                658                 :                :      * transaction in the standby. We partly handle this problem by tracking
                                659                 :                :      * the minimum xmin of visible tuples as the cut-off XID while marking a
                                660                 :                :      * page all-visible on the primary and WAL log that along with the
                                661                 :                :      * visibility map SET operation. In hot standby, we wait for (or abort)
                                662                 :                :      * all transactions that can potentially may not see one or more tuples on
                                663                 :                :      * the page. That's how index-only scans work fine in hot standby. A
                                664                 :                :      * crucial difference between index-only scans and heap scans is that the
                                665                 :                :      * index-only scan completely relies on the visibility map where as heap
                                666                 :                :      * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
                                667                 :                :      * the page-level flag can be trusted in the same way, because it might
                                668                 :                :      * get propagated somehow without being explicitly WAL-logged, e.g. via a
                                669                 :                :      * full page write. Until we can prove that beyond doubt, let's check each
                                670                 :                :      * tuple for visibility the hard way.
                                671                 :                :      */
                                672   [ +  +  +  + ]:        3090271 :     all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
                                673                 :                :     check_serializable =
  841 andres@anarazel.de        674                 :        3090271 :         CheckForSerializableConflictOutNeeded(scan->rs_base.rs_rd, snapshot);
                                675                 :                : 
                                676                 :                :     /*
                                677                 :                :      * We call page_collect_tuples() with constant arguments, to get the
                                678                 :                :      * compiler to constant fold the constant arguments. Separate calls with
                                679                 :                :      * constant arguments, rather than variables, are needed on several
                                680                 :                :      * compilers to actually perform constant folding.
                                681                 :                :      */
                                682         [ +  + ]:        3090271 :     if (likely(all_visible))
                                683                 :                :     {
                                684         [ +  - ]:        1282211 :         if (likely(!check_serializable))
  840                           685                 :        1282211 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                686                 :                :                                                    block, lines, true, false);
                                687                 :                :         else
  840 andres@anarazel.de        688                 :UBC           0 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                689                 :                :                                                    block, lines, true, true);
                                690                 :                :     }
                                691                 :                :     else
                                692                 :                :     {
  841 andres@anarazel.de        693         [ +  + ]:CBC     1808060 :         if (likely(!check_serializable))
  840                           694                 :        1807429 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                695                 :                :                                                    block, lines, false, false);
                                696                 :                :         else
                                697                 :            631 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                698                 :                :                                                    block, lines, false, true);
                                699                 :                :     }
                                700                 :                : 
 7547 tgl@sss.pgh.pa.us         701                 :        3090263 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                                702                 :        3090263 : }
                                703                 :                : 
                                704                 :                : /*
                                705                 :                :  * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
                                706                 :                :  *
                                707                 :                :  * Read the next block of the scan relation from the read stream and save it
                                708                 :                :  * in the scan descriptor.  It is already pinned.
                                709                 :                :  */
                                710                 :                : static inline void
  843 drowley@postgresql.o      711                 :        4091354 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
                                712                 :                : {
  839 tmunro@postgresql.or      713         [ -  + ]:        4091354 :     Assert(scan->rs_read_stream);
                                714                 :                : 
                                715                 :                :     /* release previous scan buffer, if any */
  843 drowley@postgresql.o      716         [ +  + ]:        4091354 :     if (BufferIsValid(scan->rs_cbuf))
                                717                 :                :     {
                                718                 :        3010862 :         ReleaseBuffer(scan->rs_cbuf);
                                719                 :        3010862 :         scan->rs_cbuf = InvalidBuffer;
                                720                 :                :     }
                                721                 :                : 
                                722                 :                :     /*
                                723                 :                :      * Be sure to check for interrupts at least once per page.  Checks at
                                724                 :                :      * higher code levels won't be able to stop a seqscan that encounters many
                                725                 :                :      * pages' worth of consecutive dead tuples.
                                726                 :                :      */
                                727         [ +  + ]:        4091354 :     CHECK_FOR_INTERRUPTS();
                                728                 :                : 
                                729                 :                :     /*
                                730                 :                :      * If the scan direction is changing, reset the prefetch block to the
                                731                 :                :      * current block. Otherwise, we will incorrectly prefetch the blocks
                                732                 :                :      * between the prefetch block and the current block again before
                                733                 :                :      * prefetching blocks in the new, correct scan direction.
                                734                 :                :      */
  839 tmunro@postgresql.or      735         [ +  + ]:        4091349 :     if (unlikely(scan->rs_dir != dir))
                                736                 :                :     {
                                737                 :            101 :         scan->rs_prefetch_block = scan->rs_cblock;
                                738                 :            101 :         read_stream_reset(scan->rs_read_stream);
                                739                 :                :     }
                                740                 :                : 
                                741                 :        4091349 :     scan->rs_dir = dir;
                                742                 :                : 
                                743                 :        4091349 :     scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
                                744         [ +  + ]:        4091320 :     if (BufferIsValid(scan->rs_cbuf))
                                745                 :        3201586 :         scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
  843 drowley@postgresql.o      746                 :        4091320 : }
                                747                 :                : 
                                748                 :                : /*
                                749                 :                :  * heapgettup_initial_block - return the first BlockNumber to scan
                                750                 :                :  *
                                751                 :                :  * Returns InvalidBlockNumber when there are no blocks to scan.  This can
                                752                 :                :  * occur with empty tables and in parallel scans when parallel workers get all
                                753                 :                :  * of the pages before we can get a chance to get our first page.
                                754                 :                :  */
                                755                 :                : static pg_noinline BlockNumber
 1270                           756                 :        1077637 : heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
                                757                 :                : {
                                758         [ -  + ]:        1077637 :     Assert(!scan->rs_inited);
  839 tmunro@postgresql.or      759         [ -  + ]:        1077637 :     Assert(scan->rs_base.rs_parallel == NULL);
                                760                 :                : 
                                761                 :                :     /* When there are no pages to scan, return InvalidBlockNumber */
 1270 drowley@postgresql.o      762   [ +  +  +  + ]:        1077637 :     if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
                                763                 :         524627 :         return InvalidBlockNumber;
                                764                 :                : 
                                765         [ +  + ]:         553010 :     if (ScanDirectionIsForward(dir))
                                766                 :                :     {
  839 tmunro@postgresql.or      767                 :         552969 :         return scan->rs_startblock;
                                768                 :                :     }
                                769                 :                :     else
                                770                 :                :     {
                                771                 :                :         /*
                                772                 :                :          * Disable reporting to syncscan logic in a backwards scan; it's not
                                773                 :                :          * very likely anyone else is doing the same thing at the same time,
                                774                 :                :          * and much more likely that we'll just bollix things for forward
                                775                 :                :          * scanners.
                                776                 :                :          */
 1270 drowley@postgresql.o      777                 :             41 :         scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                778                 :                : 
                                779                 :                :         /*
                                780                 :                :          * Start from last page of the scan.  Ensure we take into account
                                781                 :                :          * rs_numblocks if it's been adjusted by heap_setscanlimits().
                                782                 :                :          */
                                783         [ +  + ]:             41 :         if (scan->rs_numblocks != InvalidBlockNumber)
                                784                 :              4 :             return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
                                785                 :                : 
                                786         [ -  + ]:             37 :         if (scan->rs_startblock > 0)
 1270 drowley@postgresql.o      787                 :UBC           0 :             return scan->rs_startblock - 1;
                                788                 :                : 
 1270 drowley@postgresql.o      789                 :CBC          37 :         return scan->rs_nblocks - 1;
                                790                 :                :     }
                                791                 :                : }
                                792                 :                : 
                                793                 :                : 
                                794                 :                : /*
                                795                 :                :  * heapgettup_start_page - helper function for heapgettup()
                                796                 :                :  *
                                797                 :                :  * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
                                798                 :                :  * to the number of tuples on this page.  Also set *lineoff to the first
                                799                 :                :  * offset to scan with forward scans getting the first offset and backward
                                800                 :                :  * getting the final offset on the page.
                                801                 :                :  */
                                802                 :                : static Page
 1269                           803                 :         117002 : heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
                                804                 :                :                       OffsetNumber *lineoff)
                                805                 :                : {
                                806                 :                :     Page        page;
                                807                 :                : 
                                808         [ -  + ]:         117002 :     Assert(scan->rs_inited);
                                809         [ -  + ]:         117002 :     Assert(BufferIsValid(scan->rs_cbuf));
                                810                 :                : 
                                811                 :                :     /* Caller is responsible for ensuring buffer is locked if needed */
                                812                 :         117002 :     page = BufferGetPage(scan->rs_cbuf);
                                813                 :                : 
 1265                           814                 :         117002 :     *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
                                815                 :                : 
 1269                           816         [ +  - ]:         117002 :     if (ScanDirectionIsForward(dir))
                                817                 :         117002 :         *lineoff = FirstOffsetNumber;
                                818                 :                :     else
 1269 drowley@postgresql.o      819                 :UBC           0 :         *lineoff = (OffsetNumber) (*linesleft);
                                820                 :                : 
                                821                 :                :     /* lineoff now references the physically previous or next tid */
 1269 drowley@postgresql.o      822                 :CBC      117002 :     return page;
                                823                 :                : }
                                824                 :                : 
                                825                 :                : 
                                826                 :                : /*
                                827                 :                :  * heapgettup_continue_page - helper function for heapgettup()
                                828                 :                :  *
                                829                 :                :  * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
                                830                 :                :  * to the number of tuples left to scan on this page.  Also set *lineoff to
                                831                 :                :  * the next offset to scan according to the ScanDirection in 'dir'.
                                832                 :                :  */
                                833                 :                : static inline Page
                                834                 :        9428110 : heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
                                835                 :                :                          OffsetNumber *lineoff)
                                836                 :                : {
                                837                 :                :     Page        page;
                                838                 :                : 
                                839         [ -  + ]:        9428110 :     Assert(scan->rs_inited);
                                840         [ -  + ]:        9428110 :     Assert(BufferIsValid(scan->rs_cbuf));
                                841                 :                : 
                                842                 :                :     /* Caller is responsible for ensuring buffer is locked if needed */
                                843                 :        9428110 :     page = BufferGetPage(scan->rs_cbuf);
                                844                 :                : 
                                845         [ +  - ]:        9428110 :     if (ScanDirectionIsForward(dir))
                                846                 :                :     {
                                847                 :        9428110 :         *lineoff = OffsetNumberNext(scan->rs_coffset);
                                848                 :        9428110 :         *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
                                849                 :                :     }
                                850                 :                :     else
                                851                 :                :     {
                                852                 :                :         /*
                                853                 :                :          * The previous returned tuple may have been vacuumed since the
                                854                 :                :          * previous scan when we use a non-MVCC snapshot, so we must
                                855                 :                :          * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
                                856                 :                :          */
 1269 drowley@postgresql.o      857         [ #  # ]:UBC           0 :         *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
                                858                 :              0 :         *linesleft = *lineoff;
                                859                 :                :     }
                                860                 :                : 
                                861                 :                :     /* lineoff now references the physically previous or next tid */
 1269 drowley@postgresql.o      862                 :CBC     9428110 :     return page;
                                863                 :                : }
                                864                 :                : 
                                865                 :                : /*
                                866                 :                :  * heapgettup_advance_block - helper for heap_fetch_next_buffer()
                                867                 :                :  *
                                868                 :                :  * Given the current block number, the scan direction, and various information
                                869                 :                :  * contained in the scan descriptor, calculate the BlockNumber to scan next
                                870                 :                :  * and return it.  If there are no further blocks to scan, return
                                871                 :                :  * InvalidBlockNumber to indicate this fact to the caller.
                                872                 :                :  *
                                873                 :                :  * This should not be called to determine the initial block number -- only for
                                874                 :                :  * subsequent blocks.
                                875                 :                :  *
                                876                 :                :  * This also adjusts rs_numblocks when a limit has been imposed by
                                877                 :                :  * heap_setscanlimits().
                                878                 :                :  */
                                879                 :                : static inline BlockNumber
                                880                 :        3075977 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
                                881                 :                : {
  839 tmunro@postgresql.or      882         [ -  + ]:        3075977 :     Assert(scan->rs_base.rs_parallel == NULL);
                                883                 :                : 
                                884         [ +  + ]:        3075977 :     if (likely(ScanDirectionIsForward(dir)))
                                885                 :                :     {
                                886                 :        3075900 :         block++;
                                887                 :                : 
                                888                 :                :         /* wrap back to the start of the heap */
                                889         [ +  + ]:        3075900 :         if (block >= scan->rs_nblocks)
                                890                 :         433307 :             block = 0;
                                891                 :                : 
                                892                 :                :         /*
                                893                 :                :          * Report our new scan position for synchronization purposes. We don't
                                894                 :                :          * do that when moving backwards, however. That would just mess up any
                                895                 :                :          * other forward-moving scanners.
                                896                 :                :          *
                                897                 :                :          * Note: we do this before checking for end of scan so that the final
                                898                 :                :          * state of the position hint is back at the start of the rel.  That's
                                899                 :                :          * not strictly necessary, but otherwise when you run the same query
                                900                 :                :          * multiple times the starting position would shift a little bit
                                901                 :                :          * backwards on every invocation, which is confusing. We don't
                                902                 :                :          * guarantee any specific ordering in general, though.
                                903                 :                :          */
                                904         [ +  + ]:        3075900 :         if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
                                905                 :          39381 :             ss_report_location(scan->rs_base.rs_rd, block);
                                906                 :                : 
                                907                 :                :         /* we're done if we're back at where we started */
                                908         [ +  + ]:        3075900 :         if (block == scan->rs_startblock)
                                909                 :         433257 :             return InvalidBlockNumber;
                                910                 :                : 
                                911                 :                :         /* check if the limit imposed by heap_setscanlimits() is met */
                                912         [ +  + ]:        2642643 :         if (scan->rs_numblocks != InvalidBlockNumber)
                                913                 :                :         {
                                914         [ +  + ]:           2824 :             if (--scan->rs_numblocks == 0)
                                915                 :           1596 :                 return InvalidBlockNumber;
                                916                 :                :         }
                                917                 :                : 
                                918                 :        2641047 :         return block;
                                919                 :                :     }
                                920                 :                :     else
                                921                 :                :     {
                                922                 :                :         /* we're done if the last block is the start position */
 1269 drowley@postgresql.o      923         [ +  - ]:             77 :         if (block == scan->rs_startblock)
                                924                 :             77 :             return InvalidBlockNumber;
                                925                 :                : 
                                926                 :                :         /* check if the limit imposed by heap_setscanlimits() is met */
 1269 drowley@postgresql.o      927         [ #  # ]:UBC           0 :         if (scan->rs_numblocks != InvalidBlockNumber)
                                928                 :                :         {
                                929         [ #  # ]:              0 :             if (--scan->rs_numblocks == 0)
                                930                 :              0 :                 return InvalidBlockNumber;
                                931                 :                :         }
                                932                 :                : 
                                933                 :                :         /* wrap to the end of the heap when the last page was page 0 */
                                934         [ #  # ]:              0 :         if (block == 0)
                                935                 :              0 :             block = scan->rs_nblocks;
                                936                 :                : 
                                937                 :              0 :         block--;
                                938                 :                : 
                                939                 :              0 :         return block;
                                940                 :                :     }
                                941                 :                : }
                                942                 :                : 
                                943                 :                : /* ----------------
                                944                 :                :  *      heapgettup - fetch next heap tuple
                                945                 :                :  *
                                946                 :                :  *      Initialize the scan if not already done; then advance to the next
                                947                 :                :  *      tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
                                948                 :                :  *      or set scan->rs_ctup.t_data = NULL if no more tuples.
                                949                 :                :  *
                                950                 :                :  * Note: the reason nkeys/key are passed separately, even though they are
                                951                 :                :  * kept in the scan descriptor, is that the caller may not want us to check
                                952                 :                :  * the scankeys.
                                953                 :                :  *
                                954                 :                :  * Note: when we fall off the end of the scan in either direction, we
                                955                 :                :  * reset rs_inited.  This means that a further request with the same
                                956                 :                :  * scan direction will restart the scan, which is a bit odd, but a
                                957                 :                :  * request with the opposite scan direction will start a fresh scan
                                958                 :                :  * in the proper direction.  The latter is required behavior for cursors,
                                959                 :                :  * while the former case is generally undefined behavior in Postgres
                                960                 :                :  * so we don't care too much.
                                961                 :                :  * ----------------
                                962                 :                :  */
                                963                 :                : static void
 7547 tgl@sss.pgh.pa.us         964                 :CBC     9455544 : heapgettup(HeapScanDesc scan,
                                965                 :                :            ScanDirection dir,
                                966                 :                :            int nkeys,
                                967                 :                :            ScanKey key)
                                968                 :                : {
                                969                 :        9455544 :     HeapTuple   tuple = &(scan->rs_ctup);
                                970                 :                :     Page        page;
                                971                 :                :     OffsetNumber lineoff;
                                972                 :                :     int         linesleft;
                                973                 :                : 
  843 drowley@postgresql.o      974         [ +  + ]:        9455544 :     if (likely(scan->rs_inited))
                                975                 :                :     {
                                976                 :                :         /* continue from previously returned page/tuple */
 1269                           977                 :        9428110 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
                                978                 :        9428110 :         page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
 1265                           979                 :        9428110 :         goto continue_page;
                                980                 :                :     }
                                981                 :                : 
                                982                 :                :     /*
                                983                 :                :      * advance the scan until we find a qualifying tuple or run out of stuff
                                984                 :                :      * to scan
                                985                 :                :      */
                                986                 :                :     while (true)
                                987                 :                :     {
  843                           988                 :         143572 :         heap_fetch_next_buffer(scan, dir);
                                989                 :                : 
                                990                 :                :         /* did we run out of blocks to scan? */
                                991         [ +  + ]:         143572 :         if (!BufferIsValid(scan->rs_cbuf))
                                992                 :          26570 :             break;
                                993                 :                : 
                                994         [ -  + ]:         117002 :         Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
                                995                 :                : 
 1265                           996                 :         117002 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
                                997                 :         117002 :         page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
                                998                 :        9545112 : continue_page:
                                999                 :                : 
                               1000                 :                :         /*
                               1001                 :                :          * Only continue scanning the page while we have lines left.
                               1002                 :                :          *
                               1003                 :                :          * Note that this protects us from accessing line pointers past
                               1004                 :                :          * PageGetMaxOffsetNumber(); both for forward scans when we resume the
                               1005                 :                :          * table scan, and for when we start scanning a new page.
                               1006                 :                :          */
                               1007         [ +  + ]:        9601320 :         for (; linesleft > 0; linesleft--, lineoff += dir)
                               1008                 :                :         {
                               1009                 :                :             bool        visible;
                               1010                 :        9485182 :             ItemId      lpp = PageGetItemId(page, lineoff);
                               1011                 :                : 
                               1012         [ +  + ]:        9485182 :             if (!ItemIdIsNormal(lpp))
                               1013                 :          34702 :                 continue;
                               1014                 :                : 
                               1015                 :        9450480 :             tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
                               1016                 :        9450480 :             tuple->t_len = ItemIdGetLength(lpp);
  843                          1017                 :        9450480 :             ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
                               1018                 :                : 
 1265                          1019                 :        9450480 :             visible = HeapTupleSatisfiesVisibility(tuple,
                               1020                 :                :                                                    scan->rs_base.rs_snapshot,
                               1021                 :                :                                                    scan->rs_cbuf);
                               1022                 :                : 
                               1023                 :        9450480 :             HeapCheckForSerializableConflictOut(visible, scan->rs_base.rs_rd,
                               1024                 :                :                                                 tuple, scan->rs_cbuf,
                               1025                 :                :                                                 scan->rs_base.rs_snapshot);
                               1026                 :                : 
                               1027                 :                :             /* skip tuples not visible to this snapshot */
                               1028         [ +  + ]:        9450480 :             if (!visible)
                               1029                 :           7312 :                 continue;
                               1030                 :                : 
                               1031                 :                :             /* skip any tuples that don't match the scan key */
                               1032         [ +  + ]:        9443168 :             if (key != NULL &&
                               1033         [ +  + ]:          14908 :                 !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
                               1034                 :                :                              nkeys, key))
                               1035                 :          14194 :                 continue;
                               1036                 :                : 
                               1037                 :        9428974 :             LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                               1038                 :        9428974 :             scan->rs_coffset = lineoff;
                               1039                 :        9428974 :             return;
                               1040                 :                :         }
                               1041                 :                : 
                               1042                 :                :         /*
                               1043                 :                :          * if we get here, it means we've exhausted the items on this page and
                               1044                 :                :          * it's time to move to the next.
                               1045                 :                :          */
 7547 tgl@sss.pgh.pa.us        1046                 :         116138 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                               1047                 :                :     }
                               1048                 :                : 
                               1049                 :                :     /* end of scan */
 1265 drowley@postgresql.o     1050         [ -  + ]:          26570 :     if (BufferIsValid(scan->rs_cbuf))
 1265 drowley@postgresql.o     1051                 :UBC           0 :         ReleaseBuffer(scan->rs_cbuf);
                               1052                 :                : 
 1265 drowley@postgresql.o     1053                 :CBC       26570 :     scan->rs_cbuf = InvalidBuffer;
                               1054                 :          26570 :     scan->rs_cblock = InvalidBlockNumber;
  839 tmunro@postgresql.or     1055                 :          26570 :     scan->rs_prefetch_block = InvalidBlockNumber;
 1265 drowley@postgresql.o     1056                 :          26570 :     tuple->t_data = NULL;
                               1057                 :          26570 :     scan->rs_inited = false;
                               1058                 :                : }
                               1059                 :                : 
                               1060                 :                : /* ----------------
                               1061                 :                :  *      heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
                               1062                 :                :  *
                               1063                 :                :  *      Same API as heapgettup, but used in page-at-a-time mode
                               1064                 :                :  *
                               1065                 :                :  * The internal logic is much the same as heapgettup's too, but there are some
                               1066                 :                :  * differences: we do not take the buffer content lock (that only needs to
                               1067                 :                :  * happen inside heap_prepare_pagescan), and we iterate through just the
                               1068                 :                :  * tuples listed in rs_vistuples[] rather than all tuples on the page.  Notice
                               1069                 :                :  * that lineindex is 0-based, where the corresponding loop variable lineoff in
                               1070                 :                :  * heapgettup is 1-based.
                               1071                 :                :  * ----------------
                               1072                 :                :  */
                               1073                 :                : static void
 7547 tgl@sss.pgh.pa.us        1074                 :       63124713 : heapgettup_pagemode(HeapScanDesc scan,
                               1075                 :                :                     ScanDirection dir,
                               1076                 :                :                     int nkeys,
                               1077                 :                :                     ScanKey key)
                               1078                 :                : {
                               1079                 :       63124713 :     HeapTuple   tuple = &(scan->rs_ctup);
                               1080                 :                :     Page        page;
                               1081                 :                :     uint32      lineindex;
                               1082                 :                :     uint32      linesleft;
                               1083                 :                : 
  843 drowley@postgresql.o     1084         [ +  + ]:       63124713 :     if (likely(scan->rs_inited))
                               1085                 :                :     {
                               1086                 :                :         /* continue from previously returned page/tuple */
 1269                          1087                 :       62071655 :         page = BufferGetPage(scan->rs_cbuf);
                               1088                 :                : 
                               1089                 :       62071655 :         lineindex = scan->rs_cindex + dir;
                               1090         [ +  + ]:       62071655 :         if (ScanDirectionIsForward(dir))
                               1091                 :       62071218 :             linesleft = scan->rs_ntuples - lineindex;
                               1092                 :                :         else
                               1093                 :            437 :             linesleft = scan->rs_cindex;
                               1094                 :                :         /* lineindex now references the next or previous visible tid */
                               1095                 :                : 
 1265                          1096                 :       62071655 :         goto continue_page;
                               1097                 :                :     }
                               1098                 :                : 
                               1099                 :                :     /*
                               1100                 :                :      * advance the scan until we find a qualifying tuple or run out of stuff
                               1101                 :                :      * to scan
                               1102                 :                :      */
                               1103                 :                :     while (true)
                               1104                 :                :     {
  843                          1105                 :        3947782 :         heap_fetch_next_buffer(scan, dir);
                               1106                 :                : 
                               1107                 :                :         /* did we run out of blocks to scan? */
                               1108         [ +  + ]:        3947748 :         if (!BufferIsValid(scan->rs_cbuf))
                               1109                 :         863164 :             break;
                               1110                 :                : 
                               1111         [ -  + ]:        3084584 :         Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
                               1112                 :                : 
                               1113                 :                :         /* prune the page and determine visible tuple offsets */
                               1114                 :        3084584 :         heap_prepare_pagescan((TableScanDesc) scan);
 1265                          1115                 :        3084576 :         page = BufferGetPage(scan->rs_cbuf);
                               1116                 :        3084576 :         linesleft = scan->rs_ntuples;
                               1117         [ +  + ]:        3084576 :         lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
                               1118                 :                : 
                               1119                 :                :         /* block is the same for all tuples, set it once outside the loop */
  481 heikki.linnakangas@i     1120                 :        3084576 :         ItemPointerSetBlockNumber(&tuple->t_self, scan->rs_cblock);
                               1121                 :                : 
                               1122                 :                :         /* lineindex now references the next or previous visible tid */
 1265 drowley@postgresql.o     1123                 :       65156231 : continue_page:
                               1124                 :                : 
                               1125         [ +  + ]:      126039999 :         for (; linesleft > 0; linesleft--, lineindex += dir)
                               1126                 :                :         {
                               1127                 :                :             ItemId      lpp;
                               1128                 :                :             OffsetNumber lineoff;
                               1129                 :                : 
  202 heikki.linnakangas@i     1130         [ -  + ]:      123145275 :             Assert(lineindex < scan->rs_ntuples);
 7547 tgl@sss.pgh.pa.us        1131                 :      123145275 :             lineoff = scan->rs_vistuples[lineindex];
 1348 peter@eisentraut.org     1132                 :      123145275 :             lpp = PageGetItemId(page, lineoff);
 6892 tgl@sss.pgh.pa.us        1133         [ -  + ]:      123145275 :             Assert(ItemIdIsNormal(lpp));
                               1134                 :                : 
 1348 peter@eisentraut.org     1135                 :      123145275 :             tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
 7547 tgl@sss.pgh.pa.us        1136                 :      123145275 :             tuple->t_len = ItemIdGetLength(lpp);
  481 heikki.linnakangas@i     1137                 :      123145275 :             ItemPointerSetOffsetNumber(&tuple->t_self, lineoff);
                               1138                 :                : 
                               1139                 :                :             /* skip any tuples that don't match the scan key */
 1265 drowley@postgresql.o     1140         [ +  + ]:      123145275 :             if (key != NULL &&
                               1141         [ +  + ]:       61267174 :                 !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
                               1142                 :                :                              nkeys, key))
                               1143                 :       60883768 :                 continue;
                               1144                 :                : 
                               1145                 :       62261507 :             scan->rs_cindex = lineindex;
                               1146                 :       62261507 :             return;
                               1147                 :                :         }
                               1148                 :                :     }
                               1149                 :                : 
                               1150                 :                :     /* end of scan */
                               1151         [ -  + ]:         863164 :     if (BufferIsValid(scan->rs_cbuf))
 1265 drowley@postgresql.o     1152                 :UBC           0 :         ReleaseBuffer(scan->rs_cbuf);
 1265 drowley@postgresql.o     1153                 :CBC      863164 :     scan->rs_cbuf = InvalidBuffer;
                               1154                 :         863164 :     scan->rs_cblock = InvalidBlockNumber;
  839 tmunro@postgresql.or     1155                 :         863164 :     scan->rs_prefetch_block = InvalidBlockNumber;
 1265 drowley@postgresql.o     1156                 :         863164 :     tuple->t_data = NULL;
                               1157                 :         863164 :     scan->rs_inited = false;
                               1158                 :                : }
                               1159                 :                : 
                               1160                 :                : 
                               1161                 :                : /* ----------------------------------------------------------------
                               1162                 :                :  *                   heap access method interface
                               1163                 :                :  * ----------------------------------------------------------------
                               1164                 :                :  */
                               1165                 :                : 
                               1166                 :                : 
                               1167                 :                : TableScanDesc
 8833 tgl@sss.pgh.pa.us        1168                 :         471135 : heap_beginscan(Relation relation, Snapshot snapshot,
                               1169                 :                :                int nkeys, ScanKey key,
                               1170                 :                :                ParallelTableScanDesc parallel_scan,
                               1171                 :                :                uint32 flags)
                               1172                 :                : {
                               1173                 :                :     HeapScanDesc scan;
                               1174                 :                : 
                               1175                 :                :     /*
                               1176                 :                :      * increment relation ref count while scanning relation
                               1177                 :                :      *
                               1178                 :                :      * This is just to make really sure the relcache entry won't go away while
                               1179                 :                :      * the scan has a pointer to it.  Caller should be holding the rel open
                               1180                 :                :      * anyway, so this is redundant in all normal scenarios...
                               1181                 :                :      */
 9391                          1182                 :         471135 :     RelationIncrementReferenceCount(relation);
                               1183                 :                : 
                               1184                 :                :     /*
                               1185                 :                :      * allocate and initialize scan descriptor
                               1186                 :                :      */
  556 melanieplageman@gmai     1187         [ +  + ]:         471135 :     if (flags & SO_TYPE_BITMAPSCAN)
                               1188                 :                :     {
  228 michael@paquier.xyz      1189                 :          12539 :         BitmapHeapScanDesc bscan = palloc_object(BitmapHeapScanDescData);
                               1190                 :                : 
                               1191                 :                :         /*
                               1192                 :                :          * Bitmap Heap scans do not have any fields that a normal Heap Scan
                               1193                 :                :          * does not have, so no special initializations required here.
                               1194                 :                :          */
  556 melanieplageman@gmai     1195                 :          12539 :         scan = (HeapScanDesc) bscan;
                               1196                 :                :     }
                               1197                 :                :     else
  228 michael@paquier.xyz      1198                 :         458596 :         scan = (HeapScanDesc) palloc_object(HeapScanDescData);
                               1199                 :                : 
 2694 andres@anarazel.de       1200                 :         471135 :     scan->rs_base.rs_rd = relation;
                               1201                 :         471135 :     scan->rs_base.rs_snapshot = snapshot;
                               1202                 :         471135 :     scan->rs_base.rs_nkeys = nkeys;
 2625                          1203                 :         471135 :     scan->rs_base.rs_flags = flags;
 2694                          1204                 :         471135 :     scan->rs_base.rs_parallel = parallel_scan;
  110 tomas.vondra@postgre     1205                 :         471135 :     scan->rs_base.rs_instrument = NULL;
 2625 andres@anarazel.de       1206                 :         471135 :     scan->rs_strategy = NULL;    /* set in initscan */
  498 melanieplageman@gmai     1207                 :         471135 :     scan->rs_cbuf = InvalidBuffer;
                               1208                 :                : 
                               1209                 :                :     /*
                               1210                 :                :      * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
                               1211                 :                :      */
 2625 andres@anarazel.de       1212   [ +  +  +  + ]:         471135 :     if (!(snapshot && IsMVCCSnapshot(snapshot)))
                               1213                 :          38978 :         scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
                               1214                 :                : 
                               1215                 :                :     /* Check that a historic snapshot is not used for non-catalog tables */
  338 heikki.linnakangas@i     1216         [ +  + ]:         471135 :     if (snapshot &&
                               1217         [ +  + ]:         459591 :         IsHistoricMVCCSnapshot(snapshot) &&
                               1218   [ -  +  -  -  :            714 :         !RelationIsAccessibleInLogicalDecoding(relation))
                                     +  -  -  +  -  
                                     -  -  -  -  +  
                                     -  -  -  -  -  
                                        -  -  -  -  
                                                 - ]
                               1219                 :                :     {
  338 heikki.linnakangas@i     1220         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1221                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               1222                 :                :                  errmsg("cannot query non-catalog table \"%s\" during logical decoding",
                               1223                 :                :                         RelationGetRelationName(relation))));
                               1224                 :                :     }
                               1225                 :                : 
                               1226                 :                :     /*
                               1227                 :                :      * For seqscan and sample scans in a serializable transaction, acquire a
                               1228                 :                :      * predicate lock on the entire relation. This is required not only to
                               1229                 :                :      * lock all the matching tuples, but also to conflict with new insertions
                               1230                 :                :      * into the table. In an indexscan, we take page locks on the index pages
                               1231                 :                :      * covering the range specified in the scan qual, but in a heap scan there
                               1232                 :                :      * is nothing more fine-grained to lock. A bitmap scan is a different
                               1233                 :                :      * story, there we have already scanned the index and locked the index
                               1234                 :                :      * pages covering the predicate. But in that case we still have to lock
                               1235                 :                :      * any matching heap tuples. For sample scan we could optimize the locking
                               1236                 :                :      * to be at least page-level granularity, but we'd need to add per-tuple
                               1237                 :                :      * locking for that.
                               1238                 :                :      */
 2625 andres@anarazel.de       1239         [ +  + ]:CBC      471135 :     if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN))
                               1240                 :                :     {
                               1241                 :                :         /*
                               1242                 :                :          * Ensure a missing snapshot is noticed reliably, even if the
                               1243                 :                :          * isolation mode means predicate locking isn't performed (and
                               1244                 :                :          * therefore the snapshot isn't used here).
                               1245                 :                :          */
                               1246         [ -  + ]:         445255 :         Assert(snapshot);
 5506 heikki.linnakangas@i     1247                 :         445255 :         PredicateLockRelation(relation, snapshot);
                               1248                 :                :     }
                               1249                 :                : 
                               1250                 :                :     /* we only need to set this up once */
 7547 tgl@sss.pgh.pa.us        1251                 :         471135 :     scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
                               1252                 :                : 
                               1253                 :                :     /*
                               1254                 :                :      * Allocate memory to keep track of page allocation for parallel workers
                               1255                 :                :      * when doing a parallel scan.
                               1256                 :                :      */
 1944 drowley@postgresql.o     1257         [ +  + ]:         471135 :     if (parallel_scan != NULL)
  228 michael@paquier.xyz      1258                 :           4526 :         scan->rs_parallelworkerdata = palloc_object(ParallelBlockTableScanWorkerData);
                               1259                 :                :     else
 1944 drowley@postgresql.o     1260                 :         466609 :         scan->rs_parallelworkerdata = NULL;
                               1261                 :                : 
                               1262                 :                :     /*
                               1263                 :                :      * we do this here instead of in initscan() because heap_rescan also calls
                               1264                 :                :      * initscan() and we don't want to allocate memory again
                               1265                 :                :      */
 8833 tgl@sss.pgh.pa.us        1266         [ +  + ]:         471135 :     if (nkeys > 0)
  228 michael@paquier.xyz      1267                 :         264155 :         scan->rs_base.rs_key = palloc_array(ScanKeyData, nkeys);
                               1268                 :                :     else
 2694 andres@anarazel.de       1269                 :         206980 :         scan->rs_base.rs_key = NULL;
                               1270                 :                : 
 6255 tgl@sss.pgh.pa.us        1271                 :         471135 :     initscan(scan, key, false);
                               1272                 :                : 
  839 tmunro@postgresql.or     1273                 :         471133 :     scan->rs_read_stream = NULL;
                               1274                 :                : 
                               1275                 :                :     /*
                               1276                 :                :      * Set up a read stream for sequential scans and TID range scans. This
                               1277                 :                :      * should be done after initscan() because initscan() allocates the
                               1278                 :                :      * BufferAccessStrategy object passed to the read stream API.
                               1279                 :                :      */
                               1280         [ +  + ]:         471133 :     if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
                               1281         [ +  + ]:          25974 :         scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
                               1282                 :         446468 :     {
                               1283                 :                :         ReadStreamBlockNumberCB cb;
                               1284                 :                : 
                               1285         [ +  + ]:         446473 :         if (scan->rs_base.rs_parallel)
                               1286                 :           4526 :             cb = heap_scan_stream_read_next_parallel;
                               1287                 :                :         else
                               1288                 :         441947 :             cb = heap_scan_stream_read_next_serial;
                               1289                 :                : 
                               1290                 :                :         /* ---
                               1291                 :                :          * It is safe to use batchmode as the only locks taken by `cb`
                               1292                 :                :          * are never taken while waiting for IO:
                               1293                 :                :          * - SyncScanLock is used in the non-parallel case
                               1294                 :                :          * - in the parallel case, only spinlocks and atomics are used
                               1295                 :                :          * ---
                               1296                 :                :          */
  483 andres@anarazel.de       1297                 :         446473 :         scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_SEQUENTIAL |
                               1298                 :                :                                                           READ_STREAM_USE_BATCHING,
                               1299                 :                :                                                           scan->rs_strategy,
                               1300                 :                :                                                           scan->rs_base.rs_rd,
                               1301                 :                :                                                           MAIN_FORKNUM,
                               1302                 :                :                                                           cb,
                               1303                 :                :                                                           scan,
                               1304                 :                :                                                           0);
                               1305                 :                :     }
  498 melanieplageman@gmai     1306         [ +  + ]:          24660 :     else if (scan->rs_base.rs_flags & SO_TYPE_BITMAPSCAN)
                               1307                 :                :     {
  479                          1308                 :          12539 :         scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_DEFAULT |
                               1309                 :                :                                                           READ_STREAM_USE_BATCHING,
                               1310                 :                :                                                           scan->rs_strategy,
                               1311                 :                :                                                           scan->rs_base.rs_rd,
                               1312                 :                :                                                           MAIN_FORKNUM,
                               1313                 :                :                                                           bitmapheap_stream_read_next,
                               1314                 :                :                                                           scan,
                               1315                 :                :                                                           sizeof(TBMIterateResult));
                               1316                 :                :     }
                               1317                 :                : 
                               1318                 :                :     /* enable read stream instrumentation */
  110 tomas.vondra@postgre     1319   [ +  +  +  - ]:         471128 :     if ((flags & SO_SCAN_INSTRUMENT) && (scan->rs_read_stream != NULL))
                               1320                 :                :     {
                               1321                 :              8 :         scan->rs_base.rs_instrument = palloc0_object(TableScanInstrumentation);
                               1322                 :              8 :         read_stream_enable_stats(scan->rs_read_stream,
                               1323                 :              8 :                                  &scan->rs_base.rs_instrument->io);
                               1324                 :                :     }
                               1325                 :                : 
  133 melanieplageman@gmai     1326                 :         471128 :     scan->rs_vmbuffer = InvalidBuffer;
                               1327                 :                : 
 2694 andres@anarazel.de       1328                 :         471128 :     return (TableScanDesc) scan;
                               1329                 :                : }
                               1330                 :                : 
                               1331                 :                : void
                               1332                 :         638264 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
                               1333                 :                :             bool allow_strat, bool allow_sync, bool allow_pagemode)
                               1334                 :                : {
                               1335                 :         638264 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1336                 :                : 
                               1337         [ +  + ]:         638264 :     if (set_params)
                               1338                 :                :     {
 2625                          1339         [ +  - ]:             19 :         if (allow_strat)
                               1340                 :             19 :             scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
                               1341                 :                :         else
 2625 andres@anarazel.de       1342                 :UBC           0 :             scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
                               1343                 :                : 
 2625 andres@anarazel.de       1344         [ +  + ]:CBC          19 :         if (allow_sync)
                               1345                 :              8 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                               1346                 :                :         else
                               1347                 :             11 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                               1348                 :                : 
                               1349   [ +  -  +  - ]:             19 :         if (allow_pagemode && scan->rs_base.rs_snapshot &&
                               1350         [ +  - ]:             19 :             IsMVCCSnapshot(scan->rs_base.rs_snapshot))
                               1351                 :             19 :             scan->rs_base.rs_flags |= SO_ALLOW_PAGEMODE;
                               1352                 :                :         else
 2625 andres@anarazel.de       1353                 :UBC           0 :             scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
                               1354                 :                :     }
                               1355                 :                : 
                               1356                 :                :     /*
                               1357                 :                :      * unpin scan buffers
                               1358                 :                :      */
 9178 tgl@sss.pgh.pa.us        1359         [ +  + ]:CBC      638264 :     if (BufferIsValid(scan->rs_cbuf))
                               1360                 :                :     {
                               1361                 :           3066 :         ReleaseBuffer(scan->rs_cbuf);
  498 melanieplageman@gmai     1362                 :           3066 :         scan->rs_cbuf = InvalidBuffer;
                               1363                 :                :     }
                               1364                 :                : 
  133                          1365         [ +  + ]:         638264 :     if (BufferIsValid(scan->rs_vmbuffer))
                               1366                 :                :     {
                               1367                 :             15 :         ReleaseBuffer(scan->rs_vmbuffer);
                               1368                 :             15 :         scan->rs_vmbuffer = InvalidBuffer;
                               1369                 :                :     }
                               1370                 :                : 
                               1371                 :                :     /*
                               1372                 :                :      * SO_TYPE_BITMAPSCAN would be cleaned up here, but it does not hold any
                               1373                 :                :      * additional data vs a normal HeapScan
                               1374                 :                :      */
                               1375                 :                : 
                               1376                 :                :     /*
                               1377                 :                :      * The read stream is reset on rescan. This must be done before
                               1378                 :                :      * initscan(), as some state referred to by read_stream_reset() is reset
                               1379                 :                :      * in initscan().
                               1380                 :                :      */
  839 tmunro@postgresql.or     1381         [ +  + ]:         638264 :     if (scan->rs_read_stream)
                               1382                 :         638241 :         read_stream_reset(scan->rs_read_stream);
                               1383                 :                : 
                               1384                 :                :     /*
                               1385                 :                :      * reinitialize scan descriptor
                               1386                 :                :      */
 6255 tgl@sss.pgh.pa.us        1387                 :         638264 :     initscan(scan, key, true);
10974 scrappy@hub.org          1388                 :         638264 : }
                               1389                 :                : 
                               1390                 :                : void
 2694 andres@anarazel.de       1391                 :         467820 : heap_endscan(TableScanDesc sscan)
                               1392                 :                : {
                               1393                 :         467820 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1394                 :                : 
                               1395                 :                :     /* Note: no locking manipulations needed */
                               1396                 :                : 
                               1397                 :                :     /*
                               1398                 :                :      * unpin scan buffers
                               1399                 :                :      */
 9178 tgl@sss.pgh.pa.us        1400         [ +  + ]:         467820 :     if (BufferIsValid(scan->rs_cbuf))
                               1401                 :         185343 :         ReleaseBuffer(scan->rs_cbuf);
                               1402                 :                : 
  133 melanieplageman@gmai     1403         [ +  + ]:         467820 :     if (BufferIsValid(scan->rs_vmbuffer))
                               1404                 :           2757 :         ReleaseBuffer(scan->rs_vmbuffer);
                               1405                 :                : 
                               1406                 :                :     /*
                               1407                 :                :      * Must free the read stream before freeing the BufferAccessStrategy.
                               1408                 :                :      */
  839 tmunro@postgresql.or     1409         [ +  + ]:         467820 :     if (scan->rs_read_stream)
                               1410                 :         455766 :         read_stream_end(scan->rs_read_stream);
                               1411                 :                : 
                               1412                 :                :     /*
                               1413                 :                :      * decrement relation reference count and free scan descriptor storage
                               1414                 :                :      */
 2694 andres@anarazel.de       1415                 :         467820 :     RelationDecrementReferenceCount(scan->rs_base.rs_rd);
                               1416                 :                : 
                               1417         [ +  + ]:         467820 :     if (scan->rs_base.rs_key)
                               1418                 :         264106 :         pfree(scan->rs_base.rs_key);
                               1419                 :                : 
 6997 tgl@sss.pgh.pa.us        1420         [ +  + ]:         467820 :     if (scan->rs_strategy != NULL)
                               1421                 :          14225 :         FreeAccessStrategy(scan->rs_strategy);
                               1422                 :                : 
 1944 drowley@postgresql.o     1423         [ +  + ]:         467820 :     if (scan->rs_parallelworkerdata != NULL)
                               1424                 :           4526 :         pfree(scan->rs_parallelworkerdata);
                               1425                 :                : 
 2625 andres@anarazel.de       1426         [ +  + ]:         467820 :     if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
 2694                          1427                 :          46532 :         UnregisterSnapshot(scan->rs_base.rs_snapshot);
                               1428                 :                : 
  110 tomas.vondra@postgre     1429         [ +  + ]:         467820 :     if (scan->rs_base.rs_instrument)
                               1430                 :              8 :         pfree(scan->rs_base.rs_instrument);
                               1431                 :                : 
 9808 tgl@sss.pgh.pa.us        1432                 :         467820 :     pfree(scan);
10974 scrappy@hub.org          1433                 :         467820 : }
                               1434                 :                : 
                               1435                 :                : HeapTuple
 2694 andres@anarazel.de       1436                 :       11823276 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
                               1437                 :                : {
                               1438                 :       11823276 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1439                 :                : 
                               1440                 :                :     /*
                               1441                 :                :      * This is still widely used directly, without going through table AM, so
                               1442                 :                :      * add a safety check.  It's possible we should, at a later point,
                               1443                 :                :      * downgrade this to an assert. The reason for checking the AM routine,
                               1444                 :                :      * rather than the AM oid, is that this allows to write regression tests
                               1445                 :                :      * that create another AM reusing the heap handler.
                               1446                 :                :      */
                               1447         [ -  + ]:       11823276 :     if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
 2694 andres@anarazel.de       1448         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1449                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1450                 :                :                  errmsg_internal("only heap AM is supported")));
                               1451                 :                : 
                               1452                 :                :     /* Note: no locking manipulations needed */
                               1453                 :                : 
 2625 andres@anarazel.de       1454         [ +  + ]:CBC    11823276 :     if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
 7460 neilc@samurai.com        1455                 :        2969019 :         heapgettup_pagemode(scan, direction,
 2694 andres@anarazel.de       1456                 :        2969019 :                             scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
                               1457                 :                :     else
                               1458                 :        8854257 :         heapgettup(scan, direction,
                               1459                 :        8854257 :                    scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
                               1460                 :                : 
 7547 tgl@sss.pgh.pa.us        1461         [ +  + ]:       11823275 :     if (scan->rs_ctup.t_data == NULL)
 8833                          1462                 :          78079 :         return NULL;
                               1463                 :                : 
                               1464                 :                :     /*
                               1465                 :                :      * if we get here it means we have a new current scan tuple, so point to
                               1466                 :                :      * the proper return buffer and return the tuple.
                               1467                 :                :      */
                               1468                 :                : 
 2694 andres@anarazel.de       1469   [ -  +  -  -  :       11745196 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
                                              +  - ]
                               1470                 :                : 
                               1471                 :       11745196 :     return &scan->rs_ctup;
                               1472                 :                : }
                               1473                 :                : 
                               1474                 :                : bool
                               1475                 :       60750345 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
                               1476                 :                : {
                               1477                 :       60750345 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1478                 :                : 
                               1479                 :                :     /* Note: no locking manipulations needed */
                               1480                 :                : 
 2625                          1481         [ +  + ]:       60750345 :     if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
                               1482                 :       60149058 :         heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1483                 :                :     else
                               1484                 :         601287 :         heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1485                 :                : 
 2694                          1486         [ +  + ]:       60750314 :     if (scan->rs_ctup.t_data == NULL)
                               1487                 :                :     {
                               1488                 :         811517 :         ExecClearTuple(slot);
                               1489                 :         811517 :         return false;
                               1490                 :                :     }
                               1491                 :                : 
                               1492                 :                :     /*
                               1493                 :                :      * if we get here it means we have a new current scan tuple, so point to
                               1494                 :                :      * the proper return buffer and return the tuple.
                               1495                 :                :      */
                               1496                 :                : 
                               1497   [ +  +  -  +  :       59938797 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
                                              +  + ]
                               1498                 :                : 
                               1499                 :       59938797 :     ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
                               1500                 :                :                              scan->rs_cbuf);
                               1501                 :       59938797 :     return true;
                               1502                 :                : }
                               1503                 :                : 
                               1504                 :                : void
 1975 drowley@postgresql.o     1505                 :           1374 : heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
                               1506                 :                :                   ItemPointer maxtid)
                               1507                 :                : {
                               1508                 :           1374 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1509                 :                :     BlockNumber startBlk;
                               1510                 :                :     BlockNumber numBlks;
                               1511                 :                :     ItemPointerData highestItem;
                               1512                 :                :     ItemPointerData lowestItem;
                               1513                 :                : 
                               1514                 :                :     /*
                               1515                 :                :      * For relations without any pages, we can simply leave the TID range
                               1516                 :                :      * unset.  There will be no tuples to scan, therefore no tuples outside
                               1517                 :                :      * the given TID range.
                               1518                 :                :      */
                               1519         [ +  + ]:           1374 :     if (scan->rs_nblocks == 0)
                               1520                 :             32 :         return;
                               1521                 :                : 
                               1522                 :                :     /*
                               1523                 :                :      * Set up some ItemPointers which point to the first and last possible
                               1524                 :                :      * tuples in the heap.
                               1525                 :                :      */
                               1526                 :           1366 :     ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
                               1527                 :           1366 :     ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
                               1528                 :                : 
                               1529                 :                :     /*
                               1530                 :                :      * If the given maximum TID is below the highest possible TID in the
                               1531                 :                :      * relation, then restrict the range to that, otherwise we scan to the end
                               1532                 :                :      * of the relation.
                               1533                 :                :      */
                               1534         [ +  + ]:           1366 :     if (ItemPointerCompare(maxtid, &highestItem) < 0)
                               1535                 :            172 :         ItemPointerCopy(maxtid, &highestItem);
                               1536                 :                : 
                               1537                 :                :     /*
                               1538                 :                :      * If the given minimum TID is above the lowest possible TID in the
                               1539                 :                :      * relation, then restrict the range to only scan for TIDs above that.
                               1540                 :                :      */
                               1541         [ +  + ]:           1366 :     if (ItemPointerCompare(mintid, &lowestItem) > 0)
                               1542                 :           1210 :         ItemPointerCopy(mintid, &lowestItem);
                               1543                 :                : 
                               1544                 :                :     /*
                               1545                 :                :      * Check for an empty range and protect from would be negative results
                               1546                 :                :      * from the numBlks calculation below.
                               1547                 :                :      */
                               1548         [ +  + ]:           1366 :     if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
                               1549                 :                :     {
                               1550                 :                :         /* Set an empty range of blocks to scan */
                               1551                 :             24 :         heap_setscanlimits(sscan, 0, 0);
                               1552                 :             24 :         return;
                               1553                 :                :     }
                               1554                 :                : 
                               1555                 :                :     /*
                               1556                 :                :      * Calculate the first block and the number of blocks we must scan. We
                               1557                 :                :      * could be more aggressive here and perform some more validation to try
                               1558                 :                :      * and further narrow the scope of blocks to scan by checking if the
                               1559                 :                :      * lowestItem has an offset above MaxOffsetNumber.  In this case, we could
                               1560                 :                :      * advance startBlk by one.  Likewise, if highestItem has an offset of 0
                               1561                 :                :      * we could scan one fewer blocks.  However, such an optimization does not
                               1562                 :                :      * seem worth troubling over, currently.
                               1563                 :                :      */
                               1564                 :           1342 :     startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
                               1565                 :                : 
                               1566                 :           1342 :     numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
                               1567                 :           1342 :         ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
                               1568                 :                : 
                               1569                 :                :     /* Set the start block and number of blocks to scan */
                               1570                 :           1342 :     heap_setscanlimits(sscan, startBlk, numBlks);
                               1571                 :                : 
                               1572                 :                :     /* Finally, set the TID range in sscan */
  639 melanieplageman@gmai     1573                 :           1342 :     ItemPointerCopy(&lowestItem, &sscan->st.tidrange.rs_mintid);
                               1574                 :           1342 :     ItemPointerCopy(&highestItem, &sscan->st.tidrange.rs_maxtid);
                               1575                 :                : }
                               1576                 :                : 
                               1577                 :                : bool
 1975 drowley@postgresql.o     1578                 :           6512 : heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
                               1579                 :                :                           TupleTableSlot *slot)
                               1580                 :                : {
                               1581                 :           6512 :     HeapScanDesc scan = (HeapScanDesc) sscan;
  639 melanieplageman@gmai     1582                 :           6512 :     ItemPointer mintid = &sscan->st.tidrange.rs_mintid;
                               1583                 :           6512 :     ItemPointer maxtid = &sscan->st.tidrange.rs_maxtid;
                               1584                 :                : 
                               1585                 :                :     /* Note: no locking manipulations needed */
                               1586                 :                :     for (;;)
                               1587                 :                :     {
 1975 drowley@postgresql.o     1588         [ +  - ]:           6636 :         if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
                               1589                 :           6636 :             heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1590                 :                :         else
 1975 drowley@postgresql.o     1591                 :UBC           0 :             heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1592                 :                : 
 1975 drowley@postgresql.o     1593         [ +  + ]:CBC        6626 :         if (scan->rs_ctup.t_data == NULL)
                               1594                 :                :         {
                               1595                 :            138 :             ExecClearTuple(slot);
                               1596                 :            138 :             return false;
                               1597                 :                :         }
                               1598                 :                : 
                               1599                 :                :         /*
                               1600                 :                :          * heap_set_tidrange will have used heap_setscanlimits to limit the
                               1601                 :                :          * range of pages we scan to only ones that can contain the TID range
                               1602                 :                :          * we're scanning for.  Here we must filter out any tuples from these
                               1603                 :                :          * pages that are outside of that range.
                               1604                 :                :          */
                               1605         [ +  + ]:           6488 :         if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
                               1606                 :                :         {
                               1607                 :            124 :             ExecClearTuple(slot);
                               1608                 :                : 
                               1609                 :                :             /*
                               1610                 :                :              * When scanning backwards, the TIDs will be in descending order.
                               1611                 :                :              * Future tuples in this direction will be lower still, so we can
                               1612                 :                :              * just return false to indicate there will be no more tuples.
                               1613                 :                :              */
                               1614         [ -  + ]:            124 :             if (ScanDirectionIsBackward(direction))
 1975 drowley@postgresql.o     1615                 :UBC           0 :                 return false;
                               1616                 :                : 
 1975 drowley@postgresql.o     1617                 :CBC         124 :             continue;
                               1618                 :                :         }
                               1619                 :                : 
                               1620                 :                :         /*
                               1621                 :                :          * Likewise for the final page, we must filter out TIDs greater than
                               1622                 :                :          * maxtid.
                               1623                 :                :          */
                               1624         [ +  + ]:           6364 :         if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
                               1625                 :                :         {
                               1626                 :             74 :             ExecClearTuple(slot);
                               1627                 :                : 
                               1628                 :                :             /*
                               1629                 :                :              * When scanning forward, the TIDs will be in ascending order.
                               1630                 :                :              * Future tuples in this direction will be higher still, so we can
                               1631                 :                :              * just return false to indicate there will be no more tuples.
                               1632                 :                :              */
                               1633         [ +  - ]:             74 :             if (ScanDirectionIsForward(direction))
                               1634                 :             74 :                 return false;
 1975 drowley@postgresql.o     1635                 :UBC           0 :             continue;
                               1636                 :                :         }
                               1637                 :                : 
 1975 drowley@postgresql.o     1638                 :CBC        6290 :         break;
                               1639                 :                :     }
                               1640                 :                : 
                               1641                 :                :     /*
                               1642                 :                :      * if we get here it means we have a new current scan tuple, so point to
                               1643                 :                :      * the proper return buffer and return the tuple.
                               1644                 :                :      */
                               1645   [ -  +  -  -  :           6290 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
                                              +  - ]
                               1646                 :                : 
                               1647                 :           6290 :     ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
                               1648                 :           6290 :     return true;
                               1649                 :                : }
                               1650                 :                : 
                               1651                 :                : /*
                               1652                 :                :  *  heap_fetch      - retrieve tuple with given tid
                               1653                 :                :  *
                               1654                 :                :  * On entry, tuple->t_self is the TID to fetch.  We pin the buffer holding
                               1655                 :                :  * the tuple, fill in the remaining fields of *tuple, and check the tuple
                               1656                 :                :  * against the specified snapshot.
                               1657                 :                :  *
                               1658                 :                :  * If successful (tuple found and passes snapshot time qual), then *userbuf
                               1659                 :                :  * is set to the buffer holding the tuple and true is returned.  The caller
                               1660                 :                :  * must unpin the buffer when done with the tuple.
                               1661                 :                :  *
                               1662                 :                :  * If the tuple is not found (ie, item number references a deleted slot),
                               1663                 :                :  * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
                               1664                 :                :  * and false is returned.
                               1665                 :                :  *
                               1666                 :                :  * If the tuple is found but fails the time qual check, then the behavior
                               1667                 :                :  * depends on the keep_buf parameter.  If keep_buf is false, the results
                               1668                 :                :  * are the same as for the tuple-not-found case.  If keep_buf is true,
                               1669                 :                :  * then tuple->t_data and *userbuf are returned as for the success case,
                               1670                 :                :  * and again the caller must unpin the buffer; but false is returned.
                               1671                 :                :  *
                               1672                 :                :  * heap_fetch does not follow HOT chains: only the exact TID requested will
                               1673                 :                :  * be fetched.
                               1674                 :                :  *
                               1675                 :                :  * It is somewhat inconsistent that we ereport() on invalid block number but
                               1676                 :                :  * return false on invalid item number.  There are a couple of reasons though.
                               1677                 :                :  * One is that the caller can relatively easily check the block number for
                               1678                 :                :  * validity, but cannot check the item number without reading the page
                               1679                 :                :  * himself.  Another is that when we are following a t_ctid link, we can be
                               1680                 :                :  * reasonably confident that the page number is valid (since VACUUM shouldn't
                               1681                 :                :  * truncate off the destination page without having killed the referencing
                               1682                 :                :  * tuple first), but the item number might well not be good.
                               1683                 :                :  */
                               1684                 :                : bool
10974 scrappy@hub.org          1685                 :        2841751 : heap_fetch(Relation relation,
                               1686                 :                :            Snapshot snapshot,
                               1687                 :                :            HeapTuple tuple,
                               1688                 :                :            Buffer *userbuf,
                               1689                 :                :            bool keep_buf)
                               1690                 :                : {
 8829 tgl@sss.pgh.pa.us        1691                 :        2841751 :     ItemPointer tid = &(tuple->t_self);
                               1692                 :                :     ItemId      lp;
                               1693                 :                :     Buffer      buffer;
                               1694                 :                :     Page        page;
                               1695                 :                :     OffsetNumber offnum;
                               1696                 :                :     bool        valid;
                               1697                 :                : 
                               1698                 :                :     /*
                               1699                 :                :      * Fetch and pin the appropriate page of the relation.
                               1700                 :                :      */
 6688                          1701                 :        2841751 :     buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
                               1702                 :                : 
                               1703                 :                :     /*
                               1704                 :                :      * Need share lock on buffer to examine tuple commit status.
                               1705                 :                :      */
10085 vadim4o@yahoo.com        1706                 :        2841743 :     LockBuffer(buffer, BUFFER_LOCK_SHARE);
 3749 kgrittn@postgresql.o     1707                 :        2841743 :     page = BufferGetPage(buffer);
                               1708                 :                : 
                               1709                 :                :     /*
                               1710                 :                :      * We'd better check for out-of-range offnum in case of VACUUM since the
                               1711                 :                :      * TID was obtained.
                               1712                 :                :      */
10549 bruce@momjian.us         1713                 :        2841743 :     offnum = ItemPointerGetOffsetNumber(tid);
 6587 tgl@sss.pgh.pa.us        1714   [ +  -  +  + ]:        2841743 :     if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
                               1715                 :                :     {
  121 andres@anarazel.de       1716                 :              4 :         UnlockReleaseBuffer(buffer);
 2682                          1717                 :              4 :         *userbuf = InvalidBuffer;
 7791 tgl@sss.pgh.pa.us        1718                 :              4 :         tuple->t_data = NULL;
                               1719                 :              4 :         return false;
                               1720                 :                :     }
                               1721                 :                : 
                               1722                 :                :     /*
                               1723                 :                :      * get the item line pointer corresponding to the requested tid
                               1724                 :                :      */
 6587                          1725                 :        2841739 :     lp = PageGetItemId(page, offnum);
                               1726                 :                : 
                               1727                 :                :     /*
                               1728                 :                :      * Must check for deleted tuple.
                               1729                 :                :      */
 6892                          1730         [ +  + ]:        2841739 :     if (!ItemIdIsNormal(lp))
                               1731                 :                :     {
  121 andres@anarazel.de       1732                 :            293 :         UnlockReleaseBuffer(buffer);
 2682                          1733                 :            293 :         *userbuf = InvalidBuffer;
 8829 tgl@sss.pgh.pa.us        1734                 :            293 :         tuple->t_data = NULL;
                               1735                 :            293 :         return false;
                               1736                 :                :     }
                               1737                 :                : 
                               1738                 :                :     /*
                               1739                 :                :      * fill in *tuple fields
                               1740                 :                :      */
 6587                          1741                 :        2841446 :     tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
10103 vadim4o@yahoo.com        1742                 :        2841446 :     tuple->t_len = ItemIdGetLength(lp);
 7645 tgl@sss.pgh.pa.us        1743                 :        2841446 :     tuple->t_tableOid = RelationGetRelid(relation);
                               1744                 :                : 
                               1745                 :                :     /*
                               1746                 :                :      * check tuple visibility, then release lock
                               1747                 :                :      */
 7547                          1748                 :        2841446 :     valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
                               1749                 :                : 
 5648 heikki.linnakangas@i     1750         [ +  + ]:        2841446 :     if (valid)
 2371 tmunro@postgresql.or     1751                 :        2841384 :         PredicateLockTID(relation, &(tuple->t_self), snapshot,
                               1752                 :        2841384 :                          HeapTupleHeaderGetXmin(tuple->t_data));
                               1753                 :                : 
                               1754                 :        2841446 :     HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
                               1755                 :                : 
 5623 heikki.linnakangas@i     1756                 :        2841446 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               1757                 :                : 
 8829 tgl@sss.pgh.pa.us        1758         [ +  + ]:        2841446 :     if (valid)
                               1759                 :                :     {
                               1760                 :                :         /*
                               1761                 :                :          * All checks passed, so return the tuple as valid. Caller is now
                               1762                 :                :          * responsible for releasing the buffer.
                               1763                 :                :          */
 9802                          1764                 :        2841384 :         *userbuf = buffer;
                               1765                 :                : 
 8829                          1766                 :        2841384 :         return true;
                               1767                 :                :     }
                               1768                 :                : 
                               1769                 :                :     /* Tuple failed time qual, but maybe caller wants to see it anyway. */
 1565                          1770         [ +  + ]:             62 :     if (keep_buf)
                               1771                 :             38 :         *userbuf = buffer;
                               1772                 :                :     else
                               1773                 :                :     {
                               1774                 :             24 :         ReleaseBuffer(buffer);
                               1775                 :             24 :         *userbuf = InvalidBuffer;
                               1776                 :             24 :         tuple->t_data = NULL;
                               1777                 :                :     }
                               1778                 :                : 
 8829                          1779                 :             62 :     return false;
                               1780                 :                : }
                               1781                 :                : 
                               1782                 :                : /*
                               1783                 :                :  *  heap_get_latest_tid -  get the latest tid of a specified tuple
                               1784                 :                :  *
                               1785                 :                :  * Actually, this gets the latest version that is visible according to the
                               1786                 :                :  * scan's snapshot.  Create a scan using SnapshotDirty to get the very latest,
                               1787                 :                :  * possibly uncommitted version.
                               1788                 :                :  *
                               1789                 :                :  * *tid is both an input and an output parameter: it is updated to
                               1790                 :                :  * show the latest version of the row.  Note that it will not be changed
                               1791                 :                :  * if no version of the row passes the snapshot test.
                               1792                 :                :  */
                               1793                 :                : void
 2627 andres@anarazel.de       1794                 :            207 : heap_get_latest_tid(TableScanDesc sscan,
                               1795                 :                :                     ItemPointer tid)
                               1796                 :                : {
 2622 tgl@sss.pgh.pa.us        1797                 :            207 :     Relation    relation = sscan->rs_rd;
                               1798                 :            207 :     Snapshot    snapshot = sscan->rs_snapshot;
                               1799                 :                :     ItemPointerData ctid;
                               1800                 :                :     TransactionId priorXmax;
                               1801                 :                : 
                               1802                 :                :     /*
                               1803                 :                :      * table_tuple_get_latest_tid() verified that the passed in tid is valid.
                               1804                 :                :      * Assume that t_ctid links are valid however - there shouldn't be invalid
                               1805                 :                :      * ones in the table.
                               1806                 :                :      */
 2627 andres@anarazel.de       1807         [ -  + ]:            207 :     Assert(ItemPointerIsValid(tid));
                               1808                 :                : 
                               1809                 :                :     /*
                               1810                 :                :      * Loop to chase down t_ctid links.  At top of loop, ctid is the tuple we
                               1811                 :                :      * need to examine, and *tid is the TID we will return if ctid turns out
                               1812                 :                :      * to be bogus.
                               1813                 :                :      *
                               1814                 :                :      * Note that we will loop until we reach the end of the t_ctid chain.
                               1815                 :                :      * Depending on the snapshot passed, there might be at most one visible
                               1816                 :                :      * version of the row, but we don't try to optimize for that.
                               1817                 :                :      */
 7645 tgl@sss.pgh.pa.us        1818                 :            207 :     ctid = *tid;
                               1819                 :            207 :     priorXmax = InvalidTransactionId;   /* cannot check first XMIN */
                               1820                 :                :     for (;;)
                               1821                 :             64 :     {
                               1822                 :                :         Buffer      buffer;
                               1823                 :                :         Page        page;
                               1824                 :                :         OffsetNumber offnum;
                               1825                 :                :         ItemId      lp;
                               1826                 :                :         HeapTupleData tp;
                               1827                 :                :         bool        valid;
                               1828                 :                : 
                               1829                 :                :         /*
                               1830                 :                :          * Read, pin, and lock the page.
                               1831                 :                :          */
                               1832                 :            271 :         buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
                               1833                 :            271 :         LockBuffer(buffer, BUFFER_LOCK_SHARE);
 3749 kgrittn@postgresql.o     1834                 :            271 :         page = BufferGetPage(buffer);
                               1835                 :                : 
                               1836                 :                :         /*
                               1837                 :                :          * Check for bogus item number.  This is not treated as an error
                               1838                 :                :          * condition because it can happen while following a t_ctid link. We
                               1839                 :                :          * just assume that the prior tid is OK and return it unchanged.
                               1840                 :                :          */
 7645 tgl@sss.pgh.pa.us        1841                 :            271 :         offnum = ItemPointerGetOffsetNumber(&ctid);
 6587                          1842   [ +  -  -  + ]:            271 :         if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
                               1843                 :                :         {
 7422 tgl@sss.pgh.pa.us        1844                 :UBC           0 :             UnlockReleaseBuffer(buffer);
 7645                          1845                 :              0 :             break;
                               1846                 :                :         }
 6587 tgl@sss.pgh.pa.us        1847                 :CBC         271 :         lp = PageGetItemId(page, offnum);
 6892                          1848         [ -  + ]:            271 :         if (!ItemIdIsNormal(lp))
                               1849                 :                :         {
 7422 tgl@sss.pgh.pa.us        1850                 :UBC           0 :             UnlockReleaseBuffer(buffer);
 7645                          1851                 :              0 :             break;
                               1852                 :                :         }
                               1853                 :                : 
                               1854                 :                :         /* OK to access the tuple */
 7645 tgl@sss.pgh.pa.us        1855                 :CBC         271 :         tp.t_self = ctid;
 6587                          1856                 :            271 :         tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
 7645                          1857                 :            271 :         tp.t_len = ItemIdGetLength(lp);
 4752 rhaas@postgresql.org     1858                 :            271 :         tp.t_tableOid = RelationGetRelid(relation);
                               1859                 :                : 
                               1860                 :                :         /*
                               1861                 :                :          * After following a t_ctid link, we might arrive at an unrelated
                               1862                 :                :          * tuple.  Check for XMIN match.
                               1863                 :                :          */
 7645 tgl@sss.pgh.pa.us        1864   [ +  +  -  + ]:            335 :         if (TransactionIdIsValid(priorXmax) &&
 3188 alvherre@alvh.no-ip.     1865                 :             64 :             !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
                               1866                 :                :         {
 7422 tgl@sss.pgh.pa.us        1867                 :UBC           0 :             UnlockReleaseBuffer(buffer);
 7645                          1868                 :              0 :             break;
                               1869                 :                :         }
                               1870                 :                : 
                               1871                 :                :         /*
                               1872                 :                :          * Check tuple visibility; if visible, set it as the new result
                               1873                 :                :          * candidate.
                               1874                 :                :          */
 7547 tgl@sss.pgh.pa.us        1875                 :CBC         271 :         valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
 2371 tmunro@postgresql.or     1876                 :            271 :         HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
 7645 tgl@sss.pgh.pa.us        1877         [ +  + ]:            271 :         if (valid)
                               1878                 :            191 :             *tid = ctid;
                               1879                 :                : 
                               1880                 :                :         /*
                               1881                 :                :          * If there's a valid t_ctid link, follow it, else we're done.
                               1882                 :                :          */
 4932 alvherre@alvh.no-ip.     1883   [ +  +  +  + ]:            391 :         if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
                               1884         [ +  - ]:            200 :             HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
 3032 andres@anarazel.de       1885         [ +  + ]:            160 :             HeapTupleHeaderIndicatesMovedPartitions(tp.t_data) ||
 7645 tgl@sss.pgh.pa.us        1886                 :             80 :             ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
                               1887                 :                :         {
 7422                          1888                 :            207 :             UnlockReleaseBuffer(buffer);
 7645                          1889                 :            207 :             break;
                               1890                 :                :         }
                               1891                 :                : 
                               1892                 :             64 :         ctid = tp.t_data->t_ctid;
 4932 alvherre@alvh.no-ip.     1893                 :             64 :         priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
 7422 tgl@sss.pgh.pa.us        1894                 :             64 :         UnlockReleaseBuffer(buffer);
                               1895                 :                :     }                           /* end of loop */
 9785 inoue@tpf.co.jp          1896                 :            207 : }
                               1897                 :                : 
                               1898                 :                : 
                               1899                 :                : /*
                               1900                 :                :  * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
                               1901                 :                :  *
                               1902                 :                :  * This is called after we have waited for the XMAX transaction to terminate.
                               1903                 :                :  * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
                               1904                 :                :  * be set on exit.  If the transaction committed, we set the XMAX_COMMITTED
                               1905                 :                :  * hint bit if possible --- but beware that that may not yet be possible,
                               1906                 :                :  * if the transaction committed asynchronously.
                               1907                 :                :  *
                               1908                 :                :  * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
                               1909                 :                :  * even if it commits.
                               1910                 :                :  *
                               1911                 :                :  * Hence callers should look only at XMAX_INVALID.
                               1912                 :                :  *
                               1913                 :                :  * Note this is not allowed for tuples whose xmax is a multixact.
                               1914                 :                :  */
                               1915                 :                : static void
 6921 tgl@sss.pgh.pa.us        1916                 :            281 : UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
                               1917                 :                : {
 4932 alvherre@alvh.no-ip.     1918         [ -  + ]:            281 :     Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
                               1919         [ -  + ]:            281 :     Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
                               1920                 :                : 
 6921 tgl@sss.pgh.pa.us        1921         [ +  + ]:            281 :     if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
                               1922                 :                :     {
 4932 alvherre@alvh.no-ip.     1923   [ +  +  +  + ]:            510 :         if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
                               1924                 :            230 :             TransactionIdDidCommit(xid))
 6921 tgl@sss.pgh.pa.us        1925                 :            203 :             HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
                               1926                 :                :                                  xid);
                               1927                 :                :         else
                               1928                 :             77 :             HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
                               1929                 :                :                                  InvalidTransactionId);
                               1930                 :                :     }
                               1931                 :            281 : }
                               1932                 :                : 
                               1933                 :                : 
                               1934                 :                : /*
                               1935                 :                :  * GetBulkInsertState - prepare status object for a bulk insert
                               1936                 :                :  */
                               1937                 :                : BulkInsertState
 6471                          1938                 :           3597 : GetBulkInsertState(void)
                               1939                 :                : {
                               1940                 :                :     BulkInsertState bistate;
                               1941                 :                : 
  228 michael@paquier.xyz      1942                 :           3597 :     bistate = (BulkInsertState) palloc_object(BulkInsertStateData);
 6471 tgl@sss.pgh.pa.us        1943                 :           3597 :     bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
                               1944                 :           3597 :     bistate->current_buf = InvalidBuffer;
 1207 andres@anarazel.de       1945                 :           3597 :     bistate->next_free = InvalidBlockNumber;
                               1946                 :           3597 :     bistate->last_free = InvalidBlockNumber;
 1077                          1947                 :           3597 :     bistate->already_extended_by = 0;
 6471 tgl@sss.pgh.pa.us        1948                 :           3597 :     return bistate;
                               1949                 :                : }
                               1950                 :                : 
                               1951                 :                : /*
                               1952                 :                :  * FreeBulkInsertState - clean up after finishing a bulk insert
                               1953                 :                :  */
                               1954                 :                : void
                               1955                 :           3361 : FreeBulkInsertState(BulkInsertState bistate)
                               1956                 :                : {
                               1957         [ +  + ]:           3361 :     if (bistate->current_buf != InvalidBuffer)
 6254 bruce@momjian.us         1958                 :           2641 :         ReleaseBuffer(bistate->current_buf);
 6471 tgl@sss.pgh.pa.us        1959                 :           3361 :     FreeAccessStrategy(bistate->strategy);
                               1960                 :           3361 :     pfree(bistate);
                               1961                 :           3361 : }
                               1962                 :                : 
                               1963                 :                : /*
                               1964                 :                :  * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
                               1965                 :                :  */
                               1966                 :                : void
 3470 rhaas@postgresql.org     1967                 :          90779 : ReleaseBulkInsertStatePin(BulkInsertState bistate)
                               1968                 :                : {
                               1969         [ +  + ]:          90779 :     if (bistate->current_buf != InvalidBuffer)
                               1970                 :          40028 :         ReleaseBuffer(bistate->current_buf);
                               1971                 :          90779 :     bistate->current_buf = InvalidBuffer;
                               1972                 :                : 
                               1973                 :                :     /*
                               1974                 :                :      * Despite the name, we also reset bulk relation extension state.
                               1975                 :                :      * Otherwise we can end up erroring out due to looking for free space in
                               1976                 :                :      * ->next_free of one partition, even though ->next_free was set when
                               1977                 :                :      * extending another partition. It could obviously also be bad for
                               1978                 :                :      * efficiency to look at existing blocks at offsets from another
                               1979                 :                :      * partition, even if we don't error out.
                               1980                 :                :      */
 1017 andres@anarazel.de       1981                 :          90779 :     bistate->next_free = InvalidBlockNumber;
                               1982                 :          90779 :     bistate->last_free = InvalidBlockNumber;
 3470 rhaas@postgresql.org     1983                 :          90779 : }
                               1984                 :                : 
                               1985                 :                : 
                               1986                 :                : /*
                               1987                 :                :  *  heap_insert     - insert tuple into a heap
                               1988                 :                :  *
                               1989                 :                :  * The new tuple is stamped with current transaction ID and the specified
                               1990                 :                :  * command ID.
                               1991                 :                :  *
                               1992                 :                :  * See table_tuple_insert for comments about most of the input flags, except
                               1993                 :                :  * that this routine directly takes a tuple rather than a slot.
                               1994                 :                :  *
                               1995                 :                :  * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
                               1996                 :                :  * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
                               1997                 :                :  * implement table_tuple_insert_speculative().
                               1998                 :                :  *
                               1999                 :                :  * On return the header fields of *tup are updated to match the stored tuple;
                               2000                 :                :  * in particular tup->t_self receives the actual TID where the tuple was
                               2001                 :                :  * stored.  But note that any toasting of fields within the tuple data is NOT
                               2002                 :                :  * reflected into *tup.
                               2003                 :                :  */
                               2004                 :                : void
 7706 tgl@sss.pgh.pa.us        2005                 :       11741884 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
                               2006                 :                :             uint32 options, BulkInsertState bistate)
                               2007                 :                : {
 7983                          2008                 :       11741884 :     TransactionId xid = GetCurrentTransactionId();
                               2009                 :                :     HeapTuple   heaptup;
                               2010                 :                :     Buffer      buffer;
                               2011                 :                :     Page        page;
 5514 rhaas@postgresql.org     2012                 :       11741884 :     Buffer      vmbuffer = InvalidBuffer;
   11 melanieplageman@gmai     2013                 :       11741884 :     bool        clear_all_visible = false;
                               2014                 :       11741884 :     bool        vmbuffer_modified = false;
                               2015                 :                : 
                               2016                 :                :     /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
 1903 tgl@sss.pgh.pa.us        2017         [ -  + ]:       11741884 :     Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
                               2018                 :                :            RelationGetNumberOfAttributes(relation));
                               2019                 :                : 
  422 nathan@postgresql.or     2020                 :       11741884 :     AssertHasSnapshotForToast(relation);
                               2021                 :                : 
                               2022                 :                :     /*
                               2023                 :                :      * Fill in tuple header fields and toast the tuple if necessary.
                               2024                 :                :      *
                               2025                 :                :      * Note: below this point, heaptup is the data we actually intend to store
                               2026                 :                :      * into the relation; tup is the caller's original untoasted data.
                               2027                 :                :      */
 5373 heikki.linnakangas@i     2028                 :       11741884 :     heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
                               2029                 :                : 
                               2030                 :                :     /*
                               2031                 :                :      * Find buffer to insert this tuple into.  If the page is all visible,
                               2032                 :                :      * this will also pin the requisite visibility map page.
                               2033                 :                :      */
 3921 kgrittn@postgresql.o     2034                 :       11741884 :     buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
                               2035                 :                :                                        InvalidBuffer, options, bistate,
                               2036                 :                :                                        &vmbuffer, NULL,
                               2037                 :                :                                        0);
                               2038                 :                : 
  118 melanieplageman@gmai     2039                 :       11741882 :     page = BufferGetPage(buffer);
                               2040                 :                : 
                               2041                 :                :     /*
                               2042                 :                :      * We're about to do the actual insert -- but check for conflict first, to
                               2043                 :                :      * avoid possibly having to roll back work we've just done.
                               2044                 :                :      *
                               2045                 :                :      * This is safe without a recheck as long as there is no possibility of
                               2046                 :                :      * another process scanning the page between this check and the insert
                               2047                 :                :      * being visible to the scan (i.e., an exclusive buffer content lock is
                               2048                 :                :      * continuously held from this point until the tuple insert is visible).
                               2049                 :                :      *
                               2050                 :                :      * For a heap insert, we only need to check for table-level SSI locks. Our
                               2051                 :                :      * new tuple can't possibly conflict with existing tuple locks, and heap
                               2052                 :                :      * page locks are only consolidated versions of tuple locks; they do not
                               2053                 :                :      * lock "gaps" as index page locks do.  So we don't need to specify a
                               2054                 :                :      * buffer when making the call, which makes for a faster check.
                               2055                 :                :      */
 2371 tmunro@postgresql.or     2056                 :       11741882 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
                               2057                 :                : 
                               2058                 :                :     /* Lock the vmbuffer before the critical section */
   11 melanieplageman@gmai     2059         [ +  + ]:       11741868 :     if (PageIsAllVisible(page))
                               2060                 :                :     {
                               2061                 :           9527 :         LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
                               2062                 :           9527 :         clear_all_visible = true;
                               2063                 :                :     }
                               2064                 :                : 
                               2065                 :                :     /* NO EREPORT(ERROR) from here till changes are logged */
 9326 tgl@sss.pgh.pa.us        2066                 :       11741868 :     START_CRIT_SECTION();
                               2067                 :                : 
 4097 andres@anarazel.de       2068                 :       11741868 :     RelationPutHeapTuple(relation, buffer, heaptup,
                               2069                 :       11741868 :                          (options & HEAP_INSERT_SPECULATIVE) != 0);
                               2070                 :                : 
   11 melanieplageman@gmai     2071         [ +  + ]:       11741868 :     if (clear_all_visible)
                               2072                 :                :     {
                               2073                 :                :         /* It's possible the VM bits were already clear */
   11 melanieplageman@gmai     2074         [ +  + ]:GNC        9527 :         if (visibilitymap_clear(relation->rd_locator,
   11 melanieplageman@gmai     2075                 :CBC        9527 :                                 ItemPointerGetBlockNumber(&(heaptup->t_self)),
                               2076                 :                :                                 vmbuffer, VISIBILITYMAP_VALID_BITS))
                               2077                 :           9525 :             vmbuffer_modified = true;
                               2078                 :                : 
  118                          2079                 :           9527 :         PageClearAllVisible(page);
                               2080                 :                :     }
                               2081                 :                : 
                               2082                 :                :     /*
                               2083                 :                :      * Set pd_prune_xid to trigger heap_page_prune_and_freeze() once the page
                               2084                 :                :      * is full so that we can set the page all-visible in the VM on the next
                               2085                 :                :      * page access.
                               2086                 :                :      *
                               2087                 :                :      * Setting pd_prune_xid is also handy if the inserting transaction
                               2088                 :                :      * eventually aborts making this tuple DEAD and hence available for
                               2089                 :                :      * pruning. If no other tuple in this page is UPDATEd/DELETEd, the aborted
                               2090                 :                :      * tuple would never otherwise be pruned until next vacuum is triggered.
                               2091                 :                :      *
                               2092                 :                :      * Don't set it if we are in bootstrap mode or we are inserting a frozen
                               2093                 :                :      * tuple, as there is no further pruning/freezing needed in those cases.
                               2094                 :                :      */
                               2095   [ +  +  +  + ]:       11741868 :     if (TransactionIdIsNormal(xid) && !(options & HEAP_INSERT_FROZEN))
                               2096   [ -  +  +  +  :       11099942 :         PageSetPrunable(page, xid);
                                              +  + ]
                               2097                 :                : 
 7422 tgl@sss.pgh.pa.us        2098                 :       11741868 :     MarkBufferDirty(buffer);
                               2099                 :                : 
                               2100                 :                :     /* XLOG stuff */
 2304 noah@leadboat.com        2101   [ +  +  +  +  :       11741868 :     if (RelationNeedsWAL(relation))
                                        +  +  +  + ]
                               2102                 :                :     {
                               2103                 :                :         xl_heap_insert xlrec;
                               2104                 :                :         xl_heap_header xlhdr;
                               2105                 :                :         XLogRecPtr  recptr;
 9257 bruce@momjian.us         2106                 :       10628501 :         uint8       info = XLOG_HEAP_INSERT;
 4266 heikki.linnakangas@i     2107                 :       10628501 :         int         bufflags = 0;
                               2108                 :                : 
                               2109                 :                :         /*
                               2110                 :                :          * If this is a catalog, we need to transmit combo CIDs to properly
                               2111                 :                :          * decode, so log that as well.
                               2112                 :                :          */
 4611 rhaas@postgresql.org     2113   [ +  +  +  +  :       10628501 :         if (RelationIsAccessibleInLogicalDecoding(relation))
                                     +  -  -  +  -  
                                     -  -  -  +  +  
                                     +  +  -  +  -  
                                           -  +  + ]
                               2114                 :           3711 :             log_heap_new_cid(relation, heaptup);
                               2115                 :                : 
                               2116                 :                :         /*
                               2117                 :                :          * If this is the single and first tuple on page, we can reinit the
                               2118                 :                :          * page instead of restoring the whole thing.  Set flag, and hide
                               2119                 :                :          * buffer references from XLogInsert.
                               2120                 :                :          */
 4266 heikki.linnakangas@i     2121   [ +  +  +  + ]:       10750474 :         if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
                               2122                 :         121973 :             PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
                               2123                 :                :         {
                               2124                 :         120142 :             info |= XLOG_HEAP_INIT_PAGE;
                               2125                 :         120142 :             bufflags |= REGBUF_WILL_INIT;
                               2126                 :                :         }
                               2127                 :                : 
                               2128                 :       10628501 :         xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
 4097 andres@anarazel.de       2129                 :       10628501 :         xlrec.flags = 0;
   11 melanieplageman@gmai     2130         [ +  + ]:       10628501 :         if (clear_all_visible)
 4097 andres@anarazel.de       2131                 :           9523 :             xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
                               2132         [ +  + ]:       10628501 :         if (options & HEAP_INSERT_SPECULATIVE)
                               2133                 :           2207 :             xlrec.flags |= XLH_INSERT_IS_SPECULATIVE;
 4266 heikki.linnakangas@i     2134         [ -  + ]:       10628501 :         Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
                               2135                 :                : 
                               2136                 :                :         /*
                               2137                 :                :          * For logical decoding, we need the tuple even if we're doing a full
                               2138                 :                :          * page write, so make sure it's included even if we take a full-page
                               2139                 :                :          * image. (XXX We could alternatively store a pointer into the FPW).
                               2140                 :                :          */
 2846 andres@anarazel.de       2141   [ +  +  +  +  :       10628501 :         if (RelationIsLogicallyLogged(relation) &&
                                     +  -  -  +  -  
                                     -  -  -  +  -  
                                              +  + ]
                               2142         [ +  + ]:         273018 :             !(options & HEAP_INSERT_NO_LOGICAL))
                               2143                 :                :         {
 4097                          2144                 :         272899 :             xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
 4266 heikki.linnakangas@i     2145                 :         272899 :             bufflags |= REGBUF_KEEP_DATA;
                               2146                 :                : 
 2178 akapila@postgresql.o     2147         [ +  + ]:         272899 :             if (IsToastRelation(relation))
                               2148                 :           1855 :                 xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
                               2149                 :                :         }
                               2150                 :                : 
 4266 heikki.linnakangas@i     2151                 :       10628501 :         XLogBeginInsert();
  530 peter@eisentraut.org     2152                 :       10628501 :         XLogRegisterData(&xlrec, SizeOfHeapInsert);
                               2153                 :                : 
 4266 heikki.linnakangas@i     2154                 :       10628501 :         xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
                               2155                 :       10628501 :         xlhdr.t_infomask = heaptup->t_data->t_infomask;
                               2156                 :       10628501 :         xlhdr.t_hoff = heaptup->t_data->t_hoff;
                               2157                 :                : 
                               2158                 :                :         /*
                               2159                 :                :          * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
                               2160                 :                :          * write the whole page to the xlog, we don't need to store
                               2161                 :                :          * xl_heap_header in the xlog.
                               2162                 :                :          */
   11 melanieplageman@gmai     2163                 :       10628501 :         XLogRegisterBuffer(HEAP_INSERT_BLKREF_HEAP, buffer,
                               2164                 :       10628501 :                            REGBUF_STANDARD | bufflags);
                               2165                 :       10628501 :         XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP, &xlhdr,
                               2166                 :                :                             SizeOfHeapHeader);
                               2167                 :                :         /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
                               2168                 :       10628501 :         XLogRegisterBufData(HEAP_INSERT_BLKREF_HEAP,
 4173 tgl@sss.pgh.pa.us        2169                 :       10628501 :                             (char *) heaptup->t_data + SizeofHeapTupleHeader,
                               2170                 :       10628501 :                             heaptup->t_len - SizeofHeapTupleHeader);
                               2171                 :                : 
                               2172                 :                :         /* filtering by origin on a row level is much more efficient */
 3503 andres@anarazel.de       2173                 :       10628501 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               2174                 :                : 
   11 melanieplageman@gmai     2175         [ +  + ]:       10628501 :         if (vmbuffer_modified)
                               2176                 :           9521 :             XLogRegisterBuffer(HEAP_INSERT_BLKREF_VM, vmbuffer, 0);
                               2177                 :                : 
 4266 heikki.linnakangas@i     2178                 :       10628501 :         recptr = XLogInsert(RM_HEAP_ID, info);
                               2179                 :                : 
 9341 vadim4o@yahoo.com        2180                 :       10628501 :         PageSetLSN(page, recptr);
                               2181                 :                : 
   11 melanieplageman@gmai     2182         [ +  + ]:       10628501 :         if (vmbuffer_modified)
                               2183                 :           9521 :             PageSetLSN(BufferGetPage(vmbuffer), recptr);
                               2184                 :                :     }
                               2185                 :                : 
 9326 tgl@sss.pgh.pa.us        2186         [ -  + ]:       11741868 :     END_CRIT_SECTION();
                               2187                 :                : 
 7422                          2188                 :       11741868 :     UnlockReleaseBuffer(buffer);
                               2189                 :                : 
                               2190                 :                :     /*
                               2191                 :                :      * We locked vmbuffer if clear_all_visible was true regardless of whether
                               2192                 :                :      * or not we ended up modifying the vmbuffer.
                               2193                 :                :      */
   11 melanieplageman@gmai     2194         [ +  + ]:       11741868 :     if (clear_all_visible)
                               2195                 :           9527 :         LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
                               2196         [ +  + ]:       11741868 :     if (BufferIsValid(vmbuffer))
 5514 rhaas@postgresql.org     2197                 :           9903 :         ReleaseBuffer(vmbuffer);
                               2198                 :                : 
                               2199                 :                :     /*
                               2200                 :                :      * If tuple is cacheable, mark it for invalidation from the caches in case
                               2201                 :                :      * we abort.  Note it is OK to do this after releasing the buffer, because
                               2202                 :                :      * the heaptup data structure is all in local memory, not in the shared
                               2203                 :                :      * buffer.
                               2204                 :                :      */
 5458 tgl@sss.pgh.pa.us        2205                 :       11741868 :     CacheInvalidateHeapTuple(relation, heaptup, NULL);
                               2206                 :                : 
                               2207                 :                :     /* Note: speculative insertions are counted too, even if aborted later */
 5373 heikki.linnakangas@i     2208                 :       11741868 :     pgstat_count_heap_insert(relation, 1);
                               2209                 :                : 
                               2210                 :                :     /*
                               2211                 :                :      * If heaptup is a private copy, release it.  Don't forget to copy t_self
                               2212                 :                :      * back to the caller's image, too.
                               2213                 :                :      */
 7553 tgl@sss.pgh.pa.us        2214         [ +  + ]:       11741868 :     if (heaptup != tup)
                               2215                 :                :     {
                               2216                 :          22510 :         tup->t_self = heaptup->t_self;
                               2217                 :          22510 :         heap_freetuple(heaptup);
                               2218                 :                :     }
10974 scrappy@hub.org          2219                 :       11741868 : }
                               2220                 :                : 
                               2221                 :                : /*
                               2222                 :                :  * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
                               2223                 :                :  * tuple header fields and toasts the tuple if necessary.  Returns a toasted
                               2224                 :                :  * version of the tuple if it was toasted, or the original tuple if not. Note
                               2225                 :                :  * that in any case, the header fields are also set in the original tuple.
                               2226                 :                :  */
                               2227                 :                : static HeapTuple
 5373 heikki.linnakangas@i     2228                 :       13583112 : heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
                               2229                 :                :                     CommandId cid, uint32 options)
                               2230                 :                : {
                               2231                 :                :     /*
                               2232                 :                :      * To allow parallel inserts, we need to ensure that they are safe to be
                               2233                 :                :      * performed in workers. We have the infrastructure to allow parallel
                               2234                 :                :      * inserts in general except for the cases where inserts generate a new
                               2235                 :                :      * CommandId (eg. inserts into a table having a foreign key column).
                               2236                 :                :      */
 3216 rhaas@postgresql.org     2237         [ -  + ]:       13583112 :     if (IsParallelWorker())
 4105 rhaas@postgresql.org     2238         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2239                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               2240                 :                :                  errmsg("cannot insert tuples in a parallel worker")));
                               2241                 :                : 
 5373 heikki.linnakangas@i     2242                 :CBC    13583112 :     tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
                               2243                 :       13583112 :     tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
                               2244                 :       13583112 :     tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
 4599 rhaas@postgresql.org     2245                 :       13583112 :     HeapTupleHeaderSetXmin(tup->t_data, xid);
 4984 simon@2ndQuadrant.co     2246         [ +  + ]:       13583112 :     if (options & HEAP_INSERT_FROZEN)
 4599 rhaas@postgresql.org     2247                 :         102651 :         HeapTupleHeaderSetXminFrozen(tup->t_data);
                               2248                 :                : 
 5373 heikki.linnakangas@i     2249                 :       13583112 :     HeapTupleHeaderSetCmin(tup->t_data, cid);
 3322 tgl@sss.pgh.pa.us        2250                 :       13583112 :     HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
 5373 heikki.linnakangas@i     2251                 :       13583112 :     tup->t_tableOid = RelationGetRelid(relation);
                               2252                 :                : 
                               2253                 :                :     /*
                               2254                 :                :      * If the new tuple is too big for storage or contains already toasted
                               2255                 :                :      * out-of-line attributes from some other relation, invoke the toaster.
                               2256                 :                :      */
 4893 kgrittn@postgresql.o     2257         [ +  + ]:       13583112 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
                               2258         [ +  + ]:          36283 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
                               2259                 :                :     {
                               2260                 :                :         /* toast table entries should never be recursively toasted */
 5373 heikki.linnakangas@i     2261         [ -  + ]:          36222 :         Assert(!HeapTupleHasExternal(tup));
                               2262                 :          36222 :         return tup;
                               2263                 :                :     }
                               2264   [ +  +  +  + ]:       13546890 :     else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
 2487 rhaas@postgresql.org     2265                 :          22569 :         return heap_toast_insert_or_update(relation, tup, NULL, options);
                               2266                 :                :     else
 5373 heikki.linnakangas@i     2267                 :       13524321 :         return tup;
                               2268                 :                : }
                               2269                 :                : 
                               2270                 :                : /*
                               2271                 :                :  * Helper for heap_multi_insert() that computes the number of entire pages
                               2272                 :                :  * that inserting the remaining heaptuples requires. Used to determine how
                               2273                 :                :  * much the relation needs to be extended by.
                               2274                 :                :  */
                               2275                 :                : static int
 1207 andres@anarazel.de       2276                 :         496043 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
                               2277                 :                : {
                               2278                 :         496043 :     size_t      page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
                               2279                 :         496043 :     int         npages = 1;
                               2280                 :                : 
                               2281         [ +  + ]:        3024406 :     for (int i = done; i < ntuples; i++)
                               2282                 :                :     {
                               2283                 :        2528363 :         size_t      tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
                               2284                 :                : 
                               2285         [ +  + ]:        2528363 :         if (page_avail < tup_sz)
                               2286                 :                :         {
                               2287                 :          17687 :             npages++;
                               2288                 :          17687 :             page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
                               2289                 :                :         }
                               2290                 :        2528363 :         page_avail -= tup_sz;
                               2291                 :                :     }
                               2292                 :                : 
                               2293                 :         496043 :     return npages;
                               2294                 :                : }
                               2295                 :                : 
                               2296                 :                : /*
                               2297                 :                :  *  heap_multi_insert   - insert multiple tuples into a heap
                               2298                 :                :  *
                               2299                 :                :  * This is like heap_insert(), but inserts multiple tuples in one operation.
                               2300                 :                :  * That's faster than calling heap_insert() in a loop, because when multiple
                               2301                 :                :  * tuples can be inserted on a single page, we can write just a single WAL
                               2302                 :                :  * record covering all of them, and only need to lock/unlock the page once.
                               2303                 :                :  *
                               2304                 :                :  * Note: this leaks memory into the current memory context. You can create a
                               2305                 :                :  * temporary context before calling this, if that's a problem.
                               2306                 :                :  */
                               2307                 :                : void
 2670                          2308                 :         487172 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
                               2309                 :                :                   CommandId cid, uint32 options, BulkInsertState bistate)
                               2310                 :                : {
 5373 heikki.linnakangas@i     2311                 :         487172 :     TransactionId xid = GetCurrentTransactionId();
                               2312                 :                :     HeapTuple  *heaptuples;
                               2313                 :                :     int         i;
                               2314                 :                :     int         ndone;
                               2315                 :                :     PGAlignedBlock scratch;
                               2316                 :                :     Page        page;
 2016 tomas.vondra@postgre     2317                 :         487172 :     Buffer      vmbuffer = InvalidBuffer;
                               2318                 :                :     bool        needwal;
                               2319                 :                :     Size        saveFreeSpace;
 4611 rhaas@postgresql.org     2320   [ +  +  +  +  :         487172 :     bool        need_tuple_data = RelationIsLogicallyLogged(relation);
                                     +  -  -  +  -  
                                     -  -  -  +  -  
                                              +  + ]
                               2321   [ +  +  +  +  :         487172 :     bool        need_cids = RelationIsAccessibleInLogicalDecoding(relation);
                                     +  -  -  +  -  
                                     -  -  -  +  +  
                                     -  +  -  -  -  
                                           -  -  - ]
 1207 andres@anarazel.de       2322                 :         487172 :     bool        starting_with_empty_page = false;
                               2323                 :         487172 :     int         npages = 0;
                               2324                 :         487172 :     int         npages_used = 0;
                               2325                 :                : 
                               2326                 :                :     /* currently not needed (thus unsupported) for heap_multi_insert() */
 1367 peter@eisentraut.org     2327         [ -  + ]:         487172 :     Assert(!(options & HEAP_INSERT_NO_LOGICAL));
                               2328                 :                : 
  422 nathan@postgresql.or     2329                 :         487172 :     AssertHasSnapshotForToast(relation);
                               2330                 :                : 
 2304 noah@leadboat.com        2331   [ +  +  +  +  :         487172 :     needwal = RelationNeedsWAL(relation);
                                        +  -  +  + ]
  836 akorotkov@postgresql     2332         [ +  + ]:         487172 :     saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
                               2333                 :                :                                                    HEAP_DEFAULT_FILLFACTOR);
                               2334                 :                : 
                               2335                 :                :     /* Toast and set header data in all the slots */
 5373 heikki.linnakangas@i     2336                 :         487172 :     heaptuples = palloc(ntuples * sizeof(HeapTuple));
                               2337         [ +  + ]:        2328400 :     for (i = 0; i < ntuples; i++)
                               2338                 :                :     {
                               2339                 :                :         HeapTuple   tuple;
                               2340                 :                : 
 2670 andres@anarazel.de       2341                 :        1841228 :         tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
                               2342                 :        1841228 :         slots[i]->tts_tableOid = RelationGetRelid(relation);
                               2343                 :        1841228 :         tuple->t_tableOid = slots[i]->tts_tableOid;
                               2344                 :        1841228 :         heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
                               2345                 :                :                                             options);
                               2346                 :                :     }
                               2347                 :                : 
                               2348                 :                :     /*
                               2349                 :                :      * We're about to do the actual inserts -- but check for conflict first,
                               2350                 :                :      * to minimize the possibility of having to roll back work we've just
                               2351                 :                :      * done.
                               2352                 :                :      *
                               2353                 :                :      * A check here does not definitively prevent a serialization anomaly;
                               2354                 :                :      * that check MUST be done at least past the point of acquiring an
                               2355                 :                :      * exclusive buffer content lock on every buffer that will be affected,
                               2356                 :                :      * and MAY be done after all inserts are reflected in the buffers and
                               2357                 :                :      * those locks are released; otherwise there is a race condition.  Since
                               2358                 :                :      * multiple buffers can be locked and unlocked in the loop below, and it
                               2359                 :                :      * would not be feasible to identify and lock all of those buffers before
                               2360                 :                :      * the loop, we must do a final check at the end.
                               2361                 :                :      *
                               2362                 :                :      * The check here could be omitted with no loss of correctness; it is
                               2363                 :                :      * present strictly as an optimization.
                               2364                 :                :      *
                               2365                 :                :      * For heap inserts, we only need to check for table-level SSI locks. Our
                               2366                 :                :      * new tuples can't possibly conflict with existing tuple locks, and heap
                               2367                 :                :      * page locks are only consolidated versions of tuple locks; they do not
                               2368                 :                :      * lock "gaps" as index page locks do.  So we don't need to specify a
                               2369                 :                :      * buffer when making the call, which makes for a faster check.
                               2370                 :                :      */
 2371 tmunro@postgresql.or     2371                 :         487172 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
                               2372                 :                : 
 5373 heikki.linnakangas@i     2373                 :         487172 :     ndone = 0;
                               2374         [ +  + ]:         992551 :     while (ndone < ntuples)
                               2375                 :                :     {
                               2376                 :                :         Buffer      buffer;
   11 melanieplageman@gmai     2377                 :         505379 :         bool        clear_all_visible = false;
 2016 tomas.vondra@postgre     2378                 :         505379 :         bool        all_frozen_set = false;
   11 melanieplageman@gmai     2379                 :         505379 :         bool        vmbuffer_modified = false;
                               2380                 :                :         int         nthispage;
                               2381                 :                : 
 4416 rhaas@postgresql.org     2382         [ -  + ]:         505379 :         CHECK_FOR_INTERRUPTS();
                               2383                 :                : 
                               2384                 :                :         /*
                               2385                 :                :          * Compute number of pages needed to fit the to-be-inserted tuples in
                               2386                 :                :          * the worst case.  This will be used to determine how much to extend
                               2387                 :                :          * the relation by in RelationGetBufferForTuple(), if needed.  If we
                               2388                 :                :          * filled a prior page from scratch, we can just update our last
                               2389                 :                :          * computation, but if we started with a partially filled page,
                               2390                 :                :          * recompute from scratch, the number of potentially required pages
                               2391                 :                :          * can vary due to tuples needing to fit onto the page, page headers
                               2392                 :                :          * etc.
                               2393                 :                :          */
 1207 andres@anarazel.de       2394   [ +  +  +  + ]:         505379 :         if (ndone == 0 || !starting_with_empty_page)
                               2395                 :                :         {
                               2396                 :         496043 :             npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
                               2397                 :                :                                              saveFreeSpace);
                               2398                 :         496043 :             npages_used = 0;
                               2399                 :                :         }
                               2400                 :                :         else
                               2401                 :           9336 :             npages_used++;
                               2402                 :                : 
                               2403                 :                :         /*
                               2404                 :                :          * Find buffer where at least the next tuple will fit.  If the page is
                               2405                 :                :          * all-visible, this will also pin the requisite visibility map page.
                               2406                 :                :          *
                               2407                 :                :          * Also pin visibility map page if COPY FREEZE inserts tuples into an
                               2408                 :                :          * empty page. See all_frozen_set below.
                               2409                 :                :          */
 5373 heikki.linnakangas@i     2410                 :         505379 :         buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
                               2411                 :                :                                            InvalidBuffer, options, bistate,
                               2412                 :                :                                            &vmbuffer, NULL,
                               2413                 :                :                                            npages - npages_used);
 3749 kgrittn@postgresql.o     2414                 :         505379 :         page = BufferGetPage(buffer);
                               2415                 :                : 
 2016 tomas.vondra@postgre     2416                 :         505379 :         starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
                               2417                 :                : 
                               2418   [ +  +  +  + ]:         505379 :         if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
                               2419                 :                :         {
                               2420                 :           1665 :             all_frozen_set = true;
                               2421                 :                :             /* Lock the vmbuffer before entering the critical section */
  290 melanieplageman@gmai     2422                 :           1665 :             LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
                               2423                 :                :         }
   11                          2424   [ +  +  +  + ]:         503714 :         else if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
                               2425                 :                :         {
                               2426                 :           7061 :             clear_all_visible = true;
                               2427                 :                :             /* Lock the vmbuffer before entering the critical section */
                               2428                 :           7061 :             LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
                               2429                 :                :         }
                               2430                 :                : 
                               2431                 :                :         /* NO EREPORT(ERROR) from here till changes are logged */
 5373 heikki.linnakangas@i     2432                 :         505379 :         START_CRIT_SECTION();
                               2433                 :                : 
                               2434                 :                :         /*
                               2435                 :                :          * RelationGetBufferForTuple has ensured that the first tuple fits.
                               2436                 :                :          * Put that on the page, and then as many other tuples as fit.
                               2437                 :                :          */
 4097 andres@anarazel.de       2438                 :         505379 :         RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
                               2439                 :                : 
                               2440                 :                :         /*
                               2441                 :                :          * For logical decoding we need combo CIDs to properly decode the
                               2442                 :                :          * catalog.
                               2443                 :                :          */
 2343 michael@paquier.xyz      2444   [ +  +  +  + ]:         505379 :         if (needwal && need_cids)
                               2445                 :           5431 :             log_heap_new_cid(relation, heaptuples[ndone]);
                               2446                 :                : 
 4974 heikki.linnakangas@i     2447         [ +  + ]:        1841228 :         for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
                               2448                 :                :         {
 5373                          2449                 :        1354056 :             HeapTuple   heaptup = heaptuples[ndone + nthispage];
                               2450                 :                : 
 5184                          2451         [ +  + ]:        1354056 :             if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
 5373                          2452                 :          18207 :                 break;
                               2453                 :                : 
 4097 andres@anarazel.de       2454                 :        1335849 :             RelationPutHeapTuple(relation, buffer, heaptup, false);
                               2455                 :                : 
                               2456                 :                :             /*
                               2457                 :                :              * For logical decoding we need combo CIDs to properly decode the
                               2458                 :                :              * catalog.
                               2459                 :                :              */
 4266 heikki.linnakangas@i     2460   [ +  +  +  + ]:        1335849 :             if (needwal && need_cids)
                               2461                 :           5039 :                 log_heap_new_cid(relation, heaptup);
                               2462                 :                :         }
                               2463                 :                : 
                               2464                 :                :         /*
                               2465                 :                :          * If the page is all visible, need to clear that, unless we're only
                               2466                 :                :          * going to add further frozen rows to it.
                               2467                 :                :          *
                               2468                 :                :          * If we're only adding already frozen rows to a previously empty
                               2469                 :                :          * page, mark it as all-frozen and update the visibility map. We're
                               2470                 :                :          * already holding a pin on the vmbuffer.
                               2471                 :                :          */
   11 melanieplageman@gmai     2472         [ +  + ]:         505379 :         if (clear_all_visible)
                               2473                 :                :         {
                               2474         [ -  + ]:           7061 :             Assert(!(options & HEAP_INSERT_FROZEN));
                               2475                 :                :             /* It's possible the VM bits were already clear */
   11 melanieplageman@gmai     2476         [ +  + ]:GNC        7061 :             if (visibilitymap_clear(relation->rd_locator,
                               2477                 :                :                                     BufferGetBlockNumber(buffer),
                               2478                 :                :                                     vmbuffer, VISIBILITYMAP_VALID_BITS))
   11 melanieplageman@gmai     2479                 :CBC        7060 :                 vmbuffer_modified = true;
                               2480                 :                : 
 5162 rhaas@postgresql.org     2481                 :           7061 :             PageClearAllVisible(page);
                               2482                 :                :         }
 2016 tomas.vondra@postgre     2483         [ +  + ]:         498318 :         else if (all_frozen_set)
                               2484                 :                :         {
                               2485                 :           1665 :             PageSetAllVisible(page);
  146 melanieplageman@gmai     2486                 :           1665 :             PageClearPrunable(page);
  124                          2487                 :           1665 :             visibilitymap_set(BufferGetBlockNumber(buffer),
                               2488                 :                :                               vmbuffer,
                               2489                 :                :                               VISIBILITYMAP_ALL_VISIBLE |
                               2490                 :                :                               VISIBILITYMAP_ALL_FROZEN,
                               2491                 :                :                               relation->rd_locator);
                               2492                 :                :         }
                               2493                 :                : 
                               2494                 :                :         /*
                               2495                 :                :          * Set pd_prune_xid. See heap_insert() for more on why we do this when
                               2496                 :                :          * inserting tuples. This only makes sense if we aren't already
                               2497                 :                :          * setting the page frozen in the VM and we're not in bootstrap mode.
                               2498                 :                :          */
  118                          2499   [ +  +  +  + ]:         505379 :         if (!all_frozen_set && TransactionIdIsNormal(xid))
                               2500   [ -  +  +  +  :         481426 :             PageSetPrunable(page, xid);
                                              +  + ]
                               2501                 :                : 
 5373 heikki.linnakangas@i     2502                 :         505379 :         MarkBufferDirty(buffer);
                               2503                 :                : 
                               2504                 :                :         /* XLOG stuff */
                               2505         [ +  + ]:         505379 :         if (needwal)
                               2506                 :                :         {
                               2507                 :                :             XLogRecPtr  recptr;
                               2508                 :                :             xl_heap_multi_insert *xlrec;
                               2509                 :         501480 :             uint8       info = XLOG_HEAP2_MULTI_INSERT;
                               2510                 :                :             char       *tupledata;
                               2511                 :                :             int         totaldatalen;
 2885 tgl@sss.pgh.pa.us        2512                 :         501480 :             char       *scratchptr = scratch.data;
                               2513                 :                :             bool        init;
 4266 heikki.linnakangas@i     2514                 :         501480 :             int         bufflags = 0;
                               2515                 :                : 
                               2516                 :                :             /*
                               2517                 :                :              * If the page was previously empty, we can reinit the page
                               2518                 :                :              * instead of restoring the whole thing.
                               2519                 :                :              */
 2016 tomas.vondra@postgre     2520                 :         501480 :             init = starting_with_empty_page;
                               2521                 :                : 
                               2522                 :                :             /* allocate xl_heap_multi_insert struct from the scratch area */
 5373 heikki.linnakangas@i     2523                 :         501480 :             xlrec = (xl_heap_multi_insert *) scratchptr;
                               2524                 :         501480 :             scratchptr += SizeOfHeapMultiInsert;
                               2525                 :                : 
                               2526                 :                :             /*
                               2527                 :                :              * Allocate offsets array. Unless we're reinitializing the page,
                               2528                 :                :              * in that case the tuples are stored in order starting at
                               2529                 :                :              * FirstOffsetNumber and we don't need to store the offsets
                               2530                 :                :              * explicitly.
                               2531                 :                :              */
                               2532         [ +  + ]:         501480 :             if (!init)
                               2533                 :         486679 :                 scratchptr += nthispage * sizeof(OffsetNumber);
                               2534                 :                : 
                               2535                 :                :             /* the rest of the scratch space is used for tuple data */
                               2536                 :         501480 :             tupledata = scratchptr;
                               2537                 :                : 
                               2538                 :                :             /* check that the mutually exclusive flags are not both set */
   11 melanieplageman@gmai     2539   [ +  +  -  + ]:         501480 :             Assert(!(clear_all_visible && all_frozen_set));
                               2540                 :                : 
 2016 tomas.vondra@postgre     2541                 :         501480 :             xlrec->flags = 0;
   11 melanieplageman@gmai     2542         [ +  + ]:         501480 :             if (clear_all_visible)
 2016 tomas.vondra@postgre     2543                 :           7061 :                 xlrec->flags = XLH_INSERT_ALL_VISIBLE_CLEARED;
                               2544                 :                : 
                               2545                 :                :             /*
                               2546                 :                :              * We don't have to worry about including a conflict xid in the
                               2547                 :                :              * WAL record, as HEAP_INSERT_FROZEN intentionally violates
                               2548                 :                :              * visibility rules.
                               2549                 :                :              */
                               2550         [ +  + ]:         501480 :             if (all_frozen_set)
                               2551                 :             21 :                 xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
                               2552                 :                : 
 5373 heikki.linnakangas@i     2553                 :         501480 :             xlrec->ntuples = nthispage;
                               2554                 :                : 
                               2555                 :                :             /*
                               2556                 :                :              * Write out an xl_multi_insert_tuple and the tuple data itself
                               2557                 :                :              * for each tuple.
                               2558                 :                :              */
                               2559         [ +  + ]:        2135533 :             for (i = 0; i < nthispage; i++)
                               2560                 :                :             {
                               2561                 :        1634053 :                 HeapTuple   heaptup = heaptuples[ndone + i];
                               2562                 :                :                 xl_multi_insert_tuple *tuphdr;
                               2563                 :                :                 int         datalen;
                               2564                 :                : 
                               2565         [ +  + ]:        1634053 :                 if (!init)
                               2566                 :        1000931 :                     xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
                               2567                 :                :                 /* xl_multi_insert_tuple needs two-byte alignment. */
                               2568                 :        1634053 :                 tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
                               2569                 :        1634053 :                 scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
                               2570                 :                : 
                               2571                 :        1634053 :                 tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
                               2572                 :        1634053 :                 tuphdr->t_infomask = heaptup->t_data->t_infomask;
                               2573                 :        1634053 :                 tuphdr->t_hoff = heaptup->t_data->t_hoff;
                               2574                 :                : 
                               2575                 :                :                 /* write bitmap [+ padding] [+ oid] + data */
 4173 tgl@sss.pgh.pa.us        2576                 :        1634053 :                 datalen = heaptup->t_len - SizeofHeapTupleHeader;
 5373 heikki.linnakangas@i     2577                 :        1634053 :                 memcpy(scratchptr,
 4173 tgl@sss.pgh.pa.us        2578                 :        1634053 :                        (char *) heaptup->t_data + SizeofHeapTupleHeader,
                               2579                 :                :                        datalen);
 5373 heikki.linnakangas@i     2580                 :        1634053 :                 tuphdr->datalen = datalen;
                               2581                 :        1634053 :                 scratchptr += datalen;
                               2582                 :                :             }
                               2583                 :         501480 :             totaldatalen = scratchptr - tupledata;
 2885 tgl@sss.pgh.pa.us        2584         [ -  + ]:         501480 :             Assert((scratchptr - scratch.data) < BLCKSZ);
                               2585                 :                : 
 4611 rhaas@postgresql.org     2586         [ +  + ]:         501480 :             if (need_tuple_data)
 4097 andres@anarazel.de       2587                 :             72 :                 xlrec->flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
                               2588                 :                : 
                               2589                 :                :             /*
                               2590                 :                :              * Signal that this is the last xl_heap_multi_insert record
                               2591                 :                :              * emitted by this call to heap_multi_insert(). Needed for logical
                               2592                 :                :              * decoding so it knows when to cleanup temporary data.
                               2593                 :                :              */
 4266 heikki.linnakangas@i     2594         [ +  + ]:         501480 :             if (ndone + nthispage == ntuples)
 4097 andres@anarazel.de       2595                 :         486718 :                 xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
                               2596                 :                : 
 5373 heikki.linnakangas@i     2597         [ +  + ]:         501480 :             if (init)
                               2598                 :                :             {
                               2599                 :          14801 :                 info |= XLOG_HEAP_INIT_PAGE;
 4266                          2600                 :          14801 :                 bufflags |= REGBUF_WILL_INIT;
                               2601                 :                :             }
                               2602                 :                : 
                               2603                 :                :             /*
                               2604                 :                :              * If we're doing logical decoding, include the new tuple data
                               2605                 :                :              * even if we take a full-page image of the page.
                               2606                 :                :              */
                               2607         [ +  + ]:         501480 :             if (need_tuple_data)
                               2608                 :             72 :                 bufflags |= REGBUF_KEEP_DATA;
                               2609                 :                : 
                               2610                 :         501480 :             XLogBeginInsert();
  530 peter@eisentraut.org     2611                 :         501480 :             XLogRegisterData(xlrec, tupledata - scratch.data);
   11 melanieplageman@gmai     2612                 :         501480 :             XLogRegisterBuffer(HEAP_MULTI_INSERT_BLKREF_HEAP, buffer,
                               2613                 :         501480 :                                REGBUF_STANDARD | bufflags);
                               2614   [ +  +  +  + ]:         501480 :             if (all_frozen_set || vmbuffer_modified)
                               2615                 :           7081 :                 XLogRegisterBuffer(HEAP_MULTI_INSERT_BLKREF_VM, vmbuffer, 0);
                               2616                 :                : 
                               2617                 :         501480 :             XLogRegisterBufData(HEAP_MULTI_INSERT_BLKREF_HEAP, tupledata,
                               2618                 :                :                                 totaldatalen);
                               2619                 :                : 
                               2620                 :                :             /* filtering by origin on a row level is much more efficient */
 3503 andres@anarazel.de       2621                 :         501480 :             XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               2622                 :                : 
 4266 heikki.linnakangas@i     2623                 :         501480 :             recptr = XLogInsert(RM_HEAP2_ID, info);
                               2624                 :                : 
 5373                          2625                 :         501480 :             PageSetLSN(page, recptr);
   11 melanieplageman@gmai     2626   [ +  +  +  + ]:         501480 :             if (all_frozen_set || vmbuffer_modified)
                               2627                 :                :             {
  290                          2628         [ -  + ]:           7081 :                 Assert(BufferIsDirty(vmbuffer));
                               2629                 :           7081 :                 PageSetLSN(BufferGetPage(vmbuffer), recptr);
                               2630                 :                :             }
                               2631                 :                :         }
                               2632                 :                : 
 5373 heikki.linnakangas@i     2633         [ -  + ]:         505379 :         END_CRIT_SECTION();
                               2634                 :                : 
                               2635                 :                :         /*
                               2636                 :                :          * We locked vmbuffer if clear_all_visible was true regardless of
                               2637                 :                :          * whether or not we ended up modifying the vmbuffer.
                               2638                 :                :          */
   11 melanieplageman@gmai     2639   [ +  +  +  + ]:         505379 :         if (all_frozen_set || clear_all_visible)
  290                          2640                 :           8726 :             LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
                               2641                 :                : 
 2016 tomas.vondra@postgre     2642                 :         505379 :         UnlockReleaseBuffer(buffer);
 5373 heikki.linnakangas@i     2643                 :         505379 :         ndone += nthispage;
                               2644                 :                : 
                               2645                 :                :         /*
                               2646                 :                :          * NB: Only release vmbuffer after inserting all tuples - it's fairly
                               2647                 :                :          * likely that we'll insert into subsequent heap pages that are likely
                               2648                 :                :          * to use the same vm page.
                               2649                 :                :          */
                               2650                 :                :     }
                               2651                 :                : 
                               2652                 :                :     /* We're done with inserting all tuples, so release the last vmbuffer. */
 2016 tomas.vondra@postgre     2653         [ +  + ]:         487172 :     if (vmbuffer != InvalidBuffer)
                               2654                 :           7071 :         ReleaseBuffer(vmbuffer);
                               2655                 :                : 
                               2656                 :                :     /*
                               2657                 :                :      * We're done with the actual inserts.  Check for conflicts again, to
                               2658                 :                :      * ensure that all rw-conflicts in to these inserts are detected.  Without
                               2659                 :                :      * this final check, a sequential scan of the heap may have locked the
                               2660                 :                :      * table after the "before" check, missing one opportunity to detect the
                               2661                 :                :      * conflict, and then scanned the table before the new tuples were there,
                               2662                 :                :      * missing the other chance to detect the conflict.
                               2663                 :                :      *
                               2664                 :                :      * For heap inserts, we only need to check for table-level SSI locks. Our
                               2665                 :                :      * new tuples can't possibly conflict with existing tuple locks, and heap
                               2666                 :                :      * page locks are only consolidated versions of tuple locks; they do not
                               2667                 :                :      * lock "gaps" as index page locks do.  So we don't need to specify a
                               2668                 :                :      * buffer when making the call.
                               2669                 :                :      */
 2371 tmunro@postgresql.or     2670                 :         487172 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
                               2671                 :                : 
                               2672                 :                :     /*
                               2673                 :                :      * If tuples are cacheable, mark them for invalidation from the caches in
                               2674                 :                :      * case we abort.  Note it is OK to do this after releasing the buffer,
                               2675                 :                :      * because the heaptuples data structure is all in local memory, not in
                               2676                 :                :      * the shared buffer.
                               2677                 :                :      */
 4623 rhaas@postgresql.org     2678         [ +  + ]:         487172 :     if (IsCatalogRelation(relation))
                               2679                 :                :     {
 5373 heikki.linnakangas@i     2680         [ +  + ]:        1609677 :         for (i = 0; i < ntuples; i++)
                               2681                 :        1123975 :             CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
                               2682                 :                :     }
                               2683                 :                : 
                               2684                 :                :     /* copy t_self fields back to the caller's slots */
 5277                          2685         [ +  + ]:        2328400 :     for (i = 0; i < ntuples; i++)
 2670 andres@anarazel.de       2686                 :        1841228 :         slots[i]->tts_tid = heaptuples[i]->t_self;
                               2687                 :                : 
 5373 heikki.linnakangas@i     2688                 :         487172 :     pgstat_count_heap_insert(relation, ntuples);
                               2689                 :         487172 : }
                               2690                 :                : 
                               2691                 :                : /*
                               2692                 :                :  *  simple_heap_insert - insert a tuple
                               2693                 :                :  *
                               2694                 :                :  * Currently, this routine differs from heap_insert only in supplying
                               2695                 :                :  * a default command ID and not allowing access to the speedup options.
                               2696                 :                :  *
                               2697                 :                :  * This should be used rather than using heap_insert directly in most places
                               2698                 :                :  * where we are modifying system catalogs.
                               2699                 :                :  */
                               2700                 :                : void
 8832 tgl@sss.pgh.pa.us        2701                 :        1075201 : simple_heap_insert(Relation relation, HeapTuple tup)
                               2702                 :                : {
 2805 andres@anarazel.de       2703                 :        1075201 :     heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
 8832 tgl@sss.pgh.pa.us        2704                 :        1075201 : }
                               2705                 :                : 
                               2706                 :                : /*
                               2707                 :                :  * Given infomask/infomask2, compute the bits that must be saved in the
                               2708                 :                :  * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
                               2709                 :                :  * xl_heap_lock_updated WAL records.
                               2710                 :                :  *
                               2711                 :                :  * See fix_infomask_from_infobits.
                               2712                 :                :  */
                               2713                 :                : static uint8
 4932 alvherre@alvh.no-ip.     2714                 :        6513470 : compute_infobits(uint16 infomask, uint16 infomask2)
                               2715                 :                : {
                               2716                 :                :     return
                               2717                 :        6513470 :         ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
                               2718                 :        6513470 :         ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
                               2719                 :        6513470 :         ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
                               2720                 :                :     /* note we ignore HEAP_XMAX_SHR_LOCK here */
                               2721                 :       13026940 :         ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
                               2722                 :                :         ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
                               2723                 :        6513470 :          XLHL_KEYS_UPDATED : 0);
                               2724                 :                : }
                               2725                 :                : 
                               2726                 :                : /*
                               2727                 :                :  * Given two versions of the same t_infomask for a tuple, compare them and
                               2728                 :                :  * return whether the relevant status for a tuple Xmax has changed.  This is
                               2729                 :                :  * used after a buffer lock has been released and reacquired: we want to ensure
                               2730                 :                :  * that the tuple state continues to be the same it was when we previously
                               2731                 :                :  * examined it.
                               2732                 :                :  *
                               2733                 :                :  * Note the Xmax field itself must be compared separately.
                               2734                 :                :  */
                               2735                 :                : static inline bool
 4476                          2736                 :           5452 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
                               2737                 :                : {
 4464 bruce@momjian.us         2738                 :           5452 :     const uint16 interesting =
                               2739                 :                :         HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
                               2740                 :                : 
 4476 alvherre@alvh.no-ip.     2741         [ +  + ]:           5452 :     if ((new_infomask & interesting) != (old_infomask & interesting))
                               2742                 :             15 :         return true;
                               2743                 :                : 
                               2744                 :           5437 :     return false;
                               2745                 :                : }
                               2746                 :                : 
                               2747                 :                : /*
                               2748                 :                :  *  heap_delete - delete a tuple
                               2749                 :                :  *
                               2750                 :                :  * See table_tuple_delete() for an explanation of the parameters, except that
                               2751                 :                :  * this routine directly takes a tuple rather than a slot.
                               2752                 :                :  *
                               2753                 :                :  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
                               2754                 :                :  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
                               2755                 :                :  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
                               2756                 :                :  * generated by another transaction).
                               2757                 :                :  */
                               2758                 :                : TM_Result
  269 peter@eisentraut.org     2759                 :        1865984 : heap_delete(Relation relation, const ItemPointerData *tid,
                               2760                 :                :             CommandId cid, uint32 options, Snapshot crosscheck,
                               2761                 :                :             bool wait, TM_FailureData *tmfd)
                               2762                 :                : {
                               2763                 :                :     TM_Result   result;
 7983 tgl@sss.pgh.pa.us        2764                 :        1865984 :     TransactionId xid = GetCurrentTransactionId();
                               2765                 :                :     ItemId      lp;
                               2766                 :                :     HeapTupleData tp;
                               2767                 :                :     Page        page;
                               2768                 :                :     BlockNumber block;
                               2769                 :                :     Buffer      buffer;
 5514 rhaas@postgresql.org     2770                 :        1865984 :     Buffer      vmbuffer = InvalidBuffer;
   11 melanieplageman@gmai     2771                 :        1865984 :     bool        vmbuffer_modified = false;
                               2772                 :                :     TransactionId new_xmax;
                               2773                 :                :     uint16      new_infomask,
                               2774                 :                :                 new_infomask2;
  116 alvherre@kurilemu.de     2775                 :        1865984 :     bool        changingPart = (options & TABLE_DELETE_CHANGING_PARTITION) != 0;
  111                          2776                 :        1865984 :     bool        walLogical = (options & TABLE_DELETE_NO_LOGICAL) == 0;
 7757 tgl@sss.pgh.pa.us        2777                 :        1865984 :     bool        have_tuple_lock = false;
                               2778                 :                :     bool        iscombo;
   11 melanieplageman@gmai     2779                 :        1865984 :     bool        clear_all_visible = false;
 4464 bruce@momjian.us         2780                 :        1865984 :     HeapTuple   old_key_tuple = NULL;   /* replica identity of the tuple */
 4611 rhaas@postgresql.org     2781                 :        1865984 :     bool        old_key_copied = false;
                               2782                 :                : 
10549 bruce@momjian.us         2783         [ -  + ]:        1865984 :     Assert(ItemPointerIsValid(tid));
                               2784                 :                : 
  422 nathan@postgresql.or     2785                 :        1865984 :     AssertHasSnapshotForToast(relation);
                               2786                 :                : 
                               2787                 :                :     /*
                               2788                 :                :      * Forbid this during a parallel operation, lest it allocate a combo CID.
                               2789                 :                :      * Other workers might need that combo CID for visibility checks, and we
                               2790                 :                :      * have no provision for broadcasting it to them.
                               2791                 :                :      */
 4105 rhaas@postgresql.org     2792         [ -  + ]:        1865984 :     if (IsInParallelMode())
 4105 rhaas@postgresql.org     2793         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2794                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               2795                 :                :                  errmsg("cannot delete tuples during a parallel operation")));
                               2796                 :                : 
 5514 rhaas@postgresql.org     2797                 :CBC     1865984 :     block = ItemPointerGetBlockNumber(tid);
                               2798                 :        1865984 :     buffer = ReadBuffer(relation, block);
 3749 kgrittn@postgresql.o     2799                 :        1865984 :     page = BufferGetPage(buffer);
                               2800                 :                : 
                               2801                 :                :     /*
                               2802                 :                :      * Before locking the buffer, pin the visibility map page if it appears to
                               2803                 :                :      * be necessary.  Since we haven't got the lock yet, someone else might be
                               2804                 :                :      * in the middle of changing this, so we'll need to recheck after we have
                               2805                 :                :      * the lock.
                               2806                 :                :      */
 5514 rhaas@postgresql.org     2807         [ +  + ]:        1865984 :     if (PageIsAllVisible(page))
                               2808                 :           1964 :         visibilitymap_pin(relation, block, &vmbuffer);
                               2809                 :                : 
10085 vadim4o@yahoo.com        2810                 :        1865984 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2811                 :                : 
 1403 jdavis@postgresql.or     2812                 :        1865984 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
                               2813         [ -  + ]:        1865984 :     Assert(ItemIdIsNormal(lp));
                               2814                 :                : 
                               2815                 :        1865984 :     tp.t_tableOid = RelationGetRelid(relation);
                               2816                 :        1865984 :     tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
                               2817                 :        1865984 :     tp.t_len = ItemIdGetLength(lp);
                               2818                 :        1865984 :     tp.t_self = *tid;
                               2819                 :                : 
                               2820                 :              1 : l1:
                               2821                 :                : 
                               2822                 :                :     /*
                               2823                 :                :      * If we didn't pin the visibility map page and the page has become all
                               2824                 :                :      * visible while we were busy locking the buffer, we'll have to unlock and
                               2825                 :                :      * re-lock, to avoid holding the buffer lock across an I/O.  That's a bit
                               2826                 :                :      * unfortunate, but hopefully shouldn't happen often.
                               2827                 :                :      */
 5514 rhaas@postgresql.org     2828   [ +  +  -  + ]:        1865985 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
                               2829                 :                :     {
 5514 rhaas@postgresql.org     2830                 :UBC           0 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               2831                 :              0 :         visibilitymap_pin(relation, block, &vmbuffer);
                               2832                 :              0 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2833                 :                :     }
                               2834                 :                : 
 4752 rhaas@postgresql.org     2835                 :CBC     1865985 :     result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
                               2836                 :                : 
 2682 andres@anarazel.de       2837         [ -  + ]:        1865985 :     if (result == TM_Invisible)
                               2838                 :                :     {
 7422 tgl@sss.pgh.pa.us        2839                 :UBC           0 :         UnlockReleaseBuffer(buffer);
 4011                          2840         [ #  # ]:              0 :         ereport(ERROR,
                               2841                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               2842                 :                :                  errmsg("attempted to delete invisible tuple")));
                               2843                 :                :     }
  836 akorotkov@postgresql     2844   [ +  +  +  - ]:CBC     1865985 :     else if (result == TM_BeingModified && wait)
                               2845                 :                :     {
                               2846                 :                :         TransactionId xwait;
                               2847                 :                :         uint16      infomask;
                               2848                 :                : 
                               2849                 :                :         /* must copy state data before unlocking buffer */
 4932 alvherre@alvh.no-ip.     2850                 :          40671 :         xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
 7757 tgl@sss.pgh.pa.us        2851                 :          40671 :         infomask = tp.t_data->t_infomask;
                               2852                 :                : 
                               2853                 :                :         /*
                               2854                 :                :          * Sleep until concurrent transaction ends -- except when there's a
                               2855                 :                :          * single locker and it's our own transaction.  Note we don't care
                               2856                 :                :          * which lock mode the locker has, because we need the strongest one.
                               2857                 :                :          *
                               2858                 :                :          * Before sleeping, we need to acquire tuple lock to establish our
                               2859                 :                :          * priority for the tuple (see heap_lock_tuple).  LockTuple will
                               2860                 :                :          * release us when we are next-in-line for the tuple.
                               2861                 :                :          *
                               2862                 :                :          * If we are forced to "start over" below, we keep the tuple lock;
                               2863                 :                :          * this arranges that we stay at the head of the line while rechecking
                               2864                 :                :          * tuple state.
                               2865                 :                :          */
 7759                          2866         [ +  + ]:          40671 :         if (infomask & HEAP_XMAX_IS_MULTI)
                               2867                 :                :         {
 2595 alvherre@alvh.no-ip.     2868                 :              8 :             bool        current_is_member = false;
                               2869                 :                : 
 4125                          2870         [ +  - ]:              8 :             if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
                               2871                 :                :                                         LockTupleExclusive, &current_is_member))
                               2872                 :                :             {
                               2873                 :              8 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               2874                 :                : 
                               2875                 :                :                 /*
                               2876                 :                :                  * Acquire the lock, if necessary (but skip it when we're
                               2877                 :                :                  * requesting a lock and already have one; avoids deadlock).
                               2878                 :                :                  */
 2595                          2879         [ +  + ]:              8 :                 if (!current_is_member)
                               2880                 :              6 :                     heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
                               2881                 :                :                                          LockWaitBlock, &have_tuple_lock);
                               2882                 :                : 
                               2883                 :                :                 /* wait for multixact */
 4125                          2884                 :              8 :                 MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
                               2885                 :                :                                 relation, &(tp.t_self), XLTW_Delete,
                               2886                 :                :                                 NULL);
                               2887                 :              8 :                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2888                 :                : 
                               2889                 :                :                 /*
                               2890                 :                :                  * If xwait had just locked the tuple then some other xact
                               2891                 :                :                  * could update this tuple before we get to this point.  Check
                               2892                 :                :                  * for xmax change, and start over if so.
                               2893                 :                :                  *
                               2894                 :                :                  * We also must start over if we didn't pin the VM page, and
                               2895                 :                :                  * the page has become all visible.
                               2896                 :                :                  */
 1403 jdavis@postgresql.or     2897   [ +  -  +  -  :             16 :                 if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
                                              +  - ]
                               2898         [ -  + ]:             16 :                     xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
 4125 alvherre@alvh.no-ip.     2899                 :              8 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
                               2900                 :                :                                          xwait))
 4125 alvherre@alvh.no-ip.     2901                 :UBC           0 :                     goto l1;
                               2902                 :                :             }
                               2903                 :                : 
                               2904                 :                :             /*
                               2905                 :                :              * You might think the multixact is necessarily done here, but not
                               2906                 :                :              * so: it could have surviving members, namely our own xact or
                               2907                 :                :              * other subxacts of this backend.  It is legal for us to delete
                               2908                 :                :              * the tuple in either case, however (the latter case is
                               2909                 :                :              * essentially a situation of upgrading our former shared lock to
                               2910                 :                :              * exclusive).  We don't bother changing the on-disk hint bits
                               2911                 :                :              * since we are about to overwrite the xmax altogether.
                               2912                 :                :              */
                               2913                 :                :         }
 4125 alvherre@alvh.no-ip.     2914         [ +  + ]:CBC       40663 :         else if (!TransactionIdIsCurrentTransactionId(xwait))
                               2915                 :                :         {
                               2916                 :                :             /*
                               2917                 :                :              * Wait for regular transaction to end; but first, acquire tuple
                               2918                 :                :              * lock.
                               2919                 :                :              */
                               2920                 :             71 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               2921                 :             71 :             heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
                               2922                 :                :                                  LockWaitBlock, &have_tuple_lock);
 4190 heikki.linnakangas@i     2923                 :             71 :             XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
 7759 tgl@sss.pgh.pa.us        2924                 :             67 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2925                 :                : 
                               2926                 :                :             /*
                               2927                 :                :              * xwait is done, but if xwait had just locked the tuple then some
                               2928                 :                :              * other xact could update this tuple before we get to this point.
                               2929                 :                :              * Check for xmax change, and start over if so.
                               2930                 :                :              *
                               2931                 :                :              * We also must start over if we didn't pin the VM page, and the
                               2932                 :                :              * page has become all visible.
                               2933                 :                :              */
 1403 jdavis@postgresql.or     2934   [ +  -  +  -  :            134 :             if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
                                              +  + ]
                               2935         [ -  + ]:            133 :                 xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
 4932 alvherre@alvh.no-ip.     2936                 :             66 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
                               2937                 :                :                                      xwait))
 7759 tgl@sss.pgh.pa.us        2938                 :              1 :                 goto l1;
                               2939                 :                : 
                               2940                 :                :             /* Otherwise check if it committed or aborted */
 6921                          2941                 :             66 :             UpdateXmaxHintBits(tp.t_data, buffer, xwait);
                               2942                 :                :         }
                               2943                 :                : 
                               2944                 :                :         /*
                               2945                 :                :          * We may overwrite if previous xmax aborted, or if it committed but
                               2946                 :                :          * only locked the tuple without updating it.
                               2947                 :                :          */
 4932 alvherre@alvh.no-ip.     2948   [ +  +  +  + ]:          81312 :         if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
                               2949         [ +  + ]:          40696 :             HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
                               2950                 :             50 :             HeapTupleHeaderIsOnlyLocked(tp.t_data))
 2682 andres@anarazel.de       2951                 :          40620 :             result = TM_Ok;
 1980 alvherre@alvh.no-ip.     2952         [ +  + ]:             46 :         else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
 2682 andres@anarazel.de       2953                 :             33 :             result = TM_Updated;
                               2954                 :                :         else
                               2955                 :             13 :             result = TM_Deleted;
                               2956                 :                :     }
                               2957                 :                : 
                               2958                 :                :     /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
                               2959         [ +  + ]:        1865980 :     if (result != TM_Ok)
                               2960                 :                :     {
                               2961   [ +  +  +  +  :            101 :         Assert(result == TM_SelfModified ||
                                        -  +  -  - ]
                               2962                 :                :                result == TM_Updated ||
                               2963                 :                :                result == TM_Deleted ||
                               2964                 :                :                result == TM_BeingModified);
 7645 tgl@sss.pgh.pa.us        2965         [ -  + ]:            101 :         Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
 2682 andres@anarazel.de       2966   [ +  +  -  + ]:            101 :         Assert(result != TM_Updated ||
                               2967                 :                :                !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
                               2968                 :                :     }
                               2969                 :                : 
  971 heikki.linnakangas@i     2970   [ +  +  +  - ]:        1865980 :     if (crosscheck != InvalidSnapshot && result == TM_Ok)
                               2971                 :                :     {
                               2972                 :                :         /* Perform additional check for transaction-snapshot mode RI updates */
                               2973         [ +  - ]:              1 :         if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
                               2974                 :              1 :             result = TM_Updated;
                               2975                 :                :     }
                               2976                 :                : 
                               2977         [ +  + ]:        1865980 :     if (result != TM_Ok)
                               2978                 :                :     {
 2682 andres@anarazel.de       2979                 :            102 :         tmfd->ctid = tp.t_data->t_ctid;
                               2980                 :            102 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
                               2981         [ +  + ]:            102 :         if (result == TM_SelfModified)
                               2982                 :             36 :             tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
                               2983                 :                :         else
                               2984                 :             66 :             tmfd->cmax = InvalidCommandId;
  836 akorotkov@postgresql     2985                 :            102 :         UnlockReleaseBuffer(buffer);
 7757 tgl@sss.pgh.pa.us        2986         [ +  + ]:            102 :         if (have_tuple_lock)
 4932 alvherre@alvh.no-ip.     2987                 :             46 :             UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
 5514 rhaas@postgresql.org     2988         [ -  + ]:            102 :         if (vmbuffer != InvalidBuffer)
 5514 rhaas@postgresql.org     2989                 :UBC           0 :             ReleaseBuffer(vmbuffer);
10085 vadim4o@yahoo.com        2990                 :CBC         102 :         return result;
                               2991                 :                :     }
                               2992                 :                : 
                               2993                 :                :     /*
                               2994                 :                :      * We're about to do the actual delete -- check for conflict first, to
                               2995                 :                :      * avoid possibly having to roll back work we've just done.
                               2996                 :                :      *
                               2997                 :                :      * This is safe without a recheck as long as there is no possibility of
                               2998                 :                :      * another process scanning the page between this check and the delete
                               2999                 :                :      * being visible to the scan (i.e., an exclusive buffer content lock is
                               3000                 :                :      * continuously held from this point until the tuple delete is visible).
                               3001                 :                :      */
 2371 tmunro@postgresql.or     3002                 :        1865878 :     CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
                               3003                 :                : 
                               3004                 :                :     /* replace cid with a combo CID if necessary */
 7107 tgl@sss.pgh.pa.us        3005                 :        1865864 :     HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
                               3006                 :                : 
                               3007                 :                :     /*
                               3008                 :                :      * Compute replica identity tuple before entering the critical section so
                               3009                 :                :      * we don't PANIC upon a memory allocation failure.
                               3010                 :                :      */
  111 alvherre@kurilemu.de     3011                 :        1865864 :     old_key_tuple = walLogical ?
                               3012         [ +  + ]:        1865864 :         ExtractReplicaIdentity(relation, &tp, true, &old_key_copied) : NULL;
                               3013                 :                : 
                               3014                 :                :     /*
                               3015                 :                :      * If this is the first possibly-multixact-able operation in the current
                               3016                 :                :      * transaction, set my per-backend OldestMemberMXactId setting. We can be
                               3017                 :                :      * certain that the transaction will never become a member of any older
                               3018                 :                :      * MultiXactIds than that.  (We have to do this even if we end up just
                               3019                 :                :      * using our own TransactionId below, since some other backend could
                               3020                 :                :      * incorporate our XID into a MultiXact immediately afterwards.)
                               3021                 :                :      */
 4496 heikki.linnakangas@i     3022                 :        1865864 :     MultiXactIdSetOldestMember();
                               3023                 :                : 
                               3024                 :        1865864 :     compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
                               3025                 :        1865864 :                               tp.t_data->t_infomask, tp.t_data->t_infomask2,
                               3026                 :                :                               xid, LockTupleExclusive, true,
                               3027                 :                :                               &new_xmax, &new_infomask, &new_infomask2);
                               3028                 :                : 
                               3029                 :                :     /* Lock the VM before entering the critical section */
   11 melanieplageman@gmai     3030         [ +  + ]:        1865864 :     if (PageIsAllVisible(page))
                               3031                 :                :     {
                               3032                 :           1964 :         clear_all_visible = true;
                               3033                 :           1964 :         LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
                               3034                 :                :     }
                               3035                 :                : 
 9326 tgl@sss.pgh.pa.us        3036                 :        1865864 :     START_CRIT_SECTION();
                               3037                 :                : 
                               3038                 :                :     /*
                               3039                 :                :      * If this transaction commits, the tuple will become DEAD sooner or
                               3040                 :                :      * later.  Set flag that this page is a candidate for pruning once our xid
                               3041                 :                :      * falls below the OldestXmin horizon.  If the transaction finally aborts,
                               3042                 :                :      * the subsequent page pruning will be a no-op and the hint will be
                               3043                 :                :      * cleared.
                               3044                 :                :      */
 6587                          3045   [ -  +  +  +  :        1865864 :     PageSetPrunable(page, xid);
                                              +  + ]
                               3046                 :                : 
   11 melanieplageman@gmai     3047         [ +  + ]:        1865864 :     if (clear_all_visible)
                               3048                 :                :     {
                               3049                 :                :         /* It's possible the VM bits were already clear */
   11 melanieplageman@gmai     3050         [ +  - ]:GNC        1964 :         if (visibilitymap_clear(relation->rd_locator, BufferGetBlockNumber(buffer),
                               3051                 :                :                                 vmbuffer, VISIBILITYMAP_VALID_BITS))
   11 melanieplageman@gmai     3052                 :CBC        1964 :             vmbuffer_modified = true;
                               3053                 :                : 
 6444 heikki.linnakangas@i     3054                 :           1964 :         PageClearAllVisible(page);
                               3055                 :                :     }
                               3056                 :                : 
                               3057                 :                :     /* store transaction information of xact deleting the tuple */
 4932 alvherre@alvh.no-ip.     3058                 :        1865864 :     tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               3059                 :        1865864 :     tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               3060                 :        1865864 :     tp.t_data->t_infomask |= new_infomask;
                               3061                 :        1865864 :     tp.t_data->t_infomask2 |= new_infomask2;
 6884 tgl@sss.pgh.pa.us        3062                 :        1865864 :     HeapTupleHeaderClearHotUpdated(tp.t_data);
 4932 alvherre@alvh.no-ip.     3063                 :        1865864 :     HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
 7107 tgl@sss.pgh.pa.us        3064                 :        1865864 :     HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
                               3065                 :                :     /* Make sure there is no forward chain link in t_ctid */
 8748                          3066                 :        1865864 :     tp.t_data->t_ctid = tp.t_self;
                               3067                 :                : 
                               3068                 :                :     /* Signal that this is actually a move into another partition */
 3032 andres@anarazel.de       3069         [ +  + ]:        1865864 :     if (changingPart)
                               3070                 :            666 :         HeapTupleHeaderSetMovedPartitions(tp.t_data);
                               3071                 :                : 
 7422 tgl@sss.pgh.pa.us        3072                 :        1865864 :     MarkBufferDirty(buffer);
                               3073                 :                : 
                               3074                 :                :     /*
                               3075                 :                :      * XLOG stuff
                               3076                 :                :      *
                               3077                 :                :      * NB: heap_abort_speculative() uses the same xlog record and replay
                               3078                 :                :      * routines.
                               3079                 :                :      */
 5704 rhaas@postgresql.org     3080   [ +  +  +  +  :        1865864 :     if (RelationNeedsWAL(relation))
                                        +  -  +  + ]
                               3081                 :                :     {
                               3082                 :                :         xl_heap_delete xlrec;
                               3083                 :                :         xl_heap_header xlhdr;
                               3084                 :                :         XLogRecPtr  recptr;
                               3085                 :                : 
                               3086                 :                :         /*
                               3087                 :                :          * For logical decode we need combo CIDs to properly decode the
                               3088                 :                :          * catalog
                               3089                 :                :          */
 4611                          3090   [ +  +  +  +  :        1782617 :         if (RelationIsAccessibleInLogicalDecoding(relation))
                                     +  -  -  +  -  
                                     -  -  -  +  +  
                                     +  +  -  +  -  
                                           -  -  + ]
                               3091                 :           6967 :             log_heap_new_cid(relation, &tp);
                               3092                 :                : 
 3032 andres@anarazel.de       3093                 :        1782617 :         xlrec.flags = 0;
   11 melanieplageman@gmai     3094         [ +  + ]:        1782617 :         if (clear_all_visible)
 3032 andres@anarazel.de       3095                 :           1964 :             xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
                               3096         [ +  + ]:        1782617 :         if (changingPart)
                               3097                 :            666 :             xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
 4932 alvherre@alvh.no-ip.     3098                 :        3565234 :         xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
                               3099                 :        1782617 :                                               tp.t_data->t_infomask2);
 4266 heikki.linnakangas@i     3100                 :        1782617 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
 4932 alvherre@alvh.no-ip.     3101                 :        1782617 :         xlrec.xmax = new_xmax;
                               3102                 :                : 
 4266 heikki.linnakangas@i     3103         [ +  + ]:        1782617 :         if (old_key_tuple != NULL)
                               3104                 :                :         {
                               3105         [ +  + ]:          47028 :             if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
 4097 andres@anarazel.de       3106                 :            135 :                 xlrec.flags |= XLH_DELETE_CONTAINS_OLD_TUPLE;
                               3107                 :                :             else
                               3108                 :          46893 :                 xlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;
                               3109                 :                :         }
                               3110                 :                : 
                               3111                 :                :         /*
                               3112                 :                :          * Mark the change as not-for-logical-decoding if caller requested so.
                               3113                 :                :          *
                               3114                 :                :          * (This is used for changes that affect relations not visible to
                               3115                 :                :          * other transactions, such as the transient table during concurrent
                               3116                 :                :          * repack.)
                               3117                 :                :          */
  111 alvherre@kurilemu.de     3118         [ +  + ]:        1782617 :         if (!walLogical)
                               3119                 :              3 :             xlrec.flags |= XLH_DELETE_NO_LOGICAL;
                               3120                 :                : 
 4266 heikki.linnakangas@i     3121                 :        1782617 :         XLogBeginInsert();
  530 peter@eisentraut.org     3122                 :        1782617 :         XLogRegisterData(&xlrec, SizeOfHeapDelete);
                               3123                 :                : 
   11 melanieplageman@gmai     3124                 :        1782617 :         XLogRegisterBuffer(HEAP_DELETE_BLKREF_HEAP, buffer, REGBUF_STANDARD);
                               3125                 :                : 
                               3126                 :                :         /*
                               3127                 :                :          * Log replica identity of the deleted tuple if there is one
                               3128                 :                :          */
 4611 rhaas@postgresql.org     3129         [ +  + ]:        1782617 :         if (old_key_tuple != NULL)
                               3130                 :                :         {
                               3131                 :          47028 :             xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
                               3132                 :          47028 :             xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
                               3133                 :          47028 :             xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
                               3134                 :                : 
  530 peter@eisentraut.org     3135                 :          47028 :             XLogRegisterData(&xlhdr, SizeOfHeapHeader);
 4266 heikki.linnakangas@i     3136                 :          47028 :             XLogRegisterData((char *) old_key_tuple->t_data
                               3137                 :                :                              + SizeofHeapTupleHeader,
                               3138                 :          47028 :                              old_key_tuple->t_len
                               3139                 :                :                              - SizeofHeapTupleHeader);
                               3140                 :                :         }
                               3141                 :                : 
                               3142                 :                :         /* filtering by origin on a row level is much more efficient */
 3503 andres@anarazel.de       3143                 :        1782617 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               3144                 :                : 
   11 melanieplageman@gmai     3145         [ +  + ]:        1782617 :         if (vmbuffer_modified)
                               3146                 :           1964 :             XLogRegisterBuffer(HEAP_DELETE_BLKREF_VM, vmbuffer, 0);
                               3147                 :                : 
 4266 heikki.linnakangas@i     3148                 :        1782617 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
                               3149                 :                : 
 6587 tgl@sss.pgh.pa.us        3150                 :        1782617 :         PageSetLSN(page, recptr);
                               3151                 :                : 
   11 melanieplageman@gmai     3152         [ +  + ]:        1782617 :         if (vmbuffer_modified)
                               3153                 :           1964 :             PageSetLSN(BufferGetPage(vmbuffer), recptr);
                               3154                 :                :     }
                               3155                 :                : 
 9326 tgl@sss.pgh.pa.us        3156         [ -  + ]:        1865864 :     END_CRIT_SECTION();
                               3157                 :                : 
                               3158                 :                :     /*
                               3159                 :                :      * Release VM lock first, since it covers many heap blocks. We locked
                               3160                 :                :      * vmbuffer if clear_all_visible was true regardless of whether or not we
                               3161                 :                :      * ended up modifying the vmbuffer.
                               3162                 :                :      */
   11 melanieplageman@gmai     3163         [ +  + ]:        1865864 :     if (clear_all_visible)
                               3164                 :           1964 :         LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
                               3165                 :                : 
 9323 tgl@sss.pgh.pa.us        3166                 :        1865864 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               3167                 :                : 
 5514 rhaas@postgresql.org     3168         [ +  + ]:        1865864 :     if (vmbuffer != InvalidBuffer)
                               3169                 :           1964 :         ReleaseBuffer(vmbuffer);
                               3170                 :                : 
                               3171                 :                :     /*
                               3172                 :                :      * If the tuple has toasted out-of-line attributes, we need to delete
                               3173                 :                :      * those items too.  We have to do this before releasing the buffer
                               3174                 :                :      * because we need to look at the contents of the tuple, but it's OK to
                               3175                 :                :      * release the content lock on the buffer first.
                               3176                 :                :      */
 4893 kgrittn@postgresql.o     3177         [ +  + ]:        1865864 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
                               3178         [ +  + ]:           4016 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
                               3179                 :                :     {
                               3180                 :                :         /* toast table entries should never be recursively toasted */
 7054 tgl@sss.pgh.pa.us        3181         [ -  + ]:           4003 :         Assert(!HeapTupleHasExternal(&tp));
                               3182                 :                :     }
                               3183         [ +  + ]:        1861861 :     else if (HeapTupleHasExternal(&tp))
 2487 rhaas@postgresql.org     3184                 :            546 :         heap_toast_delete(relation, &tp, false);
                               3185                 :                : 
                               3186                 :                :     /*
                               3187                 :                :      * Mark tuple for invalidation from system caches at next command
                               3188                 :                :      * boundary. We have to do this before releasing the buffer because we
                               3189                 :                :      * need to look at the contents of the tuple.
                               3190                 :                :      */
 5458 tgl@sss.pgh.pa.us        3191                 :        1865864 :     CacheInvalidateHeapTuple(relation, &tp, NULL);
                               3192                 :                : 
                               3193                 :                :     /* Now we can release the buffer */
  836 akorotkov@postgresql     3194                 :        1865864 :     ReleaseBuffer(buffer);
                               3195                 :                : 
                               3196                 :                :     /*
                               3197                 :                :      * Release the lmgr tuple lock, if we had it.
                               3198                 :                :      */
 7757 tgl@sss.pgh.pa.us        3199         [ +  + ]:        1865864 :     if (have_tuple_lock)
 4932 alvherre@alvh.no-ip.     3200                 :             26 :         UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
                               3201                 :                : 
 7000 tgl@sss.pgh.pa.us        3202                 :        1865864 :     pgstat_count_heap_delete(relation);
                               3203                 :                : 
 4611 rhaas@postgresql.org     3204   [ +  +  +  + ]:        1865864 :     if (old_key_tuple != NULL && old_key_copied)
                               3205                 :          46894 :         heap_freetuple(old_key_tuple);
                               3206                 :                : 
 2682 andres@anarazel.de       3207                 :        1865864 :     return TM_Ok;
                               3208                 :                : }
                               3209                 :                : 
                               3210                 :                : /*
                               3211                 :                :  *  simple_heap_delete - delete a tuple
                               3212                 :                :  *
                               3213                 :                :  * This routine may be used to delete a tuple when concurrent updates of
                               3214                 :                :  * the target tuple are not expected (for example, because we have a lock
                               3215                 :                :  * on the relation associated with the tuple).  Any failure is reported
                               3216                 :                :  * via ereport().
                               3217                 :                :  */
                               3218                 :                : void
  269 peter@eisentraut.org     3219                 :         838251 : simple_heap_delete(Relation relation, const ItemPointerData *tid)
                               3220                 :                : {
                               3221                 :                :     TM_Result   result;
                               3222                 :                :     TM_FailureData tmfd;
                               3223                 :                : 
 8350 tgl@sss.pgh.pa.us        3224                 :         838251 :     result = heap_delete(relation, tid,
                               3225                 :                :                          GetCurrentCommandId(true),
                               3226                 :                :                          0,
                               3227                 :                :                          InvalidSnapshot,
                               3228                 :                :                          true /* wait for commit */ ,
                               3229                 :                :                          &tmfd);
 9315                          3230   [ -  +  -  -  :         838251 :     switch (result)
                                                 - ]
                               3231                 :                :     {
 2682 andres@anarazel.de       3232                 :UBC           0 :         case TM_SelfModified:
                               3233                 :                :             /* Tuple was already updated in current command? */
 8406 tgl@sss.pgh.pa.us        3234         [ #  # ]:              0 :             elog(ERROR, "tuple already updated by self");
                               3235                 :                :             break;
                               3236                 :                : 
 2682 andres@anarazel.de       3237                 :CBC      838251 :         case TM_Ok:
                               3238                 :                :             /* done successfully */
 9315 tgl@sss.pgh.pa.us        3239                 :         838251 :             break;
                               3240                 :                : 
 2682 andres@anarazel.de       3241                 :UBC           0 :         case TM_Updated:
 8406 tgl@sss.pgh.pa.us        3242         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently updated");
                               3243                 :                :             break;
                               3244                 :                : 
 2682 andres@anarazel.de       3245                 :              0 :         case TM_Deleted:
                               3246         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently deleted");
                               3247                 :                :             break;
                               3248                 :                : 
 9315 tgl@sss.pgh.pa.us        3249                 :              0 :         default:
 8406                          3250         [ #  # ]:              0 :             elog(ERROR, "unrecognized heap_delete status: %u", result);
                               3251                 :                :             break;
                               3252                 :                :     }
 9315 tgl@sss.pgh.pa.us        3253                 :CBC      838251 : }
                               3254                 :                : 
                               3255                 :                : /*
                               3256                 :                :  *  heap_update - replace a tuple
                               3257                 :                :  *
                               3258                 :                :  * See table_tuple_update() for an explanation of the parameters, except that
                               3259                 :                :  * this routine directly takes a tuple rather than a slot.
                               3260                 :                :  *
                               3261                 :                :  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
                               3262                 :                :  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
                               3263                 :                :  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
                               3264                 :                :  * generated by another transaction).
                               3265                 :                :  */
                               3266                 :                : TM_Result
  269 peter@eisentraut.org     3267                 :        2389226 : heap_update(Relation relation, const ItemPointerData *otid, HeapTuple newtup,
                               3268                 :                :             CommandId cid, uint32 options pg_attribute_unused(), Snapshot crosscheck, bool wait,
                               3269                 :                :             TM_FailureData *tmfd, LockTupleMode *lockmode,
                               3270                 :                :             TU_UpdateIndexes *update_indexes)
                               3271                 :                : {
                               3272                 :                :     TM_Result   result;
 7983 tgl@sss.pgh.pa.us        3273                 :        2389226 :     TransactionId xid = GetCurrentTransactionId();
                               3274                 :                :     Bitmapset  *hot_attrs;
                               3275                 :                :     Bitmapset  *sum_attrs;
                               3276                 :                :     Bitmapset  *key_attrs;
                               3277                 :                :     Bitmapset  *id_attrs;
                               3278                 :                :     Bitmapset  *interesting_attrs;
                               3279                 :                :     Bitmapset  *modified_attrs;
                               3280                 :                :     ItemId      lp;
                               3281                 :                :     HeapTupleData oldtup;
                               3282                 :                :     HeapTuple   heaptup;
 4611 rhaas@postgresql.org     3283                 :        2389226 :     HeapTuple   old_key_tuple = NULL;
                               3284                 :        2389226 :     bool        old_key_copied = false;
  111 alvherre@kurilemu.de     3285                 :        2389226 :     bool        walLogical = (options & TABLE_UPDATE_NO_LOGICAL) == 0;
                               3286                 :                :     Page        page,
                               3287                 :                :                 newpage;
                               3288                 :                :     BlockNumber block;
                               3289                 :                :     MultiXactStatus mxact_status;
                               3290                 :                :     Buffer      buffer,
                               3291                 :                :                 newbuf,
 5514 rhaas@postgresql.org     3292                 :        2389226 :                 vmbuffer = InvalidBuffer,
                               3293                 :        2389226 :                 vmbuffer_new = InvalidBuffer;
   11 melanieplageman@gmai     3294                 :        2389226 :     bool        unlock_vmbuffer = false;
                               3295                 :        2389226 :     bool        unlock_vmbuffer_new = false;
                               3296                 :                :     bool        need_toast;
                               3297                 :                :     Size        newtupsize,
                               3298                 :                :                 pagefree;
 7757 tgl@sss.pgh.pa.us        3299                 :        2389226 :     bool        have_tuple_lock = false;
                               3300                 :                :     bool        iscombo;
 6884                          3301                 :        2389226 :     bool        use_hot_update = false;
 1224 tomas.vondra@postgre     3302                 :        2389226 :     bool        summarized_update = false;
                               3303                 :                :     bool        key_intact;
   11 melanieplageman@gmai     3304                 :        2389226 :     bool        clear_all_visible = false;
                               3305                 :        2389226 :     bool        clear_all_visible_new = false;
                               3306                 :        2389226 :     bool        vmbuffer_modified = false;
                               3307                 :        2389226 :     bool        vmbuffer_new_modified = false;
                               3308                 :                :     bool        checked_lockers;
                               3309                 :                :     bool        locker_remains;
 1623 akapila@postgresql.o     3310                 :        2389226 :     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                 :                : 
10549 bruce@momjian.us         3318         [ -  + ]:        2389226 :     Assert(ItemPointerIsValid(otid));
                               3319                 :                : 
                               3320                 :                :     /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
 1903 tgl@sss.pgh.pa.us        3321         [ -  + ]:        2389226 :     Assert(HeapTupleHeaderGetNatts(newtup->t_data) <=
                               3322                 :                :            RelationGetNumberOfAttributes(relation));
                               3323                 :                : 
  422 nathan@postgresql.or     3324                 :        2389226 :     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                 :                :      */
 4105 rhaas@postgresql.org     3331         [ -  + ]:        2389226 :     if (IsInParallelMode())
 4105 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
  670 noah@leadboat.com        3337                 :CBC     2389226 :     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                 :                :      */
 1224 tomas.vondra@postgre     3356                 :        2389226 :     hot_attrs = RelationGetIndexAttrBitmap(relation,
                               3357                 :                :                                            INDEX_ATTR_BITMAP_HOT_BLOCKING);
                               3358                 :        2389226 :     sum_attrs = RelationGetIndexAttrBitmap(relation,
                               3359                 :                :                                            INDEX_ATTR_BITMAP_SUMMARIZED);
 4611 rhaas@postgresql.org     3360                 :        2389226 :     key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
                               3361                 :        2389226 :     id_attrs = RelationGetIndexAttrBitmap(relation,
                               3362                 :                :                                           INDEX_ATTR_BITMAP_IDENTITY_KEY);
 1703 pg@bowt.ie               3363                 :        2389226 :     interesting_attrs = NULL;
                               3364                 :        2389226 :     interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
 1224 tomas.vondra@postgre     3365                 :        2389226 :     interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
 1703 pg@bowt.ie               3366                 :        2389226 :     interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
                               3367                 :        2389226 :     interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
                               3368                 :                : 
 5514 rhaas@postgresql.org     3369                 :        2389226 :     block = ItemPointerGetBlockNumber(otid);
  442 michael@paquier.xyz      3370                 :        2389226 :     INJECTION_POINT("heap_update-before-pin", NULL);
 5514 rhaas@postgresql.org     3371                 :        2389226 :     buffer = ReadBuffer(relation, block);
 3749 kgrittn@postgresql.o     3372                 :        2389226 :     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                 :                :      */
 5514 rhaas@postgresql.org     3380         [ +  + ]:        2389226 :     if (PageIsAllVisible(page))
                               3381                 :           2935 :         visibilitymap_pin(relation, block, &vmbuffer);
                               3382                 :                : 
10085 vadim4o@yahoo.com        3383                 :        2389226 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               3384                 :                : 
 6587 tgl@sss.pgh.pa.us        3385                 :        2389226 :     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                 :                :      */
  547 noah@leadboat.com        3410         [ +  + ]:        2389226 :     if (!ItemIdIsNormal(lp))
                               3411                 :                :     {
                               3412         [ -  + ]:              1 :         Assert(RelationSupportsSysCache(RelationGetRelid(relation)));
                               3413                 :                : 
                               3414                 :              1 :         UnlockReleaseBuffer(buffer);
                               3415         [ -  + ]:              1 :         Assert(!have_tuple_lock);
                               3416         [ +  - ]:              1 :         if (vmbuffer != InvalidBuffer)
                               3417                 :              1 :             ReleaseBuffer(vmbuffer);
                               3418                 :              1 :         tmfd->ctid = *otid;
                               3419                 :              1 :         tmfd->xmax = InvalidTransactionId;
                               3420                 :              1 :         tmfd->cmax = InvalidCommandId;
                               3421                 :              1 :         *update_indexes = TU_None;
                               3422                 :                : 
                               3423                 :              1 :         bms_free(hot_attrs);
                               3424                 :              1 :         bms_free(sum_attrs);
                               3425                 :              1 :         bms_free(key_attrs);
                               3426                 :              1 :         bms_free(id_attrs);
                               3427                 :                :         /* modified_attrs not yet initialized */
                               3428                 :              1 :         bms_free(interesting_attrs);
                               3429                 :              1 :         return TM_Deleted;
                               3430                 :                :     }
                               3431                 :                : 
                               3432                 :                :     /*
                               3433                 :                :      * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
                               3434                 :                :      * properly.
                               3435                 :                :      */
 4923 alvherre@alvh.no-ip.     3436                 :        2389225 :     oldtup.t_tableOid = RelationGetRelid(relation);
 6587 tgl@sss.pgh.pa.us        3437                 :        2389225 :     oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
10103 vadim4o@yahoo.com        3438                 :        2389225 :     oldtup.t_len = ItemIdGetLength(lp);
                               3439                 :        2389225 :     oldtup.t_self = *otid;
                               3440                 :                : 
                               3441                 :                :     /* the new tuple is ready, except for this: */
 4923 alvherre@alvh.no-ip.     3442                 :        2389225 :     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                 :                :      */
 1623 akapila@postgresql.o     3452                 :        2389225 :     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                 :                :      */
 3406 alvherre@alvh.no-ip.     3467         [ +  + ]:        2389225 :     if (!bms_overlap(modified_attrs, key_attrs))
                               3468                 :                :     {
 3027 simon@2ndQuadrant.co     3469                 :        2383292 :         *lockmode = LockTupleNoKeyExclusive;
 4932 alvherre@alvh.no-ip.     3470                 :        2383292 :         mxact_status = MultiXactStatusNoKeyUpdate;
                               3471                 :        2383292 :         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                 :        2383292 :         MultiXactIdSetOldestMember();
                               3483                 :                :     }
                               3484                 :                :     else
                               3485                 :                :     {
 3027 simon@2ndQuadrant.co     3486                 :           5933 :         *lockmode = LockTupleExclusive;
 4932 alvherre@alvh.no-ip.     3487                 :           5933 :         mxact_status = MultiXactStatusUpdate;
                               3488                 :           5933 :         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                 :                : 
10085 vadim4o@yahoo.com        3498                 :              1 : l2:
 4932 alvherre@alvh.no-ip.     3499                 :        2389226 :     checked_lockers = false;
                               3500                 :        2389226 :     locker_remains = false;
 4752 rhaas@postgresql.org     3501                 :        2389226 :     result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
                               3502                 :                : 
                               3503                 :                :     /* see below about the "no wait" case */
  836 akorotkov@postgresql     3504   [ +  +  -  + ]:        2389226 :     Assert(result != TM_BeingModified || wait);
                               3505                 :                : 
 2682 andres@anarazel.de       3506         [ -  + ]:        2389226 :     if (result == TM_Invisible)
                               3507                 :                :     {
 7422 tgl@sss.pgh.pa.us        3508                 :UBC           0 :         UnlockReleaseBuffer(buffer);
 4011                          3509         [ #  # ]:              0 :         ereport(ERROR,
                               3510                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               3511                 :                :                  errmsg("attempted to update invisible tuple")));
                               3512                 :                :     }
  836 akorotkov@postgresql     3513   [ +  +  +  - ]:CBC     2389226 :     else if (result == TM_BeingModified && wait)
                               3514                 :                :     {
                               3515                 :                :         TransactionId xwait;
                               3516                 :                :         uint16      infomask;
 4932 alvherre@alvh.no-ip.     3517                 :          36551 :         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                 :          36551 :         xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
 7757 tgl@sss.pgh.pa.us        3534                 :          36551 :         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                 :                :          */
 7759                          3558         [ +  + ]:          36551 :         if (infomask & HEAP_XMAX_IS_MULTI)
                               3559                 :                :         {
                               3560                 :                :             TransactionId update_xact;
                               3561                 :                :             int         remain;
 2595 alvherre@alvh.no-ip.     3562                 :            179 :             bool        current_is_member = false;
                               3563                 :                : 
 4125                          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                 :                :                  */
 2595                          3573         [ -  + ]:              8 :                 if (!current_is_member)
 2595 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 */
 4125 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) ||
 3322 tgl@sss.pgh.pa.us        3592                 :              8 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
                               3593                 :                :                                          xwait))
 4125 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                 :                :              */
 4932 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
 4125                          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                 :                :              */
 4932                          3627   [ +  +  +  + ]:            187 :             if (!TransactionIdIsValid(update_xact) ||
                               3628                 :              8 :                 TransactionIdDidAbort(update_xact))
                               3629                 :            172 :                 can_continue = true;
                               3630                 :                :         }
 4125                          3631         [ +  + ]:          36372 :         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                 :          36244 :             checked_lockers = true;
                               3638                 :          36244 :             locker_remains = true;
                               3639                 :          36244 :             can_continue = true;
                               3640                 :                :         }
                               3641   [ +  +  +  + ]:            128 :         else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
                               3642                 :                :         {
                               3643                 :                :             /*
                               3644                 :                :              * If it's just a key-share locker, and we're not changing the key
                               3645                 :                :              * columns, we don't need to wait for it to end; but we need to
                               3646                 :                :              * preserve it as locker.
                               3647                 :                :              */
                               3648                 :             29 :             checked_lockers = true;
                               3649                 :             29 :             locker_remains = true;
                               3650                 :             29 :             can_continue = true;
                               3651                 :                :         }
                               3652                 :                :         else
                               3653                 :                :         {
                               3654                 :                :             /*
                               3655                 :                :              * Wait for regular transaction to end; but first, acquire tuple
                               3656                 :                :              * lock.
                               3657                 :                :              */
                               3658                 :             99 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
 3027 simon@2ndQuadrant.co     3659                 :             99 :             heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
                               3660                 :                :                                  LockWaitBlock, &have_tuple_lock);
 4125 alvherre@alvh.no-ip.     3661                 :             99 :             XactLockTableWait(xwait, relation, &oldtup.t_self,
                               3662                 :                :                               XLTW_Update);
                               3663                 :             99 :             checked_lockers = true;
                               3664                 :             99 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               3665                 :                : 
                               3666                 :                :             /*
                               3667                 :                :              * xwait is done, but if xwait had just locked the tuple then some
                               3668                 :                :              * other xact could update this tuple before we get to this point.
                               3669                 :                :              * Check for xmax change, and start over if so.
                               3670                 :                :              */
                               3671   [ +  +  -  + ]:            197 :             if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
                               3672                 :             98 :                 !TransactionIdEquals(xwait,
                               3673                 :                :                                      HeapTupleHeaderGetRawXmax(oldtup.t_data)))
                               3674                 :              1 :                 goto l2;
                               3675                 :                : 
                               3676                 :                :             /* Otherwise check if it committed or aborted */
                               3677                 :             98 :             UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
                               3678         [ +  + ]:             98 :             if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
 4932                          3679                 :             22 :                 can_continue = true;
                               3680                 :                :         }
                               3681                 :                : 
 2682 andres@anarazel.de       3682         [ +  + ]:          36550 :         if (can_continue)
                               3683                 :          36467 :             result = TM_Ok;
 1980 alvherre@alvh.no-ip.     3684         [ +  + ]:             83 :         else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
 2682 andres@anarazel.de       3685                 :             69 :             result = TM_Updated;
                               3686                 :                :         else
                               3687                 :             14 :             result = TM_Deleted;
                               3688                 :                :     }
                               3689                 :                : 
                               3690                 :                :     /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
                               3691         [ +  + ]:        2389225 :     if (result != TM_Ok)
                               3692                 :                :     {
                               3693   [ +  +  +  +  :            208 :         Assert(result == TM_SelfModified ||
                                        -  +  -  - ]
                               3694                 :                :                result == TM_Updated ||
                               3695                 :                :                result == TM_Deleted ||
                               3696                 :                :                result == TM_BeingModified);
 7645 tgl@sss.pgh.pa.us        3697         [ -  + ]:            208 :         Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
 2682 andres@anarazel.de       3698   [ +  +  -  + ]:            208 :         Assert(result != TM_Updated ||
                               3699                 :                :                !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
                               3700                 :                :     }
                               3701                 :                : 
  971 heikki.linnakangas@i     3702   [ +  +  +  - ]:        2389225 :     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         [ +  + ]:        2389225 :     if (result != TM_Ok)
                               3710                 :                :     {
 2682 andres@anarazel.de       3711                 :            209 :         tmfd->ctid = oldtup.t_data->t_ctid;
                               3712                 :            209 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
                               3713         [ +  + ]:            209 :         if (result == TM_SelfModified)
                               3714                 :             73 :             tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
                               3715                 :                :         else
                               3716                 :            136 :             tmfd->cmax = InvalidCommandId;
  836 akorotkov@postgresql     3717                 :            209 :         UnlockReleaseBuffer(buffer);
 7757 tgl@sss.pgh.pa.us        3718         [ +  + ]:            209 :         if (have_tuple_lock)
 3027 simon@2ndQuadrant.co     3719                 :             76 :             UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
 5514 rhaas@postgresql.org     3720         [ -  + ]:            209 :         if (vmbuffer != InvalidBuffer)
 5514 rhaas@postgresql.org     3721                 :UBC           0 :             ReleaseBuffer(vmbuffer);
 1224 tomas.vondra@postgre     3722                 :CBC         209 :         *update_indexes = TU_None;
                               3723                 :                : 
 6884 tgl@sss.pgh.pa.us        3724                 :            209 :         bms_free(hot_attrs);
 1224 tomas.vondra@postgre     3725                 :            209 :         bms_free(sum_attrs);
 4932 alvherre@alvh.no-ip.     3726                 :            209 :         bms_free(key_attrs);
 3623 tgl@sss.pgh.pa.us        3727                 :            209 :         bms_free(id_attrs);
 3406 alvherre@alvh.no-ip.     3728                 :            209 :         bms_free(modified_attrs);
                               3729                 :            209 :         bms_free(interesting_attrs);
10085 vadim4o@yahoo.com        3730                 :            209 :         return result;
                               3731                 :                :     }
                               3732                 :                : 
                               3733                 :                :     /*
                               3734                 :                :      * If we didn't pin the visibility map page and the page has become all
                               3735                 :                :      * visible while we were busy locking the buffer, or during some
                               3736                 :                :      * subsequent window during which we had it unlocked, we'll have to unlock
                               3737                 :                :      * and re-lock, to avoid holding the buffer lock across an I/O.  That's a
                               3738                 :                :      * bit unfortunate, especially since we'll now have to recheck whether the
                               3739                 :                :      * tuple has been locked or updated under us, but hopefully it won't
                               3740                 :                :      * happen very often.
                               3741                 :                :      */
 5508 rhaas@postgresql.org     3742   [ +  +  -  + ]:        2389016 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
                               3743                 :                :     {
 5508 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);
 5416                          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                 :                :      */
 4932 alvherre@alvh.no-ip.     3756                 :CBC     2389016 :     compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
                               3757                 :        2389016 :                               oldtup.t_data->t_infomask,
                               3758                 :        2389016 :                               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   [ +  +  +  - ]:        2425461 :     if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
 3684                          3771         [ +  + ]:          72890 :         HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
 4932                          3772         [ -  + ]:          36274 :         (checked_lockers && !locker_remains))
                               3773                 :        2352571 :         xmax_new_tuple = InvalidTransactionId;
                               3774                 :                :     else
                               3775                 :          36445 :         xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
                               3776                 :                : 
                               3777         [ +  + ]:        2389016 :     if (!TransactionIdIsValid(xmax_new_tuple))
                               3778                 :                :     {
                               3779                 :        2352571 :         infomask_new_tuple = HEAP_XMAX_INVALID;
                               3780                 :        2352571 :         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         [ +  + ]:          36445 :         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                 :          36273 :             infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
                               3798                 :          36273 :             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                 :                :      */
10103 vadim4o@yahoo.com        3806                 :        2389016 :     newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
 6884 tgl@sss.pgh.pa.us        3807                 :        2389016 :     newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
 7983                          3808                 :        2389016 :     HeapTupleHeaderSetXmin(newtup->t_data, xid);
 8807 bruce@momjian.us         3809                 :        2389016 :     HeapTupleHeaderSetCmin(newtup->t_data, cid);
 4932 alvherre@alvh.no-ip.     3810                 :        2389016 :     newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
                               3811                 :        2389016 :     newtup->t_data->t_infomask2 |= infomask2_new_tuple;
                               3812                 :        2389016 :     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                 :                :      */
 7107 tgl@sss.pgh.pa.us        3818                 :        2389016 :     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                 :                :      */
 4893 kgrittn@postgresql.o     3831         [ -  + ]:        2389016 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
 4893 kgrittn@postgresql.o     3832         [ #  # ]:UBC           0 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
                               3833                 :                :     {
                               3834                 :                :         /* toast table entries should never be recursively toasted */
 7054 tgl@sss.pgh.pa.us        3835         [ #  # ]:              0 :         Assert(!HeapTupleHasExternal(&oldtup));
                               3836         [ #  # ]:              0 :         Assert(!HeapTupleHasExternal(newtup));
                               3837                 :              0 :         need_toast = false;
                               3838                 :                :     }
                               3839                 :                :     else
 7054 tgl@sss.pgh.pa.us        3840         [ +  + ]:CBC     7166424 :         need_toast = (HeapTupleHasExternal(&oldtup) ||
                               3841         [ +  + ]:        4777408 :                       HeapTupleHasExternal(newtup) ||
                               3842         [ +  + ]:        2388360 :                       newtup->t_len > TOAST_TUPLE_THRESHOLD);
                               3843                 :                : 
 6587                          3844                 :        2389016 :     pagefree = PageGetHeapFreeSpace(page);
                               3845                 :                : 
 7112                          3846                 :        2389016 :     newtupsize = MAXALIGN(newtup->t_len);
                               3847                 :                : 
 9202                          3848   [ +  +  +  + ]:        2389016 :     if (need_toast || newtupsize > pagefree)
 9453 vadim4o@yahoo.com        3849                 :        2201475 :     {
                               3850                 :                :         TransactionId xmax_lock_old_tuple;
                               3851                 :                :         uint16      infomask_lock_old_tuple,
                               3852                 :                :                     infomask2_lock_old_tuple;
 3660 andres@anarazel.de       3853                 :        2201475 :         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                 :                :          */
 3663                          3873                 :        2201475 :         compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
                               3874                 :        2201475 :                                   oldtup.t_data->t_infomask,
                               3875                 :        2201475 :                                   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         [ -  + ]:        2201475 :         Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
                               3881                 :                : 
   11 melanieplageman@gmai     3882         [ +  + ]:        2201475 :         if (PageIsAllVisible(page))
                               3883                 :                :         {
                               3884                 :           1853 :             LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
                               3885                 :           1853 :             unlock_vmbuffer = true;
                               3886                 :                :         }
                               3887                 :                : 
 3663 andres@anarazel.de       3888                 :        2201475 :         START_CRIT_SECTION();
                               3889                 :                : 
                               3890                 :                :         /* Clear obsolete visibility flags ... */
 4932 alvherre@alvh.no-ip.     3891                 :        2201475 :         oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               3892                 :        2201475 :         oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
 6884 tgl@sss.pgh.pa.us        3893                 :        2201475 :         HeapTupleClearHotUpdated(&oldtup);
                               3894                 :                :         /* ... and store info about transaction updating this tuple */
 3663 andres@anarazel.de       3895         [ -  + ]:        2201475 :         Assert(TransactionIdIsValid(xmax_lock_old_tuple));
                               3896                 :        2201475 :         HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
                               3897                 :        2201475 :         oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
                               3898                 :        2201475 :         oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
 7107 tgl@sss.pgh.pa.us        3899                 :        2201475 :         HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
                               3900                 :                : 
                               3901                 :                :         /* temporarily make it look not-updated, but locked */
 7553                          3902                 :        2201475 :         oldtup.t_data->t_ctid = oldtup.t_self;
                               3903                 :                : 
                               3904                 :                :         /*
                               3905                 :                :          * Clear all-frozen bit on visibility map if needed. We could
                               3906                 :                :          * immediately reset ALL_VISIBLE, but given that the WAL logging
                               3907                 :                :          * overhead would be unchanged, that doesn't seem necessarily
                               3908                 :                :          * worthwhile.
                               3909                 :                :          */
   11 melanieplageman@gmai     3910         [ +  + ]:        2201475 :         if (PageIsAllVisible(page))
                               3911                 :                :         {
                               3912                 :                :             /* It's possible all-frozen was already clear */
   11 melanieplageman@gmai     3913         [ +  + ]:GNC        1853 :             if (visibilitymap_clear(relation->rd_locator, block, vmbuffer,
                               3914                 :                :                                     VISIBILITYMAP_ALL_FROZEN))
   11 melanieplageman@gmai     3915                 :CBC         804 :                 cleared_all_frozen = true;
                               3916                 :                :         }
                               3917                 :                : 
 3663 andres@anarazel.de       3918                 :        2201475 :         MarkBufferDirty(buffer);
                               3919                 :                : 
                               3920   [ +  +  +  +  :        2201475 :         if (RelationNeedsWAL(relation))
                                        +  -  +  + ]
                               3921                 :                :         {
                               3922                 :                :             xl_heap_lock xlrec;
                               3923                 :                :             XLogRecPtr  recptr;
                               3924                 :                : 
                               3925                 :        2191338 :             XLogBeginInsert();
   11 melanieplageman@gmai     3926                 :        2191338 :             XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, buffer, REGBUF_STANDARD);
                               3927                 :                : 
 3663 andres@anarazel.de       3928                 :        2191338 :             xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
 1202 pg@bowt.ie               3929                 :        2191338 :             xlrec.xmax = xmax_lock_old_tuple;
 3663 andres@anarazel.de       3930                 :        4382676 :             xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
                               3931                 :        2191338 :                                                   oldtup.t_data->t_infomask2);
 3660                          3932                 :        2191338 :             xlrec.flags =
                               3933                 :        2191338 :                 cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
  530 peter@eisentraut.org     3934                 :        2191338 :             XLogRegisterData(&xlrec, SizeOfHeapLock);
                               3935                 :                : 
   11 melanieplageman@gmai     3936         [ +  + ]:        2191338 :             if (cleared_all_frozen)
                               3937                 :            804 :                 XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
                               3938                 :                : 
 3663 andres@anarazel.de       3939                 :        2191338 :             recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
                               3940                 :        2191338 :             PageSetLSN(page, recptr);
                               3941                 :                : 
   11 melanieplageman@gmai     3942         [ +  + ]:        2191338 :             if (cleared_all_frozen)
                               3943                 :            804 :                 PageSetLSN(BufferGetPage(vmbuffer), recptr);
                               3944                 :                :         }
                               3945                 :                : 
 3663 andres@anarazel.de       3946         [ -  + ]:        2201475 :         END_CRIT_SECTION();
                               3947                 :                : 
                               3948                 :                :         /* release VM lock first, since it covers many heap blocks */
   11 melanieplageman@gmai     3949         [ +  + ]:        2201475 :         if (unlock_vmbuffer)
                               3950                 :           1853 :             LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
                               3951                 :        2201475 :         unlock_vmbuffer = false;
                               3952                 :                : 
 9453 vadim4o@yahoo.com        3953                 :        2201475 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               3954                 :                : 
                               3955                 :                :         /*
                               3956                 :                :          * Let the toaster do its thing, if needed.
                               3957                 :                :          *
                               3958                 :                :          * Note: below this point, heaptup is the data we actually intend to
                               3959                 :                :          * store into the relation; newtup is the caller's original untoasted
                               3960                 :                :          * data.
                               3961                 :                :          */
 9323 tgl@sss.pgh.pa.us        3962         [ +  + ]:        2201475 :         if (need_toast)
                               3963                 :                :         {
                               3964                 :                :             /* Note we always use WAL and FSM during updates */
 2487 rhaas@postgresql.org     3965                 :           2203 :             heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
 7553 tgl@sss.pgh.pa.us        3966                 :           2203 :             newtupsize = MAXALIGN(heaptup->t_len);
                               3967                 :                :         }
                               3968                 :                :         else
                               3969                 :        2199272 :             heaptup = newtup;
                               3970                 :                : 
                               3971                 :                :         /*
                               3972                 :                :          * Now, do we need a new page for the tuple, or not?  This is a bit
                               3973                 :                :          * tricky since someone else could have added tuples to the page while
                               3974                 :                :          * we weren't looking.  We have to recheck the available space after
                               3975                 :                :          * reacquiring the buffer lock.  But don't bother to do that if the
                               3976                 :                :          * former amount of free space is still not enough; it's unlikely
                               3977                 :                :          * there's more free now than before.
                               3978                 :                :          *
                               3979                 :                :          * What's more, if we need to get a new page, we will need to acquire
                               3980                 :                :          * buffer locks on both old and new pages.  To avoid deadlock against
                               3981                 :                :          * some other backend trying to get the same two locks in the other
                               3982                 :                :          * order, we must be consistent about the order we get the locks in.
                               3983                 :                :          * We use the rule "lock the lower-numbered page of the relation
                               3984                 :                :          * first".  To implement this, we must do RelationGetBufferForTuple
                               3985                 :                :          * while not holding the lock on the old page, and we must rely on it
                               3986                 :                :          * to get the locks on both pages in the correct order.
                               3987                 :                :          *
                               3988                 :                :          * Another consideration is that we need visibility map page pin(s) if
                               3989                 :                :          * we will have to clear the all-visible flag on either page.  If we
                               3990                 :                :          * call RelationGetBufferForTuple, we rely on it to acquire any such
                               3991                 :                :          * pins; but if we don't, we have to handle that here.  Hence we need
                               3992                 :                :          * a loop.
                               3993                 :                :          */
                               3994                 :                :         for (;;)
                               3995                 :                :         {
 1930                          3996         [ +  + ]:        2201475 :             if (newtupsize > pagefree)
                               3997                 :                :             {
                               3998                 :                :                 /* It doesn't fit, must use RelationGetBufferForTuple. */
                               3999                 :        2200727 :                 newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
                               4000                 :                :                                                    buffer, 0, NULL,
                               4001                 :                :                                                    &vmbuffer_new, &vmbuffer,
                               4002                 :                :                                                    0);
                               4003                 :                :                 /* We're all done. */
                               4004                 :        2200727 :                 break;
                               4005                 :                :             }
                               4006                 :                :             /* Acquire VM page pin if needed and we don't have it. */
                               4007   [ +  +  -  + ]:            748 :             if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
 1930 tgl@sss.pgh.pa.us        4008                 :UBC           0 :                 visibilitymap_pin(relation, block, &vmbuffer);
                               4009                 :                :             /* Re-acquire the lock on the old tuple's page. */
 9202 tgl@sss.pgh.pa.us        4010                 :CBC         748 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               4011                 :                :             /* Re-check using the up-to-date free space */
 6587                          4012                 :            748 :             pagefree = PageGetHeapFreeSpace(page);
 1930                          4013         [ +  - ]:            748 :             if (newtupsize > pagefree ||
                               4014   [ +  +  -  + ]:            748 :                 (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
                               4015                 :                :             {
                               4016                 :                :                 /*
                               4017                 :                :                  * Rats, it doesn't fit anymore, or somebody just now set the
                               4018                 :                :                  * all-visible flag.  We must now unlock and loop to avoid
                               4019                 :                :                  * deadlock.  Fortunately, this path should seldom be taken.
                               4020                 :                :                  */
 9202 tgl@sss.pgh.pa.us        4021                 :UBC           0 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               4022                 :                :             }
                               4023                 :                :             else
                               4024                 :                :             {
                               4025                 :                :                 /* We're all done. */
 9202 tgl@sss.pgh.pa.us        4026                 :CBC         748 :                 newbuf = buffer;
 1930                          4027                 :            748 :                 break;
                               4028                 :                :             }
                               4029                 :                :         }
                               4030                 :                :     }
                               4031                 :                :     else
                               4032                 :                :     {
                               4033                 :                :         /* No TOAST work needed, and it'll fit on same page */
 9323                          4034                 :         187541 :         newbuf = buffer;
 7553                          4035                 :         187541 :         heaptup = newtup;
                               4036                 :                :     }
                               4037                 :                : 
  133 melanieplageman@gmai     4038                 :        2389016 :     newpage = BufferGetPage(newbuf);
                               4039                 :                : 
                               4040                 :                :     /*
                               4041                 :                :      * We're about to do the actual update -- check for conflict first, to
                               4042                 :                :      * avoid possibly having to roll back work we've just done.
                               4043                 :                :      *
                               4044                 :                :      * This is safe without a recheck as long as there is no possibility of
                               4045                 :                :      * another process scanning the pages between this check and the update
                               4046                 :                :      * being visible to the scan (i.e., exclusive buffer content lock(s) are
                               4047                 :                :      * continuously held from this point until the tuple update is visible).
                               4048                 :                :      *
                               4049                 :                :      * For the new tuple the only check needed is at the relation level, but
                               4050                 :                :      * since both tuples are in the same relation and the check for oldtup
                               4051                 :                :      * will include checking the relation level, there is no benefit to a
                               4052                 :                :      * separate check for the new tuple.
                               4053                 :                :      */
 1930 tmunro@postgresql.or     4054                 :        2389016 :     CheckForSerializableConflictIn(relation, &oldtup.t_self,
                               4055                 :                :                                    BufferGetBlockNumber(buffer));
                               4056                 :                : 
                               4057                 :                :     /*
                               4058                 :                :      * At this point newbuf and buffer are both pinned and locked, and newbuf
                               4059                 :                :      * has enough space for the new tuple.  If they are the same buffer, only
                               4060                 :                :      * one pin is held.
                               4061                 :                :      */
                               4062                 :                : 
 6884 tgl@sss.pgh.pa.us        4063         [ +  + ]:        2389004 :     if (newbuf == buffer)
                               4064                 :                :     {
                               4065                 :                :         /*
                               4066                 :                :          * Since the new tuple is going into the same page, we might be able
                               4067                 :                :          * to do a HOT update.  Check if any of the index columns have been
                               4068                 :                :          * changed.
                               4069                 :                :          */
 1703 pg@bowt.ie               4070         [ +  + ]:         188277 :         if (!bms_overlap(modified_attrs, hot_attrs))
                               4071                 :                :         {
 6884 tgl@sss.pgh.pa.us        4072                 :         171532 :             use_hot_update = true;
                               4073                 :                : 
                               4074                 :                :             /*
                               4075                 :                :              * If none of the columns that are used in hot-blocking indexes
                               4076                 :                :              * were updated, we can apply HOT, but we do still need to check
                               4077                 :                :              * if we need to update the summarizing indexes, and update those
                               4078                 :                :              * indexes if the columns were updated, or we may fail to detect
                               4079                 :                :              * e.g. value bound changes in BRIN minmax indexes.
                               4080                 :                :              */
 1224 tomas.vondra@postgre     4081         [ +  + ]:         171532 :             if (bms_overlap(modified_attrs, sum_attrs))
                               4082                 :           2188 :                 summarized_update = true;
                               4083                 :                :         }
                               4084                 :                :     }
                               4085                 :                :     else
                               4086                 :                :     {
                               4087                 :                :         /* Set a hint that the old page could use prune/defrag */
 6587 tgl@sss.pgh.pa.us        4088                 :        2200727 :         PageSetFull(page);
                               4089                 :                :     }
                               4090                 :                : 
                               4091                 :                :     /*
                               4092                 :                :      * Compute replica identity tuple before entering the critical section so
                               4093                 :                :      * we don't PANIC upon a memory allocation failure.
                               4094                 :                :      * ExtractReplicaIdentity() will return NULL if nothing needs to be
                               4095                 :                :      * logged.  Pass old key required as true only if the replica identity key
                               4096                 :                :      * columns are modified or it has external data.
                               4097                 :                :      */
 3406 alvherre@alvh.no-ip.     4098                 :        2389004 :     old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
 1623 akapila@postgresql.o     4099   [ +  +  +  + ]:        2389004 :                                            bms_overlap(modified_attrs, id_attrs) ||
                               4100                 :                :                                            id_has_external,
 3406 alvherre@alvh.no-ip.     4101                 :        2389004 :                                            &old_key_copied);
                               4102                 :                : 
   11 melanieplageman@gmai     4103                 :        2389004 :     clear_all_visible = PageIsAllVisible(page);
                               4104   [ +  +  +  + ]:        2389004 :     clear_all_visible_new = newbuf != buffer && PageIsAllVisible(newpage);
                               4105                 :                : 
                               4106                 :                :     /*
                               4107                 :                :      * Clear PD_ALL_VISIBLE flags and reset visibility map bits for any heap
                               4108                 :                :      * pages that were all-visible. If there are two heap pages, we may need
                               4109                 :                :      * to clear VM bits for both.
                               4110                 :                :      */
                               4111   [ +  +  +  + ]:        2389004 :     if (clear_all_visible && clear_all_visible_new &&
                               4112         [ +  - ]:            168 :         vmbuffer_new == vmbuffer)
                               4113                 :                :     {
                               4114                 :                :         /*
                               4115                 :                :          * This is the more complicated case: both the new and old heap pages
                               4116                 :                :          * are all-visible and both their VM bits are on the same page of the
                               4117                 :                :          * VM, so we register a single VM buffer as HEAP_UPDATE_BLKREF_VM_NEW
                               4118                 :                :          * in the WAL record. We must be careful to only lock and register one
                               4119                 :                :          * buffer, even though we modify it twice -- once for each heap
                               4120                 :                :          * block's VM bits.
                               4121                 :                :          */
                               4122                 :            168 :         LockBuffer(vmbuffer_new, BUFFER_LOCK_EXCLUSIVE);
                               4123                 :            168 :         unlock_vmbuffer_new = true;
                               4124                 :                : 
                               4125                 :                :         /* We will not lock or attempt to modify old VM buffer */
                               4126                 :                :     }
                               4127                 :                :     else
                               4128                 :                :     {
                               4129                 :                :         /*
                               4130                 :                :          * In all the remaining cases, we will clear at most one heap block's
                               4131                 :                :          * VM bits per VM page.
                               4132                 :                :          */
                               4133                 :        4777672 :         Buffer      vmbuffers[2] = {
                               4134         [ +  + ]:        2388836 :             clear_all_visible ? vmbuffer : InvalidBuffer,
                               4135         [ +  + ]:        2388836 :             clear_all_visible_new ? vmbuffer_new : InvalidBuffer
                               4136                 :                :         };
                               4137                 :                : 
                               4138                 :                :         /*
                               4139                 :                :          * When both pages need different VM pages cleared, acquire the VM
                               4140                 :                :          * buffer locks in VM block order to avoid deadlocks between backends
                               4141                 :                :          * updating tuples in opposite directions across VM pages.
                               4142                 :                :          */
                               4143   [ +  +  -  +  :        2388836 :         if (clear_all_visible && clear_all_visible_new &&
                                              -  - ]
   11 melanieplageman@gmai     4144                 :UBC           0 :             BufferGetBlockNumber(vmbuffers[0]) > BufferGetBlockNumber(vmbuffers[1]))
                               4145                 :                :         {
                               4146                 :              0 :             Buffer      swap = vmbuffers[0];
                               4147                 :                : 
                               4148                 :              0 :             vmbuffers[0] = vmbuffers[1];
                               4149                 :              0 :             vmbuffers[1] = swap;
                               4150                 :                :         }
                               4151                 :                : 
   11 melanieplageman@gmai     4152   [ +  +  +  +  :CBC     2388836 :         Assert((!BufferIsValid(vmbuffers[0]) && !BufferIsValid(vmbuffers[1])) ||
                                              -  + ]
                               4153                 :                :                vmbuffers[0] != vmbuffers[1]);
                               4154                 :                : 
                               4155         [ +  + ]:        2388836 :         if (BufferIsValid(vmbuffers[0]))
                               4156                 :           2766 :             LockBuffer(vmbuffers[0], BUFFER_LOCK_EXCLUSIVE);
                               4157         [ +  + ]:        2388836 :         if (BufferIsValid(vmbuffers[1]))
                               4158                 :           1578 :             LockBuffer(vmbuffers[1], BUFFER_LOCK_EXCLUSIVE);
                               4159                 :                : 
                               4160         [ +  + ]:        2388836 :         if (clear_all_visible)
                               4161                 :           2766 :             unlock_vmbuffer = true;
                               4162         [ +  + ]:        2388836 :         if (clear_all_visible_new)
                               4163                 :           1578 :             unlock_vmbuffer_new = true;
                               4164                 :                :     }
                               4165                 :                : 
                               4166                 :                :     /* NO EREPORT(ERROR) from here till changes are logged */
 9326 tgl@sss.pgh.pa.us        4167                 :        2389004 :     START_CRIT_SECTION();
                               4168                 :                : 
                               4169                 :                :     /*
                               4170                 :                :      * If this transaction commits, the old tuple will become DEAD sooner or
                               4171                 :                :      * later.  Set flag that this page is a candidate for pruning once our xid
                               4172                 :                :      * falls below the OldestXmin horizon.  If the transaction finally aborts,
                               4173                 :                :      * the subsequent page pruning will be a no-op and the hint will be
                               4174                 :                :      * cleared.
                               4175                 :                :      *
                               4176                 :                :      * We set the new page prunable as well. See heap_insert() for more on why
                               4177                 :                :      * we do this when inserting tuples.
                               4178                 :                :      */
 6587                          4179   [ -  +  +  +  :        2389004 :     PageSetPrunable(page, xid);
                                              +  + ]
  118 melanieplageman@gmai     4180         [ +  + ]:        2389004 :     if (newbuf != buffer)
                               4181   [ -  +  +  +  :        2200727 :         PageSetPrunable(newpage, xid);
                                              +  + ]
                               4182                 :                : 
 6884 tgl@sss.pgh.pa.us        4183         [ +  + ]:        2389004 :     if (use_hot_update)
                               4184                 :                :     {
                               4185                 :                :         /* Mark the old tuple as HOT-updated */
                               4186                 :         171532 :         HeapTupleSetHotUpdated(&oldtup);
                               4187                 :                :         /* And mark the new tuple as heap-only */
                               4188                 :         171532 :         HeapTupleSetHeapOnly(heaptup);
                               4189                 :                :         /* Mark the caller's copy too, in case different from heaptup */
                               4190                 :         171532 :         HeapTupleSetHeapOnly(newtup);
                               4191                 :                :     }
                               4192                 :                :     else
                               4193                 :                :     {
                               4194                 :                :         /* Make sure tuples are correctly marked as not-HOT */
                               4195                 :        2217472 :         HeapTupleClearHotUpdated(&oldtup);
                               4196                 :        2217472 :         HeapTupleClearHeapOnly(heaptup);
                               4197                 :        2217472 :         HeapTupleClearHeapOnly(newtup);
                               4198                 :                :     }
                               4199                 :                : 
 3322                          4200                 :        2389004 :     RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
                               4201                 :                : 
                               4202                 :                : 
                               4203                 :                :     /* Clear obsolete visibility flags, possibly set by ourselves above... */
 3663 andres@anarazel.de       4204                 :        2389004 :     oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               4205                 :        2389004 :     oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               4206                 :                :     /* ... and store info about transaction updating this tuple */
                               4207         [ -  + ]:        2389004 :     Assert(TransactionIdIsValid(xmax_old_tuple));
                               4208                 :        2389004 :     HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
                               4209                 :        2389004 :     oldtup.t_data->t_infomask |= infomask_old_tuple;
                               4210                 :        2389004 :     oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
                               4211                 :        2389004 :     HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
                               4212                 :                : 
                               4213                 :                :     /* record address of new tuple in t_ctid of old one */
 7553 tgl@sss.pgh.pa.us        4214                 :        2389004 :     oldtup.t_data->t_ctid = heaptup->t_self;
                               4215                 :                : 
                               4216                 :                :     /*
                               4217                 :                :      * Clear PD_ALL_VISIBLE flags and reset all visibilitymap bits. In all
                               4218                 :                :      * cases, it's possible that PD_ALL_VISIBLE was set but the corresponding
                               4219                 :                :      * visibility map bits were already clear.
                               4220                 :                :      */
   11 melanieplageman@gmai     4221         [ +  + ]:        2389004 :     if (clear_all_visible)
                               4222                 :                :     {
   11 melanieplageman@gmai     4223         [ +  - ]:GNC        2934 :         if (visibilitymap_clear(relation->rd_locator, block,
                               4224                 :                :                                 vmbuffer, VISIBILITYMAP_VALID_BITS))
                               4225                 :                :         {
                               4226                 :                :             /*
                               4227                 :                :              * When old and new heap blocks' VM bits are on the same VM page,
                               4228                 :                :              * that page is registered in the WAL record only once. If both
                               4229                 :                :              * heap pages were PD_ALL_VISIBLE and either VM bit needs
                               4230                 :                :              * clearing, we register the VM buffer as
                               4231                 :                :              * HEAP_UPDATE_BLKREF_VM_NEW.
                               4232                 :                :              */
   11 melanieplageman@gmai     4233   [ +  +  +  - ]:CBC        2934 :             if (clear_all_visible_new && vmbuffer == vmbuffer_new)
                               4234                 :            168 :                 vmbuffer_new_modified = true;
                               4235                 :                :             else
                               4236                 :           2766 :                 vmbuffer_modified = true;
                               4237                 :                :         }
                               4238                 :                : 
  133                          4239                 :           2934 :         PageClearAllVisible(page);
                               4240                 :                :     }
   11                          4241         [ +  + ]:        2389004 :     if (clear_all_visible_new)
                               4242                 :                :     {
                               4243                 :                :         /*
                               4244                 :                :          * If both heap blocks' VM bits are on the same VM buffer, this will
                               4245                 :                :          * clear the new heap block's VM bits from the shared vmbuffer.
                               4246                 :                :          */
   11 melanieplageman@gmai     4247         [ +  - ]:GNC        1746 :         if (visibilitymap_clear(relation->rd_locator, BufferGetBlockNumber(newbuf),
                               4248                 :                :                                 vmbuffer_new, VISIBILITYMAP_VALID_BITS))
   11 melanieplageman@gmai     4249                 :CBC        1746 :             vmbuffer_new_modified = true;
                               4250                 :                : 
  133                          4251                 :           1746 :         PageClearAllVisible(newpage);
                               4252                 :                :     }
                               4253                 :                : 
 7422 tgl@sss.pgh.pa.us        4254         [ +  + ]:        2389004 :     if (newbuf != buffer)
                               4255                 :        2200727 :         MarkBufferDirty(newbuf);
                               4256                 :        2389004 :     MarkBufferDirty(buffer);
                               4257                 :                : 
                               4258                 :                :     /* XLOG stuff */
 5704 rhaas@postgresql.org     4259   [ +  +  +  +  :        2389004 :     if (RelationNeedsWAL(relation))
                                        +  -  +  + ]
                               4260                 :                :     {
                               4261                 :                :         XLogRecPtr  recptr;
                               4262                 :                : 
                               4263                 :                :         /*
                               4264                 :                :          * For logical decoding we need combo CIDs to properly decode the
                               4265                 :                :          * catalog.
                               4266                 :                :          */
 4611                          4267   [ +  +  +  +  :        2377216 :         if (RelationIsAccessibleInLogicalDecoding(relation))
                                     +  -  -  +  -  
                                     -  -  -  +  +  
                                     +  +  -  +  -  
                                           -  +  + ]
                               4268                 :                :         {
                               4269                 :           2724 :             log_heap_new_cid(relation, &oldtup);
                               4270                 :           2724 :             log_heap_new_cid(relation, heaptup);
                               4271                 :                :         }
                               4272                 :                : 
                               4273   [ +  +  +  + ]:        2377216 :         recptr = log_heap_update(relation, buffer,
                               4274                 :                :                                  vmbuffer_modified ? vmbuffer : InvalidBuffer,
                               4275                 :                :                                  newbuf,
                               4276                 :                :                                  vmbuffer_new_modified ? vmbuffer_new : InvalidBuffer,
                               4277                 :                :                                  &oldtup, heaptup,
                               4278                 :                :                                  old_key_tuple,
                               4279                 :                :                                  clear_all_visible,
                               4280                 :                :                                  clear_all_visible_new,
                               4281                 :                :                                  walLogical);
 9519 vadim4o@yahoo.com        4282         [ +  + ]:        2377216 :         if (newbuf != buffer)
                               4283                 :                :         {
  133 melanieplageman@gmai     4284                 :        2190598 :             PageSetLSN(newpage, recptr);
                               4285                 :                :         }
                               4286                 :        2377216 :         PageSetLSN(page, recptr);
                               4287                 :                : 
   11                          4288         [ +  + ]:        2377216 :         if (vmbuffer_modified)
                               4289                 :           2765 :             PageSetLSN(BufferGetPage(vmbuffer), recptr);
                               4290         [ +  + ]:        2377216 :         if (vmbuffer_new_modified)
                               4291                 :           1746 :             PageSetLSN(BufferGetPage(vmbuffer_new), recptr);
                               4292                 :                :     }
                               4293                 :                : 
 9326 tgl@sss.pgh.pa.us        4294         [ -  + ]:        2389004 :     END_CRIT_SECTION();
                               4295                 :                : 
   11 melanieplageman@gmai     4296         [ +  + ]:        2389004 :     if (unlock_vmbuffer)
                               4297                 :           2766 :         LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
                               4298         [ +  + ]:        2389004 :     if (unlock_vmbuffer_new)
                               4299                 :           1746 :         LockBuffer(vmbuffer_new, BUFFER_LOCK_UNLOCK);
                               4300                 :                : 
 9519 vadim4o@yahoo.com        4301         [ +  + ]:        2389004 :     if (newbuf != buffer)
                               4302                 :        2200727 :         LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
10085                          4303                 :        2389004 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               4304                 :                : 
                               4305                 :                :     /*
                               4306                 :                :      * Mark old tuple for invalidation from system caches at next command
                               4307                 :                :      * boundary, and mark the new tuple for invalidation in case we abort. We
                               4308                 :                :      * have to do this before releasing the buffer because oldtup is in the
                               4309                 :                :      * buffer.  (heaptup is all in local memory, but it's necessary to process
                               4310                 :                :      * both tuple versions in one call to inval.c so we can avoid redundant
                               4311                 :                :      * sinval messages.)
                               4312                 :                :      */
 5458 tgl@sss.pgh.pa.us        4313                 :        2389004 :     CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
                               4314                 :                : 
                               4315                 :                :     /* Now we can release the buffer(s) */
 9331                          4316         [ +  + ]:        2389004 :     if (newbuf != buffer)
 7422                          4317                 :        2200727 :         ReleaseBuffer(newbuf);
  836 akorotkov@postgresql     4318                 :        2389004 :     ReleaseBuffer(buffer);
 5514 rhaas@postgresql.org     4319         [ +  + ]:        2389004 :     if (BufferIsValid(vmbuffer_new))
                               4320                 :           1749 :         ReleaseBuffer(vmbuffer_new);
                               4321         [ +  + ]:        2389004 :     if (BufferIsValid(vmbuffer))
                               4322                 :           2934 :         ReleaseBuffer(vmbuffer);
                               4323                 :                : 
                               4324                 :                :     /*
                               4325                 :                :      * Release the lmgr tuple lock, if we had it.
                               4326                 :                :      */
 7757 tgl@sss.pgh.pa.us        4327         [ +  + ]:        2389004 :     if (have_tuple_lock)
 3027 simon@2ndQuadrant.co     4328                 :             22 :         UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
                               4329                 :                : 
 1221 pg@bowt.ie               4330                 :        2389004 :     pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
                               4331                 :                : 
                               4332                 :                :     /*
                               4333                 :                :      * If heaptup is a private copy, release it.  Don't forget to copy t_self
                               4334                 :                :      * back to the caller's image, too.
                               4335                 :                :      */
 7553 tgl@sss.pgh.pa.us        4336         [ +  + ]:        2389004 :     if (heaptup != newtup)
                               4337                 :                :     {
                               4338                 :           2137 :         newtup->t_self = heaptup->t_self;
                               4339                 :           2137 :         heap_freetuple(heaptup);
                               4340                 :                :     }
                               4341                 :                : 
                               4342                 :                :     /*
                               4343                 :                :      * If it is a HOT update, the update may still need to update summarized
                               4344                 :                :      * indexes, lest we fail to update those summaries and get incorrect
                               4345                 :                :      * results (for example, minmax bounds of the block may change with this
                               4346                 :                :      * update).
                               4347                 :                :      */
 1224 tomas.vondra@postgre     4348         [ +  + ]:        2389004 :     if (use_hot_update)
                               4349                 :                :     {
                               4350         [ +  + ]:         171532 :         if (summarized_update)
                               4351                 :           2188 :             *update_indexes = TU_Summarizing;
                               4352                 :                :         else
                               4353                 :         169344 :             *update_indexes = TU_None;
                               4354                 :                :     }
                               4355                 :                :     else
                               4356                 :        2217472 :         *update_indexes = TU_All;
                               4357                 :                : 
 4611 rhaas@postgresql.org     4358   [ +  +  +  + ]:        2389004 :     if (old_key_tuple != NULL && old_key_copied)
                               4359                 :             96 :         heap_freetuple(old_key_tuple);
                               4360                 :                : 
 6884 tgl@sss.pgh.pa.us        4361                 :        2389004 :     bms_free(hot_attrs);
 1224 tomas.vondra@postgre     4362                 :        2389004 :     bms_free(sum_attrs);
 4932 alvherre@alvh.no-ip.     4363                 :        2389004 :     bms_free(key_attrs);
 3623 tgl@sss.pgh.pa.us        4364                 :        2389004 :     bms_free(id_attrs);
 3406 alvherre@alvh.no-ip.     4365                 :        2389004 :     bms_free(modified_attrs);
                               4366                 :        2389004 :     bms_free(interesting_attrs);
                               4367                 :                : 
 2682 andres@anarazel.de       4368                 :        2389004 :     return TM_Ok;
                               4369                 :                : }
                               4370                 :                : 
                               4371                 :                : #ifdef USE_ASSERT_CHECKING
                               4372                 :                : /*
                               4373                 :                :  * Confirm adequate lock held during heap_update(), per rules from
                               4374                 :                :  * README.tuplock section "Locking to write inplace-updated tables".
                               4375                 :                :  */
                               4376                 :                : static void
  670 noah@leadboat.com        4377                 :        2389226 : check_lock_if_inplace_updateable_rel(Relation relation,
                               4378                 :                :                                      const ItemPointerData *otid,
                               4379                 :                :                                      HeapTuple newtup)
                               4380                 :                : {
                               4381                 :                :     /* LOCKTAG_TUPLE acceptable for any catalog */
                               4382         [ +  + ]:        2389226 :     switch (RelationGetRelid(relation))
                               4383                 :                :     {
                               4384                 :          89570 :         case RelationRelationId:
                               4385                 :                :         case DatabaseRelationId:
                               4386                 :                :             {
                               4387                 :                :                 LOCKTAG     tuptag;
                               4388                 :                : 
                               4389                 :          89570 :                 SET_LOCKTAG_TUPLE(tuptag,
                               4390                 :                :                                   relation->rd_lockInfo.lockRelId.dbId,
                               4391                 :                :                                   relation->rd_lockInfo.lockRelId.relId,
                               4392                 :                :                                   ItemPointerGetBlockNumber(otid),
                               4393                 :                :                                   ItemPointerGetOffsetNumber(otid));
                               4394         [ +  + ]:          89570 :                 if (LockHeldByMe(&tuptag, InplaceUpdateTupleLock, false))
                               4395                 :          37571 :                     return;
                               4396                 :                :             }
                               4397                 :          51999 :             break;
                               4398                 :        2299656 :         default:
                               4399         [ -  + ]:        2299656 :             Assert(!IsInplaceUpdateRelation(relation));
                               4400                 :        2299656 :             return;
                               4401                 :                :     }
                               4402                 :                : 
                               4403      [ +  -  - ]:          51999 :     switch (RelationGetRelid(relation))
                               4404                 :                :     {
                               4405                 :          51999 :         case RelationRelationId:
                               4406                 :                :             {
                               4407                 :                :                 /* LOCKTAG_TUPLE or LOCKTAG_RELATION ok */
                               4408                 :          51999 :                 Form_pg_class classForm = (Form_pg_class) GETSTRUCT(newtup);
                               4409                 :          51999 :                 Oid         relid = classForm->oid;
                               4410                 :                :                 Oid         dbid;
                               4411                 :                :                 LOCKTAG     tag;
                               4412                 :                : 
                               4413         [ +  + ]:          51999 :                 if (IsSharedRelation(relid))
                               4414                 :             47 :                     dbid = InvalidOid;
                               4415                 :                :                 else
                               4416                 :          51952 :                     dbid = MyDatabaseId;
                               4417                 :                : 
                               4418         [ +  + ]:          51999 :                 if (classForm->relkind == RELKIND_INDEX)
                               4419                 :                :                 {
                               4420                 :           1312 :                     Relation    irel = index_open(relid, AccessShareLock);
                               4421                 :                : 
                               4422                 :           1312 :                     SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
                               4423                 :           1312 :                     index_close(irel, AccessShareLock);
                               4424                 :                :                 }
                               4425                 :                :                 else
                               4426                 :          50687 :                     SET_LOCKTAG_RELATION(tag, dbid, relid);
                               4427                 :                : 
                               4428         [ +  + ]:          51999 :                 if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, false) &&
                               4429         [ -  + ]:          47440 :                     !LockHeldByMe(&tag, ShareRowExclusiveLock, true))
  670 noah@leadboat.com        4430         [ #  # ]:UBC           0 :                     elog(WARNING,
                               4431                 :                :                          "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
                               4432                 :                :                          NameStr(classForm->relname),
                               4433                 :                :                          relid,
                               4434                 :                :                          classForm->relkind,
                               4435                 :                :                          ItemPointerGetBlockNumber(otid),
                               4436                 :                :                          ItemPointerGetOffsetNumber(otid));
                               4437                 :                :             }
  670 noah@leadboat.com        4438                 :CBC       51999 :             break;
  670 noah@leadboat.com        4439                 :UBC           0 :         case DatabaseRelationId:
                               4440                 :                :             {
                               4441                 :                :                 /* LOCKTAG_TUPLE required */
                               4442                 :              0 :                 Form_pg_database dbForm = (Form_pg_database) GETSTRUCT(newtup);
                               4443                 :                : 
                               4444         [ #  # ]:              0 :                 elog(WARNING,
                               4445                 :                :                      "missing lock on database \"%s\" (OID %u) @ TID (%u,%u)",
                               4446                 :                :                      NameStr(dbForm->datname),
                               4447                 :                :                      dbForm->oid,
                               4448                 :                :                      ItemPointerGetBlockNumber(otid),
                               4449                 :                :                      ItemPointerGetOffsetNumber(otid));
                               4450                 :                :             }
                               4451                 :              0 :             break;
                               4452                 :                :     }
                               4453                 :                : }
                               4454                 :                : 
                               4455                 :                : /*
                               4456                 :                :  * Confirm adequate relation lock held, per rules from README.tuplock section
                               4457                 :                :  * "Locking to write inplace-updated tables".
                               4458                 :                :  */
                               4459                 :                : static void
  670 noah@leadboat.com        4460                 :CBC      117699 : check_inplace_rel_lock(HeapTuple oldtup)
                               4461                 :                : {
                               4462                 :         117699 :     Form_pg_class classForm = (Form_pg_class) GETSTRUCT(oldtup);
                               4463                 :         117699 :     Oid         relid = classForm->oid;
                               4464                 :                :     Oid         dbid;
                               4465                 :                :     LOCKTAG     tag;
                               4466                 :                : 
                               4467         [ +  + ]:         117699 :     if (IsSharedRelation(relid))
                               4468                 :           9891 :         dbid = InvalidOid;
                               4469                 :                :     else
                               4470                 :         107808 :         dbid = MyDatabaseId;
                               4471                 :                : 
                               4472         [ +  + ]:         117699 :     if (classForm->relkind == RELKIND_INDEX)
                               4473                 :                :     {
                               4474                 :          51793 :         Relation    irel = index_open(relid, AccessShareLock);
                               4475                 :                : 
                               4476                 :          51793 :         SET_LOCKTAG_RELATION(tag, dbid, irel->rd_index->indrelid);
                               4477                 :          51793 :         index_close(irel, AccessShareLock);
                               4478                 :                :     }
                               4479                 :                :     else
                               4480                 :          65906 :         SET_LOCKTAG_RELATION(tag, dbid, relid);
                               4481                 :                : 
                               4482         [ -  + ]:         117699 :     if (!LockHeldByMe(&tag, ShareUpdateExclusiveLock, true))
  670 noah@leadboat.com        4483         [ #  # ]:UBC           0 :         elog(WARNING,
                               4484                 :                :              "missing lock for relation \"%s\" (OID %u, relkind %c) @ TID (%u,%u)",
                               4485                 :                :              NameStr(classForm->relname),
                               4486                 :                :              relid,
                               4487                 :                :              classForm->relkind,
                               4488                 :                :              ItemPointerGetBlockNumber(&oldtup->t_self),
                               4489                 :                :              ItemPointerGetOffsetNumber(&oldtup->t_self));
  670 noah@leadboat.com        4490                 :CBC      117699 : }
                               4491                 :                : #endif
                               4492                 :                : 
                               4493                 :                : /*
                               4494                 :                :  * Check if the specified attribute's values are the same.  Subroutine for
                               4495                 :                :  * HeapDetermineColumnsInfo.
                               4496                 :                :  */
                               4497                 :                : static bool
 1623 akapila@postgresql.o     4498                 :        1000450 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
                               4499                 :                :                  bool isnull1, bool isnull2)
                               4500                 :                : {
                               4501                 :                :     /*
                               4502                 :                :      * If one value is NULL and other is not, then they are certainly not
                               4503                 :                :      * equal
                               4504                 :                :      */
 6884 tgl@sss.pgh.pa.us        4505         [ +  + ]:        1000450 :     if (isnull1 != isnull2)
                               4506                 :             60 :         return false;
                               4507                 :                : 
                               4508                 :                :     /*
                               4509                 :                :      * If both are NULL, they can be considered equal.
                               4510                 :                :      */
                               4511         [ +  + ]:        1000390 :     if (isnull1)
                               4512                 :           6641 :         return true;
                               4513                 :                : 
                               4514                 :                :     /*
                               4515                 :                :      * We do simple binary comparison of the two datums.  This may be overly
                               4516                 :                :      * strict because there can be multiple binary representations for the
                               4517                 :                :      * same logical value.  But we should be OK as long as there are no false
                               4518                 :                :      * positives.  Using a type-specific equality operator is messy because
                               4519                 :                :      * there could be multiple notions of equality in different operator
                               4520                 :                :      * classes; furthermore, we cannot safely invoke user-defined functions
                               4521                 :                :      * while holding exclusive buffer lock.
                               4522                 :                :      */
                               4523         [ -  + ]:         993749 :     if (attrnum <= 0)
                               4524                 :                :     {
                               4525                 :                :         /* The only allowed system columns are OIDs, so do this */
 6884 tgl@sss.pgh.pa.us        4526                 :UBC           0 :         return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
                               4527                 :                :     }
                               4528                 :                :     else
                               4529                 :                :     {
                               4530                 :                :         CompactAttribute *att;
                               4531                 :                : 
 6884 tgl@sss.pgh.pa.us        4532         [ -  + ]:CBC      993749 :         Assert(attrnum <= tupdesc->natts);
  583 drowley@postgresql.o     4533                 :         993749 :         att = TupleDescCompactAttr(tupdesc, attrnum - 1);
 6884 tgl@sss.pgh.pa.us        4534                 :         993749 :         return datumIsEqual(value1, value2, att->attbyval, att->attlen);
                               4535                 :                :     }
                               4536                 :                : }
                               4537                 :                : 
                               4538                 :                : /*
                               4539                 :                :  * Check which columns are being updated.
                               4540                 :                :  *
                               4541                 :                :  * Given an updated tuple, determine (and return into the output bitmapset),
                               4542                 :                :  * from those listed as interesting, the set of columns that changed.
                               4543                 :                :  *
                               4544                 :                :  * has_external indicates if any of the unmodified attributes (from those
                               4545                 :                :  * listed as interesting) of the old tuple is a member of external_cols and is
                               4546                 :                :  * stored externally.
                               4547                 :                :  */
                               4548                 :                : static Bitmapset *
 1623 akapila@postgresql.o     4549                 :        2389225 : HeapDetermineColumnsInfo(Relation relation,
                               4550                 :                :                          Bitmapset *interesting_cols,
                               4551                 :                :                          Bitmapset *external_cols,
                               4552                 :                :                          HeapTuple oldtup, HeapTuple newtup,
                               4553                 :                :                          bool *has_external)
                               4554                 :                : {
                               4555                 :                :     int         attidx;
 3357 bruce@momjian.us         4556                 :        2389225 :     Bitmapset  *modified = NULL;
 1623 akapila@postgresql.o     4557                 :        2389225 :     TupleDesc   tupdesc = RelationGetDescr(relation);
                               4558                 :                : 
 1242 tgl@sss.pgh.pa.us        4559                 :        2389225 :     attidx = -1;
                               4560         [ +  + ]:        3389675 :     while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
                               4561                 :                :     {
                               4562                 :                :         /* attidx is zero-based, attrnum is the normal attribute number */
                               4563                 :        1000450 :         AttrNumber  attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
                               4564                 :                :         Datum       value1,
                               4565                 :                :                     value2;
                               4566                 :                :         bool        isnull1,
                               4567                 :                :                     isnull2;
                               4568                 :                : 
                               4569                 :                :         /*
                               4570                 :                :          * If it's a whole-tuple reference, say "not equal".  It's not really
                               4571                 :                :          * worth supporting this case, since it could only succeed after a
                               4572                 :                :          * no-op update, which is hardly a case worth optimizing for.
                               4573                 :                :          */
 1623 akapila@postgresql.o     4574         [ -  + ]:        1000450 :         if (attrnum == 0)
                               4575                 :                :         {
 1242 tgl@sss.pgh.pa.us        4576                 :UBC           0 :             modified = bms_add_member(modified, attidx);
 1623 akapila@postgresql.o     4577                 :CBC      968070 :             continue;
                               4578                 :                :         }
                               4579                 :                : 
                               4580                 :                :         /*
                               4581                 :                :          * Likewise, automatically say "not equal" for any system attribute
                               4582                 :                :          * other than tableOID; we cannot expect these to be consistent in a
                               4583                 :                :          * HOT chain, or even to be set correctly yet in the new tuple.
                               4584                 :                :          */
                               4585         [ -  + ]:        1000450 :         if (attrnum < 0)
                               4586                 :                :         {
 1623 akapila@postgresql.o     4587         [ #  # ]:UBC           0 :             if (attrnum != TableOidAttributeNumber)
                               4588                 :                :             {
 1242 tgl@sss.pgh.pa.us        4589                 :              0 :                 modified = bms_add_member(modified, attidx);
 1623 akapila@postgresql.o     4590                 :              0 :                 continue;
                               4591                 :                :             }
                               4592                 :                :         }
                               4593                 :                : 
                               4594                 :                :         /*
                               4595                 :                :          * Extract the corresponding values.  XXX this is pretty inefficient
                               4596                 :                :          * if there are many indexed columns.  Should we do a single
                               4597                 :                :          * heap_deform_tuple call on each tuple, instead?   But that doesn't
                               4598                 :                :          * work for system columns ...
                               4599                 :                :          */
 1623 akapila@postgresql.o     4600                 :CBC     1000450 :         value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
                               4601                 :        1000450 :         value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
                               4602                 :                : 
                               4603         [ +  + ]:        1000450 :         if (!heap_attr_equals(tupdesc, attrnum, value1,
                               4604                 :                :                               value2, isnull1, isnull2))
                               4605                 :                :         {
 1242 tgl@sss.pgh.pa.us        4606                 :          54857 :             modified = bms_add_member(modified, attidx);
 1623 akapila@postgresql.o     4607                 :          54857 :             continue;
                               4608                 :                :         }
                               4609                 :                : 
                               4610                 :                :         /*
                               4611                 :                :          * No need to check attributes that can't be stored externally. Note
                               4612                 :                :          * that system attributes can't be stored externally.
                               4613                 :                :          */
                               4614   [ +  -  +  + ]:         945593 :         if (attrnum < 0 || isnull1 ||
  583 drowley@postgresql.o     4615         [ +  + ]:         938952 :             TupleDescCompactAttr(tupdesc, attrnum - 1)->attlen != -1)
 1623 akapila@postgresql.o     4616                 :         913213 :             continue;
                               4617                 :                : 
                               4618                 :                :         /*
                               4619                 :                :          * Check if the old tuple's attribute is stored externally and is a
                               4620                 :                :          * member of external_cols.
                               4621                 :                :          */
  165 michael@paquier.xyz      4622   [ +  +  +  + ]:          32385 :         if (VARATT_IS_EXTERNAL((varlena *) DatumGetPointer(value1)) &&
 1242 tgl@sss.pgh.pa.us        4623                 :              5 :             bms_is_member(attidx, external_cols))
 1623 akapila@postgresql.o     4624                 :              2 :             *has_external = true;
                               4625                 :                :     }
                               4626                 :                : 
 3406 alvherre@alvh.no-ip.     4627                 :        2389225 :     return modified;
                               4628                 :                : }
                               4629                 :                : 
                               4630                 :                : /*
                               4631                 :                :  *  simple_heap_update - replace a tuple
                               4632                 :                :  *
                               4633                 :                :  * This routine may be used to update a tuple when concurrent updates of
                               4634                 :                :  * the target tuple are not expected (for example, because we have a lock
                               4635                 :                :  * on the relation associated with the tuple).  Any failure is reported
                               4636                 :                :  * via ereport().
                               4637                 :                :  */
                               4638                 :                : void
  269 peter@eisentraut.org     4639                 :         144870 : simple_heap_update(Relation relation, const ItemPointerData *otid, HeapTuple tup,
                               4640                 :                :                    TU_UpdateIndexes *update_indexes)
                               4641                 :                : {
                               4642                 :                :     TM_Result   result;
                               4643                 :                :     TM_FailureData tmfd;
                               4644                 :                :     LockTupleMode lockmode;
                               4645                 :                : 
 8350 tgl@sss.pgh.pa.us        4646                 :         144870 :     result = heap_update(relation, otid, tup,
                               4647                 :                :                          GetCurrentCommandId(true), 0,
                               4648                 :                :                          InvalidSnapshot,
                               4649                 :                :                          true /* wait for commit */ ,
                               4650                 :                :                          &tmfd, &lockmode, update_indexes);
 9315                          4651   [ -  +  -  +  :         144870 :     switch (result)
                                                 - ]
                               4652                 :                :     {
 2682 andres@anarazel.de       4653                 :UBC           0 :         case TM_SelfModified:
                               4654                 :                :             /* Tuple was already updated in current command? */
 8406 tgl@sss.pgh.pa.us        4655         [ #  # ]:              0 :             elog(ERROR, "tuple already updated by self");
                               4656                 :                :             break;
                               4657                 :                : 
 2682 andres@anarazel.de       4658                 :CBC      144869 :         case TM_Ok:
                               4659                 :                :             /* done successfully */
 9315 tgl@sss.pgh.pa.us        4660                 :         144869 :             break;
                               4661                 :                : 
 2682 andres@anarazel.de       4662                 :UBC           0 :         case TM_Updated:
 8406 tgl@sss.pgh.pa.us        4663         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently updated");
                               4664                 :                :             break;
                               4665                 :                : 
 2682 andres@anarazel.de       4666                 :CBC           1 :         case TM_Deleted:
                               4667         [ +  - ]:              1 :             elog(ERROR, "tuple concurrently deleted");
                               4668                 :                :             break;
                               4669                 :                : 
 9315 tgl@sss.pgh.pa.us        4670                 :UBC           0 :         default:
 8406                          4671         [ #  # ]:              0 :             elog(ERROR, "unrecognized heap_update status: %u", result);
                               4672                 :                :             break;
                               4673                 :                :     }
 9315 tgl@sss.pgh.pa.us        4674                 :CBC      144869 : }
                               4675                 :                : 
                               4676                 :                : 
                               4677                 :                : /*
                               4678                 :                :  * Return the MultiXactStatus corresponding to the given tuple lock mode.
                               4679                 :                :  */
                               4680                 :                : static MultiXactStatus
 4932 alvherre@alvh.no-ip.     4681                 :         115522 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
                               4682                 :                : {
                               4683                 :                :     int         retval;
                               4684                 :                : 
                               4685         [ +  + ]:         115522 :     if (is_update)
                               4686                 :            216 :         retval = tupleLockExtraInfo[mode].updstatus;
                               4687                 :                :     else
                               4688                 :         115306 :         retval = tupleLockExtraInfo[mode].lockstatus;
                               4689                 :                : 
                               4690         [ -  + ]:         115522 :     if (retval == -1)
 4932 alvherre@alvh.no-ip.     4691   [ #  #  #  # ]:UBC           0 :         elog(ERROR, "invalid lock tuple mode %d/%s", mode,
                               4692                 :                :              is_update ? "true" : "false");
                               4693                 :                : 
 4779 alvherre@alvh.no-ip.     4694                 :CBC      115522 :     return (MultiXactStatus) retval;
                               4695                 :                : }
                               4696                 :                : 
                               4697                 :                : /*
                               4698                 :                :  *  heap_lock_tuple - lock a tuple in shared or exclusive mode
                               4699                 :                :  *
                               4700                 :                :  * Note that this acquires a buffer pin, which the caller must release.
                               4701                 :                :  *
                               4702                 :                :  * Input parameters:
                               4703                 :                :  *  relation: relation containing tuple (caller must hold suitable lock)
                               4704                 :                :  *  cid: current command ID (used for visibility test, and stored into
                               4705                 :                :  *      tuple's cmax if lock is successful)
                               4706                 :                :  *  mode: indicates if shared or exclusive tuple lock is desired
                               4707                 :                :  *  wait_policy: what to do if tuple lock is not available
                               4708                 :                :  *  follow_updates: if true, follow the update chain to also lock descendant
                               4709                 :                :  *      tuples.
                               4710                 :                :  *
                               4711                 :                :  * Output parameters:
                               4712                 :                :  *  *tuple: all fields filled in
                               4713                 :                :  *  *buffer: set to buffer holding tuple (pinned but not locked at exit)
                               4714                 :                :  *  *tmfd: filled in failure cases (see below)
                               4715                 :                :  *
                               4716                 :                :  * Function results are the same as the ones for table_tuple_lock().
                               4717                 :                :  *
                               4718                 :                :  * In the failure cases other than TM_Invisible, the routine fills
                               4719                 :                :  * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
                               4720                 :                :  * if necessary), and t_cmax (the last only for TM_SelfModified,
                               4721                 :                :  * since we cannot obtain cmax from a combo CID generated by another
                               4722                 :                :  * transaction).
                               4723                 :                :  * See comments for struct TM_FailureData for additional info.
                               4724                 :                :  *
                               4725                 :                :  * See README.tuplock for a thorough explanation of this mechanism.
                               4726                 :                :  */
                               4727                 :                : TM_Result
  836 akorotkov@postgresql     4728                 :         571704 : heap_lock_tuple(Relation relation, HeapTuple tuple,
                               4729                 :                :                 CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
                               4730                 :                :                 bool follow_updates,
                               4731                 :                :                 Buffer *buffer, TM_FailureData *tmfd)
                               4732                 :                : {
                               4733                 :                :     TM_Result   result;
                               4734                 :         571704 :     ItemPointer tid = &(tuple->t_self);
                               4735                 :                :     ItemId      lp;
                               4736                 :                :     Page        page;
 3660 andres@anarazel.de       4737                 :         571704 :     Buffer      vmbuffer = InvalidBuffer;
   11 melanieplageman@gmai     4738                 :         571704 :     bool        unlock_vmbuffer = false;
                               4739                 :                :     BlockNumber block;
                               4740                 :                :     TransactionId xid,
                               4741                 :                :                 xmax;
                               4742                 :                :     uint16      old_infomask,
                               4743                 :                :                 new_infomask,
                               4744                 :                :                 new_infomask2;
 4125 alvherre@alvh.no-ip.     4745                 :         571704 :     bool        first_time = true;
 2595                          4746                 :         571704 :     bool        skip_tuple_lock = false;
 7757 tgl@sss.pgh.pa.us        4747                 :         571704 :     bool        have_tuple_lock = false;
 3660 andres@anarazel.de       4748                 :         571704 :     bool        cleared_all_frozen = false;
                               4749                 :                : 
  836 akorotkov@postgresql     4750                 :         571704 :     *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
 3660 andres@anarazel.de       4751                 :         571704 :     block = ItemPointerGetBlockNumber(tid);
   11 melanieplageman@gmai     4752                 :         571704 :     page = BufferGetPage(*buffer);
                               4753                 :                : 
                               4754                 :                :     /*
                               4755                 :                :      * Before locking the buffer, pin the visibility map page if it appears to
                               4756                 :                :      * be necessary.  Since we haven't got the lock yet, someone else might be
                               4757                 :                :      * in the middle of changing this, so we'll need to recheck after we have
                               4758                 :                :      * the lock.
                               4759                 :                :      */
                               4760         [ +  + ]:         571704 :     if (PageIsAllVisible(page))
 3660 andres@anarazel.de       4761                 :         413509 :         visibilitymap_pin(relation, block, &vmbuffer);
                               4762                 :                : 
  836 akorotkov@postgresql     4763                 :         571704 :     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4764                 :                : 
 6587 tgl@sss.pgh.pa.us        4765                 :         571704 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
 6892                          4766         [ -  + ]:         571704 :     Assert(ItemIdIsNormal(lp));
                               4767                 :                : 
 6587                          4768                 :         571704 :     tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
10085 vadim4o@yahoo.com        4769                 :         571704 :     tuple->t_len = ItemIdGetLength(lp);
 7645 tgl@sss.pgh.pa.us        4770                 :         571704 :     tuple->t_tableOid = RelationGetRelid(relation);
                               4771                 :                : 
10085 vadim4o@yahoo.com        4772                 :             15 : l3:
  836 akorotkov@postgresql     4773                 :         571719 :     result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
                               4774                 :                : 
 2682 andres@anarazel.de       4775         [ +  + ]:         571719 :     if (result == TM_Invisible)
                               4776                 :                :     {
                               4777                 :                :         /*
                               4778                 :                :          * This is possible, but only when locking a tuple for ON CONFLICT DO
                               4779                 :                :          * SELECT/UPDATE.  We return this value here rather than throwing an
                               4780                 :                :          * error in order to give that case the opportunity to throw a more
                               4781                 :                :          * specific error.
                               4782                 :                :          */
                               4783                 :             28 :         result = TM_Invisible;
 3660                          4784                 :             28 :         goto out_locked;
                               4785                 :                :     }
 2682                          4786   [ +  +  +  + ]:         571691 :     else if (result == TM_BeingModified ||
                               4787         [ +  + ]:          81052 :              result == TM_Updated ||
                               4788                 :                :              result == TM_Deleted)
                               4789                 :                :     {
                               4790                 :                :         TransactionId xwait;
                               4791                 :                :         uint16      infomask;
                               4792                 :                :         uint16      infomask2;
                               4793                 :                :         bool        require_sleep;
                               4794                 :                :         ItemPointerData t_ctid;
                               4795                 :                : 
                               4796                 :                :         /* must copy state data before unlocking buffer */
 4932 alvherre@alvh.no-ip.     4797                 :         490640 :         xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
 7757 tgl@sss.pgh.pa.us        4798                 :         490640 :         infomask = tuple->t_data->t_infomask;
 4932 alvherre@alvh.no-ip.     4799                 :         490640 :         infomask2 = tuple->t_data->t_infomask2;
                               4800                 :         490640 :         ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
                               4801                 :                : 
  836 akorotkov@postgresql     4802                 :         490640 :         LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
                               4803                 :                : 
                               4804                 :                :         /*
                               4805                 :                :          * If any subtransaction of the current top transaction already holds
                               4806                 :                :          * a lock as strong as or stronger than what we're requesting, we
                               4807                 :                :          * effectively hold the desired lock already.  We *must* succeed
                               4808                 :                :          * without trying to take the tuple lock, else we will deadlock
                               4809                 :                :          * against anyone wanting to acquire a stronger lock.
                               4810                 :                :          *
                               4811                 :                :          * Note we only do this the first time we loop on the HTSU result;
                               4812                 :                :          * there is no point in testing in subsequent passes, because
                               4813                 :                :          * evidently our own transaction cannot have acquired a new lock after
                               4814                 :                :          * the first time we checked.
                               4815                 :                :          */
 4125 alvherre@alvh.no-ip.     4816         [ +  + ]:         490640 :         if (first_time)
                               4817                 :                :         {
                               4818                 :         490629 :             first_time = false;
                               4819                 :                : 
                               4820         [ +  + ]:         490629 :             if (infomask & HEAP_XMAX_IS_MULTI)
                               4821                 :                :             {
                               4822                 :                :                 int         i;
                               4823                 :                :                 int         nmembers;
                               4824                 :                :                 MultiXactMember *members;
                               4825                 :                : 
                               4826                 :                :                 /*
                               4827                 :                :                  * We don't need to allow old multixacts here; if that had
                               4828                 :                :                  * been the case, HeapTupleSatisfiesUpdate would have returned
                               4829                 :                :                  * MayBeUpdated and we wouldn't be here.
                               4830                 :                :                  */
                               4831                 :                :                 nmembers =
                               4832                 :          73297 :                     GetMultiXactIdMembers(xwait, &members, false,
                               4833                 :          73297 :                                           HEAP_XMAX_IS_LOCKED_ONLY(infomask));
                               4834                 :                : 
                               4835         [ +  + ]:        1422663 :                 for (i = 0; i < nmembers; i++)
                               4836                 :                :                 {
                               4837                 :                :                     /* only consider members of our own transaction */
                               4838         [ +  + ]:        1349380 :                     if (!TransactionIdIsCurrentTransactionId(members[i].xid))
                               4839                 :        1349330 :                         continue;
                               4840                 :                : 
                               4841         [ +  + ]:             50 :                     if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
                               4842                 :                :                     {
 4932                          4843                 :             14 :                         pfree(members);
 2682 andres@anarazel.de       4844                 :             14 :                         result = TM_Ok;
 3660                          4845                 :             14 :                         goto out_unlocked;
                               4846                 :                :                     }
                               4847                 :                :                     else
                               4848                 :                :                     {
                               4849                 :                :                         /*
                               4850                 :                :                          * Disable acquisition of the heavyweight tuple lock.
                               4851                 :                :                          * Otherwise, when promoting a weaker lock, we might
                               4852                 :                :                          * deadlock with another locker that has acquired the
                               4853                 :                :                          * heavyweight tuple lock and is waiting for our
                               4854                 :                :                          * transaction to finish.
                               4855                 :                :                          *
                               4856                 :                :                          * Note that in this case we still need to wait for
                               4857                 :                :                          * the multixact if required, to avoid acquiring
                               4858                 :                :                          * conflicting locks.
                               4859                 :                :                          */
 2595 alvherre@alvh.no-ip.     4860                 :             36 :                         skip_tuple_lock = true;
                               4861                 :                :                     }
                               4862                 :                :                 }
                               4863                 :                : 
 4125                          4864         [ +  - ]:          73283 :                 if (members)
                               4865                 :          73283 :                     pfree(members);
                               4866                 :                :             }
                               4867         [ +  + ]:         417332 :             else if (TransactionIdIsCurrentTransactionId(xwait))
                               4868                 :                :             {
                               4869   [ +  +  +  +  :         415907 :                 switch (mode)
                                                 - ]
                               4870                 :                :                 {
                               4871                 :         409468 :                     case LockTupleKeyShare:
                               4872   [ -  +  -  -  :         409468 :                         Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
                                              -  - ]
                               4873                 :                :                                HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
                               4874                 :                :                                HEAP_XMAX_IS_EXCL_LOCKED(infomask));
 2682 andres@anarazel.de       4875                 :         409468 :                         result = TM_Ok;
 3660                          4876                 :         409468 :                         goto out_unlocked;
 4125 alvherre@alvh.no-ip.     4877                 :             32 :                     case LockTupleShare:
                               4878   [ +  +  -  + ]:             38 :                         if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
                               4879                 :              6 :                             HEAP_XMAX_IS_EXCL_LOCKED(infomask))
                               4880                 :                :                         {
 2682 andres@anarazel.de       4881                 :             26 :                             result = TM_Ok;
 3660                          4882                 :             26 :                             goto out_unlocked;
                               4883                 :                :                         }
 4125 alvherre@alvh.no-ip.     4884                 :              6 :                         break;
                               4885                 :             85 :                     case LockTupleNoKeyExclusive:
                               4886         [ +  + ]:             85 :                         if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
                               4887                 :                :                         {
 2682 andres@anarazel.de       4888                 :             72 :                             result = TM_Ok;
 3660                          4889                 :             72 :                             goto out_unlocked;
                               4890                 :                :                         }
 4125 alvherre@alvh.no-ip.     4891                 :             13 :                         break;
                               4892                 :           6322 :                     case LockTupleExclusive:
                               4893         [ +  + ]:           6322 :                         if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
                               4894         [ +  + ]:           1280 :                             infomask2 & HEAP_KEYS_UPDATED)
                               4895                 :                :                         {
 2682 andres@anarazel.de       4896                 :           1251 :                             result = TM_Ok;
 3660                          4897                 :           1251 :                             goto out_unlocked;
                               4898                 :                :                         }
 4125 alvherre@alvh.no-ip.     4899                 :           5071 :                         break;
                               4900                 :                :                 }
                               4901                 :                :             }
                               4902                 :                :         }
                               4903                 :                : 
                               4904                 :                :         /*
                               4905                 :                :          * Initially assume that we will have to wait for the locking
                               4906                 :                :          * transaction(s) to finish.  We check various cases below in which
                               4907                 :                :          * this can be turned off.
                               4908                 :                :          */
 4932                          4909                 :          79809 :         require_sleep = true;
                               4910         [ +  + ]:          79809 :         if (mode == LockTupleKeyShare)
                               4911                 :                :         {
                               4912                 :                :             /*
                               4913                 :                :              * If we're requesting KeyShare, and there's no update present, we
                               4914                 :                :              * don't need to wait.  Even if there is an update, we can still
                               4915                 :                :              * continue if the key hasn't been modified.
                               4916                 :                :              *
                               4917                 :                :              * However, if there are updates, we need to walk the update chain
                               4918                 :                :              * to mark future versions of the row as locked, too.  That way,
                               4919                 :                :              * if somebody deletes that future version, we're protected
                               4920                 :                :              * against the key going away.  This locking of future versions
                               4921                 :                :              * could block momentarily, if a concurrent transaction is
                               4922                 :                :              * deleting a key; or it could return a value to the effect that
                               4923                 :                :              * the transaction deleting the key has already committed.  So we
                               4924                 :                :              * do this before re-locking the buffer; otherwise this would be
                               4925                 :                :              * prone to deadlocks.
                               4926                 :                :              *
                               4927                 :                :              * Note that the TID we're locking was grabbed before we unlocked
                               4928                 :                :              * the buffer.  For it to change while we're not looking, the
                               4929                 :                :              * other properties we're testing for below after re-locking the
                               4930                 :                :              * buffer would also change, in which case we would restart this
                               4931                 :                :              * loop above.
                               4932                 :                :              */
                               4933         [ +  + ]:          73897 :             if (!(infomask2 & HEAP_KEYS_UPDATED))
                               4934                 :                :             {
                               4935                 :                :                 bool        updated;
                               4936                 :                : 
                               4937                 :          73850 :                 updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
                               4938                 :                : 
                               4939                 :                :                 /*
                               4940                 :                :                  * If there are updates, follow the update chain; bail out if
                               4941                 :                :                  * that cannot be done.
                               4942                 :                :                  */
  215 heikki.linnakangas@i     4943   [ +  -  +  + ]:          73850 :                 if (follow_updates && updated &&
                               4944         [ +  - ]:           2171 :                     !ItemPointerEquals(&tuple->t_self, &t_ctid))
                               4945                 :                :                 {
                               4946                 :                :                     TM_Result   res;
                               4947                 :                : 
                               4948                 :           2171 :                     res = heap_lock_updated_tuple(relation,
                               4949                 :                :                                                   infomask, xwait, &t_ctid,
                               4950                 :                :                                                   GetCurrentTransactionId(),
                               4951                 :                :                                                   mode);
 2682 andres@anarazel.de       4952         [ +  + ]:           2171 :                     if (res != TM_Ok)
                               4953                 :                :                     {
 4932 alvherre@alvh.no-ip.     4954                 :              6 :                         result = res;
                               4955                 :                :                         /* recovery code expects to have buffer lock held */
  836 akorotkov@postgresql     4956                 :              6 :                         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4932 alvherre@alvh.no-ip.     4957                 :            207 :                         goto failed;
                               4958                 :                :                     }
                               4959                 :                :                 }
                               4960                 :                : 
  836 akorotkov@postgresql     4961                 :          73844 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4962                 :                : 
                               4963                 :                :                 /*
                               4964                 :                :                  * Make sure it's still an appropriate lock, else start over.
                               4965                 :                :                  * Also, if it wasn't updated before we released the lock, but
                               4966                 :                :                  * is updated now, we start over too; the reason is that we
                               4967                 :                :                  * now need to follow the update chain to lock the new
                               4968                 :                :                  * versions.
                               4969                 :                :                  */
 4932 alvherre@alvh.no-ip.     4970         [ +  + ]:          73844 :                 if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
                               4971         [ +  - ]:           2153 :                     ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
                               4972         [ -  + ]:           2153 :                      !updated))
                               4973                 :             15 :                     goto l3;
                               4974                 :                : 
                               4975                 :                :                 /* Things look okay, so we can skip sleeping */
                               4976                 :          73844 :                 require_sleep = false;
                               4977                 :                : 
                               4978                 :                :                 /*
                               4979                 :                :                  * Note we allow Xmax to change here; other updaters/lockers
                               4980                 :                :                  * could have modified it before we grabbed the buffer lock.
                               4981                 :                :                  * However, this is not a problem, because with the recheck we
                               4982                 :                :                  * just did we ensure that they still don't conflict with the
                               4983                 :                :                  * lock we want.
                               4984                 :                :                  */
                               4985                 :                :             }
                               4986                 :                :         }
                               4987         [ +  + ]:           5912 :         else if (mode == LockTupleShare)
                               4988                 :                :         {
                               4989                 :                :             /*
                               4990                 :                :              * If we're requesting Share, we can similarly avoid sleeping if
                               4991                 :                :              * there's no update and no exclusive lock present.
                               4992                 :                :              */
                               4993         [ +  - ]:            481 :             if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
                               4994         [ +  + ]:            481 :                 !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
                               4995                 :                :             {
  836 akorotkov@postgresql     4996                 :            475 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4997                 :                : 
                               4998                 :                :                 /*
                               4999                 :                :                  * Make sure it's still an appropriate lock, else start over.
                               5000                 :                :                  * See above about allowing xmax to change.
                               5001                 :                :                  */
 4932 alvherre@alvh.no-ip.     5002   [ +  -  -  + ]:            950 :                 if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
                               5003                 :            475 :                     HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
 4932 alvherre@alvh.no-ip.     5004                 :UBC           0 :                     goto l3;
 4932 alvherre@alvh.no-ip.     5005                 :CBC         475 :                 require_sleep = false;
                               5006                 :                :             }
                               5007                 :                :         }
                               5008         [ +  + ]:           5431 :         else if (mode == LockTupleNoKeyExclusive)
                               5009                 :                :         {
                               5010                 :                :             /*
                               5011                 :                :              * If we're requesting NoKeyExclusive, we might also be able to
                               5012                 :                :              * avoid sleeping; just ensure that there no conflicting lock
                               5013                 :                :              * already acquired.
                               5014                 :                :              */
                               5015         [ +  + ]:            175 :             if (infomask & HEAP_XMAX_IS_MULTI)
                               5016                 :                :             {
 4230                          5017         [ +  + ]:             26 :                 if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
                               5018                 :                :                                              mode, NULL))
                               5019                 :                :                 {
                               5020                 :                :                     /*
                               5021                 :                :                      * No conflict, but if the xmax changed under us in the
                               5022                 :                :                      * meantime, start over.
                               5023                 :                :                      */
  836 akorotkov@postgresql     5024                 :             13 :                     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4230 alvherre@alvh.no-ip.     5025   [ +  -  -  + ]:             26 :                     if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
                               5026                 :             13 :                         !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               5027                 :                :                                              xwait))
 4230 alvherre@alvh.no-ip.     5028                 :UBC           0 :                         goto l3;
                               5029                 :                : 
                               5030                 :                :                     /* otherwise, we're good */
 4230 alvherre@alvh.no-ip.     5031                 :CBC          13 :                     require_sleep = false;
                               5032                 :                :                 }
                               5033                 :                :             }
 4932                          5034         [ +  + ]:            149 :             else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
                               5035                 :                :             {
  836 akorotkov@postgresql     5036                 :             19 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               5037                 :                : 
                               5038                 :                :                 /* if the xmax changed in the meantime, start over */
 4476 alvherre@alvh.no-ip.     5039   [ +  -  -  + ]:             38 :                 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
 2369                          5040                 :             19 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               5041                 :                :                                          xwait))
 4932 alvherre@alvh.no-ip.     5042                 :UBC           0 :                     goto l3;
                               5043                 :                :                 /* otherwise, we're good */
 4932 alvherre@alvh.no-ip.     5044                 :CBC          19 :                 require_sleep = false;
                               5045                 :                :             }
                               5046                 :                :         }
                               5047                 :                : 
                               5048                 :                :         /*
                               5049                 :                :          * As a check independent from those above, we can also avoid sleeping
                               5050                 :                :          * if the current transaction is the sole locker of the tuple.  Note
                               5051                 :                :          * that the strength of the lock already held is irrelevant; this is
                               5052                 :                :          * not about recording the lock in Xmax (which will be done regardless
                               5053                 :                :          * of this optimization, below).  Also, note that the cases where we
                               5054                 :                :          * hold a lock stronger than we are requesting are already handled
                               5055                 :                :          * above by not doing anything.
                               5056                 :                :          *
                               5057                 :                :          * Note we only deal with the non-multixact case here; MultiXactIdWait
                               5058                 :                :          * is well equipped to deal with this situation on its own.
                               5059                 :                :          */
 4125                          5060   [ +  +  +  +  :          85212 :         if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
                                              +  + ]
                               5061                 :           5409 :             TransactionIdIsCurrentTransactionId(xwait))
                               5062                 :                :         {
                               5063                 :                :             /* ... but if the xmax changed in the meantime, start over */
  836 akorotkov@postgresql     5064                 :           5071 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4125 alvherre@alvh.no-ip.     5065   [ +  -  -  + ]:          10142 :             if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
                               5066                 :           5071 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               5067                 :                :                                      xwait))
 4125 alvherre@alvh.no-ip.     5068                 :UBC           0 :                 goto l3;
 4125 alvherre@alvh.no-ip.     5069         [ -  + ]:CBC        5071 :             Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
                               5070                 :           5071 :             require_sleep = false;
                               5071                 :                :         }
                               5072                 :                : 
                               5073                 :                :         /*
                               5074                 :                :          * Time to sleep on the other transaction/multixact, if necessary.
                               5075                 :                :          *
                               5076                 :                :          * If the other transaction is an update/delete that's already
                               5077                 :                :          * committed, then sleeping cannot possibly do any good: if we're
                               5078                 :                :          * required to sleep, get out to raise an error instead.
                               5079                 :                :          *
                               5080                 :                :          * By here, we either have already acquired the buffer exclusive lock,
                               5081                 :                :          * or we must wait for the locking transaction or multixact; so below
                               5082                 :                :          * we ensure that we grab buffer lock after the sleep.
                               5083                 :                :          */
 2682 andres@anarazel.de       5084   [ +  +  +  +  :          79803 :         if (require_sleep && (result == TM_Updated || result == TM_Deleted))
                                              +  + ]
                               5085                 :                :         {
  836 akorotkov@postgresql     5086                 :            162 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3663 alvherre@alvh.no-ip.     5087                 :            162 :             goto failed;
                               5088                 :                :         }
                               5089         [ +  + ]:          79641 :         else if (require_sleep)
                               5090                 :                :         {
                               5091                 :                :             /*
                               5092                 :                :              * Acquire tuple lock to establish our priority for the tuple, or
                               5093                 :                :              * die trying.  LockTuple will release us when we are next-in-line
                               5094                 :                :              * for the tuple.  We must do this even if we are share-locking,
                               5095                 :                :              * but not if we already have a weaker lock on the tuple.
                               5096                 :                :              *
                               5097                 :                :              * If we are forced to "start over" below, we keep the tuple lock;
                               5098                 :                :              * this arranges that we stay at the head of the line while
                               5099                 :                :              * rechecking tuple state.
                               5100                 :                :              */
 2595                          5101         [ +  + ]:            219 :             if (!skip_tuple_lock &&
                               5102         [ +  + ]:            202 :                 !heap_acquire_tuplock(relation, tid, mode, wait_policy,
                               5103                 :                :                                       &have_tuple_lock))
                               5104                 :                :             {
                               5105                 :                :                 /*
                               5106                 :                :                  * This can only happen if wait_policy is Skip and the lock
                               5107                 :                :                  * couldn't be obtained.
                               5108                 :                :                  */
 2682 andres@anarazel.de       5109                 :              1 :                 result = TM_WouldBlock;
                               5110                 :                :                 /* recovery code expects to have buffer lock held */
  836 akorotkov@postgresql     5111                 :              1 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4230 alvherre@alvh.no-ip.     5112                 :              1 :                 goto failed;
                               5113                 :                :             }
                               5114                 :                : 
 4932                          5115         [ +  + ]:            217 :             if (infomask & HEAP_XMAX_IS_MULTI)
                               5116                 :                :             {
                               5117                 :             43 :                 MultiXactStatus status = get_mxact_status_for_lock(mode, false);
                               5118                 :                : 
                               5119                 :                :                 /* We only ever lock tuples, never update them */
                               5120         [ -  + ]:             43 :                 if (status >= MultiXactStatusNoKeyUpdate)
 4932 alvherre@alvh.no-ip.     5121         [ #  # ]:UBC           0 :                     elog(ERROR, "invalid lock mode in heap_lock_tuple");
                               5122                 :                : 
                               5123                 :                :                 /* wait for multixact to end, or die trying  */
 4310 alvherre@alvh.no-ip.     5124   [ +  +  +  - ]:CBC          43 :                 switch (wait_policy)
                               5125                 :                :                 {
                               5126                 :             37 :                     case LockWaitBlock:
                               5127                 :             37 :                         MultiXactIdWait((MultiXactId) xwait, status, infomask,
 3322 tgl@sss.pgh.pa.us        5128                 :             37 :                                         relation, &tuple->t_self, XLTW_Lock, NULL);
 4310 alvherre@alvh.no-ip.     5129                 :             37 :                         break;
                               5130                 :              2 :                     case LockWaitSkip:
                               5131         [ +  - ]:              2 :                         if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
                               5132                 :                :                                                         status, infomask, relation,
                               5133                 :                :                                                         NULL, false))
                               5134                 :                :                         {
 2682 andres@anarazel.de       5135                 :              2 :                             result = TM_WouldBlock;
                               5136                 :                :                             /* recovery code expects to have buffer lock held */
  836 akorotkov@postgresql     5137                 :              2 :                             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4310 alvherre@alvh.no-ip.     5138                 :              2 :                             goto failed;
                               5139                 :                :                         }
 4310 alvherre@alvh.no-ip.     5140                 :UBC           0 :                         break;
 4310 alvherre@alvh.no-ip.     5141                 :CBC           4 :                     case LockWaitError:
                               5142         [ +  - ]:              4 :                         if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
                               5143                 :                :                                                         status, infomask, relation,
                               5144                 :                :                                                         NULL, log_lock_failures))
                               5145         [ +  - ]:              4 :                             ereport(ERROR,
                               5146                 :                :                                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                               5147                 :                :                                      errmsg("could not obtain lock on row in relation \"%s\"",
                               5148                 :                :                                             RelationGetRelationName(relation))));
                               5149                 :                : 
 4310 alvherre@alvh.no-ip.     5150                 :UBC           0 :                         break;
                               5151                 :                :                 }
                               5152                 :                : 
                               5153                 :                :                 /*
                               5154                 :                :                  * Of course, the multixact might not be done here: if we're
                               5155                 :                :                  * requesting a light lock mode, other transactions with light
                               5156                 :                :                  * locks could still be alive, as well as locks owned by our
                               5157                 :                :                  * own xact or other subxacts of this backend.  We need to
                               5158                 :                :                  * preserve the surviving MultiXact members.  Note that it
                               5159                 :                :                  * isn't absolutely necessary in the latter case, but doing so
                               5160                 :                :                  * is simpler.
                               5161                 :                :                  */
                               5162                 :                :             }
                               5163                 :                :             else
                               5164                 :                :             {
                               5165                 :                :                 /* wait for regular transaction to end, or die trying */
 4310 alvherre@alvh.no-ip.     5166   [ +  +  +  - ]:CBC         174 :                 switch (wait_policy)
                               5167                 :                :                 {
                               5168                 :            133 :                     case LockWaitBlock:
 4190 heikki.linnakangas@i     5169                 :            133 :                         XactLockTableWait(xwait, relation, &tuple->t_self,
                               5170                 :                :                                           XLTW_Lock);
 4310 alvherre@alvh.no-ip.     5171                 :            133 :                         break;
                               5172                 :             33 :                     case LockWaitSkip:
  499 fujii@postgresql.org     5173         [ +  - ]:             33 :                         if (!ConditionalXactLockTableWait(xwait, false))
                               5174                 :                :                         {
 2682 andres@anarazel.de       5175                 :             33 :                             result = TM_WouldBlock;
                               5176                 :                :                             /* recovery code expects to have buffer lock held */
  836 akorotkov@postgresql     5177                 :             33 :                             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4310 alvherre@alvh.no-ip.     5178                 :             33 :                             goto failed;
                               5179                 :                :                         }
 4310 alvherre@alvh.no-ip.     5180                 :UBC           0 :                         break;
 4310 alvherre@alvh.no-ip.     5181                 :CBC           8 :                     case LockWaitError:
  418 fujii@postgresql.org     5182         [ +  - ]:              8 :                         if (!ConditionalXactLockTableWait(xwait, log_lock_failures))
 4310 alvherre@alvh.no-ip.     5183         [ +  - ]:              8 :                             ereport(ERROR,
                               5184                 :                :                                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                               5185                 :                :                                      errmsg("could not obtain lock on row in relation \"%s\"",
                               5186                 :                :                                             RelationGetRelationName(relation))));
 4310 alvherre@alvh.no-ip.     5187                 :UBC           0 :                         break;
                               5188                 :                :                 }
                               5189                 :                :             }
                               5190                 :                : 
                               5191                 :                :             /* if there are updates, follow the update chain */
  215 heikki.linnakangas@i     5192   [ +  +  +  + ]:CBC         170 :             if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
                               5193         [ +  + ]:             77 :                 !ItemPointerEquals(&tuple->t_self, &t_ctid))
                               5194                 :                :             {
                               5195                 :                :                 TM_Result   res;
                               5196                 :                : 
                               5197                 :             55 :                 res = heap_lock_updated_tuple(relation,
                               5198                 :                :                                               infomask, xwait, &t_ctid,
                               5199                 :                :                                               GetCurrentTransactionId(),
                               5200                 :                :                                               mode);
 2682 andres@anarazel.de       5201         [ +  + ]:             55 :                 if (res != TM_Ok)
                               5202                 :                :                 {
 4125 alvherre@alvh.no-ip.     5203                 :              3 :                     result = res;
                               5204                 :                :                     /* recovery code expects to have buffer lock held */
  836 akorotkov@postgresql     5205                 :              3 :                     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4125 alvherre@alvh.no-ip.     5206                 :              3 :                     goto failed;
                               5207                 :                :                 }
                               5208                 :                :             }
                               5209                 :                : 
  836 akorotkov@postgresql     5210                 :            167 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               5211                 :                : 
                               5212                 :                :             /*
                               5213                 :                :              * xwait is done, but if xwait had just locked the tuple then some
                               5214                 :                :              * other xact could update this tuple before we get to this point.
                               5215                 :                :              * Check for xmax change, and start over if so.
                               5216                 :                :              */
 4125 alvherre@alvh.no-ip.     5217   [ +  +  +  + ]:            321 :             if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
                               5218                 :            154 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               5219                 :                :                                      xwait))
                               5220                 :             15 :                 goto l3;
                               5221                 :                : 
                               5222         [ +  + ]:            152 :             if (!(infomask & HEAP_XMAX_IS_MULTI))
                               5223                 :                :             {
                               5224                 :                :                 /*
                               5225                 :                :                  * Otherwise check if it committed or aborted.  Note we cannot
                               5226                 :                :                  * be here if the tuple was only locked by somebody who didn't
                               5227                 :                :                  * conflict with us; that would have been handled above.  So
                               5228                 :                :                  * that transaction must necessarily be gone by now.  But
                               5229                 :                :                  * don't check for this in the multixact case, because some
                               5230                 :                :                  * locker transactions might still be running.
                               5231                 :                :                  */
  836 akorotkov@postgresql     5232                 :            117 :                 UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
                               5233                 :                :             }
                               5234                 :                :         }
                               5235                 :                : 
                               5236                 :                :         /* By here, we're certain that we hold buffer exclusive lock again */
                               5237                 :                : 
                               5238                 :                :         /*
                               5239                 :                :          * We may lock if previous xmax aborted, or if it committed but only
                               5240                 :                :          * locked the tuple without updating it; or if we didn't have to wait
                               5241                 :                :          * at all for whatever reason.
                               5242                 :                :          */
 4932 alvherre@alvh.no-ip.     5243         [ +  + ]:          79574 :         if (!require_sleep ||
                               5244   [ +  +  +  + ]:            268 :             (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
                               5245         [ +  + ]:            216 :             HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
                               5246                 :            100 :             HeapTupleHeaderIsOnlyLocked(tuple->t_data))
 2682 andres@anarazel.de       5247                 :          79482 :             result = TM_Ok;
 1980 alvherre@alvh.no-ip.     5248         [ +  + ]:             92 :         else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
 2682 andres@anarazel.de       5249                 :             66 :             result = TM_Updated;
                               5250                 :                :         else
                               5251                 :             26 :             result = TM_Deleted;
                               5252                 :                :     }
                               5253                 :                : 
 4932 alvherre@alvh.no-ip.     5254                 :          81051 : failed:
 2682 andres@anarazel.de       5255         [ +  + ]:         160832 :     if (result != TM_Ok)
                               5256                 :                :     {
                               5257   [ +  +  +  +  :            307 :         Assert(result == TM_SelfModified || result == TM_Updated ||
                                        +  +  -  + ]
                               5258                 :                :                result == TM_Deleted || result == TM_WouldBlock);
                               5259                 :                : 
                               5260                 :                :         /*
                               5261                 :                :          * When locking a tuple under LockWaitSkip semantics and we fail with
                               5262                 :                :          * TM_WouldBlock above, it's possible for concurrent transactions to
                               5263                 :                :          * release the lock and set HEAP_XMAX_INVALID in the meantime.  So
                               5264                 :                :          * this assert is slightly different from the equivalent one in
                               5265                 :                :          * heap_delete and heap_update.
                               5266                 :                :          */
 1664 alvherre@alvh.no-ip.     5267   [ +  +  -  + ]:            307 :         Assert((result == TM_WouldBlock) ||
                               5268                 :                :                !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
 2682 andres@anarazel.de       5269   [ +  +  -  + ]:            307 :         Assert(result != TM_Updated ||
                               5270                 :                :                !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
                               5271                 :            307 :         tmfd->ctid = tuple->t_data->t_ctid;
                               5272                 :            307 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
                               5273         [ +  + ]:            307 :         if (result == TM_SelfModified)
                               5274                 :              8 :             tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
                               5275                 :                :         else
                               5276                 :            299 :             tmfd->cmax = InvalidCommandId;
 3660                          5277                 :            307 :         goto out_locked;
                               5278                 :                :     }
                               5279                 :                : 
                               5280                 :                :     /*
                               5281                 :                :      * If we didn't pin the visibility map page and the page has become all
                               5282                 :                :      * visible while we were busy locking the buffer, or during some
                               5283                 :                :      * subsequent window during which we had it unlocked, we'll have to unlock
                               5284                 :                :      * and re-lock, to avoid holding the buffer lock across I/O.  That's a bit
                               5285                 :                :      * unfortunate, especially since we'll now have to recheck whether the
                               5286                 :                :      * tuple has been locked or updated under us, but hopefully it won't
                               5287                 :                :      * happen very often.
                               5288                 :                :      */
 3643                          5289   [ +  +  -  + ]:         160525 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
                               5290                 :                :     {
  836 akorotkov@postgresql     5291                 :UBC           0 :         LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
 3643 andres@anarazel.de       5292                 :              0 :         visibilitymap_pin(relation, block, &vmbuffer);
  836 akorotkov@postgresql     5293                 :              0 :         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3643 andres@anarazel.de       5294                 :              0 :         goto l3;
                               5295                 :                :     }
                               5296                 :                : 
 4932 alvherre@alvh.no-ip.     5297                 :CBC      160525 :     xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
                               5298                 :         160525 :     old_infomask = tuple->t_data->t_infomask;
                               5299                 :                : 
                               5300                 :                :     /*
                               5301                 :                :      * If this is the first possibly-multixact-able operation in the current
                               5302                 :                :      * transaction, set my per-backend OldestMemberMXactId setting. We can be
                               5303                 :                :      * certain that the transaction will never become a member of any older
                               5304                 :                :      * MultiXactIds than that.  (We have to do this even if we end up just
                               5305                 :                :      * using our own TransactionId below, since some other backend could
                               5306                 :                :      * incorporate our XID into a MultiXact immediately afterwards.)
                               5307                 :                :      */
                               5308                 :         160525 :     MultiXactIdSetOldestMember();
                               5309                 :                : 
                               5310                 :                :     /*
                               5311                 :                :      * Compute the new xmax and infomask to store into the tuple.  Note we do
                               5312                 :                :      * not modify the tuple just yet, because that would leave it in the wrong
                               5313                 :                :      * state if multixact.c elogs.
                               5314                 :                :      */
                               5315                 :         160525 :     compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
                               5316                 :                :                               GetCurrentTransactionId(), mode, false,
                               5317                 :                :                               &xid, &new_infomask, &new_infomask2);
                               5318                 :                : 
                               5319                 :                :     /* Lock VM buffer before entering critical section */
   11 melanieplageman@gmai     5320         [ +  + ]:         160525 :     if (PageIsAllVisible(page))
                               5321                 :                :     {
                               5322                 :           3612 :         LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
                               5323                 :           3612 :         unlock_vmbuffer = true;
                               5324                 :                :     }
                               5325                 :                : 
 7759 tgl@sss.pgh.pa.us        5326                 :         160525 :     START_CRIT_SECTION();
                               5327                 :                : 
                               5328                 :                :     /*
                               5329                 :                :      * Store transaction information of xact locking the tuple.
                               5330                 :                :      *
                               5331                 :                :      * Note: Cmax is meaningless in this context, so don't set it; this avoids
                               5332                 :                :      * possibly generating a useless combo CID.  Moreover, if we're locking a
                               5333                 :                :      * previously updated tuple, it's important to preserve the Cmax.
                               5334                 :                :      *
                               5335                 :                :      * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
                               5336                 :                :      * we would break the HOT chain.
                               5337                 :                :      */
 4932 alvherre@alvh.no-ip.     5338                 :         160525 :     tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
                               5339                 :         160525 :     tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               5340                 :         160525 :     tuple->t_data->t_infomask |= new_infomask;
                               5341                 :         160525 :     tuple->t_data->t_infomask2 |= new_infomask2;
                               5342         [ +  + ]:         160525 :     if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
                               5343                 :         158376 :         HeapTupleHeaderClearHotUpdated(tuple->t_data);
 7983 tgl@sss.pgh.pa.us        5344                 :         160525 :     HeapTupleHeaderSetXmax(tuple->t_data, xid);
                               5345                 :                : 
                               5346                 :                :     /*
                               5347                 :                :      * Make sure there is no forward chain link in t_ctid.  Note that in the
                               5348                 :                :      * cases where the tuple has been updated, we must not overwrite t_ctid,
                               5349                 :                :      * because it was set by the updater.  Moreover, if the tuple has been
                               5350                 :                :      * updated, we need to follow the update chain to lock the new versions of
                               5351                 :                :      * the tuple as well.
                               5352                 :                :      */
 4932 alvherre@alvh.no-ip.     5353         [ +  + ]:         160525 :     if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
                               5354                 :         158376 :         tuple->t_data->t_ctid = *tid;
                               5355                 :                : 
                               5356                 :                :     /* Clear only the all-frozen bit on visibility map if needed */
   11 melanieplageman@gmai     5357         [ +  + ]:         160525 :     if (PageIsAllVisible(page))
                               5358                 :                :     {
   11 melanieplageman@gmai     5359         [ +  + ]:GNC        3612 :         if (visibilitymap_clear(relation->rd_locator, block, vmbuffer,
                               5360                 :                :                                 VISIBILITYMAP_ALL_FROZEN))
   11 melanieplageman@gmai     5361                 :CBC          17 :             cleared_all_frozen = true;
                               5362                 :                :     }
                               5363                 :                : 
                               5364                 :                : 
  836 akorotkov@postgresql     5365                 :         160525 :     MarkBufferDirty(*buffer);
                               5366                 :                : 
                               5367                 :                :     /*
                               5368                 :                :      * XLOG stuff.  You might think that we don't need an XLOG record because
                               5369                 :                :      * there is no state change worth restoring after a crash.  You would be
                               5370                 :                :      * wrong however: we have just written either a TransactionId or a
                               5371                 :                :      * MultiXactId that may never have been seen on disk before, and we need
                               5372                 :                :      * to make sure that there are XLOG entries covering those ID numbers.
                               5373                 :                :      * Else the same IDs might be re-used after a crash, which would be
                               5374                 :                :      * disastrous if this page made it to disk before the crash.  Essentially
                               5375                 :                :      * we have to enforce the WAL log-before-data rule even in this case.
                               5376                 :                :      * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
                               5377                 :                :      * entries for everything anyway.)
                               5378                 :                :      */
 5704 rhaas@postgresql.org     5379   [ +  +  +  +  :         160525 :     if (RelationNeedsWAL(relation))
                                        +  -  +  - ]
                               5380                 :                :     {
                               5381                 :                :         xl_heap_lock xlrec;
                               5382                 :                :         XLogRecPtr  recptr;
                               5383                 :                : 
 4266 heikki.linnakangas@i     5384                 :         160096 :         XLogBeginInsert();
   11 melanieplageman@gmai     5385                 :         160096 :         XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, *buffer, REGBUF_STANDARD);
                               5386                 :                : 
 4266 heikki.linnakangas@i     5387                 :         160096 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
 1202 pg@bowt.ie               5388                 :         160096 :         xlrec.xmax = xid;
 4932 alvherre@alvh.no-ip.     5389                 :         320192 :         xlrec.infobits_set = compute_infobits(new_infomask,
                               5390                 :         160096 :                                               tuple->t_data->t_infomask2);
 3660 andres@anarazel.de       5391                 :         160096 :         xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
  530 peter@eisentraut.org     5392                 :         160096 :         XLogRegisterData(&xlrec, SizeOfHeapLock);
                               5393                 :                : 
   11 melanieplageman@gmai     5394         [ +  + ]:         160096 :         if (cleared_all_frozen)
                               5395                 :             17 :             XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
                               5396                 :                : 
                               5397                 :                :         /* we don't decode row locks atm, so no need to log the origin */
                               5398                 :                : 
 4266 heikki.linnakangas@i     5399                 :         160096 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
                               5400                 :                : 
 6587 tgl@sss.pgh.pa.us        5401                 :         160096 :         PageSetLSN(page, recptr);
                               5402                 :                : 
   11 melanieplageman@gmai     5403         [ +  + ]:         160096 :         if (cleared_all_frozen)
                               5404                 :             17 :             PageSetLSN(BufferGetPage(vmbuffer), recptr);
                               5405                 :                :     }
                               5406                 :                : 
 7759 tgl@sss.pgh.pa.us        5407         [ -  + ]:         160525 :     END_CRIT_SECTION();
                               5408                 :                : 
                               5409                 :                :     /* release VM lock first, since it covers many heap blocks */
   11 melanieplageman@gmai     5410         [ +  + ]:         160525 :     if (unlock_vmbuffer)
                               5411                 :                :     {
                               5412                 :           3612 :         LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
                               5413                 :           3612 :         unlock_vmbuffer = false;
                               5414                 :                :     }
                               5415                 :                : 
 2682 andres@anarazel.de       5416                 :         160525 :     result = TM_Ok;
                               5417                 :                : 
 3660                          5418                 :         160860 : out_locked:
  836 akorotkov@postgresql     5419                 :         160860 :     LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
   11 melanieplageman@gmai     5420         [ -  + ]:         160860 :     Assert(!unlock_vmbuffer);
                               5421                 :                : 
 3660 andres@anarazel.de       5422                 :         160860 : out_unlocked:
                               5423         [ +  + ]:         571691 :     if (BufferIsValid(vmbuffer))
                               5424                 :         413509 :         ReleaseBuffer(vmbuffer);
                               5425                 :                : 
                               5426                 :                :     /*
                               5427                 :                :      * Don't update the visibility map here. Locking a tuple doesn't change
                               5428                 :                :      * visibility info.
                               5429                 :                :      */
                               5430                 :                : 
                               5431                 :                :     /*
                               5432                 :                :      * Now that we have successfully marked the tuple as locked, we can
                               5433                 :                :      * release the lmgr tuple lock, if we had it.
                               5434                 :                :      */
 7757 tgl@sss.pgh.pa.us        5435         [ +  + ]:         571691 :     if (have_tuple_lock)
 4932 alvherre@alvh.no-ip.     5436                 :            183 :         UnlockTupleTuplock(relation, tid, mode);
                               5437                 :                : 
 3660 andres@anarazel.de       5438                 :         571691 :     return result;
                               5439                 :                : }
                               5440                 :                : 
                               5441                 :                : /*
                               5442                 :                :  * Acquire heavyweight lock on the given tuple, in preparation for acquiring
                               5443                 :                :  * its normal, Xmax-based tuple lock.
                               5444                 :                :  *
                               5445                 :                :  * have_tuple_lock is an input and output parameter: on input, it indicates
                               5446                 :                :  * whether the lock has previously been acquired (and this function does
                               5447                 :                :  * nothing in that case).  If this function returns success, have_tuple_lock
                               5448                 :                :  * has been flipped to true.
                               5449                 :                :  *
                               5450                 :                :  * Returns false if it was unable to obtain the lock; this can only happen if
                               5451                 :                :  * wait_policy is Skip.
                               5452                 :                :  */
                               5453                 :                : static bool
  269 peter@eisentraut.org     5454                 :            378 : heap_acquire_tuplock(Relation relation, const ItemPointerData *tid, LockTupleMode mode,
                               5455                 :                :                      LockWaitPolicy wait_policy, bool *have_tuple_lock)
                               5456                 :                : {
 4230 alvherre@alvh.no-ip.     5457         [ +  + ]:            378 :     if (*have_tuple_lock)
                               5458                 :              9 :         return true;
                               5459                 :                : 
                               5460   [ +  +  +  - ]:            369 :     switch (wait_policy)
                               5461                 :                :     {
                               5462                 :            324 :         case LockWaitBlock:
                               5463                 :            324 :             LockTupleTuplock(relation, tid, mode);
                               5464                 :            324 :             break;
                               5465                 :                : 
                               5466                 :             34 :         case LockWaitSkip:
  499 fujii@postgresql.org     5467         [ +  + ]:             34 :             if (!ConditionalLockTupleTuplock(relation, tid, mode, false))
 4230 alvherre@alvh.no-ip.     5468                 :              1 :                 return false;
                               5469                 :             33 :             break;
                               5470                 :                : 
                               5471                 :             11 :         case LockWaitError:
  418 fujii@postgresql.org     5472         [ +  + ]:             11 :             if (!ConditionalLockTupleTuplock(relation, tid, mode, log_lock_failures))
 4230 alvherre@alvh.no-ip.     5473         [ +  - ]:              1 :                 ereport(ERROR,
                               5474                 :                :                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                               5475                 :                :                          errmsg("could not obtain lock on row in relation \"%s\"",
                               5476                 :                :                                 RelationGetRelationName(relation))));
                               5477                 :             10 :             break;
                               5478                 :                :     }
                               5479                 :            367 :     *have_tuple_lock = true;
                               5480                 :                : 
                               5481                 :            367 :     return true;
                               5482                 :                : }
                               5483                 :                : 
                               5484                 :                : /*
                               5485                 :                :  * Given an original set of Xmax and infomask, and a transaction (identified by
                               5486                 :                :  * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
                               5487                 :                :  * corresponding infomasks to use on the tuple.
                               5488                 :                :  *
                               5489                 :                :  * Note that this might have side effects such as creating a new MultiXactId.
                               5490                 :                :  *
                               5491                 :                :  * Most callers will have called HeapTupleSatisfiesUpdate before this function;
                               5492                 :                :  * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
                               5493                 :                :  * but it was not running anymore. There is a race condition, which is that the
                               5494                 :                :  * MultiXactId may have finished since then, but that uncommon case is handled
                               5495                 :                :  * either here, or within MultiXactIdExpand.
                               5496                 :                :  *
                               5497                 :                :  * There is a similar race condition possible when the old xmax was a regular
                               5498                 :                :  * TransactionId.  We test TransactionIdIsInProgress again just to narrow the
                               5499                 :                :  * window, but it's still possible to end up creating an unnecessary
                               5500                 :                :  * MultiXactId.  Fortunately this is harmless.
                               5501                 :                :  */
                               5502                 :                : static void
 4932                          5503                 :        6619071 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
                               5504                 :                :                           uint16 old_infomask2, TransactionId add_to_xmax,
                               5505                 :                :                           LockTupleMode mode, bool is_update,
                               5506                 :                :                           TransactionId *result_xmax, uint16 *result_infomask,
                               5507                 :                :                           uint16 *result_infomask2)
                               5508                 :                : {
                               5509                 :                :     TransactionId new_xmax;
                               5510                 :                :     uint16      new_infomask,
                               5511                 :                :                 new_infomask2;
                               5512                 :                : 
 4602                          5513         [ +  - ]:        6619071 :     Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
                               5514                 :                : 
 4932                          5515                 :        6723685 : l5:
                               5516                 :        6723685 :     new_infomask = 0;
                               5517                 :        6723685 :     new_infomask2 = 0;
                               5518         [ +  + ]:        6723685 :     if (old_infomask & HEAP_XMAX_INVALID)
                               5519                 :                :     {
                               5520                 :                :         /*
                               5521                 :                :          * No previous locker; we just insert our own TransactionId.
                               5522                 :                :          *
                               5523                 :                :          * Note that it's critical that this case be the first one checked,
                               5524                 :                :          * because there are several blocks below that come back to this one
                               5525                 :                :          * to implement certain optimizations; old_infomask might contain
                               5526                 :                :          * other dirty bits in those cases, but we don't really care.
                               5527                 :                :          */
                               5528         [ +  + ]:        6542373 :         if (is_update)
                               5529                 :                :         {
                               5530                 :        4254664 :             new_xmax = add_to_xmax;
                               5531         [ +  + ]:        4254664 :             if (mode == LockTupleExclusive)
                               5532                 :        1903852 :                 new_infomask2 |= HEAP_KEYS_UPDATED;
                               5533                 :                :         }
                               5534                 :                :         else
                               5535                 :                :         {
                               5536                 :        2287709 :             new_infomask |= HEAP_XMAX_LOCK_ONLY;
                               5537   [ +  +  +  +  :        2287709 :             switch (mode)
                                                 - ]
                               5538                 :                :             {
                               5539                 :           5815 :                 case LockTupleKeyShare:
                               5540                 :           5815 :                     new_xmax = add_to_xmax;
                               5541                 :           5815 :                     new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
                               5542                 :           5815 :                     break;
                               5543                 :            806 :                 case LockTupleShare:
                               5544                 :            806 :                     new_xmax = add_to_xmax;
                               5545                 :            806 :                     new_infomask |= HEAP_XMAX_SHR_LOCK;
                               5546                 :            806 :                     break;
                               5547                 :        2184956 :                 case LockTupleNoKeyExclusive:
                               5548                 :        2184956 :                     new_xmax = add_to_xmax;
                               5549                 :        2184956 :                     new_infomask |= HEAP_XMAX_EXCL_LOCK;
                               5550                 :        2184956 :                     break;
                               5551                 :          96132 :                 case LockTupleExclusive:
                               5552                 :          96132 :                     new_xmax = add_to_xmax;
                               5553                 :          96132 :                     new_infomask |= HEAP_XMAX_EXCL_LOCK;
                               5554                 :          96132 :                     new_infomask2 |= HEAP_KEYS_UPDATED;
                               5555                 :          96132 :                     break;
 4932 alvherre@alvh.no-ip.     5556                 :UBC           0 :                 default:
                               5557                 :              0 :                     new_xmax = InvalidTransactionId;    /* silence compiler */
                               5558         [ #  # ]:              0 :                     elog(ERROR, "invalid lock mode");
                               5559                 :                :             }
                               5560                 :                :         }
                               5561                 :                :     }
 4932 alvherre@alvh.no-ip.     5562         [ +  + ]:CBC      181312 :     else if (old_infomask & HEAP_XMAX_IS_MULTI)
                               5563                 :                :     {
                               5564                 :                :         MultiXactStatus new_status;
                               5565                 :                : 
                               5566                 :                :         /*
                               5567                 :                :          * Currently we don't allow XMAX_COMMITTED to be set for multis, so
                               5568                 :                :          * cross-check.
                               5569                 :                :          */
                               5570         [ -  + ]:          75560 :         Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
                               5571                 :                : 
                               5572                 :                :         /*
                               5573                 :                :          * A multixact together with LOCK_ONLY set but neither lock bit set
                               5574                 :                :          * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
                               5575                 :                :          * anymore.  This check is critical for databases upgraded by
                               5576                 :                :          * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
                               5577                 :                :          * that such multis are never passed.
                               5578                 :                :          */
 3684                          5579         [ -  + ]:          75560 :         if (HEAP_LOCKED_UPGRADED(old_infomask))
                               5580                 :                :         {
 4932 alvherre@alvh.no-ip.     5581                 :UBC           0 :             old_infomask &= ~HEAP_XMAX_IS_MULTI;
                               5582                 :              0 :             old_infomask |= HEAP_XMAX_INVALID;
                               5583                 :              0 :             goto l5;
                               5584                 :                :         }
                               5585                 :                : 
                               5586                 :                :         /*
                               5587                 :                :          * If the XMAX is already a MultiXactId, then we need to expand it to
                               5588                 :                :          * include add_to_xmax; but if all the members were lockers and are
                               5589                 :                :          * all gone, we can do away with the IS_MULTI bit and just set
                               5590                 :                :          * add_to_xmax as the only locker/updater.  If all lockers are gone
                               5591                 :                :          * and we have an updater that aborted, we can also do without a
                               5592                 :                :          * multi.
                               5593                 :                :          *
                               5594                 :                :          * The cost of doing GetMultiXactIdMembers would be paid by
                               5595                 :                :          * MultiXactIdExpand if we weren't to do this, so this check is not
                               5596                 :                :          * incurring extra work anyhow.
                               5597                 :                :          */
 4380 alvherre@alvh.no-ip.     5598         [ +  + ]:CBC       75560 :         if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
                               5599                 :                :         {
 4932                          5600         [ +  + ]:             25 :             if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
 4125                          5601         [ +  - ]:              9 :                 !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
                               5602                 :                :                                                                 old_infomask)))
                               5603                 :                :             {
                               5604                 :                :                 /*
                               5605                 :                :                  * Reset these bits and restart; otherwise fall through to
                               5606                 :                :                  * create a new multi below.
                               5607                 :                :                  */
 4932                          5608                 :             25 :                 old_infomask &= ~HEAP_XMAX_IS_MULTI;
                               5609                 :             25 :                 old_infomask |= HEAP_XMAX_INVALID;
                               5610                 :             25 :                 goto l5;
                               5611                 :                :             }
                               5612                 :                :         }
                               5613                 :                : 
                               5614                 :          75535 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5615                 :                : 
                               5616                 :          75535 :         new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
                               5617                 :                :                                      new_status);
                               5618                 :          75535 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5619                 :                :     }
                               5620         [ +  + ]:         105752 :     else if (old_infomask & HEAP_XMAX_COMMITTED)
                               5621                 :                :     {
                               5622                 :                :         /*
                               5623                 :                :          * It's a committed update, so we need to preserve him as updater of
                               5624                 :                :          * the tuple.
                               5625                 :                :          */
                               5626                 :                :         MultiXactStatus status;
                               5627                 :                :         MultiXactStatus new_status;
                               5628                 :                : 
                               5629         [ -  + ]:             13 :         if (old_infomask2 & HEAP_KEYS_UPDATED)
 4932 alvherre@alvh.no-ip.     5630                 :UBC           0 :             status = MultiXactStatusUpdate;
                               5631                 :                :         else
 4932 alvherre@alvh.no-ip.     5632                 :CBC          13 :             status = MultiXactStatusNoKeyUpdate;
                               5633                 :                : 
                               5634                 :             13 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5635                 :                : 
                               5636                 :                :         /*
                               5637                 :                :          * since it's not running, it's obviously impossible for the old
                               5638                 :                :          * updater to be identical to the current one, so we need not check
                               5639                 :                :          * for that case as we do in the block above.
                               5640                 :                :          */
                               5641                 :             13 :         new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
                               5642                 :             13 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5643                 :                :     }
                               5644         [ +  + ]:         105739 :     else if (TransactionIdIsInProgress(xmax))
                               5645                 :                :     {
                               5646                 :                :         /*
                               5647                 :                :          * If the XMAX is a valid, in-progress TransactionId, then we need to
                               5648                 :                :          * create a new MultiXactId that includes both the old locker or
                               5649                 :                :          * updater and our own TransactionId.
                               5650                 :                :          */
                               5651                 :                :         MultiXactStatus new_status;
                               5652                 :                :         MultiXactStatus old_status;
                               5653                 :                :         LockTupleMode old_mode;
                               5654                 :                : 
                               5655         [ +  + ]:         105724 :         if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
                               5656                 :                :         {
                               5657         [ +  + ]:         105696 :             if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
 4602                          5658                 :           5724 :                 old_status = MultiXactStatusForKeyShare;
 4932                          5659         [ +  + ]:          99972 :             else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
 4602                          5660                 :            472 :                 old_status = MultiXactStatusForShare;
 4932                          5661         [ +  - ]:          99500 :             else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
                               5662                 :                :             {
                               5663         [ +  + ]:          99500 :                 if (old_infomask2 & HEAP_KEYS_UPDATED)
 4602                          5664                 :          92949 :                     old_status = MultiXactStatusForUpdate;
                               5665                 :                :                 else
                               5666                 :           6551 :                     old_status = MultiXactStatusForNoKeyUpdate;
                               5667                 :                :             }
                               5668                 :                :             else
                               5669                 :                :             {
                               5670                 :                :                 /*
                               5671                 :                :                  * LOCK_ONLY can be present alone only when a page has been
                               5672                 :                :                  * upgraded by pg_upgrade.  But in that case,
                               5673                 :                :                  * TransactionIdIsInProgress() should have returned false.  We
                               5674                 :                :                  * assume it's no longer locked in this case.
                               5675                 :                :                  */
 4932 alvherre@alvh.no-ip.     5676         [ #  # ]:UBC           0 :                 elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
                               5677                 :              0 :                 old_infomask |= HEAP_XMAX_INVALID;
                               5678                 :              0 :                 old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
                               5679                 :              0 :                 goto l5;
                               5680                 :                :             }
                               5681                 :                :         }
                               5682                 :                :         else
                               5683                 :                :         {
                               5684                 :                :             /* it's an update, but which kind? */
 4932 alvherre@alvh.no-ip.     5685         [ -  + ]:CBC          28 :             if (old_infomask2 & HEAP_KEYS_UPDATED)
 4602 alvherre@alvh.no-ip.     5686                 :UBC           0 :                 old_status = MultiXactStatusUpdate;
                               5687                 :                :             else
 4602 alvherre@alvh.no-ip.     5688                 :CBC          28 :                 old_status = MultiXactStatusNoKeyUpdate;
                               5689                 :                :         }
                               5690                 :                : 
                               5691                 :         105724 :         old_mode = TUPLOCK_from_mxstatus(old_status);
                               5692                 :                : 
                               5693                 :                :         /*
                               5694                 :                :          * If the lock to be acquired is for the same TransactionId as the
                               5695                 :                :          * existing lock, there's an optimization possible: consider only the
                               5696                 :                :          * strongest of both locks as the only one present, and restart.
                               5697                 :                :          */
 4932                          5698         [ +  + ]:         105724 :         if (xmax == add_to_xmax)
                               5699                 :                :         {
                               5700                 :                :             /*
                               5701                 :                :              * Note that it's not possible for the original tuple to be
                               5702                 :                :              * updated: we wouldn't be here because the tuple would have been
                               5703                 :                :              * invisible and we wouldn't try to update it.  As a subtlety,
                               5704                 :                :              * this code can also run when traversing an update chain to lock
                               5705                 :                :              * future versions of a tuple.  But we wouldn't be here either,
                               5706                 :                :              * because the add_to_xmax would be different from the original
                               5707                 :                :              * updater.
                               5708                 :                :              */
 4602                          5709         [ -  + ]:         104575 :             Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
                               5710                 :                : 
                               5711                 :                :             /* acquire the strongest of both */
                               5712         [ +  + ]:         104575 :             if (mode < old_mode)
                               5713                 :          52247 :                 mode = old_mode;
                               5714                 :                :             /* mustn't touch is_update */
                               5715                 :                : 
                               5716                 :         104575 :             old_infomask |= HEAP_XMAX_INVALID;
                               5717                 :         104575 :             goto l5;
                               5718                 :                :         }
                               5719                 :                : 
                               5720                 :                :         /* otherwise, just fall back to creating a new multixact */
                               5721                 :           1149 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5722                 :           1149 :         new_xmax = MultiXactIdCreate(xmax, old_status,
                               5723                 :                :                                      add_to_xmax, new_status);
 4932                          5724                 :           1149 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5725                 :                :     }
                               5726   [ +  +  +  + ]:             20 :     else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
                               5727                 :              5 :              TransactionIdDidCommit(xmax))
                               5728                 :              1 :     {
                               5729                 :                :         /*
                               5730                 :                :          * It's a committed update, so we gotta preserve him as updater of the
                               5731                 :                :          * tuple.
                               5732                 :                :          */
                               5733                 :                :         MultiXactStatus status;
                               5734                 :                :         MultiXactStatus new_status;
                               5735                 :                : 
                               5736         [ -  + ]:              1 :         if (old_infomask2 & HEAP_KEYS_UPDATED)
 4932 alvherre@alvh.no-ip.     5737                 :UBC           0 :             status = MultiXactStatusUpdate;
                               5738                 :                :         else
 4932 alvherre@alvh.no-ip.     5739                 :CBC           1 :             status = MultiXactStatusNoKeyUpdate;
                               5740                 :                : 
                               5741                 :              1 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5742                 :                : 
                               5743                 :                :         /*
                               5744                 :                :          * since it's not running, it's obviously impossible for the old
                               5745                 :                :          * updater to be identical to the current one, so we need not check
                               5746                 :                :          * for that case as we do in the block above.
                               5747                 :                :          */
                               5748                 :              1 :         new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
                               5749                 :              1 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5750                 :                :     }
                               5751                 :                :     else
                               5752                 :                :     {
                               5753                 :                :         /*
                               5754                 :                :          * Can get here iff the locking/updating transaction was running when
                               5755                 :                :          * the infomask was extracted from the tuple, but finished before
                               5756                 :                :          * TransactionIdIsInProgress got to run.  Deal with it as if there was
                               5757                 :                :          * no locker at all in the first place.
                               5758                 :                :          */
                               5759                 :             14 :         old_infomask |= HEAP_XMAX_INVALID;
                               5760                 :             14 :         goto l5;
                               5761                 :                :     }
                               5762                 :                : 
                               5763                 :        6619071 :     *result_infomask = new_infomask;
                               5764                 :        6619071 :     *result_infomask2 = new_infomask2;
                               5765                 :        6619071 :     *result_xmax = new_xmax;
                               5766                 :        6619071 : }
                               5767                 :                : 
                               5768                 :                : /*
                               5769                 :                :  * Subroutine for heap_lock_updated_tuple_rec.
                               5770                 :                :  *
                               5771                 :                :  * Given a hypothetical multixact status held by the transaction identified
                               5772                 :                :  * with the given xid, does the current transaction need to wait, fail, or can
                               5773                 :                :  * it continue if it wanted to acquire a lock of the given mode?  "needwait"
                               5774                 :                :  * is set to true if waiting is necessary; if it can continue, then TM_Ok is
                               5775                 :                :  * returned.  If the lock is already held by the current transaction, return
                               5776                 :                :  * TM_SelfModified.  In case of a conflict with another transaction, a
                               5777                 :                :  * different HeapTupleSatisfiesUpdate return code is returned.
                               5778                 :                :  *
                               5779                 :                :  * The held status is said to be hypothetical because it might correspond to a
                               5780                 :                :  * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
                               5781                 :                :  * way for simplicity of API.
                               5782                 :                :  */
                               5783                 :                : static TM_Result
 4624                          5784                 :          38781 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
                               5785                 :                :                            LockTupleMode mode, HeapTuple tup,
                               5786                 :                :                            bool *needwait)
                               5787                 :                : {
                               5788                 :                :     MultiXactStatus wantedstatus;
                               5789                 :                : 
                               5790                 :          38781 :     *needwait = false;
                               5791                 :          38781 :     wantedstatus = get_mxact_status_for_lock(mode, false);
                               5792                 :                : 
                               5793                 :                :     /*
                               5794                 :                :      * Note: we *must* check TransactionIdIsInProgress before
                               5795                 :                :      * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
                               5796                 :                :      * for an explanation.
                               5797                 :                :      */
                               5798         [ -  + ]:          38781 :     if (TransactionIdIsCurrentTransactionId(xid))
                               5799                 :                :     {
                               5800                 :                :         /*
                               5801                 :                :          * The tuple has already been locked by our own transaction.  This is
                               5802                 :                :          * very rare but can happen if multiple transactions are trying to
                               5803                 :                :          * lock an ancient version of the same tuple.
                               5804                 :                :          */
 2682 andres@anarazel.de       5805                 :UBC           0 :         return TM_SelfModified;
                               5806                 :                :     }
 4624 alvherre@alvh.no-ip.     5807         [ +  + ]:CBC       38781 :     else if (TransactionIdIsInProgress(xid))
                               5808                 :                :     {
                               5809                 :                :         /*
                               5810                 :                :          * If the locking transaction is running, what we do depends on
                               5811                 :                :          * whether the lock modes conflict: if they do, then we must wait for
                               5812                 :                :          * it to finish; otherwise we can fall through to lock this tuple
                               5813                 :                :          * version without waiting.
                               5814                 :                :          */
                               5815         [ +  + ]:          36539 :         if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
                               5816                 :          36539 :                                 LOCKMODE_from_mxstatus(wantedstatus)))
                               5817                 :                :         {
                               5818                 :              8 :             *needwait = true;
                               5819                 :                :         }
                               5820                 :                : 
                               5821                 :                :         /*
                               5822                 :                :          * If we set needwait above, then this value doesn't matter;
                               5823                 :                :          * otherwise, this value signals to caller that it's okay to proceed.
                               5824                 :                :          */
 2682 andres@anarazel.de       5825                 :          36539 :         return TM_Ok;
                               5826                 :                :     }
 4624 alvherre@alvh.no-ip.     5827         [ +  + ]:           2242 :     else if (TransactionIdDidAbort(xid))
 2682 andres@anarazel.de       5828                 :            206 :         return TM_Ok;
 4624 alvherre@alvh.no-ip.     5829         [ +  - ]:           2036 :     else if (TransactionIdDidCommit(xid))
                               5830                 :                :     {
                               5831                 :                :         /*
                               5832                 :                :          * The other transaction committed.  If it was only a locker, then the
                               5833                 :                :          * lock is completely gone now and we can return success; but if it
                               5834                 :                :          * was an update, then what we do depends on whether the two lock
                               5835                 :                :          * modes conflict.  If they conflict, then we must report error to
                               5836                 :                :          * caller. But if they don't, we can fall through to allow the current
                               5837                 :                :          * transaction to lock the tuple.
                               5838                 :                :          *
                               5839                 :                :          * Note: the reason we worry about ISUPDATE here is because as soon as
                               5840                 :                :          * a transaction ends, all its locks are gone and meaningless, and
                               5841                 :                :          * thus we can ignore them; whereas its updates persist.  In the
                               5842                 :                :          * TransactionIdIsInProgress case, above, we don't need to check
                               5843                 :                :          * because we know the lock is still "alive" and thus a conflict needs
                               5844                 :                :          * always be checked.
                               5845                 :                :          */
 4616                          5846         [ +  + ]:           2036 :         if (!ISUPDATE_from_mxstatus(status))
 2682 andres@anarazel.de       5847                 :           2026 :             return TM_Ok;
                               5848                 :                : 
 4624 alvherre@alvh.no-ip.     5849         [ +  + ]:             10 :         if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
                               5850                 :             10 :                                 LOCKMODE_from_mxstatus(wantedstatus)))
                               5851                 :                :         {
                               5852                 :                :             /* bummer */
 1980                          5853         [ +  + ]:              9 :             if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
 2682 andres@anarazel.de       5854                 :              7 :                 return TM_Updated;
                               5855                 :                :             else
                               5856                 :              2 :                 return TM_Deleted;
                               5857                 :                :         }
                               5858                 :                : 
                               5859                 :              1 :         return TM_Ok;
                               5860                 :                :     }
                               5861                 :                : 
                               5862                 :                :     /* Not in progress, not aborted, not committed -- must have crashed */
 2682 andres@anarazel.de       5863                 :UBC           0 :     return TM_Ok;
                               5864                 :                : }
                               5865                 :                : 
                               5866                 :                : 
                               5867                 :                : /*
                               5868                 :                :  * Recursive part of heap_lock_updated_tuple
                               5869                 :                :  *
                               5870                 :                :  * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
                               5871                 :                :  * xid with the given mode; if this tuple is updated, recurse to lock the new
                               5872                 :                :  * version as well.
                               5873                 :                :  */
                               5874                 :                : static TM_Result
  215 heikki.linnakangas@i     5875                 :CBC        2224 : heap_lock_updated_tuple_rec(Relation rel, TransactionId priorXmax,
                               5876                 :                :                             const ItemPointerData *tid, TransactionId xid,
                               5877                 :                :                             LockTupleMode mode)
                               5878                 :                : {
                               5879                 :                :     TM_Result   result;
                               5880                 :                :     ItemPointerData tupid;
                               5881                 :                :     HeapTupleData mytup;
                               5882                 :                :     Buffer      buf;
                               5883                 :                :     Page        page;
                               5884                 :                :     uint16      new_infomask,
                               5885                 :                :                 new_infomask2,
                               5886                 :                :                 old_infomask,
                               5887                 :                :                 old_infomask2;
                               5888                 :                :     TransactionId xmax,
                               5889                 :                :                 new_xmax;
 3660 andres@anarazel.de       5890                 :           2224 :     bool        cleared_all_frozen = false;
                               5891                 :                :     bool        pinned_desired_page;
                               5892                 :           2224 :     Buffer      vmbuffer = InvalidBuffer;
   11 melanieplageman@gmai     5893                 :           2224 :     bool        unlock_vmbuffer = false;
                               5894                 :                :     BlockNumber block;
                               5895                 :                : 
 4932 alvherre@alvh.no-ip.     5896                 :           2224 :     ItemPointerCopy(tid, &tupid);
                               5897                 :                : 
                               5898                 :                :     for (;;)
                               5899                 :                :     {
                               5900                 :           2227 :         new_infomask = 0;
                               5901                 :           2227 :         new_xmax = InvalidTransactionId;
   11 melanieplageman@gmai     5902                 :           2227 :         cleared_all_frozen = false;
 3660 andres@anarazel.de       5903                 :           2227 :         block = ItemPointerGetBlockNumber(&tupid);
 4932 alvherre@alvh.no-ip.     5904                 :           2227 :         ItemPointerCopy(&tupid, &(mytup.t_self));
                               5905                 :                : 
 1565 tgl@sss.pgh.pa.us        5906         [ +  - ]:           2227 :         if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
                               5907                 :                :         {
                               5908                 :                :             /*
                               5909                 :                :              * if we fail to find the updated version of the tuple, it's
                               5910                 :                :              * because it was vacuumed/pruned away after its creator
                               5911                 :                :              * transaction aborted.  So behave as if we got to the end of the
                               5912                 :                :              * chain, and there's no further tuple to lock: return success to
                               5913                 :                :              * caller.
                               5914                 :                :              */
 2682 andres@anarazel.de       5915                 :UBC           0 :             result = TM_Ok;
 3068 tgl@sss.pgh.pa.us        5916                 :              0 :             goto out_unlocked;
                               5917                 :                :         }
                               5918                 :                : 
 4932 alvherre@alvh.no-ip.     5919                 :CBC        2227 : l4:
                               5920         [ -  + ]:           2235 :         CHECK_FOR_INTERRUPTS();
                               5921                 :                : 
   11 melanieplageman@gmai     5922                 :           2235 :         page = BufferGetPage(buf);
                               5923                 :                : 
                               5924                 :                :         /*
                               5925                 :                :          * Before locking the buffer, pin the visibility map page if it
                               5926                 :                :          * appears to be necessary.  Since we haven't got the lock yet,
                               5927                 :                :          * someone else might be in the middle of changing this, so we'll need
                               5928                 :                :          * to recheck after we have the lock.
                               5929                 :                :          */
                               5930         [ -  + ]:           2235 :         if (PageIsAllVisible(page))
                               5931                 :                :         {
 3660 andres@anarazel.de       5932                 :UBC           0 :             visibilitymap_pin(rel, block, &vmbuffer);
 3068 tgl@sss.pgh.pa.us        5933                 :              0 :             pinned_desired_page = true;
                               5934                 :                :         }
                               5935                 :                :         else
 3068 tgl@sss.pgh.pa.us        5936                 :CBC        2235 :             pinned_desired_page = false;
                               5937                 :                : 
 4932 alvherre@alvh.no-ip.     5938                 :           2235 :         LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
                               5939                 :                : 
                               5940                 :                :         /*
                               5941                 :                :          * If we didn't pin the visibility map page and the page has become
                               5942                 :                :          * all visible while we were busy locking the buffer, we'll have to
                               5943                 :                :          * unlock and re-lock, to avoid holding the buffer lock across I/O.
                               5944                 :                :          * That's a bit unfortunate, but hopefully shouldn't happen often.
                               5945                 :                :          *
                               5946                 :                :          * Note: in some paths through this function, we will reach here
                               5947                 :                :          * holding a pin on a vm page that may or may not be the one matching
                               5948                 :                :          * this page.  If this page isn't all-visible, we won't use the vm
                               5949                 :                :          * page, but we hold onto such a pin till the end of the function.
                               5950                 :                :          */
   11 melanieplageman@gmai     5951   [ +  -  -  + ]:           2235 :         if (!pinned_desired_page && PageIsAllVisible(page))
                               5952                 :                :         {
 3643 andres@anarazel.de       5953                 :UBC           0 :             LockBuffer(buf, BUFFER_LOCK_UNLOCK);
                               5954                 :              0 :             visibilitymap_pin(rel, block, &vmbuffer);
                               5955                 :              0 :             LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
                               5956                 :                :         }
                               5957                 :                : 
                               5958                 :                :         /*
                               5959                 :                :          * Check the tuple XMIN against prior XMAX, if any.  If we reached the
                               5960                 :                :          * end of the chain, we're done, so return success.
                               5961                 :                :          */
 4624 alvherre@alvh.no-ip.     5962   [ +  -  +  + ]:CBC        4470 :         if (TransactionIdIsValid(priorXmax) &&
 3188                          5963                 :           2235 :             !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
                               5964                 :                :                                  priorXmax))
                               5965                 :                :         {
 2682 andres@anarazel.de       5966                 :              2 :             result = TM_Ok;
 3660                          5967                 :              2 :             goto out_locked;
                               5968                 :                :         }
                               5969                 :                : 
                               5970                 :                :         /*
                               5971                 :                :          * Also check Xmin: if this tuple was created by an aborted
                               5972                 :                :          * (sub)transaction, then we already locked the last live one in the
                               5973                 :                :          * chain, thus we're done, so return success.
                               5974                 :                :          */
 3607 alvherre@alvh.no-ip.     5975         [ +  + ]:           2233 :         if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
                               5976                 :                :         {
 2682 andres@anarazel.de       5977                 :             25 :             result = TM_Ok;
 3068 tgl@sss.pgh.pa.us        5978                 :             25 :             goto out_locked;
                               5979                 :                :         }
                               5980                 :                : 
 4932 alvherre@alvh.no-ip.     5981                 :           2208 :         old_infomask = mytup.t_data->t_infomask;
 4624                          5982                 :           2208 :         old_infomask2 = mytup.t_data->t_infomask2;
 4932                          5983                 :           2208 :         xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
                               5984                 :                : 
                               5985                 :                :         /*
                               5986                 :                :          * If this tuple version has been updated or locked by some concurrent
                               5987                 :                :          * transaction(s), what we do depends on whether our lock mode
                               5988                 :                :          * conflicts with what those other transactions hold, and also on the
                               5989                 :                :          * status of them.
                               5990                 :                :          */
 4624                          5991         [ +  + ]:           2208 :         if (!(old_infomask & HEAP_XMAX_INVALID))
                               5992                 :                :         {
                               5993                 :                :             TransactionId rawxmax;
                               5994                 :                :             bool        needwait;
                               5995                 :                : 
                               5996                 :           2145 :             rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
                               5997         [ +  + ]:           2145 :             if (old_infomask & HEAP_XMAX_IS_MULTI)
                               5998                 :                :             {
                               5999                 :                :                 int         nmembers;
                               6000                 :                :                 int         i;
                               6001                 :                :                 MultiXactMember *members;
                               6002                 :                : 
                               6003                 :                :                 /*
                               6004                 :                :                  * We don't need a test for pg_upgrade'd tuples: this is only
                               6005                 :                :                  * applied to tuples after the first in an update chain.  Said
                               6006                 :                :                  * first tuple in the chain may well be locked-in-9.2-and-
                               6007                 :                :                  * pg_upgraded, but that one was already locked by our caller,
                               6008                 :                :                  * not us; and any subsequent ones cannot be because our
                               6009                 :                :                  * caller must necessarily have obtained a snapshot later than
                               6010                 :                :                  * the pg_upgrade itself.
                               6011                 :                :                  */
 3684                          6012         [ -  + ]:           2109 :                 Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
                               6013                 :                : 
 4380                          6014                 :           2109 :                 nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
 3322 tgl@sss.pgh.pa.us        6015                 :           2109 :                                                  HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
 4624 alvherre@alvh.no-ip.     6016         [ +  + ]:          40854 :                 for (i = 0; i < nmembers; i++)
                               6017                 :                :                 {
 3660 andres@anarazel.de       6018                 :          38745 :                     result = test_lockmode_for_conflict(members[i].status,
                               6019                 :          38745 :                                                         members[i].xid,
                               6020                 :                :                                                         mode,
                               6021                 :                :                                                         &mytup,
                               6022                 :                :                                                         &needwait);
                               6023                 :                : 
                               6024                 :                :                     /*
                               6025                 :                :                      * If the tuple was already locked by ourselves in a
                               6026                 :                :                      * previous iteration of this (say heap_lock_tuple was
                               6027                 :                :                      * forced to restart the locking loop because of a change
                               6028                 :                :                      * in xmax), then we hold the lock already on this tuple
                               6029                 :                :                      * version and we don't need to do anything; and this is
                               6030                 :                :                      * not an error condition either.  We just need to skip
                               6031                 :                :                      * this tuple and continue locking the next version in the
                               6032                 :                :                      * update chain.
                               6033                 :                :                      */
 2682                          6034         [ -  + ]:          38745 :                     if (result == TM_SelfModified)
                               6035                 :                :                     {
 3287 alvherre@alvh.no-ip.     6036                 :UBC           0 :                         pfree(members);
                               6037                 :              0 :                         goto next;
                               6038                 :                :                     }
                               6039                 :                : 
 4624 alvherre@alvh.no-ip.     6040         [ -  + ]:CBC       38745 :                     if (needwait)
                               6041                 :                :                     {
 4624 alvherre@alvh.no-ip.     6042                 :UBC           0 :                         LockBuffer(buf, BUFFER_LOCK_UNLOCK);
 4512                          6043                 :              0 :                         XactLockTableWait(members[i].xid, rel,
                               6044                 :                :                                           &mytup.t_self,
                               6045                 :                :                                           XLTW_LockUpdated);
 4624                          6046                 :              0 :                         pfree(members);
                               6047                 :              0 :                         goto l4;
                               6048                 :                :                     }
 2682 andres@anarazel.de       6049         [ -  + ]:CBC       38745 :                     if (result != TM_Ok)
                               6050                 :                :                     {
 4624 alvherre@alvh.no-ip.     6051                 :UBC           0 :                         pfree(members);
 3660 andres@anarazel.de       6052                 :              0 :                         goto out_locked;
                               6053                 :                :                     }
                               6054                 :                :                 }
 4624 alvherre@alvh.no-ip.     6055         [ +  - ]:CBC        2109 :                 if (members)
                               6056                 :           2109 :                     pfree(members);
                               6057                 :                :             }
                               6058                 :                :             else
                               6059                 :                :             {
                               6060                 :                :                 MultiXactStatus status;
                               6061                 :                : 
                               6062                 :                :                 /*
                               6063                 :                :                  * For a non-multi Xmax, we first need to compute the
                               6064                 :                :                  * corresponding MultiXactStatus by using the infomask bits.
                               6065                 :                :                  */
                               6066         [ +  + ]:             36 :                 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
                               6067                 :                :                 {
                               6068         [ +  - ]:             16 :                     if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
                               6069                 :             16 :                         status = MultiXactStatusForKeyShare;
 4624 alvherre@alvh.no-ip.     6070         [ #  # ]:UBC           0 :                     else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
                               6071                 :              0 :                         status = MultiXactStatusForShare;
                               6072         [ #  # ]:              0 :                     else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
                               6073                 :                :                     {
                               6074         [ #  # ]:              0 :                         if (old_infomask2 & HEAP_KEYS_UPDATED)
                               6075                 :              0 :                             status = MultiXactStatusForUpdate;
                               6076                 :                :                         else
                               6077                 :              0 :                             status = MultiXactStatusForNoKeyUpdate;
                               6078                 :                :                     }
                               6079                 :                :                     else
                               6080                 :                :                     {
                               6081                 :                :                         /*
                               6082                 :                :                          * LOCK_ONLY present alone (a pg_upgraded tuple marked
                               6083                 :                :                          * as share-locked in the old cluster) shouldn't be
                               6084                 :                :                          * seen in the middle of an update chain.
                               6085                 :                :                          */
                               6086         [ #  # ]:              0 :                         elog(ERROR, "invalid lock status in tuple");
                               6087                 :                :                     }
                               6088                 :                :                 }
                               6089                 :                :                 else
                               6090                 :                :                 {
                               6091                 :                :                     /* it's an update, but which kind? */
 4624 alvherre@alvh.no-ip.     6092         [ +  + ]:CBC          20 :                     if (old_infomask2 & HEAP_KEYS_UPDATED)
                               6093                 :             15 :                         status = MultiXactStatusUpdate;
                               6094                 :                :                     else
                               6095                 :              5 :                         status = MultiXactStatusNoKeyUpdate;
                               6096                 :                :                 }
                               6097                 :                : 
 3660 andres@anarazel.de       6098                 :             36 :                 result = test_lockmode_for_conflict(status, rawxmax, mode,
                               6099                 :                :                                                     &mytup, &needwait);
                               6100                 :                : 
                               6101                 :                :                 /*
                               6102                 :                :                  * If the tuple was already locked by ourselves in a previous
                               6103                 :                :                  * iteration of this (say heap_lock_tuple was forced to
                               6104                 :                :                  * restart the locking loop because of a change in xmax), then
                               6105                 :                :                  * we hold the lock already on this tuple version and we don't
                               6106                 :                :                  * need to do anything; and this is not an error condition
                               6107                 :                :                  * either.  We just need to skip this tuple and continue
                               6108                 :                :                  * locking the next version in the update chain.
                               6109                 :                :                  */
 2682                          6110         [ -  + ]:             36 :                 if (result == TM_SelfModified)
 3287 alvherre@alvh.no-ip.     6111                 :UBC           0 :                     goto next;
                               6112                 :                : 
 4624 alvherre@alvh.no-ip.     6113         [ +  + ]:CBC          36 :                 if (needwait)
                               6114                 :                :                 {
                               6115                 :              8 :                     LockBuffer(buf, BUFFER_LOCK_UNLOCK);
 4190 heikki.linnakangas@i     6116                 :              8 :                     XactLockTableWait(rawxmax, rel, &mytup.t_self,
                               6117                 :                :                                       XLTW_LockUpdated);
 4624 alvherre@alvh.no-ip.     6118                 :              8 :                     goto l4;
                               6119                 :                :                 }
 2682 andres@anarazel.de       6120         [ +  + ]:             28 :                 if (result != TM_Ok)
                               6121                 :                :                 {
 3660                          6122                 :              9 :                     goto out_locked;
                               6123                 :                :                 }
                               6124                 :                :             }
                               6125                 :                :         }
                               6126                 :                : 
                               6127                 :                :         /* compute the new Xmax and infomask values for the tuple ... */
 4932 alvherre@alvh.no-ip.     6128                 :           2191 :         compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
                               6129                 :                :                                   xid, mode, false,
                               6130                 :                :                                   &new_xmax, &new_infomask, &new_infomask2);
                               6131                 :                : 
   11 melanieplageman@gmai     6132         [ -  + ]:           2191 :         if (PageIsAllVisible(page))
                               6133                 :                :         {
   11 melanieplageman@gmai     6134                 :UBC           0 :             LockBuffer(vmbuffer, BUFFER_LOCK_EXCLUSIVE);
                               6135                 :              0 :             unlock_vmbuffer = true;
                               6136                 :                :         }
                               6137                 :                : 
 4932 alvherre@alvh.no-ip.     6138                 :CBC        2191 :         START_CRIT_SECTION();
                               6139                 :                : 
                               6140                 :                :         /* ... and set them */
                               6141                 :           2191 :         HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
                               6142                 :           2191 :         mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
                               6143                 :           2191 :         mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               6144                 :           2191 :         mytup.t_data->t_infomask |= new_infomask;
                               6145                 :           2191 :         mytup.t_data->t_infomask2 |= new_infomask2;
                               6146                 :                : 
                               6147                 :           2191 :         MarkBufferDirty(buf);
                               6148                 :                : 
   11 melanieplageman@gmai     6149         [ -  + ]:           2191 :         if (PageIsAllVisible(page))
                               6150                 :                :         {
                               6151                 :                :             /* It's possible all-frozen was already clear */
   11 melanieplageman@gmai     6152         [ #  # ]:UNC           0 :             if (visibilitymap_clear(rel->rd_locator, block, vmbuffer,
                               6153                 :                :                                     VISIBILITYMAP_ALL_FROZEN))
   11 melanieplageman@gmai     6154                 :UBC           0 :                 cleared_all_frozen = true;
                               6155                 :                :         }
                               6156                 :                : 
                               6157                 :                :         /* XLOG stuff */
 4932 alvherre@alvh.no-ip.     6158   [ +  -  +  +  :CBC        2191 :         if (RelationNeedsWAL(rel))
                                        +  -  +  - ]
                               6159                 :                :         {
                               6160                 :                :             xl_heap_lock_updated xlrec;
                               6161                 :                :             XLogRecPtr  recptr;
                               6162                 :                : 
 4266 heikki.linnakangas@i     6163                 :           2191 :             XLogBeginInsert();
   11 melanieplageman@gmai     6164                 :           2191 :             XLogRegisterBuffer(HEAP_LOCK_BLKREF_HEAP, buf, REGBUF_STANDARD);
                               6165                 :                : 
 4266 heikki.linnakangas@i     6166                 :           2191 :             xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
 4932 alvherre@alvh.no-ip.     6167                 :           2191 :             xlrec.xmax = new_xmax;
                               6168                 :           2191 :             xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
 3660 andres@anarazel.de       6169                 :           2191 :             xlrec.flags =
                               6170                 :           2191 :                 cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
                               6171                 :                : 
  530 peter@eisentraut.org     6172                 :           2191 :             XLogRegisterData(&xlrec, SizeOfHeapLockUpdated);
                               6173                 :                : 
   11 melanieplageman@gmai     6174         [ -  + ]:           2191 :             if (cleared_all_frozen)
   11 melanieplageman@gmai     6175                 :UBC           0 :                 XLogRegisterBuffer(HEAP_LOCK_BLKREF_VM, vmbuffer, 0);
                               6176                 :                : 
 4266 heikki.linnakangas@i     6177                 :CBC        2191 :             recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
                               6178                 :                : 
 4932 alvherre@alvh.no-ip.     6179                 :           2191 :             PageSetLSN(page, recptr);
                               6180                 :                : 
   11 melanieplageman@gmai     6181         [ -  + ]:           2191 :             if (cleared_all_frozen)
   11 melanieplageman@gmai     6182                 :UBC           0 :                 PageSetLSN(BufferGetPage(vmbuffer), recptr);
                               6183                 :                :         }
                               6184                 :                : 
 4932 alvherre@alvh.no-ip.     6185         [ -  + ]:CBC        2191 :         END_CRIT_SECTION();
                               6186                 :                : 
                               6187                 :                :         /* release VM lock first, since it covers many heap blocks */
   11 melanieplageman@gmai     6188         [ +  - ]:           2191 :         if (unlock_vmbuffer)
                               6189                 :                :         {
   11 melanieplageman@gmai     6190                 :UBC           0 :             LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
                               6191                 :              0 :             unlock_vmbuffer = false;
                               6192                 :                :         }
                               6193                 :                : 
 3287 alvherre@alvh.no-ip.     6194                 :CBC        2191 : next:
                               6195                 :                :         /* if we find the end of update chain, we're done. */
 4932                          6196   [ +  -  +  - ]:           4382 :         if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
 3032 andres@anarazel.de       6197         [ +  + ]:           4382 :             HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
 4806 bruce@momjian.us         6198         [ +  + ]:           2195 :             ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
 4932 alvherre@alvh.no-ip.     6199                 :              4 :             HeapTupleHeaderIsOnlyLocked(mytup.t_data))
                               6200                 :                :         {
 2682 andres@anarazel.de       6201                 :           2188 :             result = TM_Ok;
 3660                          6202                 :           2188 :             goto out_locked;
                               6203                 :                :         }
                               6204                 :                : 
                               6205                 :                :         /* tail recursion */
 4624 alvherre@alvh.no-ip.     6206                 :              3 :         priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
 4932                          6207                 :              3 :         ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
                               6208                 :              3 :         UnlockReleaseBuffer(buf);
                               6209                 :                :     }
                               6210                 :                : 
                               6211                 :                :     result = TM_Ok;
                               6212                 :                : 
 3660 andres@anarazel.de       6213                 :           2224 : out_locked:
                               6214                 :           2224 :     UnlockReleaseBuffer(buf);
                               6215                 :                : 
 3068 tgl@sss.pgh.pa.us        6216                 :           2224 : out_unlocked:
 3660 andres@anarazel.de       6217         [ -  + ]:           2224 :     if (vmbuffer != InvalidBuffer)
 3660 andres@anarazel.de       6218                 :UBC           0 :         ReleaseBuffer(vmbuffer);
   11 melanieplageman@gmai     6219         [ -  + ]:CBC        2224 :     Assert(!unlock_vmbuffer);
                               6220                 :                : 
 3660 andres@anarazel.de       6221                 :           2224 :     return result;
                               6222                 :                : }
                               6223                 :                : 
                               6224                 :                : /*
                               6225                 :                :  * heap_lock_updated_tuple
                               6226                 :                :  *      Follow update chain when locking an updated tuple, acquiring locks (row
                               6227                 :                :  *      marks) on the updated versions.
                               6228                 :                :  *
                               6229                 :                :  * 'prior_infomask', 'prior_raw_xmax' and 'prior_ctid' are the corresponding
                               6230                 :                :  * fields from the initial tuple.  We will lock the tuples starting from the
                               6231                 :                :  * one that 'prior_ctid' points to.  Note: This function does not lock the
                               6232                 :                :  * initial tuple itself.
                               6233                 :                :  *
                               6234                 :                :  * This function doesn't check visibility, it just unconditionally marks the
                               6235                 :                :  * tuple(s) as locked.  If any tuple in the updated chain is being deleted
                               6236                 :                :  * concurrently (or updated with the key being modified), sleep until the
                               6237                 :                :  * transaction doing it is finished.
                               6238                 :                :  *
                               6239                 :                :  * Note that we don't acquire heavyweight tuple locks on the tuples we walk
                               6240                 :                :  * when we have to wait for other transactions to release them, as opposed to
                               6241                 :                :  * what heap_lock_tuple does.  The reason is that having more than one
                               6242                 :                :  * transaction walking the chain is probably uncommon enough that risk of
                               6243                 :                :  * starvation is not likely: one of the preconditions for being here is that
                               6244                 :                :  * the snapshot in use predates the update that created this tuple (because we
                               6245                 :                :  * started at an earlier version of the tuple), but at the same time such a
                               6246                 :                :  * transaction cannot be using repeatable read or serializable isolation
                               6247                 :                :  * levels, because that would lead to a serializability failure.
                               6248                 :                :  */
                               6249                 :                : static TM_Result
  215 heikki.linnakangas@i     6250                 :           2226 : heap_lock_updated_tuple(Relation rel,
                               6251                 :                :                         uint16 prior_infomask,
                               6252                 :                :                         TransactionId prior_raw_xmax,
                               6253                 :                :                         const ItemPointerData *prior_ctid,
                               6254                 :                :                         TransactionId xid, LockTupleMode mode)
                               6255                 :                : {
                               6256                 :           2226 :     INJECTION_POINT("heap_lock_updated_tuple", NULL);
                               6257                 :                : 
                               6258                 :                :     /*
                               6259                 :                :      * If the tuple has moved into another partition (effectively a delete)
                               6260                 :                :      * stop here.
                               6261                 :                :      */
                               6262         [ +  + ]:           2226 :     if (!ItemPointerIndicatesMovedPartitions(prior_ctid))
                               6263                 :                :     {
                               6264                 :                :         TransactionId prior_xmax;
                               6265                 :                : 
                               6266                 :                :         /*
                               6267                 :                :          * If this is the first possibly-multixact-able operation in the
                               6268                 :                :          * current transaction, set my per-backend OldestMemberMXactId
                               6269                 :                :          * setting. We can be certain that the transaction will never become a
                               6270                 :                :          * member of any older MultiXactIds than that.  (We have to do this
                               6271                 :                :          * even if we end up just using our own TransactionId below, since
                               6272                 :                :          * some other backend could incorporate our XID into a MultiXact
                               6273                 :                :          * immediately afterwards.)
                               6274                 :                :          */
 4932 alvherre@alvh.no-ip.     6275                 :           2224 :         MultiXactIdSetOldestMember();
                               6276                 :                : 
  215 heikki.linnakangas@i     6277                 :           4448 :         prior_xmax = (prior_infomask & HEAP_XMAX_IS_MULTI) ?
                               6278         [ +  + ]:           2224 :             MultiXactIdGetUpdateXid(prior_raw_xmax, prior_infomask) : prior_raw_xmax;
                               6279                 :           2224 :         return heap_lock_updated_tuple_rec(rel, prior_xmax, prior_ctid, xid, mode);
                               6280                 :                :     }
                               6281                 :                : 
                               6282                 :                :     /* nothing to lock */
 2682 andres@anarazel.de       6283                 :              2 :     return TM_Ok;
                               6284                 :                : }
                               6285                 :                : 
                               6286                 :                : /*
                               6287                 :                :  *  heap_finish_speculative - mark speculative insertion as successful
                               6288                 :                :  *
                               6289                 :                :  * To successfully finish a speculative insertion we have to clear speculative
                               6290                 :                :  * token from tuple.  To do so the t_ctid field, which will contain a
                               6291                 :                :  * speculative token value, is modified in place to point to the tuple itself,
                               6292                 :                :  * which is characteristic of a newly inserted ordinary tuple.
                               6293                 :                :  *
                               6294                 :                :  * NB: It is not ok to commit without either finishing or aborting a
                               6295                 :                :  * speculative insertion.  We could treat speculative tuples of committed
                               6296                 :                :  * transactions implicitly as completed, but then we would have to be prepared
                               6297                 :                :  * to deal with speculative tokens on committed tuples.  That wouldn't be
                               6298                 :                :  * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
                               6299                 :                :  * but clearing the token at completion isn't very expensive either.
                               6300                 :                :  * An explicit confirmation WAL record also makes logical decoding simpler.
                               6301                 :                :  */
                               6302                 :                : void
  269 peter@eisentraut.org     6303                 :           2216 : heap_finish_speculative(Relation relation, const ItemPointerData *tid)
                               6304                 :                : {
                               6305                 :                :     Buffer      buffer;
                               6306                 :                :     Page        page;
                               6307                 :                :     OffsetNumber offnum;
                               6308                 :                :     ItemId      lp;
                               6309                 :                :     HeapTupleHeader htup;
                               6310                 :                : 
 2682 andres@anarazel.de       6311                 :           2216 :     buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
 4097                          6312                 :           2216 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
  331 peter@eisentraut.org     6313                 :           2216 :     page = BufferGetPage(buffer);
                               6314                 :                : 
 2682 andres@anarazel.de       6315                 :           2216 :     offnum = ItemPointerGetOffsetNumber(tid);
  223 tgl@sss.pgh.pa.us        6316   [ +  -  -  + ]:           2216 :     if (offnum < 1 || offnum > PageGetMaxOffsetNumber(page))
  223 tgl@sss.pgh.pa.us        6317         [ #  # ]:UBC           0 :         elog(ERROR, "offnum out of range");
  223 tgl@sss.pgh.pa.us        6318                 :CBC        2216 :     lp = PageGetItemId(page, offnum);
                               6319         [ -  + ]:           2216 :     if (!ItemIdIsNormal(lp))
 3902 andres@anarazel.de       6320         [ #  # ]:UBC           0 :         elog(ERROR, "invalid lp");
                               6321                 :                : 
 4097 andres@anarazel.de       6322                 :CBC        2216 :     htup = (HeapTupleHeader) PageGetItem(page, lp);
                               6323                 :                : 
                               6324                 :                :     /* NO EREPORT(ERROR) from here till changes are logged */
                               6325                 :           2216 :     START_CRIT_SECTION();
                               6326                 :                : 
 2682                          6327         [ -  + ]:           2216 :     Assert(HeapTupleHeaderIsSpeculative(htup));
                               6328                 :                : 
 4097                          6329                 :           2216 :     MarkBufferDirty(buffer);
                               6330                 :                : 
                               6331                 :                :     /*
                               6332                 :                :      * Replace the speculative insertion token with a real t_ctid, pointing to
                               6333                 :                :      * itself like it does on regular tuples.
                               6334                 :                :      */
 2682                          6335                 :           2216 :     htup->t_ctid = *tid;
                               6336                 :                : 
                               6337                 :                :     /* XLOG stuff */
 4097                          6338   [ +  +  +  +  :           2216 :     if (RelationNeedsWAL(relation))
                                        +  -  +  - ]
                               6339                 :                :     {
                               6340                 :                :         xl_heap_confirm xlrec;
                               6341                 :                :         XLogRecPtr  recptr;
                               6342                 :                : 
 2682                          6343                 :           2196 :         xlrec.offnum = ItemPointerGetOffsetNumber(tid);
                               6344                 :                : 
 4097                          6345                 :           2196 :         XLogBeginInsert();
                               6346                 :                : 
                               6347                 :                :         /* We want the same filtering on this as on a plain insert */
 3503                          6348                 :           2196 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               6349                 :                : 
  530 peter@eisentraut.org     6350                 :           2196 :         XLogRegisterData(&xlrec, SizeOfHeapConfirm);
 4097 andres@anarazel.de       6351                 :           2196 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               6352                 :                : 
                               6353                 :           2196 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
                               6354                 :                : 
                               6355                 :           2196 :         PageSetLSN(page, recptr);
                               6356                 :                :     }
                               6357                 :                : 
                               6358         [ -  + ]:           2216 :     END_CRIT_SECTION();
                               6359                 :                : 
                               6360                 :           2216 :     UnlockReleaseBuffer(buffer);
                               6361                 :           2216 : }
                               6362                 :                : 
                               6363                 :                : /*
                               6364                 :                :  *  heap_abort_speculative - kill a speculatively inserted tuple
                               6365                 :                :  *
                               6366                 :                :  * Marks a tuple that was speculatively inserted in the same command as dead,
                               6367                 :                :  * by setting its xmin as invalid.  That makes it immediately appear as dead
                               6368                 :                :  * to all transactions, including our own.  In particular, it makes
                               6369                 :                :  * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
                               6370                 :                :  * inserting a duplicate key value won't unnecessarily wait for our whole
                               6371                 :                :  * transaction to finish (it'll just wait for our speculative insertion to
                               6372                 :                :  * finish).
                               6373                 :                :  *
                               6374                 :                :  * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
                               6375                 :                :  * that arise due to a mutual dependency that is not user visible.  By
                               6376                 :                :  * definition, unprincipled deadlocks cannot be prevented by the user
                               6377                 :                :  * reordering lock acquisition in client code, because the implementation level
                               6378                 :                :  * lock acquisitions are not under the user's direct control.  If speculative
                               6379                 :                :  * inserters did not take this precaution, then under high concurrency they
                               6380                 :                :  * could deadlock with each other, which would not be acceptable.
                               6381                 :                :  *
                               6382                 :                :  * This is somewhat redundant with heap_delete, but we prefer to have a
                               6383                 :                :  * dedicated routine with stripped down requirements.  Note that this is also
                               6384                 :                :  * used to delete the TOAST tuples created during speculative insertion.
                               6385                 :                :  *
                               6386                 :                :  * This routine does not affect logical decoding as it only looks at
                               6387                 :                :  * confirmation records.
                               6388                 :                :  */
                               6389                 :                : void
  269 peter@eisentraut.org     6390                 :             16 : heap_abort_speculative(Relation relation, const ItemPointerData *tid)
                               6391                 :                : {
 4097 andres@anarazel.de       6392                 :             16 :     TransactionId xid = GetCurrentTransactionId();
                               6393                 :                :     ItemId      lp;
                               6394                 :                :     HeapTupleData tp;
                               6395                 :                :     Page        page;
                               6396                 :                :     BlockNumber block;
                               6397                 :                :     Buffer      buffer;
                               6398                 :                : 
                               6399         [ -  + ]:             16 :     Assert(ItemPointerIsValid(tid));
                               6400                 :                : 
                               6401                 :             16 :     block = ItemPointerGetBlockNumber(tid);
                               6402                 :             16 :     buffer = ReadBuffer(relation, block);
 3749 kgrittn@postgresql.o     6403                 :             16 :     page = BufferGetPage(buffer);
                               6404                 :                : 
 4097 andres@anarazel.de       6405                 :             16 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               6406                 :                : 
                               6407                 :                :     /*
                               6408                 :                :      * Page can't be all visible, we just inserted into it, and are still
                               6409                 :                :      * running.
                               6410                 :                :      */
                               6411         [ -  + ]:             16 :     Assert(!PageIsAllVisible(page));
                               6412                 :                : 
                               6413                 :             16 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
                               6414         [ -  + ]:             16 :     Assert(ItemIdIsNormal(lp));
                               6415                 :                : 
                               6416                 :             16 :     tp.t_tableOid = RelationGetRelid(relation);
                               6417                 :             16 :     tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
                               6418                 :             16 :     tp.t_len = ItemIdGetLength(lp);
                               6419                 :             16 :     tp.t_self = *tid;
                               6420                 :                : 
                               6421                 :                :     /*
                               6422                 :                :      * Sanity check that the tuple really is a speculatively inserted tuple,
                               6423                 :                :      * inserted by us.
                               6424                 :                :      */
                               6425         [ -  + ]:             16 :     if (tp.t_data->t_choice.t_heap.t_xmin != xid)
 4097 andres@anarazel.de       6426         [ #  # ]:UBC           0 :         elog(ERROR, "attempted to kill a tuple inserted by another transaction");
 3630 andres@anarazel.de       6427   [ +  +  -  + ]:CBC          16 :     if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
 4097 andres@anarazel.de       6428         [ #  # ]:UBC           0 :         elog(ERROR, "attempted to kill a non-speculative tuple");
 4097 andres@anarazel.de       6429         [ -  + ]:CBC          16 :     Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
                               6430                 :                : 
                               6431                 :                :     /*
                               6432                 :                :      * No need to check for serializable conflicts here.  There is never a
                               6433                 :                :      * need for a combo CID, either.  No need to extract replica identity, or
                               6434                 :                :      * do anything special with infomask bits.
                               6435                 :                :      */
                               6436                 :                : 
                               6437                 :             16 :     START_CRIT_SECTION();
                               6438                 :                : 
                               6439                 :                :     /*
                               6440                 :                :      * The tuple will become DEAD immediately.  Flag that this page is a
                               6441                 :                :      * candidate for pruning by setting xmin to TransactionXmin. While not
                               6442                 :                :      * immediately prunable, it is the oldest xid we can cheaply determine
                               6443                 :                :      * that's safe against wraparound / being older than the table's
                               6444                 :                :      * relfrozenxid.  To defend against the unlikely case of a new relation
                               6445                 :                :      * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
                               6446                 :                :      * if so (vacuum can't subsequently move relfrozenxid to beyond
                               6447                 :                :      * TransactionXmin, so there's no race here).
                               6448                 :                :      */
 2303                          6449         [ -  + ]:             16 :     Assert(TransactionIdIsValid(TransactionXmin));
                               6450                 :                :     {
  818 noah@leadboat.com        6451                 :             16 :         TransactionId relfrozenxid = relation->rd_rel->relfrozenxid;
                               6452                 :                :         TransactionId prune_xid;
                               6453                 :                : 
                               6454         [ -  + ]:             16 :         if (TransactionIdPrecedes(TransactionXmin, relfrozenxid))
  818 noah@leadboat.com        6455                 :UBC           0 :             prune_xid = relfrozenxid;
                               6456                 :                :         else
  818 noah@leadboat.com        6457                 :CBC          16 :             prune_xid = TransactionXmin;
                               6458   [ -  +  +  -  :             16 :         PageSetPrunable(page, prune_xid);
                                              +  + ]
                               6459                 :                :     }
                               6460                 :                : 
                               6461                 :                :     /* store transaction information of xact deleting the tuple */
 4097 andres@anarazel.de       6462                 :             16 :     tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               6463                 :             16 :     tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               6464                 :                : 
                               6465                 :                :     /*
                               6466                 :                :      * Set the tuple header xmin to InvalidTransactionId.  This makes the
                               6467                 :                :      * tuple immediately invisible everyone.  (In particular, to any
                               6468                 :                :      * transactions waiting on the speculative token, woken up later.)
                               6469                 :                :      */
                               6470                 :             16 :     HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
                               6471                 :                : 
                               6472                 :                :     /* Clear the speculative insertion token too */
                               6473                 :             16 :     tp.t_data->t_ctid = tp.t_self;
                               6474                 :                : 
                               6475                 :             16 :     MarkBufferDirty(buffer);
                               6476                 :                : 
                               6477                 :                :     /*
                               6478                 :                :      * XLOG stuff
                               6479                 :                :      *
                               6480                 :                :      * The WAL records generated here match heap_delete().  The same recovery
                               6481                 :                :      * routines are used.
                               6482                 :                :      */
                               6483   [ +  +  +  +  :             16 :     if (RelationNeedsWAL(relation))
                                        +  -  +  - ]
                               6484                 :                :     {
                               6485                 :                :         xl_heap_delete xlrec;
                               6486                 :                :         XLogRecPtr  recptr;
                               6487                 :                : 
                               6488                 :             12 :         xlrec.flags = XLH_DELETE_IS_SUPER;
                               6489                 :             24 :         xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
                               6490                 :             12 :                                               tp.t_data->t_infomask2);
                               6491                 :             12 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
                               6492                 :             12 :         xlrec.xmax = xid;
                               6493                 :                : 
                               6494                 :             12 :         XLogBeginInsert();
  530 peter@eisentraut.org     6495                 :             12 :         XLogRegisterData(&xlrec, SizeOfHeapDelete);
 4097 andres@anarazel.de       6496                 :             12 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               6497                 :                : 
                               6498                 :                :         /* No replica identity & replication origin logged */
                               6499                 :                : 
                               6500                 :             12 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
                               6501                 :                : 
                               6502                 :             12 :         PageSetLSN(page, recptr);
                               6503                 :                :     }
                               6504                 :                : 
                               6505         [ -  + ]:             16 :     END_CRIT_SECTION();
                               6506                 :                : 
                               6507                 :             16 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               6508                 :                : 
                               6509         [ +  + ]:             16 :     if (HeapTupleHasExternal(&tp))
                               6510                 :                :     {
 3630                          6511         [ -  + ]:              1 :         Assert(!IsToastRelation(relation));
 2487 rhaas@postgresql.org     6512                 :              1 :         heap_toast_delete(relation, &tp, true);
                               6513                 :                :     }
                               6514                 :                : 
                               6515                 :                :     /*
                               6516                 :                :      * Never need to mark tuple for invalidation, since catalogs don't support
                               6517                 :                :      * speculative insertion
                               6518                 :                :      */
                               6519                 :                : 
                               6520                 :                :     /* Now we can release the buffer */
 4097 andres@anarazel.de       6521                 :             16 :     ReleaseBuffer(buffer);
                               6522                 :                : 
                               6523                 :                :     /* count deletion, as we counted the insertion too */
                               6524                 :             16 :     pgstat_count_heap_delete(relation);
                               6525                 :             16 : }
                               6526                 :                : 
                               6527                 :                : /*
                               6528                 :                :  * heap_inplace_lock - protect inplace update from concurrent heap_update()
                               6529                 :                :  *
                               6530                 :                :  * Evaluate whether the tuple's state is compatible with a no-key update.
                               6531                 :                :  * Current transaction rowmarks are fine, as is KEY SHARE from any
                               6532                 :                :  * transaction.  If compatible, return true with the buffer exclusive-locked,
                               6533                 :                :  * and the caller must release that by calling
                               6534                 :                :  * heap_inplace_update_and_unlock(), calling heap_inplace_unlock(), or raising
                               6535                 :                :  * an error.  Otherwise, call release_callback(arg), wait for blocking
                               6536                 :                :  * transactions to end, and return false.
                               6537                 :                :  *
                               6538                 :                :  * Since this is intended for system catalogs and SERIALIZABLE doesn't cover
                               6539                 :                :  * DDL, this doesn't guarantee any particular predicate locking.
                               6540                 :                :  *
                               6541                 :                :  * heap_delete() is a rarer source of blocking transactions (xwait).  We'll
                               6542                 :                :  * wait for such a transaction just like for the normal heap_update() case.
                               6543                 :                :  * Normal concurrent DROP commands won't cause that, because all inplace
                               6544                 :                :  * updaters take some lock that conflicts with DROP.  An explicit SQL "DELETE
                               6545                 :                :  * FROM pg_class" can cause it.  By waiting, if the concurrent transaction
                               6546                 :                :  * executed both "DELETE FROM pg_class" and "INSERT INTO pg_class", our caller
                               6547                 :                :  * can find the successor tuple.
                               6548                 :                :  *
                               6549                 :                :  * Readers of inplace-updated fields expect changes to those fields are
                               6550                 :                :  * durable.  For example, vac_truncate_clog() reads datfrozenxid from
                               6551                 :                :  * pg_database tuples via catalog snapshots.  A future snapshot must not
                               6552                 :                :  * return a lower datfrozenxid for the same database OID (lower in the
                               6553                 :                :  * FullTransactionIdPrecedes() sense).  We achieve that since no update of a
                               6554                 :                :  * tuple can start while we hold a lock on its buffer.  In cases like
                               6555                 :                :  * BEGIN;GRANT;CREATE INDEX;COMMIT we're inplace-updating a tuple visible only
                               6556                 :                :  * to this transaction.  ROLLBACK then is one case where it's okay to lose
                               6557                 :                :  * inplace updates.  (Restoring relhasindex=false on ROLLBACK is fine, since
                               6558                 :                :  * any concurrent CREATE INDEX would have blocked, then inplace-updated the
                               6559                 :                :  * committed tuple.)
                               6560                 :                :  *
                               6561                 :                :  * In principle, we could avoid waiting by overwriting every tuple in the
                               6562                 :                :  * updated tuple chain.  Reader expectations permit updating a tuple only if
                               6563                 :                :  * it's aborted, is the tail of the chain, or we already updated the tuple
                               6564                 :                :  * referenced in its t_ctid.  Hence, we would need to overwrite the tuples in
                               6565                 :                :  * order from tail to head.  That would imply either (a) mutating all tuples
                               6566                 :                :  * in one critical section or (b) accepting a chance of partial completion.
                               6567                 :                :  * Partial completion of a relfrozenxid update would have the weird
                               6568                 :                :  * consequence that the table's next VACUUM could see the table's relfrozenxid
                               6569                 :                :  * move forward between vacuum_get_cutoffs() and finishing.
                               6570                 :                :  */
                               6571                 :                : bool
  670 noah@leadboat.com        6572                 :         119044 : heap_inplace_lock(Relation relation,
                               6573                 :                :                   HeapTuple oldtup_ptr, Buffer buffer,
                               6574                 :                :                   void (*release_callback) (void *), void *arg)
                               6575                 :                : {
                               6576                 :         119044 :     HeapTupleData oldtup = *oldtup_ptr; /* minimize diff vs. heap_update() */
                               6577                 :                :     TM_Result   result;
                               6578                 :                :     bool        ret;
                               6579                 :                : 
                               6580                 :                : #ifdef USE_ASSERT_CHECKING
                               6581         [ +  + ]:         119044 :     if (RelationGetRelid(relation) == RelationRelationId)
                               6582                 :         117699 :         check_inplace_rel_lock(oldtup_ptr);
                               6583                 :                : #endif
                               6584                 :                : 
                               6585         [ -  + ]:         119044 :     Assert(BufferIsValid(buffer));
                               6586                 :                : 
                               6587                 :                :     /*
                               6588                 :                :      * Register shared cache invals if necessary.  Other sessions may finish
                               6589                 :                :      * inplace updates of this tuple between this step and LockTuple().  Since
                               6590                 :                :      * inplace updates don't change cache keys, that's harmless.
                               6591                 :                :      *
                               6592                 :                :      * While it's tempting to register invals only after confirming we can
                               6593                 :                :      * return true, the following obstacle precludes reordering steps that
                               6594                 :                :      * way.  Registering invals might reach a CatalogCacheInitializeCache()
                               6595                 :                :      * that locks "buffer".  That would hang indefinitely if running after our
                               6596                 :                :      * own LockBuffer().  Hence, we must register invals before LockBuffer().
                               6597                 :                :      */
  223                          6598                 :         119044 :     CacheInvalidateHeapTupleInplace(relation, oldtup_ptr);
                               6599                 :                : 
  670                          6600                 :         119044 :     LockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
                               6601                 :         119044 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               6602                 :                : 
                               6603                 :                :     /*----------
                               6604                 :                :      * Interpret HeapTupleSatisfiesUpdate() like heap_update() does, except:
                               6605                 :                :      *
                               6606                 :                :      * - wait unconditionally
                               6607                 :                :      * - already locked tuple above, since inplace needs that unconditionally
                               6608                 :                :      * - don't recheck header after wait: simpler to defer to next iteration
                               6609                 :                :      * - don't try to continue even if the updater aborts: likewise
                               6610                 :                :      * - no crosscheck
                               6611                 :                :      */
                               6612                 :         119044 :     result = HeapTupleSatisfiesUpdate(&oldtup, GetCurrentCommandId(false),
                               6613                 :                :                                       buffer);
                               6614                 :                : 
                               6615         [ -  + ]:         119044 :     if (result == TM_Invisible)
                               6616                 :                :     {
                               6617                 :                :         /* no known way this can happen */
 4105 rhaas@postgresql.org     6618         [ #  # ]:UBC           0 :         ereport(ERROR,
                               6619                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               6620                 :                :                  errmsg_internal("attempted to overwrite invisible tuple")));
                               6621                 :                :     }
  670 noah@leadboat.com        6622         [ -  + ]:CBC      119044 :     else if (result == TM_SelfModified)
                               6623                 :                :     {
                               6624                 :                :         /*
                               6625                 :                :          * CREATE INDEX might reach this if an expression is silly enough to
                               6626                 :                :          * call e.g. SELECT ... FROM pg_class FOR SHARE.  C code of other SQL
                               6627                 :                :          * statements might get here after a heap_update() of the same row, in
                               6628                 :                :          * the absence of an intervening CommandCounterIncrement().
                               6629                 :                :          */
  670 noah@leadboat.com        6630         [ #  # ]:UBC           0 :         ereport(ERROR,
                               6631                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               6632                 :                :                  errmsg("tuple to be updated was already modified by an operation triggered by the current command")));
                               6633                 :                :     }
  670 noah@leadboat.com        6634         [ +  + ]:CBC      119044 :     else if (result == TM_BeingModified)
                               6635                 :                :     {
                               6636                 :                :         TransactionId xwait;
                               6637                 :                :         uint16      infomask;
                               6638                 :                : 
                               6639                 :             64 :         xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
                               6640                 :             64 :         infomask = oldtup.t_data->t_infomask;
                               6641                 :                : 
                               6642         [ +  + ]:             64 :         if (infomask & HEAP_XMAX_IS_MULTI)
                               6643                 :                :         {
                               6644                 :              5 :             LockTupleMode lockmode = LockTupleNoKeyExclusive;
                               6645                 :              5 :             MultiXactStatus mxact_status = MultiXactStatusNoKeyUpdate;
                               6646                 :                :             int         remain;
                               6647                 :                : 
                               6648         [ +  + ]:              5 :             if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
                               6649                 :                :                                         lockmode, NULL))
                               6650                 :                :             {
                               6651                 :              2 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
  635                          6652                 :              2 :                 release_callback(arg);
  670                          6653                 :              2 :                 ret = false;
                               6654                 :              2 :                 MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
                               6655                 :                :                                 relation, &oldtup.t_self, XLTW_Update,
                               6656                 :                :                                 &remain);
                               6657                 :                :             }
                               6658                 :                :             else
                               6659                 :              3 :                 ret = true;
                               6660                 :                :         }
                               6661         [ +  + ]:             59 :         else if (TransactionIdIsCurrentTransactionId(xwait))
                               6662                 :              1 :             ret = true;
                               6663         [ +  + ]:             58 :         else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
                               6664                 :              1 :             ret = true;
                               6665                 :                :         else
                               6666                 :                :         {
                               6667                 :             57 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
  635                          6668                 :             57 :             release_callback(arg);
  670                          6669                 :             57 :             ret = false;
                               6670                 :             57 :             XactLockTableWait(xwait, relation, &oldtup.t_self,
                               6671                 :                :                               XLTW_Update);
                               6672                 :                :         }
                               6673                 :                :     }
                               6674                 :                :     else
                               6675                 :                :     {
                               6676                 :         118980 :         ret = (result == TM_Ok);
                               6677         [ +  + ]:         118980 :         if (!ret)
                               6678                 :                :         {
  670 noah@leadboat.com        6679                 :GBC           2 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
  635                          6680                 :              2 :             release_callback(arg);
                               6681                 :                :         }
                               6682                 :                :     }
                               6683                 :                : 
                               6684                 :                :     /*
                               6685                 :                :      * GetCatalogSnapshot() relies on invalidation messages to know when to
                               6686                 :                :      * take a new snapshot.  COMMIT of xwait is responsible for sending the
                               6687                 :                :      * invalidation.  We're not acquiring heavyweight locks sufficient to
                               6688                 :                :      * block if not yet sent, so we must take a new snapshot to ensure a later
                               6689                 :                :      * attempt has a fair chance.  While we don't need this if xwait aborted,
                               6690                 :                :      * don't bother optimizing that.
                               6691                 :                :      */
  670 noah@leadboat.com        6692         [ +  + ]:CBC      119044 :     if (!ret)
                               6693                 :                :     {
                               6694                 :             61 :         UnlockTuple(relation, &oldtup.t_self, InplaceUpdateTupleLock);
  631                          6695                 :             61 :         ForgetInplace_Inval();
  670                          6696                 :             61 :         InvalidateCatalogSnapshot();
                               6697                 :                :     }
                               6698                 :         119044 :     return ret;
                               6699                 :                : }
                               6700                 :                : 
                               6701                 :                : /*
                               6702                 :                :  * heap_inplace_update_and_unlock - core of systable_inplace_update_finish
                               6703                 :                :  *
                               6704                 :                :  * The tuple cannot change size, and therefore its header fields and null
                               6705                 :                :  * bitmap (if any) don't change either.
                               6706                 :                :  *
                               6707                 :                :  * Since we hold LOCKTAG_TUPLE, no updater has a local copy of this tuple.
                               6708                 :                :  */
                               6709                 :                : void
                               6710                 :          82264 : heap_inplace_update_and_unlock(Relation relation,
                               6711                 :                :                                HeapTuple oldtup, HeapTuple tuple,
                               6712                 :                :                                Buffer buffer)
                               6713                 :                : {
                               6714                 :          82264 :     HeapTupleHeader htup = oldtup->t_data;
                               6715                 :                :     uint32      oldlen;
                               6716                 :                :     uint32      newlen;
                               6717                 :                :     char       *dst;
                               6718                 :                :     char       *src;
  639                          6719                 :          82264 :     int         nmsgs = 0;
                               6720                 :          82264 :     SharedInvalidationMessage *invalMessages = NULL;
                               6721                 :          82264 :     bool        RelcacheInitFileInval = false;
                               6722                 :                : 
  670                          6723         [ -  + ]:          82264 :     Assert(ItemPointerEquals(&oldtup->t_self, &tuple->t_self));
                               6724                 :          82264 :     oldlen = oldtup->t_len - htup->t_hoff;
 7382 tgl@sss.pgh.pa.us        6725                 :          82264 :     newlen = tuple->t_len - tuple->t_data->t_hoff;
                               6726   [ +  -  -  + ]:          82264 :     if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
 3902 andres@anarazel.de       6727         [ #  # ]:UBC           0 :         elog(ERROR, "wrong tuple length");
                               6728                 :                : 
  639 noah@leadboat.com        6729                 :CBC       82264 :     dst = (char *) htup + htup->t_hoff;
                               6730                 :          82264 :     src = (char *) tuple->t_data + tuple->t_data->t_hoff;
                               6731                 :                : 
                               6732                 :                :     /* Like RecordTransactionCommit(), log only if needed */
                               6733         [ +  + ]:          82264 :     if (XLogStandbyInfoActive())
                               6734                 :          74700 :         nmsgs = inplaceGetInvalidationMessages(&invalMessages,
                               6735                 :                :                                                &RelcacheInitFileInval);
                               6736                 :                : 
                               6737                 :                :     /*
                               6738                 :                :      * Unlink relcache init files as needed.  If unlinking, acquire
                               6739                 :                :      * RelCacheInitLock until after associated invalidations.  By doing this
                               6740                 :                :      * in advance, if we checkpoint and then crash between inplace
                               6741                 :                :      * XLogInsert() and inval, we don't rely on StartupXLOG() ->
                               6742                 :                :      * RelationCacheInitFileRemove().  That uses elevel==LOG, so replay would
                               6743                 :                :      * neglect to PANIC on EIO.
                               6744                 :                :      */
                               6745                 :          82264 :     PreInplace_Inval();
                               6746                 :                : 
                               6747                 :                :     /*----------
                               6748                 :                :      * NO EREPORT(ERROR) from here till changes are complete
                               6749                 :                :      *
                               6750                 :                :      * Our exclusive buffer lock won't stop a reader having already pinned and
                               6751                 :                :      * checked visibility for this tuple. With the usual order of changes
                               6752                 :                :      * (i.e. updating the buffer contents before WAL logging), a reader could
                               6753                 :                :      * observe our not-yet-persistent update to relfrozenxid and update
                               6754                 :                :      * datfrozenxid based on that. A crash in that moment could allow
                               6755                 :                :      * datfrozenxid to overtake relfrozenxid:
                               6756                 :                :      *
                               6757                 :                :      * ["D" is a VACUUM (ONLY_DATABASE_STATS)]
                               6758                 :                :      * ["R" is a VACUUM tbl]
                               6759                 :                :      * D: vac_update_datfrozenxid() -> systable_beginscan(pg_class)
                               6760                 :                :      * D: systable_getnext() returns pg_class tuple of tbl
                               6761                 :                :      * R: memcpy() into pg_class tuple of tbl
                               6762                 :                :      * D: raise pg_database.datfrozenxid, XLogInsert(), finish
                               6763                 :                :      * [crash]
                               6764                 :                :      * [recovery restores datfrozenxid w/o relfrozenxid]
                               6765                 :                :      *
                               6766                 :                :      * We avoid that by using a temporary copy of the buffer to hide our
                               6767                 :                :      * change from other backends until the change has been WAL-logged. We
                               6768                 :                :      * apply our change to the temporary copy and WAL-log it, before modifying
                               6769                 :                :      * the real page. That way any action a reader of the in-place-updated
                               6770                 :                :      * value takes will be WAL logged after this change.
                               6771                 :                :      */
                               6772                 :          82264 :     START_CRIT_SECTION();
                               6773                 :                : 
  138 andres@anarazel.de       6774                 :          82264 :     MarkBufferDirty(buffer);
                               6775                 :                : 
                               6776                 :                :     /* XLOG stuff */
 5704 rhaas@postgresql.org     6777   [ +  -  +  +  :          82264 :     if (RelationNeedsWAL(relation))
                                        +  -  +  + ]
                               6778                 :                :     {
                               6779                 :                :         xl_heap_inplace xlrec;
                               6780                 :                :         PGAlignedBlock copied_buffer;
  639 noah@leadboat.com        6781                 :          82260 :         char       *origdata = (char *) BufferGetBlock(buffer);
                               6782                 :          82260 :         Page        page = BufferGetPage(buffer);
                               6783                 :          82260 :         uint16      lower = ((PageHeader) page)->pd_lower;
                               6784                 :          82260 :         uint16      upper = ((PageHeader) page)->pd_upper;
                               6785                 :                :         uintptr_t   dst_offset_in_block;
                               6786                 :                :         RelFileLocator rlocator;
                               6787                 :                :         ForkNumber  forkno;
                               6788                 :                :         BlockNumber blkno;
                               6789                 :                :         XLogRecPtr  recptr;
                               6790                 :                : 
 4266 heikki.linnakangas@i     6791                 :          82260 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
  639 noah@leadboat.com        6792                 :          82260 :         xlrec.dbId = MyDatabaseId;
                               6793                 :          82260 :         xlrec.tsId = MyDatabaseTableSpace;
                               6794                 :          82260 :         xlrec.relcacheInitFileInval = RelcacheInitFileInval;
                               6795                 :          82260 :         xlrec.nmsgs = nmsgs;
                               6796                 :                : 
 4266 heikki.linnakangas@i     6797                 :          82260 :         XLogBeginInsert();
  530 peter@eisentraut.org     6798                 :          82260 :         XLogRegisterData(&xlrec, MinSizeOfHeapInplace);
  639 noah@leadboat.com        6799         [ +  + ]:          82260 :         if (nmsgs != 0)
  530 peter@eisentraut.org     6800                 :          57060 :             XLogRegisterData(invalMessages,
                               6801                 :                :                              nmsgs * sizeof(SharedInvalidationMessage));
                               6802                 :                : 
                               6803                 :                :         /* register block matching what buffer will look like after changes */
  639 noah@leadboat.com        6804                 :          82260 :         memcpy(copied_buffer.data, origdata, lower);
                               6805                 :          82260 :         memcpy(copied_buffer.data + upper, origdata + upper, BLCKSZ - upper);
                               6806                 :          82260 :         dst_offset_in_block = dst - origdata;
                               6807                 :          82260 :         memcpy(copied_buffer.data + dst_offset_in_block, src, newlen);
                               6808                 :          82260 :         BufferGetTag(buffer, &rlocator, &forkno, &blkno);
                               6809         [ -  + ]:          82260 :         Assert(forkno == MAIN_FORKNUM);
                               6810                 :          82260 :         XLogRegisterBlock(0, &rlocator, forkno, blkno, copied_buffer.data,
                               6811                 :                :                           REGBUF_STANDARD);
                               6812                 :          82260 :         XLogRegisterBufData(0, src, newlen);
                               6813                 :                : 
                               6814                 :                :         /* inplace updates aren't decoded atm, don't log the origin */
                               6815                 :                : 
 4266 heikki.linnakangas@i     6816                 :          82260 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
                               6817                 :                : 
  639 noah@leadboat.com        6818                 :          82260 :         PageSetLSN(page, recptr);
                               6819                 :                :     }
                               6820                 :                : 
                               6821                 :          82264 :     memcpy(dst, src, newlen);
                               6822                 :                : 
                               6823                 :          82264 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               6824                 :                : 
                               6825                 :                :     /*
                               6826                 :                :      * Send invalidations to shared queue.  SearchSysCacheLocked1() assumes we
                               6827                 :                :      * do this before UnlockTuple().
                               6828                 :                :      */
                               6829                 :          82264 :     AtInplace_Inval();
                               6830                 :                : 
 7382 tgl@sss.pgh.pa.us        6831         [ -  + ]:          82264 :     END_CRIT_SECTION();
  639 noah@leadboat.com        6832                 :          82264 :     UnlockTuple(relation, &tuple->t_self, InplaceUpdateTupleLock);
                               6833                 :                : 
                               6834                 :          82264 :     AcceptInvalidationMessages();   /* local processing of just-sent inval */
                               6835                 :                : 
                               6836                 :                :     /*
                               6837                 :                :      * Queue a transactional inval, for logical decoding and for third-party
                               6838                 :                :      * code that might have been relying on it since long before inplace
                               6839                 :                :      * update adopted immediate invalidation.  See README.tuplock section
                               6840                 :                :      * "Reading inplace-updated columns" for logical decoding details.
                               6841                 :                :      */
 7382 tgl@sss.pgh.pa.us        6842         [ +  + ]:          82264 :     if (!IsBootstrapProcessingMode())
 5458                          6843                 :          64624 :         CacheInvalidateHeapTuple(relation, tuple, NULL);
 7382                          6844                 :          82264 : }
                               6845                 :                : 
                               6846                 :                : /*
                               6847                 :                :  * heap_inplace_unlock - reverse of heap_inplace_lock
                               6848                 :                :  */
                               6849                 :                : void
  670 noah@leadboat.com        6850                 :          36719 : heap_inplace_unlock(Relation relation,
                               6851                 :                :                     HeapTuple oldtup, Buffer buffer)
                               6852                 :                : {
                               6853                 :          36719 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               6854                 :          36719 :     UnlockTuple(relation, &oldtup->t_self, InplaceUpdateTupleLock);
  631                          6855                 :          36719 :     ForgetInplace_Inval();
  670                          6856                 :          36719 : }
                               6857                 :                : 
                               6858                 :                : #define     FRM_NOOP                0x0001
                               6859                 :                : #define     FRM_INVALIDATE_XMAX     0x0002
                               6860                 :                : #define     FRM_RETURN_IS_XID       0x0004
                               6861                 :                : #define     FRM_RETURN_IS_MULTI     0x0008
                               6862                 :                : #define     FRM_MARK_COMMITTED      0x0010
                               6863                 :                : 
                               6864                 :                : /*
                               6865                 :                :  * FreezeMultiXactId
                               6866                 :                :  *      Determine what to do during freezing when a tuple is marked by a
                               6867                 :                :  *      MultiXactId.
                               6868                 :                :  *
                               6869                 :                :  * "flags" is an output value; it's used to tell caller what to do on return.
                               6870                 :                :  * "pagefrz" is an input/output value, used to manage page level freezing.
                               6871                 :                :  *
                               6872                 :                :  * Possible values that we can set in "flags":
                               6873                 :                :  * FRM_NOOP
                               6874                 :                :  *      don't do anything -- keep existing Xmax
                               6875                 :                :  * FRM_INVALIDATE_XMAX
                               6876                 :                :  *      mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
                               6877                 :                :  * FRM_RETURN_IS_XID
                               6878                 :                :  *      The Xid return value is a single update Xid to set as xmax.
                               6879                 :                :  * FRM_MARK_COMMITTED
                               6880                 :                :  *      Xmax can be marked as HEAP_XMAX_COMMITTED
                               6881                 :                :  * FRM_RETURN_IS_MULTI
                               6882                 :                :  *      The return value is a new MultiXactId to set as new Xmax.
                               6883                 :                :  *      (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
                               6884                 :                :  *
                               6885                 :                :  * Caller delegates control of page freezing to us.  In practice we always
                               6886                 :                :  * force freezing of caller's page unless FRM_NOOP processing is indicated.
                               6887                 :                :  * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
                               6888                 :                :  * can never be left behind.  We freely choose when and how to process each
                               6889                 :                :  * Multi, without ever violating the cutoff postconditions for freezing.
                               6890                 :                :  *
                               6891                 :                :  * It's useful to remove Multis on a proactive timeline (relative to freezing
                               6892                 :                :  * XIDs) to keep MultiXact member SLRU buffer misses to a minimum.  It can also
                               6893                 :                :  * be cheaper in the short run, for us, since we too can avoid SLRU buffer
                               6894                 :                :  * misses through eager processing.
                               6895                 :                :  *
                               6896                 :                :  * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
                               6897                 :                :  * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
                               6898                 :                :  * This can usually be put off, which is usually enough to avoid it altogether.
                               6899                 :                :  * Allocating new multis during VACUUM should be avoided on general principle;
                               6900                 :                :  * only VACUUM can advance relminmxid, so allocating new Multis here comes with
                               6901                 :                :  * its own special risks.
                               6902                 :                :  *
                               6903                 :                :  * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
                               6904                 :                :  * using heap_tuple_should_freeze when we haven't forced page-level freezing.
                               6905                 :                :  *
                               6906                 :                :  * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
                               6907                 :                :  * have already forced page-level freezing, since that might incur the same
                               6908                 :                :  * SLRU buffer misses that we specifically intended to avoid by freezing.
                               6909                 :                :  */
                               6910                 :                : static TransactionId
 4605 alvherre@alvh.no-ip.     6911                 :              6 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
                               6912                 :                :                   const struct VacuumCutoffs *cutoffs, uint16 *flags,
                               6913                 :                :                   HeapPageFreeze *pagefrz)
                               6914                 :                : {
                               6915                 :                :     TransactionId newxmax;
                               6916                 :                :     MultiXactMember *members;
                               6917                 :                :     int         nmembers;
                               6918                 :                :     bool        need_replace;
                               6919                 :                :     int         nnewmembers;
                               6920                 :                :     MultiXactMember *newmembers;
                               6921                 :                :     bool        has_lockers;
                               6922                 :                :     TransactionId update_xid;
                               6923                 :                :     bool        update_committed;
                               6924                 :                :     TransactionId FreezePageRelfrozenXid;
                               6925                 :                : 
                               6926                 :              6 :     *flags = 0;
                               6927                 :                : 
                               6928                 :                :     /* We should only be called in Multis */
                               6929         [ -  + ]:              6 :     Assert(t_infomask & HEAP_XMAX_IS_MULTI);
                               6930                 :                : 
 3684                          6931   [ +  -  -  + ]:             12 :     if (!MultiXactIdIsValid(multi) ||
                               6932                 :              6 :         HEAP_LOCKED_UPGRADED(t_infomask))
                               6933                 :                :     {
 4605 alvherre@alvh.no-ip.     6934                 :UBC           0 :         *flags |= FRM_INVALIDATE_XMAX;
 1306 pg@bowt.ie               6935                 :              0 :         pagefrz->freeze_required = true;
 4605 alvherre@alvh.no-ip.     6936                 :              0 :         return InvalidTransactionId;
                               6937                 :                :     }
 1312 pg@bowt.ie               6938         [ -  + ]:CBC           6 :     else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
 3177 andres@anarazel.de       6939         [ #  # ]:UBC           0 :         ereport(ERROR,
                               6940                 :                :                 (errcode(ERRCODE_DATA_CORRUPTED),
                               6941                 :                :                  errmsg_internal("found multixact %u from before relminmxid %u",
                               6942                 :                :                                  multi, cutoffs->relminmxid)));
 1306 pg@bowt.ie               6943         [ +  + ]:CBC           6 :     else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
                               6944                 :                :     {
                               6945                 :                :         TransactionId update_xact;
                               6946                 :                : 
                               6947                 :                :         /*
                               6948                 :                :          * This old multi cannot possibly have members still running, but
                               6949                 :                :          * verify just in case.  If it was a locker only, it can be removed
                               6950                 :                :          * without any further consideration; but if it contained an update,
                               6951                 :                :          * we might need to preserve it.
                               6952                 :                :          */
 3177 andres@anarazel.de       6953         [ -  + ]:              4 :         if (MultiXactIdIsRunning(multi,
                               6954                 :              4 :                                  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
 3177 andres@anarazel.de       6955         [ #  # ]:UBC           0 :             ereport(ERROR,
                               6956                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6957                 :                :                      errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
                               6958                 :                :                                      multi, cutoffs->OldestMxact)));
                               6959                 :                : 
 4605 alvherre@alvh.no-ip.     6960         [ +  - ]:CBC           4 :         if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
                               6961                 :                :         {
                               6962                 :              4 :             *flags |= FRM_INVALIDATE_XMAX;
 1306 pg@bowt.ie               6963                 :              4 :             pagefrz->freeze_required = true;
                               6964                 :              4 :             return InvalidTransactionId;
                               6965                 :                :         }
                               6966                 :                : 
                               6967                 :                :         /* replace multi with single XID for its updater? */
 1306 pg@bowt.ie               6968                 :UBC           0 :         update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
                               6969         [ #  # ]:              0 :         if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
                               6970         [ #  # ]:              0 :             ereport(ERROR,
                               6971                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6972                 :                :                      errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
                               6973                 :                :                                      multi, update_xact,
                               6974                 :                :                                      cutoffs->relfrozenxid)));
                               6975         [ #  # ]:              0 :         else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
                               6976                 :                :         {
                               6977                 :                :             /*
                               6978                 :                :              * Updater XID has to have aborted (otherwise the tuple would have
                               6979                 :                :              * been pruned away instead, since updater XID is < OldestXmin).
                               6980                 :                :              * Just remove xmax.
                               6981                 :                :              */
 1300                          6982         [ #  # ]:              0 :             if (TransactionIdDidCommit(update_xact))
 1306                          6983         [ #  # ]:              0 :                 ereport(ERROR,
                               6984                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               6985                 :                :                          errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
                               6986                 :                :                                          multi, update_xact,
                               6987                 :                :                                          cutoffs->OldestXmin)));
                               6988                 :              0 :             *flags |= FRM_INVALIDATE_XMAX;
                               6989                 :              0 :             pagefrz->freeze_required = true;
                               6990                 :              0 :             return InvalidTransactionId;
                               6991                 :                :         }
                               6992                 :                : 
                               6993                 :                :         /* Have to keep updater XID as new xmax */
                               6994                 :              0 :         *flags |= FRM_RETURN_IS_XID;
                               6995                 :              0 :         pagefrz->freeze_required = true;
                               6996                 :              0 :         return update_xact;
                               6997                 :                :     }
                               6998                 :                : 
                               6999                 :                :     /*
                               7000                 :                :      * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
                               7001                 :                :      * need to walk the whole members array to figure out what to do, if
                               7002                 :                :      * anything.
                               7003                 :                :      */
                               7004                 :                :     nmembers =
 3684 alvherre@alvh.no-ip.     7005                 :CBC           2 :         GetMultiXactIdMembers(multi, &members, false,
 4380                          7006                 :              2 :                               HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
 4605                          7007         [ -  + ]:              2 :     if (nmembers <= 0)
                               7008                 :                :     {
                               7009                 :                :         /* Nothing worth keeping */
 4605 alvherre@alvh.no-ip.     7010                 :UBC           0 :         *flags |= FRM_INVALIDATE_XMAX;
 1306 pg@bowt.ie               7011                 :              0 :         pagefrz->freeze_required = true;
 4605 alvherre@alvh.no-ip.     7012                 :              0 :         return InvalidTransactionId;
                               7013                 :                :     }
                               7014                 :                : 
                               7015                 :                :     /*
                               7016                 :                :      * The FRM_NOOP case is the only case where we might need to ratchet back
                               7017                 :                :      * FreezePageRelfrozenXid or FreezePageRelminMxid.  It is also the only
                               7018                 :                :      * case where our caller might ratchet back its NoFreezePageRelfrozenXid
                               7019                 :                :      * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
                               7020                 :                :      * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
                               7021                 :                :      * trackers managed by VACUUM being ratcheting back by xmax to the degree
                               7022                 :                :      * required to make it safe to leave xmax undisturbed, independent of
                               7023                 :                :      * whether or not page freezing is triggered somewhere else.
                               7024                 :                :      *
                               7025                 :                :      * Our policy is to force freezing in every case other than FRM_NOOP,
                               7026                 :                :      * which obviates the need to maintain either set of trackers, anywhere.
                               7027                 :                :      * Every other case will reliably execute a freeze plan for xmax that
                               7028                 :                :      * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
                               7029                 :                :      * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
                               7030                 :                :      * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
                               7031                 :                :      * OldestXmin/OldestMxact, so later values never need to be tracked here.)
                               7032                 :                :      */
 4605 alvherre@alvh.no-ip.     7033                 :CBC           2 :     need_replace = false;
 1306 pg@bowt.ie               7034                 :              2 :     FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
 1312                          7035         [ +  + ]:              4 :     for (int i = 0; i < nmembers; i++)
                               7036                 :                :     {
                               7037                 :              3 :         TransactionId xid = members[i].xid;
                               7038                 :                : 
                               7039         [ -  + ]:              3 :         Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
                               7040                 :                : 
                               7041         [ +  + ]:              3 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
                               7042                 :                :         {
                               7043                 :                :             /* Can't violate the FreezeLimit postcondition */
 4605 alvherre@alvh.no-ip.     7044                 :              1 :             need_replace = true;
                               7045                 :              1 :             break;
                               7046                 :                :         }
 1306 pg@bowt.ie               7047         [ -  + ]:              2 :         if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
 1306 pg@bowt.ie               7048                 :UBC           0 :             FreezePageRelfrozenXid = xid;
                               7049                 :                :     }
                               7050                 :                : 
                               7051                 :                :     /* Can't violate the MultiXactCutoff postcondition, either */
 1306 pg@bowt.ie               7052         [ +  + ]:CBC           2 :     if (!need_replace)
                               7053                 :              1 :         need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
                               7054                 :                : 
 4605 alvherre@alvh.no-ip.     7055         [ +  + ]:              2 :     if (!need_replace)
                               7056                 :                :     {
                               7057                 :                :         /*
                               7058                 :                :          * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
                               7059                 :                :          * both together to make it safe to retain this particular multi after
                               7060                 :                :          * freezing its page
                               7061                 :                :          */
                               7062                 :              1 :         *flags |= FRM_NOOP;
 1306 pg@bowt.ie               7063                 :              1 :         pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
                               7064         [ -  + ]:              1 :         if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
 1306 pg@bowt.ie               7065                 :UBC           0 :             pagefrz->FreezePageRelminMxid = multi;
 4605 alvherre@alvh.no-ip.     7066                 :CBC           1 :         pfree(members);
 1575 pg@bowt.ie               7067                 :              1 :         return multi;
                               7068                 :                :     }
                               7069                 :                : 
                               7070                 :                :     /*
                               7071                 :                :      * Do a more thorough second pass over the multi to figure out which
                               7072                 :                :      * member XIDs actually need to be kept.  Checking the precise status of
                               7073                 :                :      * individual members might even show that we don't need to keep anything.
                               7074                 :                :      * That is quite possible even though the Multi must be >= OldestMxact,
                               7075                 :                :      * since our second pass only keeps member XIDs when it's truly necessary;
                               7076                 :                :      * even member XIDs >= OldestXmin often won't be kept by second pass.
                               7077                 :                :      */
 4605 alvherre@alvh.no-ip.     7078                 :              1 :     nnewmembers = 0;
  228 michael@paquier.xyz      7079                 :              1 :     newmembers = palloc_array(MultiXactMember, nmembers);
 4605 alvherre@alvh.no-ip.     7080                 :              1 :     has_lockers = false;
                               7081                 :              1 :     update_xid = InvalidTransactionId;
                               7082                 :              1 :     update_committed = false;
                               7083                 :                : 
                               7084                 :                :     /*
                               7085                 :                :      * Determine whether to keep each member xid, or to ignore it instead
                               7086                 :                :      */
 1312 pg@bowt.ie               7087         [ +  + ]:              3 :     for (int i = 0; i < nmembers; i++)
                               7088                 :                :     {
                               7089                 :              2 :         TransactionId xid = members[i].xid;
                               7090                 :              2 :         MultiXactStatus mstatus = members[i].status;
                               7091                 :                : 
                               7092         [ -  + ]:              2 :         Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
                               7093                 :                : 
                               7094         [ +  - ]:              2 :         if (!ISUPDATE_from_mxstatus(mstatus))
                               7095                 :                :         {
                               7096                 :                :             /*
                               7097                 :                :              * Locker XID (not updater XID).  We only keep lockers that are
                               7098                 :                :              * still running.
                               7099                 :                :              */
                               7100   [ +  -  +  + ]:              4 :             if (TransactionIdIsCurrentTransactionId(xid) ||
                               7101                 :              2 :                 TransactionIdIsInProgress(xid))
                               7102                 :                :             {
 1306                          7103         [ -  + ]:              1 :                 if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
 1306 pg@bowt.ie               7104         [ #  # ]:UBC           0 :                     ereport(ERROR,
                               7105                 :                :                             (errcode(ERRCODE_DATA_CORRUPTED),
                               7106                 :                :                              errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
                               7107                 :                :                                              multi, xid,
                               7108                 :                :                                              cutoffs->OldestXmin)));
 1312 pg@bowt.ie               7109                 :CBC           1 :                 newmembers[nnewmembers++] = members[i];
                               7110                 :              1 :                 has_lockers = true;
                               7111                 :                :             }
                               7112                 :                : 
                               7113                 :              2 :             continue;
                               7114                 :                :         }
                               7115                 :                : 
                               7116                 :                :         /*
                               7117                 :                :          * Updater XID (not locker XID).  Should we keep it?
                               7118                 :                :          *
                               7119                 :                :          * Since the tuple wasn't totally removed when vacuum pruned, the
                               7120                 :                :          * update Xid cannot possibly be older than OldestXmin cutoff unless
                               7121                 :                :          * the updater XID aborted.  If the updater transaction is known
                               7122                 :                :          * aborted or crashed then it's okay to ignore it, otherwise not.
                               7123                 :                :          *
                               7124                 :                :          * In any case the Multi should never contain two updaters, whatever
                               7125                 :                :          * their individual commit status.  Check for that first, in passing.
                               7126                 :                :          */
 1312 pg@bowt.ie               7127         [ #  # ]:UBC           0 :         if (TransactionIdIsValid(update_xid))
                               7128         [ #  # ]:              0 :             ereport(ERROR,
                               7129                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               7130                 :                :                      errmsg_internal("multixact %u has two or more updating members",
                               7131                 :                :                                      multi),
                               7132                 :                :                      errdetail_internal("First updater XID=%u second updater XID=%u.",
                               7133                 :                :                                         update_xid, xid)));
                               7134                 :                : 
                               7135                 :                :         /*
                               7136                 :                :          * As with all tuple visibility routines, it's critical to test
                               7137                 :                :          * TransactionIdIsInProgress before TransactionIdDidCommit, because of
                               7138                 :                :          * race conditions explained in detail in heapam_visibility.c.
                               7139                 :                :          */
                               7140   [ #  #  #  # ]:              0 :         if (TransactionIdIsCurrentTransactionId(xid) ||
                               7141                 :              0 :             TransactionIdIsInProgress(xid))
                               7142                 :              0 :             update_xid = xid;
                               7143         [ #  # ]:              0 :         else if (TransactionIdDidCommit(xid))
                               7144                 :                :         {
                               7145                 :                :             /*
                               7146                 :                :              * The transaction committed, so we can tell caller to set
                               7147                 :                :              * HEAP_XMAX_COMMITTED.  (We can only do this because we know the
                               7148                 :                :              * transaction is not running.)
                               7149                 :                :              */
                               7150                 :              0 :             update_committed = true;
                               7151                 :              0 :             update_xid = xid;
                               7152                 :                :         }
                               7153                 :                :         else
                               7154                 :                :         {
                               7155                 :                :             /*
                               7156                 :                :              * Not in progress, not committed -- must be aborted or crashed;
                               7157                 :                :              * we can ignore it.
                               7158                 :                :              */
                               7159                 :              0 :             continue;
                               7160                 :                :         }
                               7161                 :                : 
                               7162                 :                :         /*
                               7163                 :                :          * We determined that updater must be kept -- add it to pending new
                               7164                 :                :          * members list
                               7165                 :                :          */
 1306                          7166         [ #  # ]:              0 :         if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
                               7167         [ #  # ]:              0 :             ereport(ERROR,
                               7168                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               7169                 :                :                      errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
                               7170                 :                :                                      multi, xid, cutoffs->OldestXmin)));
 1312                          7171                 :              0 :         newmembers[nnewmembers++] = members[i];
                               7172                 :                :     }
                               7173                 :                : 
 4605 alvherre@alvh.no-ip.     7174                 :CBC           1 :     pfree(members);
                               7175                 :                : 
                               7176                 :                :     /*
                               7177                 :                :      * Determine what to do with caller's multi based on information gathered
                               7178                 :                :      * during our second pass
                               7179                 :                :      */
                               7180         [ -  + ]:              1 :     if (nnewmembers == 0)
                               7181                 :                :     {
                               7182                 :                :         /* Nothing worth keeping */
 4605 alvherre@alvh.no-ip.     7183                 :UBC           0 :         *flags |= FRM_INVALIDATE_XMAX;
 1312 pg@bowt.ie               7184                 :              0 :         newxmax = InvalidTransactionId;
                               7185                 :                :     }
 4605 alvherre@alvh.no-ip.     7186   [ -  +  -  - ]:CBC           1 :     else if (TransactionIdIsValid(update_xid) && !has_lockers)
                               7187                 :                :     {
                               7188                 :                :         /*
                               7189                 :                :          * If there's a single member and it's an update, pass it back alone
                               7190                 :                :          * without creating a new Multi.  (XXX we could do this when there's a
                               7191                 :                :          * single remaining locker, too, but that would complicate the API too
                               7192                 :                :          * much; moreover, the case with the single updater is more
                               7193                 :                :          * interesting, because those are longer-lived.)
                               7194                 :                :          */
 4605 alvherre@alvh.no-ip.     7195         [ #  # ]:UBC           0 :         Assert(nnewmembers == 1);
                               7196                 :              0 :         *flags |= FRM_RETURN_IS_XID;
                               7197         [ #  # ]:              0 :         if (update_committed)
                               7198                 :              0 :             *flags |= FRM_MARK_COMMITTED;
 1312 pg@bowt.ie               7199                 :              0 :         newxmax = update_xid;
                               7200                 :                :     }
                               7201                 :                :     else
                               7202                 :                :     {
                               7203                 :                :         /*
                               7204                 :                :          * Create a new multixact with the surviving members of the previous
                               7205                 :                :          * one, to set as new Xmax in the tuple
                               7206                 :                :          */
 1312 pg@bowt.ie               7207                 :CBC           1 :         newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
 4605 alvherre@alvh.no-ip.     7208                 :              1 :         *flags |= FRM_RETURN_IS_MULTI;
                               7209                 :                :     }
                               7210                 :                : 
                               7211                 :              1 :     pfree(newmembers);
                               7212                 :                : 
 1306 pg@bowt.ie               7213                 :              1 :     pagefrz->freeze_required = true;
 1312                          7214                 :              1 :     return newxmax;
                               7215                 :                : }
                               7216                 :                : 
                               7217                 :                : /*
                               7218                 :                :  * heap_prepare_freeze_tuple
                               7219                 :                :  *
                               7220                 :                :  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
                               7221                 :                :  * are older than the OldestXmin and/or OldestMxact freeze cutoffs.  If so,
                               7222                 :                :  * setup enough state (in the *frz output argument) to enable caller to
                               7223                 :                :  * process this tuple as part of freezing its page, and return true.  Return
                               7224                 :                :  * false if nothing can be changed about the tuple right now.
                               7225                 :                :  *
                               7226                 :                :  * FreezePageConflictXid is advanced only for xmin/xvac freezing, not for xmax
                               7227                 :                :  * changes. We only remove xmax state here when it is lock-only, or when the
                               7228                 :                :  * updater XID (including an updater member of a MultiXact) must be aborted;
                               7229                 :                :  * otherwise, the tuple would already be removable. Neither case affects
                               7230                 :                :  * visibility on a standby.
                               7231                 :                :  *
                               7232                 :                :  * Also sets *totally_frozen to true if the tuple will be totally frozen once
                               7233                 :                :  * caller executes returned freeze plan (or if the tuple was already totally
                               7234                 :                :  * frozen by an earlier VACUUM).  This indicates that there are no remaining
                               7235                 :                :  * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
                               7236                 :                :  *
                               7237                 :                :  * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
                               7238                 :                :  * tuple that we returned true for, and then execute freezing.  Caller must
                               7239                 :                :  * initialize pagefrz fields for page as a whole before first call here for
                               7240                 :                :  * each heap page.
                               7241                 :                :  *
                               7242                 :                :  * VACUUM caller decides on whether or not to freeze the page as a whole.
                               7243                 :                :  * We'll often prepare freeze plans for a page that caller just discards.
                               7244                 :                :  * However, VACUUM doesn't always get to make a choice; it must freeze when
                               7245                 :                :  * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
                               7246                 :                :  * MXIDs < MultiXactCutoff) can never be left behind.  We help to make sure
                               7247                 :                :  * that VACUUM always follows that rule.
                               7248                 :                :  *
                               7249                 :                :  * We sometimes force freezing of xmax MultiXactId values long before it is
                               7250                 :                :  * strictly necessary to do so just to ensure the FreezeLimit postcondition.
                               7251                 :                :  * It's worth processing MultiXactIds proactively when it is cheap to do so,
                               7252                 :                :  * and it's convenient to make that happen by piggy-backing it on the "force
                               7253                 :                :  * freezing" mechanism.  Conversely, we sometimes delay freezing MultiXactIds
                               7254                 :                :  * because it is expensive right now (though only when it's still possible to
                               7255                 :                :  * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
                               7256                 :                :  *
                               7257                 :                :  * It is assumed that the caller has checked the tuple with
                               7258                 :                :  * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
                               7259                 :                :  * (else we should be removing the tuple, not freezing it).
                               7260                 :                :  *
                               7261                 :                :  * NB: This function has side effects: it might allocate a new MultiXactId.
                               7262                 :                :  * It will be set as tuple's new xmax when our *frz output is processed within
                               7263                 :                :  * heap_execute_freeze_tuple later on.  If the tuple is in a shared buffer
                               7264                 :                :  * then caller had better have an exclusive lock on it already.
                               7265                 :                :  */
                               7266                 :                : bool
 3177 andres@anarazel.de       7267                 :        7403773 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
                               7268                 :                :                           const struct VacuumCutoffs *cutoffs,
                               7269                 :                :                           HeapPageFreeze *pagefrz,
                               7270                 :                :                           HeapTupleFreeze *frz, bool *totally_frozen)
                               7271                 :                : {
 1312 pg@bowt.ie               7272                 :        7403773 :     bool        xmin_already_frozen = false,
                               7273                 :        7403773 :                 xmax_already_frozen = false;
                               7274                 :        7403773 :     bool        freeze_xmin = false,
                               7275                 :        7403773 :                 replace_xvac = false,
                               7276                 :        7403773 :                 replace_xmax = false,
                               7277                 :        7403773 :                 freeze_xmax = false;
                               7278                 :                :     TransactionId xid;
                               7279                 :                : 
 1300                          7280                 :        7403773 :     frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
 4605 alvherre@alvh.no-ip.     7281                 :        7403773 :     frz->t_infomask2 = tuple->t_infomask2;
                               7282                 :        7403773 :     frz->t_infomask = tuple->t_infomask;
 1300 pg@bowt.ie               7283                 :        7403773 :     frz->frzflags = 0;
                               7284                 :        7403773 :     frz->checkflags = 0;
                               7285                 :                : 
                               7286                 :                :     /*
                               7287                 :                :      * Process xmin, while keeping track of whether it's already frozen, or
                               7288                 :                :      * will become frozen iff our freeze plan is executed by caller (could be
                               7289                 :                :      * neither).
                               7290                 :                :      */
 7203 tgl@sss.pgh.pa.us        7291                 :        7403773 :     xid = HeapTupleHeaderGetXmin(tuple);
 2642 alvherre@alvh.no-ip.     7292         [ +  + ]:        7403773 :     if (!TransactionIdIsNormal(xid))
 1312 pg@bowt.ie               7293                 :         905585 :         xmin_already_frozen = true;
                               7294                 :                :     else
                               7295                 :                :     {
                               7296         [ -  + ]:        6498188 :         if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
 3177 andres@anarazel.de       7297         [ #  # ]:UBC           0 :             ereport(ERROR,
                               7298                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               7299                 :                :                      errmsg_internal("found xmin %u from before relfrozenxid %u",
                               7300                 :                :                                      xid, cutoffs->relfrozenxid)));
                               7301                 :                : 
                               7302                 :                :         /* Will set freeze_xmin flags in freeze plan below */
 1306 pg@bowt.ie               7303                 :CBC     6498188 :         freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
                               7304                 :                : 
                               7305                 :                :         /* Verify that xmin committed if and when freeze plan is executed */
 1300                          7306         [ +  + ]:        6498188 :         if (freeze_xmin)
                               7307                 :                :         {
                               7308                 :        4994675 :             frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
  138 melanieplageman@gmai     7309         [ +  + ]:        4994675 :             if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
                               7310                 :         549516 :                 pagefrz->FreezePageConflictXid = xid;
                               7311                 :                :         }
                               7312                 :                :     }
                               7313                 :                : 
                               7314                 :                :     /*
                               7315                 :                :      * Old-style VACUUM FULL is gone, but we have to process xvac for as long
                               7316                 :                :      * as we support having MOVED_OFF/MOVED_IN tuples in the database
                               7317                 :                :      */
 1312 pg@bowt.ie               7318                 :        7403773 :     xid = HeapTupleHeaderGetXvac(tuple);
                               7319         [ -  + ]:        7403773 :     if (TransactionIdIsNormal(xid))
                               7320                 :                :     {
 1312 pg@bowt.ie               7321         [ #  # ]:UBC           0 :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
                               7322         [ #  # ]:              0 :         Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
                               7323                 :                : 
                               7324                 :                :         /*
                               7325                 :                :          * For Xvac, we always freeze proactively.  This allows totally_frozen
                               7326                 :                :          * tracking to ignore xvac.
                               7327                 :                :          */
 1306                          7328                 :              0 :         replace_xvac = pagefrz->freeze_required = true;
                               7329                 :                : 
  138 melanieplageman@gmai     7330         [ #  # ]:              0 :         if (TransactionIdFollows(xid, pagefrz->FreezePageConflictXid))
                               7331                 :              0 :             pagefrz->FreezePageConflictXid = xid;
                               7332                 :                : 
                               7333                 :                :         /* Will set replace_xvac flags in freeze plan below */
                               7334                 :                :     }
                               7335                 :                : 
                               7336                 :                :     /* Now process xmax */
 1300 pg@bowt.ie               7337                 :CBC     7403773 :     xid = frz->xmax;
 4623 alvherre@alvh.no-ip.     7338         [ +  + ]:        7403773 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
                               7339                 :                :     {
                               7340                 :                :         /* Raw xmax is a MultiXactId */
                               7341                 :                :         TransactionId newxmax;
                               7342                 :                :         uint16      flags;
                               7343                 :                : 
                               7344                 :                :         /*
                               7345                 :                :          * We will either remove xmax completely (in the "freeze_xmax" path),
                               7346                 :                :          * process xmax by replacing it (in the "replace_xmax" path), or
                               7347                 :                :          * perform no-op xmax processing.  The only constraint is that the
                               7348                 :                :          * FreezeLimit/MultiXactCutoff postcondition must never be violated.
                               7349                 :                :          */
 1312 pg@bowt.ie               7350                 :              6 :         newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
                               7351                 :                :                                     &flags, pagefrz);
                               7352                 :                : 
 1306                          7353         [ +  + ]:              6 :         if (flags & FRM_NOOP)
                               7354                 :                :         {
                               7355                 :                :             /*
                               7356                 :                :              * xmax is a MultiXactId, and nothing about it changes for now.
                               7357                 :                :              * This is the only case where 'freeze_required' won't have been
                               7358                 :                :              * set for us by FreezeMultiXactId, as well as the only case where
                               7359                 :                :              * neither freeze_xmax nor replace_xmax are set (given a multi).
                               7360                 :                :              *
                               7361                 :                :              * This is a no-op, but the call to FreezeMultiXactId might have
                               7362                 :                :              * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
                               7363                 :                :              * for us (the "freeze page" variants, specifically).  That'll
                               7364                 :                :              * make it safe for our caller to freeze the page later on, while
                               7365                 :                :              * leaving this particular xmax undisturbed.
                               7366                 :                :              *
                               7367                 :                :              * FreezeMultiXactId is _not_ responsible for the "no freeze"
                               7368                 :                :              * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
                               7369                 :                :              * job.  A call to heap_tuple_should_freeze for this same tuple
                               7370                 :                :              * will take place below if 'freeze_required' isn't set already.
                               7371                 :                :              * (This repeats work from FreezeMultiXactId, but allows "no
                               7372                 :                :              * freeze" tracker maintenance to happen in only one place.)
                               7373                 :                :              */
                               7374         [ -  + ]:              1 :             Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
                               7375   [ +  -  -  + ]:              1 :             Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
                               7376                 :                :         }
                               7377         [ -  + ]:              5 :         else if (flags & FRM_RETURN_IS_XID)
                               7378                 :                :         {
                               7379                 :                :             /*
                               7380                 :                :              * xmax will become an updater Xid (original MultiXact's updater
                               7381                 :                :              * member Xid will be carried forward as a simple Xid in Xmax).
                               7382                 :                :              */
 1312 pg@bowt.ie               7383         [ #  # ]:UBC           0 :             Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
                               7384                 :                : 
                               7385                 :                :             /*
                               7386                 :                :              * NB -- some of these transformations are only valid because we
                               7387                 :                :              * know the return Xid is a tuple updater (i.e. not merely a
                               7388                 :                :              * locker.) Also note that the only reason we don't explicitly
                               7389                 :                :              * worry about HEAP_KEYS_UPDATED is because it lives in
                               7390                 :                :              * t_infomask2 rather than t_infomask.
                               7391                 :                :              */
 4605 alvherre@alvh.no-ip.     7392                 :              0 :             frz->t_infomask &= ~HEAP_XMAX_BITS;
                               7393                 :              0 :             frz->xmax = newxmax;
                               7394         [ #  # ]:              0 :             if (flags & FRM_MARK_COMMITTED)
 3307 teodor@sigaev.ru         7395                 :              0 :                 frz->t_infomask |= HEAP_XMAX_COMMITTED;
 1312 pg@bowt.ie               7396                 :              0 :             replace_xmax = true;
                               7397                 :                :         }
 4605 alvherre@alvh.no-ip.     7398         [ +  + ]:CBC           5 :         else if (flags & FRM_RETURN_IS_MULTI)
                               7399                 :                :         {
                               7400                 :                :             uint16      newbits;
                               7401                 :                :             uint16      newbits2;
                               7402                 :                : 
                               7403                 :                :             /*
                               7404                 :                :              * xmax is an old MultiXactId that we have to replace with a new
                               7405                 :                :              * MultiXactId, to carry forward two or more original member XIDs.
                               7406                 :                :              */
 1312 pg@bowt.ie               7407         [ -  + ]:              1 :             Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
                               7408                 :                : 
                               7409                 :                :             /*
                               7410                 :                :              * We can't use GetMultiXactIdHintBits directly on the new multi
                               7411                 :                :              * here; that routine initializes the masks to all zeroes, which
                               7412                 :                :              * would lose other bits we need.  Doing it this way ensures all
                               7413                 :                :              * unrelated bits remain untouched.
                               7414                 :                :              */
 4605 alvherre@alvh.no-ip.     7415                 :              1 :             frz->t_infomask &= ~HEAP_XMAX_BITS;
                               7416                 :              1 :             frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               7417                 :              1 :             GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
                               7418                 :              1 :             frz->t_infomask |= newbits;
                               7419                 :              1 :             frz->t_infomask2 |= newbits2;
                               7420                 :              1 :             frz->xmax = newxmax;
 1312 pg@bowt.ie               7421                 :              1 :             replace_xmax = true;
                               7422                 :                :         }
                               7423                 :                :         else
                               7424                 :                :         {
                               7425                 :                :             /*
                               7426                 :                :              * Freeze plan for tuple "freezes xmax" in the strictest sense:
                               7427                 :                :              * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
                               7428                 :                :              */
                               7429         [ -  + ]:              4 :             Assert(flags & FRM_INVALIDATE_XMAX);
 1575                          7430         [ -  + ]:              4 :             Assert(!TransactionIdIsValid(newxmax));
                               7431                 :                : 
                               7432                 :                :             /* Will set freeze_xmax flags in freeze plan below */
 1312                          7433                 :              4 :             freeze_xmax = true;
                               7434                 :                :         }
                               7435                 :                : 
                               7436                 :                :         /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
 1306                          7437   [ -  +  -  -  :              6 :         Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
                                              -  - ]
                               7438                 :                :     }
 3693 rhaas@postgresql.org     7439         [ +  + ]:        7403767 :     else if (TransactionIdIsNormal(xid))
                               7440                 :                :     {
                               7441                 :                :         /* Raw xmax is normal XID */
 1312 pg@bowt.ie               7442         [ -  + ]:        1351992 :         if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
 3177 andres@anarazel.de       7443         [ #  # ]:UBC           0 :             ereport(ERROR,
                               7444                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               7445                 :                :                      errmsg_internal("found xmax %u from before relfrozenxid %u",
                               7446                 :                :                                      xid, cutoffs->relfrozenxid)));
                               7447                 :                : 
                               7448                 :                :         /* Will set freeze_xmax flags in freeze plan below */
 1300 pg@bowt.ie               7449                 :CBC     1351992 :         freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
                               7450                 :                : 
                               7451                 :                :         /*
                               7452                 :                :          * Verify that xmax aborted if and when freeze plan is executed,
                               7453                 :                :          * provided it's from an update. (A lock-only xmax can be removed
                               7454                 :                :          * independent of this, since the lock is released at xact end.)
                               7455                 :                :          */
                               7456   [ +  +  +  + ]:        1351992 :         if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
                               7457                 :           5445 :             frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
                               7458                 :                :     }
 1341                          7459         [ +  - ]:        6051775 :     else if (!TransactionIdIsValid(xid))
                               7460                 :                :     {
                               7461                 :                :         /* Raw xmax is InvalidTransactionId XID */
                               7462         [ -  + ]:        6051775 :         Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
 3005 alvherre@alvh.no-ip.     7463                 :        6051775 :         xmax_already_frozen = true;
                               7464                 :                :     }
                               7465                 :                :     else
 3005 alvherre@alvh.no-ip.     7466         [ #  # ]:UBC           0 :         ereport(ERROR,
                               7467                 :                :                 (errcode(ERRCODE_DATA_CORRUPTED),
                               7468                 :                :                  errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
                               7469                 :                :                                  xid, tuple->t_infomask)));
                               7470                 :                : 
 1312 pg@bowt.ie               7471         [ +  + ]:CBC     7403773 :     if (freeze_xmin)
                               7472                 :                :     {
                               7473         [ -  + ]:        4994675 :         Assert(!xmin_already_frozen);
                               7474                 :                : 
                               7475                 :        4994675 :         frz->t_infomask |= HEAP_XMIN_FROZEN;
                               7476                 :                :     }
                               7477         [ -  + ]:        7403773 :     if (replace_xvac)
                               7478                 :                :     {
                               7479                 :                :         /*
                               7480                 :                :          * If a MOVED_OFF tuple is not dead, the xvac transaction must have
                               7481                 :                :          * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
                               7482                 :                :          * transaction succeeded.
                               7483                 :                :          */
 1306 pg@bowt.ie               7484         [ #  # ]:UBC           0 :         Assert(pagefrz->freeze_required);
 1312                          7485         [ #  # ]:              0 :         if (tuple->t_infomask & HEAP_MOVED_OFF)
                               7486                 :              0 :             frz->frzflags |= XLH_INVALID_XVAC;
                               7487                 :                :         else
                               7488                 :              0 :             frz->frzflags |= XLH_FREEZE_XVAC;
                               7489                 :                :     }
 1312 pg@bowt.ie               7490         [ +  + ]:CBC     7403773 :     if (replace_xmax)
                               7491                 :                :     {
                               7492   [ +  -  -  + ]:              1 :         Assert(!xmax_already_frozen && !freeze_xmax);
 1306                          7493         [ -  + ]:              1 :         Assert(pagefrz->freeze_required);
                               7494                 :                : 
                               7495                 :                :         /* Already set replace_xmax flags in freeze plan earlier */
                               7496                 :                :     }
 4623 alvherre@alvh.no-ip.     7497         [ +  + ]:        7403773 :     if (freeze_xmax)
                               7498                 :                :     {
 1312 pg@bowt.ie               7499   [ +  -  -  + ]:           6450 :         Assert(!xmax_already_frozen && !replace_xmax);
                               7500                 :                : 
 4605 alvherre@alvh.no-ip.     7501                 :           6450 :         frz->xmax = InvalidTransactionId;
                               7502                 :                : 
                               7503                 :                :         /*
                               7504                 :                :          * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
                               7505                 :                :          * LOCKED.  Normalize to INVALID just to be sure no one gets confused.
                               7506                 :                :          * Also get rid of the HEAP_KEYS_UPDATED bit.
                               7507                 :                :          */
                               7508                 :           6450 :         frz->t_infomask &= ~HEAP_XMAX_BITS;
                               7509                 :           6450 :         frz->t_infomask |= HEAP_XMAX_INVALID;
                               7510                 :           6450 :         frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
                               7511                 :           6450 :         frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               7512                 :                :     }
                               7513                 :                : 
                               7514                 :                :     /*
                               7515                 :                :      * Determine if this tuple is already totally frozen, or will become
                               7516                 :                :      * totally frozen (provided caller executes freeze plans for the page)
                               7517                 :                :      */
 1312 pg@bowt.ie               7518   [ +  +  +  +  :       13297583 :     *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
                                              +  + ]
                               7519         [ +  + ]:        5893810 :                        (freeze_xmax || xmax_already_frozen));
                               7520                 :                : 
 1306                          7521   [ +  +  +  +  :        7403773 :     if (!pagefrz->freeze_required && !(xmin_already_frozen &&
                                              +  + ]
                               7522                 :                :                                        xmax_already_frozen))
                               7523                 :                :     {
                               7524                 :                :         /*
                               7525                 :                :          * So far no previous tuple from the page made freezing mandatory.
                               7526                 :                :          * Does this tuple force caller to freeze the entire page?
                               7527                 :                :          */
                               7528                 :        5145384 :         pagefrz->freeze_required =
                               7529                 :        5145384 :             heap_tuple_should_freeze(tuple, cutoffs,
                               7530                 :                :                                      &pagefrz->NoFreezePageRelfrozenXid,
                               7531                 :                :                                      &pagefrz->NoFreezePageRelminMxid);
                               7532                 :                :     }
                               7533                 :                : 
                               7534                 :                :     /* Tell caller if this tuple has a usable freeze plan set in *frz */
 1312                          7535   [ +  +  +  -  :        7403773 :     return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
                                        +  -  +  + ]
                               7536                 :                : }
                               7537                 :                : 
                               7538                 :                : /*
                               7539                 :                :  * Perform xmin/xmax XID status sanity checks before actually executing freeze
                               7540                 :                :  * plans.
                               7541                 :                :  *
                               7542                 :                :  * heap_prepare_freeze_tuple doesn't perform these checks directly because
                               7543                 :                :  * pg_xact lookups are relatively expensive.  They shouldn't be repeated by
                               7544                 :                :  * successive VACUUMs that each decide against freezing the same page.
                               7545                 :                :  */
                               7546                 :                : void
  844 heikki.linnakangas@i     7547                 :          25149 : heap_pre_freeze_checks(Buffer buffer,
                               7548                 :                :                        HeapTupleFreeze *tuples, int ntuples)
                               7549                 :                : {
 1349 pg@bowt.ie               7550                 :          25149 :     Page        page = BufferGetPage(buffer);
                               7551                 :                : 
 1300                          7552         [ +  + ]:        1317639 :     for (int i = 0; i < ntuples; i++)
                               7553                 :                :     {
                               7554                 :        1292490 :         HeapTupleFreeze *frz = tuples + i;
                               7555                 :        1292490 :         ItemId      itemid = PageGetItemId(page, frz->offset);
                               7556                 :                :         HeapTupleHeader htup;
                               7557                 :                : 
                               7558                 :        1292490 :         htup = (HeapTupleHeader) PageGetItem(page, itemid);
                               7559                 :                : 
                               7560                 :                :         /* Deliberately avoid relying on tuple hint bits here */
                               7561         [ +  + ]:        1292490 :         if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
                               7562                 :                :         {
                               7563                 :        1292489 :             TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
                               7564                 :                : 
                               7565         [ -  + ]:        1292489 :             Assert(!HeapTupleHeaderXminFrozen(htup));
                               7566         [ -  + ]:        1292489 :             if (unlikely(!TransactionIdDidCommit(xmin)))
 1300 pg@bowt.ie               7567         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               7568                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               7569                 :                :                          errmsg_internal("uncommitted xmin %u needs to be frozen",
                               7570                 :                :                                          xmin)));
                               7571                 :                :         }
                               7572                 :                : 
                               7573                 :                :         /*
                               7574                 :                :          * TransactionIdDidAbort won't work reliably in the presence of XIDs
                               7575                 :                :          * left behind by transactions that were in progress during a crash,
                               7576                 :                :          * so we can only check that xmax didn't commit
                               7577                 :                :          */
 1300 pg@bowt.ie               7578         [ +  + ]:CBC     1292490 :         if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
                               7579                 :                :         {
                               7580                 :           1268 :             TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
                               7581                 :                : 
                               7582         [ -  + ]:           1268 :             Assert(TransactionIdIsNormal(xmax));
                               7583         [ -  + ]:           1268 :             if (unlikely(TransactionIdDidCommit(xmax)))
 1300 pg@bowt.ie               7584         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               7585                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               7586                 :                :                          errmsg_internal("cannot freeze committed xmax %u",
                               7587                 :                :                                          xmax)));
                               7588                 :                :         }
                               7589                 :                :     }
  844 heikki.linnakangas@i     7590                 :CBC       25149 : }
                               7591                 :                : 
                               7592                 :                : /*
                               7593                 :                :  * Helper which executes freezing of one or more heap tuples on a page on
                               7594                 :                :  * behalf of caller.  Caller passes an array of tuple plans from
                               7595                 :                :  * heap_prepare_freeze_tuple.  Caller must set 'offset' in each plan for us.
                               7596                 :                :  * Must be called in a critical section that also marks the buffer dirty and,
                               7597                 :                :  * if needed, emits WAL.
                               7598                 :                :  */
                               7599                 :                : void
                               7600                 :          25149 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
                               7601                 :                : {
                               7602                 :          25149 :     Page        page = BufferGetPage(buffer);
                               7603                 :                : 
 1349 pg@bowt.ie               7604         [ +  + ]:        1317639 :     for (int i = 0; i < ntuples; i++)
                               7605                 :                :     {
 1300                          7606                 :        1292490 :         HeapTupleFreeze *frz = tuples + i;
                               7607                 :        1292490 :         ItemId      itemid = PageGetItemId(page, frz->offset);
                               7608                 :                :         HeapTupleHeader htup;
                               7609                 :                : 
 1349                          7610                 :        1292490 :         htup = (HeapTupleHeader) PageGetItem(page, itemid);
 1300                          7611                 :        1292490 :         heap_execute_freeze_tuple(htup, frz);
                               7612                 :                :     }
 1349                          7613                 :          25149 : }
                               7614                 :                : 
                               7615                 :                : /*
                               7616                 :                :  * heap_freeze_tuple
                               7617                 :                :  *      Freeze tuple in place, without WAL logging.
                               7618                 :                :  *
                               7619                 :                :  * Useful for callers like CLUSTER that perform their own WAL logging.
                               7620                 :                :  */
                               7621                 :                : bool
 3177 andres@anarazel.de       7622                 :         474721 : heap_freeze_tuple(HeapTupleHeader tuple,
                               7623                 :                :                   TransactionId relfrozenxid, TransactionId relminmxid,
                               7624                 :                :                   TransactionId FreezeLimit, TransactionId MultiXactCutoff)
                               7625                 :                : {
                               7626                 :                :     HeapTupleFreeze frz;
                               7627                 :                :     bool        do_freeze;
                               7628                 :                :     bool        totally_frozen;
                               7629                 :                :     struct VacuumCutoffs cutoffs;
                               7630                 :                :     HeapPageFreeze pagefrz;
                               7631                 :                : 
 1312 pg@bowt.ie               7632                 :         474721 :     cutoffs.relfrozenxid = relfrozenxid;
                               7633                 :         474721 :     cutoffs.relminmxid = relminmxid;
                               7634                 :         474721 :     cutoffs.OldestXmin = FreezeLimit;
                               7635                 :         474721 :     cutoffs.OldestMxact = MultiXactCutoff;
                               7636                 :         474721 :     cutoffs.FreezeLimit = FreezeLimit;
                               7637                 :         474721 :     cutoffs.MultiXactCutoff = MultiXactCutoff;
                               7638                 :                : 
 1306                          7639                 :         474721 :     pagefrz.freeze_required = true;
                               7640                 :         474721 :     pagefrz.FreezePageRelfrozenXid = FreezeLimit;
                               7641                 :         474721 :     pagefrz.FreezePageRelminMxid = MultiXactCutoff;
  138 melanieplageman@gmai     7642                 :         474721 :     pagefrz.FreezePageConflictXid = InvalidTransactionId;
 1306 pg@bowt.ie               7643                 :         474721 :     pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
                               7644                 :         474721 :     pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
                               7645                 :                : 
 1312                          7646                 :         474721 :     do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
                               7647                 :                :                                           &pagefrz, &frz, &totally_frozen);
                               7648                 :                : 
                               7649                 :                :     /*
                               7650                 :                :      * Note that because this is not a WAL-logged operation, we don't need to
                               7651                 :                :      * fill in the offset in the freeze record.
                               7652                 :                :      */
                               7653                 :                : 
 4605 alvherre@alvh.no-ip.     7654         [ +  + ]:         474721 :     if (do_freeze)
                               7655                 :         379204 :         heap_execute_freeze_tuple(tuple, &frz);
                               7656                 :         474721 :     return do_freeze;
                               7657                 :                : }
                               7658                 :                : 
                               7659                 :                : /*
                               7660                 :                :  * For a given MultiXactId, return the hint bits that should be set in the
                               7661                 :                :  * tuple's infomask.
                               7662                 :                :  *
                               7663                 :                :  * Normally this should be called for a multixact that was just created, and
                               7664                 :                :  * so is on our local cache, so the GetMembers call is fast.
                               7665                 :                :  */
                               7666                 :                : static void
 4932                          7667                 :          76871 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
                               7668                 :                :                        uint16 *new_infomask2)
                               7669                 :                : {
                               7670                 :                :     int         nmembers;
                               7671                 :                :     MultiXactMember *members;
                               7672                 :                :     int         i;
 4806 bruce@momjian.us         7673                 :          76871 :     uint16      bits = HEAP_XMAX_IS_MULTI;
                               7674                 :          76871 :     uint16      bits2 = 0;
                               7675                 :          76871 :     bool        has_update = false;
                               7676                 :          76871 :     LockTupleMode strongest = LockTupleKeyShare;
                               7677                 :                : 
                               7678                 :                :     /*
                               7679                 :                :      * We only use this in multis we just created, so they cannot be values
                               7680                 :                :      * pre-pg_upgrade.
                               7681                 :                :      */
 4380 alvherre@alvh.no-ip.     7682                 :          76871 :     nmembers = GetMultiXactIdMembers(multi, &members, false, false);
                               7683                 :                : 
 4932                          7684         [ +  + ]:        1472824 :     for (i = 0; i < nmembers; i++)
                               7685                 :                :     {
                               7686                 :                :         LockTupleMode mode;
                               7687                 :                : 
                               7688                 :                :         /*
                               7689                 :                :          * Remember the strongest lock mode held by any member of the
                               7690                 :                :          * multixact.
                               7691                 :                :          */
 4924                          7692                 :        1395953 :         mode = TUPLOCK_from_mxstatus(members[i].status);
                               7693         [ +  + ]:        1395953 :         if (mode > strongest)
                               7694                 :           2930 :             strongest = mode;
                               7695                 :                : 
                               7696                 :                :         /* See what other bits we need */
 4932                          7697   [ +  +  +  +  :        1395953 :         switch (members[i].status)
                                                 - ]
                               7698                 :                :         {
                               7699                 :        1393531 :             case MultiXactStatusForKeyShare:
                               7700                 :                :             case MultiXactStatusForShare:
                               7701                 :                :             case MultiXactStatusForNoKeyUpdate:
                               7702                 :        1393531 :                 break;
                               7703                 :                : 
                               7704                 :             53 :             case MultiXactStatusForUpdate:
                               7705                 :             53 :                 bits2 |= HEAP_KEYS_UPDATED;
                               7706                 :             53 :                 break;
                               7707                 :                : 
                               7708                 :           2359 :             case MultiXactStatusNoKeyUpdate:
                               7709                 :           2359 :                 has_update = true;
                               7710                 :           2359 :                 break;
                               7711                 :                : 
                               7712                 :             10 :             case MultiXactStatusUpdate:
                               7713                 :             10 :                 bits2 |= HEAP_KEYS_UPDATED;
                               7714                 :             10 :                 has_update = true;
                               7715                 :             10 :                 break;
                               7716                 :                :         }
                               7717                 :                :     }
                               7718                 :                : 
 4924                          7719   [ +  +  +  + ]:          76871 :     if (strongest == LockTupleExclusive ||
                               7720                 :                :         strongest == LockTupleNoKeyExclusive)
                               7721                 :           2450 :         bits |= HEAP_XMAX_EXCL_LOCK;
                               7722         [ +  + ]:          74421 :     else if (strongest == LockTupleShare)
                               7723                 :            477 :         bits |= HEAP_XMAX_SHR_LOCK;
                               7724         [ +  - ]:          73944 :     else if (strongest == LockTupleKeyShare)
                               7725                 :          73944 :         bits |= HEAP_XMAX_KEYSHR_LOCK;
                               7726                 :                : 
 4932                          7727         [ +  + ]:          76871 :     if (!has_update)
                               7728                 :          74502 :         bits |= HEAP_XMAX_LOCK_ONLY;
                               7729                 :                : 
                               7730         [ +  - ]:          76871 :     if (nmembers > 0)
                               7731                 :          76871 :         pfree(members);
                               7732                 :                : 
                               7733                 :          76871 :     *new_infomask = bits;
                               7734                 :          76871 :     *new_infomask2 = bits2;
                               7735                 :          76871 : }
                               7736                 :                : 
                               7737                 :                : /*
                               7738                 :                :  * MultiXactIdGetUpdateXid
                               7739                 :                :  *
                               7740                 :                :  * Given a multixact Xmax and corresponding infomask, which does not have the
                               7741                 :                :  * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
                               7742                 :                :  * transaction.
                               7743                 :                :  *
                               7744                 :                :  * Caller is expected to check the status of the updating transaction, if
                               7745                 :                :  * necessary.
                               7746                 :                :  */
                               7747                 :                : static TransactionId
                               7748                 :         162117 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
                               7749                 :                : {
 4806 bruce@momjian.us         7750                 :         162117 :     TransactionId update_xact = InvalidTransactionId;
                               7751                 :                :     MultiXactMember *members;
                               7752                 :                :     int         nmembers;
                               7753                 :                : 
 4932 alvherre@alvh.no-ip.     7754         [ -  + ]:         162117 :     Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
                               7755         [ -  + ]:         162117 :     Assert(t_infomask & HEAP_XMAX_IS_MULTI);
                               7756                 :                : 
                               7757                 :                :     /*
                               7758                 :                :      * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
                               7759                 :                :      * pre-pg_upgrade.
                               7760                 :                :      */
 4380                          7761                 :         162117 :     nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
                               7762                 :                : 
 4932                          7763         [ +  - ]:         162117 :     if (nmembers > 0)
                               7764                 :                :     {
                               7765                 :                :         int         i;
                               7766                 :                : 
                               7767         [ +  + ]:        3235262 :         for (i = 0; i < nmembers; i++)
                               7768                 :                :         {
                               7769                 :                :             /* Ignore lockers */
 4622                          7770         [ +  + ]:        3073145 :             if (!ISUPDATE_from_mxstatus(members[i].status))
 4932                          7771                 :        2911028 :                 continue;
                               7772                 :                : 
                               7773                 :                :             /* there can be at most one updater */
                               7774         [ -  + ]:         162117 :             Assert(update_xact == InvalidTransactionId);
                               7775                 :         162117 :             update_xact = members[i].xid;
                               7776                 :                : #ifndef USE_ASSERT_CHECKING
                               7777                 :                : 
                               7778                 :                :             /*
                               7779                 :                :              * in an assert-enabled build, walk the whole array to ensure
                               7780                 :                :              * there's no other updater.
                               7781                 :                :              */
                               7782                 :                :             break;
                               7783                 :                : #endif
                               7784                 :                :         }
                               7785                 :                : 
                               7786                 :         162117 :         pfree(members);
                               7787                 :                :     }
                               7788                 :                : 
                               7789                 :         162117 :     return update_xact;
                               7790                 :                : }
                               7791                 :                : 
                               7792                 :                : /*
                               7793                 :                :  * HeapTupleGetUpdateXid
                               7794                 :                :  *      As above, but use a HeapTupleHeader
                               7795                 :                :  *
                               7796                 :                :  * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
                               7797                 :                :  * checking the hint bits.
                               7798                 :                :  */
                               7799                 :                : TransactionId
  549 peter@eisentraut.org     7800                 :         159977 : HeapTupleGetUpdateXid(const HeapTupleHeaderData *tup)
                               7801                 :                : {
                               7802                 :         159977 :     return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tup),
                               7803                 :         159977 :                                    tup->t_infomask);
                               7804                 :                : }
                               7805                 :                : 
                               7806                 :                : /*
                               7807                 :                :  * Does the given multixact conflict with the current transaction grabbing a
                               7808                 :                :  * tuple lock of the given strength?
                               7809                 :                :  *
                               7810                 :                :  * The passed infomask pairs up with the given multixact in the tuple header.
                               7811                 :                :  *
                               7812                 :                :  * If current_is_member is not NULL, it is set to 'true' if the current
                               7813                 :                :  * transaction is a member of the given multixact.
                               7814                 :                :  */
                               7815                 :                : static bool
 4230 alvherre@alvh.no-ip.     7816                 :            218 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
                               7817                 :                :                         LockTupleMode lockmode, bool *current_is_member)
                               7818                 :                : {
                               7819                 :                :     int         nmembers;
                               7820                 :                :     MultiXactMember *members;
 4082 bruce@momjian.us         7821                 :            218 :     bool        result = false;
                               7822                 :            218 :     LOCKMODE    wanted = tupleLockExtraInfo[lockmode].hwlock;
                               7823                 :                : 
 3684 alvherre@alvh.no-ip.     7824         [ -  + ]:            218 :     if (HEAP_LOCKED_UPGRADED(infomask))
 3684 alvherre@alvh.no-ip.     7825                 :UBC           0 :         return false;
                               7826                 :                : 
 3684 alvherre@alvh.no-ip.     7827                 :CBC         218 :     nmembers = GetMultiXactIdMembers(multi, &members, false,
 4230                          7828                 :            218 :                                      HEAP_XMAX_IS_LOCKED_ONLY(infomask));
                               7829         [ +  - ]:            218 :     if (nmembers >= 0)
                               7830                 :                :     {
                               7831                 :                :         int         i;
                               7832                 :                : 
                               7833         [ +  + ]:           2682 :         for (i = 0; i < nmembers; i++)
                               7834                 :                :         {
                               7835                 :                :             TransactionId memxid;
                               7836                 :                :             LOCKMODE    memlockmode;
                               7837                 :                : 
 2595                          7838   [ +  +  +  +  :           2471 :             if (result && (current_is_member == NULL || *current_is_member))
                                              +  - ]
                               7839                 :                :                 break;
                               7840                 :                : 
                               7841                 :           2464 :             memlockmode = LOCKMODE_from_mxstatus(members[i].status);
                               7842                 :                : 
                               7843                 :                :             /* ignore members from current xact (but track their presence) */
 2597                          7844                 :           2464 :             memxid = members[i].xid;
                               7845         [ +  + ]:           2464 :             if (TransactionIdIsCurrentTransactionId(memxid))
                               7846                 :                :             {
 2595                          7847         [ +  + ]:             92 :                 if (current_is_member != NULL)
                               7848                 :             78 :                     *current_is_member = true;
                               7849                 :             92 :                 continue;
                               7850                 :                :             }
                               7851         [ +  + ]:           2372 :             else if (result)
                               7852                 :              8 :                 continue;
                               7853                 :                : 
                               7854                 :                :             /* ignore members that don't conflict with the lock we want */
                               7855         [ +  + ]:           2364 :             if (!DoLockModesConflict(memlockmode, wanted))
 2597                          7856                 :           2325 :                 continue;
                               7857                 :                : 
 4230                          7858         [ +  + ]:             39 :             if (ISUPDATE_from_mxstatus(members[i].status))
                               7859                 :                :             {
                               7860                 :                :                 /* ignore aborted updaters */
                               7861         [ +  + ]:             17 :                 if (TransactionIdDidAbort(memxid))
                               7862                 :              1 :                     continue;
                               7863                 :                :             }
                               7864                 :                :             else
                               7865                 :                :             {
                               7866                 :                :                 /* ignore lockers-only that are no longer in progress */
                               7867         [ +  + ]:             22 :                 if (!TransactionIdIsInProgress(memxid))
                               7868                 :              7 :                     continue;
                               7869                 :                :             }
                               7870                 :                : 
                               7871                 :                :             /*
                               7872                 :                :              * Whatever remains are either live lockers that conflict with our
                               7873                 :                :              * wanted lock, and updaters that are not aborted.  Those conflict
                               7874                 :                :              * with what we want.  Set up to return true, but keep going to
                               7875                 :                :              * look for the current transaction among the multixact members,
                               7876                 :                :              * if needed.
                               7877                 :                :              */
                               7878                 :             31 :             result = true;
                               7879                 :                :         }
                               7880                 :            218 :         pfree(members);
                               7881                 :                :     }
                               7882                 :                : 
                               7883                 :            218 :     return result;
                               7884                 :                : }
                               7885                 :                : 
                               7886                 :                : /*
                               7887                 :                :  * Do_MultiXactIdWait
                               7888                 :                :  *      Actual implementation for the two functions below.
                               7889                 :                :  *
                               7890                 :                :  * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
                               7891                 :                :  * needed to ensure we only sleep on conflicting members, and the infomask is
                               7892                 :                :  * used to optimize multixact access in case it's a lock-only multi); 'nowait'
                               7893                 :                :  * indicates whether to use conditional lock acquisition, to allow callers to
                               7894                 :                :  * fail if lock is unavailable.  'rel', 'ctid' and 'oper' are used to set up
                               7895                 :                :  * context information for error messages.  'remaining', if not NULL, receives
                               7896                 :                :  * the number of members that are still running, including any (non-aborted)
                               7897                 :                :  * subtransactions of our own transaction.  'logLockFailure' indicates whether
                               7898                 :                :  * to log details when a lock acquisition fails with 'nowait' enabled.
                               7899                 :                :  *
                               7900                 :                :  * We do this by sleeping on each member using XactLockTableWait.  Any
                               7901                 :                :  * members that belong to the current backend are *not* waited for, however;
                               7902                 :                :  * this would not merely be useless but would lead to Assert failure inside
                               7903                 :                :  * XactLockTableWait.  By the time this returns, it is certain that all
                               7904                 :                :  * transactions *of other backends* that were members of the MultiXactId
                               7905                 :                :  * that conflict with the requested status are dead (and no new ones can have
                               7906                 :                :  * been added, since it is not legal to add members to an existing
                               7907                 :                :  * MultiXactId).
                               7908                 :                :  *
                               7909                 :                :  * But by the time we finish sleeping, someone else may have changed the Xmax
                               7910                 :                :  * of the containing tuple, so the caller needs to iterate on us somehow.
                               7911                 :                :  *
                               7912                 :                :  * Note that in case we return false, the number of remaining members is
                               7913                 :                :  * not to be trusted.
                               7914                 :                :  */
                               7915                 :                : static bool
 4932                          7916                 :             61 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
                               7917                 :                :                    uint16 infomask, bool nowait,
                               7918                 :                :                    Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
                               7919                 :                :                    int *remaining, bool logLockFailure)
                               7920                 :                : {
                               7921                 :             61 :     bool        result = true;
                               7922                 :                :     MultiXactMember *members;
                               7923                 :                :     int         nmembers;
                               7924                 :             61 :     int         remain = 0;
                               7925                 :                : 
                               7926                 :                :     /* for pre-pg_upgrade tuples, no need to sleep at all */
 3684                          7927         [ +  - ]:             61 :     nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
                               7928                 :             61 :         GetMultiXactIdMembers(multi, &members, false,
                               7929                 :             61 :                               HEAP_XMAX_IS_LOCKED_ONLY(infomask));
                               7930                 :                : 
 4932                          7931         [ +  - ]:             61 :     if (nmembers >= 0)
                               7932                 :                :     {
                               7933                 :                :         int         i;
                               7934                 :                : 
                               7935         [ +  + ]:            192 :         for (i = 0; i < nmembers; i++)
                               7936                 :                :         {
                               7937                 :            137 :             TransactionId memxid = members[i].xid;
                               7938                 :            137 :             MultiXactStatus memstatus = members[i].status;
                               7939                 :                : 
                               7940         [ +  + ]:            137 :             if (TransactionIdIsCurrentTransactionId(memxid))
                               7941                 :                :             {
                               7942                 :             25 :                 remain++;
                               7943                 :             25 :                 continue;
                               7944                 :                :             }
                               7945                 :                : 
                               7946         [ +  + ]:            112 :             if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
                               7947                 :            112 :                                      LOCKMODE_from_mxstatus(status)))
                               7948                 :                :             {
                               7949   [ +  +  +  - ]:             22 :                 if (remaining && TransactionIdIsInProgress(memxid))
                               7950                 :              8 :                     remain++;
                               7951                 :             22 :                 continue;
                               7952                 :                :             }
                               7953                 :                : 
                               7954                 :                :             /*
                               7955                 :                :              * This member conflicts with our multi, so we have to sleep (or
                               7956                 :                :              * return failure, if asked to avoid waiting.)
                               7957                 :                :              *
                               7958                 :                :              * Note that we don't set up an error context callback ourselves,
                               7959                 :                :              * but instead we pass the info down to XactLockTableWait.  This
                               7960                 :                :              * might seem a bit wasteful because the context is set up and
                               7961                 :                :              * tore down for each member of the multixact, but in reality it
                               7962                 :                :              * should be barely noticeable, and it avoids duplicate code.
                               7963                 :                :              */
                               7964         [ +  + ]:             90 :             if (nowait)
                               7965                 :                :             {
  499 fujii@postgresql.org     7966                 :              6 :                 result = ConditionalXactLockTableWait(memxid, logLockFailure);
 4932 alvherre@alvh.no-ip.     7967         [ +  - ]:              6 :                 if (!result)
                               7968                 :              6 :                     break;
                               7969                 :                :             }
                               7970                 :                :             else
 4512                          7971                 :             84 :                 XactLockTableWait(memxid, rel, ctid, oper);
                               7972                 :                :         }
                               7973                 :                : 
 4932                          7974                 :             61 :         pfree(members);
                               7975                 :                :     }
                               7976                 :                : 
                               7977         [ +  + ]:             61 :     if (remaining)
                               7978                 :             10 :         *remaining = remain;
                               7979                 :                : 
                               7980                 :             61 :     return result;
                               7981                 :                : }
                               7982                 :                : 
                               7983                 :                : /*
                               7984                 :                :  * MultiXactIdWait
                               7985                 :                :  *      Sleep on a MultiXactId.
                               7986                 :                :  *
                               7987                 :                :  * By the time we finish sleeping, someone else may have changed the Xmax
                               7988                 :                :  * of the containing tuple, so the caller needs to iterate on us somehow.
                               7989                 :                :  *
                               7990                 :                :  * We return (in *remaining, if not NULL) the number of members that are still
                               7991                 :                :  * running, including any (non-aborted) subtransactions of our own transaction.
                               7992                 :                :  */
                               7993                 :                : static void
 4512                          7994                 :             55 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
                               7995                 :                :                 Relation rel, const ItemPointerData *ctid, XLTW_Oper oper,
                               7996                 :                :                 int *remaining)
                               7997                 :                : {
                               7998                 :             55 :     (void) Do_MultiXactIdWait(multi, status, infomask, false,
                               7999                 :                :                               rel, ctid, oper, remaining, false);
 4932                          8000                 :             55 : }
                               8001                 :                : 
                               8002                 :                : /*
                               8003                 :                :  * ConditionalMultiXactIdWait
                               8004                 :                :  *      As above, but only lock if we can get the lock without blocking.
                               8005                 :                :  *
                               8006                 :                :  * By the time we finish sleeping, someone else may have changed the Xmax
                               8007                 :                :  * of the containing tuple, so the caller needs to iterate on us somehow.
                               8008                 :                :  *
                               8009                 :                :  * If the multixact is now all gone, return true.  Returns false if some
                               8010                 :                :  * transactions might still be running.
                               8011                 :                :  *
                               8012                 :                :  * We return (in *remaining, if not NULL) the number of members that are still
                               8013                 :                :  * running, including any (non-aborted) subtransactions of our own transaction.
                               8014                 :                :  */
                               8015                 :                : static bool
                               8016                 :              6 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
                               8017                 :                :                            uint16 infomask, Relation rel, int *remaining,
                               8018                 :                :                            bool logLockFailure)
                               8019                 :                : {
 4512                          8020                 :              6 :     return Do_MultiXactIdWait(multi, status, infomask, true,
                               8021                 :                :                               rel, NULL, XLTW_None, remaining, logLockFailure);
                               8022                 :                : }
                               8023                 :                : 
                               8024                 :                : /*
                               8025                 :                :  * heap_tuple_needs_eventual_freeze
                               8026                 :                :  *
                               8027                 :                :  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
                               8028                 :                :  * will eventually require freezing (if tuple isn't removed by pruning first).
                               8029                 :                :  */
                               8030                 :                : bool
 3799 rhaas@postgresql.org     8031                 :        2160921 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
                               8032                 :                : {
                               8033                 :                :     TransactionId xid;
                               8034                 :                : 
                               8035                 :                :     /*
                               8036                 :                :      * If xmin is a normal transaction ID, this tuple is definitely not
                               8037                 :                :      * frozen.
                               8038                 :                :      */
                               8039                 :        2160921 :     xid = HeapTupleHeaderGetXmin(tuple);
                               8040         [ +  + ]:        2160921 :     if (TransactionIdIsNormal(xid))
                               8041                 :          37960 :         return true;
                               8042                 :                : 
                               8043                 :                :     /*
                               8044                 :                :      * If xmax is a valid xact or multixact, this tuple is also not frozen.
                               8045                 :                :      */
                               8046         [ +  + ]:        2122961 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
                               8047                 :                :     {
                               8048                 :                :         MultiXactId multi;
                               8049                 :                : 
                               8050                 :              2 :         multi = HeapTupleHeaderGetRawXmax(tuple);
                               8051         [ +  - ]:              2 :         if (MultiXactIdIsValid(multi))
                               8052                 :              2 :             return true;
                               8053                 :                :     }
                               8054                 :                :     else
                               8055                 :                :     {
                               8056                 :        2122959 :         xid = HeapTupleHeaderGetRawXmax(tuple);
                               8057         [ +  + ]:        2122959 :         if (TransactionIdIsNormal(xid))
                               8058                 :             40 :             return true;
                               8059                 :                :     }
                               8060                 :                : 
                               8061         [ -  + ]:        2122919 :     if (tuple->t_infomask & HEAP_MOVED)
                               8062                 :                :     {
 3799 rhaas@postgresql.org     8063                 :UBC           0 :         xid = HeapTupleHeaderGetXvac(tuple);
                               8064         [ #  # ]:              0 :         if (TransactionIdIsNormal(xid))
                               8065                 :              0 :             return true;
                               8066                 :                :     }
                               8067                 :                : 
 3799 rhaas@postgresql.org     8068                 :CBC     2122919 :     return false;
                               8069                 :                : }
                               8070                 :                : 
                               8071                 :                : /*
                               8072                 :                :  * heap_tuple_should_freeze
                               8073                 :                :  *
                               8074                 :                :  * Return value indicates if heap_prepare_freeze_tuple sibling function would
                               8075                 :                :  * (or should) force freezing of the heap page that contains caller's tuple.
                               8076                 :                :  * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
                               8077                 :                :  * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
                               8078                 :                :  *
                               8079                 :                :  * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
                               8080                 :                :  * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
                               8081                 :                :  * Our working assumption is that caller won't decide to freeze this tuple.
                               8082                 :                :  * It's up to caller to only ratchet back its own top-level trackers after the
                               8083                 :                :  * point that it fully commits to not freezing the tuple/page in question.
                               8084                 :                :  */
                               8085                 :                : bool
 1306 pg@bowt.ie               8086                 :        5146514 : heap_tuple_should_freeze(HeapTupleHeader tuple,
                               8087                 :                :                          const struct VacuumCutoffs *cutoffs,
                               8088                 :                :                          TransactionId *NoFreezePageRelfrozenXid,
                               8089                 :                :                          MultiXactId *NoFreezePageRelminMxid)
                               8090                 :                : {
                               8091                 :                :     TransactionId xid;
                               8092                 :                :     MultiXactId multi;
 1312                          8093                 :        5146514 :     bool        freeze = false;
                               8094                 :                : 
                               8095                 :                :     /* First deal with xmin */
 5375 rhaas@postgresql.org     8096                 :        5146514 :     xid = HeapTupleHeaderGetXmin(tuple);
 1575 pg@bowt.ie               8097         [ +  + ]:        5146514 :     if (TransactionIdIsNormal(xid))
                               8098                 :                :     {
 1312                          8099         [ -  + ]:        5144216 :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
 1306                          8100         [ +  + ]:        5144216 :         if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
                               8101                 :          23616 :             *NoFreezePageRelfrozenXid = xid;
 1312                          8102         [ +  + ]:        5144216 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
                               8103                 :          20734 :             freeze = true;
                               8104                 :                :     }
                               8105                 :                : 
                               8106                 :                :     /* Now deal with xmax */
 1575                          8107                 :        5146514 :     xid = InvalidTransactionId;
                               8108                 :        5146514 :     multi = InvalidMultiXactId;
                               8109         [ +  + ]:        5146514 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
 4623 alvherre@alvh.no-ip.     8110                 :              2 :         multi = HeapTupleHeaderGetRawXmax(tuple);
                               8111                 :                :     else
 1575 pg@bowt.ie               8112                 :        5146512 :         xid = HeapTupleHeaderGetRawXmax(tuple);
                               8113                 :                : 
                               8114         [ +  + ]:        5146514 :     if (TransactionIdIsNormal(xid))
                               8115                 :                :     {
 1312                          8116         [ -  + ]:        1322317 :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
                               8117                 :                :         /* xmax is a non-permanent XID */
 1306                          8118         [ +  + ]:        1322317 :         if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
                               8119                 :             17 :             *NoFreezePageRelfrozenXid = xid;
 1312                          8120         [ +  + ]:        1322317 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
                               8121                 :             11 :             freeze = true;
                               8122                 :                :     }
 1575                          8123         [ +  + ]:        3824197 :     else if (!MultiXactIdIsValid(multi))
                               8124                 :                :     {
                               8125                 :                :         /* xmax is a permanent XID or invalid MultiXactId/XID */
                               8126                 :                :     }
                               8127         [ -  + ]:              2 :     else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
                               8128                 :                :     {
                               8129                 :                :         /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
 1306 pg@bowt.ie               8130         [ #  # ]:UBC           0 :         if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
                               8131                 :              0 :             *NoFreezePageRelminMxid = multi;
                               8132                 :                :         /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
 1312                          8133                 :              0 :         freeze = true;
                               8134                 :                :     }
                               8135                 :                :     else
                               8136                 :                :     {
                               8137                 :                :         /* xmax is a MultiXactId that may have an updater XID */
                               8138                 :                :         MultiXactMember *members;
                               8139                 :                :         int         nmembers;
                               8140                 :                : 
 1312 pg@bowt.ie               8141         [ -  + ]:CBC           2 :         Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
 1306                          8142         [ +  - ]:              2 :         if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
                               8143                 :              2 :             *NoFreezePageRelminMxid = multi;
 1312                          8144         [ +  - ]:              2 :         if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
                               8145                 :              2 :             freeze = true;
                               8146                 :                : 
                               8147                 :                :         /* need to check whether any member of the mxact is old */
 1575                          8148                 :              2 :         nmembers = GetMultiXactIdMembers(multi, &members, false,
                               8149                 :              2 :                                          HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
                               8150                 :                : 
                               8151         [ +  + ]:              5 :         for (int i = 0; i < nmembers; i++)
                               8152                 :                :         {
                               8153                 :              3 :             xid = members[i].xid;
 1312                          8154         [ -  + ]:              3 :             Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
 1306                          8155         [ -  + ]:              3 :             if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
 1306 pg@bowt.ie               8156                 :UBC           0 :                 *NoFreezePageRelfrozenXid = xid;
 1312 pg@bowt.ie               8157         [ -  + ]:CBC           3 :             if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
 1312 pg@bowt.ie               8158                 :UBC           0 :                 freeze = true;
                               8159                 :                :         }
 1575 pg@bowt.ie               8160         [ +  + ]:CBC           2 :         if (nmembers > 0)
                               8161                 :              1 :             pfree(members);
                               8162                 :                :     }
                               8163                 :                : 
 5375 rhaas@postgresql.org     8164         [ -  + ]:        5146514 :     if (tuple->t_infomask & HEAP_MOVED)
                               8165                 :                :     {
 5375 rhaas@postgresql.org     8166                 :UBC           0 :         xid = HeapTupleHeaderGetXvac(tuple);
 1575 pg@bowt.ie               8167         [ #  # ]:              0 :         if (TransactionIdIsNormal(xid))
                               8168                 :                :         {
 1312                          8169         [ #  # ]:              0 :             Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
 1306                          8170         [ #  # ]:              0 :             if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
                               8171                 :              0 :                 *NoFreezePageRelfrozenXid = xid;
                               8172                 :                :             /* heap_prepare_freeze_tuple forces xvac freezing */
 1312                          8173                 :              0 :             freeze = true;
                               8174                 :                :         }
                               8175                 :                :     }
                               8176                 :                : 
 1312 pg@bowt.ie               8177                 :CBC     5146514 :     return freeze;
                               8178                 :                : }
                               8179                 :                : 
                               8180                 :                : /*
                               8181                 :                :  * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
                               8182                 :                :  * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
                               8183                 :                :  * that caller is in the process of physically removing, e.g. via HOT pruning
                               8184                 :                :  * or index deletion.
                               8185                 :                :  *
                               8186                 :                :  * Caller must initialize its value to InvalidTransactionId, which is
                               8187                 :                :  * generally interpreted as "definitely no need for a recovery conflict".
                               8188                 :                :  * Final value must reflect all heap tuples that caller will physically remove
                               8189                 :                :  * (or remove TID references to) via its ongoing pruning/deletion operation.
                               8190                 :                :  * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
                               8191                 :                :  * caller's WAL record) by REDO routine when it replays caller's operation.
                               8192                 :                :  */
                               8193                 :                : void
 1347                          8194                 :        4080953 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
                               8195                 :                :                                       TransactionId *snapshotConflictHorizon)
                               8196                 :                : {
 6063 simon@2ndQuadrant.co     8197                 :        4080953 :     TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
 4932 alvherre@alvh.no-ip.     8198                 :        4080953 :     TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
 6063 simon@2ndQuadrant.co     8199                 :        4080953 :     TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
                               8200                 :                : 
 6012 tgl@sss.pgh.pa.us        8201         [ -  + ]:        4080953 :     if (tuple->t_infomask & HEAP_MOVED)
                               8202                 :                :     {
 1347 pg@bowt.ie               8203         [ #  # ]:UBC           0 :         if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
                               8204                 :              0 :             *snapshotConflictHorizon = xvac;
                               8205                 :                :     }
                               8206                 :                : 
                               8207                 :                :     /*
                               8208                 :                :      * Ignore tuples inserted by an aborted transaction or if the tuple was
                               8209                 :                :      * updated/deleted by the inserting transaction.
                               8210                 :                :      *
                               8211                 :                :      * Look for a committed hint bit, or if no xmin bit is set, check clog.
                               8212                 :                :      */
 4599 rhaas@postgresql.org     8213         [ +  + ]:CBC     4080953 :     if (HeapTupleHeaderXminCommitted(tuple) ||
                               8214   [ +  +  +  - ]:         136864 :         (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
                               8215                 :                :     {
 5708 simon@2ndQuadrant.co     8216   [ +  +  +  + ]:        7718868 :         if (xmax != xmin &&
 1347 pg@bowt.ie               8217                 :        3759014 :             TransactionIdFollows(xmax, *snapshotConflictHorizon))
                               8218                 :         136240 :             *snapshotConflictHorizon = xmax;
                               8219                 :                :     }
 6063 simon@2ndQuadrant.co     8220                 :        4080953 : }
                               8221                 :                : 
                               8222                 :                : #ifdef USE_PREFETCH
                               8223                 :                : /*
                               8224                 :                :  * Helper function for heap_index_delete_tuples.  Issues prefetch requests for
                               8225                 :                :  * prefetch_count buffers.  The prefetch_state keeps track of all the buffers
                               8226                 :                :  * we can prefetch, and which have already been prefetched; each call to this
                               8227                 :                :  * function picks up where the previous call left off.
                               8228                 :                :  *
                               8229                 :                :  * Note: we expect the deltids array to be sorted in an order that groups TIDs
                               8230                 :                :  * by heap block, with all TIDs for each block appearing together in exactly
                               8231                 :                :  * one group.
                               8232                 :                :  */
                               8233                 :                : static void
 2020 pg@bowt.ie               8234                 :          25321 : index_delete_prefetch_buffer(Relation rel,
                               8235                 :                :                              IndexDeletePrefetchState *prefetch_state,
                               8236                 :                :                              int prefetch_count)
                               8237                 :                : {
 2679 andres@anarazel.de       8238                 :          25321 :     BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
                               8239                 :          25321 :     int         count = 0;
                               8240                 :                :     int         i;
 2020 pg@bowt.ie               8241                 :          25321 :     int         ndeltids = prefetch_state->ndeltids;
                               8242                 :          25321 :     TM_IndexDelete *deltids = prefetch_state->deltids;
                               8243                 :                : 
 2679 andres@anarazel.de       8244                 :          25321 :     for (i = prefetch_state->next_item;
 2020 pg@bowt.ie               8245   [ +  +  +  + ]:         884646 :          i < ndeltids && count < prefetch_count;
 2679 andres@anarazel.de       8246                 :         859325 :          i++)
                               8247                 :                :     {
 2020 pg@bowt.ie               8248                 :         859325 :         ItemPointer htid = &deltids[i].tid;
                               8249                 :                : 
 2679 andres@anarazel.de       8250   [ +  +  +  + ]:        1710968 :         if (cur_hblkno == InvalidBlockNumber ||
                               8251                 :         851643 :             ItemPointerGetBlockNumber(htid) != cur_hblkno)
                               8252                 :                :         {
                               8253                 :          22964 :             cur_hblkno = ItemPointerGetBlockNumber(htid);
                               8254                 :          22964 :             PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
                               8255                 :          22964 :             count++;
                               8256                 :                :         }
                               8257                 :                :     }
                               8258                 :                : 
                               8259                 :                :     /*
                               8260                 :                :      * Save the prefetch position so that next time we can continue from that
                               8261                 :                :      * position.
                               8262                 :                :      */
                               8263                 :          25321 :     prefetch_state->next_item = i;
                               8264                 :          25321 :     prefetch_state->cur_hblkno = cur_hblkno;
                               8265                 :          25321 : }
                               8266                 :                : #endif
                               8267                 :                : 
                               8268                 :                : /*
                               8269                 :                :  * Helper function for heap_index_delete_tuples.  Checks for index corruption
                               8270                 :                :  * involving an invalid TID in index AM caller's index page.
                               8271                 :                :  *
                               8272                 :                :  * This is an ideal place for these checks.  The index AM must hold a buffer
                               8273                 :                :  * lock on the index page containing the TIDs we examine here, so we don't
                               8274                 :                :  * have to worry about concurrent VACUUMs at all.  We can be sure that the
                               8275                 :                :  * index is corrupt when htid points directly to an LP_UNUSED item or
                               8276                 :                :  * heap-only tuple, which is not the case during standard index scans.
                               8277                 :                :  */
                               8278                 :                : static inline void
 1725 pg@bowt.ie               8279                 :         713682 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
                               8280                 :                :                         Page page, OffsetNumber maxoff,
                               8281                 :                :                         const ItemPointerData *htid, TM_IndexStatus *istatus)
                               8282                 :                : {
                               8283                 :         713682 :     OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
                               8284                 :                :     ItemId      iid;
                               8285                 :                : 
                               8286   [ +  -  +  -  :         713682 :     Assert(OffsetNumberIsValid(istatus->idxoffnum));
                                              -  + ]
                               8287                 :                : 
                               8288         [ -  + ]:         713682 :     if (unlikely(indexpagehoffnum > maxoff))
 1725 pg@bowt.ie               8289         [ #  # ]:UBC           0 :         ereport(ERROR,
                               8290                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               8291                 :                :                  errmsg_internal("heap tid from index tuple (%u,%u) points past end of heap page line pointer array at offset %u of block %u in index \"%s\"",
                               8292                 :                :                                  ItemPointerGetBlockNumber(htid),
                               8293                 :                :                                  indexpagehoffnum,
                               8294                 :                :                                  istatus->idxoffnum, delstate->iblknum,
                               8295                 :                :                                  RelationGetRelationName(delstate->irel))));
                               8296                 :                : 
 1725 pg@bowt.ie               8297                 :CBC      713682 :     iid = PageGetItemId(page, indexpagehoffnum);
                               8298         [ -  + ]:         713682 :     if (unlikely(!ItemIdIsUsed(iid)))
 1725 pg@bowt.ie               8299         [ #  # ]:UBC           0 :         ereport(ERROR,
                               8300                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               8301                 :                :                  errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
                               8302                 :                :                                  ItemPointerGetBlockNumber(htid),
                               8303                 :                :                                  indexpagehoffnum,
                               8304                 :                :                                  istatus->idxoffnum, delstate->iblknum,
                               8305                 :                :                                  RelationGetRelationName(delstate->irel))));
                               8306                 :                : 
 1725 pg@bowt.ie               8307         [ +  + ]:CBC      713682 :     if (ItemIdHasStorage(iid))
                               8308                 :                :     {
                               8309                 :                :         HeapTupleHeader htup;
                               8310                 :                : 
                               8311         [ -  + ]:         445272 :         Assert(ItemIdIsNormal(iid));
                               8312                 :         445272 :         htup = (HeapTupleHeader) PageGetItem(page, iid);
                               8313                 :                : 
                               8314         [ -  + ]:         445272 :         if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
 1725 pg@bowt.ie               8315         [ #  # ]:UBC           0 :             ereport(ERROR,
                               8316                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               8317                 :                :                      errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
                               8318                 :                :                                      ItemPointerGetBlockNumber(htid),
                               8319                 :                :                                      indexpagehoffnum,
                               8320                 :                :                                      istatus->idxoffnum, delstate->iblknum,
                               8321                 :                :                                      RelationGetRelationName(delstate->irel))));
                               8322                 :                :     }
 1725 pg@bowt.ie               8323                 :CBC      713682 : }
                               8324                 :                : 
                               8325                 :                : /*
                               8326                 :                :  * heapam implementation of tableam's index_delete_tuples interface.
                               8327                 :                :  *
                               8328                 :                :  * This helper function is called by index AMs during index tuple deletion.
                               8329                 :                :  * See tableam header comments for an explanation of the interface implemented
                               8330                 :                :  * here and a general theory of operation.  Note that each call here is either
                               8331                 :                :  * a simple index deletion call, or a bottom-up index deletion call.
                               8332                 :                :  *
                               8333                 :                :  * It's possible for this to generate a fair amount of I/O, since we may be
                               8334                 :                :  * deleting hundreds of tuples from a single index block.  To amortize that
                               8335                 :                :  * cost to some degree, this uses prefetching and combines repeat accesses to
                               8336                 :                :  * the same heap block.
                               8337                 :                :  */
                               8338                 :                : TransactionId
 2020                          8339                 :           7682 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
                               8340                 :                : {
                               8341                 :                :     /* Initial assumption is that earlier pruning took care of conflict */
 1347                          8342                 :           7682 :     TransactionId snapshotConflictHorizon = InvalidTransactionId;
 2034                          8343                 :           7682 :     BlockNumber blkno = InvalidBlockNumber;
 2679 andres@anarazel.de       8344                 :           7682 :     Buffer      buf = InvalidBuffer;
 2034 pg@bowt.ie               8345                 :           7682 :     Page        page = NULL;
                               8346                 :           7682 :     OffsetNumber maxoff = InvalidOffsetNumber;
                               8347                 :                :     TransactionId priorXmax;
                               8348                 :                : #ifdef USE_PREFETCH
                               8349                 :                :     IndexDeletePrefetchState prefetch_state;
                               8350                 :                :     int         prefetch_distance;
                               8351                 :                : #endif
                               8352                 :                :     SnapshotData SnapshotNonVacuumable;
 2020                          8353                 :           7682 :     int         finalndeltids = 0,
                               8354                 :           7682 :                 nblocksaccessed = 0;
                               8355                 :                : 
                               8356                 :                :     /* State that's only used in bottom-up index deletion case */
                               8357                 :           7682 :     int         nblocksfavorable = 0;
                               8358                 :           7682 :     int         curtargetfreespace = delstate->bottomupfreespace,
                               8359                 :           7682 :                 lastfreespace = 0,
                               8360                 :           7682 :                 actualfreespace = 0;
                               8361                 :           7682 :     bool        bottomup_final_block = false;
                               8362                 :                : 
                               8363                 :           7682 :     InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
                               8364                 :                : 
                               8365                 :                :     /* Sort caller's deltids array by TID for further processing */
                               8366                 :           7682 :     index_delete_sort(delstate);
                               8367                 :                : 
                               8368                 :                :     /*
                               8369                 :                :      * Bottom-up case: resort deltids array in an order attuned to where the
                               8370                 :                :      * greatest number of promising TIDs are to be found, and determine how
                               8371                 :                :      * many blocks from the start of sorted array should be considered
                               8372                 :                :      * favorable.  This will also shrink the deltids array in order to
                               8373                 :                :      * eliminate completely unfavorable blocks up front.
                               8374                 :                :      */
                               8375         [ +  + ]:           7682 :     if (delstate->bottomup)
                               8376                 :           2785 :         nblocksfavorable = bottomup_sort_and_shrink(delstate);
                               8377                 :                : 
                               8378                 :                : #ifdef USE_PREFETCH
                               8379                 :                :     /* Initialize prefetch state. */
 2679 andres@anarazel.de       8380                 :           7682 :     prefetch_state.cur_hblkno = InvalidBlockNumber;
                               8381                 :           7682 :     prefetch_state.next_item = 0;
 2020 pg@bowt.ie               8382                 :           7682 :     prefetch_state.ndeltids = delstate->ndeltids;
                               8383                 :           7682 :     prefetch_state.deltids = delstate->deltids;
                               8384                 :                : 
                               8385                 :                :     /*
                               8386                 :                :      * Determine the prefetch distance that we will attempt to maintain.
                               8387                 :                :      *
                               8388                 :                :      * Since the caller holds a buffer lock somewhere in rel, we'd better make
                               8389                 :                :      * sure that isn't a catalog relation before we call code that does
                               8390                 :                :      * syscache lookups, to avoid risk of deadlock.
                               8391                 :                :      */
 2672 tmunro@postgresql.or     8392         [ +  + ]:           7682 :     if (IsCatalogRelation(rel))
 2323                          8393                 :           5461 :         prefetch_distance = maintenance_io_concurrency;
                               8394                 :                :     else
                               8395                 :                :         prefetch_distance =
                               8396                 :           2221 :             get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
                               8397                 :                : 
                               8398                 :                :     /* Cap initial prefetch distance for bottom-up deletion caller */
 2020 pg@bowt.ie               8399         [ +  + ]:           7682 :     if (delstate->bottomup)
                               8400                 :                :     {
                               8401         [ -  + ]:           2785 :         Assert(nblocksfavorable >= 1);
                               8402         [ -  + ]:           2785 :         Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
                               8403                 :           2785 :         prefetch_distance = Min(prefetch_distance, nblocksfavorable);
                               8404                 :                :     }
                               8405                 :                : 
                               8406                 :                :     /* Start prefetching. */
                               8407                 :           7682 :     index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
                               8408                 :                : #endif
                               8409                 :                : 
                               8410                 :                :     /* Iterate over deltids, determine which to delete, check their horizon */
                               8411         [ -  + ]:           7682 :     Assert(delstate->ndeltids > 0);
                               8412         [ +  + ]:         721364 :     for (int i = 0; i < delstate->ndeltids; i++)
                               8413                 :                :     {
                               8414                 :         716466 :         TM_IndexDelete *ideltid = &delstate->deltids[i];
                               8415                 :         716466 :         TM_IndexStatus *istatus = delstate->status + ideltid->id;
                               8416                 :         716466 :         ItemPointer htid = &ideltid->tid;
                               8417                 :                :         OffsetNumber offnum;
                               8418                 :                : 
                               8419                 :                :         /*
                               8420                 :                :          * Read buffer, and perform required extra steps each time a new block
                               8421                 :                :          * is encountered.  Avoid refetching if it's the same block as the one
                               8422                 :                :          * from the last htid.
                               8423                 :                :          */
 2034                          8424   [ +  +  +  + ]:        1425250 :         if (blkno == InvalidBlockNumber ||
                               8425                 :         708784 :             ItemPointerGetBlockNumber(htid) != blkno)
                               8426                 :                :         {
                               8427                 :                :             /*
                               8428                 :                :              * Consider giving up early for bottom-up index deletion caller
                               8429                 :                :              * first. (Only prefetch next-next block afterwards, when it
                               8430                 :                :              * becomes clear that we're at least going to access the next
                               8431                 :                :              * block in line.)
                               8432                 :                :              *
                               8433                 :                :              * Sometimes the first block frees so much space for bottom-up
                               8434                 :                :              * caller that the deletion process can end without accessing any
                               8435                 :                :              * more blocks.  It is usually necessary to access 2 or 3 blocks
                               8436                 :                :              * per bottom-up deletion operation, though.
                               8437                 :                :              */
 2020                          8438         [ +  + ]:          20423 :             if (delstate->bottomup)
                               8439                 :                :             {
                               8440                 :                :                 /*
                               8441                 :                :                  * We often allow caller to delete a few additional items
                               8442                 :                :                  * whose entries we reached after the point that space target
                               8443                 :                :                  * from caller was satisfied.  The cost of accessing the page
                               8444                 :                :                  * was already paid at that point, so it made sense to finish
                               8445                 :                :                  * it off.  When that happened, we finalize everything here
                               8446                 :                :                  * (by finishing off the whole bottom-up deletion operation
                               8447                 :                :                  * without needlessly paying the cost of accessing any more
                               8448                 :                :                  * blocks).
                               8449                 :                :                  */
                               8450         [ +  + ]:           5921 :                 if (bottomup_final_block)
                               8451                 :            169 :                     break;
                               8452                 :                : 
                               8453                 :                :                 /*
                               8454                 :                :                  * Give up when we didn't enable our caller to free any
                               8455                 :                :                  * additional space as a result of processing the page that we
                               8456                 :                :                  * just finished up with.  This rule is the main way in which
                               8457                 :                :                  * we keep the cost of bottom-up deletion under control.
                               8458                 :                :                  */
                               8459   [ +  +  +  + ]:           5752 :                 if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
                               8460                 :           2615 :                     break;
                               8461                 :           3137 :                 lastfreespace = actualfreespace;    /* for next time */
                               8462                 :                : 
                               8463                 :                :                 /*
                               8464                 :                :                  * Deletion operation (which is bottom-up) will definitely
                               8465                 :                :                  * access the next block in line.  Prepare for that now.
                               8466                 :                :                  *
                               8467                 :                :                  * Decay target free space so that we don't hang on for too
                               8468                 :                :                  * long with a marginal case. (Space target is only truly
                               8469                 :                :                  * helpful when it allows us to recognize that we don't need
                               8470                 :                :                  * to access more than 1 or 2 blocks to satisfy caller due to
                               8471                 :                :                  * agreeable workload characteristics.)
                               8472                 :                :                  *
                               8473                 :                :                  * We are a bit more patient when we encounter contiguous
                               8474                 :                :                  * blocks, though: these are treated as favorable blocks.  The
                               8475                 :                :                  * decay process is only applied when the next block in line
                               8476                 :                :                  * is not a favorable/contiguous block.  This is not an
                               8477                 :                :                  * exception to the general rule; we still insist on finding
                               8478                 :                :                  * at least one deletable item per block accessed.  See
                               8479                 :                :                  * bottomup_nblocksfavorable() for full details of the theory
                               8480                 :                :                  * behind favorable blocks and heap block locality in general.
                               8481                 :                :                  *
                               8482                 :                :                  * Note: The first block in line is always treated as a
                               8483                 :                :                  * favorable block, so the earliest possible point that the
                               8484                 :                :                  * decay can be applied is just before we access the second
                               8485                 :                :                  * block in line.  The Assert() verifies this for us.
                               8486                 :                :                  */
                               8487   [ +  +  -  + ]:           3137 :                 Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
                               8488         [ +  + ]:           3137 :                 if (nblocksfavorable > 0)
                               8489                 :           2945 :                     nblocksfavorable--;
                               8490                 :                :                 else
                               8491                 :            192 :                     curtargetfreespace /= 2;
                               8492                 :                :             }
                               8493                 :                : 
                               8494                 :                :             /* release old buffer */
                               8495         [ +  + ]:          17639 :             if (BufferIsValid(buf))
                               8496                 :           9957 :                 UnlockReleaseBuffer(buf);
                               8497                 :                : 
                               8498                 :          17639 :             blkno = ItemPointerGetBlockNumber(htid);
 2034                          8499                 :          17639 :             buf = ReadBuffer(rel, blkno);
 2020                          8500                 :          17639 :             nblocksaccessed++;
                               8501   [ +  +  -  + ]:          17639 :             Assert(!delstate->bottomup ||
                               8502                 :                :                    nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
                               8503                 :                : 
                               8504                 :                : #ifdef USE_PREFETCH
                               8505                 :                : 
                               8506                 :                :             /*
                               8507                 :                :              * To maintain the prefetch distance, prefetch one more page for
                               8508                 :                :              * each page we read.
                               8509                 :                :              */
                               8510                 :          17639 :             index_delete_prefetch_buffer(rel, &prefetch_state, 1);
                               8511                 :                : #endif
                               8512                 :                : 
 2034                          8513                 :          17639 :             LockBuffer(buf, BUFFER_LOCK_SHARE);
                               8514                 :                : 
                               8515                 :          17639 :             page = BufferGetPage(buf);
                               8516                 :          17639 :             maxoff = PageGetMaxOffsetNumber(page);
                               8517                 :                :         }
                               8518                 :                : 
                               8519                 :                :         /*
                               8520                 :                :          * In passing, detect index corruption involving an index page with a
                               8521                 :                :          * TID that points to a location in the heap that couldn't possibly be
                               8522                 :                :          * correct.  We only do this with actual TIDs from caller's index page
                               8523                 :                :          * (not items reached by traversing through a HOT chain).
                               8524                 :                :          */
 1725                          8525                 :         713682 :         index_delete_check_htid(delstate, page, maxoff, htid, istatus);
                               8526                 :                : 
 2020                          8527         [ +  + ]:         713682 :         if (istatus->knowndeletable)
                               8528   [ +  -  -  + ]:         160868 :             Assert(!delstate->bottomup && !istatus->promising);
                               8529                 :                :         else
                               8530                 :                :         {
                               8531                 :         552814 :             ItemPointerData tmp = *htid;
                               8532                 :                :             HeapTupleData heapTuple;
                               8533                 :                : 
                               8534                 :                :             /* Are any tuples from this HOT chain non-vacuumable? */
                               8535         [ +  + ]:         552814 :             if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
                               8536                 :                :                                        &heapTuple, NULL, true))
                               8537                 :         344799 :                 continue;       /* can't delete entry */
                               8538                 :                : 
                               8539                 :                :             /* Caller will delete, since whole HOT chain is vacuumable */
                               8540                 :         208015 :             istatus->knowndeletable = true;
                               8541                 :                : 
                               8542                 :                :             /* Maintain index free space info for bottom-up deletion case */
                               8543         [ +  + ]:         208015 :             if (delstate->bottomup)
                               8544                 :                :             {
                               8545         [ -  + ]:           9425 :                 Assert(istatus->freespace > 0);
                               8546                 :           9425 :                 actualfreespace += istatus->freespace;
                               8547         [ +  + ]:           9425 :                 if (actualfreespace >= curtargetfreespace)
                               8548                 :           2787 :                     bottomup_final_block = true;
                               8549                 :                :             }
                               8550                 :                :         }
                               8551                 :                : 
                               8552                 :                :         /*
                               8553                 :                :          * Maintain snapshotConflictHorizon value for deletion operation as a
                               8554                 :                :          * whole by advancing current value using heap tuple headers.  This is
                               8555                 :                :          * loosely based on the logic for pruning a HOT chain.
                               8556                 :                :          */
 2034                          8557                 :         368883 :         offnum = ItemPointerGetOffsetNumber(htid);
                               8558                 :         368883 :         priorXmax = InvalidTransactionId;   /* cannot check first XMIN */
                               8559                 :                :         for (;;)
 2679 andres@anarazel.de       8560                 :          22467 :         {
                               8561                 :                :             ItemId      lp;
                               8562                 :                :             HeapTupleHeader htup;
                               8563                 :                : 
                               8564                 :                :             /* Sanity check (pure paranoia) */
 1768 pg@bowt.ie               8565         [ -  + ]:         391350 :             if (offnum < FirstOffsetNumber)
 1768 pg@bowt.ie               8566                 :UBC           0 :                 break;
                               8567                 :                : 
                               8568                 :                :             /*
                               8569                 :                :              * An offset past the end of page's line pointer array is possible
                               8570                 :                :              * when the array was truncated
                               8571                 :                :              */
 1768 pg@bowt.ie               8572         [ -  + ]:CBC      391350 :             if (offnum > maxoff)
 2034 pg@bowt.ie               8573                 :UBC           0 :                 break;
                               8574                 :                : 
 2034 pg@bowt.ie               8575                 :CBC      391350 :             lp = PageGetItemId(page, offnum);
                               8576         [ +  + ]:         391350 :             if (ItemIdIsRedirected(lp))
                               8577                 :                :             {
                               8578                 :          10067 :                 offnum = ItemIdGetRedirect(lp);
                               8579                 :          10067 :                 continue;
                               8580                 :                :             }
                               8581                 :                : 
                               8582                 :                :             /*
                               8583                 :                :              * We'll often encounter LP_DEAD line pointers (especially with an
                               8584                 :                :              * entry marked knowndeletable by our caller up front).  No heap
                               8585                 :                :              * tuple headers get examined for an htid that leads us to an
                               8586                 :                :              * LP_DEAD item.  This is okay because the earlier pruning
                               8587                 :                :              * operation that made the line pointer LP_DEAD in the first place
                               8588                 :                :              * must have considered the original tuple header as part of
                               8589                 :                :              * generating its own snapshotConflictHorizon value.
                               8590                 :                :              *
                               8591                 :                :              * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
                               8592                 :                :              * the same strategy that index vacuuming uses in all cases. Index
                               8593                 :                :              * VACUUM WAL records don't even have a snapshotConflictHorizon
                               8594                 :                :              * field of their own for this reason.
                               8595                 :                :              */
                               8596         [ +  + ]:         381283 :             if (!ItemIdIsNormal(lp))
                               8597                 :         241002 :                 break;
                               8598                 :                : 
                               8599                 :         140281 :             htup = (HeapTupleHeader) PageGetItem(page, lp);
                               8600                 :                : 
                               8601                 :                :             /*
                               8602                 :                :              * Check the tuple XMIN against prior XMAX, if any
                               8603                 :                :              */
                               8604   [ +  +  -  + ]:         152681 :             if (TransactionIdIsValid(priorXmax) &&
                               8605                 :          12400 :                 !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
 2034 pg@bowt.ie               8606                 :UBC           0 :                 break;
                               8607                 :                : 
 1347 pg@bowt.ie               8608                 :CBC      140281 :             HeapTupleHeaderAdvanceConflictHorizon(htup,
                               8609                 :                :                                                   &snapshotConflictHorizon);
                               8610                 :                : 
                               8611                 :                :             /*
                               8612                 :                :              * If the tuple is not HOT-updated, then we are at the end of this
                               8613                 :                :              * HOT-chain.  No need to visit later tuples from the same update
                               8614                 :                :              * chain (they get their own index entries) -- just move on to
                               8615                 :                :              * next htid from index AM caller.
                               8616                 :                :              */
 2034                          8617         [ +  + ]:         140281 :             if (!HeapTupleHeaderIsHotUpdated(htup))
                               8618                 :         127881 :                 break;
                               8619                 :                : 
                               8620                 :                :             /* Advance to next HOT chain member */
                               8621         [ -  + ]:          12400 :             Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
                               8622                 :          12400 :             offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
                               8623                 :          12400 :             priorXmax = HeapTupleHeaderGetUpdateXid(htup);
                               8624                 :                :         }
                               8625                 :                : 
                               8626                 :                :         /* Enable further/final shrinking of deltids for caller */
 2020                          8627                 :         368883 :         finalndeltids = i + 1;
                               8628                 :                :     }
                               8629                 :                : 
                               8630                 :           7682 :     UnlockReleaseBuffer(buf);
                               8631                 :                : 
                               8632                 :                :     /*
                               8633                 :                :      * Shrink deltids array to exclude non-deletable entries at the end.  This
                               8634                 :                :      * is not just a minor optimization.  Final deltids array size might be
                               8635                 :                :      * zero for a bottom-up caller.  Index AM is explicitly allowed to rely on
                               8636                 :                :      * ndeltids being zero in all cases with zero total deletable entries.
                               8637                 :                :      */
                               8638   [ +  +  -  + ]:           7682 :     Assert(finalndeltids > 0 || delstate->bottomup);
                               8639                 :           7682 :     delstate->ndeltids = finalndeltids;
                               8640                 :                : 
 1347                          8641                 :           7682 :     return snapshotConflictHorizon;
                               8642                 :                : }
                               8643                 :                : 
                               8644                 :                : /*
                               8645                 :                :  * Specialized inlineable comparison function for index_delete_sort()
                               8646                 :                :  */
                               8647                 :                : static inline int
 2020                          8648                 :       17143006 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
                               8649                 :                : {
                               8650                 :       17143006 :     ItemPointer tid1 = &deltid1->tid;
                               8651                 :       17143006 :     ItemPointer tid2 = &deltid2->tid;
                               8652                 :                : 
                               8653                 :                :     {
                               8654                 :       17143006 :         BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
                               8655                 :       17143006 :         BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
                               8656                 :                : 
                               8657         [ +  + ]:       17143006 :         if (blk1 != blk2)
                               8658         [ +  + ]:        6944415 :             return (blk1 < blk2) ? -1 : 1;
                               8659                 :                :     }
                               8660                 :                :     {
                               8661                 :       10198591 :         OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
                               8662                 :       10198591 :         OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
                               8663                 :                : 
                               8664         [ +  - ]:       10198591 :         if (pos1 != pos2)
                               8665         [ +  + ]:       10198591 :             return (pos1 < pos2) ? -1 : 1;
                               8666                 :                :     }
                               8667                 :                : 
 1731 pg@bowt.ie               8668                 :UBC           0 :     Assert(false);
                               8669                 :                : 
                               8670                 :                :     return 0;
                               8671                 :                : }
                               8672                 :                : 
                               8673                 :                : /*
                               8674                 :                :  * Sort deltids array from delstate by TID.  This prepares it for further
                               8675                 :                :  * processing by heap_index_delete_tuples().
                               8676                 :                :  *
                               8677                 :                :  * This operation becomes a noticeable consumer of CPU cycles with some
                               8678                 :                :  * workloads, so we go to the trouble of specialization/micro optimization.
                               8679                 :                :  * We use shellsort for this because it's easy to specialize, compiles to
                               8680                 :                :  * relatively few instructions, and is adaptive to presorted inputs/subsets
                               8681                 :                :  * (which are typical here).
                               8682                 :                :  */
                               8683                 :                : static void
 2020 pg@bowt.ie               8684                 :CBC        7682 : index_delete_sort(TM_IndexDeleteOp *delstate)
                               8685                 :                : {
                               8686                 :           7682 :     TM_IndexDelete *deltids = delstate->deltids;
                               8687                 :           7682 :     int         ndeltids = delstate->ndeltids;
                               8688                 :                : 
                               8689                 :                :     /*
                               8690                 :                :      * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
                               8691                 :                :      *
                               8692                 :                :      * This implementation is fast with array sizes up to ~4500.  This covers
                               8693                 :                :      * all supported BLCKSZ values.
                               8694                 :                :      */
                               8695                 :           7682 :     const int   gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
                               8696                 :                : 
                               8697                 :                :     /* Think carefully before changing anything here -- keep swaps cheap */
                               8698                 :                :     StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
                               8699                 :                :                      "element size exceeds 8 bytes");
                               8700                 :                : 
   15 peter@eisentraut.org     8701         [ +  + ]:GNC       76820 :     for (size_t g = 0; g < lengthof(gaps); g++)
                               8702                 :                :     {
  627 dgustafsson@postgres     8703         [ +  + ]:CBC    10357842 :         for (int hi = gaps[g], i = hi; i < ndeltids; i++)
                               8704                 :                :         {
 2020 pg@bowt.ie               8705                 :       10288704 :             TM_IndexDelete d = deltids[i];
                               8706                 :       10288704 :             int         j = i;
                               8707                 :                : 
                               8708   [ +  +  +  + ]:       17645002 :             while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
                               8709                 :                :             {
                               8710                 :        7356298 :                 deltids[j] = deltids[j - hi];
                               8711                 :        7356298 :                 j -= hi;
                               8712                 :                :             }
                               8713                 :       10288704 :             deltids[j] = d;
                               8714                 :                :         }
                               8715                 :                :     }
                               8716                 :           7682 : }
                               8717                 :                : 
                               8718                 :                : /*
                               8719                 :                :  * Returns how many blocks should be considered favorable/contiguous for a
                               8720                 :                :  * bottom-up index deletion pass.  This is a number of heap blocks that starts
                               8721                 :                :  * from and includes the first block in line.
                               8722                 :                :  *
                               8723                 :                :  * There is always at least one favorable block during bottom-up index
                               8724                 :                :  * deletion.  In the worst case (i.e. with totally random heap blocks) the
                               8725                 :                :  * first block in line (the only favorable block) can be thought of as a
                               8726                 :                :  * degenerate array of contiguous blocks that consists of a single block.
                               8727                 :                :  * heap_index_delete_tuples() will expect this.
                               8728                 :                :  *
                               8729                 :                :  * Caller passes blockgroups, a description of the final order that deltids
                               8730                 :                :  * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
                               8731                 :                :  * processing.  Note that deltids need not actually be sorted just yet (caller
                               8732                 :                :  * only passes deltids to us so that we can interpret blockgroups).
                               8733                 :                :  *
                               8734                 :                :  * You might guess that the existence of contiguous blocks cannot matter much,
                               8735                 :                :  * since in general the main factor that determines which blocks we visit is
                               8736                 :                :  * the number of promising TIDs, which is a fixed hint from the index AM.
                               8737                 :                :  * We're not really targeting the general case, though -- the actual goal is
                               8738                 :                :  * to adapt our behavior to a wide variety of naturally occurring conditions.
                               8739                 :                :  * The effects of most of the heuristics we apply are only noticeable in the
                               8740                 :                :  * aggregate, over time and across many _related_ bottom-up index deletion
                               8741                 :                :  * passes.
                               8742                 :                :  *
                               8743                 :                :  * Deeming certain blocks favorable allows heapam to recognize and adapt to
                               8744                 :                :  * workloads where heap blocks visited during bottom-up index deletion can be
                               8745                 :                :  * accessed contiguously, in the sense that each newly visited block is the
                               8746                 :                :  * neighbor of the block that bottom-up deletion just finished processing (or
                               8747                 :                :  * close enough to it).  It will likely be cheaper to access more favorable
                               8748                 :                :  * blocks sooner rather than later (e.g. in this pass, not across a series of
                               8749                 :                :  * related bottom-up passes).  Either way it is probably only a matter of time
                               8750                 :                :  * (or a matter of further correlated version churn) before all blocks that
                               8751                 :                :  * appear together as a single large batch of favorable blocks get accessed by
                               8752                 :                :  * _some_ bottom-up pass.  Large batches of favorable blocks tend to either
                               8753                 :                :  * appear almost constantly or not even once (it all depends on per-index
                               8754                 :                :  * workload characteristics).
                               8755                 :                :  *
                               8756                 :                :  * Note that the blockgroups sort order applies a power-of-two bucketing
                               8757                 :                :  * scheme that creates opportunities for contiguous groups of blocks to get
                               8758                 :                :  * batched together, at least with workloads that are naturally amenable to
                               8759                 :                :  * being driven by heap block locality.  This doesn't just enhance the spatial
                               8760                 :                :  * locality of bottom-up heap block processing in the obvious way.  It also
                               8761                 :                :  * enables temporal locality of access, since sorting by heap block number
                               8762                 :                :  * naturally tends to make the bottom-up processing order deterministic.
                               8763                 :                :  *
                               8764                 :                :  * Consider the following example to get a sense of how temporal locality
                               8765                 :                :  * might matter: There is a heap relation with several indexes, each of which
                               8766                 :                :  * is low to medium cardinality.  It is subject to constant non-HOT updates.
                               8767                 :                :  * The updates are skewed (in one part of the primary key, perhaps).  None of
                               8768                 :                :  * the indexes are logically modified by the UPDATE statements (if they were
                               8769                 :                :  * then bottom-up index deletion would not be triggered in the first place).
                               8770                 :                :  * Naturally, each new round of index tuples (for each heap tuple that gets a
                               8771                 :                :  * heap_update() call) will have the same heap TID in each and every index.
                               8772                 :                :  * Since these indexes are low cardinality and never get logically modified,
                               8773                 :                :  * heapam processing during bottom-up deletion passes will access heap blocks
                               8774                 :                :  * in approximately sequential order.  Temporal locality of access occurs due
                               8775                 :                :  * to bottom-up deletion passes behaving very similarly across each of the
                               8776                 :                :  * indexes at any given moment.  This keeps the number of buffer misses needed
                               8777                 :                :  * to visit heap blocks to a minimum.
                               8778                 :                :  */
                               8779                 :                : static int
                               8780                 :           2785 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
                               8781                 :                :                           TM_IndexDelete *deltids)
                               8782                 :                : {
                               8783                 :           2785 :     int64       lastblock = -1;
                               8784                 :           2785 :     int         nblocksfavorable = 0;
                               8785                 :                : 
                               8786         [ -  + ]:           2785 :     Assert(nblockgroups >= 1);
                               8787         [ -  + ]:           2785 :     Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
                               8788                 :                : 
                               8789                 :                :     /*
                               8790                 :                :      * We tolerate heap blocks that will be accessed only slightly out of
                               8791                 :                :      * physical order.  Small blips occur when a pair of almost-contiguous
                               8792                 :                :      * blocks happen to fall into different buckets (perhaps due only to a
                               8793                 :                :      * small difference in npromisingtids that the bucketing scheme didn't
                               8794                 :                :      * quite manage to ignore).  We effectively ignore these blips by applying
                               8795                 :                :      * a small tolerance.  The precise tolerance we use is a little arbitrary,
                               8796                 :                :      * but it works well enough in practice.
                               8797                 :                :      */
                               8798         [ +  + ]:           8555 :     for (int b = 0; b < nblockgroups; b++)
                               8799                 :                :     {
                               8800                 :           8199 :         IndexDeleteCounts *group = blockgroups + b;
                               8801                 :           8199 :         TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
                               8802                 :           8199 :         BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
                               8803                 :                : 
                               8804         [ +  + ]:           8199 :         if (lastblock != -1 &&
                               8805         [ +  + ]:           5414 :             ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
                               8806         [ +  + ]:           4767 :              (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
                               8807                 :                :             break;
                               8808                 :                : 
                               8809                 :           5770 :         nblocksfavorable++;
                               8810                 :           5770 :         lastblock = block;
                               8811                 :                :     }
                               8812                 :                : 
                               8813                 :                :     /* Always indicate that there is at least 1 favorable block */
                               8814         [ -  + ]:           2785 :     Assert(nblocksfavorable >= 1);
                               8815                 :                : 
                               8816                 :           2785 :     return nblocksfavorable;
                               8817                 :                : }
                               8818                 :                : 
                               8819                 :                : /*
                               8820                 :                :  * qsort comparison function for bottomup_sort_and_shrink()
                               8821                 :                :  */
                               8822                 :                : static int
                               8823                 :         262461 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
                               8824                 :                : {
                               8825                 :         262461 :     const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
                               8826                 :         262461 :     const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
                               8827                 :                : 
                               8828                 :                :     /*
                               8829                 :                :      * Most significant field is npromisingtids (which we invert the order of
                               8830                 :                :      * so as to sort in desc order).
                               8831                 :                :      *
                               8832                 :                :      * Caller should have already normalized npromisingtids fields into
                               8833                 :                :      * power-of-two values (buckets).
                               8834                 :                :      */
                               8835         [ +  + ]:         262461 :     if (group1->npromisingtids > group2->npromisingtids)
                               8836                 :          12618 :         return -1;
                               8837         [ +  + ]:         249843 :     if (group1->npromisingtids < group2->npromisingtids)
                               8838                 :          14721 :         return 1;
                               8839                 :                : 
                               8840                 :                :     /*
                               8841                 :                :      * Tiebreak: desc ntids sort order.
                               8842                 :                :      *
                               8843                 :                :      * We cannot expect power-of-two values for ntids fields.  We should
                               8844                 :                :      * behave as if they were already rounded up for us instead.
                               8845                 :                :      */
                               8846         [ +  + ]:         235122 :     if (group1->ntids != group2->ntids)
                               8847                 :                :     {
                               8848                 :         168790 :         uint32      ntids1 = pg_nextpower2_32((uint32) group1->ntids);
                               8849                 :         168790 :         uint32      ntids2 = pg_nextpower2_32((uint32) group2->ntids);
                               8850                 :                : 
                               8851         [ +  + ]:         168790 :         if (ntids1 > ntids2)
                               8852                 :          26065 :             return -1;
                               8853         [ +  + ]:         142725 :         if (ntids1 < ntids2)
                               8854                 :          31418 :             return 1;
                               8855                 :                :     }
                               8856                 :                : 
                               8857                 :                :     /*
                               8858                 :                :      * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
                               8859                 :                :      * block in deltids array) order.
                               8860                 :                :      *
                               8861                 :                :      * This is equivalent to sorting in ascending heap block number order
                               8862                 :                :      * (among otherwise equal subsets of the array).  This approach allows us
                               8863                 :                :      * to avoid accessing the out-of-line TID.  (We rely on the assumption
                               8864                 :                :      * that the deltids array was sorted in ascending heap TID order when
                               8865                 :                :      * these offsets to the first TID from each heap block group were formed.)
                               8866                 :                :      */
                               8867         [ +  + ]:         177639 :     if (group1->ifirsttid > group2->ifirsttid)
                               8868                 :          88383 :         return 1;
                               8869         [ +  - ]:          89256 :     if (group1->ifirsttid < group2->ifirsttid)
                               8870                 :          89256 :         return -1;
                               8871                 :                : 
 2020 pg@bowt.ie               8872                 :UBC           0 :     pg_unreachable();
                               8873                 :                : 
                               8874                 :                :     return 0;
                               8875                 :                : }
                               8876                 :                : 
                               8877                 :                : /*
                               8878                 :                :  * heap_index_delete_tuples() helper function for bottom-up deletion callers.
                               8879                 :                :  *
                               8880                 :                :  * Sorts deltids array in the order needed for useful processing by bottom-up
                               8881                 :                :  * deletion.  The array should already be sorted in TID order when we're
                               8882                 :                :  * called.  The sort process groups heap TIDs from deltids into heap block
                               8883                 :                :  * groupings.  Earlier/more-promising groups/blocks are usually those that are
                               8884                 :                :  * known to have the most "promising" TIDs.
                               8885                 :                :  *
                               8886                 :                :  * Sets new size of deltids array (ndeltids) in state.  deltids will only have
                               8887                 :                :  * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
                               8888                 :                :  * return.  This often means that deltids will be shrunk to a small fraction
                               8889                 :                :  * of its original size (we eliminate many heap blocks from consideration for
                               8890                 :                :  * caller up front).
                               8891                 :                :  *
                               8892                 :                :  * Returns the number of "favorable" blocks.  See bottomup_nblocksfavorable()
                               8893                 :                :  * for a definition and full details.
                               8894                 :                :  */
                               8895                 :                : static int
 2020 pg@bowt.ie               8896                 :CBC        2785 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
                               8897                 :                : {
                               8898                 :                :     IndexDeleteCounts *blockgroups;
                               8899                 :                :     TM_IndexDelete *reordereddeltids;
                               8900                 :           2785 :     BlockNumber curblock = InvalidBlockNumber;
                               8901                 :           2785 :     int         nblockgroups = 0;
                               8902                 :           2785 :     int         ncopied = 0;
                               8903                 :           2785 :     int         nblocksfavorable = 0;
                               8904                 :                : 
                               8905         [ -  + ]:           2785 :     Assert(delstate->bottomup);
                               8906         [ -  + ]:           2785 :     Assert(delstate->ndeltids > 0);
                               8907                 :                : 
                               8908                 :                :     /* Calculate per-heap-block count of TIDs */
  228 michael@paquier.xyz      8909                 :           2785 :     blockgroups = palloc_array(IndexDeleteCounts, delstate->ndeltids);
 2020 pg@bowt.ie               8910         [ +  + ]:        1324716 :     for (int i = 0; i < delstate->ndeltids; i++)
                               8911                 :                :     {
                               8912                 :        1321931 :         TM_IndexDelete *ideltid = &delstate->deltids[i];
                               8913                 :        1321931 :         TM_IndexStatus *istatus = delstate->status + ideltid->id;
                               8914                 :        1321931 :         ItemPointer htid = &ideltid->tid;
                               8915                 :        1321931 :         bool        promising = istatus->promising;
                               8916                 :                : 
                               8917         [ +  + ]:        1321931 :         if (curblock != ItemPointerGetBlockNumber(htid))
                               8918                 :                :         {
                               8919                 :                :             /* New block group */
                               8920                 :          51195 :             nblockgroups++;
                               8921                 :                : 
                               8922   [ +  +  -  + ]:          51195 :             Assert(curblock < ItemPointerGetBlockNumber(htid) ||
                               8923                 :                :                    !BlockNumberIsValid(curblock));
                               8924                 :                : 
                               8925                 :          51195 :             curblock = ItemPointerGetBlockNumber(htid);
                               8926                 :          51195 :             blockgroups[nblockgroups - 1].ifirsttid = i;
                               8927                 :          51195 :             blockgroups[nblockgroups - 1].ntids = 1;
                               8928                 :          51195 :             blockgroups[nblockgroups - 1].npromisingtids = 0;
                               8929                 :                :         }
                               8930                 :                :         else
                               8931                 :                :         {
                               8932                 :        1270736 :             blockgroups[nblockgroups - 1].ntids++;
                               8933                 :                :         }
                               8934                 :                : 
                               8935         [ +  + ]:        1321931 :         if (promising)
                               8936                 :         213659 :             blockgroups[nblockgroups - 1].npromisingtids++;
                               8937                 :                :     }
                               8938                 :                : 
                               8939                 :                :     /*
                               8940                 :                :      * We're about ready to sort block groups to determine the optimal order
                               8941                 :                :      * for visiting heap blocks.  But before we do, round the number of
                               8942                 :                :      * promising tuples for each block group up to the next power-of-two,
                               8943                 :                :      * unless it is very low (less than 4), in which case we round up to 4.
                               8944                 :                :      * npromisingtids is far too noisy to trust when choosing between a pair
                               8945                 :                :      * of block groups that both have very low values.
                               8946                 :                :      *
                               8947                 :                :      * This scheme divides heap blocks/block groups into buckets.  Each bucket
                               8948                 :                :      * contains blocks that have _approximately_ the same number of promising
                               8949                 :                :      * TIDs as each other.  The goal is to ignore relatively small differences
                               8950                 :                :      * in the total number of promising entries, so that the whole process can
                               8951                 :                :      * give a little weight to heapam factors (like heap block locality)
                               8952                 :                :      * instead.  This isn't a trade-off, really -- we have nothing to lose. It
                               8953                 :                :      * would be foolish to interpret small differences in npromisingtids
                               8954                 :                :      * values as anything more than noise.
                               8955                 :                :      *
                               8956                 :                :      * We tiebreak on nhtids when sorting block group subsets that have the
                               8957                 :                :      * same npromisingtids, but this has the same issues as npromisingtids,
                               8958                 :                :      * and so nhtids is subject to the same power-of-two bucketing scheme. The
                               8959                 :                :      * only reason that we don't fix nhtids in the same way here too is that
                               8960                 :                :      * we'll need accurate nhtids values after the sort.  We handle nhtids
                               8961                 :                :      * bucketization dynamically instead (in the sort comparator).
                               8962                 :                :      *
                               8963                 :                :      * See bottomup_nblocksfavorable() for a full explanation of when and how
                               8964                 :                :      * heap locality/favorable blocks can significantly influence when and how
                               8965                 :                :      * heap blocks are accessed.
                               8966                 :                :      */
                               8967         [ +  + ]:          53980 :     for (int b = 0; b < nblockgroups; b++)
                               8968                 :                :     {
                               8969                 :          51195 :         IndexDeleteCounts *group = blockgroups + b;
                               8970                 :                : 
                               8971                 :                :         /* Better off falling back on nhtids with low npromisingtids */
                               8972         [ +  + ]:          51195 :         if (group->npromisingtids <= 4)
                               8973                 :          43301 :             group->npromisingtids = 4;
                               8974                 :                :         else
                               8975                 :           7894 :             group->npromisingtids =
                               8976                 :           7894 :                 pg_nextpower2_32((uint32) group->npromisingtids);
                               8977                 :                :     }
                               8978                 :                : 
                               8979                 :                :     /* Sort groups and rearrange caller's deltids array */
                               8980                 :           2785 :     qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
                               8981                 :                :           bottomup_sort_and_shrink_cmp);
                               8982                 :           2785 :     reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
                               8983                 :                : 
                               8984                 :           2785 :     nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
                               8985                 :                :     /* Determine number of favorable blocks at the start of final deltids */
                               8986                 :           2785 :     nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
                               8987                 :                :                                                  delstate->deltids);
                               8988                 :                : 
                               8989         [ +  + ]:          18005 :     for (int b = 0; b < nblockgroups; b++)
                               8990                 :                :     {
                               8991                 :          15220 :         IndexDeleteCounts *group = blockgroups + b;
                               8992                 :          15220 :         TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
                               8993                 :                : 
                               8994                 :          15220 :         memcpy(reordereddeltids + ncopied, firstdtid,
                               8995                 :          15220 :                sizeof(TM_IndexDelete) * group->ntids);
                               8996                 :          15220 :         ncopied += group->ntids;
                               8997                 :                :     }
                               8998                 :                : 
                               8999                 :                :     /* Copy final grouped and sorted TIDs back into start of caller's array */
                               9000                 :           2785 :     memcpy(delstate->deltids, reordereddeltids,
                               9001                 :                :            sizeof(TM_IndexDelete) * ncopied);
                               9002                 :           2785 :     delstate->ndeltids = ncopied;
                               9003                 :                : 
                               9004                 :           2785 :     pfree(reordereddeltids);
                               9005                 :           2785 :     pfree(blockgroups);
                               9006                 :                : 
                               9007                 :           2785 :     return nblocksfavorable;
                               9008                 :                : }
                               9009                 :                : 
                               9010                 :                : /*
                               9011                 :                :  * Perform XLogInsert for a heap-update operation.  Caller must already
                               9012                 :                :  * have modified the buffer(s) and marked them dirty.
                               9013                 :                :  */
                               9014                 :                : static XLogRecPtr
   11 melanieplageman@gmai     9015                 :        2377216 : log_heap_update(Relation reln, Buffer oldbuf, Buffer vmbuffer_old,
                               9016                 :                :                 Buffer newbuf, Buffer vmbuffer_new,
                               9017                 :                :                 HeapTuple oldtup, HeapTuple newtup,
                               9018                 :                :                 HeapTuple old_key_tuple,
                               9019                 :                :                 bool all_visible_cleared, bool new_all_visible_cleared,
                               9020                 :                :                 bool walLogical)
                               9021                 :                : {
                               9022                 :                :     xl_heap_update xlrec;
                               9023                 :                :     xl_heap_header xlhdr;
                               9024                 :                :     xl_heap_header xlhdr_idx;
                               9025                 :                :     uint8       info;
                               9026                 :                :     uint16      prefix_suffix[2];
 4519 heikki.linnakangas@i     9027                 :        2377216 :     uint16      prefixlen = 0,
                               9028                 :        2377216 :                 suffixlen = 0;
                               9029                 :                :     XLogRecPtr  recptr;
 3749 kgrittn@postgresql.o     9030                 :        2377216 :     Page        page = BufferGetPage(newbuf);
  111 alvherre@kurilemu.de     9031   [ +  +  +  +  :        2377216 :     bool        need_tuple_data = walLogical && RelationIsLogicallyLogged(reln);
                                     +  +  +  -  -  
                                     +  -  -  -  -  
                                        +  -  +  + ]
                               9032                 :                :     bool        init;
                               9033                 :                :     int         bufflags;
                               9034                 :                : 
                               9035                 :                :     /* Caller should not call me on a non-WAL-logged relation */
 5704 rhaas@postgresql.org     9036   [ +  -  +  +  :        2377216 :     Assert(RelationNeedsWAL(reln));
                                        +  -  -  + ]
                               9037                 :                : 
 4266 heikki.linnakangas@i     9038                 :        2377216 :     XLogBeginInsert();
                               9039                 :                : 
 6012 tgl@sss.pgh.pa.us        9040         [ +  + ]:        2377216 :     if (HeapTupleIsHeapOnly(newtup))
 6884                          9041                 :         169949 :         info = XLOG_HEAP_HOT_UPDATE;
                               9042                 :                :     else
                               9043                 :        2207267 :         info = XLOG_HEAP_UPDATE;
                               9044                 :                : 
                               9045                 :                :     /*
                               9046                 :                :      * If the old and new tuple are on the same page, we only need to log the
                               9047                 :                :      * parts of the new tuple that were changed.  That saves on the amount of
                               9048                 :                :      * WAL we need to write.  Currently, we just count any unchanged bytes in
                               9049                 :                :      * the beginning and end of the tuple.  That's quick to check, and
                               9050                 :                :      * perfectly covers the common case that only one field is updated.
                               9051                 :                :      *
                               9052                 :                :      * We could do this even if the old and new tuple are on different pages,
                               9053                 :                :      * but only if we don't make a full-page image of the old page, which is
                               9054                 :                :      * difficult to know in advance.  Also, if the old tuple is corrupt for
                               9055                 :                :      * some reason, it would allow the corruption to propagate the new page,
                               9056                 :                :      * so it seems best to avoid.  Under the general assumption that most
                               9057                 :                :      * updates tend to create the new tuple version on the same page, there
                               9058                 :                :      * isn't much to be gained by doing this across pages anyway.
                               9059                 :                :      *
                               9060                 :                :      * Skip this if we're taking a full-page image of the new page, as we
                               9061                 :                :      * don't include the new tuple in the WAL record in that case.  Also
                               9062                 :                :      * disable if effective_wal_level='logical', as logical decoding needs to
                               9063                 :                :      * be able to read the new tuple in whole from the WAL record alone.
                               9064                 :                :      */
 4519 heikki.linnakangas@i     9065   [ +  +  +  + ]:        2377216 :     if (oldbuf == newbuf && !need_tuple_data &&
                               9066         [ +  + ]:         174647 :         !XLogCheckBufferNeedsBackup(newbuf))
                               9067                 :                :     {
                               9068                 :         174086 :         char       *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
                               9069                 :         174086 :         char       *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
                               9070                 :         174086 :         int         oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
                               9071                 :         174086 :         int         newlen = newtup->t_len - newtup->t_data->t_hoff;
                               9072                 :                : 
                               9073                 :                :         /* Check for common prefix between old and new tuple */
                               9074         [ +  + ]:       14659365 :         for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
                               9075                 :                :         {
                               9076         [ +  + ]:       14630927 :             if (newp[prefixlen] != oldp[prefixlen])
                               9077                 :         145648 :                 break;
                               9078                 :                :         }
                               9079                 :                : 
                               9080                 :                :         /*
                               9081                 :                :          * Storing the length of the prefix takes 2 bytes, so we need to save
                               9082                 :                :          * at least 3 bytes or there's no point.
                               9083                 :                :          */
                               9084         [ +  + ]:         174086 :         if (prefixlen < 3)
                               9085                 :          22842 :             prefixlen = 0;
                               9086                 :                : 
                               9087                 :                :         /* Same for suffix */
                               9088         [ +  + ]:        6346234 :         for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
                               9089                 :                :         {
                               9090         [ +  + ]:        6317447 :             if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
                               9091                 :         145299 :                 break;
                               9092                 :                :         }
                               9093         [ +  + ]:         174086 :         if (suffixlen < 3)
                               9094                 :          43179 :             suffixlen = 0;
                               9095                 :                :     }
                               9096                 :                : 
                               9097                 :                :     /* Prepare main WAL data chain */
 4611 rhaas@postgresql.org     9098                 :        2377216 :     xlrec.flags = 0;
                               9099         [ +  + ]:        2377216 :     if (all_visible_cleared)
 4097 andres@anarazel.de       9100                 :           2933 :         xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
 4611 rhaas@postgresql.org     9101         [ +  + ]:        2377216 :     if (new_all_visible_cleared)
 4097 andres@anarazel.de       9102                 :           1746 :         xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
 4519 heikki.linnakangas@i     9103         [ +  + ]:        2377216 :     if (prefixlen > 0)
 4097 andres@anarazel.de       9104                 :         151244 :         xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
 4519 heikki.linnakangas@i     9105         [ +  + ]:        2377216 :     if (suffixlen > 0)
 4097 andres@anarazel.de       9106                 :         130907 :         xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
 4266 heikki.linnakangas@i     9107         [ +  + ]:        2377216 :     if (need_tuple_data)
                               9108                 :                :     {
 4097 andres@anarazel.de       9109                 :          47051 :         xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
 4266 heikki.linnakangas@i     9110         [ +  + ]:          47051 :         if (old_key_tuple)
                               9111                 :                :         {
                               9112         [ +  + ]:            161 :             if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
 4097 andres@anarazel.de       9113                 :             68 :                 xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
                               9114                 :                :             else
                               9115                 :             93 :                 xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
                               9116                 :                :         }
                               9117                 :                :     }
                               9118                 :                : 
                               9119                 :                :     /* If new tuple is the single and first tuple on page... */
 4519 heikki.linnakangas@i     9120   [ +  +  +  + ]:        2390550 :     if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
                               9121                 :          13334 :         PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
                               9122                 :                :     {
                               9123                 :          12776 :         info |= XLOG_HEAP_INIT_PAGE;
 4266                          9124                 :          12776 :         init = true;
                               9125                 :                :     }
                               9126                 :                :     else
                               9127                 :        2364440 :         init = false;
                               9128                 :                : 
                               9129                 :                :     /* Prepare WAL data for the old page */
                               9130                 :        2377216 :     xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
                               9131                 :        2377216 :     xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
                               9132                 :        4754432 :     xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
                               9133                 :        2377216 :                                               oldtup->t_data->t_infomask2);
                               9134                 :                : 
                               9135                 :                :     /* Prepare WAL data for the new page */
                               9136                 :        2377216 :     xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
                               9137                 :        2377216 :     xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
                               9138                 :                : 
                               9139                 :        2377216 :     bufflags = REGBUF_STANDARD;
                               9140         [ +  + ]:        2377216 :     if (init)
                               9141                 :          12776 :         bufflags |= REGBUF_WILL_INIT;
                               9142         [ +  + ]:        2377216 :     if (need_tuple_data)
                               9143                 :          47051 :         bufflags |= REGBUF_KEEP_DATA;
                               9144                 :                : 
   11 melanieplageman@gmai     9145                 :        2377216 :     XLogRegisterBuffer(HEAP_UPDATE_BLKREF_HEAP_NEW, newbuf, bufflags);
 4266 heikki.linnakangas@i     9146         [ +  + ]:        2377216 :     if (oldbuf != newbuf)
   11 melanieplageman@gmai     9147                 :        2190598 :         XLogRegisterBuffer(HEAP_UPDATE_BLKREF_HEAP_OLD, oldbuf, REGBUF_STANDARD);
                               9148                 :                : 
  530 peter@eisentraut.org     9149                 :        2377216 :     XLogRegisterData(&xlrec, SizeOfHeapUpdate);
                               9150                 :                : 
                               9151                 :                :     /*
                               9152                 :                :      * Prepare WAL data for the new tuple.
                               9153                 :                :      */
 4519 heikki.linnakangas@i     9154   [ +  +  +  + ]:        2377216 :     if (prefixlen > 0 || suffixlen > 0)
                               9155                 :                :     {
                               9156   [ +  +  +  + ]:         173510 :         if (prefixlen > 0 && suffixlen > 0)
                               9157                 :                :         {
                               9158                 :         108641 :             prefix_suffix[0] = prefixlen;
                               9159                 :         108641 :             prefix_suffix[1] = suffixlen;
   11 melanieplageman@gmai     9160                 :         108641 :             XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &prefix_suffix,
                               9161                 :                :                                 sizeof(uint16) * 2);
                               9162                 :                :         }
 4519 heikki.linnakangas@i     9163         [ +  + ]:          64869 :         else if (prefixlen > 0)
                               9164                 :                :         {
   11 melanieplageman@gmai     9165                 :          42603 :             XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &prefixlen,
                               9166                 :                :                                 sizeof(uint16));
                               9167                 :                :         }
                               9168                 :                :         else
                               9169                 :                :         {
                               9170                 :          22266 :             XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &suffixlen,
                               9171                 :                :                                 sizeof(uint16));
                               9172                 :                :         }
                               9173                 :                :     }
                               9174                 :                : 
 4266 heikki.linnakangas@i     9175                 :        2377216 :     xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
                               9176                 :        2377216 :     xlhdr.t_infomask = newtup->t_data->t_infomask;
                               9177                 :        2377216 :     xlhdr.t_hoff = newtup->t_data->t_hoff;
 4173 tgl@sss.pgh.pa.us        9178         [ -  + ]:        2377216 :     Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
                               9179                 :                : 
                               9180                 :                :     /*
                               9181                 :                :      * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
                               9182                 :                :      *
                               9183                 :                :      * The 'data' doesn't include the common prefix or suffix.
                               9184                 :                :      */
   11 melanieplageman@gmai     9185                 :        2377216 :     XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW, &xlhdr, SizeOfHeapHeader);
 4519 heikki.linnakangas@i     9186         [ +  + ]:        2377216 :     if (prefixlen == 0)
                               9187                 :                :     {
   11 melanieplageman@gmai     9188                 :        2225972 :         XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
  530 peter@eisentraut.org     9189                 :        2225972 :                             (char *) newtup->t_data + SizeofHeapTupleHeader,
 3322 tgl@sss.pgh.pa.us        9190                 :        2225972 :                             newtup->t_len - SizeofHeapTupleHeader - suffixlen);
                               9191                 :                :     }
                               9192                 :                :     else
                               9193                 :                :     {
                               9194                 :                :         /*
                               9195                 :                :          * Have to write the null bitmap and data after the common prefix as
                               9196                 :                :          * two separate rdata entries.
                               9197                 :                :          */
                               9198                 :                :         /* bitmap [+ padding] [+ oid] */
 4173                          9199         [ +  - ]:         151244 :         if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
                               9200                 :                :         {
   11 melanieplageman@gmai     9201                 :         151244 :             XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
  530 peter@eisentraut.org     9202                 :         151244 :                                 (char *) newtup->t_data + SizeofHeapTupleHeader,
 3322 tgl@sss.pgh.pa.us        9203                 :         151244 :                                 newtup->t_data->t_hoff - SizeofHeapTupleHeader);
                               9204                 :                :         }
                               9205                 :                : 
                               9206                 :                :         /* data after common prefix */
   11 melanieplageman@gmai     9207                 :         151244 :         XLogRegisterBufData(HEAP_UPDATE_BLKREF_HEAP_NEW,
  530 peter@eisentraut.org     9208                 :         151244 :                             (char *) newtup->t_data + newtup->t_data->t_hoff + prefixlen,
 3322 tgl@sss.pgh.pa.us        9209                 :         151244 :                             newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
                               9210                 :                :     }
                               9211                 :                : 
                               9212                 :                :     /* We need to log a tuple identity */
 4266 heikki.linnakangas@i     9213   [ +  +  +  + ]:        2377216 :     if (need_tuple_data && old_key_tuple)
                               9214                 :                :     {
                               9215                 :                :         /* don't really need this, but its more comfy to decode */
                               9216                 :            161 :         xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
                               9217                 :            161 :         xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
                               9218                 :            161 :         xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
                               9219                 :                : 
  530 peter@eisentraut.org     9220                 :            161 :         XLogRegisterData(&xlhdr_idx, SizeOfHeapHeader);
                               9221                 :                : 
                               9222                 :                :         /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
 4173 tgl@sss.pgh.pa.us        9223                 :            161 :         XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
                               9224                 :            161 :                          old_key_tuple->t_len - SizeofHeapTupleHeader);
                               9225                 :                :     }
                               9226                 :                : 
                               9227                 :                :     /*
                               9228                 :                :      * Register VM buffers. If the old and new heap pages' VM bits are on the
                               9229                 :                :      * same VM page and both their VM bits were cleared, the caller passes
                               9230                 :                :      * only vmbuffer_new (mirroring the heap page convention where block 0 =
                               9231                 :                :      * new is always registered).
                               9232                 :                :      */
   11 melanieplageman@gmai     9233   [ +  +  +  +  :        2377216 :     Assert((BufferIsInvalid(vmbuffer_old) && BufferIsInvalid(vmbuffer_new)) ||
                                              -  + ]
                               9234                 :                :            (vmbuffer_old != vmbuffer_new));
                               9235                 :                : 
                               9236         [ +  + ]:        2377216 :     if (BufferIsValid(vmbuffer_new))
                               9237                 :           1746 :         XLogRegisterBuffer(HEAP_UPDATE_BLKREF_VM_NEW, vmbuffer_new, 0);
                               9238                 :                : 
                               9239         [ +  + ]:        2377216 :     if (BufferIsValid(vmbuffer_old))
                               9240                 :           2765 :         XLogRegisterBuffer(HEAP_UPDATE_BLKREF_VM_OLD, vmbuffer_old, 0);
                               9241                 :                : 
                               9242                 :                :     /* filtering by origin on a row level is much more efficient */
 3503 andres@anarazel.de       9243                 :        2377216 :     XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               9244                 :                : 
 4266 heikki.linnakangas@i     9245                 :        2377216 :     recptr = XLogInsert(RM_HEAP_ID, info);
                               9246                 :                : 
 7501 neilc@samurai.com        9247                 :        2377216 :     return recptr;
                               9248                 :                : }
                               9249                 :                : 
                               9250                 :                : /*
                               9251                 :                :  * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
                               9252                 :                :  *
                               9253                 :                :  * This is only used when effective_wal_level is logical, and only for
                               9254                 :                :  * catalog tuples.
                               9255                 :                :  */
                               9256                 :                : static XLogRecPtr
 4611 rhaas@postgresql.org     9257                 :          26596 : log_heap_new_cid(Relation relation, HeapTuple tup)
                               9258                 :                : {
                               9259                 :                :     xl_heap_new_cid xlrec;
                               9260                 :                : 
                               9261                 :                :     XLogRecPtr  recptr;
                               9262                 :          26596 :     HeapTupleHeader hdr = tup->t_data;
                               9263                 :                : 
                               9264         [ -  + ]:          26596 :     Assert(ItemPointerIsValid(&tup->t_self));
                               9265         [ -  + ]:          26596 :     Assert(tup->t_tableOid != InvalidOid);
                               9266                 :                : 
                               9267                 :          26596 :     xlrec.top_xid = GetTopTransactionId();
 1481                          9268                 :          26596 :     xlrec.target_locator = relation->rd_locator;
 4266 heikki.linnakangas@i     9269                 :          26596 :     xlrec.target_tid = tup->t_self;
                               9270                 :                : 
                               9271                 :                :     /*
                               9272                 :                :      * If the tuple got inserted & deleted in the same TX we definitely have a
                               9273                 :                :      * combo CID, set cmin and cmax.
                               9274                 :                :      */
 4611 rhaas@postgresql.org     9275         [ +  + ]:          26596 :     if (hdr->t_infomask & HEAP_COMBOCID)
                               9276                 :                :     {
                               9277         [ -  + ]:           2237 :         Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
 4599                          9278         [ -  + ]:           2237 :         Assert(!HeapTupleHeaderXminInvalid(hdr));
 4611                          9279                 :           2237 :         xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
                               9280                 :           2237 :         xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
                               9281                 :           2237 :         xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
                               9282                 :                :     }
                               9283                 :                :     /* No combo CID, so only cmin or cmax can be set by this TX */
                               9284                 :                :     else
                               9285                 :                :     {
                               9286                 :                :         /*
                               9287                 :                :          * Tuple inserted.
                               9288                 :                :          *
                               9289                 :                :          * We need to check for LOCK ONLY because multixacts might be
                               9290                 :                :          * transferred to the new tuple in case of FOR KEY SHARE updates in
                               9291                 :                :          * which case there will be an xmax, although the tuple just got
                               9292                 :                :          * inserted.
                               9293                 :                :          */
                               9294   [ +  +  +  + ]:          31814 :         if (hdr->t_infomask & HEAP_XMAX_INVALID ||
                               9295                 :           7455 :             HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
                               9296                 :                :         {
                               9297                 :          16905 :             xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
                               9298                 :          16905 :             xlrec.cmax = InvalidCommandId;
                               9299                 :                :         }
                               9300                 :                :         /* Tuple from a different tx updated or deleted. */
                               9301                 :                :         else
                               9302                 :                :         {
                               9303                 :           7454 :             xlrec.cmin = InvalidCommandId;
                               9304                 :           7454 :             xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
                               9305                 :                :         }
                               9306                 :          24359 :         xlrec.combocid = InvalidCommandId;
                               9307                 :                :     }
                               9308                 :                : 
                               9309                 :                :     /*
                               9310                 :                :      * Note that we don't need to register the buffer here, because this
                               9311                 :                :      * operation does not modify the page. The insert/update/delete that
                               9312                 :                :      * called us certainly did, but that's WAL-logged separately.
                               9313                 :                :      */
 4266 heikki.linnakangas@i     9314                 :          26596 :     XLogBeginInsert();
  530 peter@eisentraut.org     9315                 :          26596 :     XLogRegisterData(&xlrec, SizeOfHeapNewCid);
                               9316                 :                : 
                               9317                 :                :     /* will be looked at irrespective of origin */
                               9318                 :                : 
 4266 heikki.linnakangas@i     9319                 :          26596 :     recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
                               9320                 :                : 
 4611 rhaas@postgresql.org     9321                 :          26596 :     return recptr;
                               9322                 :                : }
                               9323                 :                : 
                               9324                 :                : /*
                               9325                 :                :  * Build a heap tuple representing the configured REPLICA IDENTITY to represent
                               9326                 :                :  * the old tuple in an UPDATE or DELETE.
                               9327                 :                :  *
                               9328                 :                :  * Returns NULL if there's no need to log an identity or if there's no suitable
                               9329                 :                :  * key defined.
                               9330                 :                :  *
                               9331                 :                :  * Pass key_required true if any replica identity columns changed value, or if
                               9332                 :                :  * any of them have any external data.  Delete must always pass true.
                               9333                 :                :  *
                               9334                 :                :  * *copy is set to true if the returned tuple is a modified copy rather than
                               9335                 :                :  * the same tuple that was passed in.
                               9336                 :                :  */
                               9337                 :                : static HeapTuple
 1623 akapila@postgresql.o     9338                 :        4254865 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
                               9339                 :                :                        bool *copy)
                               9340                 :                : {
 4611 rhaas@postgresql.org     9341                 :        4254865 :     TupleDesc   desc = RelationGetDescr(relation);
                               9342                 :        4254865 :     char        replident = relation->rd_rel->relreplident;
                               9343                 :                :     Bitmapset  *idattrs;
                               9344                 :                :     HeapTuple   key_tuple;
                               9345                 :                :     bool        nulls[MaxHeapAttributeNumber];
                               9346                 :                :     Datum       values[MaxHeapAttributeNumber];
                               9347                 :                : 
                               9348                 :        4254865 :     *copy = false;
                               9349                 :                : 
                               9350   [ +  +  +  +  :        4254865 :     if (!RelationIsLogicallyLogged(relation))
                                     +  +  -  +  -  
                                     -  -  -  +  -  
                                              +  + ]
                               9351                 :        4154471 :         return NULL;
                               9352                 :                : 
                               9353         [ +  + ]:         100394 :     if (replident == REPLICA_IDENTITY_NOTHING)
                               9354                 :            272 :         return NULL;
                               9355                 :                : 
                               9356         [ +  + ]:         100122 :     if (replident == REPLICA_IDENTITY_FULL)
                               9357                 :                :     {
                               9358                 :                :         /*
                               9359                 :                :          * When logging the entire old tuple, it very well could contain
                               9360                 :                :          * toasted columns. If so, force them to be inlined.
                               9361                 :                :          */
                               9362         [ +  + ]:            203 :         if (HeapTupleHasExternal(tp))
                               9363                 :                :         {
                               9364                 :              4 :             *copy = true;
 2519 tgl@sss.pgh.pa.us        9365                 :              4 :             tp = toast_flatten_tuple(tp, desc);
                               9366                 :                :         }
 4611 rhaas@postgresql.org     9367                 :            203 :         return tp;
                               9368                 :                :     }
                               9369                 :                : 
                               9370                 :                :     /* if the key isn't required and we're only logging the key, we're done */
 1623 akapila@postgresql.o     9371         [ +  + ]:          99919 :     if (!key_required)
 4611 rhaas@postgresql.org     9372                 :          46912 :         return NULL;
                               9373                 :                : 
                               9374                 :                :     /* find out the replica identity columns */
 2519 tgl@sss.pgh.pa.us        9375                 :          53007 :     idattrs = RelationGetIndexAttrBitmap(relation,
                               9376                 :                :                                          INDEX_ATTR_BITMAP_IDENTITY_KEY);
                               9377                 :                : 
                               9378                 :                :     /*
                               9379                 :                :      * If there's no defined replica identity columns, treat as !key_required.
                               9380                 :                :      * (This case should not be reachable from heap_update, since that should
                               9381                 :                :      * calculate key_required accurately.  But heap_delete just passes
                               9382                 :                :      * constant true for key_required, so we can hit this case in deletes.)
                               9383                 :                :      */
                               9384         [ +  + ]:          53007 :     if (bms_is_empty(idattrs))
                               9385                 :           6021 :         return NULL;
                               9386                 :                : 
                               9387                 :                :     /*
                               9388                 :                :      * Construct a new tuple containing only the replica identity columns,
                               9389                 :                :      * with nulls elsewhere.  While we're at it, assert that the replica
                               9390                 :                :      * identity columns aren't null.
                               9391                 :                :      */
                               9392                 :          46986 :     heap_deform_tuple(tp, desc, values, nulls);
                               9393                 :                : 
                               9394         [ +  + ]:         150979 :     for (int i = 0; i < desc->natts; i++)
                               9395                 :                :     {
                               9396         [ +  + ]:         103993 :         if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
                               9397                 :                :                           idattrs))
                               9398         [ -  + ]:          47006 :             Assert(!nulls[i]);
                               9399                 :                :         else
                               9400                 :          56987 :             nulls[i] = true;
                               9401                 :                :     }
                               9402                 :                : 
 4611 rhaas@postgresql.org     9403                 :          46986 :     key_tuple = heap_form_tuple(desc, values, nulls);
                               9404                 :          46986 :     *copy = true;
                               9405                 :                : 
 2519 tgl@sss.pgh.pa.us        9406                 :          46986 :     bms_free(idattrs);
                               9407                 :                : 
                               9408                 :                :     /*
                               9409                 :                :      * If the tuple, which by here only contains indexed columns, still has
                               9410                 :                :      * toasted columns, force them to be inlined. This is somewhat unlikely
                               9411                 :                :      * since there's limits on the size of indexed columns, so we don't
                               9412                 :                :      * duplicate toast_flatten_tuple()s functionality in the above loop over
                               9413                 :                :      * the indexed columns, even if it would be more efficient.
                               9414                 :                :      */
 4611 rhaas@postgresql.org     9415         [ +  + ]:          46986 :     if (HeapTupleHasExternal(key_tuple))
                               9416                 :                :     {
 4464 bruce@momjian.us         9417                 :              4 :         HeapTuple   oldtup = key_tuple;
                               9418                 :                : 
 2519 tgl@sss.pgh.pa.us        9419                 :              4 :         key_tuple = toast_flatten_tuple(oldtup, desc);
 4611 rhaas@postgresql.org     9420                 :              4 :         heap_freetuple(oldtup);
                               9421                 :                :     }
                               9422                 :                : 
                               9423                 :          46986 :     return key_tuple;
                               9424                 :                : }
                               9425                 :                : 
                               9426                 :                : /*
                               9427                 :                :  * HeapCheckForSerializableConflictOut
                               9428                 :                :  *      We are reading a tuple.  If it's not visible, there may be a
                               9429                 :                :  *      rw-conflict out with the inserter.  Otherwise, if it is visible to us
                               9430                 :                :  *      but has been deleted, there may be a rw-conflict out with the deleter.
                               9431                 :                :  *
                               9432                 :                :  * We will determine the top level xid of the writing transaction with which
                               9433                 :                :  * we may be in conflict, and ask CheckForSerializableConflictOut() to check
                               9434                 :                :  * for overlap with our own transaction.
                               9435                 :                :  *
                               9436                 :                :  * This function should be called just about anywhere in heapam.c where a
                               9437                 :                :  * tuple has been read. The caller must hold at least a shared lock on the
                               9438                 :                :  * buffer, because this function might set hint bits on the tuple. There is
                               9439                 :                :  * currently no known reason to call this function from an index AM.
                               9440                 :                :  */
                               9441                 :                : void
 2371 tmunro@postgresql.or     9442                 :       41294003 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
                               9443                 :                :                                     HeapTuple tuple, Buffer buffer,
                               9444                 :                :                                     Snapshot snapshot)
                               9445                 :                : {
                               9446                 :                :     TransactionId xid;
                               9447                 :                :     HTSV_Result htsvResult;
                               9448                 :                : 
                               9449         [ +  + ]:       41294003 :     if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
                               9450                 :       41286056 :         return;
                               9451                 :                : 
                               9452                 :                :     /*
                               9453                 :                :      * Check to see whether the tuple has been written to by a concurrent
                               9454                 :                :      * transaction, either to create it not visible to us, or to delete it
                               9455                 :                :      * while it is visible to us.  The "visible" bool indicates whether the
                               9456                 :                :      * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
                               9457                 :                :      * is going on with it.
                               9458                 :                :      *
                               9459                 :                :      * In the event of a concurrently inserted tuple that also happens to have
                               9460                 :                :      * been concurrently updated (by a separate transaction), the xmin of the
                               9461                 :                :      * tuple will be used -- not the updater's xid.
                               9462                 :                :      */
                               9463                 :           7947 :     htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
                               9464   [ +  +  +  +  :           7947 :     switch (htsvResult)
                                                 - ]
                               9465                 :                :     {
                               9466                 :           7139 :         case HEAPTUPLE_LIVE:
                               9467         [ +  + ]:           7139 :             if (visible)
                               9468                 :           7124 :                 return;
                               9469                 :             15 :             xid = HeapTupleHeaderGetXmin(tuple->t_data);
                               9470                 :             15 :             break;
                               9471                 :            361 :         case HEAPTUPLE_RECENTLY_DEAD:
                               9472                 :                :         case HEAPTUPLE_DELETE_IN_PROGRESS:
 2236 pg@bowt.ie               9473         [ +  + ]:            361 :             if (visible)
                               9474                 :            286 :                 xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
                               9475                 :                :             else
                               9476                 :             75 :                 xid = HeapTupleHeaderGetXmin(tuple->t_data);
                               9477                 :                : 
                               9478         [ +  + ]:            361 :             if (TransactionIdPrecedes(xid, TransactionXmin))
                               9479                 :                :             {
                               9480                 :                :                 /* This is like the HEAPTUPLE_DEAD case */
                               9481         [ -  + ]:             68 :                 Assert(!visible);
                               9482                 :             68 :                 return;
                               9483                 :                :             }
 2371 tmunro@postgresql.or     9484                 :            293 :             break;
                               9485                 :            327 :         case HEAPTUPLE_INSERT_IN_PROGRESS:
                               9486                 :            327 :             xid = HeapTupleHeaderGetXmin(tuple->t_data);
                               9487                 :            327 :             break;
                               9488                 :            120 :         case HEAPTUPLE_DEAD:
 2236 pg@bowt.ie               9489         [ -  + ]:            120 :             Assert(!visible);
 2371 tmunro@postgresql.or     9490                 :            120 :             return;
 2371 tmunro@postgresql.or     9491                 :UBC           0 :         default:
                               9492                 :                : 
                               9493                 :                :             /*
                               9494                 :                :              * The only way to get to this default clause is if a new value is
                               9495                 :                :              * added to the enum type without adding it to this switch
                               9496                 :                :              * statement.  That's a bug, so elog.
                               9497                 :                :              */
                               9498         [ #  # ]:              0 :             elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
                               9499                 :                : 
                               9500                 :                :             /*
                               9501                 :                :              * In spite of having all enum values covered and calling elog on
                               9502                 :                :              * this default, some compilers think this is a code path which
                               9503                 :                :              * allows xid to be used below without initialization. Silence
                               9504                 :                :              * that warning.
                               9505                 :                :              */
                               9506                 :                :             xid = InvalidTransactionId;
                               9507                 :                :     }
                               9508                 :                : 
 2371 tmunro@postgresql.or     9509         [ -  + ]:CBC         635 :     Assert(TransactionIdIsValid(xid));
                               9510         [ -  + ]:            635 :     Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
                               9511                 :                : 
                               9512                 :                :     /*
                               9513                 :                :      * Find top level xid.  Bail out if xid is too early to be a conflict, or
                               9514                 :                :      * if it's our own xid.
                               9515                 :                :      */
                               9516         [ +  + ]:            635 :     if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
                               9517                 :             64 :         return;
                               9518                 :            571 :     xid = SubTransGetTopmostTransaction(xid);
                               9519         [ -  + ]:            571 :     if (TransactionIdPrecedes(xid, TransactionXmin))
 2371 tmunro@postgresql.or     9520                 :UBC           0 :         return;
                               9521                 :                : 
 2371 tmunro@postgresql.or     9522                 :CBC         571 :     CheckForSerializableConflictOut(relation, xid, snapshot);
                               9523                 :                : }
        

Generated by: LCOV version 2.0-1